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