Salome HOME
2888a362cf23aeda129c0e8ea361791f16d9bb58
[modules/smesh.git] / src / StdMeshers / StdMeshers_Projection_2D.cxx
1 // Copyright (C) 2007-2016  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, or (at your option) any later version.
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_Mesh.hxx"
39 #include "SMESHDS_SubMesh.hxx"
40 #include "SMESH_Block.hxx"
41 #include "SMESH_Comment.hxx"
42 #include "SMESH_Gen.hxx"
43 #include "SMESH_Mesh.hxx"
44 #include "SMESH_MeshAlgos.hxx"
45 #include "SMESH_MesherHelper.hxx"
46 #include "SMESH_Pattern.hxx"
47 #include "SMESH_subMesh.hxx"
48 #include "SMESH_subMeshEventListener.hxx"
49
50 #include <utilities.h>
51
52 #include <BRepAdaptor_Curve.hxx>
53 #include <BRepAdaptor_Surface.hxx>
54 #include <BRepMesh_Delaun.hxx>
55 #include <BRep_Tool.hxx>
56 #include <Bnd_B2d.hxx>
57 #include <GeomAPI_ProjectPointOnSurf.hxx>
58 #include <GeomLib_IsPlanarSurface.hxx>
59 #include <Precision.hxx>
60 #include <TopExp.hxx>
61 #include <TopExp_Explorer.hxx>
62 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
63 #include <TopTools_ListIteratorOfListOfShape.hxx>
64 #include <TopTools_MapOfShape.hxx>
65 #include <TopoDS.hxx>
66 #include <TopoDS_Solid.hxx>
67 #include <gp_Ax2.hxx>
68 #include <gp_Ax3.hxx>
69 #include <gp_GTrsf.hxx>
70
71
72 using namespace std;
73
74 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
75
76 namespace TAssocTool = StdMeshers_ProjectionUtils;
77 //typedef StdMeshers_ProjectionUtils TAssocTool;
78
79 //=======================================================================
80 //function : StdMeshers_Projection_2D
81 //purpose  : 
82 //=======================================================================
83
84 StdMeshers_Projection_2D::StdMeshers_Projection_2D(int hypId, int studyId, SMESH_Gen* gen)
85   :SMESH_2D_Algo(hypId, studyId, gen)
86 {
87   _name = "Projection_2D";
88   _compatibleHypothesis.push_back("ProjectionSource2D");
89   _sourceHypo = 0;
90 }
91
92 //================================================================================
93 /*!
94  * \brief Destructor
95  */
96 //================================================================================
97
98 StdMeshers_Projection_2D::~StdMeshers_Projection_2D()
99 {}
100
101 //=======================================================================
102 //function : CheckHypothesis
103 //purpose  : 
104 //=======================================================================
105
106 bool StdMeshers_Projection_2D::CheckHypothesis(SMESH_Mesh&                          theMesh,
107                                                const TopoDS_Shape&                  theShape,
108                                                SMESH_Hypothesis::Hypothesis_Status& theStatus)
109 {
110   list <const SMESHDS_Hypothesis * >::const_iterator itl;
111
112   const list <const SMESHDS_Hypothesis * >&hyps = GetUsedHypothesis(theMesh, theShape);
113   if ( hyps.size() == 0 )
114   {
115     theStatus = HYP_MISSING;
116     return false;  // can't work with no hypothesis
117   }
118
119   if ( hyps.size() > 1 )
120   {
121     theStatus = HYP_ALREADY_EXIST;
122     return false;
123   }
124
125   const SMESHDS_Hypothesis *theHyp = hyps.front();
126
127   string hypName = theHyp->GetName();
128
129   theStatus = HYP_OK;
130
131   if (hypName == "ProjectionSource2D")
132   {
133     _sourceHypo = static_cast<const StdMeshers_ProjectionSource2D *>(theHyp);
134
135     // Check hypo parameters
136
137     SMESH_Mesh* srcMesh = _sourceHypo->GetSourceMesh();
138     SMESH_Mesh* tgtMesh = & theMesh;
139     if ( !srcMesh )
140       srcMesh = tgtMesh;
141
142     // check vertices
143     if ( _sourceHypo->HasVertexAssociation() )
144     {
145       // source vertices
146       TopoDS_Shape edge = TAssocTool::GetEdgeByVertices
147         ( srcMesh, _sourceHypo->GetSourceVertex(1), _sourceHypo->GetSourceVertex(2) );
148       if ( edge.IsNull() ||
149            !SMESH_MesherHelper::IsSubShape( edge, srcMesh ) ||
150            !SMESH_MesherHelper::IsSubShape( edge, _sourceHypo->GetSourceFace() ))
151       {
152         theStatus = HYP_BAD_PARAMETER;
153         error("Invalid source vertices");
154         SCRUTE((edge.IsNull()));
155         SCRUTE((SMESH_MesherHelper::IsSubShape( edge, srcMesh )));
156         SCRUTE((SMESH_MesherHelper::IsSubShape( edge, _sourceHypo->GetSourceFace() )));
157       }
158       else
159       {
160         // target vertices
161         edge = TAssocTool::GetEdgeByVertices
162           ( tgtMesh, _sourceHypo->GetTargetVertex(1), _sourceHypo->GetTargetVertex(2) );
163         if ( edge.IsNull() || !SMESH_MesherHelper::IsSubShape( edge, tgtMesh ))
164         {
165           theStatus = HYP_BAD_PARAMETER;
166           error("Invalid target vertices");
167           SCRUTE((edge.IsNull()));
168           SCRUTE((SMESH_MesherHelper::IsSubShape( edge, tgtMesh )));
169         }
170         // PAL16203
171         else if ( !_sourceHypo->IsCompoundSource() &&
172                   !SMESH_MesherHelper::IsSubShape( edge, theShape ))
173         {
174           theStatus = HYP_BAD_PARAMETER;
175           error("Invalid target vertices");
176           SCRUTE((SMESH_MesherHelper::IsSubShape( edge, theShape )));
177         }
178       }
179     }
180     // check a source face
181     if ( !SMESH_MesherHelper::IsSubShape( _sourceHypo->GetSourceFace(), srcMesh ) ||
182          ( srcMesh == tgtMesh && theShape == _sourceHypo->GetSourceFace() ))
183     {
184       theStatus = HYP_BAD_PARAMETER;
185       error("Invalid source face");
186       SCRUTE((SMESH_MesherHelper::IsSubShape( _sourceHypo->GetSourceFace(), srcMesh )));
187       SCRUTE((srcMesh == tgtMesh));
188       SCRUTE(( theShape == _sourceHypo->GetSourceFace() ));
189     }
190   }
191   else
192   {
193     theStatus = HYP_INCOMPATIBLE;
194   }
195   return ( theStatus == HYP_OK );
196 }
197
198 namespace {
199
200   //================================================================================
201   /*!
202    * \brief define if a node is new or old
203    * \param node - node to check
204    * \retval bool - true if the node existed before Compute() is called
205    */
206   //================================================================================
207
208   bool isOldNode( const SMDS_MeshNode* node )
209   {
210     // old nodes are shared by edges and new ones are shared
211     // only by faces created by mapper
212     //if ( is1DComputed )
213     {
214       bool isOld = node->NbInverseElements(SMDSAbs_Edge) > 0;
215       return isOld;
216     }
217     // else
218     // {
219     //   SMDS_ElemIteratorPtr invFace = node->GetInverseElementIterator(SMDSAbs_Face);
220     //   bool isNew = invFace->more();
221     //   return !isNew;
222     // }
223   }
224
225   //================================================================================
226   /*!
227    * \brief Class to remove mesh built by pattern mapper on edges
228    * and vertices in the case of failure of projection algo.
229    * It does it's job at destruction
230    */
231   //================================================================================
232
233   class MeshCleaner {
234     SMESH_subMesh* sm;
235   public:
236     MeshCleaner( SMESH_subMesh* faceSubMesh ): sm(faceSubMesh) {}
237     ~MeshCleaner() { Clean(sm); }
238     void Release() { sm = 0; } // mesh will not be removed
239     static void Clean( SMESH_subMesh* sm, bool withSub=true )
240     {
241       if ( !sm || !sm->GetSubMeshDS() ) return;
242       // PAL16567, 18920. Remove face nodes as well
243 //       switch ( sm->GetSubShape().ShapeType() ) {
244 //       case TopAbs_VERTEX:
245 //       case TopAbs_EDGE: {
246         SMDS_NodeIteratorPtr nIt = sm->GetSubMeshDS()->GetNodes();
247         SMESHDS_Mesh* mesh = sm->GetFather()->GetMeshDS();
248         while ( nIt->more() ) {
249           const SMDS_MeshNode* node = nIt->next();
250           if ( !isOldNode( node ) )
251             mesh->RemoveNode( node );
252         }
253         // do not break but iterate over DependsOn()
254 //       }
255 //       default:
256         if ( !withSub ) return;
257         SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(false,false);
258         while ( smIt->more() )
259           Clean( smIt->next(), false );
260 //       }
261     }
262   };
263
264   //================================================================================
265   /*!
266    * \brief find new nodes belonging to one free border of mesh on face
267     * \param sm - submesh on edge or vertex containing nodes to choose from
268     * \param face - the face bound by the submesh
269     * \param u2nodes - map to fill with nodes
270     * \param seamNodes - set of found nodes
271     * \retval bool - is a success
272    */
273   //================================================================================
274
275   bool getBoundaryNodes ( SMESH_subMesh*                        sm,
276                           const TopoDS_Face&                    face,
277                           map< double, const SMDS_MeshNode* > & u2nodes,
278                           set< const SMDS_MeshNode* > &         seamNodes)
279   {
280     u2nodes.clear();
281     seamNodes.clear();
282     if ( !sm || !sm->GetSubMeshDS() )
283       RETURN_BAD_RESULT("Null submesh");
284
285     SMDS_NodeIteratorPtr nIt = sm->GetSubMeshDS()->GetNodes();
286     switch ( sm->GetSubShape().ShapeType() ) {
287
288     case TopAbs_VERTEX: {
289       while ( nIt->more() ) {
290         const SMDS_MeshNode* node = nIt->next();
291         if ( isOldNode( node ) ) continue;
292         u2nodes.insert( make_pair( 0., node ));
293         seamNodes.insert( node );
294         return true;
295       }
296       break;
297     }
298     case TopAbs_EDGE: {
299       
300       // Get submeshes of sub-vertices
301       const map< int, SMESH_subMesh * >& subSM = sm->DependsOn();
302       if ( subSM.size() != 2 )
303         RETURN_BAD_RESULT("there must be 2 submeshes of sub-vertices"
304                           " but we have " << subSM.size());
305       SMESH_subMesh* smV1 = subSM.begin()->second;
306       SMESH_subMesh* smV2 = subSM.rbegin()->second;
307       if ( !smV1->IsMeshComputed() || !smV2->IsMeshComputed() )
308         RETURN_BAD_RESULT("Empty vertex submeshes");
309
310       const SMDS_MeshNode* nV1 = 0;
311       const SMDS_MeshNode* nE = 0;
312
313       // Look for nV1 - a new node on V1
314       nIt = smV1->GetSubMeshDS()->GetNodes();
315       while ( nIt->more() && !nE ) {
316         const SMDS_MeshNode* node = nIt->next();
317         if ( isOldNode( node ) ) continue;
318         nV1 = node;
319
320         // Find nE - a new node connected to nV1 and belonging to edge submesh;
321         SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
322         SMDS_ElemIteratorPtr vElems = nV1->GetInverseElementIterator(SMDSAbs_Face);
323         while ( vElems->more() && !nE ) {
324           const SMDS_MeshElement* elem = vElems->next();
325           int nbNodes = elem->NbNodes();
326           if ( elem->IsQuadratic() )
327             nbNodes /= 2;
328           int iV1 = elem->GetNodeIndex( nV1 );
329           // try next after nV1
330           int iE = SMESH_MesherHelper::WrapIndex( iV1 + 1, nbNodes );
331           if ( smDS->Contains( elem->GetNode( iE ) ))
332             nE = elem->GetNode( iE );
333           if ( !nE ) {
334             // try node before nV1
335             iE = SMESH_MesherHelper::WrapIndex( iV1 - 1, nbNodes );
336             if ( smDS->Contains( elem->GetNode( iE )))
337               nE = elem->GetNode( iE );
338           }
339           if ( nE && elem->IsQuadratic() ) { // find medium node between nV1 and nE
340             if ( Abs( iV1 - iE ) == 1 )
341               nE = elem->GetNode( Min ( iV1, iE ) + nbNodes );
342             else
343               nE = elem->GetNode( elem->NbNodes() - 1 );
344           }
345         }
346       }
347       if ( !nV1 )
348         RETURN_BAD_RESULT("No new node found on V1");
349       if ( !nE )
350         RETURN_BAD_RESULT("new node on edge not found");
351
352       // Get the whole free border of a face
353       list< const SMDS_MeshNode* > bordNodes;
354       list< const SMDS_MeshElement* > bordFaces;
355       if ( !SMESH_MeshEditor::FindFreeBorder (nV1, nE, nV1, bordNodes, bordFaces ))
356         RETURN_BAD_RESULT("free border of a face not found by nodes " <<
357                           nV1->GetID() << " " << nE->GetID() );
358
359       // Insert nodes of the free border to the map until node on V2 encountered
360       SMESHDS_SubMesh* v2smDS = smV2->GetSubMeshDS();
361       list< const SMDS_MeshNode* >::iterator bordIt = bordNodes.begin();
362       bordIt++; // skip nV1
363       for ( ; bordIt != bordNodes.end(); ++bordIt ) {
364         const SMDS_MeshNode* node = *bordIt;
365         if ( v2smDS->Contains( node ))
366           break;
367         if ( node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
368           RETURN_BAD_RESULT("Bad node position type: node " << node->GetID() <<
369                             " pos type " << node->GetPosition()->GetTypeOfPosition());
370         const SMDS_EdgePosition* pos =
371           static_cast<const SMDS_EdgePosition*>(node->GetPosition());
372         u2nodes.insert( make_pair( pos->GetUParameter(), node ));
373         seamNodes.insert( node );
374       }
375       if ( u2nodes.size() != seamNodes.size() )
376         RETURN_BAD_RESULT("Bad node params on edge " << sm->GetId() <<
377                           ", " << u2nodes.size() << " != " << seamNodes.size() );
378       return true;
379     }
380     default:;
381     }
382     RETURN_BAD_RESULT ("Unexpected submesh type");
383
384   } // bool getBoundaryNodes()
385
386   //================================================================================
387   /*!
388    * \brief Check if two consecutive EDGEs are connected in 2D
389    *  \param [in] E1 - a well oriented non-seam EDGE
390    *  \param [in] E2 - a possibly well oriented seam EDGE
391    *  \param [in] F - a FACE
392    *  \return bool - result
393    */
394   //================================================================================
395
396   bool are2dConnected( const TopoDS_Edge & E1,
397                        const TopoDS_Edge & E2,
398                        const TopoDS_Face & F )
399   {
400     double f,l;
401     Handle(Geom2d_Curve) c1 = BRep_Tool::CurveOnSurface( E1, F, f, l );
402     gp_Pnt2d uvFirst1 = c1->Value( f );
403     gp_Pnt2d uvLast1  = c1->Value( l );
404
405     Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( E2, F, f, l );
406     gp_Pnt2d uvFirst2 = c2->Value( E2.Orientation() == TopAbs_REVERSED ? l : f );
407     double tol2 = Max( Precision::PConfusion() * Precision::PConfusion(),
408                        1e-5 * uvLast1.SquareDistance( uvFirst1 ));
409
410     return (( uvFirst2.SquareDistance( uvFirst1 ) < tol2 ) ||
411             ( uvFirst2.SquareDistance( uvLast1  ) < tol2 ));
412   }
413
414   //================================================================================
415   /*!
416    * \brief Compose TSideVector for both FACEs keeping matching order of EDGEs
417    *        and fill src2tgtNodes map
418    */
419   //================================================================================
420
421   TError getWires(const TopoDS_Face&                 tgtFace,
422                   const TopoDS_Face&                 srcFace,
423                   SMESH_Mesh *                       tgtMesh,
424                   SMESH_Mesh *                       srcMesh,
425                   const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
426                   TSideVector&                       srcWires,
427                   TSideVector&                       tgtWires,
428                   TAssocTool::TNodeNodeMap&          src2tgtNodes,
429                   bool&                              is1DComputed)
430   {
431     src2tgtNodes.clear();
432
433     // get ordered src EDGEs
434     TError err;
435     srcWires = StdMeshers_FaceSide::GetFaceWires( srcFace, *srcMesh,/*skipMediumNodes=*/0, err);
436     if (( err && !err->IsOK() ) ||
437         ( srcWires.empty() ))
438       return err;
439
440     SMESH_MesherHelper srcHelper( *srcMesh );
441     srcHelper.SetSubShape( srcFace );
442
443     // make corresponding sequence of tgt EDGEs
444     tgtWires.resize( srcWires.size() );
445     for ( size_t iW = 0; iW < srcWires.size(); ++iW )
446     {
447       StdMeshers_FaceSidePtr srcWire = srcWires[iW];
448
449       list< TopoDS_Edge > tgtEdges;
450       TopTools_IndexedMapOfShape edgeMap; // to detect seam edges
451       for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
452       {
453         TopoDS_Edge     srcE = srcWire->Edge( iE );
454         TopoDS_Edge     tgtE = TopoDS::Edge( shape2ShapeMap( srcE, /*isSrc=*/true));
455         TopoDS_Shape srcEbis = shape2ShapeMap( tgtE, /*isSrc=*/false );
456         if ( srcE.Orientation() != srcEbis.Orientation() )
457           tgtE.Reverse();
458         // reverse a seam edge encountered for the second time
459         const int index = edgeMap.Add( tgtE );
460         if ( index < edgeMap.Extent() ) // E is a seam
461         {
462           // check which of edges to reverse, E or one already being in tgtEdges
463           if ( are2dConnected( tgtEdges.back(), tgtE, tgtFace ))
464           {
465             list< TopoDS_Edge >::iterator eIt = tgtEdges.begin();
466             std::advance( eIt, index-1 );
467             if ( are2dConnected( tgtEdges.back(), *eIt, tgtFace ))
468               eIt->Reverse();
469           }
470           else
471           {
472             tgtE.Reverse();
473           }
474         }
475         if ( srcWire->NbEdges() == 1 && tgtMesh == srcMesh ) // circle
476         {
477           // try to verify ori by propagation
478           pair<int,TopoDS_Edge> nE =
479             StdMeshers_ProjectionUtils::GetPropagationEdge( srcMesh, tgtE, srcE );
480           if ( !nE.second.IsNull() )
481             tgtE = nE.second;
482         }
483         tgtEdges.push_back( tgtE );
484       }
485
486       tgtWires[ iW ].reset( new StdMeshers_FaceSide( tgtFace, tgtEdges, tgtMesh,
487                                                      /*theIsForward = */ true,
488                                                      /*theIgnoreMediumNodes = */false));
489       StdMeshers_FaceSidePtr tgtWire = tgtWires[ iW ];
490
491       // Fill map of src to tgt nodes with nodes on edges
492
493       for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
494       {
495         if ( srcMesh->GetSubMesh( srcWire->Edge(iE) )->IsEmpty() ||
496              tgtMesh->GetSubMesh( tgtWire->Edge(iE) )->IsEmpty() )
497         {
498           // add nodes on VERTEXes for a case of not meshes EDGEs
499           const SMDS_MeshNode* srcN = srcWire->VertexNode( iE );
500           const SMDS_MeshNode* tgtN = tgtWire->VertexNode( iE );
501           if ( srcN && tgtN )
502             src2tgtNodes.insert( make_pair( srcN, tgtN ));
503         }
504         else
505         {
506           const bool skipMedium = true, isFwd = true;
507           StdMeshers_FaceSide srcEdge( srcFace, srcWire->Edge(iE), srcMesh, isFwd, skipMedium);
508           StdMeshers_FaceSide tgtEdge( tgtFace, tgtWire->Edge(iE), tgtMesh, isFwd, skipMedium);
509           
510           vector< const SMDS_MeshNode* > srcNodes = srcEdge.GetOrderedNodes();
511           vector< const SMDS_MeshNode* > tgtNodes = tgtEdge.GetOrderedNodes();
512
513           if (( srcNodes.size() != tgtNodes.size() ) && tgtNodes.size() > 0 )
514             return SMESH_ComputeError::New( COMPERR_BAD_INPUT_MESH,
515                                             "Different number of nodes on edges");
516           if ( !tgtNodes.empty() )
517           {
518             vector< const SMDS_MeshNode* >::iterator tn = tgtNodes.begin();
519             //if ( srcWire->Edge(iE).Orientation() == tgtWire->Edge(iE).Orientation() )
520             {
521               vector< const SMDS_MeshNode* >::iterator sn = srcNodes.begin();
522               for ( ; tn != tgtNodes.end(); ++tn, ++sn)
523                 src2tgtNodes.insert( make_pair( *sn, *tn ));
524             }
525             // else
526             // {
527             //   vector< const SMDS_MeshNode* >::reverse_iterator sn = srcNodes.rbegin();
528             //   for ( ; tn != tgtNodes.end(); ++tn, ++sn)
529             //     src2tgtNodes.insert( make_pair( *sn, *tn ));
530             // }
531             is1DComputed = true;
532           }
533         }
534       } // loop on EDGEs of a WIRE
535
536     } // loop on WIREs
537
538     return TError();
539   }
540
541   //================================================================================
542   /*!
543    * \brief Preform projection in case if tgtFace.IsPartner( srcFace ) and in case
544    * if projection by 3D transformation is possible
545    */
546   //================================================================================
547
548   bool projectPartner(const TopoDS_Face&                 tgtFace,
549                       const TopoDS_Face&                 srcFace,
550                       const TSideVector&                 tgtWires,
551                       const TSideVector&                 srcWires,
552                       const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
553                       TAssocTool::TNodeNodeMap&          src2tgtNodes,
554                       const bool                         is1DComputed)
555   {
556     SMESH_Mesh *    tgtMesh = tgtWires[0]->GetMesh();
557     SMESH_Mesh *    srcMesh = srcWires[0]->GetMesh();
558     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
559     SMESHDS_Mesh* srcMeshDS = srcMesh->GetMeshDS();
560     SMESH_MesherHelper helper( *tgtMesh );
561
562     const double tol = 1.e-7 * srcMeshDS->getMaxDim();
563
564     // transformation to get location of target nodes from source ones
565     StdMeshers_ProjectionUtils::TrsfFinder3D trsf;
566     bool trsfIsOK = false;
567     if ( tgtFace.IsPartner( srcFace ))
568     {
569       gp_GTrsf srcTrsf = srcFace.Location().Transformation();
570       gp_GTrsf tgtTrsf = tgtFace.Location().Transformation();
571       gp_GTrsf t = srcTrsf.Inverted().Multiplied( tgtTrsf );
572       trsf.Set( t );
573       // check
574       gp_Pnt srcP = BRep_Tool::Pnt( srcWires[0]->FirstVertex() );
575       gp_Pnt tgtP = BRep_Tool::Pnt( tgtWires[0]->FirstVertex() );
576       trsfIsOK = ( tgtP.Distance( trsf.Transform( srcP )) < tol );
577       if ( !trsfIsOK )
578       {
579         trsf.Set( tgtTrsf.Inverted().Multiplied( srcTrsf ));
580         trsfIsOK = ( tgtP.Distance( trsf.Transform( srcP )) < tol );
581       }
582     }
583     if ( !trsfIsOK )
584     {
585       // Try to find the 3D transformation
586
587       const int totNbSeg = 50;
588       vector< gp_XYZ > srcPnts, tgtPnts;
589       srcPnts.reserve( totNbSeg );
590       tgtPnts.reserve( totNbSeg );
591       gp_XYZ srcBC( 0,0,0 ), tgtBC( 0,0,0 );
592       for ( size_t iW = 0; iW < srcWires.size(); ++iW )
593       {
594         const double minSegLen = srcWires[iW]->Length() / totNbSeg;
595         for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
596         {
597           size_t nbSeg = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
598           double srcU  = srcWires[iW]->FirstParameter( iE );
599           double tgtU  = tgtWires[iW]->FirstParameter( iE );
600           double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
601           double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
602           for ( size_t i = 0; i < nbSeg; ++i  )
603           {
604             srcPnts.push_back( srcWires[iW]->Value3d( srcU ).XYZ() );
605             tgtPnts.push_back( tgtWires[iW]->Value3d( tgtU ).XYZ() );
606             srcU += srcDu;
607             tgtU += tgtDu;
608             srcBC += srcPnts.back();
609             tgtBC += tgtPnts.back();
610           }
611         }
612       }
613       if ( !trsf.Solve( srcPnts, tgtPnts ))
614         return false;
615
616       // check trsf
617
618       const int nbTestPnt = 20;
619       const size_t  iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
620       // check boundary
621       gp_Pnt trsfTgt = trsf.Transform( srcBC / srcPnts.size() );
622       trsfIsOK = ( trsfTgt.SquareDistance( tgtBC / tgtPnts.size() ) < tol*tol );
623       for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
624       {
625         gp_Pnt trsfTgt = trsf.Transform( srcPnts[i] );
626         trsfIsOK = ( trsfTgt.SquareDistance( tgtPnts[i] ) < tol*tol );
627       }
628       // check an in-FACE point
629       if ( trsfIsOK )
630       {
631         BRepAdaptor_Surface srcSurf( srcFace );
632         gp_Pnt srcP =
633           srcSurf.Value( 0.321 * ( srcSurf.FirstUParameter() + srcSurf.LastUParameter() ),
634                          0.123 * ( srcSurf.FirstVParameter() + srcSurf.LastVParameter() ));
635         gp_Pnt tgtTrsfP = trsf.Transform( srcP );
636         TopLoc_Location loc;
637         GeomAPI_ProjectPointOnSurf& proj = helper.GetProjector( tgtFace, loc, 0.1*tol );
638         if ( !loc.IsIdentity() )
639           tgtTrsfP.Transform( loc.Transformation().Inverted() );
640         proj.Perform( tgtTrsfP );
641         trsfIsOK = ( proj.IsDone() &&
642                      proj.NbPoints() > 0 &&
643                      proj.LowerDistance() < tol );
644       }
645       if ( !trsfIsOK )
646         return false;
647     }
648
649     // Make new faces
650
651     // prepare the helper to adding quadratic elements if necessary
652     //helper.SetSubShape( tgtFace );
653     helper.IsQuadraticSubMesh( tgtFace );
654
655     SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
656     if ( !is1DComputed && srcSubDS->NbElements() )
657       helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
658
659     SMESH_MesherHelper srcHelper( *srcMesh );
660     srcHelper.SetSubShape( srcFace );
661     SMESH_MesherHelper edgeHelper( *tgtMesh );
662     edgeHelper.ToFixNodeParameters( true );
663
664     const SMDS_MeshNode* nullNode = 0;
665     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
666
667     // indices of nodes to create properly oriented faces
668     bool isReverse = ( !trsf.IsIdentity() );
669     int tri1 = 1, tri2 = 2, quad1 = 1, quad3 = 3;
670     if ( isReverse )
671       std::swap( tri1, tri2 ), std::swap( quad1, quad3 );
672
673     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
674     vector< const SMDS_MeshNode* > tgtNodes;
675     while ( elemIt->more() ) // loop on all mesh faces on srcFace
676     {
677       const SMDS_MeshElement* elem = elemIt->next();
678       const int nbN = elem->NbCornerNodes(); 
679       tgtNodes.resize( nbN );
680       helper.SetElementsOnShape( false );
681       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
682       {
683         const SMDS_MeshNode* srcNode = elem->GetNode(i);
684         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
685         if ( srcN_tgtN->second == nullNode )
686         {
687           // create a new node
688           gp_Pnt tgtP = trsf.Transform( SMESH_TNodeXYZ( srcNode ));
689           SMDS_MeshNode* n = helper.AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
690           srcN_tgtN->second = n;
691           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
692           {
693           case SMDS_TOP_FACE:
694           {
695             gp_Pnt2d srcUV = srcHelper.GetNodeUV( srcFace, srcNode );
696             tgtMeshDS->SetNodeOnFace( n, helper.GetSubShapeID(), srcUV.X(), srcUV.Y() );
697             break;
698           }
699           case SMDS_TOP_EDGE:
700           {
701             const TopoDS_Edge& srcE = TopoDS::Edge( srcMeshDS->IndexToShape( srcNode->getshapeId()));
702             const TopoDS_Edge& tgtE = TopoDS::Edge( shape2ShapeMap( srcE, /*isSrc=*/true ));
703             double srcU = srcHelper.GetNodeU( srcE, srcNode );
704             tgtMeshDS->SetNodeOnEdge( n, tgtE, srcU );
705             if ( !tgtFace.IsPartner( srcFace ))
706             {
707               edgeHelper.SetSubShape( tgtE );
708               double tol = BRep_Tool::Tolerance( tgtE );
709               bool isOk = edgeHelper.CheckNodeU( tgtE, n, srcU, 2 * tol, /*force=*/true );
710               if ( !isOk ) // projection of n to tgtE failed (23395)
711               {
712                 double sF, sL, tF, tL;
713                 BRep_Tool::Range( srcE, sF, sL );
714                 BRep_Tool::Range( tgtE, tF, tL );
715                 double srcR = ( srcU - sF ) / ( sL - sF );
716                 double tgtU  = tF + srcR * ( tL - tF );
717                 tgtMeshDS->SetNodeOnEdge( n, tgtE, tgtU );
718                 gp_Pnt newP = BRepAdaptor_Curve( tgtE ).Value( tgtU );
719                 double dist = newP.Distance( tgtP );
720                 if ( tol < dist && dist < 1000*tol )
721                   tgtMeshDS->MoveNode( n, newP.X(), newP.Y(), newP.Z() );
722               }
723             }
724             break;
725           }
726           case SMDS_TOP_VERTEX:
727           {
728             const TopoDS_Shape & srcV = srcMeshDS->IndexToShape( srcNode->getshapeId() );
729             const TopoDS_Shape & tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
730             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
731             break;
732           }
733           default:;
734           }
735         }
736         tgtNodes[i] = srcN_tgtN->second;
737       }
738       // create a new face
739       helper.SetElementsOnShape( true );
740       switch ( nbN )
741       {
742       case 3: helper.AddFace(tgtNodes[0], tgtNodes[tri1], tgtNodes[tri2]); break;
743       case 4: helper.AddFace(tgtNodes[0], tgtNodes[quad1], tgtNodes[2], tgtNodes[quad3]); break;
744       default:
745         if ( isReverse ) std::reverse( tgtNodes.begin(), tgtNodes.end() );
746         helper.AddPolygonalFace( tgtNodes );
747       }
748     }
749
750     // check node positions
751
752     if ( !tgtFace.IsPartner( srcFace ) )
753     {
754       helper.ToFixNodeParameters( true );
755
756       int nbOkPos = 0;
757       const double tol2d = 1e-12;
758       srcN_tgtN = src2tgtNodes.begin();
759       for ( ; srcN_tgtN != src2tgtNodes.end(); ++srcN_tgtN )
760       {
761         const SMDS_MeshNode* n = srcN_tgtN->second;
762         switch ( n->GetPosition()->GetTypeOfPosition() )
763         {
764         case SMDS_TOP_FACE:
765         {
766           if ( nbOkPos > 10 ) break;
767           gp_XY uv = helper.GetNodeUV( tgtFace, n ), uvBis = uv;
768           if (( helper.CheckNodeUV( tgtFace, n, uv, tol )) &&
769               (( uv - uvBis ).SquareModulus() < tol2d ))
770             ++nbOkPos;
771           else
772             nbOkPos = -((int) src2tgtNodes.size() );
773           break;
774         }
775         case SMDS_TOP_EDGE:
776         {
777           // const TopoDS_Edge & tgtE = TopoDS::Edge( tgtMeshDS->IndexToShape( n->getshapeId() ));
778           // edgeHelper.SetSubShape( tgtE );
779           // edgeHelper.GetNodeU( tgtE, n, 0, &toCheck );
780           break;
781         }
782         default:;
783         }
784       }
785     }
786
787     return true;
788
789   } //   bool projectPartner()
790
791   //================================================================================
792   /*!
793    * \brief Preform projection in case if the faces are similar in 2D space
794    */
795   //================================================================================
796
797   bool projectBy2DSimilarity(const TopoDS_Face&                 tgtFace,
798                              const TopoDS_Face&                 srcFace,
799                              const TSideVector&                 tgtWires,
800                              const TSideVector&                 srcWires,
801                              const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
802                              TAssocTool::TNodeNodeMap&          src2tgtNodes,
803                              const bool                         is1DComputed)
804   {
805     SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
806     SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
807
808     // WARNING: we can have problems if the FACE is symmetrical in 2D,
809     // then the projection can be mirrored relating to what is expected
810
811     // 1) Find 2D transformation
812
813     StdMeshers_ProjectionUtils::TrsfFinder2D trsf;
814     {
815       // get 2 pairs of corresponding UVs
816       gp_Pnt2d srcP0 = srcWires[0]->Value2d(0.0);
817       gp_Pnt2d srcP1 = srcWires[0]->Value2d(0.333);
818       gp_Pnt2d tgtP0 = tgtWires[0]->Value2d(0.0);
819       gp_Pnt2d tgtP1 = tgtWires[0]->Value2d(0.333);
820
821       // make transformation
822       gp_Trsf2d fromTgtCS, toSrcCS; // from/to global CS
823       gp_Ax2d srcCS( srcP0, gp_Vec2d( srcP0, srcP1 ));
824       gp_Ax2d tgtCS( tgtP0, gp_Vec2d( tgtP0, tgtP1 ));
825       toSrcCS  .SetTransformation( srcCS );
826       fromTgtCS.SetTransformation( tgtCS );
827       fromTgtCS.Invert();
828       trsf.Set( fromTgtCS * toSrcCS );
829
830       // check transformation
831       bool trsfIsOK = true;
832       const double tol = 1e-5 * gp_Vec2d( srcP0, srcP1 ).Magnitude();
833       for ( double u = 0.12; ( u < 1. && trsfIsOK ); u += 0.1 )
834       {
835         gp_Pnt2d srcUV  = srcWires[0]->Value2d( u );
836         gp_Pnt2d tgtUV  = tgtWires[0]->Value2d( u );
837         gp_Pnt2d tgtUV2 = trsf.Transform( srcUV );
838         trsfIsOK = ( tgtUV.Distance( tgtUV2 ) < tol );
839       }
840
841       // Find trsf using a least-square approximation
842       if ( !trsfIsOK )
843       {
844         // find trsf
845         const int totNbSeg = 50;
846         vector< gp_XY > srcPnts, tgtPnts;
847         srcPnts.reserve( totNbSeg );
848         tgtPnts.reserve( totNbSeg );
849         for ( size_t iW = 0; iW < srcWires.size(); ++iW )
850         {
851           const double minSegLen = srcWires[iW]->Length() / totNbSeg;
852           for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
853           {
854             size_t nbSeg = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
855             double srcU  = srcWires[iW]->FirstParameter( iE );
856             double tgtU  = tgtWires[iW]->FirstParameter( iE );
857             double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
858             double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
859             for ( size_t i = 0; i < nbSeg; ++i, srcU += srcDu, tgtU += tgtDu  )
860             {
861               srcPnts.push_back( srcWires[iW]->Value2d( srcU ).XY() );
862               tgtPnts.push_back( tgtWires[iW]->Value2d( tgtU ).XY() );
863             }
864           }
865         }
866         if ( !trsf.Solve( srcPnts, tgtPnts ))
867           return false;
868
869         // check trsf
870
871         trsfIsOK = true;
872         const int nbTestPnt = 10;
873         const size_t  iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
874         for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
875         {
876           gp_Pnt2d trsfTgt = trsf.Transform( srcPnts[i] );
877           trsfIsOK = ( trsfTgt.Distance( tgtPnts[i] ) < tol );
878         }
879         if ( !trsfIsOK )
880           return false;
881       }
882     } // "Find transformation" block
883
884     // 2) Projection
885
886     SMESHDS_SubMesh* srcSubDS = srcMesh->GetMeshDS()->MeshElements( srcFace );
887
888     SMESH_MesherHelper helper( *tgtMesh );
889     helper.SetSubShape( tgtFace );
890     if ( is1DComputed )
891       helper.IsQuadraticSubMesh( tgtFace );
892     else
893       helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
894     helper.SetElementsOnShape( true );
895     Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
896     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
897
898     SMESH_MesherHelper srcHelper( *srcMesh );
899     srcHelper.SetSubShape( srcFace );
900
901     const SMDS_MeshNode* nullNode = 0;
902     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
903
904     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
905     vector< const SMDS_MeshNode* > tgtNodes;
906     bool uvOK;
907     while ( elemIt->more() ) // loop on all mesh faces on srcFace
908     {
909       const SMDS_MeshElement* elem = elemIt->next();
910       const int nbN = elem->NbCornerNodes(); 
911       tgtNodes.resize( nbN );
912       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
913       {
914         const SMDS_MeshNode* srcNode = elem->GetNode(i);
915         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
916         if ( srcN_tgtN->second == nullNode )
917         {
918           // create a new node
919           gp_Pnt2d srcUV = srcHelper.GetNodeUV( srcFace, srcNode,
920                                                 elem->GetNode( helper.WrapIndex(i+1,nbN)), &uvOK);
921           gp_Pnt2d   tgtUV = trsf.Transform( srcUV );
922           gp_Pnt      tgtP = tgtSurface->Value( tgtUV.X(), tgtUV.Y() );
923           SMDS_MeshNode* n = tgtMeshDS->AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
924           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
925           {
926           case SMDS_TOP_FACE: {
927             tgtMeshDS->SetNodeOnFace( n, helper.GetSubShapeID(), tgtUV.X(), tgtUV.Y() );
928             break;
929           }
930           case SMDS_TOP_EDGE: {
931             TopoDS_Shape srcEdge = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
932             TopoDS_Edge  tgtEdge = TopoDS::Edge( shape2ShapeMap( srcEdge, /*isSrc=*/true ));
933             double U = Precision::Infinite();
934             helper.CheckNodeU( tgtEdge, n, U, Precision::PConfusion());
935             tgtMeshDS->SetNodeOnEdge( n, TopoDS::Edge( tgtEdge ), U );
936             break;
937           }
938           case SMDS_TOP_VERTEX: {
939             TopoDS_Shape srcV = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
940             TopoDS_Shape tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
941             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
942             break;
943           }
944           default:;
945           }
946           srcN_tgtN->second = n;
947         }
948         tgtNodes[i] = srcN_tgtN->second;
949       }
950       // create a new face (with reversed orientation)
951       switch ( nbN )
952       {
953       case 3: helper.AddFace(tgtNodes[0], tgtNodes[2], tgtNodes[1]); break;
954       case 4: helper.AddFace(tgtNodes[0], tgtNodes[3], tgtNodes[2], tgtNodes[1]); break;
955       }
956     }  // loop on all mesh faces on srcFace
957
958     return true;
959   }
960
961   //================================================================================
962   /*!
963    * \brief Preform projection in case of quadrilateral faces
964    */
965   //================================================================================
966
967   bool projectQuads(const TopoDS_Face&                 tgtFace,
968                     const TopoDS_Face&                 srcFace,
969                     const TSideVector&                 tgtWires,
970                     const TSideVector&                 srcWires,
971                     const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
972                     TAssocTool::TNodeNodeMap&          src2tgtNodes,
973                     const bool                         is1DComputed)
974   {
975     // SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
976     // SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
977     // //SMESHDS_Mesh * tgtMeshDS = tgtMesh->GetMeshDS();
978     // SMESHDS_Mesh * srcMeshDS = srcMesh->GetMeshDS();
979
980     // if ( srcWires[0]->NbEdges() != 4 )
981     //   return false;
982     // if ( !is1DComputed )
983     //   return false;
984     // for ( int iE = 0; iE < 4; ++iE )
985     // {
986     //   SMESHDS_SubMesh* sm = srcMeshDS->MeshElements( srcWires[0]->Edge( iE ));
987     //   if ( !sm ) return false;
988     //   if ( sm->NbNodes() + sm->NbElements() == 0 ) return false;
989     // }
990     // if ( BRepAdaptor_Surface( tgtFace ).GetType() != GeomAbs_Plane )
991     //   return false;
992     // // if ( BRepAdaptor_Surface( tgtFace ).GetType() == GeomAbs_Plane &&
993     // //      BRepAdaptor_Surface( srcFace ).GetType() == GeomAbs_Plane )
994     // //   return false; // too easy
995
996     // // load EDGEs to SMESH_Block
997
998     // SMESH_Block block;
999     // TopTools_IndexedMapOfOrientedShape blockSubShapes;
1000     // {
1001     //   const TopoDS_Solid& box = srcMesh->PseudoShape();
1002     //   TopoDS_Shell shell = TopoDS::Shell( TopExp_Explorer( box, TopAbs_SHELL ).Current() );
1003     //   TopoDS_Vertex v;
1004     //   block.LoadBlockShapes( shell, v, v, blockSubShapes ); // fill all since operator[] is missing
1005     // }
1006     // const SMESH_Block::TShapeID srcFaceBID = SMESH_Block::ID_Fxy0;
1007     // const SMESH_Block::TShapeID tgtFaceBID = SMESH_Block::ID_Fxy1;
1008     // vector< int > edgeBID;
1009     // block.GetFaceEdgesIDs( srcFaceBID, edgeBID ); // u0, u1, 0v, 1v
1010     // blockSubShapes.Substitute( edgeBID[0], srcWires[0]->Edge(0) );
1011     // blockSubShapes.Substitute( edgeBID[1], srcWires[0]->Edge(2) );
1012     // blockSubShapes.Substitute( edgeBID[2], srcWires[0]->Edge(3) );
1013     // blockSubShapes.Substitute( edgeBID[3], srcWires[0]->Edge(1) );
1014     // block.GetFaceEdgesIDs( tgtFaceBID, edgeBID ); // u0, u1, 0v, 1v
1015     // blockSubShapes.Substitute( edgeBID[0], tgtWires[0]->Edge(0) );
1016     // blockSubShapes.Substitute( edgeBID[1], tgtWires[0]->Edge(2) );
1017     // blockSubShapes.Substitute( edgeBID[2], tgtWires[0]->Edge(3) );
1018     // blockSubShapes.Substitute( edgeBID[3], tgtWires[0]->Edge(1) );
1019     // block.LoadFace( srcFace, srcFaceBID, blockSubShapes );
1020     // block.LoadFace( tgtFace, tgtFaceBID, blockSubShapes );
1021
1022     // // remember connectivity of new faces in terms of ( node-or-XY )
1023
1024     // typedef std::pair< const SMDS_MeshNode*, gp_XYZ > TNodeOrXY; // node-or-XY
1025     // typedef std::vector< TNodeOrXY* >                 TFaceConn; // face connectivity
1026     // std::vector< TFaceConn >                    newFacesVec;     // connectivity of all faces
1027     // std::map< const SMDS_MeshNode*, TNodeOrXY > srcNode2tgtNXY;  // src node -> node-or-XY
1028
1029     // TAssocTool::TNodeNodeMap::iterator                                       srcN_tgtN;
1030     // std::map< const SMDS_MeshNode*, TNodeOrXY >::iterator                    srcN_tgtNXY;
1031     // std::pair< std::map< const SMDS_MeshNode*, TNodeOrXY >::iterator, bool > n2n_isNew;
1032     // TNodeOrXY nullNXY( (SMDS_MeshNode*)NULL, gp_XYZ(0,0,0) );
1033
1034     // SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
1035     // newFacesVec.resize( srcSubDS->NbElements() );
1036     // int iFaceSrc = 0;
1037
1038     // SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
1039     // while ( elemIt->more() ) // loop on all mesh faces on srcFace
1040     // {
1041     //   const SMDS_MeshElement* elem = elemIt->next();
1042     //   TFaceConn& tgtNodes = newFacesVec[ iFaceSrc++ ];
1043
1044     //   const int nbN = elem->NbCornerNodes(); 
1045     //   tgtNodes.resize( nbN );
1046     //   for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
1047     //   {
1048     //     const SMDS_MeshNode* srcNode = elem->GetNode(i);
1049     //     n2n_isNew = srcNode2tgtNXY.insert( make_pair( srcNode, nullNXY ));
1050     //     TNodeOrXY & tgtNodeOrXY = n2n_isNew.first->second;
1051     //     if ( n2n_isNew.second ) // new src node encounters
1052     //     {
1053     //       srcN_tgtN = src2tgtNodes.find( srcNode );
1054     //       if ( srcN_tgtN != src2tgtNodes.end() )
1055     //       {
1056     //         tgtNodeOrXY.first = srcN_tgtN->second; // tgt node exists
1057     //       }
1058     //       else 
1059     //       {
1060     //         // find XY of src node withing the quadrilateral srcFace
1061     //         if ( !block.ComputeParameters( SMESH_TNodeXYZ( srcNode ),
1062     //                                        tgtNodeOrXY.second, srcFaceBID ))
1063     //           return false;
1064     //       }
1065     //     }
1066     //     tgtNodes[ i ] = & tgtNodeOrXY;
1067     //   }
1068     // }
1069
1070     // // as all XY are computed, create tgt nodes and faces
1071
1072     // SMESH_MesherHelper helper( *tgtMesh );
1073     // helper.SetSubShape( tgtFace );
1074     // if ( is1DComputed )
1075     //   helper.IsQuadraticSubMesh( tgtFace );
1076     // else
1077     //   helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
1078     // helper.SetElementsOnShape( true );
1079     // Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
1080
1081     // SMESH_MesherHelper srcHelper( *srcMesh );
1082     // srcHelper.SetSubShape( srcFace );
1083
1084     // vector< const SMDS_MeshNode* > tgtNodes;
1085     // gp_XY uv;
1086
1087     // for ( size_t iFaceTgt = 0; iFaceTgt < newFacesVec.size(); ++iFaceTgt )
1088     // {
1089     //   TFaceConn& tgtConn = newFacesVec[ iFaceTgt ];
1090     //   tgtNodes.resize( tgtConn.size() );
1091     //   for ( size_t iN = 0; iN < tgtConn.size(); ++iN )
1092     //   {
1093     //     const SMDS_MeshNode* & tgtN = tgtConn[ iN ]->first;
1094     //     if ( !tgtN ) // create a node
1095     //     {
1096     //       if ( !block.FaceUV( tgtFaceBID, tgtConn[iN]->second, uv ))
1097     //         return false;
1098     //       gp_Pnt p = tgtSurface->Value( uv.X(), uv.Y() );
1099     //       tgtN = helper.AddNode( p.X(), p.Y(), p.Z(), uv.X(), uv.Y() );
1100     //     }
1101     //     tgtNodes[ tgtNodes.size() - iN - 1] = tgtN; // reversed orientation
1102     //   }
1103     //   switch ( tgtNodes.size() )
1104     //   {
1105     //   case 3: helper.AddFace(tgtNodes[0], tgtNodes[1], tgtNodes[2]); break;
1106     //   case 4: helper.AddFace(tgtNodes[0], tgtNodes[1], tgtNodes[2], tgtNodes[3]); break;
1107     //   default:
1108     //     if ( tgtNodes.size() > 4 )
1109     //       helper.AddPolygonalFace( tgtNodes );
1110     //   }
1111     // }
1112     return false; //true;
1113
1114   } // bool projectQuads(...)
1115
1116   //================================================================================
1117   /*!
1118    * \brief Fix bad faces by smoothing
1119    */
1120   //================================================================================
1121
1122   bool fixDistortedFaces( SMESH_MesherHelper& helper,
1123                           TSideVector&        tgtWires )
1124   {
1125     SMESH_subMesh* faceSM = helper.GetMesh()->GetSubMesh( helper.GetSubShape() );
1126
1127     if ( helper.IsDistorted2D( faceSM, /*checkUV=*/true ))
1128     {
1129       SMESH_MeshEditor editor( helper.GetMesh() );
1130       SMESHDS_SubMesh* smDS = faceSM->GetSubMeshDS();
1131       const TopoDS_Face&  F = TopoDS::Face( faceSM->GetSubShape() );
1132
1133       TIDSortedElemSet faces;
1134       SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
1135       for ( faceIt = smDS->GetElements(); faceIt->more(); )
1136         faces.insert( faces.end(), faceIt->next() );
1137
1138       // choose smoothing algo
1139       //SMESH_MeshEditor:: SmoothMethod algo = SMESH_MeshEditor::CENTROIDAL;
1140       bool isConcaveBoundary = false;
1141       for ( size_t iW = 0; iW < tgtWires.size() && !isConcaveBoundary; ++iW )
1142       {
1143         TopoDS_Edge prevEdge = tgtWires[iW]->Edge( tgtWires[iW]->NbEdges() - 1 );
1144         for ( int iE = 0; iE < tgtWires[iW]->NbEdges() && !isConcaveBoundary; ++iE )
1145         {
1146           double angle = helper.GetAngle( prevEdge, tgtWires[iW]->Edge( iE ),
1147                                           F,        tgtWires[iW]->FirstVertex( iE ));
1148           isConcaveBoundary = ( angle < -5. * M_PI / 180. );
1149
1150           prevEdge = tgtWires[iW]->Edge( iE );
1151         }
1152       }
1153       SMESH_MeshEditor:: SmoothMethod algo =
1154         isConcaveBoundary ? SMESH_MeshEditor::CENTROIDAL : SMESH_MeshEditor::LAPLACIAN;
1155
1156       // smooth in 2D or 3D?
1157       TopLoc_Location loc;
1158       Handle(Geom_Surface) surface = BRep_Tool::Surface( F, loc );
1159       bool isPlanar = GeomLib_IsPlanarSurface( surface ).IsPlanar();
1160
1161       // smoothing
1162       set<const SMDS_MeshNode*> fixedNodes;
1163       editor.Smooth( faces, fixedNodes, algo, /*nbIterations=*/ 10,
1164                      /*theTgtAspectRatio=*/1.0, /*the2D=*/!isPlanar);
1165
1166       helper.ToFixNodeParameters( true );
1167
1168       return !helper.IsDistorted2D( faceSM, /*checkUV=*/true );
1169     }
1170     return true;
1171   }
1172
1173   typedef list< pair< const SMDS_MeshNode*, const BRepMesh_Triangle* > > TNodeTriaList;
1174
1175   //================================================================================
1176   /*!
1177    * \brief Add in-FACE nodes surrounding a given node to a queue
1178    */
1179   //================================================================================
1180
1181   void addCloseNodes( const SMDS_MeshNode*     srcNode,
1182                       const BRepMesh_Triangle* bmTria,
1183                       const int                srcFaceID,
1184                       TNodeTriaList &          noTriQueue )
1185   {
1186     // find in-FACE nodes
1187     SMDS_ElemIteratorPtr elems = srcNode->GetInverseElementIterator(SMDSAbs_Face);
1188     while ( elems->more() )
1189     {
1190       const SMDS_MeshElement* elem = elems->next();
1191       if ( elem->getshapeId() == srcFaceID )
1192       {
1193         for ( int i = 0, nb = elem->NbNodes(); i < nb; ++i )
1194         {
1195           const SMDS_MeshNode* n = elem->GetNode( i );
1196           if ( !n->isMarked() )
1197             noTriQueue.push_back( make_pair( n, bmTria ));
1198         }
1199       }
1200     }
1201   }
1202
1203   //================================================================================
1204   /*!
1205    * \brief Find a delauney triangle containing a given 2D point and return
1206    *        barycentric coordinates within the found triangle
1207    */
1208   //================================================================================
1209
1210   const BRepMesh_Triangle* findTriangle( const gp_XY&                            uv,
1211                                          const BRepMesh_Triangle*                bmTria,
1212                                          Handle(BRepMesh_DataStructureOfDelaun)& triaDS,
1213                                          double                                  bc[3] )
1214   {
1215     int   nodeIDs[3];
1216     gp_XY nodeUVs[3];
1217     int   linkIDs[3];
1218     Standard_Boolean ori[3];
1219
1220     while ( bmTria )
1221     {
1222       // check bmTria
1223
1224       triaDS->ElementNodes( *bmTria, nodeIDs );
1225       nodeUVs[0] = triaDS->GetNode( nodeIDs[0] ).Coord();
1226       nodeUVs[1] = triaDS->GetNode( nodeIDs[1] ).Coord();
1227       nodeUVs[2] = triaDS->GetNode( nodeIDs[2] ).Coord();
1228
1229       SMESH_MeshAlgos::GetBarycentricCoords( uv,
1230                                              nodeUVs[0], nodeUVs[1], nodeUVs[2],
1231                                              bc[0], bc[1] );
1232       if ( bc[0] >= 0 && bc[1] >= 0 && bc[0] + bc[1] <= 1 )
1233       {
1234         bc[2] = 1 - bc[0] - bc[1];
1235         return bmTria;
1236       }
1237
1238       // look for a neighbor triangle, which is adjacent to a link intersected
1239       // by a segment( triangle center -> uv )
1240
1241       gp_XY gc = ( nodeUVs[0] + nodeUVs[1] + nodeUVs[2] ) / 3.;
1242       gp_XY seg = uv - gc;
1243
1244       bmTria->Edges( linkIDs, ori );
1245       int triaID = triaDS->IndexOf( *bmTria );
1246       bmTria = 0;
1247
1248       for ( int i = 0; i < 3; ++i )
1249       {
1250         const BRepMesh_PairOfIndex & triIDs = triaDS->ElementsConnectedTo( linkIDs[i] );
1251         if ( triIDs.Extent() < 2 )
1252           continue; // no neighbor triangle
1253
1254         // check if a link intersects gc2uv
1255         const BRepMesh_Edge & link = triaDS->GetLink( linkIDs[i] );
1256         const BRepMesh_Vertex & n1 = triaDS->GetNode( link.FirstNode() );
1257         const BRepMesh_Vertex & n2 = triaDS->GetNode( link.LastNode() );
1258         gp_XY uv1 = n1.Coord();
1259         gp_XY lin = n2.Coord() - uv1; // link direction
1260
1261         double crossSegLin = seg ^ lin;
1262         if ( Abs( crossSegLin ) < std::numeric_limits<double>::min() )
1263           continue; // parallel
1264
1265         double uSeg = ( uv1 - gc ) ^ lin / crossSegLin;
1266         if ( 0. <= uSeg && uSeg <= 1. )
1267         {
1268           bmTria = & triaDS->GetElement( triIDs.Index( 1 + ( triIDs.Index(1) == triaID )));
1269           break;
1270         }
1271       }
1272     }
1273     return bmTria;
1274   }
1275
1276   //================================================================================
1277   /*!
1278    * \brief Morph mesh on the target face to lie within FACE boundary w/o distortion
1279    *
1280    * algo:
1281    * - make a CDT on the src FACE
1282    * - find a triangle containing a src node and get its barycentric coordinates
1283    * - move the node to a point with the same barycentric coordinates in a corresponding
1284    *   tgt triangle
1285    */
1286   //================================================================================
1287
1288   bool morph( SMESH_MesherHelper&             tgtHelper,
1289               const TopoDS_Face&              tgtFace,
1290               const TopoDS_Face&              srcFace,
1291               const TSideVector&              tgtWires,
1292               const TSideVector&              srcWires,
1293               const TAssocTool::TNodeNodeMap& src2tgtNodes )
1294   {
1295     if ( srcWires.size() != tgtWires.size() ) return false;
1296     if ( srcWires.size() == 1 ) return false; // tmp
1297
1298     // count boundary points
1299     int iP = 1, nbP = 0;
1300     for ( size_t iW = 0; iW < srcWires.size(); ++iW )
1301       nbP += srcWires[iW]->NbPoints() - 1; // 1st and last points coincide
1302
1303     // fill boundary points
1304     BRepMesh::Array1OfVertexOfDelaun srcVert( 1, 1 + nbP ), tgtVert( 1, 1 + nbP );
1305     vector< const SMDS_MeshNode* > bndSrcNodes( nbP + 1 ); bndSrcNodes[0] = 0;
1306     BRepMesh_Vertex v( 0, 0, BRepMesh_Frontier );
1307     for ( size_t iW = 0; iW < srcWires.size(); ++iW )
1308     {
1309       const UVPtStructVec& srcPnt = srcWires[iW]->GetUVPtStruct();
1310       const UVPtStructVec& tgtPnt = tgtWires[iW]->GetUVPtStruct();
1311       if ( srcPnt.size() != tgtPnt.size() ) return false;
1312
1313       for ( int i = 0, nb = srcPnt.size() - 1;  i < nb;  ++i, ++iP )
1314       {
1315         bndSrcNodes[ iP ]  = srcPnt[i].node;
1316         srcPnt[i].node->setIsMarked( true );
1317
1318         v.ChangeCoord() = srcPnt[i].UV();
1319         srcVert( iP )   = v;
1320         v.ChangeCoord() = tgtPnt[i].UV();
1321         tgtVert( iP )   = v;
1322       }
1323     }
1324     // triangulate the srcFace in 2D
1325     BRepMesh_Delaun delauney( srcVert );
1326     Handle(BRepMesh_DataStructureOfDelaun) triaDS = delauney.Result();
1327
1328     Handle(ShapeAnalysis_Surface) tgtSurface = tgtHelper.GetSurface( tgtFace );
1329     SMESHDS_Mesh* srcMesh = srcWires[0]->GetMesh()->GetMeshDS();
1330     SMESHDS_Mesh* tgtMesh = tgtHelper.GetMeshDS();
1331     const SMDS_MeshNode *srcNode, *tgtNode;
1332     const BRepMesh_Triangle *bmTria;
1333
1334     // un-mark internal src nodes; later we will mark moved nodes
1335     SMDS_NodeIteratorPtr nIt = srcMesh->MeshElements( srcFace )->GetNodes();
1336     if ( !nIt || !nIt->more() ) return true;
1337     while ( nIt->more() )
1338       ( srcNode = nIt->next() )->setIsMarked( false );
1339
1340     // initialize a queue of nodes with starting triangles
1341     const int srcFaceID = srcNode->getshapeId();
1342     TNodeTriaList noTriQueue;
1343     size_t iBndSrcN = 1;
1344     for ( ; iBndSrcN < bndSrcNodes.size() &&  noTriQueue.empty();  ++iBndSrcN )
1345     {
1346       // get a triangle
1347       const BRepMesh::ListOfInteger & linkIds = triaDS->LinksConnectedTo( iBndSrcN );
1348       const BRepMesh_PairOfIndex &    triaIds = triaDS->ElementsConnectedTo( linkIds.First() );
1349       const BRepMesh_Triangle&           tria = triaDS->GetElement( triaIds.Index(1) );
1350
1351       addCloseNodes( bndSrcNodes[ iBndSrcN ], &tria, srcFaceID, noTriQueue );
1352     }
1353
1354     // Move tgt nodes
1355
1356     double bc[3]; // barycentric coordinates
1357     int    nodeIDs[3];
1358     bool   checkUV = true;
1359     const SMDS_FacePosition* pos;
1360
1361     while ( !noTriQueue.empty() )
1362     {
1363       srcNode = noTriQueue.front().first;
1364       bmTria  = noTriQueue.front().second;
1365       noTriQueue.pop_front();
1366       if ( srcNode->isMarked() )
1367         continue;
1368       srcNode->setIsMarked( true );
1369
1370       // find a delauney triangle containing the src node
1371       gp_XY uv = tgtHelper.GetNodeUV( srcFace, srcNode, NULL, &checkUV );
1372       bmTria = findTriangle( uv, bmTria, triaDS, bc );
1373       if ( !bmTria )
1374         continue;
1375
1376       // compute new coordinates for a corresponding tgt node
1377       gp_XY uvNew( 0., 0. ), nodeUV;
1378       triaDS->ElementNodes( *bmTria, nodeIDs );
1379       for ( int i = 0; i < 3; ++i )
1380         uvNew += bc[i] * tgtVert( nodeIDs[i]).Coord();
1381       gp_Pnt xyz = tgtSurface->Value( uvNew );
1382
1383       // find and move tgt node
1384       TAssocTool::TNodeNodeMap::const_iterator n2n = src2tgtNodes.find( srcNode );
1385       if ( n2n == src2tgtNodes.end() ) continue;
1386       tgtNode = n2n->second;
1387       tgtMesh->MoveNode( tgtNode, xyz.X(), xyz.Y(), xyz.Z() );
1388
1389       if (( pos = dynamic_cast< const SMDS_FacePosition* >( tgtNode->GetPosition() )))
1390         const_cast<SMDS_FacePosition*>( pos )->SetParameters( uvNew.X(), uvNew.Y() );
1391
1392       addCloseNodes( srcNode, bmTria, srcFaceID, noTriQueue );
1393
1394       // assure that all src nodes are visited
1395       for ( ; iBndSrcN < bndSrcNodes.size() &&  noTriQueue.empty();  ++iBndSrcN )
1396       {
1397         const BRepMesh::ListOfInteger & linkIds = triaDS->LinksConnectedTo( iBndSrcN );
1398         const BRepMesh_PairOfIndex &    triaIds = triaDS->ElementsConnectedTo( linkIds.First() );
1399         const BRepMesh_Triangle&           tria = triaDS->GetElement( triaIds.Index(1) );
1400         addCloseNodes( bndSrcNodes[ iBndSrcN ], &tria, srcFaceID, noTriQueue );
1401       }
1402     }
1403
1404     return true;
1405   }
1406
1407   //=======================================================================
1408   /*
1409    * Set initial association of VERTEXes for the case of projection
1410    * from a quadrangle FACE to a closed FACE, where opposite src EDGEs
1411    * have different nb of segments
1412    */
1413   //=======================================================================
1414
1415   void initAssoc4Quad2Closed(const TopoDS_Shape&          tgtFace,
1416                              SMESH_MesherHelper&          tgtHelper,
1417                              const TopoDS_Shape&          srcFace,
1418                              SMESH_Mesh*                  srcMesh,
1419                              TAssocTool::TShapeShapeMap & assocMap)
1420   {
1421     if ( !tgtHelper.HasRealSeam() || srcFace.ShapeType() != TopAbs_FACE )
1422       return; // no seam edge
1423     list< TopoDS_Edge > tgtEdges, srcEdges;
1424     list< int > tgtNbEW, srcNbEW;
1425     int tgtNbW = SMESH_Block::GetOrderedEdges( TopoDS::Face( tgtFace ), tgtEdges, tgtNbEW );
1426     int srcNbW = SMESH_Block::GetOrderedEdges( TopoDS::Face( srcFace ), srcEdges, srcNbEW );
1427     if ( tgtNbW != 1 || srcNbW != 1 ||
1428          tgtNbEW.front() != 4 || srcNbEW.front() != 4 )
1429       return; // not quads
1430
1431     int srcNbSeg[4];
1432     list< TopoDS_Edge >::iterator edgeS = srcEdges.begin(), edgeT = tgtEdges.begin();
1433     for ( int i = 0; edgeS != srcEdges.end(); ++i, ++edgeS )
1434       if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( *edgeS ))
1435         srcNbSeg[ i ] = sm->NbNodes();
1436       else
1437         return; // not meshed
1438     if ( srcNbSeg[0] == srcNbSeg[2] && srcNbSeg[1] == srcNbSeg[3] )
1439       return; // same nb segments
1440     if ( srcNbSeg[0] != srcNbSeg[2] && srcNbSeg[1] != srcNbSeg[3] )
1441       return; // all different nb segments
1442
1443     edgeS = srcEdges.begin();
1444     if ( srcNbSeg[0] != srcNbSeg[2] )
1445       ++edgeS;
1446     TAssocTool::InsertAssociation( tgtHelper.IthVertex( 0,*edgeT ),
1447                                    tgtHelper.IthVertex( 0,*edgeS ), assocMap );
1448     TAssocTool::InsertAssociation( tgtHelper.IthVertex( 1,*edgeT ),
1449                                    tgtHelper.IthVertex( 1,*edgeS ), assocMap );
1450   }
1451
1452 } // namespace
1453
1454
1455 //=======================================================================
1456 //function : Compute
1457 //purpose  :
1458 //=======================================================================
1459
1460 bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
1461 {
1462   _src2tgtNodes.clear();
1463
1464   if ( !_sourceHypo )
1465     return false;
1466
1467   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
1468   SMESH_Mesh * tgtMesh = & theMesh;
1469   if ( !srcMesh )
1470     srcMesh = tgtMesh;
1471
1472   SMESHDS_Mesh * meshDS = theMesh.GetMeshDS();
1473   SMESH_MesherHelper helper( theMesh );
1474
1475   // ---------------------------
1476   // Make sub-shapes association
1477   // ---------------------------
1478
1479   TopoDS_Face   tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
1480   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
1481
1482   helper.SetSubShape( tgtFace );
1483
1484   TAssocTool::TShapeShapeMap shape2ShapeMap;
1485   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
1486   if ( shape2ShapeMap.IsEmpty() )
1487     initAssoc4Quad2Closed( tgtFace, helper, srcShape, srcMesh, shape2ShapeMap );
1488   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
1489                                              shape2ShapeMap)  ||
1490        !shape2ShapeMap.IsBound( tgtFace ))
1491   {
1492     if ( srcShape.ShapeType() == TopAbs_FACE )
1493     {
1494       int nbE1 = helper.Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
1495       int nbE2 = helper.Count( srcShape, TopAbs_EDGE, /*ignoreSame=*/true );
1496       if ( nbE1 != nbE2 )
1497         return error(COMPERR_BAD_SHAPE,
1498                      SMESH_Comment("Different number of edges in source and target faces: ")
1499                      << nbE2 << " and " << nbE1 );
1500     }
1501     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
1502   }
1503   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
1504
1505   // ----------------------------------------------
1506   // Assure that mesh on a source Face is computed
1507   // ----------------------------------------------
1508
1509   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
1510   SMESH_subMesh* tgtSubMesh = tgtMesh->GetSubMesh( tgtFace );
1511
1512   string srcMeshError;
1513   if ( tgtMesh == srcMesh ) {
1514     if ( !TAssocTool::MakeComputed( srcSubMesh ))
1515       srcMeshError = TAssocTool::SourceNotComputedError( srcSubMesh, this );
1516   }
1517   else {
1518     if ( !srcSubMesh->IsMeshComputed() )
1519       srcMeshError = TAssocTool::SourceNotComputedError();
1520   }
1521   if ( !srcMeshError.empty() )
1522     return error(COMPERR_BAD_INPUT_MESH, srcMeshError );
1523
1524   // ===========
1525   // Projection
1526   // ===========
1527
1528   // get ordered src and tgt EDGEs
1529   TSideVector srcWires, tgtWires;
1530   bool is1DComputed = false; // if any tgt EDGE is meshed
1531   TError err = getWires( tgtFace, srcFace, tgtMesh, srcMesh,
1532                          shape2ShapeMap, srcWires, tgtWires, _src2tgtNodes, is1DComputed );
1533   if ( err && !err->IsOK() )
1534     return error( err );
1535
1536   bool projDone = false;
1537
1538   if ( !projDone )
1539   {
1540     // try to project from the same face with different location
1541     projDone = projectPartner( tgtFace, srcFace, tgtWires, srcWires,
1542                                shape2ShapeMap, _src2tgtNodes, is1DComputed );
1543   }
1544   if ( !projDone )
1545   {
1546     // projection in case if the faces are similar in 2D space
1547     projDone = projectBy2DSimilarity( tgtFace, srcFace, tgtWires, srcWires,
1548                                       shape2ShapeMap, _src2tgtNodes, is1DComputed );
1549   }
1550   if ( !projDone )
1551   {
1552     // projection in case of quadrilateral faces
1553     // NOT IMPLEMENTED, returns false
1554     projDone = projectQuads( tgtFace, srcFace, tgtWires, srcWires,
1555                              shape2ShapeMap, _src2tgtNodes, is1DComputed);
1556   }
1557
1558   // it will remove mesh built on edges and vertices in failure case
1559   MeshCleaner cleaner( tgtSubMesh );
1560
1561   if ( !projDone )
1562   {
1563     _src2tgtNodes.clear();
1564     // --------------------
1565     // Prepare to mapping 
1566     // --------------------
1567
1568     // Check if node projection to a face is needed
1569     Bnd_B2d uvBox;
1570     SMDS_ElemIteratorPtr faceIt = srcSubMesh->GetSubMeshDS()->GetElements();
1571     set< const SMDS_MeshNode* > faceNodes;
1572     for ( ; faceNodes.size() < 3 && faceIt->more();  ) {
1573       const SMDS_MeshElement* face = faceIt->next();
1574       SMDS_ElemIteratorPtr nodeIt = face->nodesIterator();
1575       while ( nodeIt->more() ) {
1576         const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
1577         if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE &&
1578              faceNodes.insert( node ).second )
1579           uvBox.Add( helper.GetNodeUV( srcFace, node ));
1580       }
1581     }
1582     bool toProjectNodes = false;
1583     if ( faceNodes.size() == 1 )
1584       toProjectNodes = ( uvBox.IsVoid() || uvBox.CornerMin().IsEqual( gp_XY(0,0), 1e-12 ));
1585     else if ( faceNodes.size() > 1 )
1586       toProjectNodes = ( uvBox.IsVoid() || uvBox.SquareExtent() < DBL_MIN );
1587
1588     // Find the corresponding source and target vertex
1589     // and <theReverse> flag needed to call mapper.Apply()
1590
1591     TopoDS_Vertex srcV1, tgtV1;
1592     bool reverse = false;
1593
1594     TopExp_Explorer vSrcExp( srcFace, TopAbs_VERTEX );
1595     srcV1 = TopoDS::Vertex( vSrcExp.Current() );
1596     tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
1597
1598     list< TopoDS_Edge > tgtEdges, srcEdges;
1599     list< int > nbEdgesInWires;
1600     SMESH_Block::GetOrderedEdges( tgtFace, tgtEdges, nbEdgesInWires, tgtV1 );
1601     SMESH_Block::GetOrderedEdges( srcFace, srcEdges, nbEdgesInWires, srcV1 );
1602
1603     if ( nbEdgesInWires.front() > 1 ) // possible to find out orientation
1604     {
1605       TopoDS_Edge srcE1 = srcEdges.front(), tgtE1 = tgtEdges.front();
1606       TopoDS_Shape srcE1bis = shape2ShapeMap( tgtE1 );
1607       reverse = ( ! srcE1.IsSame( srcE1bis ));
1608       if ( reverse &&
1609            //_sourceHypo->HasVertexAssociation() &&
1610            nbEdgesInWires.front() > 2 &&
1611            helper.IsRealSeam( tgtEdges.front() ))
1612       {
1613         // projection to a face with seam EDGE; pb is that GetOrderedEdges()
1614         // always puts a seam EDGE first (if possible) and as a result
1615         // we can't use only theReverse flag to correctly associate source
1616         // and target faces in the mapper. Thus we select srcV1 so that
1617         // GetOrderedEdges() to return EDGEs in a needed order
1618         TopoDS_Face tgtFaceBis = tgtFace;
1619         TopTools_MapOfShape checkedVMap( tgtEdges.size() );
1620         checkedVMap.Add ( srcV1 );
1621         for ( vSrcExp.Next(); vSrcExp.More(); )
1622         {
1623           tgtFaceBis.Reverse();
1624           tgtEdges.clear();
1625           SMESH_Block::GetOrderedEdges( tgtFaceBis, tgtEdges, nbEdgesInWires, tgtV1 );
1626           bool ok = true;
1627           list< TopoDS_Edge >::iterator edgeS = srcEdges.begin(), edgeT = tgtEdges.begin();
1628           for ( ; edgeS != srcEdges.end() && ok ; ++edgeS, ++edgeT )
1629             ok = edgeT->IsSame( shape2ShapeMap( *edgeS, /*isSrc=*/true ));
1630           if ( ok )
1631             break; // FOUND!
1632
1633           reverse = !reverse;
1634           if ( reverse )
1635           {
1636             vSrcExp.Next();
1637             while ( vSrcExp.More() && !checkedVMap.Add( vSrcExp.Current() ))
1638               vSrcExp.Next();
1639           }
1640           else
1641           {
1642             srcV1 = TopoDS::Vertex( vSrcExp.Current() );
1643             tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
1644             srcEdges.clear();
1645             SMESH_Block::GetOrderedEdges( srcFace, srcEdges, nbEdgesInWires, srcV1 );
1646           }
1647         }
1648       }
1649       // for the case: project to a closed face from a non-closed face w/o vertex assoc;
1650       // avoid projecting to a seam from two EDGEs with different nb nodes on them
1651       // ( test mesh_Projection_2D_01/B1 )
1652       if ( !_sourceHypo->HasVertexAssociation() &&
1653            nbEdgesInWires.front() > 2 &&
1654            helper.IsRealSeam( tgtEdges.front() ))
1655       {
1656         TopoDS_Shape srcEdge1 = shape2ShapeMap( tgtEdges.front() );
1657         list< TopoDS_Edge >::iterator srcEdge2 =
1658           std::find( srcEdges.begin(), srcEdges.end(), srcEdge1);
1659         list< TopoDS_Edge >::iterator srcEdge3 =
1660           std::find( srcEdges.begin(), srcEdges.end(), srcEdge1.Reversed());
1661         if ( srcEdge2 == srcEdges.end() || srcEdge3 == srcEdges.end() ) // srcEdge1 is not a seam
1662         {
1663           // find srcEdge2 which also will be projected to tgtEdges.front()
1664           for ( srcEdge2 = srcEdges.begin(); srcEdge2 != srcEdges.end(); ++srcEdge2 )
1665             if ( !srcEdge1.IsSame( *srcEdge2 ) &&
1666                  tgtEdges.front().IsSame( shape2ShapeMap( *srcEdge2, /*isSrc=*/true )))
1667               break;
1668           // compare nb nodes on srcEdge1 and srcEdge2
1669           if ( srcEdge2 != srcEdges.end() )
1670           {
1671             int nbN1 = 0, nbN2 = 0;
1672             if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( srcEdge1 ))
1673               nbN1 = sm->NbNodes();
1674             if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( *srcEdge2 ))
1675               nbN2 = sm->NbNodes();
1676             if ( nbN1 != nbN2 )
1677               srcV1 = helper.IthVertex( 1, srcEdges.front() );
1678           }
1679         }
1680       }
1681     }
1682     else if ( nbEdgesInWires.front() == 1 ) // a sole edge in a wire
1683     {
1684       TopoDS_Edge srcE1 = srcEdges.front(), tgtE1 = tgtEdges.front();
1685       for ( size_t iW = 0; iW < srcWires.size(); ++iW )
1686       {
1687         StdMeshers_FaceSidePtr srcWire = srcWires[iW];
1688         for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
1689           if ( srcE1.IsSame( srcWire->Edge( iE )))
1690           {
1691             reverse = ( tgtE1.Orientation() != tgtWires[iW]->Edge( iE ).Orientation() );
1692             break;
1693           }
1694       }
1695     }
1696     else
1697     {
1698       RETURN_BAD_RESULT("Bad result from SMESH_Block::GetOrderedEdges()");
1699     }
1700
1701     // Load pattern from the source face
1702     SMESH_Pattern mapper;
1703     mapper.Load( srcMesh, srcFace, toProjectNodes, srcV1, /*keepNodes=*/true );
1704     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
1705       return error(COMPERR_BAD_INPUT_MESH,"Can't load mesh pattern from the source face");
1706
1707     // --------------------
1708     // Perform 2D mapping
1709     // --------------------
1710
1711     // Compute mesh on a target face
1712
1713     mapper.Apply( tgtFace, tgtV1, reverse );
1714     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK ) {
1715       // std::ofstream file("/tmp/Pattern.smp" );
1716       // mapper.Save( file );
1717       return error("Can't apply source mesh pattern to the face");
1718     }
1719
1720     // Create the mesh
1721
1722     const bool toCreatePolygons = false, toCreatePolyedrs = false;
1723     mapper.MakeMesh( tgtMesh, toCreatePolygons, toCreatePolyedrs );
1724     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
1725       return error("Can't make mesh by source mesh pattern");
1726
1727     // fill _src2tgtNodes
1728     std::vector< const SMDS_MeshNode* > *srcNodes, *tgtNodes;
1729     mapper.GetInOutNodes( srcNodes, tgtNodes );
1730     size_t nbN = std::min( srcNodes->size(), tgtNodes->size() );
1731     for ( size_t i = 0; i < nbN; ++i )
1732       if ( (*srcNodes)[i] && (*tgtNodes)[i] )
1733         _src2tgtNodes.insert( make_pair( (*srcNodes)[i], (*tgtNodes)[i] ));
1734
1735
1736   } // end of projection using Pattern mapping
1737
1738   {
1739     // -------------------------------------------------------------------------
1740     // mapper doesn't take care of nodes already existing on edges and vertices,
1741     // so we must merge nodes created by it with existing ones
1742     // -------------------------------------------------------------------------
1743
1744     SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
1745
1746     // Make groups of nodes to merge
1747
1748     // loop on EDGE and VERTEX sub-meshes of a target FACE
1749     SMESH_subMeshIteratorPtr smIt = tgtSubMesh->getDependsOnIterator(/*includeSelf=*/false,
1750                                                                      /*complexShapeFirst=*/false);
1751     while ( smIt->more() )
1752     {
1753       SMESH_subMesh*     sm = smIt->next();
1754       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
1755       if ( !smDS || smDS->NbNodes() == 0 )
1756         continue;
1757       //if ( !is1DComputed && sm->GetSubShape().ShapeType() == TopAbs_EDGE )
1758       //  break;
1759
1760       if ( helper.IsDegenShape( sm->GetId() ) ) // to merge all nodes on degenerated
1761       {
1762         if ( sm->GetSubShape().ShapeType() == TopAbs_EDGE )
1763         {
1764           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1765           SMESH_subMeshIteratorPtr smDegenIt
1766             = sm->getDependsOnIterator(/*includeSelf=*/true,/*complexShapeFirst=*/false);
1767           while ( smDegenIt->more() )
1768             if (( smDS = smDegenIt->next()->GetSubMeshDS() ))
1769             {
1770               SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1771               while ( nIt->more() )
1772                 groupsOfNodes.back().push_back( nIt->next() );
1773             }
1774         }
1775         continue; // do not treat sm of degen VERTEX
1776       }
1777
1778       // Sort new and old nodes of a sub-mesh separately
1779
1780       bool isSeam = helper.IsRealSeam( sm->GetId() );
1781
1782       enum { NEW_NODES = 0, OLD_NODES };
1783       map< double, const SMDS_MeshNode* > u2nodesMaps[2], u2nodesOnSeam;
1784       map< double, const SMDS_MeshNode* >::iterator u_oldNode, u_newNode, u_newOnSeam, newEnd;
1785       set< const SMDS_MeshNode* > seamNodes;
1786
1787       // mapper changed, no more "mapper puts on a seam edge nodes from 2 edges"
1788       if ( isSeam && ! getBoundaryNodes ( sm, tgtFace, u2nodesOnSeam, seamNodes ))
1789         ;//RETURN_BAD_RESULT("getBoundaryNodes() failed");
1790
1791       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1792       while ( nIt->more() )
1793       {
1794         const SMDS_MeshNode* node = nIt->next();
1795         bool isOld = isOldNode( node );
1796
1797         if ( !isOld && isSeam ) { // new node on a seam edge
1798           if ( seamNodes.count( node ) )
1799             continue; // node is already in the map
1800         }
1801
1802         // sort nodes on edges by their position
1803         map< double, const SMDS_MeshNode* > & pos2nodes = u2nodesMaps[isOld ? OLD_NODES : NEW_NODES];
1804         switch ( node->GetPosition()->GetTypeOfPosition() )
1805         {
1806         case  SMDS_TOP_VERTEX: {
1807           if ( !is1DComputed && !pos2nodes.empty() )
1808             u2nodesMaps[isOld ? NEW_NODES : OLD_NODES].insert( make_pair( 0, node ));
1809           else
1810             pos2nodes.insert( make_pair( 0, node ));
1811           break;
1812         }
1813         case  SMDS_TOP_EDGE:   {
1814           const SMDS_EdgePosition* pos =
1815             static_cast<const SMDS_EdgePosition*>(node->GetPosition());
1816           pos2nodes.insert( make_pair( pos->GetUParameter(), node ));
1817           break;
1818         }
1819         default:
1820           RETURN_BAD_RESULT("Wrong node position type: "<<
1821                             node->GetPosition()->GetTypeOfPosition());
1822         }
1823       }
1824       const bool mergeNewToOld =
1825         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesMaps[ OLD_NODES ].size() );
1826       const bool mergeSeamToNew =
1827         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesOnSeam.size() );
1828
1829       if ( !mergeNewToOld )
1830         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1831              u2nodesMaps[ OLD_NODES ].size() > 0 )
1832         {
1833           u_oldNode = u2nodesMaps[ OLD_NODES ].begin(); 
1834           newEnd    = u2nodesMaps[ OLD_NODES ].end();
1835           for ( ; u_oldNode != newEnd; ++u_oldNode )
1836             SMESH_Algo::addBadInputElement( u_oldNode->second );
1837           return error( COMPERR_BAD_INPUT_MESH,
1838                         SMESH_Comment( "Existing mesh mismatches the projected 2D mesh on " )
1839                         << ( sm->GetSubShape().ShapeType() == TopAbs_EDGE ? "edge" : "vertex" )
1840                         << " #" << sm->GetId() );
1841         }
1842       if ( isSeam && !mergeSeamToNew ) {
1843         const TopoDS_Shape& seam = sm->GetSubShape();
1844         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1845              u2nodesOnSeam.size()            > 0 &&
1846              seam.ShapeType() == TopAbs_EDGE )
1847         {
1848           int nbE1 = helper.Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
1849           int nbE2 = helper.Count( srcFace, TopAbs_EDGE, /*ignoreSame=*/true );
1850           if ( nbE1 != nbE2 ) // 2 EDGEs are mapped to a seam EDGE
1851           {
1852             // find the 2 EDGEs of srcFace
1853             TopTools_DataMapIteratorOfDataMapOfShapeShape src2tgtIt( shape2ShapeMap._map2to1 );
1854             for ( ; src2tgtIt.More(); src2tgtIt.Next() )
1855               if ( seam.IsSame( src2tgtIt.Value() ))
1856                 SMESH_Algo::addBadInputElements
1857                   ( srcMesh->GetMeshDS()->MeshElements( src2tgtIt.Key() ));
1858             return error( COMPERR_BAD_INPUT_MESH,
1859                           "Different number of nodes on two edges projected to a seam edge" );
1860           }
1861         }
1862       }
1863
1864       // Make groups of nodes to merge
1865
1866       u_oldNode = u2nodesMaps[ OLD_NODES ].begin(); 
1867       u_newNode = u2nodesMaps[ NEW_NODES ].begin();
1868       newEnd    = u2nodesMaps[ NEW_NODES ].end();
1869       u_newOnSeam = u2nodesOnSeam.begin();
1870       if ( mergeNewToOld )
1871         for ( ; u_newNode != newEnd; ++u_newNode, ++u_oldNode )
1872         {
1873           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1874           groupsOfNodes.back().push_back( u_oldNode->second );
1875           groupsOfNodes.back().push_back( u_newNode->second );
1876           if ( mergeSeamToNew )
1877             groupsOfNodes.back().push_back( (u_newOnSeam++)->second );
1878         }
1879       else if ( mergeSeamToNew )
1880         for ( ; u_newNode != newEnd; ++u_newNode, ++u_newOnSeam )
1881         {
1882           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1883           groupsOfNodes.back().push_back( u_newNode->second );
1884           groupsOfNodes.back().push_back( u_newOnSeam->second );
1885         }
1886
1887     } // loop on EDGE and VERTEX submeshes of a target FACE
1888
1889     // Merge
1890
1891     SMESH_MeshEditor editor( tgtMesh );
1892     int nbFaceBeforeMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1893     editor.MergeNodes( groupsOfNodes );
1894     int nbFaceAtferMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1895     if ( nbFaceBeforeMerge != nbFaceAtferMerge && !helper.HasDegeneratedEdges() )
1896       return error(COMPERR_BAD_INPUT_MESH, "Probably invalid node parameters on geom faces");
1897
1898     // ----------------------------------------------------------------
1899     // The mapper can't create quadratic elements, so convert if needed
1900     // ----------------------------------------------------------------
1901
1902     SMDS_ElemIteratorPtr faceIt;
1903     faceIt         = srcSubMesh->GetSubMeshDS()->GetElements();
1904     bool srcIsQuad = faceIt->next()->IsQuadratic();
1905     faceIt         = tgtSubMesh->GetSubMeshDS()->GetElements();
1906     bool tgtIsQuad = faceIt->next()->IsQuadratic();
1907     if ( srcIsQuad && !tgtIsQuad )
1908     {
1909       TIDSortedElemSet tgtFaces;
1910       faceIt = tgtSubMesh->GetSubMeshDS()->GetElements();
1911       while ( faceIt->more() )
1912         tgtFaces.insert( tgtFaces.end(), faceIt->next() );
1913
1914       editor.ConvertToQuadratic(/*theForce3d=*/false, tgtFaces, false);
1915     }
1916   } // end of coincident nodes and quadratic elements treatment
1917
1918
1919   if ( !projDone || is1DComputed )
1920     // ----------------------------------------------------------------
1921     // The mapper can create distorted faces by placing nodes out of the FACE
1922     // boundary, also bad face can be created if EDGEs already discretized
1923     // --> fix bad faces by smoothing
1924     // ----------------------------------------------------------------
1925     if ( helper.IsDistorted2D( tgtSubMesh, /*checkUV=*/false ))
1926     {
1927       morph( helper, tgtFace, srcFace, tgtWires, srcWires, _src2tgtNodes );
1928
1929       if ( !fixDistortedFaces( helper, tgtWires ))
1930         return error("Invalid mesh generated");
1931     }
1932   // ---------------------------
1933   // Check elements orientation
1934   // ---------------------------
1935
1936   TopoDS_Face face = TopoDS::Face( theShape );
1937   if ( !theMesh.IsMainShape( tgtFace ))
1938   {
1939     // find the main shape
1940     TopoDS_Shape mainShape = meshDS->ShapeToMesh();
1941     switch ( mainShape.ShapeType() ) {
1942     case TopAbs_SHELL:
1943     case TopAbs_SOLID: break;
1944     default:
1945       TopTools_ListIteratorOfListOfShape ancestIt = theMesh.GetAncestors( face );
1946       for ( ; ancestIt.More(); ancestIt.Next() ) {
1947         TopAbs_ShapeEnum type = ancestIt.Value().ShapeType();
1948         if ( type == TopAbs_SOLID ) {
1949           mainShape = ancestIt.Value();
1950           break;
1951         } else if ( type == TopAbs_SHELL ) {
1952           mainShape = ancestIt.Value();
1953         }
1954       }
1955     }
1956     // find tgtFace in the main solid or shell to know it's true orientation.
1957     TopExp_Explorer exp( mainShape, TopAbs_FACE );
1958     for ( ; exp.More(); exp.Next() ) {
1959       if ( tgtFace.IsSame( exp.Current() )) {
1960         face = TopoDS::Face( exp.Current() );
1961         break;
1962       }
1963     }
1964   }
1965   // Fix orientation
1966   if ( helper.IsReversedSubMesh( face ))
1967   {
1968     SMESH_MeshEditor editor( tgtMesh );
1969     SMDS_ElemIteratorPtr eIt = meshDS->MeshElements( face )->GetElements();
1970     while ( eIt->more() ) {
1971       const SMDS_MeshElement* e = eIt->next();
1972       if ( e->GetType() == SMDSAbs_Face && !editor.Reorient( e ))
1973         RETURN_BAD_RESULT("Pb of SMESH_MeshEditor::Reorient()");
1974     }
1975   }
1976
1977   cleaner.Release(); // not to remove mesh
1978
1979   return true;
1980 }
1981
1982
1983 //=======================================================================
1984 //function : Evaluate
1985 //purpose  : 
1986 //=======================================================================
1987
1988 bool StdMeshers_Projection_2D::Evaluate(SMESH_Mesh&         theMesh,
1989                                         const TopoDS_Shape& theShape,
1990                                         MapShapeNbElems&    aResMap)
1991 {
1992   if ( !_sourceHypo )
1993     return false;
1994
1995   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
1996   SMESH_Mesh * tgtMesh = & theMesh;
1997   if ( !srcMesh )
1998     srcMesh = tgtMesh;
1999
2000   // ---------------------------
2001   // Make sub-shapes association
2002   // ---------------------------
2003
2004   TopoDS_Face tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
2005   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
2006
2007   TAssocTool::TShapeShapeMap shape2ShapeMap;
2008   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
2009   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
2010                                              shape2ShapeMap)  ||
2011        !shape2ShapeMap.IsBound( tgtFace ))
2012     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
2013
2014   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
2015
2016   // -------------------------------------------------------
2017   // Assure that mesh on a source Face is computed/evaluated
2018   // -------------------------------------------------------
2019
2020   std::vector<int> aVec;
2021
2022   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
2023   if ( srcSubMesh->IsMeshComputed() )
2024   {
2025     aVec.resize( SMDSEntity_Last, 0 );
2026     aVec[SMDSEntity_Node] = srcSubMesh->GetSubMeshDS()->NbNodes();
2027
2028     SMDS_ElemIteratorPtr elemIt = srcSubMesh->GetSubMeshDS()->GetElements();
2029     while ( elemIt->more() )
2030       aVec[ elemIt->next()->GetEntityType() ]++;
2031   }
2032   else
2033   {
2034     MapShapeNbElems  tmpResMap;
2035     MapShapeNbElems& srcResMap = (srcMesh == tgtMesh) ? aResMap : tmpResMap;
2036     if ( !_gen->Evaluate( *srcMesh, srcShape, srcResMap ))
2037       return error(COMPERR_BAD_INPUT_MESH,"Source mesh not evaluatable");
2038     aVec = srcResMap[ srcSubMesh ];
2039     if ( aVec.empty() )
2040       return error(COMPERR_BAD_INPUT_MESH,"Source mesh is wrongly evaluated");
2041   }
2042
2043   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
2044   aResMap.insert(std::make_pair(sm,aVec));
2045
2046   return true;
2047 }
2048
2049
2050 //=============================================================================
2051 /*!
2052  * \brief Sets a default event listener to submesh of the source face
2053   * \param subMesh - submesh where algo is set
2054  *
2055  * This method is called when a submesh gets HYP_OK algo_state.
2056  * After being set, event listener is notified on each event of a submesh.
2057  * Arranges that CLEAN event is translated from source submesh to
2058  * the submesh
2059  */
2060 //=============================================================================
2061
2062 void StdMeshers_Projection_2D::SetEventListener(SMESH_subMesh* subMesh)
2063 {
2064   TAssocTool::SetEventListener( subMesh,
2065                                 _sourceHypo->GetSourceFace(),
2066                                 _sourceHypo->GetSourceMesh() );
2067 }