Salome HOME
23395: EDF 13855 - Crash SALOME when creating a mesh
[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               bool isOk = true;
708               edgeHelper.SetSubShape( tgtE );
709               edgeHelper.GetNodeU( tgtE, n, 0, &isOk );
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                 double tol = BRep_Tool::Tolerance( tgtE );
721                 if ( tol < dist && dist < 1000*tol )
722                   tgtMeshDS->MoveNode( n, newP.X(), newP.Y(), newP.Z() );
723               }
724             }
725             break;
726           }
727           case SMDS_TOP_VERTEX:
728           {
729             const TopoDS_Shape & srcV = srcMeshDS->IndexToShape( srcNode->getshapeId() );
730             const TopoDS_Shape & tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
731             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
732             break;
733           }
734           default:;
735           }
736         }
737         tgtNodes[i] = srcN_tgtN->second;
738       }
739       // create a new face
740       helper.SetElementsOnShape( true );
741       switch ( nbN )
742       {
743       case 3: helper.AddFace(tgtNodes[0], tgtNodes[tri1], tgtNodes[tri2]); break;
744       case 4: helper.AddFace(tgtNodes[0], tgtNodes[quad1], tgtNodes[2], tgtNodes[quad3]); break;
745       default:
746         if ( isReverse ) std::reverse( tgtNodes.begin(), tgtNodes.end() );
747         helper.AddPolygonalFace( tgtNodes );
748       }
749     }
750
751     // check node positions
752
753     if ( !tgtFace.IsPartner( srcFace ) )
754     {
755       helper.ToFixNodeParameters( true );
756
757       int nbOkPos = 0;
758       const double tol2d = 1e-12;
759       srcN_tgtN = src2tgtNodes.begin();
760       for ( ; srcN_tgtN != src2tgtNodes.end(); ++srcN_tgtN )
761       {
762         const SMDS_MeshNode* n = srcN_tgtN->second;
763         switch ( n->GetPosition()->GetTypeOfPosition() )
764         {
765         case SMDS_TOP_FACE:
766         {
767           if ( nbOkPos > 10 ) break;
768           gp_XY uv = helper.GetNodeUV( tgtFace, n ), uvBis = uv;
769           if (( helper.CheckNodeUV( tgtFace, n, uv, tol )) &&
770               (( uv - uvBis ).SquareModulus() < tol2d ))
771             ++nbOkPos;
772           else
773             nbOkPos = -((int) src2tgtNodes.size() );
774           break;
775         }
776         case SMDS_TOP_EDGE:
777         {
778           // const TopoDS_Edge & tgtE = TopoDS::Edge( tgtMeshDS->IndexToShape( n->getshapeId() ));
779           // edgeHelper.SetSubShape( tgtE );
780           // edgeHelper.GetNodeU( tgtE, n, 0, &toCheck );
781           break;
782         }
783         default:;
784         }
785       }
786     }
787
788     return true;
789
790   } //   bool projectPartner()
791
792   //================================================================================
793   /*!
794    * \brief Preform projection in case if the faces are similar in 2D space
795    */
796   //================================================================================
797
798   bool projectBy2DSimilarity(const TopoDS_Face&                 tgtFace,
799                              const TopoDS_Face&                 srcFace,
800                              const TSideVector&                 tgtWires,
801                              const TSideVector&                 srcWires,
802                              const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
803                              TAssocTool::TNodeNodeMap&          src2tgtNodes,
804                              const bool                         is1DComputed)
805   {
806     SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
807     SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
808
809     // WARNING: we can have problems if the FACE is symmetrical in 2D,
810     // then the projection can be mirrored relating to what is expected
811
812     // 1) Find 2D transformation
813
814     StdMeshers_ProjectionUtils::TrsfFinder2D trsf;
815     {
816       // get 2 pairs of corresponding UVs
817       gp_Pnt2d srcP0 = srcWires[0]->Value2d(0.0);
818       gp_Pnt2d srcP1 = srcWires[0]->Value2d(0.333);
819       gp_Pnt2d tgtP0 = tgtWires[0]->Value2d(0.0);
820       gp_Pnt2d tgtP1 = tgtWires[0]->Value2d(0.333);
821
822       // make transformation
823       gp_Trsf2d fromTgtCS, toSrcCS; // from/to global CS
824       gp_Ax2d srcCS( srcP0, gp_Vec2d( srcP0, srcP1 ));
825       gp_Ax2d tgtCS( tgtP0, gp_Vec2d( tgtP0, tgtP1 ));
826       toSrcCS  .SetTransformation( srcCS );
827       fromTgtCS.SetTransformation( tgtCS );
828       fromTgtCS.Invert();
829       trsf.Set( fromTgtCS * toSrcCS );
830
831       // check transformation
832       bool trsfIsOK = true;
833       const double tol = 1e-5 * gp_Vec2d( srcP0, srcP1 ).Magnitude();
834       for ( double u = 0.12; ( u < 1. && trsfIsOK ); u += 0.1 )
835       {
836         gp_Pnt2d srcUV  = srcWires[0]->Value2d( u );
837         gp_Pnt2d tgtUV  = tgtWires[0]->Value2d( u );
838         gp_Pnt2d tgtUV2 = trsf.Transform( srcUV );
839         trsfIsOK = ( tgtUV.Distance( tgtUV2 ) < tol );
840       }
841
842       // Find trsf using a least-square approximation
843       if ( !trsfIsOK )
844       {
845         // find trsf
846         const int totNbSeg = 50;
847         vector< gp_XY > srcPnts, tgtPnts;
848         srcPnts.reserve( totNbSeg );
849         tgtPnts.reserve( totNbSeg );
850         for ( size_t iW = 0; iW < srcWires.size(); ++iW )
851         {
852           const double minSegLen = srcWires[iW]->Length() / totNbSeg;
853           for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
854           {
855             size_t nbSeg = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
856             double srcU  = srcWires[iW]->FirstParameter( iE );
857             double tgtU  = tgtWires[iW]->FirstParameter( iE );
858             double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
859             double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
860             for ( size_t i = 0; i < nbSeg; ++i, srcU += srcDu, tgtU += tgtDu  )
861             {
862               srcPnts.push_back( srcWires[iW]->Value2d( srcU ).XY() );
863               tgtPnts.push_back( tgtWires[iW]->Value2d( tgtU ).XY() );
864             }
865           }
866         }
867         if ( !trsf.Solve( srcPnts, tgtPnts ))
868           return false;
869
870         // check trsf
871
872         trsfIsOK = true;
873         const int nbTestPnt = 10;
874         const size_t  iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
875         for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
876         {
877           gp_Pnt2d trsfTgt = trsf.Transform( srcPnts[i] );
878           trsfIsOK = ( trsfTgt.Distance( tgtPnts[i] ) < tol );
879         }
880         if ( !trsfIsOK )
881           return false;
882       }
883     } // "Find transformation" block
884
885     // 2) Projection
886
887     SMESHDS_SubMesh* srcSubDS = srcMesh->GetMeshDS()->MeshElements( srcFace );
888
889     SMESH_MesherHelper helper( *tgtMesh );
890     helper.SetSubShape( tgtFace );
891     if ( is1DComputed )
892       helper.IsQuadraticSubMesh( tgtFace );
893     else
894       helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
895     helper.SetElementsOnShape( true );
896     Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
897     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
898
899     SMESH_MesherHelper srcHelper( *srcMesh );
900     srcHelper.SetSubShape( srcFace );
901
902     const SMDS_MeshNode* nullNode = 0;
903     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
904
905     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
906     vector< const SMDS_MeshNode* > tgtNodes;
907     bool uvOK;
908     while ( elemIt->more() ) // loop on all mesh faces on srcFace
909     {
910       const SMDS_MeshElement* elem = elemIt->next();
911       const int nbN = elem->NbCornerNodes(); 
912       tgtNodes.resize( nbN );
913       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
914       {
915         const SMDS_MeshNode* srcNode = elem->GetNode(i);
916         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
917         if ( srcN_tgtN->second == nullNode )
918         {
919           // create a new node
920           gp_Pnt2d srcUV = srcHelper.GetNodeUV( srcFace, srcNode,
921                                                 elem->GetNode( helper.WrapIndex(i+1,nbN)), &uvOK);
922           gp_Pnt2d   tgtUV = trsf.Transform( srcUV );
923           gp_Pnt      tgtP = tgtSurface->Value( tgtUV.X(), tgtUV.Y() );
924           SMDS_MeshNode* n = tgtMeshDS->AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
925           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
926           {
927           case SMDS_TOP_FACE: {
928             tgtMeshDS->SetNodeOnFace( n, helper.GetSubShapeID(), tgtUV.X(), tgtUV.Y() );
929             break;
930           }
931           case SMDS_TOP_EDGE: {
932             TopoDS_Shape srcEdge = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
933             TopoDS_Edge  tgtEdge = TopoDS::Edge( shape2ShapeMap( srcEdge, /*isSrc=*/true ));
934             double U = Precision::Infinite();
935             helper.CheckNodeU( tgtEdge, n, U, Precision::PConfusion());
936             tgtMeshDS->SetNodeOnEdge( n, TopoDS::Edge( tgtEdge ), U );
937             break;
938           }
939           case SMDS_TOP_VERTEX: {
940             TopoDS_Shape srcV = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
941             TopoDS_Shape tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
942             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
943             break;
944           }
945           default:;
946           }
947           srcN_tgtN->second = n;
948         }
949         tgtNodes[i] = srcN_tgtN->second;
950       }
951       // create a new face (with reversed orientation)
952       switch ( nbN )
953       {
954       case 3: helper.AddFace(tgtNodes[0], tgtNodes[2], tgtNodes[1]); break;
955       case 4: helper.AddFace(tgtNodes[0], tgtNodes[3], tgtNodes[2], tgtNodes[1]); break;
956       }
957     }  // loop on all mesh faces on srcFace
958
959     return true;
960   }
961
962   //================================================================================
963   /*!
964    * \brief Preform projection in case of quadrilateral faces
965    */
966   //================================================================================
967
968   bool projectQuads(const TopoDS_Face&                 tgtFace,
969                     const TopoDS_Face&                 srcFace,
970                     const TSideVector&                 tgtWires,
971                     const TSideVector&                 srcWires,
972                     const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
973                     TAssocTool::TNodeNodeMap&          src2tgtNodes,
974                     const bool                         is1DComputed)
975   {
976     // SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
977     // SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
978     // //SMESHDS_Mesh * tgtMeshDS = tgtMesh->GetMeshDS();
979     // SMESHDS_Mesh * srcMeshDS = srcMesh->GetMeshDS();
980
981     // if ( srcWires[0]->NbEdges() != 4 )
982     //   return false;
983     // if ( !is1DComputed )
984     //   return false;
985     // for ( int iE = 0; iE < 4; ++iE )
986     // {
987     //   SMESHDS_SubMesh* sm = srcMeshDS->MeshElements( srcWires[0]->Edge( iE ));
988     //   if ( !sm ) return false;
989     //   if ( sm->NbNodes() + sm->NbElements() == 0 ) return false;
990     // }
991     // if ( BRepAdaptor_Surface( tgtFace ).GetType() != GeomAbs_Plane )
992     //   return false;
993     // // if ( BRepAdaptor_Surface( tgtFace ).GetType() == GeomAbs_Plane &&
994     // //      BRepAdaptor_Surface( srcFace ).GetType() == GeomAbs_Plane )
995     // //   return false; // too easy
996
997     // // load EDGEs to SMESH_Block
998
999     // SMESH_Block block;
1000     // TopTools_IndexedMapOfOrientedShape blockSubShapes;
1001     // {
1002     //   const TopoDS_Solid& box = srcMesh->PseudoShape();
1003     //   TopoDS_Shell shell = TopoDS::Shell( TopExp_Explorer( box, TopAbs_SHELL ).Current() );
1004     //   TopoDS_Vertex v;
1005     //   block.LoadBlockShapes( shell, v, v, blockSubShapes ); // fill all since operator[] is missing
1006     // }
1007     // const SMESH_Block::TShapeID srcFaceBID = SMESH_Block::ID_Fxy0;
1008     // const SMESH_Block::TShapeID tgtFaceBID = SMESH_Block::ID_Fxy1;
1009     // vector< int > edgeBID;
1010     // block.GetFaceEdgesIDs( srcFaceBID, edgeBID ); // u0, u1, 0v, 1v
1011     // blockSubShapes.Substitute( edgeBID[0], srcWires[0]->Edge(0) );
1012     // blockSubShapes.Substitute( edgeBID[1], srcWires[0]->Edge(2) );
1013     // blockSubShapes.Substitute( edgeBID[2], srcWires[0]->Edge(3) );
1014     // blockSubShapes.Substitute( edgeBID[3], srcWires[0]->Edge(1) );
1015     // block.GetFaceEdgesIDs( tgtFaceBID, edgeBID ); // u0, u1, 0v, 1v
1016     // blockSubShapes.Substitute( edgeBID[0], tgtWires[0]->Edge(0) );
1017     // blockSubShapes.Substitute( edgeBID[1], tgtWires[0]->Edge(2) );
1018     // blockSubShapes.Substitute( edgeBID[2], tgtWires[0]->Edge(3) );
1019     // blockSubShapes.Substitute( edgeBID[3], tgtWires[0]->Edge(1) );
1020     // block.LoadFace( srcFace, srcFaceBID, blockSubShapes );
1021     // block.LoadFace( tgtFace, tgtFaceBID, blockSubShapes );
1022
1023     // // remember connectivity of new faces in terms of ( node-or-XY )
1024
1025     // typedef std::pair< const SMDS_MeshNode*, gp_XYZ > TNodeOrXY; // node-or-XY
1026     // typedef std::vector< TNodeOrXY* >                 TFaceConn; // face connectivity
1027     // std::vector< TFaceConn >                    newFacesVec;     // connectivity of all faces
1028     // std::map< const SMDS_MeshNode*, TNodeOrXY > srcNode2tgtNXY;  // src node -> node-or-XY
1029
1030     // TAssocTool::TNodeNodeMap::iterator                                       srcN_tgtN;
1031     // std::map< const SMDS_MeshNode*, TNodeOrXY >::iterator                    srcN_tgtNXY;
1032     // std::pair< std::map< const SMDS_MeshNode*, TNodeOrXY >::iterator, bool > n2n_isNew;
1033     // TNodeOrXY nullNXY( (SMDS_MeshNode*)NULL, gp_XYZ(0,0,0) );
1034
1035     // SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
1036     // newFacesVec.resize( srcSubDS->NbElements() );
1037     // int iFaceSrc = 0;
1038
1039     // SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
1040     // while ( elemIt->more() ) // loop on all mesh faces on srcFace
1041     // {
1042     //   const SMDS_MeshElement* elem = elemIt->next();
1043     //   TFaceConn& tgtNodes = newFacesVec[ iFaceSrc++ ];
1044
1045     //   const int nbN = elem->NbCornerNodes(); 
1046     //   tgtNodes.resize( nbN );
1047     //   for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
1048     //   {
1049     //     const SMDS_MeshNode* srcNode = elem->GetNode(i);
1050     //     n2n_isNew = srcNode2tgtNXY.insert( make_pair( srcNode, nullNXY ));
1051     //     TNodeOrXY & tgtNodeOrXY = n2n_isNew.first->second;
1052     //     if ( n2n_isNew.second ) // new src node encounters
1053     //     {
1054     //       srcN_tgtN = src2tgtNodes.find( srcNode );
1055     //       if ( srcN_tgtN != src2tgtNodes.end() )
1056     //       {
1057     //         tgtNodeOrXY.first = srcN_tgtN->second; // tgt node exists
1058     //       }
1059     //       else 
1060     //       {
1061     //         // find XY of src node withing the quadrilateral srcFace
1062     //         if ( !block.ComputeParameters( SMESH_TNodeXYZ( srcNode ),
1063     //                                        tgtNodeOrXY.second, srcFaceBID ))
1064     //           return false;
1065     //       }
1066     //     }
1067     //     tgtNodes[ i ] = & tgtNodeOrXY;
1068     //   }
1069     // }
1070
1071     // // as all XY are computed, create tgt nodes and faces
1072
1073     // SMESH_MesherHelper helper( *tgtMesh );
1074     // helper.SetSubShape( tgtFace );
1075     // if ( is1DComputed )
1076     //   helper.IsQuadraticSubMesh( tgtFace );
1077     // else
1078     //   helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
1079     // helper.SetElementsOnShape( true );
1080     // Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
1081
1082     // SMESH_MesherHelper srcHelper( *srcMesh );
1083     // srcHelper.SetSubShape( srcFace );
1084
1085     // vector< const SMDS_MeshNode* > tgtNodes;
1086     // gp_XY uv;
1087
1088     // for ( size_t iFaceTgt = 0; iFaceTgt < newFacesVec.size(); ++iFaceTgt )
1089     // {
1090     //   TFaceConn& tgtConn = newFacesVec[ iFaceTgt ];
1091     //   tgtNodes.resize( tgtConn.size() );
1092     //   for ( size_t iN = 0; iN < tgtConn.size(); ++iN )
1093     //   {
1094     //     const SMDS_MeshNode* & tgtN = tgtConn[ iN ]->first;
1095     //     if ( !tgtN ) // create a node
1096     //     {
1097     //       if ( !block.FaceUV( tgtFaceBID, tgtConn[iN]->second, uv ))
1098     //         return false;
1099     //       gp_Pnt p = tgtSurface->Value( uv.X(), uv.Y() );
1100     //       tgtN = helper.AddNode( p.X(), p.Y(), p.Z(), uv.X(), uv.Y() );
1101     //     }
1102     //     tgtNodes[ tgtNodes.size() - iN - 1] = tgtN; // reversed orientation
1103     //   }
1104     //   switch ( tgtNodes.size() )
1105     //   {
1106     //   case 3: helper.AddFace(tgtNodes[0], tgtNodes[1], tgtNodes[2]); break;
1107     //   case 4: helper.AddFace(tgtNodes[0], tgtNodes[1], tgtNodes[2], tgtNodes[3]); break;
1108     //   default:
1109     //     if ( tgtNodes.size() > 4 )
1110     //       helper.AddPolygonalFace( tgtNodes );
1111     //   }
1112     // }
1113     return false; //true;
1114
1115   } // bool projectQuads(...)
1116
1117   //================================================================================
1118   /*!
1119    * \brief Fix bad faces by smoothing
1120    */
1121   //================================================================================
1122
1123   bool fixDistortedFaces( SMESH_MesherHelper& helper,
1124                           TSideVector&        tgtWires )
1125   {
1126     SMESH_subMesh* faceSM = helper.GetMesh()->GetSubMesh( helper.GetSubShape() );
1127
1128     if ( helper.IsDistorted2D( faceSM, /*checkUV=*/true ))
1129     {
1130       SMESH_MeshEditor editor( helper.GetMesh() );
1131       SMESHDS_SubMesh* smDS = faceSM->GetSubMeshDS();
1132       const TopoDS_Face&  F = TopoDS::Face( faceSM->GetSubShape() );
1133
1134       TIDSortedElemSet faces;
1135       SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
1136       for ( faceIt = smDS->GetElements(); faceIt->more(); )
1137         faces.insert( faces.end(), faceIt->next() );
1138
1139       // choose smoothing algo
1140       //SMESH_MeshEditor:: SmoothMethod algo = SMESH_MeshEditor::CENTROIDAL;
1141       bool isConcaveBoundary = false;
1142       for ( size_t iW = 0; iW < tgtWires.size() && !isConcaveBoundary; ++iW )
1143       {
1144         TopoDS_Edge prevEdge = tgtWires[iW]->Edge( tgtWires[iW]->NbEdges() - 1 );
1145         for ( int iE = 0; iE < tgtWires[iW]->NbEdges() && !isConcaveBoundary; ++iE )
1146         {
1147           double angle = helper.GetAngle( prevEdge, tgtWires[iW]->Edge( iE ),
1148                                           F,        tgtWires[iW]->FirstVertex( iE ));
1149           isConcaveBoundary = ( angle < -5. * M_PI / 180. );
1150
1151           prevEdge = tgtWires[iW]->Edge( iE );
1152         }
1153       }
1154       SMESH_MeshEditor:: SmoothMethod algo =
1155         isConcaveBoundary ? SMESH_MeshEditor::CENTROIDAL : SMESH_MeshEditor::LAPLACIAN;
1156
1157       // smooth in 2D or 3D?
1158       TopLoc_Location loc;
1159       Handle(Geom_Surface) surface = BRep_Tool::Surface( F, loc );
1160       bool isPlanar = GeomLib_IsPlanarSurface( surface ).IsPlanar();
1161
1162       // smoothing
1163       set<const SMDS_MeshNode*> fixedNodes;
1164       editor.Smooth( faces, fixedNodes, algo, /*nbIterations=*/ 10,
1165                      /*theTgtAspectRatio=*/1.0, /*the2D=*/!isPlanar);
1166
1167       helper.ToFixNodeParameters( true );
1168
1169       return !helper.IsDistorted2D( faceSM, /*checkUV=*/true );
1170     }
1171     return true;
1172   }
1173
1174   typedef list< pair< const SMDS_MeshNode*, const BRepMesh_Triangle* > > TNodeTriaList;
1175
1176   //================================================================================
1177   /*!
1178    * \brief Add in-FACE nodes surrounding a given node to a queue
1179    */
1180   //================================================================================
1181
1182   void addCloseNodes( const SMDS_MeshNode*     srcNode,
1183                       const BRepMesh_Triangle* bmTria,
1184                       const int                srcFaceID,
1185                       TNodeTriaList &          noTriQueue )
1186   {
1187     // find in-FACE nodes
1188     SMDS_ElemIteratorPtr elems = srcNode->GetInverseElementIterator(SMDSAbs_Face);
1189     while ( elems->more() )
1190     {
1191       const SMDS_MeshElement* elem = elems->next();
1192       if ( elem->getshapeId() == srcFaceID )
1193       {
1194         for ( int i = 0, nb = elem->NbNodes(); i < nb; ++i )
1195         {
1196           const SMDS_MeshNode* n = elem->GetNode( i );
1197           if ( !n->isMarked() )
1198             noTriQueue.push_back( make_pair( n, bmTria ));
1199         }
1200       }
1201     }
1202   }
1203
1204   //================================================================================
1205   /*!
1206    * \brief Find a delauney triangle containing a given 2D point and return
1207    *        barycentric coordinates within the found triangle
1208    */
1209   //================================================================================
1210
1211   const BRepMesh_Triangle* findTriangle( const gp_XY&                            uv,
1212                                          const BRepMesh_Triangle*                bmTria,
1213                                          Handle(BRepMesh_DataStructureOfDelaun)& triaDS,
1214                                          double                                  bc[3] )
1215   {
1216     int   nodeIDs[3];
1217     gp_XY nodeUVs[3];
1218     int   linkIDs[3];
1219     Standard_Boolean ori[3];
1220
1221     while ( bmTria )
1222     {
1223       // check bmTria
1224
1225       triaDS->ElementNodes( *bmTria, nodeIDs );
1226       nodeUVs[0] = triaDS->GetNode( nodeIDs[0] ).Coord();
1227       nodeUVs[1] = triaDS->GetNode( nodeIDs[1] ).Coord();
1228       nodeUVs[2] = triaDS->GetNode( nodeIDs[2] ).Coord();
1229
1230       SMESH_MeshAlgos::GetBarycentricCoords( uv,
1231                                              nodeUVs[0], nodeUVs[1], nodeUVs[2],
1232                                              bc[0], bc[1] );
1233       if ( bc[0] >= 0 && bc[1] >= 0 && bc[0] + bc[1] <= 1 )
1234       {
1235         bc[2] = 1 - bc[0] - bc[1];
1236         return bmTria;
1237       }
1238
1239       // look for a neighbor triangle, which is adjacent to a link intersected
1240       // by a segment( triangle center -> uv )
1241
1242       gp_XY gc = ( nodeUVs[0] + nodeUVs[1] + nodeUVs[2] ) / 3.;
1243       gp_XY seg = uv - gc;
1244
1245       bmTria->Edges( linkIDs, ori );
1246       int triaID = triaDS->IndexOf( *bmTria );
1247       bmTria = 0;
1248
1249       for ( int i = 0; i < 3; ++i )
1250       {
1251         const BRepMesh_PairOfIndex & triIDs = triaDS->ElementsConnectedTo( linkIDs[i] );
1252         if ( triIDs.Extent() < 2 )
1253           continue; // no neighbor triangle
1254
1255         // check if a link intersects gc2uv
1256         const BRepMesh_Edge & link = triaDS->GetLink( linkIDs[i] );
1257         const BRepMesh_Vertex & n1 = triaDS->GetNode( link.FirstNode() );
1258         const BRepMesh_Vertex & n2 = triaDS->GetNode( link.LastNode() );
1259         gp_XY uv1 = n1.Coord();
1260         gp_XY lin = n2.Coord() - uv1; // link direction
1261
1262         double crossSegLin = seg ^ lin;
1263         if ( Abs( crossSegLin ) < std::numeric_limits<double>::min() )
1264           continue; // parallel
1265
1266         double uSeg = ( uv1 - gc ) ^ lin / crossSegLin;
1267         if ( 0. <= uSeg && uSeg <= 1. )
1268         {
1269           bmTria = & triaDS->GetElement( triIDs.Index( 1 + ( triIDs.Index(1) == triaID )));
1270           break;
1271         }
1272       }
1273     }
1274     return bmTria;
1275   }
1276
1277   //================================================================================
1278   /*!
1279    * \brief Morph mesh on the target face to lie within FACE boundary w/o distortion
1280    *
1281    * algo:
1282    * - make a CDT on the src FACE
1283    * - find a triangle containing a src node and get its barycentric coordinates
1284    * - move the node to a point with the same barycentric coordinates in a corresponding
1285    *   tgt triangle
1286    */
1287   //================================================================================
1288
1289   bool morph( SMESH_MesherHelper&             tgtHelper,
1290               const TopoDS_Face&              tgtFace,
1291               const TopoDS_Face&              srcFace,
1292               const TSideVector&              tgtWires,
1293               const TSideVector&              srcWires,
1294               const TAssocTool::TNodeNodeMap& src2tgtNodes )
1295   {
1296     if ( srcWires.size() != tgtWires.size() ) return false;
1297     if ( srcWires.size() == 1 ) return false; // tmp
1298
1299     // count boundary points
1300     int iP = 1, nbP = 0;
1301     for ( size_t iW = 0; iW < srcWires.size(); ++iW )
1302       nbP += srcWires[iW]->NbPoints() - 1; // 1st and last points coincide
1303
1304     // fill boundary points
1305     BRepMesh::Array1OfVertexOfDelaun srcVert( 1, 1 + nbP ), tgtVert( 1, 1 + nbP );
1306     vector< const SMDS_MeshNode* > bndSrcNodes( nbP + 1 ); bndSrcNodes[0] = 0;
1307     BRepMesh_Vertex v( 0, 0, BRepMesh_Frontier );
1308     for ( size_t iW = 0; iW < srcWires.size(); ++iW )
1309     {
1310       const UVPtStructVec& srcPnt = srcWires[iW]->GetUVPtStruct();
1311       const UVPtStructVec& tgtPnt = tgtWires[iW]->GetUVPtStruct();
1312       if ( srcPnt.size() != tgtPnt.size() ) return false;
1313
1314       for ( int i = 0, nb = srcPnt.size() - 1;  i < nb;  ++i, ++iP )
1315       {
1316         bndSrcNodes[ iP ]  = srcPnt[i].node;
1317         srcPnt[i].node->setIsMarked( true );
1318
1319         v.ChangeCoord() = srcPnt[i].UV();
1320         srcVert( iP )   = v;
1321         v.ChangeCoord() = tgtPnt[i].UV();
1322         tgtVert( iP )   = v;
1323       }
1324     }
1325     // triangulate the srcFace in 2D
1326     BRepMesh_Delaun delauney( srcVert );
1327     Handle(BRepMesh_DataStructureOfDelaun) triaDS = delauney.Result();
1328
1329     Handle(ShapeAnalysis_Surface) tgtSurface = tgtHelper.GetSurface( tgtFace );
1330     SMESHDS_Mesh* srcMesh = srcWires[0]->GetMesh()->GetMeshDS();
1331     SMESHDS_Mesh* tgtMesh = tgtHelper.GetMeshDS();
1332     const SMDS_MeshNode *srcNode, *tgtNode;
1333     const BRepMesh_Triangle *bmTria;
1334
1335     // un-mark internal src nodes; later we will mark moved nodes
1336     SMDS_NodeIteratorPtr nIt = srcMesh->MeshElements( srcFace )->GetNodes();
1337     if ( !nIt || !nIt->more() ) return true;
1338     while ( nIt->more() )
1339       ( srcNode = nIt->next() )->setIsMarked( false );
1340
1341     // initialize a queue of nodes with starting triangles
1342     const int srcFaceID = srcNode->getshapeId();
1343     TNodeTriaList noTriQueue;
1344     size_t iBndSrcN = 1;
1345     for ( ; iBndSrcN < bndSrcNodes.size() &&  noTriQueue.empty();  ++iBndSrcN )
1346     {
1347       // get a triangle
1348       const BRepMesh::ListOfInteger & linkIds = triaDS->LinksConnectedTo( iBndSrcN );
1349       const BRepMesh_PairOfIndex &    triaIds = triaDS->ElementsConnectedTo( linkIds.First() );
1350       const BRepMesh_Triangle&           tria = triaDS->GetElement( triaIds.Index(1) );
1351
1352       addCloseNodes( bndSrcNodes[ iBndSrcN ], &tria, srcFaceID, noTriQueue );
1353     }
1354
1355     // Move tgt nodes
1356
1357     double bc[3]; // barycentric coordinates
1358     int    nodeIDs[3];
1359     bool   checkUV = true;
1360     const SMDS_FacePosition* pos;
1361
1362     while ( !noTriQueue.empty() )
1363     {
1364       srcNode = noTriQueue.front().first;
1365       bmTria  = noTriQueue.front().second;
1366       noTriQueue.pop_front();
1367       if ( srcNode->isMarked() )
1368         continue;
1369       srcNode->setIsMarked( true );
1370
1371       // find a delauney triangle containing the src node
1372       gp_XY uv = tgtHelper.GetNodeUV( srcFace, srcNode, NULL, &checkUV );
1373       bmTria = findTriangle( uv, bmTria, triaDS, bc );
1374       if ( !bmTria )
1375         continue;
1376
1377       // compute new coordinates for a corresponding tgt node
1378       gp_XY uvNew( 0., 0. ), nodeUV;
1379       triaDS->ElementNodes( *bmTria, nodeIDs );
1380       for ( int i = 0; i < 3; ++i )
1381         uvNew += bc[i] * tgtVert( nodeIDs[i]).Coord();
1382       gp_Pnt xyz = tgtSurface->Value( uvNew );
1383
1384       // find and move tgt node
1385       TAssocTool::TNodeNodeMap::const_iterator n2n = src2tgtNodes.find( srcNode );
1386       if ( n2n == src2tgtNodes.end() ) continue;
1387       tgtNode = n2n->second;
1388       tgtMesh->MoveNode( tgtNode, xyz.X(), xyz.Y(), xyz.Z() );
1389
1390       if (( pos = dynamic_cast< const SMDS_FacePosition* >( tgtNode->GetPosition() )))
1391         const_cast<SMDS_FacePosition*>( pos )->SetParameters( uvNew.X(), uvNew.Y() );
1392
1393       addCloseNodes( srcNode, bmTria, srcFaceID, noTriQueue );
1394
1395       // assure that all src nodes are visited
1396       for ( ; iBndSrcN < bndSrcNodes.size() &&  noTriQueue.empty();  ++iBndSrcN )
1397       {
1398         const BRepMesh::ListOfInteger & linkIds = triaDS->LinksConnectedTo( iBndSrcN );
1399         const BRepMesh_PairOfIndex &    triaIds = triaDS->ElementsConnectedTo( linkIds.First() );
1400         const BRepMesh_Triangle&           tria = triaDS->GetElement( triaIds.Index(1) );
1401         addCloseNodes( bndSrcNodes[ iBndSrcN ], &tria, srcFaceID, noTriQueue );
1402       }
1403     }
1404
1405     return true;
1406   }
1407
1408   //=======================================================================
1409   /*
1410    * Set initial association of VERTEXes for the case of projection
1411    * from a quadrangle FACE to a closed FACE, where opposite src EDGEs
1412    * have different nb of segments
1413    */
1414   //=======================================================================
1415
1416   void initAssoc4Quad2Closed(const TopoDS_Shape&          tgtFace,
1417                              SMESH_MesherHelper&          tgtHelper,
1418                              const TopoDS_Shape&          srcFace,
1419                              SMESH_Mesh*                  srcMesh,
1420                              TAssocTool::TShapeShapeMap & assocMap)
1421   {
1422     if ( !tgtHelper.HasRealSeam() || srcFace.ShapeType() != TopAbs_FACE )
1423       return; // no seam edge
1424     list< TopoDS_Edge > tgtEdges, srcEdges;
1425     list< int > tgtNbEW, srcNbEW;
1426     int tgtNbW = SMESH_Block::GetOrderedEdges( TopoDS::Face( tgtFace ), tgtEdges, tgtNbEW );
1427     int srcNbW = SMESH_Block::GetOrderedEdges( TopoDS::Face( srcFace ), srcEdges, srcNbEW );
1428     if ( tgtNbW != 1 || srcNbW != 1 ||
1429          tgtNbEW.front() != 4 || srcNbEW.front() != 4 )
1430       return; // not quads
1431
1432     int srcNbSeg[4];
1433     list< TopoDS_Edge >::iterator edgeS = srcEdges.begin(), edgeT = tgtEdges.begin();
1434     for ( int i = 0; edgeS != srcEdges.end(); ++i, ++edgeS )
1435       if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( *edgeS ))
1436         srcNbSeg[ i ] = sm->NbNodes();
1437       else
1438         return; // not meshed
1439     if ( srcNbSeg[0] == srcNbSeg[2] && srcNbSeg[1] == srcNbSeg[3] )
1440       return; // same nb segments
1441     if ( srcNbSeg[0] != srcNbSeg[2] && srcNbSeg[1] != srcNbSeg[3] )
1442       return; // all different nb segments
1443
1444     edgeS = srcEdges.begin();
1445     if ( srcNbSeg[0] != srcNbSeg[2] )
1446       ++edgeS;
1447     TAssocTool::InsertAssociation( tgtHelper.IthVertex( 0,*edgeT ),
1448                                    tgtHelper.IthVertex( 0,*edgeS ), assocMap );
1449     TAssocTool::InsertAssociation( tgtHelper.IthVertex( 1,*edgeT ),
1450                                    tgtHelper.IthVertex( 1,*edgeS ), assocMap );
1451   }
1452
1453 } // namespace
1454
1455
1456 //=======================================================================
1457 //function : Compute
1458 //purpose  :
1459 //=======================================================================
1460
1461 bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
1462 {
1463   _src2tgtNodes.clear();
1464
1465   if ( !_sourceHypo )
1466     return false;
1467
1468   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
1469   SMESH_Mesh * tgtMesh = & theMesh;
1470   if ( !srcMesh )
1471     srcMesh = tgtMesh;
1472
1473   SMESHDS_Mesh * meshDS = theMesh.GetMeshDS();
1474   SMESH_MesherHelper helper( theMesh );
1475
1476   // ---------------------------
1477   // Make sub-shapes association
1478   // ---------------------------
1479
1480   TopoDS_Face   tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
1481   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
1482
1483   helper.SetSubShape( tgtFace );
1484
1485   TAssocTool::TShapeShapeMap shape2ShapeMap;
1486   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
1487   if ( shape2ShapeMap.IsEmpty() )
1488     initAssoc4Quad2Closed( tgtFace, helper, srcShape, srcMesh, shape2ShapeMap );
1489   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
1490                                              shape2ShapeMap)  ||
1491        !shape2ShapeMap.IsBound( tgtFace ))
1492   {
1493     if ( srcShape.ShapeType() == TopAbs_FACE )
1494     {
1495       int nbE1 = helper.Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
1496       int nbE2 = helper.Count( srcShape, TopAbs_EDGE, /*ignoreSame=*/true );
1497       if ( nbE1 != nbE2 )
1498         return error(COMPERR_BAD_SHAPE,
1499                      SMESH_Comment("Different number of edges in source and target faces: ")
1500                      << nbE2 << " and " << nbE1 );
1501     }
1502     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
1503   }
1504   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
1505
1506   // ----------------------------------------------
1507   // Assure that mesh on a source Face is computed
1508   // ----------------------------------------------
1509
1510   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
1511   SMESH_subMesh* tgtSubMesh = tgtMesh->GetSubMesh( tgtFace );
1512
1513   string srcMeshError;
1514   if ( tgtMesh == srcMesh ) {
1515     if ( !TAssocTool::MakeComputed( srcSubMesh ))
1516       srcMeshError = TAssocTool::SourceNotComputedError( srcSubMesh, this );
1517   }
1518   else {
1519     if ( !srcSubMesh->IsMeshComputed() )
1520       srcMeshError = TAssocTool::SourceNotComputedError();
1521   }
1522   if ( !srcMeshError.empty() )
1523     return error(COMPERR_BAD_INPUT_MESH, srcMeshError );
1524
1525   // ===========
1526   // Projection
1527   // ===========
1528
1529   // get ordered src and tgt EDGEs
1530   TSideVector srcWires, tgtWires;
1531   bool is1DComputed = false; // if any tgt EDGE is meshed
1532   TError err = getWires( tgtFace, srcFace, tgtMesh, srcMesh,
1533                          shape2ShapeMap, srcWires, tgtWires, _src2tgtNodes, is1DComputed );
1534   if ( err && !err->IsOK() )
1535     return error( err );
1536
1537   bool projDone = false;
1538
1539   if ( !projDone )
1540   {
1541     // try to project from the same face with different location
1542     projDone = projectPartner( tgtFace, srcFace, tgtWires, srcWires,
1543                                shape2ShapeMap, _src2tgtNodes, is1DComputed );
1544   }
1545   if ( !projDone )
1546   {
1547     // projection in case if the faces are similar in 2D space
1548     projDone = projectBy2DSimilarity( tgtFace, srcFace, tgtWires, srcWires,
1549                                       shape2ShapeMap, _src2tgtNodes, is1DComputed );
1550   }
1551   if ( !projDone )
1552   {
1553     // projection in case of quadrilateral faces
1554     // NOT IMPLEMENTED, returns false
1555     projDone = projectQuads( tgtFace, srcFace, tgtWires, srcWires,
1556                              shape2ShapeMap, _src2tgtNodes, is1DComputed);
1557   }
1558
1559   // it will remove mesh built on edges and vertices in failure case
1560   MeshCleaner cleaner( tgtSubMesh );
1561
1562   if ( !projDone )
1563   {
1564     _src2tgtNodes.clear();
1565     // --------------------
1566     // Prepare to mapping 
1567     // --------------------
1568
1569     // Check if node projection to a face is needed
1570     Bnd_B2d uvBox;
1571     SMDS_ElemIteratorPtr faceIt = srcSubMesh->GetSubMeshDS()->GetElements();
1572     set< const SMDS_MeshNode* > faceNodes;
1573     for ( ; faceNodes.size() < 3 && faceIt->more();  ) {
1574       const SMDS_MeshElement* face = faceIt->next();
1575       SMDS_ElemIteratorPtr nodeIt = face->nodesIterator();
1576       while ( nodeIt->more() ) {
1577         const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
1578         if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE &&
1579              faceNodes.insert( node ).second )
1580           uvBox.Add( helper.GetNodeUV( srcFace, node ));
1581       }
1582     }
1583     bool toProjectNodes = false;
1584     if ( faceNodes.size() == 1 )
1585       toProjectNodes = ( uvBox.IsVoid() || uvBox.CornerMin().IsEqual( gp_XY(0,0), 1e-12 ));
1586     else if ( faceNodes.size() > 1 )
1587       toProjectNodes = ( uvBox.IsVoid() || uvBox.SquareExtent() < DBL_MIN );
1588
1589     // Find the corresponding source and target vertex
1590     // and <theReverse> flag needed to call mapper.Apply()
1591
1592     TopoDS_Vertex srcV1, tgtV1;
1593     bool reverse = false;
1594
1595     TopExp_Explorer vSrcExp( srcFace, TopAbs_VERTEX );
1596     srcV1 = TopoDS::Vertex( vSrcExp.Current() );
1597     tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
1598
1599     list< TopoDS_Edge > tgtEdges, srcEdges;
1600     list< int > nbEdgesInWires;
1601     SMESH_Block::GetOrderedEdges( tgtFace, tgtEdges, nbEdgesInWires, tgtV1 );
1602     SMESH_Block::GetOrderedEdges( srcFace, srcEdges, nbEdgesInWires, srcV1 );
1603
1604     if ( nbEdgesInWires.front() > 1 ) // possible to find out orientation
1605     {
1606       TopoDS_Edge srcE1 = srcEdges.front(), tgtE1 = tgtEdges.front();
1607       TopoDS_Shape srcE1bis = shape2ShapeMap( tgtE1 );
1608       reverse = ( ! srcE1.IsSame( srcE1bis ));
1609       if ( reverse &&
1610            //_sourceHypo->HasVertexAssociation() &&
1611            nbEdgesInWires.front() > 2 &&
1612            helper.IsRealSeam( tgtEdges.front() ))
1613       {
1614         // projection to a face with seam EDGE; pb is that GetOrderedEdges()
1615         // always puts a seam EDGE first (if possible) and as a result
1616         // we can't use only theReverse flag to correctly associate source
1617         // and target faces in the mapper. Thus we select srcV1 so that
1618         // GetOrderedEdges() to return EDGEs in a needed order
1619         TopoDS_Face tgtFaceBis = tgtFace;
1620         TopTools_MapOfShape checkedVMap( tgtEdges.size() );
1621         checkedVMap.Add ( srcV1 );
1622         for ( vSrcExp.Next(); vSrcExp.More(); )
1623         {
1624           tgtFaceBis.Reverse();
1625           tgtEdges.clear();
1626           SMESH_Block::GetOrderedEdges( tgtFaceBis, tgtEdges, nbEdgesInWires, tgtV1 );
1627           bool ok = true;
1628           list< TopoDS_Edge >::iterator edgeS = srcEdges.begin(), edgeT = tgtEdges.begin();
1629           for ( ; edgeS != srcEdges.end() && ok ; ++edgeS, ++edgeT )
1630             ok = edgeT->IsSame( shape2ShapeMap( *edgeS, /*isSrc=*/true ));
1631           if ( ok )
1632             break; // FOUND!
1633
1634           reverse = !reverse;
1635           if ( reverse )
1636           {
1637             vSrcExp.Next();
1638             while ( vSrcExp.More() && !checkedVMap.Add( vSrcExp.Current() ))
1639               vSrcExp.Next();
1640           }
1641           else
1642           {
1643             srcV1 = TopoDS::Vertex( vSrcExp.Current() );
1644             tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
1645             srcEdges.clear();
1646             SMESH_Block::GetOrderedEdges( srcFace, srcEdges, nbEdgesInWires, srcV1 );
1647           }
1648         }
1649       }
1650       // for the case: project to a closed face from a non-closed face w/o vertex assoc;
1651       // avoid projecting to a seam from two EDGEs with different nb nodes on them
1652       // ( test mesh_Projection_2D_01/B1 )
1653       if ( !_sourceHypo->HasVertexAssociation() &&
1654            nbEdgesInWires.front() > 2 &&
1655            helper.IsRealSeam( tgtEdges.front() ))
1656       {
1657         TopoDS_Shape srcEdge1 = shape2ShapeMap( tgtEdges.front() );
1658         list< TopoDS_Edge >::iterator srcEdge2 =
1659           std::find( srcEdges.begin(), srcEdges.end(), srcEdge1);
1660         list< TopoDS_Edge >::iterator srcEdge3 =
1661           std::find( srcEdges.begin(), srcEdges.end(), srcEdge1.Reversed());
1662         if ( srcEdge2 == srcEdges.end() || srcEdge3 == srcEdges.end() ) // srcEdge1 is not a seam
1663         {
1664           // find srcEdge2 which also will be projected to tgtEdges.front()
1665           for ( srcEdge2 = srcEdges.begin(); srcEdge2 != srcEdges.end(); ++srcEdge2 )
1666             if ( !srcEdge1.IsSame( *srcEdge2 ) &&
1667                  tgtEdges.front().IsSame( shape2ShapeMap( *srcEdge2, /*isSrc=*/true )))
1668               break;
1669           // compare nb nodes on srcEdge1 and srcEdge2
1670           if ( srcEdge2 != srcEdges.end() )
1671           {
1672             int nbN1 = 0, nbN2 = 0;
1673             if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( srcEdge1 ))
1674               nbN1 = sm->NbNodes();
1675             if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( *srcEdge2 ))
1676               nbN2 = sm->NbNodes();
1677             if ( nbN1 != nbN2 )
1678               srcV1 = helper.IthVertex( 1, srcEdges.front() );
1679           }
1680         }
1681       }
1682     }
1683     else if ( nbEdgesInWires.front() == 1 ) // a sole edge in a wire
1684     {
1685       TopoDS_Edge srcE1 = srcEdges.front(), tgtE1 = tgtEdges.front();
1686       for ( size_t iW = 0; iW < srcWires.size(); ++iW )
1687       {
1688         StdMeshers_FaceSidePtr srcWire = srcWires[iW];
1689         for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
1690           if ( srcE1.IsSame( srcWire->Edge( iE )))
1691           {
1692             reverse = ( tgtE1.Orientation() != tgtWires[iW]->Edge( iE ).Orientation() );
1693             break;
1694           }
1695       }
1696     }
1697     else
1698     {
1699       RETURN_BAD_RESULT("Bad result from SMESH_Block::GetOrderedEdges()");
1700     }
1701
1702     // Load pattern from the source face
1703     SMESH_Pattern mapper;
1704     mapper.Load( srcMesh, srcFace, toProjectNodes, srcV1, /*keepNodes=*/true );
1705     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
1706       return error(COMPERR_BAD_INPUT_MESH,"Can't load mesh pattern from the source face");
1707
1708     // --------------------
1709     // Perform 2D mapping
1710     // --------------------
1711
1712     // Compute mesh on a target face
1713
1714     mapper.Apply( tgtFace, tgtV1, reverse );
1715     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK ) {
1716       // std::ofstream file("/tmp/Pattern.smp" );
1717       // mapper.Save( file );
1718       return error("Can't apply source mesh pattern to the face");
1719     }
1720
1721     // Create the mesh
1722
1723     const bool toCreatePolygons = false, toCreatePolyedrs = false;
1724     mapper.MakeMesh( tgtMesh, toCreatePolygons, toCreatePolyedrs );
1725     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
1726       return error("Can't make mesh by source mesh pattern");
1727
1728     // fill _src2tgtNodes
1729     std::vector< const SMDS_MeshNode* > *srcNodes, *tgtNodes;
1730     mapper.GetInOutNodes( srcNodes, tgtNodes );
1731     size_t nbN = std::min( srcNodes->size(), tgtNodes->size() );
1732     for ( size_t i = 0; i < nbN; ++i )
1733       if ( (*srcNodes)[i] && (*tgtNodes)[i] )
1734         _src2tgtNodes.insert( make_pair( (*srcNodes)[i], (*tgtNodes)[i] ));
1735
1736
1737   } // end of projection using Pattern mapping
1738
1739   {
1740     // -------------------------------------------------------------------------
1741     // mapper doesn't take care of nodes already existing on edges and vertices,
1742     // so we must merge nodes created by it with existing ones
1743     // -------------------------------------------------------------------------
1744
1745     SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
1746
1747     // Make groups of nodes to merge
1748
1749     // loop on EDGE and VERTEX sub-meshes of a target FACE
1750     SMESH_subMeshIteratorPtr smIt = tgtSubMesh->getDependsOnIterator(/*includeSelf=*/false,
1751                                                                      /*complexShapeFirst=*/false);
1752     while ( smIt->more() )
1753     {
1754       SMESH_subMesh*     sm = smIt->next();
1755       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
1756       if ( !smDS || smDS->NbNodes() == 0 )
1757         continue;
1758       //if ( !is1DComputed && sm->GetSubShape().ShapeType() == TopAbs_EDGE )
1759       //  break;
1760
1761       if ( helper.IsDegenShape( sm->GetId() ) ) // to merge all nodes on degenerated
1762       {
1763         if ( sm->GetSubShape().ShapeType() == TopAbs_EDGE )
1764         {
1765           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1766           SMESH_subMeshIteratorPtr smDegenIt
1767             = sm->getDependsOnIterator(/*includeSelf=*/true,/*complexShapeFirst=*/false);
1768           while ( smDegenIt->more() )
1769             if (( smDS = smDegenIt->next()->GetSubMeshDS() ))
1770             {
1771               SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1772               while ( nIt->more() )
1773                 groupsOfNodes.back().push_back( nIt->next() );
1774             }
1775         }
1776         continue; // do not treat sm of degen VERTEX
1777       }
1778
1779       // Sort new and old nodes of a sub-mesh separately
1780
1781       bool isSeam = helper.IsRealSeam( sm->GetId() );
1782
1783       enum { NEW_NODES = 0, OLD_NODES };
1784       map< double, const SMDS_MeshNode* > u2nodesMaps[2], u2nodesOnSeam;
1785       map< double, const SMDS_MeshNode* >::iterator u_oldNode, u_newNode, u_newOnSeam, newEnd;
1786       set< const SMDS_MeshNode* > seamNodes;
1787
1788       // mapper changed, no more "mapper puts on a seam edge nodes from 2 edges"
1789       if ( isSeam && ! getBoundaryNodes ( sm, tgtFace, u2nodesOnSeam, seamNodes ))
1790         ;//RETURN_BAD_RESULT("getBoundaryNodes() failed");
1791
1792       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1793       while ( nIt->more() )
1794       {
1795         const SMDS_MeshNode* node = nIt->next();
1796         bool isOld = isOldNode( node );
1797
1798         if ( !isOld && isSeam ) { // new node on a seam edge
1799           if ( seamNodes.count( node ) )
1800             continue; // node is already in the map
1801         }
1802
1803         // sort nodes on edges by their position
1804         map< double, const SMDS_MeshNode* > & pos2nodes = u2nodesMaps[isOld ? OLD_NODES : NEW_NODES];
1805         switch ( node->GetPosition()->GetTypeOfPosition() )
1806         {
1807         case  SMDS_TOP_VERTEX: {
1808           if ( !is1DComputed && !pos2nodes.empty() )
1809             u2nodesMaps[isOld ? NEW_NODES : OLD_NODES].insert( make_pair( 0, node ));
1810           else
1811             pos2nodes.insert( make_pair( 0, node ));
1812           break;
1813         }
1814         case  SMDS_TOP_EDGE:   {
1815           const SMDS_EdgePosition* pos =
1816             static_cast<const SMDS_EdgePosition*>(node->GetPosition());
1817           pos2nodes.insert( make_pair( pos->GetUParameter(), node ));
1818           break;
1819         }
1820         default:
1821           RETURN_BAD_RESULT("Wrong node position type: "<<
1822                             node->GetPosition()->GetTypeOfPosition());
1823         }
1824       }
1825       const bool mergeNewToOld =
1826         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesMaps[ OLD_NODES ].size() );
1827       const bool mergeSeamToNew =
1828         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesOnSeam.size() );
1829
1830       if ( !mergeNewToOld )
1831         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1832              u2nodesMaps[ OLD_NODES ].size() > 0 )
1833         {
1834           u_oldNode = u2nodesMaps[ OLD_NODES ].begin(); 
1835           newEnd    = u2nodesMaps[ OLD_NODES ].end();
1836           for ( ; u_oldNode != newEnd; ++u_oldNode )
1837             SMESH_Algo::addBadInputElement( u_oldNode->second );
1838           return error( COMPERR_BAD_INPUT_MESH,
1839                         SMESH_Comment( "Existing mesh mismatches the projected 2D mesh on " )
1840                         << ( sm->GetSubShape().ShapeType() == TopAbs_EDGE ? "edge" : "vertex" )
1841                         << " #" << sm->GetId() );
1842         }
1843       if ( isSeam && !mergeSeamToNew ) {
1844         const TopoDS_Shape& seam = sm->GetSubShape();
1845         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1846              u2nodesOnSeam.size()            > 0 &&
1847              seam.ShapeType() == TopAbs_EDGE )
1848         {
1849           int nbE1 = helper.Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
1850           int nbE2 = helper.Count( srcFace, TopAbs_EDGE, /*ignoreSame=*/true );
1851           if ( nbE1 != nbE2 ) // 2 EDGEs are mapped to a seam EDGE
1852           {
1853             // find the 2 EDGEs of srcFace
1854             TopTools_DataMapIteratorOfDataMapOfShapeShape src2tgtIt( shape2ShapeMap._map2to1 );
1855             for ( ; src2tgtIt.More(); src2tgtIt.Next() )
1856               if ( seam.IsSame( src2tgtIt.Value() ))
1857                 SMESH_Algo::addBadInputElements
1858                   ( srcMesh->GetMeshDS()->MeshElements( src2tgtIt.Key() ));
1859             return error( COMPERR_BAD_INPUT_MESH,
1860                           "Different number of nodes on two edges projected to a seam edge" );
1861           }
1862         }
1863       }
1864
1865       // Make groups of nodes to merge
1866
1867       u_oldNode = u2nodesMaps[ OLD_NODES ].begin(); 
1868       u_newNode = u2nodesMaps[ NEW_NODES ].begin();
1869       newEnd    = u2nodesMaps[ NEW_NODES ].end();
1870       u_newOnSeam = u2nodesOnSeam.begin();
1871       if ( mergeNewToOld )
1872         for ( ; u_newNode != newEnd; ++u_newNode, ++u_oldNode )
1873         {
1874           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1875           groupsOfNodes.back().push_back( u_oldNode->second );
1876           groupsOfNodes.back().push_back( u_newNode->second );
1877           if ( mergeSeamToNew )
1878             groupsOfNodes.back().push_back( (u_newOnSeam++)->second );
1879         }
1880       else if ( mergeSeamToNew )
1881         for ( ; u_newNode != newEnd; ++u_newNode, ++u_newOnSeam )
1882         {
1883           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1884           groupsOfNodes.back().push_back( u_newNode->second );
1885           groupsOfNodes.back().push_back( u_newOnSeam->second );
1886         }
1887
1888     } // loop on EDGE and VERTEX submeshes of a target FACE
1889
1890     // Merge
1891
1892     SMESH_MeshEditor editor( tgtMesh );
1893     int nbFaceBeforeMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1894     editor.MergeNodes( groupsOfNodes );
1895     int nbFaceAtferMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1896     if ( nbFaceBeforeMerge != nbFaceAtferMerge && !helper.HasDegeneratedEdges() )
1897       return error(COMPERR_BAD_INPUT_MESH, "Probably invalid node parameters on geom faces");
1898
1899     // ----------------------------------------------------------------
1900     // The mapper can't create quadratic elements, so convert if needed
1901     // ----------------------------------------------------------------
1902
1903     SMDS_ElemIteratorPtr faceIt;
1904     faceIt         = srcSubMesh->GetSubMeshDS()->GetElements();
1905     bool srcIsQuad = faceIt->next()->IsQuadratic();
1906     faceIt         = tgtSubMesh->GetSubMeshDS()->GetElements();
1907     bool tgtIsQuad = faceIt->next()->IsQuadratic();
1908     if ( srcIsQuad && !tgtIsQuad )
1909     {
1910       TIDSortedElemSet tgtFaces;
1911       faceIt = tgtSubMesh->GetSubMeshDS()->GetElements();
1912       while ( faceIt->more() )
1913         tgtFaces.insert( tgtFaces.end(), faceIt->next() );
1914
1915       editor.ConvertToQuadratic(/*theForce3d=*/false, tgtFaces, false);
1916     }
1917   } // end of coincident nodes and quadratic elements treatment
1918
1919
1920   if ( !projDone || is1DComputed )
1921     // ----------------------------------------------------------------
1922     // The mapper can create distorted faces by placing nodes out of the FACE
1923     // boundary, also bad face can be created if EDGEs already discretized
1924     // --> fix bad faces by smoothing
1925     // ----------------------------------------------------------------
1926     if ( helper.IsDistorted2D( tgtSubMesh, /*checkUV=*/false ))
1927     {
1928       morph( helper, tgtFace, srcFace, tgtWires, srcWires, _src2tgtNodes );
1929
1930       if ( !fixDistortedFaces( helper, tgtWires ))
1931         return error("Invalid mesh generated");
1932     }
1933   // ---------------------------
1934   // Check elements orientation
1935   // ---------------------------
1936
1937   TopoDS_Face face = TopoDS::Face( theShape );
1938   if ( !theMesh.IsMainShape( tgtFace ))
1939   {
1940     // find the main shape
1941     TopoDS_Shape mainShape = meshDS->ShapeToMesh();
1942     switch ( mainShape.ShapeType() ) {
1943     case TopAbs_SHELL:
1944     case TopAbs_SOLID: break;
1945     default:
1946       TopTools_ListIteratorOfListOfShape ancestIt = theMesh.GetAncestors( face );
1947       for ( ; ancestIt.More(); ancestIt.Next() ) {
1948         TopAbs_ShapeEnum type = ancestIt.Value().ShapeType();
1949         if ( type == TopAbs_SOLID ) {
1950           mainShape = ancestIt.Value();
1951           break;
1952         } else if ( type == TopAbs_SHELL ) {
1953           mainShape = ancestIt.Value();
1954         }
1955       }
1956     }
1957     // find tgtFace in the main solid or shell to know it's true orientation.
1958     TopExp_Explorer exp( mainShape, TopAbs_FACE );
1959     for ( ; exp.More(); exp.Next() ) {
1960       if ( tgtFace.IsSame( exp.Current() )) {
1961         face = TopoDS::Face( exp.Current() );
1962         break;
1963       }
1964     }
1965   }
1966   // Fix orientation
1967   if ( helper.IsReversedSubMesh( face ))
1968   {
1969     SMESH_MeshEditor editor( tgtMesh );
1970     SMDS_ElemIteratorPtr eIt = meshDS->MeshElements( face )->GetElements();
1971     while ( eIt->more() ) {
1972       const SMDS_MeshElement* e = eIt->next();
1973       if ( e->GetType() == SMDSAbs_Face && !editor.Reorient( e ))
1974         RETURN_BAD_RESULT("Pb of SMESH_MeshEditor::Reorient()");
1975     }
1976   }
1977
1978   cleaner.Release(); // not to remove mesh
1979
1980   return true;
1981 }
1982
1983
1984 //=======================================================================
1985 //function : Evaluate
1986 //purpose  : 
1987 //=======================================================================
1988
1989 bool StdMeshers_Projection_2D::Evaluate(SMESH_Mesh&         theMesh,
1990                                         const TopoDS_Shape& theShape,
1991                                         MapShapeNbElems&    aResMap)
1992 {
1993   if ( !_sourceHypo )
1994     return false;
1995
1996   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
1997   SMESH_Mesh * tgtMesh = & theMesh;
1998   if ( !srcMesh )
1999     srcMesh = tgtMesh;
2000
2001   // ---------------------------
2002   // Make sub-shapes association
2003   // ---------------------------
2004
2005   TopoDS_Face tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
2006   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
2007
2008   TAssocTool::TShapeShapeMap shape2ShapeMap;
2009   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
2010   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
2011                                              shape2ShapeMap)  ||
2012        !shape2ShapeMap.IsBound( tgtFace ))
2013     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
2014
2015   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
2016
2017   // -------------------------------------------------------
2018   // Assure that mesh on a source Face is computed/evaluated
2019   // -------------------------------------------------------
2020
2021   std::vector<int> aVec;
2022
2023   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
2024   if ( srcSubMesh->IsMeshComputed() )
2025   {
2026     aVec.resize( SMDSEntity_Last, 0 );
2027     aVec[SMDSEntity_Node] = srcSubMesh->GetSubMeshDS()->NbNodes();
2028
2029     SMDS_ElemIteratorPtr elemIt = srcSubMesh->GetSubMeshDS()->GetElements();
2030     while ( elemIt->more() )
2031       aVec[ elemIt->next()->GetEntityType() ]++;
2032   }
2033   else
2034   {
2035     MapShapeNbElems  tmpResMap;
2036     MapShapeNbElems& srcResMap = (srcMesh == tgtMesh) ? aResMap : tmpResMap;
2037     if ( !_gen->Evaluate( *srcMesh, srcShape, srcResMap ))
2038       return error(COMPERR_BAD_INPUT_MESH,"Source mesh not evaluatable");
2039     aVec = srcResMap[ srcSubMesh ];
2040     if ( aVec.empty() )
2041       return error(COMPERR_BAD_INPUT_MESH,"Source mesh is wrongly evaluated");
2042   }
2043
2044   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
2045   aResMap.insert(std::make_pair(sm,aVec));
2046
2047   return true;
2048 }
2049
2050
2051 //=============================================================================
2052 /*!
2053  * \brief Sets a default event listener to submesh of the source face
2054   * \param subMesh - submesh where algo is set
2055  *
2056  * This method is called when a submesh gets HYP_OK algo_state.
2057  * After being set, event listener is notified on each event of a submesh.
2058  * Arranges that CLEAN event is translated from source submesh to
2059  * the submesh
2060  */
2061 //=============================================================================
2062
2063 void StdMeshers_Projection_2D::SetEventListener(SMESH_subMesh* subMesh)
2064 {
2065   TAssocTool::SetEventListener( subMesh,
2066                                 _sourceHypo->GetSourceFace(),
2067                                 _sourceHypo->GetSourceMesh() );
2068 }