Salome HOME
This commit was generated by cvs2git to create tag 'V4_1_0rc1'.
[modules/smesh.git] / src / StdMeshers / StdMeshers_ProjectionUtils.cxx
1 //  SMESH SMESH : idl implementation based on 'SMESH' unit's calsses
2 //
3 //  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS 
5 // 
6 //  This library is free software; you can redistribute it and/or 
7 //  modify it under the terms of the GNU Lesser General Public 
8 //  License as published by the Free Software Foundation; either 
9 //  version 2.1 of the License. 
10 // 
11 //  This library is distributed in the hope that it will be useful, 
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of 
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
14 //  Lesser General Public License for more details. 
15 // 
16 //  You should have received a copy of the GNU Lesser General Public 
17 //  License along with this library; if not, write to the Free Software 
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA 
19 // 
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //
23 //
24 // File      : StdMeshers_ProjectionUtils.cxx
25 // Created   : Fri Oct 27 10:24:28 2006
26 // Author    : Edward AGAPOV (eap)
27
28
29 #include "StdMeshers_ProjectionUtils.hxx"
30
31 #include "StdMeshers_ProjectionSource1D.hxx"
32 #include "StdMeshers_ProjectionSource2D.hxx"
33 #include "StdMeshers_ProjectionSource3D.hxx"
34
35 #include "SMESH_Algo.hxx"
36 #include "SMESH_Block.hxx"
37 #include "SMESH_Gen.hxx"
38 #include "SMESH_Hypothesis.hxx"
39 #include "SMESH_IndexedDataMapOfShapeIndexedMapOfShape.hxx"
40 #include "SMESH_Mesh.hxx"
41 #include "SMESH_MeshEditor.hxx"
42 #include "SMESH_subMesh.hxx"
43 #include "SMESH_subMeshEventListener.hxx"
44 #include "SMDS_EdgePosition.hxx"
45
46 #include "utilities.h"
47
48 #include <BRepTools.hxx>
49 #include <BRepTools_WireExplorer.hxx>
50 #include <BRep_Builder.hxx>
51 #include <BRep_Tool.hxx>
52 #include <Bnd_Box.hxx>
53 #include <TopAbs.hxx>
54 #include <TopExp.hxx>
55 #include <TopExp_Explorer.hxx>
56 #include <TopTools_Array1OfShape.hxx>
57 #include <TopTools_ListIteratorOfListOfShape.hxx>
58 #include <TopTools_ListOfShape.hxx>
59 #include <TopTools_MapOfShape.hxx>
60 #include <TopoDS.hxx>
61 #include <TopoDS_Compound.hxx>
62 #include <TopoDS_Shape.hxx>
63 #include <gp_Pnt.hxx>
64 #include <gp_Vec.hxx>
65 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
66 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
67
68
69 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
70 #define SHOW_VERTEX(v,msg) // { \
71 //  if ( v.IsNull() ) cout << msg << " NULL SHAPE" << endl; \
72 // else if (v.ShapeType() == TopAbs_VERTEX) {\
73 //   gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( v ));\
74 //   cout << msg << (v).TShape().operator->()<<" ( " <<p.X()<<", "<<p.Y()<<", "<<p.Z()<<" )"<<endl;}\
75 // else {\
76 // cout << msg << " "; TopAbs::Print(v.ShapeType(),cout) <<" "<<(v).TShape().operator->()<<endl;}\
77 // }
78 #define SHOW_LIST(msg,l) \
79 // { \
80 //     cout << msg << " ";\
81 //     list< TopoDS_Edge >::const_iterator e = l.begin();\
82 //     for ( int i = 0; e != l.end(); ++e, ++i ) {\
83 //       cout << i << "V (" << TopExp::FirstVertex( *e, true ).TShape().operator->() << ") "\
84 //            << i << "E (" << e->TShape().operator->() << "); "; }\
85 //     cout << endl;\
86 //   }
87
88 namespace {
89   //================================================================================
90   /*!
91    * \brief Reverse order of edges in a list and their orientation
92     * \param edges - list of edges to reverse
93     * \param nbEdges - number of edges to reverse
94    */
95   //================================================================================
96
97   void Reverse( list< TopoDS_Edge > & edges, const int nbEdges )
98   {
99     SHOW_LIST("BEFORE REVERSE", edges);
100
101     list< TopoDS_Edge >::iterator eIt = edges.begin();
102     if ( edges.size() == nbEdges )
103     {
104       edges.reverse();
105     }
106     else  // reverse only the given nb of edges
107     {
108       // look for the last edge to be reversed
109       list< TopoDS_Edge >::iterator eBackIt = edges.begin();
110       for ( int i = 1; i < nbEdges; ++i )
111         ++eBackIt;
112       // reverse
113       while ( eIt != eBackIt ) {
114         std::swap( *eIt, *eBackIt );
115         SHOW_LIST("# AFTER SWAP", edges)
116         if ( (++eIt) != eBackIt )
117           --eBackIt;
118       }
119     }
120     for ( eIt = edges.begin(); eIt != edges.end(); ++eIt )
121       eIt->Reverse();
122     SHOW_LIST("ATFER REVERSE", edges)
123   }
124
125   //================================================================================
126   /*!
127    * \brief Check if propagation is possible
128     * \param theMesh1 - source mesh
129     * \param theMesh2 - target mesh
130     * \retval bool - true if possible
131    */
132   //================================================================================
133
134   bool IsPropagationPossible( SMESH_Mesh* theMesh1, SMESH_Mesh* theMesh2 )
135   {
136     if ( theMesh1 != theMesh2 ) {
137       TopoDS_Shape mainShape1 = theMesh1->GetMeshDS()->ShapeToMesh();
138       TopoDS_Shape mainShape2 = theMesh2->GetMeshDS()->ShapeToMesh();
139       return mainShape1.IsSame( mainShape2 );
140     }
141     return true;
142   }
143
144   //================================================================================
145   /*!
146    * \brief Fix up association of edges in faces by possible propagation
147     * \param nbEdges - nb of edges in an outer wire
148     * \param edges1 - edges of one face
149     * \param edges2 - matching edges of another face
150     * \param theMesh1 - mesh 1
151     * \param theMesh2 - mesh 2
152     * \retval bool - true if association was fixed
153    */
154   //================================================================================
155
156   bool FixAssocByPropagation( const int             nbEdges,
157                               list< TopoDS_Edge > & edges1,
158                               list< TopoDS_Edge > & edges2,
159                               SMESH_Mesh*           theMesh1,
160                               SMESH_Mesh*           theMesh2)
161   {
162     if ( nbEdges == 2 && IsPropagationPossible( theMesh1, theMesh2 ) )
163     {
164       list< TopoDS_Edge >::iterator eIt2 = ++edges2.begin(); // 2nd edge of the 2nd face
165       TopoDS_Edge edge2 =
166         StdMeshers_ProjectionUtils::GetPropagationEdge( theMesh1, *eIt2, edges1.front() ).second;
167       if ( !edge2.IsNull() ) { // propagation found for the second edge
168         Reverse( edges2, nbEdges );
169         return true;
170       }
171     }
172     return false;
173   }
174
175   //================================================================================
176   /*!
177    * \brief Look for a group containing a target shape and similar to a source group
178     * \param tgtShape - target edge or face
179     * \param tgtMesh1 - target mesh
180     * \param srcGroup - source group
181     * \retval TopoDS_Shape - found target group
182    */
183   //================================================================================
184
185   TopoDS_Shape FindGroupContaining(const TopoDS_Shape& tgtShape,
186                                    const SMESH_Mesh*   tgtMesh1,
187                                    const TopoDS_Shape& srcGroup)
188   {
189     list<SMESH_subMesh*> subMeshes = tgtMesh1->GetGroupSubMeshesContaining(tgtShape);
190     list<SMESH_subMesh*>::iterator sm = subMeshes.begin();
191     int type, last = TopAbs_SHAPE;
192     StdMeshers_ProjectionUtils util;
193     for ( ; sm != subMeshes.end(); ++sm ) {
194       const TopoDS_Shape & group = (*sm)->GetSubShape();
195       // check if group is similar to srcGroup
196       for ( type = srcGroup.ShapeType(); type < last; ++type)
197         if ( util.Count( srcGroup, (TopAbs_ShapeEnum)type, 0) !=
198              util.Count( group,    (TopAbs_ShapeEnum)type, 0))
199           break;
200       if ( type == last )
201         return group;
202     }
203     return TopoDS_Shape();
204   }
205 }
206
207 //=======================================================================
208 /*!
209  * \brief Looks for association of all subshapes of two shapes
210  * \param theShape1 - shape 1
211  * \param theMesh1 - mesh built on shape 1
212  * \param theShape2 - shape 2
213  * \param theMesh2 - mesh built on shape 2
214  * \param theAssociation - association map to be filled that may
215  *                         contain association of one or two pairs of vertices
216  * \retval bool - true if association found
217  */
218 //=======================================================================
219
220 bool StdMeshers_ProjectionUtils::FindSubShapeAssociation(const TopoDS_Shape& theShape1,
221                                                          SMESH_Mesh*         theMesh1,
222                                                          const TopoDS_Shape& theShape2,
223                                                          SMESH_Mesh*         theMesh2,
224                                                          TShapeShapeMap &    theMap)
225 {
226   if ( theShape1.ShapeType() != theShape2.ShapeType() ) {
227     // is it the case of a group member -> another group? (PAL16202, 16203)
228     TopoDS_Shape group1, group2;
229     if ( theShape1.ShapeType() == TopAbs_COMPOUND ) {
230       group1 = theShape1;
231       group2 = FindGroupContaining( theShape2, theMesh2, group1 );
232     }
233     else if ( theShape2.ShapeType() == TopAbs_COMPOUND ) {
234       group2 = theShape2;
235       group1 = FindGroupContaining( theShape1, theMesh1, group2 );
236     }
237     if ( group1.IsNull() || group2.IsNull() )
238       RETURN_BAD_RESULT("Different shape types");
239     // Associate compounds
240     return FindSubShapeAssociation(group1, theMesh1, group2, theMesh2, theMap );
241   }
242
243   bool bidirect = ( !theShape1.IsSame( theShape2 ));
244   if ( !theMap.IsEmpty() )
245   {
246     //======================================================================
247     // HAS initial vertex association
248     //======================================================================
249     switch ( theShape1.ShapeType() ) {
250       // ----------------------------------------------------------------------
251     case TopAbs_EDGE: { // TopAbs_EDGE
252       // ----------------------------------------------------------------------
253       if ( theMap.Extent() != 2 )
254         RETURN_BAD_RESULT("Wrong map extent " << theMap.Extent() );
255       TopoDS_Edge edge1 = TopoDS::Edge( theShape1 );
256       TopoDS_Edge edge2 = TopoDS::Edge( theShape2 );
257       TopoDS_Vertex VV1[2], VV2[2];
258       TopExp::Vertices( edge1, VV1[0], VV1[1] );
259       TopExp::Vertices( edge2, VV2[0], VV2[1] );
260       int i1 = 0, i2 = 0;
261       if ( theMap.IsBound( VV1[ i1 ] )) i1 = 1;
262       if ( theMap.IsBound( VV2[ i2 ] )) i2 = 1;
263       InsertAssociation( VV1[ i1 ], VV2[ i2 ], theMap, bidirect);
264       InsertAssociation( theShape1, theShape2, theMap, bidirect );
265       return true;
266     }
267       // ----------------------------------------------------------------------
268     case TopAbs_FACE: { // TopAbs_FACE
269       // ----------------------------------------------------------------------
270       TopoDS_Face face1 = TopoDS::Face( theShape1 );
271       TopoDS_Face face2 = TopoDS::Face( theShape2 );
272
273       TopoDS_Vertex VV1[2], VV2[2];
274       // find a not closed edge of face1 both vertices of which are associated
275       int nbEdges = 0;
276       TopExp_Explorer exp ( face1, TopAbs_EDGE );
277       for ( ; VV2[ 1 ].IsNull() && exp.More(); exp.Next(), ++nbEdges ) {
278         TopExp::Vertices( TopoDS::Edge( exp.Current() ), VV1[0], VV1[1] );
279         if ( theMap.IsBound( VV1[0] ) ) {
280           VV2[ 0 ] = TopoDS::Vertex( theMap( VV1[0] ));
281           if ( theMap.IsBound( VV1[1] ) && !VV1[0].IsSame( VV1[1] ))
282             VV2[ 1 ] = TopoDS::Vertex( theMap( VV1[1] ));
283         }
284       }
285       if ( VV2[ 1 ].IsNull() ) { // 2 bound vertices not found
286         if ( nbEdges > 1 ) {
287           RETURN_BAD_RESULT("2 bound vertices not found" );
288         } else {
289           VV2[ 1 ] = VV2[ 0 ];
290         }
291       }
292       list< TopoDS_Edge > edges1, edges2;
293       int nbE = FindFaceAssociation( face1, VV1, face2, VV2, edges1, edges2 );
294       if ( !nbE ) RETURN_BAD_RESULT("FindFaceAssociation() failed");
295       FixAssocByPropagation( nbE, edges1, edges2, theMesh1, theMesh2 );
296
297       list< TopoDS_Edge >::iterator eIt1 = edges1.begin();
298       list< TopoDS_Edge >::iterator eIt2 = edges2.begin();
299       for ( ; eIt1 != edges1.end(); ++eIt1, ++eIt2 )
300       {
301         InsertAssociation( *eIt1, *eIt2, theMap, bidirect);
302         VV1[0] = TopExp::FirstVertex( *eIt1, true );
303         VV2[0] = TopExp::FirstVertex( *eIt2, true );
304         InsertAssociation( VV1[0], VV2[0], theMap, bidirect);
305       }
306       InsertAssociation( theShape1, theShape2, theMap, bidirect );
307       return true;
308     }
309       // ----------------------------------------------------------------------
310     case TopAbs_SHELL: // TopAbs_SHELL, TopAbs_SOLID
311     case TopAbs_SOLID: {
312       // ----------------------------------------------------------------------
313       TopoDS_Vertex VV1[2], VV2[2];
314       // find a not closed edge of shape1 both vertices of which are associated
315       TopoDS_Edge edge1;
316       TopExp_Explorer exp ( theShape1, TopAbs_EDGE );
317       for ( ; VV2[ 1 ].IsNull() && exp.More(); exp.Next() ) {
318         edge1 = TopoDS::Edge( exp.Current() );
319         TopExp::Vertices( edge1 , VV1[0], VV1[1] );
320         if ( theMap.IsBound( VV1[0] )) {
321           VV2[ 0 ] = TopoDS::Vertex( theMap( VV1[0] ));
322           if ( theMap.IsBound( VV1[1] ) && !VV1[0].IsSame( VV1[1] ))
323             VV2[ 1 ] = TopoDS::Vertex( theMap( VV1[1] ));
324         }
325       }
326       if ( VV2[ 1 ].IsNull() ) // 2 bound vertices not found
327         RETURN_BAD_RESULT("2 bound vertices not found" );
328       TopoDS_Edge edge2 = GetEdgeByVertices( theMesh2, VV2[ 0 ], VV2[ 1 ]);
329       if ( edge2.IsNull() )
330         RETURN_BAD_RESULT("GetEdgeByVertices() failed");
331
332       // build map of edge to faces if shapes are not subshapes of main ones
333       bool isSubOfMain = false;
334       if ( SMESHDS_SubMesh * sm = theMesh1->GetMeshDS()->MeshElements( theShape1 ))
335         isSubOfMain = !sm->IsComplexSubmesh();
336       else
337         isSubOfMain = theMesh1->GetMeshDS()->ShapeToIndex( theShape1 );
338       TAncestorMap e2f1, e2f2;
339       const TAncestorMap& edgeToFace1 = isSubOfMain ? theMesh1->GetAncestorMap() : e2f1;
340       const TAncestorMap& edgeToFace2 = isSubOfMain ? theMesh2->GetAncestorMap() : e2f2;
341       if (!isSubOfMain) {
342         TopExp::MapShapesAndAncestors( theShape1, TopAbs_EDGE, TopAbs_FACE, e2f1 );
343         TopExp::MapShapesAndAncestors( theShape2, TopAbs_EDGE, TopAbs_FACE, e2f2 );
344         if ( !edgeToFace1.Contains( edge1 ))
345           RETURN_BAD_RESULT("edge1 does not belong to theShape1");
346         if ( !edgeToFace2.Contains( edge2 ))
347           RETURN_BAD_RESULT("edge2 does not belong to theShape2");
348       }
349       //
350       // Look for 2 corresponing faces:
351       //
352       TopoDS_Shape F1, F2;
353
354       // get a face sharing edge1 (F1)
355       TopoDS_Shape FF2[2];
356       TopTools_ListIteratorOfListOfShape ancestIt1( edgeToFace1.FindFromKey( edge1 ));
357       for ( ; F1.IsNull() && ancestIt1.More(); ancestIt1.Next() )
358         if ( ancestIt1.Value().ShapeType() == TopAbs_FACE )
359           F1 = ancestIt1.Value().Oriented( TopAbs_FORWARD );
360       if ( F1.IsNull() )
361         RETURN_BAD_RESULT(" Face1 not found");
362
363       // get 2 faces sharing edge2 (one of them is F2)
364       TopTools_ListIteratorOfListOfShape ancestIt2( edgeToFace2.FindFromKey( edge2 ));
365       for ( int i = 0; FF2[1].IsNull() && ancestIt2.More(); ancestIt2.Next() )
366         if ( ancestIt2.Value().ShapeType() == TopAbs_FACE )
367           FF2[ i++ ] = ancestIt2.Value().Oriented( TopAbs_FORWARD );
368
369       // get oriented edge1 and edge2 from F1 and FF2[0]
370       for ( exp.Init( F1, TopAbs_EDGE ); exp.More(); exp.Next() )
371         if ( edge1.IsSame( exp.Current() )) {
372           edge1 = TopoDS::Edge( exp.Current() );
373           break;
374         }
375       for ( exp.Init( FF2[ 0 ], TopAbs_EDGE ); exp.More(); exp.Next() )
376         if ( edge2.IsSame( exp.Current() )) {
377           edge2 = TopoDS::Edge( exp.Current() );
378           break;
379         }
380
381       // compare first vertices of edge1 and edge2
382       TopExp::Vertices( edge1, VV1[0], VV1[1], true );
383       TopExp::Vertices( edge2, VV2[0], VV2[1], true );
384       F2 = FF2[ 0 ]; // (F2 !)
385       if ( !VV1[ 0 ].IsSame( theMap( VV2[ 0 ]))) {
386         edge2.Reverse();
387         if ( FF2[ 1 ].IsNull() )
388           F2.Reverse();
389         else
390           F2 = FF2[ 1 ];
391       }
392
393       TopTools_MapOfShape boundEdges;
394
395       // association of face subshapes and neighbour faces
396       list< pair < TopoDS_Face, TopoDS_Edge > > FE1, FE2;
397       list< pair < TopoDS_Face, TopoDS_Edge > >::iterator fe1, fe2;
398       FE1.push_back( make_pair( TopoDS::Face( F1 ), edge1 ));
399       FE2.push_back( make_pair( TopoDS::Face( F2 ), edge2 ));
400       for ( fe1 = FE1.begin(), fe2 = FE2.begin(); fe1 != FE1.end(); ++fe1, ++fe2 )
401       {
402         const TopoDS_Face& face1 = fe1->first;
403         if ( theMap.IsBound( face1 ) ) continue;
404         const TopoDS_Face& face2 = fe2->first;
405         edge1 = fe1->second;
406         edge2 = fe2->second;
407         TopExp::Vertices( edge1, VV1[0], VV1[1], true );
408         TopExp::Vertices( edge2, VV2[0], VV2[1], true );
409         list< TopoDS_Edge > edges1, edges2;
410         int nbE = FindFaceAssociation( face1, VV1, face2, VV2, edges1, edges2 );
411         if ( !nbE ) RETURN_BAD_RESULT("FindFaceAssociation() failed");
412         InsertAssociation( face1, face2, theMap, bidirect); // assoc faces
413         MESSAGE("Assoc FACE " << theMesh1->GetMeshDS()->ShapeToIndex( face1 )<<
414                 " to "        << theMesh2->GetMeshDS()->ShapeToIndex( face2 ));
415         if ( nbE == 2 && (edge1.IsSame( edges1.front())) != (edge2.IsSame( edges2.front())))
416         {
417           Reverse( edges2, nbE );
418         }
419         list< TopoDS_Edge >::iterator eIt1 = edges1.begin();
420         list< TopoDS_Edge >::iterator eIt2 = edges2.begin();
421         for ( ; eIt1 != edges1.end(); ++eIt1, ++eIt2 )
422         {
423           if ( !boundEdges.Add( *eIt1 )) continue; // already associated
424           InsertAssociation( *eIt1, *eIt2, theMap, bidirect);  // assoc edges
425           MESSAGE("Assoc edge " << theMesh1->GetMeshDS()->ShapeToIndex( *eIt1 )<<
426                   " to "        << theMesh2->GetMeshDS()->ShapeToIndex( *eIt2 ));
427           VV1[0] = TopExp::FirstVertex( *eIt1, true );
428           VV2[0] = TopExp::FirstVertex( *eIt2, true );
429           InsertAssociation( VV1[0], VV2[0], theMap, bidirect); // assoc vertices
430           MESSAGE("Assoc vertex " << theMesh1->GetMeshDS()->ShapeToIndex( VV1[0] )<<
431                   " to "          << theMesh2->GetMeshDS()->ShapeToIndex( VV2[0] ));
432
433           // add adjacent faces to process
434           TopoDS_Face nextFace1 = GetNextFace( edgeToFace1, *eIt1, face1 );
435           TopoDS_Face nextFace2 = GetNextFace( edgeToFace2, *eIt2, face2 );
436           if ( !nextFace1.IsNull() && !nextFace2.IsNull() ) {
437             FE1.push_back( make_pair( nextFace1, *eIt1 ));
438             FE2.push_back( make_pair( nextFace2, *eIt2 ));
439           }
440         }
441       }
442       InsertAssociation( theShape1, theShape2, theMap, bidirect );
443       return true;
444     }
445       // ----------------------------------------------------------------------
446     case TopAbs_COMPOUND: { // GROUP
447       // ----------------------------------------------------------------------
448       // Maybe groups contain only one member
449       TopoDS_Iterator it1( theShape1 ), it2( theShape2 );
450       TopAbs_ShapeEnum memberType = it1.Value().ShapeType();
451       int nbMembers = Count( theShape1, memberType, true );
452       if ( nbMembers == 0 ) return true;
453       if ( nbMembers == 1 ) {
454         return FindSubShapeAssociation( it1.Value(), theMesh1, it2.Value(), theMesh2, theMap );
455       }
456       // Try to make shells of faces
457       //
458       BRep_Builder builder;
459       TopoDS_Shell shell1, shell2;
460       builder.MakeShell(shell1); builder.MakeShell(shell2);
461       if ( memberType == TopAbs_FACE ) {
462         // just add faces of groups to shells
463         for (; it1.More(); it1.Next(), it2.Next() )
464           builder.Add( shell1, it1.Value() ), builder.Add( shell2, it2.Value() );
465       }
466       else if ( memberType == TopAbs_EDGE ) {
467         // Try to add faces sharing more than one edge of a group or
468         // sharing all its vertices with the group
469         TopTools_IndexedMapOfShape groupVertices[2];
470         TopExp::MapShapes( theShape1, TopAbs_VERTEX, groupVertices[0]);
471         TopExp::MapShapes( theShape2, TopAbs_VERTEX, groupVertices[1]);
472         //
473         TopTools_MapOfShape groupEdges[2], addedFaces[2];
474         bool hasInitAssoc = (!theMap.IsEmpty()), initAssocOK = !hasInitAssoc;
475         for (; it1.More(); it1.Next(), it2.Next() ) {
476           groupEdges[0].Add( it1.Value() );
477           groupEdges[1].Add( it2.Value() );
478           if ( !initAssocOK ) {
479             // for shell association there must be an edge with both vertices bound
480             TopoDS_Vertex v1, v2;
481             TopExp::Vertices( TopoDS::Edge( it1.Value()), v1, v2 );
482             initAssocOK = ( theMap.IsBound( v1 ) && theMap.IsBound( v2 ));
483           }
484         }
485         for (int is2ndGroup = 0; initAssocOK && is2ndGroup < 2; ++is2ndGroup) {
486           const TopoDS_Shape& group = is2ndGroup ? theShape2: theShape1;
487           SMESH_Mesh*         mesh  = is2ndGroup ? theMesh2 : theMesh1;
488           TopoDS_Shell&       shell = is2ndGroup ? shell2   : shell1;
489           for ( TopoDS_Iterator it( group ); it.More(); it.Next() ) {
490             const TopoDS_Edge& edge = TopoDS::Edge( it.Value() );
491             TopoDS_Face face;
492             for ( int iF = 0; iF < 2; ++iF ) { // loop on 2 faces sharing edge
493               face = GetNextFace(mesh->GetAncestorMap(), edge, face);
494               if ( !face.IsNull() ) {
495                 int nbGroupEdges = 0;
496                 for ( TopExp_Explorer f( face, TopAbs_EDGE ); f.More(); f.Next())
497                   if ( groupEdges[ is2ndGroup ].Contains( f.Current() ))
498                     if ( ++nbGroupEdges > 1 )
499                       break;
500                 bool add = (nbGroupEdges > 1 || Count( face, TopAbs_EDGE, true ) == 1 );
501                 if ( !add ) {
502                   add = true;
503                   for ( TopExp_Explorer v( face, TopAbs_VERTEX ); add && v.More(); v.Next())
504                     add = groupVertices[ is2ndGroup ].Contains( v.Current() );
505                 }
506                 if ( add && addedFaces[ is2ndGroup ].Add( face ))
507                   builder.Add( shell, face );
508               }
509             }
510           }
511         }
512       } else {
513         RETURN_BAD_RESULT("Unexpected group type");
514       }
515       // Associate shells
516       //
517       int nbFaces1 = Count( shell1, TopAbs_FACE, 0 );
518       int nbFaces2 = Count( shell2, TopAbs_FACE, 0 );
519       if ( nbFaces1 != nbFaces2 )
520         RETURN_BAD_RESULT("Different nb of faces found for shells");
521       if ( nbFaces1 > 0 ) {
522         bool ok = false;
523         if ( nbFaces1 == 1 ) {
524           TopoDS_Shape F1 = TopoDS_Iterator( shell1 ).Value();
525           TopoDS_Shape F2 = TopoDS_Iterator( shell2 ).Value();
526           ok = FindSubShapeAssociation( F1, theMesh1, F2, theMesh2, theMap );
527         }
528         else {
529           ok = FindSubShapeAssociation(shell1, theMesh1, shell2, theMesh2, theMap );
530         }
531         // Check if all members are mapped 
532         if ( ok ) {
533           TopTools_MapOfShape boundMembers[2];
534           TopoDS_Iterator mIt;
535           for ( mIt.Initialize( theShape1 ); mIt.More(); mIt.Next())
536             if ( theMap.IsBound( mIt.Value() )) {
537               boundMembers[0].Add( mIt.Value() );
538               boundMembers[1].Add( theMap( mIt.Value() ));
539             }
540           if ( boundMembers[0].Extent() != nbMembers ) {
541             // make compounds of not bound members
542             TopoDS_Compound comp[2];
543             for ( int is2ndGroup = 0; is2ndGroup < 2; ++is2ndGroup ) {
544               builder.MakeCompound( comp[is2ndGroup] );
545               for ( mIt.Initialize( is2ndGroup ? theShape2:theShape1 ); mIt.More(); mIt.Next())
546                 if ( ! boundMembers[ is2ndGroup ].Contains( mIt.Value() ))
547                   builder.Add( comp[ is2ndGroup ], mIt.Value() );
548             }
549             // check if theMap contains initial association for the comp's
550             bool hasInitialAssoc = false;
551             if ( memberType == TopAbs_EDGE ) {
552               for ( TopExp_Explorer v( comp[0], TopAbs_VERTEX ); v.More(); v.Next())
553                 if ( theMap.IsBound( v.Current() )) {
554                   hasInitialAssoc = true;
555                   break;
556                 }
557             }
558             if ( hasInitialAssoc == bool( !theMap.IsEmpty() ))
559               ok = FindSubShapeAssociation( comp[0], theMesh1, comp[1], theMesh2, theMap );
560             else {
561               TShapeShapeMap tmpMap;
562               ok = FindSubShapeAssociation( comp[0], theMesh1, comp[1], theMesh2, tmpMap );
563               if ( ok ) {
564                 TopTools_DataMapIteratorOfDataMapOfShapeShape mapIt( tmpMap );
565                 for ( ; mapIt.More(); mapIt.Next() )
566                   theMap.Bind( mapIt.Key(), mapIt.Value());
567               }
568             }
569           }
570         }
571         return ok;
572       }
573       // Each edge of an edge group is shared by own faces
574       // ------------------------------------------------------------------
575       //
576       // map vertices to edges sharing them, avoid doubling edges in lists
577       TopTools_DataMapOfShapeListOfShape v2e[2];
578       for (int isFirst = 0; isFirst < 2; ++isFirst ) {
579         const TopoDS_Shape& group = isFirst ? theShape1 : theShape2;
580         TopTools_DataMapOfShapeListOfShape& veMap = v2e[ isFirst ? 0 : 1 ];
581         TopTools_MapOfShape addedEdges;
582         for ( TopExp_Explorer e( group, TopAbs_EDGE ); e.More(); e.Next() ) {
583           const TopoDS_Shape& edge = e.Current();
584           if ( addedEdges.Add( edge )) {
585             for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next()) {
586               const TopoDS_Shape& vertex = v.Current();
587               if ( !veMap.IsBound( vertex )) {
588                 TopTools_ListOfShape l;
589                 veMap.Bind( vertex, l );
590               }
591               veMap( vertex ).Append( edge );
592             }
593           }
594         }   
595       }
596       while ( !v2e[0].IsEmpty() )
597       {
598         // find a bound vertex
599         TopoDS_Vertex V[2];
600         TopTools_DataMapIteratorOfDataMapOfShapeListOfShape v2eIt( v2e[0] );
601         for ( ; v2eIt.More(); v2eIt.Next())
602           if ( theMap.IsBound( v2eIt.Key() )) {
603             V[0] = TopoDS::Vertex( v2eIt.Key() );
604             V[1] = TopoDS::Vertex( theMap( V[0] ));
605             break;
606           }
607         if ( V[0].IsNull() )
608           RETURN_BAD_RESULT("No more bound vertices");
609
610         while ( !V[0].IsNull() && v2e[0].IsBound( V[0] )) {
611           TopTools_ListOfShape& edges0 = v2e[0]( V[0] );
612           TopTools_ListOfShape& edges1 = v2e[1]( V[1] );
613           int nbE0 = edges0.Extent(), nbE1 = edges1.Extent();
614           if ( nbE0 != nbE1 )
615             RETURN_BAD_RESULT("Different nb of edges: "<< nbE0 << " != " << nbE1);
616
617           if ( nbE0 == 1 )
618           {
619             TopoDS_Edge e0 = TopoDS::Edge( edges0.First() );
620             TopoDS_Edge e1 = TopoDS::Edge( edges1.First() );
621             v2e[0].UnBind( V[0] );
622             v2e[1].UnBind( V[1] );
623             InsertAssociation( e0, e1, theMap, bidirect );
624             MESSAGE("Assoc edge " << theMesh1->GetMeshDS()->ShapeToIndex( e0 )<<
625                     " to "        << theMesh2->GetMeshDS()->ShapeToIndex( e1 ));
626             V[0] = GetNextVertex( e0, V[0] );
627             V[1] = GetNextVertex( e1, V[1] );
628             if ( !V[0].IsNull() ) {
629               InsertAssociation( V[0], V[1], theMap, bidirect );
630               MESSAGE("Assoc vertex " << theMesh1->GetMeshDS()->ShapeToIndex( V[0] )<<
631                       " to "          << theMesh2->GetMeshDS()->ShapeToIndex( V[1] ));
632             }
633           }
634           else if ( nbE0 == 2 )
635           {
636             // one of edges must have both ends bound
637             TopoDS_Vertex v0e0 = GetNextVertex( TopoDS::Edge( edges0.First() ), V[0] );
638             TopoDS_Vertex v1e0 = GetNextVertex( TopoDS::Edge( edges0.Last() ),  V[0] );
639             TopoDS_Vertex v0e1 = GetNextVertex( TopoDS::Edge( edges1.First() ), V[1] );
640             TopoDS_Vertex v1e1 = GetNextVertex( TopoDS::Edge( edges1.Last() ),  V[1] );
641             TopoDS_Shape e0b, e1b, e0n, e1n, v1b; // bound and not-bound
642             TopoDS_Vertex v0n, v1n;
643             if ( theMap.IsBound( v0e0 )) {
644               v0n = v1e0; e0b = edges0.First(); e0n = edges0.Last(); v1b = theMap( v0e0 );
645             } else if ( theMap.IsBound( v1e0 )) {
646               v0n = v0e0; e0n = edges0.First(); e0b = edges0.Last(); v1b = theMap( v1e0 );
647             } else {
648               RETURN_BAD_RESULT("None of vertices bound");
649             }
650             if ( v1b.IsSame( v1e1 )) {
651               v1n = v0e1; e1n = edges1.First(); e1b = edges1.Last();
652             } else {
653               v1n = v1e1; e1b = edges1.First(); e1n = edges1.Last();
654             }
655             InsertAssociation( e0b, e1b, theMap, bidirect );
656             InsertAssociation( e0n, e1n, theMap, bidirect );
657             InsertAssociation( v0n, v1n, theMap, bidirect );
658             MESSAGE("Assoc edge " << theMesh1->GetMeshDS()->ShapeToIndex( e0b )<<
659                     " to "        << theMesh2->GetMeshDS()->ShapeToIndex( e1b ));
660             MESSAGE("Assoc edge " << theMesh1->GetMeshDS()->ShapeToIndex( e0n )<<
661                     " to "        << theMesh2->GetMeshDS()->ShapeToIndex( e1n ));
662             MESSAGE("Assoc vertex " << theMesh1->GetMeshDS()->ShapeToIndex( v0n )<<
663                     " to "          << theMesh2->GetMeshDS()->ShapeToIndex( v1n ));
664             v2e[0].UnBind( V[0] );
665             v2e[1].UnBind( V[1] );
666             V[0] = v0n;
667             V[1] = v1n;
668           }
669           else {
670             RETURN_BAD_RESULT("Not implemented");
671           }
672         }
673       } //while ( !v2e[0].IsEmpty() )
674       return true;
675     }
676
677     default:
678       RETURN_BAD_RESULT("Unexpected shape type");
679
680     } // end switch by shape type
681   } // end case of available initial vertex association
682
683   //======================================================================
684   // NO INITIAL VERTEX ASSOCIATION
685   //======================================================================
686
687   switch ( theShape1.ShapeType() ) {
688
689   case TopAbs_EDGE: {
690     // ----------------------------------------------------------------------
691     TopoDS_Edge edge1 = TopoDS::Edge( theShape1 );
692     TopoDS_Edge edge2 = TopoDS::Edge( theShape2 );
693     if ( IsPropagationPossible( theMesh1, theMesh2 ))
694     {
695       TopoDS_Edge prpEdge = GetPropagationEdge( theMesh1, edge2, edge1 ).second;
696       if ( !prpEdge.IsNull() )
697       {
698         TopoDS_Vertex VV1[2], VV2[2];
699         TopExp::Vertices( edge1,   VV1[0], VV1[1], true );
700         TopExp::Vertices( prpEdge, VV2[0], VV2[1], true );
701         InsertAssociation( VV1[ 0 ], VV2[ 0 ], theMap, bidirect);
702         InsertAssociation( VV1[ 1 ], VV2[ 1 ], theMap, bidirect);
703         if ( VV1[0].IsSame( VV1[1] ) || // one of edges is closed
704              VV2[0].IsSame( VV2[1] ) )
705         {
706           InsertAssociation( edge1, prpEdge, theMap, bidirect); // insert with a proper orientation
707         }
708         InsertAssociation( theShape1, theShape2, theMap, bidirect );
709         return true; // done
710       }
711     }
712     if ( IsClosedEdge( edge1 ) && IsClosedEdge( edge2 ))
713     {
714       // TODO: find out a proper orientation (is it possible?)
715       InsertAssociation( edge1, edge2, theMap, bidirect); // insert with a proper orientation
716       InsertAssociation( TopExp::FirstVertex(edge1), TopExp::FirstVertex(edge2),
717                          theMap, bidirect);
718       InsertAssociation( theShape1, theShape2, theMap, bidirect );
719       return true; // done
720     }
721     break; // try by vertex closeness
722   }
723
724   case TopAbs_FACE: {
725     // ----------------------------------------------------------------------
726     if ( IsPropagationPossible( theMesh1, theMesh2 )) // try by propagation in one mesh
727     {
728       TopoDS_Face face1 = TopoDS::Face(theShape1);
729       TopoDS_Face face2 = TopoDS::Face(theShape2);
730       TopoDS_Edge edge1, edge2;
731       // get outer edge of theShape1
732       edge1 = TopoDS::Edge( OuterShape( face1, TopAbs_EDGE ));
733       // find out if any edge of face2 is a propagation edge of outer edge1
734       map<int,TopoDS_Edge> propag_edges; // use map to find the closest propagation edge
735       for ( TopExp_Explorer exp( face2, TopAbs_EDGE ); exp.More(); exp.Next() ) {
736         edge2 = TopoDS::Edge( exp.Current() );
737         pair<int,TopoDS_Edge> step_edge = GetPropagationEdge( theMesh1, edge2, edge1 );
738         if ( !step_edge.second.IsNull() ) { // propagation found
739           propag_edges.insert( step_edge );
740         }
741       }
742       if ( !propag_edges.empty() ) // propagation found
743       {
744         edge2 = propag_edges.begin()->second;
745         TopoDS_Vertex VV1[2], VV2[2];
746         TopExp::Vertices( edge1, VV1[0], VV1[1], true );
747         TopExp::Vertices( edge2, VV2[0], VV2[1], true );
748         list< TopoDS_Edge > edges1, edges2;
749         int nbE = FindFaceAssociation( face1, VV1, face2, VV2, edges1, edges2 );
750         if ( !nbE ) RETURN_BAD_RESULT("FindFaceAssociation() failed");
751         if ( nbE == 2 ) // only 2 edges
752         {
753           // take care of proper association of propagated edges
754           bool same1 = edge1.IsSame( edges1.front() );
755           bool same2 = edge2.IsSame( edges2.front() );
756           if ( same1 != same2 )
757             Reverse(edges2, nbE);
758         }
759         // store association
760         list< TopoDS_Edge >::iterator eIt1 = edges1.begin();
761         list< TopoDS_Edge >::iterator eIt2 = edges2.begin();
762         for ( ; eIt1 != edges1.end(); ++eIt1, ++eIt2 )
763         {
764           InsertAssociation( *eIt1, *eIt2, theMap, bidirect);
765           VV1[0] = TopExp::FirstVertex( *eIt1, true );
766           VV2[0] = TopExp::FirstVertex( *eIt2, true );
767           InsertAssociation( VV1[0], VV2[0], theMap, bidirect);
768         }
769         InsertAssociation( theShape1, theShape2, theMap, bidirect );
770         return true;
771       }
772     }
773     break; // try by vertex closeness
774   }
775   default:;
776   }
777
778   // Find association by closeness of vertices
779   // ------------------------------------------
780
781   TopTools_IndexedMapOfShape vMap1, vMap2;
782   TopExp::MapShapes( theShape1, TopAbs_VERTEX, vMap1 );
783   TopExp::MapShapes( theShape2, TopAbs_VERTEX, vMap2 );
784
785   if ( vMap1.Extent() != vMap2.Extent() )
786     RETURN_BAD_RESULT("Different nb of vertices");
787
788   if ( vMap1.Extent() == 1 ) {
789     InsertAssociation( vMap1(1), vMap2(1), theMap, bidirect);
790     if ( theShape1.ShapeType() == TopAbs_EDGE ) {
791       InsertAssociation( theShape1, theShape2, theMap, bidirect );
792       return true;
793     }
794     return FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap);
795   }
796
797   // Find transformation to make the shapes be of similar size at same location
798
799   Bnd_Box box[2];
800   for ( int i = 1; i <= vMap1.Extent(); ++i ) {
801     box[ 0 ].Add( BRep_Tool::Pnt ( TopoDS::Vertex( vMap1( i ))));
802     box[ 1 ].Add( BRep_Tool::Pnt ( TopoDS::Vertex( vMap2( i ))));
803   }
804
805   gp_Pnt gc[2]; // box center
806   double x0,y0,z0, x1,y1,z1;
807   box[0].Get( x0,y0,z0, x1,y1,z1 );
808   gc[0] = 0.5 * ( gp_XYZ( x0,y0,z0 ) + gp_XYZ( x1,y1,z1 ));
809   box[1].Get( x0,y0,z0, x1,y1,z1 );
810   gc[1] = 0.5 * ( gp_XYZ( x0,y0,z0 ) + gp_XYZ( x1,y1,z1 ));
811
812   // 1 -> 2
813   gp_Vec vec01( gc[0], gc[1] );
814   double scale = sqrt( box[1].SquareExtent() / box[0].SquareExtent() );
815
816   // Find 2 closest vertices
817
818   TopoDS_Vertex VV1[2], VV2[2];
819   // get 2 linked vertices of shape 1 not belonging to an inner wire of a face
820   TopoDS_Shape edge = theShape1;
821   TopExp_Explorer expF( theShape1, TopAbs_FACE ), expE;
822   if ( expF.More() ) {
823     for ( ; expF.More(); expF.Next() ) {
824       edge.Nullify();
825       TopoDS_Shape wire = OuterShape( TopoDS::Face( expF.Current() ), TopAbs_WIRE );
826       for ( expE.Init( wire, TopAbs_EDGE ); edge.IsNull() && expE.More(); expE.Next() )
827         if ( !IsClosedEdge( TopoDS::Edge( expE.Current() )))
828           edge = expE.Current();
829       if ( !edge.IsNull() )
830         break;
831     }
832   } else if (edge.ShapeType() != TopAbs_EDGE) { // no faces
833     edge.Nullify();
834     for ( expE.Init( theShape1, TopAbs_EDGE ); edge.IsNull() && expE.More(); expE.Next() )
835       if ( !IsClosedEdge( TopoDS::Edge( expE.Current() )))
836         edge = expE.Current();
837   }
838   if ( edge.IsNull() || edge.ShapeType() != TopAbs_EDGE )
839     RETURN_BAD_RESULT("Edge not found");
840
841   TopExp::Vertices( TopoDS::Edge( edge ), VV1[0], VV1[1]);
842   if ( VV1[0].IsSame( VV1[1] ))
843     RETURN_BAD_RESULT("Only closed edges");
844
845   // find vertices closest to 2 linked vertices of shape 1
846   for ( int i1 = 0; i1 < 2; ++i1 )
847   {
848     double dist2 = DBL_MAX;
849     gp_Pnt p1 = BRep_Tool::Pnt( VV1[ i1 ]);
850     p1.Translate( vec01 );
851     p1.Scale( gc[1], scale );
852     for ( int i2 = 1; i2 <= vMap2.Extent(); ++i2 )
853     {
854       TopoDS_Vertex V2 = TopoDS::Vertex( vMap2( i2 ));
855       gp_Pnt p2 = BRep_Tool::Pnt ( V2 );
856       double d2 = p1.SquareDistance( p2 );
857       if ( d2 < dist2 && !V2.IsSame( VV2[ 0 ])) {
858         VV2[ i1 ] = V2; dist2 = d2;
859       }
860     }
861   }
862
863   InsertAssociation( VV1[ 0 ], VV2[ 0 ], theMap, bidirect);
864   InsertAssociation( VV1[ 1 ], VV2[ 1 ], theMap, bidirect);
865   MESSAGE("Initial assoc VERT " << theMesh1->GetMeshDS()->ShapeToIndex( VV1[ 0 ] )<<
866           " to "                << theMesh2->GetMeshDS()->ShapeToIndex( VV2[ 0 ] )<<
867           "\nand         VERT " << theMesh1->GetMeshDS()->ShapeToIndex( VV1[ 1 ] )<<
868           " to "                << theMesh2->GetMeshDS()->ShapeToIndex( VV2[ 1 ] ));
869   if ( theShape1.ShapeType() == TopAbs_EDGE ) {
870     InsertAssociation( theShape1, theShape2, theMap, bidirect );
871     return true;
872   }
873
874   return FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap );
875 }
876
877 //================================================================================
878 /*!
879  * \brief Find association of edges of faces
880  * \param face1 - face 1
881  * \param VV1 - vertices of face 1
882  * \param face2 - face 2
883  * \param VV2 - vertices of face 2 associated with oned of face 1
884  * \param edges1 - out list of edges of face 1
885  * \param edges2 - out list of edges of face 2
886  * \retval int - nb of edges in an outer wire in a success case, else zero
887  */
888 //================================================================================
889
890 int StdMeshers_ProjectionUtils::FindFaceAssociation(const TopoDS_Face& face1,
891                                                     TopoDS_Vertex      VV1[2],
892                                                     const TopoDS_Face& face2,
893                                                     TopoDS_Vertex      VV2[2],
894                                                     list< TopoDS_Edge > & edges1,
895                                                     list< TopoDS_Edge > & edges2)
896 {
897   edges1.clear();
898   edges2.clear();
899
900   list< int > nbVInW1, nbVInW2;
901   if ( SMESH_Block::GetOrderedEdges( face1, VV1[0], edges1, nbVInW1) !=
902        SMESH_Block::GetOrderedEdges( face2, VV2[0], edges2, nbVInW2) )
903     RETURN_BAD_RESULT("Different number of wires in faces ");
904
905   if ( nbVInW1.front() != nbVInW2.front() )
906     RETURN_BAD_RESULT("Different number of edges in faces: " <<
907                       nbVInW1.front() << " != " << nbVInW2.front());
908
909   // Define if we need to reverse one of wires to make edges in lists match each other
910
911   bool reverse = false;
912
913   list< TopoDS_Edge >::iterator eBackIt;
914   if ( !VV1[1].IsSame( TopExp::LastVertex( edges1.front(), true ))) {
915     reverse = true;
916     eBackIt = --edges1.end();
917     // check if the second vertex belongs to the first or last edge in the wire
918     if ( !VV1[1].IsSame( TopExp::FirstVertex( *eBackIt, true ))) {
919       bool KO = true; // belongs to none
920       if ( nbVInW1.size() > 1 ) { // several wires
921         eBackIt = edges1.begin();
922         for ( int i = 1; i < nbVInW1.front(); ++i ) ++eBackIt;
923         KO = !VV1[1].IsSame( TopExp::FirstVertex( *eBackIt, true ));
924       }
925       if ( KO )
926         RETURN_BAD_RESULT("GetOrderedEdges() failed");
927     }
928   }
929   eBackIt = --edges2.end();
930   if ( !VV2[1].IsSame( TopExp::LastVertex( edges2.front(), true ))) {
931     reverse = !reverse;
932     // check if the second vertex belongs to the first or last edge in the wire
933     if ( !VV2[1].IsSame( TopExp::FirstVertex( *eBackIt, true ))) {
934       bool KO = true; // belongs to none
935       if ( nbVInW2.size() > 1 ) { // several wires
936         eBackIt = edges2.begin();
937         for ( int i = 1; i < nbVInW2.front(); ++i ) ++eBackIt;
938         KO = !VV2[1].IsSame( TopExp::FirstVertex( *eBackIt, true ));
939       }
940       if ( KO )
941         RETURN_BAD_RESULT("GetOrderedEdges() failed");
942     }
943   }
944   if ( reverse )
945   {
946     Reverse( edges2 , nbVInW2.front());
947     if (( VV1[1].IsSame( TopExp::LastVertex( edges1.front(), true ))) !=
948         ( VV2[1].IsSame( TopExp::LastVertex( edges2.front(), true ))))
949       RETURN_BAD_RESULT("GetOrderedEdges() failed");
950   }
951   return nbVInW2.front();
952 }
953
954 //=======================================================================
955 //function : InitVertexAssociation
956 //purpose  : 
957 //=======================================================================
958
959 void StdMeshers_ProjectionUtils::InitVertexAssociation( const SMESH_Hypothesis* theHyp,
960                                                         TShapeShapeMap &        theAssociationMap,
961                                                         const TopoDS_Shape&     theTargetShape)
962 {
963   string hypName = theHyp->GetName();
964   if ( hypName == "ProjectionSource1D" ) {
965     const StdMeshers_ProjectionSource1D * hyp =
966       static_cast<const StdMeshers_ProjectionSource1D*>( theHyp );
967     if ( hyp->HasVertexAssociation() )
968       InsertAssociation( hyp->GetSourceVertex(),hyp->GetTargetVertex(),theAssociationMap);
969   }
970   else if ( hypName == "ProjectionSource2D" ) {
971     const StdMeshers_ProjectionSource2D * hyp =
972       static_cast<const StdMeshers_ProjectionSource2D*>( theHyp );
973     if ( hyp->HasVertexAssociation() ) {
974       InsertAssociation( hyp->GetSourceVertex(1),hyp->GetTargetVertex(1),theAssociationMap);
975       InsertAssociation( hyp->GetSourceVertex(2),hyp->GetTargetVertex(2),theAssociationMap);
976     }
977   }
978   else if ( hypName == "ProjectionSource3D" ) {
979     const StdMeshers_ProjectionSource3D * hyp =
980       static_cast<const StdMeshers_ProjectionSource3D*>( theHyp );
981     if ( hyp->HasVertexAssociation() ) {
982       InsertAssociation( hyp->GetSourceVertex(1),hyp->GetTargetVertex(1),theAssociationMap);
983       InsertAssociation( hyp->GetSourceVertex(2),hyp->GetTargetVertex(2),theAssociationMap);
984     }
985   }
986 }
987
988 //=======================================================================
989 /*!
990  * \brief Inserts association theShape1 <-> theShape2 to TShapeShapeMap
991  * \param theShape1 - shape 1
992  * \param theShape2 - shape 2
993  * \param theAssociationMap - association map 
994  * \retval bool - true if there was no association for these shapes before
995  */
996 //=======================================================================
997
998 bool StdMeshers_ProjectionUtils::InsertAssociation( const TopoDS_Shape& theShape1,
999                                                     const TopoDS_Shape& theShape2,
1000                                                     TShapeShapeMap &    theAssociationMap,
1001                                                     const bool          theBidirectional)
1002 {
1003   if ( !theShape1.IsNull() && !theShape2.IsNull() ) {
1004     SHOW_VERTEX(theShape1,"Assoc ");
1005     SHOW_VERTEX(theShape2," to ");
1006     bool isNew = ( theAssociationMap.Bind( theShape1, theShape2 ));
1007     if ( theBidirectional )
1008       theAssociationMap.Bind( theShape2, theShape1 );
1009     return isNew;
1010   }
1011   else {
1012     throw SALOME_Exception("StdMeshers_ProjectionUtils: attempt to associate NULL shape");
1013   }
1014   return false;
1015 }
1016
1017 //=======================================================================
1018 //function : IsSubShape
1019 //purpose  : 
1020 //=======================================================================
1021
1022 bool StdMeshers_ProjectionUtils::IsSubShape( const TopoDS_Shape& shape,
1023                                              SMESH_Mesh*         aMesh )
1024 {
1025   if ( shape.IsNull() || !aMesh )
1026     return false;
1027   return
1028     aMesh->GetMeshDS()->ShapeToIndex( shape ) ||
1029     // PAL16202
1030     shape.ShapeType() == TopAbs_COMPOUND && aMesh->GetMeshDS()->IsGroupOfSubShapes( shape );
1031 }
1032
1033 //=======================================================================
1034 //function : IsSubShape
1035 //purpose  : 
1036 //=======================================================================
1037
1038 bool StdMeshers_ProjectionUtils::IsSubShape( const TopoDS_Shape& shape,
1039                                              const TopoDS_Shape& mainShape )
1040 {
1041   if ( !shape.IsNull() && !mainShape.IsNull() )
1042   {
1043     for ( TopExp_Explorer exp( mainShape, shape.ShapeType());
1044           exp.More();
1045           exp.Next() )
1046       if ( shape.IsSame( exp.Current() ))
1047         return true;
1048   }
1049   SCRUTE((shape.IsNull()));
1050   SCRUTE((mainShape.IsNull()));
1051   return false;
1052 }
1053
1054
1055 //=======================================================================
1056 /*!
1057  * \brief Finds an edge by its vertices in a main shape of the mesh
1058  * \param aMesh - the mesh
1059  * \param V1 - vertex 1
1060  * \param V2 - vertex 2
1061  * \retval TopoDS_Edge - found edge
1062  */
1063 //=======================================================================
1064
1065 TopoDS_Edge StdMeshers_ProjectionUtils::GetEdgeByVertices( SMESH_Mesh*          theMesh,
1066                                                            const TopoDS_Vertex& theV1,
1067                                                            const TopoDS_Vertex& theV2)
1068 {
1069   if ( theMesh && !theV1.IsNull() && !theV2.IsNull() )
1070   {
1071     TopTools_ListIteratorOfListOfShape ancestorIt( theMesh->GetAncestors( theV1 ));
1072     for ( ; ancestorIt.More(); ancestorIt.Next() )
1073       if ( ancestorIt.Value().ShapeType() == TopAbs_EDGE )
1074         for ( TopExp_Explorer expV ( ancestorIt.Value(), TopAbs_VERTEX );
1075               expV.More();
1076               expV.Next() )
1077           if ( theV2.IsSame( expV.Current() ))
1078             return TopoDS::Edge( ancestorIt.Value() );
1079   }
1080   return TopoDS_Edge();
1081 }
1082
1083 //================================================================================
1084 /*!
1085  * \brief Return another face sharing an edge
1086  * \param edgeToFaces - data map of descendants to ancestors
1087  * \param edge - edge
1088  * \param face - face
1089  * \retval TopoDS_Face - found face
1090  */
1091 //================================================================================
1092
1093 TopoDS_Face StdMeshers_ProjectionUtils::GetNextFace( const TAncestorMap& edgeToFaces,
1094                                                      const TopoDS_Edge&  edge,
1095                                                      const TopoDS_Face&  face)
1096 {
1097 //   if ( !edge.IsNull() && !face.IsNull() && edgeToFaces.Contains( edge ))
1098   if ( !edge.IsNull() && edgeToFaces.Contains( edge )) // PAL16202
1099   {
1100     TopTools_ListIteratorOfListOfShape ancestorIt( edgeToFaces.FindFromKey( edge ));
1101     for ( ; ancestorIt.More(); ancestorIt.Next() )
1102       if ( ancestorIt.Value().ShapeType() == TopAbs_FACE &&
1103            !face.IsSame( ancestorIt.Value() ))
1104         return TopoDS::Face( ancestorIt.Value() );
1105   }
1106   return TopoDS_Face();
1107 }
1108
1109 //================================================================================
1110 /*!
1111  * \brief Return other vertex of an edge
1112  */
1113 //================================================================================
1114
1115 TopoDS_Vertex StdMeshers_ProjectionUtils::GetNextVertex(const TopoDS_Edge&   edge,
1116                                                         const TopoDS_Vertex& vertex)
1117 {
1118   TopoDS_Vertex vF,vL;
1119   TopExp::Vertices(edge,vF,vL);
1120   if ( vF.IsSame( vL ))
1121     return TopoDS_Vertex();
1122   return vertex.IsSame( vF ) ? vL : vF; 
1123 }
1124
1125 //================================================================================
1126 /*!
1127  * \brief Return a propagation edge
1128  * \param aMesh - mesh
1129  * \param theEdge - edge to find by propagation
1130  * \param fromEdge - start edge for propagation
1131  * \retval pair<int,TopoDS_Edge> - propagation step and found edge
1132  */
1133 //================================================================================
1134
1135 pair<int,TopoDS_Edge>
1136 StdMeshers_ProjectionUtils::GetPropagationEdge( SMESH_Mesh*        aMesh,
1137                                                 const TopoDS_Edge& theEdge,
1138                                                 const TopoDS_Edge& fromEdge)
1139 {
1140   SMESH_IndexedMapOfShape aChain;
1141   int step = 0;
1142
1143   // List of edges, added to chain on the previous cycle pass
1144   TopTools_ListOfShape listPrevEdges;
1145   listPrevEdges.Append(fromEdge);
1146
1147   // Collect all edges pass by pass
1148   while (listPrevEdges.Extent() > 0) {
1149     step++;
1150     // List of edges, added to chain on this cycle pass
1151     TopTools_ListOfShape listCurEdges;
1152
1153     // Find the next portion of edges
1154     TopTools_ListIteratorOfListOfShape itE (listPrevEdges);
1155     for (; itE.More(); itE.Next()) {
1156       TopoDS_Shape anE = itE.Value();
1157
1158       // Iterate on faces, having edge <anE>
1159       TopTools_ListIteratorOfListOfShape itA (aMesh->GetAncestors(anE));
1160       for (; itA.More(); itA.Next()) {
1161         TopoDS_Shape aW = itA.Value();
1162
1163         // There are objects of different type among the ancestors of edge
1164         if (aW.ShapeType() == TopAbs_WIRE) {
1165           TopoDS_Shape anOppE;
1166
1167           BRepTools_WireExplorer aWE (TopoDS::Wire(aW));
1168           Standard_Integer nb = 1, found = 0;
1169           TopTools_Array1OfShape anEdges (1,4);
1170           for (; aWE.More(); aWE.Next(), nb++) {
1171             if (nb > 4) {
1172               found = 0;
1173               break;
1174             }
1175             anEdges(nb) = aWE.Current();
1176             if (anEdges(nb).IsSame(anE)) found = nb;
1177           }
1178
1179           if (nb == 5 && found > 0) {
1180             // Quadrangle face found, get an opposite edge
1181             Standard_Integer opp = found + 2;
1182             if (opp > 4) opp -= 4;
1183             anOppE = anEdges(opp);
1184
1185             // add anOppE to aChain if ...
1186             if (!aChain.Contains(anOppE)) { // ... anOppE is not in aChain
1187               // Add found edge to the chain oriented so that to
1188               // have it co-directed with a forward MainEdge
1189               TopAbs_Orientation ori = anE.Orientation();
1190               if ( anEdges(opp).Orientation() == anEdges(found).Orientation() )
1191                 ori = TopAbs::Reverse( ori );
1192               anOppE.Orientation( ori );
1193               if ( anOppE.IsSame( theEdge ))
1194                 return make_pair( step, TopoDS::Edge( anOppE ));
1195               aChain.Add(anOppE);
1196               listCurEdges.Append(anOppE);
1197             }
1198           } // if (nb == 5 && found > 0)
1199         } // if (aF.ShapeType() == TopAbs_WIRE)
1200       } // for (; itF.More(); itF.Next())
1201     } // for (; itE.More(); itE.Next())
1202
1203     listPrevEdges = listCurEdges;
1204   } // while (listPrevEdges.Extent() > 0)
1205
1206   return make_pair( INT_MAX, TopoDS_Edge());
1207 }
1208
1209 //================================================================================
1210   /*!
1211    * \brief Find corresponding nodes on two faces
1212     * \param face1 - the first face
1213     * \param mesh1 - mesh containing elements on the first face
1214     * \param face2 - the second face
1215     * \param mesh2 - mesh containing elements on the second face
1216     * \param assocMap - map associating subshapes of the faces
1217     * \param node1To2Map - map containing found matching nodes
1218     * \retval bool - is a success
1219    */
1220 //================================================================================
1221
1222 bool StdMeshers_ProjectionUtils::
1223 FindMatchingNodesOnFaces( const TopoDS_Face&     face1,
1224                           SMESH_Mesh*            mesh1,
1225                           const TopoDS_Face&     face2,
1226                           SMESH_Mesh*            mesh2,
1227                           const TShapeShapeMap & assocMap,
1228                           TNodeNodeMap &         node1To2Map)
1229 {
1230   SMESHDS_Mesh* meshDS1 = mesh1->GetMeshDS();
1231   SMESHDS_Mesh* meshDS2 = mesh2->GetMeshDS();
1232   
1233   SMESH_MesherHelper helper1( *mesh1 );
1234   SMESH_MesherHelper helper2( *mesh2 );
1235
1236   // Get corresponding submeshes and roughly check match of meshes
1237
1238   SMESHDS_SubMesh * SM2 = meshDS2->MeshElements( face2 );
1239   SMESHDS_SubMesh * SM1 = meshDS1->MeshElements( face1 );
1240   if ( !SM2 || !SM1 )
1241     RETURN_BAD_RESULT("Empty submeshes");
1242   if ( SM2->NbNodes()    != SM1->NbNodes() ||
1243        SM2->NbElements() != SM1->NbElements() )
1244     RETURN_BAD_RESULT("Different meshes on corresponding faces "
1245                       << meshDS1->ShapeToIndex( face1 ) << " and "
1246                       << meshDS2->ShapeToIndex( face2 ));
1247   if ( SM2->NbElements() == 0 )
1248     RETURN_BAD_RESULT("Empty submeshes");
1249
1250   helper1.SetSubShape( face1 );
1251   helper2.SetSubShape( face2 );
1252   if ( helper1.HasSeam() != helper2.HasSeam() )
1253     RETURN_BAD_RESULT("Different faces' geometry");
1254
1255   // Data to call SMESH_MeshEditor::FindMatchingNodes():
1256
1257   // 1. Nodes of corresponding links:
1258
1259   // get 2 matching edges, try to find not seam ones
1260   TopoDS_Edge edge1, edge2, seam1, seam2;
1261   TopExp_Explorer eE( OuterShape( face2, TopAbs_WIRE ), TopAbs_EDGE );
1262   do {
1263     // edge 2
1264     TopoDS_Edge e2 = TopoDS::Edge( eE.Current() );
1265     eE.Next();
1266     // edge 1
1267     if ( !assocMap.IsBound( e2 ))
1268       RETURN_BAD_RESULT("Association not found for edge " << meshDS2->ShapeToIndex( e2 ));
1269     TopoDS_Edge e1 = TopoDS::Edge( assocMap( e2 ));
1270     if ( !IsSubShape( e1, face1 ))
1271       RETURN_BAD_RESULT("Wrong association, edge " << meshDS1->ShapeToIndex( e1 ) <<
1272                         " isn't a subshape of face " << meshDS1->ShapeToIndex( face1 ));
1273     // check that there are nodes on edges
1274     SMESHDS_SubMesh * eSM1 = meshDS1->MeshElements( e1 );
1275     SMESHDS_SubMesh * eSM2 = meshDS2->MeshElements( e2 );
1276     bool nodesOnEdges = ( eSM1 && eSM2 && eSM1->NbNodes() && eSM2->NbNodes() );
1277     // check that the nodes on edges belong to faces
1278     bool nodesOfFaces = false;
1279     if ( nodesOnEdges ) {
1280       const SMDS_MeshNode* n1 = eSM1->GetNodes()->next();
1281       const SMDS_MeshNode* n2 = eSM2->GetNodes()->next();
1282       nodesOfFaces = ( n1->GetInverseElementIterator(SMDSAbs_Face)->more() &&
1283                        n2->GetInverseElementIterator(SMDSAbs_Face)->more() );
1284     }
1285     if ( nodesOfFaces )
1286     {
1287       if ( BRep_Tool::IsClosed( e2, face2 )) {
1288         seam1 = e1; seam2 = e2;
1289       }
1290       else {
1291         edge1 = e1; edge2 = e2;
1292       }
1293     }
1294   } while ( edge2.IsNull() && eE.More() );
1295   //
1296   if ( edge2.IsNull() ) {
1297     edge1 = seam1; edge2 = seam2;
1298   }
1299   if ( edge2.IsNull() ) RETURN_BAD_RESULT("No matching edges with nodes found");
1300
1301   // get 2 matching vertices
1302   TopoDS_Vertex V2 = TopExp::FirstVertex( TopoDS::Edge( edge2 ));
1303   if ( !assocMap.IsBound( V2 ))
1304     RETURN_BAD_RESULT("Association not found for vertex " << meshDS2->ShapeToIndex( V2 ));
1305   TopoDS_Vertex V1 = TopoDS::Vertex( assocMap( V2 ));
1306
1307   // nodes on vertices
1308   const SMDS_MeshNode* vNode1 = SMESH_Algo::VertexNode( V1, meshDS1 );
1309   const SMDS_MeshNode* vNode2 = SMESH_Algo::VertexNode( V2, meshDS2 );
1310   if ( !vNode1 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS1->ShapeToIndex( V1 ));
1311   if ( !vNode2 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS2->ShapeToIndex( V2 ));
1312
1313   // nodes on edges linked with nodes on vertices
1314   const SMDS_MeshNode* nullNode = 0;
1315   vector< const SMDS_MeshNode*> eNode1( 2, nullNode );
1316   vector< const SMDS_MeshNode*> eNode2( 2, nullNode );
1317   int nbNodeToGet = 1;
1318   if ( IsClosedEdge( edge1 ) || IsClosedEdge( edge2 ) )
1319     nbNodeToGet = 2;
1320   for ( int is2 = 0; is2 < 2; ++is2 )
1321   {
1322     TopoDS_Edge &     edge  = is2 ? edge2 : edge1;
1323     SMESHDS_Mesh *    smDS  = is2 ? meshDS2 : meshDS1;
1324     SMESHDS_SubMesh* edgeSM = smDS->MeshElements( edge );
1325     // nodes linked with ones on vertices
1326     const SMDS_MeshNode*           vNode = is2 ? vNode2 : vNode1;
1327     vector< const SMDS_MeshNode*>& eNode = is2 ? eNode2 : eNode1;
1328     int nbGotNode = 0;
1329     SMDS_ElemIteratorPtr vElem = vNode->GetInverseElementIterator();
1330     while ( vElem->more() && nbGotNode != nbNodeToGet ) {
1331       const SMDS_MeshElement* elem = vElem->next();
1332       if ( elem->GetType() == SMDSAbs_Edge && edgeSM->Contains( elem ))
1333         eNode[ nbGotNode++ ] = 
1334           ( elem->GetNode(0) == vNode ) ? elem->GetNode(1) : elem->GetNode(0);
1335     }
1336     if ( nbGotNode > 1 ) // sort found nodes by param on edge
1337     {
1338       SMESH_MesherHelper* helper = is2 ? &helper2 : &helper1;
1339       double u0 = helper->GetNodeU( edge, eNode[ 0 ]);
1340       double u1 = helper->GetNodeU( edge, eNode[ 1 ]);
1341       if ( u0 > u1 ) std::swap( eNode[ 0 ], eNode[ 1 ]);
1342     }
1343     if ( nbGotNode == 0 )
1344       RETURN_BAD_RESULT("Found no nodes on edge " << smDS->ShapeToIndex( edge ) <<
1345                         " linked to " << vNode );
1346   }
1347
1348   // 2. face sets
1349
1350   set<const SMDS_MeshElement*> Elems1, Elems2;
1351   for ( int is2 = 0; is2 < 2; ++is2 )
1352   {
1353     set<const SMDS_MeshElement*> & elems = is2 ? Elems2 : Elems1;
1354     SMESHDS_SubMesh*                  sm = is2 ? SM2 : SM1;
1355     SMESH_MesherHelper*           helper = is2 ? &helper2 : &helper1;
1356     const TopoDS_Face &             face = is2 ? face2 : face1;
1357     SMDS_ElemIteratorPtr eIt = sm->GetElements();
1358
1359     if ( !helper->IsSeamShape( is2 ? edge2 : edge1 ))
1360     {
1361       while ( eIt->more() ) elems.insert( eIt->next() );
1362     }
1363     else
1364     {
1365       // the only suitable edge is seam, i.e. it is a sphere.
1366       // FindMatchingNodes() will not know which way to go from any edge.
1367       // So we ignore all faces having nodes on edges or vertices except
1368       // one of faces sharing current start nodes
1369
1370       // find a face to keep
1371       const SMDS_MeshElement* faceToKeep = 0;
1372       const SMDS_MeshNode* vNode = is2 ? vNode2 : vNode1;
1373       const SMDS_MeshNode* eNode = is2 ? eNode2[0] : eNode1[0];
1374       TIDSortedElemSet inSet, notInSet;
1375
1376       const SMDS_MeshElement* f1 =
1377         SMESH_MeshEditor::FindFaceInSet( vNode, eNode, inSet, notInSet );
1378       if ( !f1 ) RETURN_BAD_RESULT("The first face on seam not found");
1379       notInSet.insert( f1 );
1380
1381       const SMDS_MeshElement* f2 =
1382         SMESH_MeshEditor::FindFaceInSet( vNode, eNode, inSet, notInSet );
1383       if ( !f2 ) RETURN_BAD_RESULT("The second face on seam not found");
1384
1385       // select a face with less UV of vNode
1386       const SMDS_MeshNode* notSeamNode[2] = {0, 0};
1387       for ( int iF = 0; iF < 2; ++iF ) {
1388         const SMDS_MeshElement* f = ( iF ? f2 : f1 );
1389         for ( int i = 0; !notSeamNode[ iF ] && i < f->NbNodes(); ++i ) {
1390           const SMDS_MeshNode* node = f->GetNode( i );
1391           if ( !helper->IsSeamShape( node->GetPosition()->GetShapeId() ))
1392             notSeamNode[ iF ] = node;
1393         }
1394       }
1395       gp_Pnt2d uv1 = helper->GetNodeUV( face, vNode, notSeamNode[0] );
1396       gp_Pnt2d uv2 = helper->GetNodeUV( face, vNode, notSeamNode[1] );
1397       if ( uv1.X() + uv1.Y() > uv2.X() + uv2.Y() )
1398         faceToKeep = f2;
1399       else
1400         faceToKeep = f1;
1401
1402       // fill elem set
1403       elems.insert( faceToKeep );
1404       while ( eIt->more() ) {
1405         const SMDS_MeshElement* f = eIt->next();
1406         int nbNodes = f->NbNodes();
1407         if ( f->IsQuadratic() )
1408           nbNodes /= 2;
1409         bool onBnd = false;
1410         for ( int i = 0; !onBnd && i < nbNodes; ++i ) {
1411           const SMDS_MeshNode* node = f->GetNode( i );
1412           onBnd = ( node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE);
1413         }
1414         if ( !onBnd )
1415           elems.insert( f );
1416       }
1417       // add also faces adjacent to faceToKeep
1418       int nbNodes = faceToKeep->NbNodes();
1419       if ( faceToKeep->IsQuadratic() ) nbNodes /= 2;
1420       notInSet.insert( f1 );
1421       notInSet.insert( f2 );
1422       for ( int i = 0; i < nbNodes; ++i ) {
1423         const SMDS_MeshNode* n1 = faceToKeep->GetNode( i );
1424         const SMDS_MeshNode* n2 = faceToKeep->GetNode( i+1 );
1425         f1 = SMESH_MeshEditor::FindFaceInSet( n1, n2, inSet, notInSet );
1426         if ( f1 )
1427           elems.insert( f1 );
1428       }
1429     } // case on a sphere
1430   } // loop on 2 faces
1431
1432   //  int quadFactor = (*Elems1.begin())->IsQuadratic() ? 2 : 1;
1433
1434   node1To2Map.clear();
1435   int res = SMESH_MeshEditor::FindMatchingNodes( Elems1, Elems2,
1436                                                  vNode1, vNode2,
1437                                                  eNode1[0], eNode2[0],
1438                                                  node1To2Map);
1439   if ( res != SMESH_MeshEditor::SEW_OK )
1440     RETURN_BAD_RESULT("FindMatchingNodes() result " << res );
1441
1442   // On a sphere, add matching nodes on the edge
1443
1444   if ( helper1.IsSeamShape( edge1 ))
1445   {
1446     // sort nodes on edges by param on edge
1447     map< double, const SMDS_MeshNode* > u2nodesMaps[2];
1448     for ( int is2 = 0; is2 < 2; ++is2 )
1449     {
1450       TopoDS_Edge &     edge  = is2 ? edge2 : edge1;
1451       SMESHDS_Mesh *    smDS  = is2 ? meshDS2 : meshDS1;
1452       SMESHDS_SubMesh* edgeSM = smDS->MeshElements( edge );
1453       map< double, const SMDS_MeshNode* > & pos2nodes = u2nodesMaps[ is2 ];
1454
1455       SMDS_NodeIteratorPtr nIt = edgeSM->GetNodes();
1456       while ( nIt->more() ) {
1457         const SMDS_MeshNode* node = nIt->next();
1458         const SMDS_EdgePosition* pos =
1459           static_cast<const SMDS_EdgePosition*>(node->GetPosition().get());
1460         pos2nodes.insert( make_pair( pos->GetUParameter(), node ));
1461       }
1462       if ( pos2nodes.size() != edgeSM->NbNodes() )
1463         RETURN_BAD_RESULT("Equal params of nodes on edge "
1464                           << smDS->ShapeToIndex( edge ) << " of face " << is2 );
1465     }
1466     if ( u2nodesMaps[0].size() != u2nodesMaps[1].size() )
1467       RETURN_BAD_RESULT("Different nb of new nodes on edges or wrong params");
1468
1469     // compare edge orientation
1470     double u1 = helper1.GetNodeU( edge1, vNode1 );
1471     double u2 = helper2.GetNodeU( edge2, vNode2 );
1472     bool isFirst1 = ( u1 < u2nodesMaps[0].begin()->first );
1473     bool isFirst2 = ( u2 < u2nodesMaps[1].begin()->first );
1474     bool reverse ( isFirst1 != isFirst2 );
1475
1476     // associate matching nodes
1477     map< double, const SMDS_MeshNode* >::iterator u_Node1, u_Node2, end1;
1478     map< double, const SMDS_MeshNode* >::reverse_iterator uR_Node2;
1479     u_Node1 = u2nodesMaps[0].begin();
1480     u_Node2 = u2nodesMaps[1].begin();
1481     uR_Node2 = u2nodesMaps[1].rbegin();
1482     end1 = u2nodesMaps[0].end();
1483     for ( ; u_Node1 != end1; ++u_Node1 ) {
1484       const SMDS_MeshNode* n1 = u_Node1->second;
1485       const SMDS_MeshNode* n2 = ( reverse ? (uR_Node2++)->second : (u_Node2++)->second );
1486       node1To2Map.insert( make_pair( n1, n2 ));
1487     }
1488
1489     // associate matching nodes on the last vertices
1490     V2 = TopExp::LastVertex( TopoDS::Edge( edge2 ));
1491     if ( !assocMap.IsBound( V2 ))
1492       RETURN_BAD_RESULT("Association not found for vertex " << meshDS2->ShapeToIndex( V2 ));
1493     V1 = TopoDS::Vertex( assocMap( V2 ));
1494     vNode1 = SMESH_Algo::VertexNode( V1, meshDS1 );
1495     vNode2 = SMESH_Algo::VertexNode( V2, meshDS2 );
1496     if ( !vNode1 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS1->ShapeToIndex( V1 ));
1497     if ( !vNode2 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS2->ShapeToIndex( V2 ));
1498     node1To2Map.insert( make_pair( vNode1, vNode2 ));
1499   }
1500
1501 // don't know why this condition is usually true :(
1502 //   if ( node1To2Map.size() * quadFactor < SM1->NbNodes() )
1503 //     MESSAGE("FindMatchingNodes() found too few node pairs starting from nodes ("
1504 //             << vNode1->GetID() << " - " << eNode1[0]->GetID() << ") ("
1505 //             << vNode2->GetID() << " - " << eNode2[0]->GetID() << "):"
1506 //             << node1To2Map.size() * quadFactor << " < " << SM1->NbNodes());
1507   
1508   return true;
1509 }
1510
1511 //================================================================================
1512 /*!
1513  * \brief Check if the first and last vertices of an edge are the same
1514  * \param anEdge - the edge to check
1515  * \retval bool - true if same
1516  */
1517 //================================================================================
1518
1519 bool StdMeshers_ProjectionUtils::IsClosedEdge( const TopoDS_Edge& anEdge )
1520 {
1521   return TopExp::FirstVertex( anEdge ).IsSame( TopExp::LastVertex( anEdge ));
1522 }
1523
1524 //================================================================================
1525   /*!
1526    * \brief Return any subshape of a face belonging to the outer wire
1527     * \param face - the face
1528     * \param type - type of subshape to return
1529     * \retval TopoDS_Shape - the found subshape
1530    */
1531 //================================================================================
1532
1533 TopoDS_Shape StdMeshers_ProjectionUtils::OuterShape( const TopoDS_Face& face,
1534                                                      TopAbs_ShapeEnum   type)
1535 {
1536   TopExp_Explorer exp( BRepTools::OuterWire( face ), type );
1537   if ( exp.More() )
1538     return exp.Current();
1539   return TopoDS_Shape();
1540 }
1541
1542 //================================================================================
1543   /*!
1544    * \brief Check that submesh is computed and try to compute it if is not
1545     * \param sm - submesh to compute
1546     * \param iterationNb - int used to stop infinite recursive call
1547     * \retval bool - true if computed
1548    */
1549 //================================================================================
1550
1551 bool StdMeshers_ProjectionUtils::MakeComputed(SMESH_subMesh * sm, const int iterationNb)
1552 {
1553   if ( iterationNb > 10 )
1554     RETURN_BAD_RESULT("Infinite recursive projection");
1555   if ( !sm )
1556     RETURN_BAD_RESULT("NULL submesh");
1557   if ( sm->IsMeshComputed() )
1558     return true;
1559
1560   SMESH_Mesh* mesh = sm->GetFather();
1561   SMESH_Gen* gen   = mesh->GetGen();
1562   SMESH_Algo* algo = gen->GetAlgo( *mesh, sm->GetSubShape() );
1563   if ( !algo )
1564     RETURN_BAD_RESULT("No algo assigned to submesh " << sm->GetId());
1565
1566   string algoType = algo->GetName();
1567   if ( algoType.substr(0, 11) != "Projection_")
1568     return gen->Compute( *mesh, sm->GetSubShape() );
1569
1570   // try to compute source mesh
1571
1572   const list <const SMESHDS_Hypothesis *> & hyps =
1573     algo->GetUsedHypothesis( *mesh, sm->GetSubShape() );
1574
1575   TopoDS_Shape srcShape;
1576   SMESH_Mesh* srcMesh = 0;
1577   list <const SMESHDS_Hypothesis*>::const_iterator hIt = hyps.begin();
1578   for ( ; srcShape.IsNull() && hIt != hyps.end(); ++hIt ) {
1579     string hypName = (*hIt)->GetName();
1580     if ( hypName == "ProjectionSource1D" ) {
1581       const StdMeshers_ProjectionSource1D * hyp =
1582         static_cast<const StdMeshers_ProjectionSource1D*>( *hIt );
1583       srcShape = hyp->GetSourceEdge();
1584       srcMesh = hyp->GetSourceMesh();
1585     }
1586     else if ( hypName == "ProjectionSource2D" ) {
1587       const StdMeshers_ProjectionSource2D * hyp =
1588         static_cast<const StdMeshers_ProjectionSource2D*>( *hIt );
1589       srcShape = hyp->GetSourceFace();
1590       srcMesh = hyp->GetSourceMesh();
1591     }
1592     else if ( hypName == "ProjectionSource3D" ) {
1593       const StdMeshers_ProjectionSource3D * hyp =
1594         static_cast<const StdMeshers_ProjectionSource3D*>( *hIt );
1595       srcShape = hyp->GetSource3DShape();
1596       srcMesh = hyp->GetSourceMesh();
1597     }
1598   }
1599   if ( srcShape.IsNull() ) // no projection source defined
1600     return gen->Compute( *mesh, sm->GetSubShape() );
1601
1602   if ( srcShape.IsSame( sm->GetSubShape() ))
1603     RETURN_BAD_RESULT("Projection from self");
1604     
1605   if ( !srcMesh )
1606     srcMesh = mesh;
1607
1608   return MakeComputed( srcMesh->GetSubMesh( srcShape ), iterationNb + 1 );
1609 }
1610
1611 //================================================================================
1612   /*!
1613    * \brief Count nb of subshapes
1614     * \param shape - the shape
1615     * \param type - the type of subshapes to count
1616     * \retval int - the calculated number
1617    */
1618 //================================================================================
1619
1620 int StdMeshers_ProjectionUtils::Count(const TopoDS_Shape&    shape,
1621                                       const TopAbs_ShapeEnum type,
1622                                       const bool             ignoreSame)
1623 {
1624   if ( ignoreSame ) {
1625     TopTools_IndexedMapOfShape map;
1626     TopExp::MapShapes( shape, type, map );
1627     return map.Extent();
1628   }
1629   else {
1630     int nb = 0;
1631     for ( TopExp_Explorer exp( shape, type ); exp.More(); exp.Next() )
1632       ++nb;
1633     return nb;
1634   }
1635 }
1636
1637 namespace {
1638
1639   SMESH_subMeshEventListener* GetSrcSubMeshListener();
1640
1641   //================================================================================
1642   /*!
1643    * \brief Listener that resets an event listener on source submesh when 
1644    * "ProjectionSource*D" hypothesis is modified
1645    */
1646   //================================================================================
1647
1648   struct HypModifWaiter: SMESH_subMeshEventListener
1649   {
1650     HypModifWaiter():SMESH_subMeshEventListener(0){} // won't be deleted by submesh
1651
1652     void ProcessEvent(const int event, const int eventType, SMESH_subMesh* subMesh,
1653                       EventListenerData*, const SMESH_Hypothesis*)
1654     {
1655       if ( event     == SMESH_subMesh::MODIF_HYP &&
1656            eventType == SMESH_subMesh::ALGO_EVENT)
1657       {
1658         // delete current source listener
1659         subMesh->DeleteEventListener( GetSrcSubMeshListener() );
1660         // let algo set a new one
1661         SMESH_Gen* gen = subMesh->GetFather()->GetGen();
1662         if ( SMESH_Algo* algo = gen->GetAlgo( *subMesh->GetFather(),
1663                                               subMesh->GetSubShape() ))
1664           algo->SetEventListener( subMesh );
1665       }
1666     }
1667   };
1668   //================================================================================
1669   /*!
1670    * \brief return static HypModifWaiter
1671    */
1672   //================================================================================
1673
1674   SMESH_subMeshEventListener* GetHypModifWaiter() {
1675     static HypModifWaiter aHypModifWaiter;
1676     return &aHypModifWaiter;
1677   }
1678   //================================================================================
1679   /*!
1680    * \brief return static listener for source shape submeshes
1681    */
1682   //================================================================================
1683
1684   SMESH_subMeshEventListener* GetSrcSubMeshListener() {
1685     static SMESH_subMeshEventListener srcListener(0); // won't be deleted by submesh
1686     return &srcListener;
1687   }
1688 }
1689
1690 //================================================================================
1691 /*!
1692  * \brief Set event listeners to submesh with projection algo
1693  * \param subMesh - submesh with projection algo
1694  * \param srcShape - source shape
1695  * \param srcMesh - source mesh
1696  */
1697 //================================================================================
1698
1699 void StdMeshers_ProjectionUtils::SetEventListener(SMESH_subMesh* subMesh,
1700                                                   TopoDS_Shape   srcShape,
1701                                                   SMESH_Mesh*    srcMesh)
1702 {
1703   // Set listener that resets an event listener on source submesh when
1704   // "ProjectionSource*D" hypothesis is modified
1705   subMesh->SetEventListener( GetHypModifWaiter(),0,subMesh);
1706
1707   // Set an event listener to submesh of the source shape
1708   if ( !srcShape.IsNull() )
1709   {
1710     if ( !srcMesh )
1711       srcMesh = subMesh->GetFather();
1712
1713     SMESH_subMesh* srcShapeSM = srcMesh->GetSubMesh( srcShape );
1714
1715     if ( srcShapeSM != subMesh ) {
1716       if ( srcShapeSM->GetSubMeshDS() &&
1717            srcShapeSM->GetSubMeshDS()->IsComplexSubmesh() )
1718       {  // source shape is a group
1719         TopExp_Explorer it(srcShapeSM->GetSubShape(), // explore the group into subshapes...
1720                            subMesh->GetSubShape().ShapeType()); // ...of target shape type
1721         for (; it.More(); it.Next())
1722         {
1723           SMESH_subMesh* srcSM = srcMesh->GetSubMesh( it.Current() );
1724           SMESH_subMeshEventListenerData* data =
1725             srcSM->GetEventListenerData(GetSrcSubMeshListener());
1726           if ( data )
1727             data->mySubMeshes.push_back( subMesh );
1728           else
1729             data = SMESH_subMeshEventListenerData::MakeData( subMesh );
1730           subMesh->SetEventListener ( GetSrcSubMeshListener(), data, srcSM );
1731         }
1732       }
1733       else
1734       {
1735         subMesh->SetEventListener( GetSrcSubMeshListener(),
1736                                    SMESH_subMeshEventListenerData::MakeData( subMesh ),
1737                                    srcShapeSM );
1738       }
1739     }
1740   }
1741 }