Salome HOME
Merge from V6_main 11/02/2013
[modules/smesh.git] / src / StdMeshers / StdMeshers_ProjectionUtils.cxx
1 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  SMESH SMESH : idl implementation based on 'SMESH' unit's calsses
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_Mesh.hxx"
39 #include "SMESH_MesherHelper.hxx"
40 #include "SMESH_subMesh.hxx"
41 #include "SMESH_subMeshEventListener.hxx"
42 #include "SMDS_EdgePosition.hxx"
43
44 #include "utilities.h"
45
46 #include <BRepAdaptor_Surface.hxx>
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_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
57 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
58 #include <TopTools_IndexedMapOfShape.hxx>
59 #include <TopTools_ListIteratorOfListOfShape.hxx>
60 #include <TopTools_ListOfShape.hxx>
61 #include <TopTools_MapOfShape.hxx>
62 #include <TopoDS.hxx>
63 #include <TopoDS_Compound.hxx>
64 #include <TopoDS_Shape.hxx>
65 #include <gp_Pnt.hxx>
66 #include <gp_Vec.hxx>
67
68 #include <numeric>
69 #include <limits>
70
71 using namespace std;
72
73
74 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
75 #define CONT_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); continue; }
76 #define SHOW_SHAPE(v,msg) \
77 // { \
78 //  if ( (v).IsNull() ) cout << msg << " NULL SHAPE" << endl; \
79 // else if ((v).ShapeType() == TopAbs_VERTEX) {\
80 //   gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( (v) ));\
81 //   cout<<msg<<" "<<shapeIndex((v))<<" ( "<<p.X()<<", "<<p.Y()<<", "<<p.Z()<<" )"<<endl;} \
82 // else {\
83 // cout << msg << " "; TopAbs::Print((v).ShapeType(),cout) <<" "<<shapeIndex((v))<<endl;}\
84 // }
85 #define SHOW_LIST(msg,l) \
86 // { \
87 //     cout << msg << " ";\
88 //     list< TopoDS_Edge >::const_iterator e = l.begin();\
89 //     for ( int i = 0; e != l.end(); ++e, ++i ) {\
90 //       cout << i << "V (" << TopExp::FirstVertex( *e, true ).TShape().operator->() << ") "\
91 //            << i << "E (" << e->TShape().operator->() << "); "; }\
92 //     cout << endl;\
93 //   }
94
95 #define HERE StdMeshers_ProjectionUtils
96
97 namespace {
98
99   static SMESHDS_Mesh* theMeshDS[2] = { 0, 0 }; // used to debug only
100   long shapeIndex(const TopoDS_Shape& S)
101   {
102     if ( theMeshDS[0] && theMeshDS[1] )
103       return max(theMeshDS[0]->ShapeToIndex(S), theMeshDS[1]->ShapeToIndex(S) );
104     return long(S.TShape().operator->());
105   }
106
107   //================================================================================
108   /*!
109    * \brief Write shape for debug purposes
110    */
111   //================================================================================
112
113   bool _StoreBadShape(const TopoDS_Shape& shape)
114   {
115 #ifdef _DEBUG_
116     const char* type[] ={"COMPOUND","COMPSOLID","SOLID","SHELL","FACE","WIRE","EDGE","VERTEX"};
117     BRepTools::Write( shape, SMESH_Comment("/tmp/") << type[shape.ShapeType()] << "_"
118                       << shape.TShape().operator->() << ".brep");
119 #endif
120     return false;
121   }
122   
123   //================================================================================
124   /*!
125    * \brief Reverse order of edges in a list and their orientation
126     * \param edges - list of edges to reverse
127     * \param nbEdges - number of edges to reverse
128    */
129   //================================================================================
130
131   void Reverse( list< TopoDS_Edge > & edges, const int nbEdges, const int firstEdge=0)
132   {
133     SHOW_LIST("BEFORE REVERSE", edges);
134
135     list< TopoDS_Edge >::iterator eIt = edges.begin();
136     std::advance( eIt, firstEdge );
137     list< TopoDS_Edge >::iterator eBackIt = eIt;
138     for ( int i = 0; i < nbEdges; ++i, ++eBackIt )
139       eBackIt->Reverse(); // reverse edge
140     // reverse list
141     --eBackIt;
142     while ( eIt != eBackIt )
143     {
144       std::swap( *eIt, *eBackIt );
145       SHOW_LIST("# AFTER SWAP", edges)
146         if ( (++eIt) != eBackIt )
147           --eBackIt;
148     }
149     SHOW_LIST("ATFER REVERSE", edges)
150   }
151
152   //================================================================================
153   /*!
154    * \brief Check if propagation is possible
155     * \param theMesh1 - source mesh
156     * \param theMesh2 - target mesh
157     * \retval bool - true if possible
158    */
159   //================================================================================
160
161   bool IsPropagationPossible( SMESH_Mesh* theMesh1, SMESH_Mesh* theMesh2 )
162   {
163     if ( theMesh1 != theMesh2 ) {
164       TopoDS_Shape mainShape1 = theMesh1->GetMeshDS()->ShapeToMesh();
165       TopoDS_Shape mainShape2 = theMesh2->GetMeshDS()->ShapeToMesh();
166       return mainShape1.IsSame( mainShape2 );
167     }
168     return true;
169   }
170
171   //================================================================================
172   /*!
173    * \brief Fix up association of edges in faces by possible propagation
174     * \param nbEdges - nb of edges in an outer wire
175     * \param edges1 - edges of one face
176     * \param edges2 - matching edges of another face
177     * \param theMesh1 - mesh 1
178     * \param theMesh2 - mesh 2
179     * \retval bool - true if association was fixed
180    */
181   //================================================================================
182
183   bool FixAssocByPropagation( const int             nbEdges,
184                               list< TopoDS_Edge > & edges1,
185                               list< TopoDS_Edge > & edges2,
186                               SMESH_Mesh*           theMesh1,
187                               SMESH_Mesh*           theMesh2)
188   {
189     if ( nbEdges == 2 && IsPropagationPossible( theMesh1, theMesh2 ) )
190     {
191       list< TopoDS_Edge >::iterator eIt2 = ++edges2.begin(); // 2nd edge of the 2nd face
192       TopoDS_Edge edge2 = HERE::GetPropagationEdge( theMesh1, *eIt2, edges1.front() ).second;
193       if ( !edge2.IsNull() ) { // propagation found for the second edge
194         Reverse( edges2, nbEdges );
195         return true;
196       }
197     }
198     return false;
199   }
200
201   //================================================================================
202   /*!
203    * \brief Look for a group containing a target shape and similar to a source group
204     * \param tgtShape - target edge or face
205     * \param tgtMesh1 - target mesh
206     * \param srcGroup - source group
207     * \retval TopoDS_Shape - found target group
208    */
209   //================================================================================
210
211   TopoDS_Shape FindGroupContaining(const TopoDS_Shape& tgtShape,
212                                    const SMESH_Mesh*   tgtMesh1,
213                                    const TopoDS_Shape& srcGroup)
214   {
215     list<SMESH_subMesh*> subMeshes = tgtMesh1->GetGroupSubMeshesContaining(tgtShape);
216     list<SMESH_subMesh*>::iterator sm = subMeshes.begin();
217     int type, last = TopAbs_SHAPE;
218     for ( ; sm != subMeshes.end(); ++sm ) {
219       const TopoDS_Shape & group = (*sm)->GetSubShape();
220       // check if group is similar to srcGroup
221       for ( type = srcGroup.ShapeType(); type < last; ++type)
222         if ( SMESH_MesherHelper::Count( srcGroup, (TopAbs_ShapeEnum)type, 0) !=
223              SMESH_MesherHelper::Count( group,    (TopAbs_ShapeEnum)type, 0))
224           break;
225       if ( type == last )
226         return group;
227     }
228     return TopoDS_Shape();
229   }
230
231   //================================================================================
232   /*!
233    * \brief Find association of groups at top and bottom of prism
234    */
235   //================================================================================
236
237   bool AssocGroupsByPropagation(const TopoDS_Shape&   theGroup1,
238                                 const TopoDS_Shape&   theGroup2,
239                                 SMESH_Mesh&           theMesh,
240                                 HERE::TShapeShapeMap& theMap)
241   {
242     // If groups are on top and bottom of prism then we can associate
243     // them using "vertical" (or "side") edges and faces of prism since
244     // they connect corresponding vertices and edges of groups.
245
246     TopTools_IndexedMapOfShape subshapes1, subshapes2;
247     TopExp::MapShapes( theGroup1, subshapes1 );
248     TopExp::MapShapes( theGroup2, subshapes2 );
249     TopTools_ListIteratorOfListOfShape ancestIt;
250
251     // Iterate on vertices of group1 to find corresponding vertices in group2
252     // and associate adjacent edges and faces
253
254     TopTools_MapOfShape verticShapes;
255     TopExp_Explorer vExp1( theGroup1, TopAbs_VERTEX );
256     for ( ; vExp1.More(); vExp1.Next() )
257     {
258       const TopoDS_Vertex& v1 = TopoDS::Vertex( vExp1.Current() );
259       if ( theMap.IsBound( v1 )) continue; // already processed
260
261       // Find "vertical" edge ending in v1 and whose other vertex belongs to group2
262       TopoDS_Shape verticEdge, v2;
263       ancestIt.Initialize( theMesh.GetAncestors( v1 ));
264       for ( ; verticEdge.IsNull() && ancestIt.More(); ancestIt.Next() )
265       {
266         if ( ancestIt.Value().ShapeType() != TopAbs_EDGE ) continue;
267         v2 = HERE::GetNextVertex( TopoDS::Edge( ancestIt.Value() ), v1 );
268         if ( subshapes2.Contains( v2 ))
269           verticEdge = ancestIt.Value();
270       }
271       if ( verticEdge.IsNull() )
272         return false;
273
274       HERE::InsertAssociation( v1, v2, theMap);
275
276       // Associate edges by vertical faces sharing the found vertical edge
277       ancestIt.Initialize( theMesh.GetAncestors( verticEdge ) );
278       for ( ; ancestIt.More(); ancestIt.Next() )
279       {
280         if ( ancestIt.Value().ShapeType() != TopAbs_FACE ) continue;
281         if ( !verticShapes.Add( ancestIt.Value() )) continue;
282         const TopoDS_Face& face = TopoDS::Face( ancestIt.Value() );
283
284         // get edges of the face
285         TopoDS_Edge edgeGr1, edgeGr2, verticEdge2;
286         list< TopoDS_Edge > edges;    list< int > nbEdgesInWire;
287         SMESH_Block::GetOrderedEdges( face, edges, nbEdgesInWire, v1);
288         if ( nbEdgesInWire.front() != 4 )
289           return _StoreBadShape( face );
290         list< TopoDS_Edge >::iterator edge = edges.begin();
291         if ( verticEdge.IsSame( *edge )) {
292           edgeGr2     = *(++edge);
293           verticEdge2 = *(++edge);
294           edgeGr1     = *(++edge);
295         } else {
296           edgeGr1     = *(edge++);
297           verticEdge2 = *(edge++);
298           edgeGr2     = *(edge++);
299         }
300
301         HERE::InsertAssociation( edgeGr1, edgeGr2.Reversed(), theMap);
302       }
303     }
304
305     // Associate faces
306     TopoDS_Iterator gr1It( theGroup1 );
307     if ( gr1It.Value().ShapeType() == TopAbs_FACE )
308     {
309       // find a boundary edge of group1 to start from
310       TopoDS_Shape bndEdge = HERE::GetBoundaryEdge( theGroup1, theMesh );
311       if ( bndEdge.IsNull() )
312         return false;
313
314       list< TopoDS_Shape > edges(1, bndEdge);
315       list< TopoDS_Shape >::iterator edge1 = edges.begin();
316       for ( ; edge1 != edges.end(); ++edge1 )
317       {
318         // there must be one or zero not associated faces between ancestors of edge
319         // belonging to theGroup1
320         TopoDS_Shape face1;
321         ancestIt.Initialize( theMesh.GetAncestors( *edge1 ) );
322         for ( ; ancestIt.More() && face1.IsNull(); ancestIt.Next() ) {
323           if ( ancestIt.Value().ShapeType() == TopAbs_FACE &&
324                !theMap.IsBound( ancestIt.Value() ) &&
325                subshapes1.Contains( ancestIt.Value() ))
326             face1 = ancestIt.Value();
327
328           // add edges of face1 to start searching for adjacent faces from
329           for ( TopExp_Explorer e(face1, TopAbs_EDGE); e.More(); e.Next())
330             if ( !edge1->IsSame( e.Current() ))
331               edges.push_back( e.Current() );
332         }
333         if ( !face1.IsNull() ) {
334           // find the corresponding face of theGroup2
335           TopoDS_Shape edge2 = theMap( *edge1 );
336           TopoDS_Shape face2;
337           ancestIt.Initialize( theMesh.GetAncestors( edge2 ) );
338           for ( ; ancestIt.More() && face2.IsNull(); ancestIt.Next() ) {
339             if ( ancestIt.Value().ShapeType() == TopAbs_FACE &&
340                  !theMap.IsBound( ancestIt.Value(), /*is2nd=*/true ) &&
341                  subshapes2.Contains( ancestIt.Value() ))
342               face2 = ancestIt.Value();
343           }
344           if ( face2.IsNull() )
345             return false;
346
347           HERE::InsertAssociation( face1, face2, theMap);
348         }
349       }
350     }
351     return true;
352   }
353
354   //================================================================================
355   /*!
356    * \brief Return true if uv position of the vIndex-th vertex of edge on face is close
357    * enough to given uv 
358    */
359   //================================================================================
360
361   bool sameVertexUV( const TopoDS_Edge& edge,
362                      const TopoDS_Face& face,
363                      const int&         vIndex,
364                      const gp_Pnt2d&    uv,
365                      const double&      tol2d )
366   {
367     TopoDS_Vertex VV[2];
368     TopExp::Vertices( edge, VV[0], VV[1], true);
369     gp_Pnt2d v1UV = BRep_Tool::Parameters( VV[vIndex], face);
370     double dist2d = v1UV.Distance( uv );
371     return dist2d < tol2d;
372   }
373
374   //================================================================================
375   /*!
376    * \brief Returns an EDGE suitable for search of initial vertex association
377    */
378   //================================================================================
379
380   bool getOuterEdges( const TopoDS_Shape        shape,
381                       SMESH_Mesh&               mesh,
382                       std::list< TopoDS_Edge >& allBndEdges )
383   {
384     if ( shape.ShapeType() == TopAbs_COMPOUND )
385     {
386       TopoDS_Iterator it( shape );
387       if ( it.More() && it.Value().ShapeType() == TopAbs_FACE ) // group of FACEs
388       {
389         // look for a boundary EDGE of a group
390         StdMeshers_ProjectionUtils::GetBoundaryEdge( shape, mesh, &allBndEdges );
391         if ( !allBndEdges.empty() )
392           return true;
393       }
394     }
395     TopExp_Explorer expF( shape, TopAbs_FACE ), expE;
396     if ( expF.More() ) {
397       for ( ; expF.More(); expF.Next() ) {
398         TopoDS_Shape wire =
399           StdMeshers_ProjectionUtils::OuterShape( TopoDS::Face( expF.Current() ), TopAbs_WIRE );
400         for ( expE.Init( wire, TopAbs_EDGE ); expE.More(); expE.Next() )
401           if ( !SMESH_MesherHelper::IsClosedEdge( TopoDS::Edge( expE.Current() )))
402             allBndEdges.push_back( TopoDS::Edge( expE.Current() ));
403       }
404     }
405     else if ( shape.ShapeType() != TopAbs_EDGE) { // no faces
406       for ( expE.Init( shape, TopAbs_EDGE ); expE.More(); expE.Next() )
407         if ( !SMESH_MesherHelper::IsClosedEdge( TopoDS::Edge( expE.Current() )))
408           allBndEdges.push_back( TopoDS::Edge( expE.Current() ));
409     }
410     else if ( shape.ShapeType() == TopAbs_EDGE ) {
411       if ( !SMESH_MesherHelper::IsClosedEdge( TopoDS::Edge( shape )))
412         allBndEdges.push_back( TopoDS::Edge( shape ));
413     }
414     return !allBndEdges.empty();
415   }
416
417 } // namespace
418
419 //=======================================================================
420 /*!
421  * \brief Looks for association of all sub-shapes of two shapes
422  * \param theShape1 - target shape
423  * \param theMesh1 - mesh built on shape 1
424  * \param theShape2 - source shape
425  * \param theMesh2 - mesh built on shape 2
426  * \param theAssociation - association map to be filled that may
427  *                         contain association of one or two pairs of vertices
428  * \retval bool - true if association found
429  */
430 //=======================================================================
431
432 bool StdMeshers_ProjectionUtils::FindSubShapeAssociation(const TopoDS_Shape& theShape1,
433                                                          SMESH_Mesh*         theMesh1,
434                                                          const TopoDS_Shape& theShape2,
435                                                          SMESH_Mesh*         theMesh2,
436                                                          TShapeShapeMap &    theMap)
437 {
438   // Structure of this long function is following
439   // 1) Group->group projection: theShape1 is a group member,
440   //    theShape2 is a group. We find a group theShape1 is in and recall self.
441   // 2) Accosiate same shapes with different location (partners).
442   // 3) If vertex association is given, perform accosiation according to shape type:
443   //       switch ( ShapeType ) {
444   //         case TopAbs_EDGE:
445   //         case ...:
446   //       }
447   // 4) else try to accosiate in different ways:
448   //       a) accosiate shapes by propagation and other simple cases
449   //            switch ( ShapeType ) {
450   //            case TopAbs_EDGE:
451   //            case ...:
452   //            }
453   //       b) find association of a couple of vertices and recall self.
454   //
455
456   theMeshDS[0] = theMesh1->GetMeshDS(); // debug
457   theMeshDS[1] = theMesh2->GetMeshDS();
458
459   // =================================================================================
460   // 1) Is it the case of associating a group member -> another group? (PAL16202, 16203)
461   // =================================================================================
462   if ( theShape1.ShapeType() != theShape2.ShapeType() ) {
463     TopoDS_Shape group1, group2;
464     if ( theShape1.ShapeType() == TopAbs_COMPOUND ) {
465       group1 = theShape1;
466       group2 = FindGroupContaining( theShape2, theMesh2, group1 );
467     }
468     else if ( theShape2.ShapeType() == TopAbs_COMPOUND ) {
469       group2 = theShape2;
470       group1 = FindGroupContaining( theShape1, theMesh1, group2 );
471     }
472     if ( group1.IsNull() || group2.IsNull() )
473       RETURN_BAD_RESULT("Different shape types");
474     // Associate compounds
475     return FindSubShapeAssociation(group1, theMesh1, group2, theMesh2, theMap );
476   }
477
478   // ============
479   // 2) Is partner?
480   // ============
481   bool partner = theShape1.IsPartner( theShape2 );
482   TopTools_DataMapIteratorOfDataMapOfShapeShape vvIt( theMap._map1to2 );
483   for ( ; partner && vvIt.More(); vvIt.Next() )
484     partner = vvIt.Key().IsPartner( vvIt.Value() );
485
486   if ( partner ) // Same shape with different location
487   {
488     // recursively associate all sub-shapes of theShape1 and theShape2
489     typedef list< pair< TopoDS_Shape, TopoDS_Shape > > TShapePairsList;
490     TShapePairsList shapesQueue( 1, make_pair( theShape1, theShape2 ));
491     TShapePairsList::iterator s1_s2 = shapesQueue.begin();
492     for ( ; s1_s2 != shapesQueue.end(); ++s1_s2 )
493     {
494       InsertAssociation( s1_s2->first, s1_s2->second, theMap );
495       TopoDS_Iterator s1It( s1_s2->first), s2It( s1_s2->second );
496       for ( ; s1It.More(); s1It.Next(), s2It.Next() )
497         shapesQueue.push_back( make_pair( s1It.Value(), s2It.Value() ));
498     }
499     return true;
500   }
501
502   if ( !theMap.IsEmpty() )
503   {
504     //======================================================================
505     // 3) HAS initial vertex association
506     //======================================================================
507     switch ( theShape1.ShapeType() ) {
508       // ----------------------------------------------------------------------
509     case TopAbs_EDGE: { // TopAbs_EDGE
510       // ----------------------------------------------------------------------
511       if ( theMap.Extent() != 2 )
512         RETURN_BAD_RESULT("Wrong map extent " << theMap.Extent() );
513       TopoDS_Edge edge1 = TopoDS::Edge( theShape1 );
514       TopoDS_Edge edge2 = TopoDS::Edge( theShape2 );
515       if ( edge1.Orientation() >= TopAbs_INTERNAL ) edge1.Orientation( TopAbs_FORWARD );
516       if ( edge2.Orientation() >= TopAbs_INTERNAL ) edge2.Orientation( TopAbs_FORWARD );
517       TopoDS_Vertex VV1[2], VV2[2];
518       TopExp::Vertices( edge1, VV1[0], VV1[1] );
519       TopExp::Vertices( edge2, VV2[0], VV2[1] );
520       int i1 = 0, i2 = 0;
521       if ( theMap.IsBound( VV1[ i1 ] )) i1 = 1;
522       if ( theMap.IsBound( VV2[ i2 ] )) i2 = 1;
523       InsertAssociation( VV1[ i1 ], VV2[ i2 ], theMap );
524       InsertAssociation( theShape1, theShape2, theMap );
525       return true;
526     }
527       // ----------------------------------------------------------------------
528     case TopAbs_FACE: { // TopAbs_FACE
529       // ----------------------------------------------------------------------
530       TopoDS_Face face1 = TopoDS::Face( theShape1 );
531       TopoDS_Face face2 = TopoDS::Face( theShape2 );
532       if ( face1.Orientation() >= TopAbs_INTERNAL ) face1.Orientation( TopAbs_FORWARD );
533       if ( face2.Orientation() >= TopAbs_INTERNAL ) face2.Orientation( TopAbs_FORWARD );
534
535       TopoDS_Vertex VV1[2], VV2[2];
536       // find a not closed edge of face1 both vertices of which are associated
537       int nbEdges = 0;
538       TopExp_Explorer exp ( face1, TopAbs_EDGE );
539       for ( ; VV2[ 1 ].IsNull() && exp.More(); exp.Next(), ++nbEdges ) {
540         TopExp::Vertices( TopoDS::Edge( exp.Current() ), VV1[0], VV1[1] );
541         if ( theMap.IsBound( VV1[0] ) ) {
542           VV2[ 0 ] = TopoDS::Vertex( theMap( VV1[0] ));
543           if ( theMap.IsBound( VV1[1] ) && !VV1[0].IsSame( VV1[1] ))
544             VV2[ 1 ] = TopoDS::Vertex( theMap( VV1[1] ));
545         }
546       }
547       if ( VV2[ 1 ].IsNull() ) { // 2 bound vertices not found
548         if ( nbEdges > 1 ) {
549           RETURN_BAD_RESULT("2 bound vertices not found" );
550         } else {
551           VV2[ 1 ] = VV2[ 0 ];
552         }
553       }
554       list< TopoDS_Edge > edges1, edges2;
555       int nbE = FindFaceAssociation( face1, VV1, face2, VV2, edges1, edges2 );
556       if ( !nbE ) RETURN_BAD_RESULT("FindFaceAssociation() failed");
557       FixAssocByPropagation( nbE, edges1, edges2, theMesh1, theMesh2 );
558
559       list< TopoDS_Edge >::iterator eIt1 = edges1.begin();
560       list< TopoDS_Edge >::iterator eIt2 = edges2.begin();
561       for ( ; eIt1 != edges1.end(); ++eIt1, ++eIt2 )
562       {
563         InsertAssociation( *eIt1, *eIt2, theMap );
564         VV1[0] = TopExp::FirstVertex( *eIt1, true );
565         VV2[0] = TopExp::FirstVertex( *eIt2, true );
566         InsertAssociation( VV1[0], VV2[0], theMap );
567       }
568       InsertAssociation( theShape1, theShape2, theMap );
569       return true;
570     }
571       // ----------------------------------------------------------------------
572     case TopAbs_SHELL: // TopAbs_SHELL, TopAbs_SOLID
573     case TopAbs_SOLID: {
574       // ----------------------------------------------------------------------
575       TopoDS_Vertex VV1[2], VV2[2];
576       // try to find a not closed edge of shape1 both vertices of which are associated
577       TopoDS_Edge edge1;
578       TopExp_Explorer exp ( theShape1, TopAbs_EDGE );
579       for ( ; VV2[ 1 ].IsNull() && exp.More(); exp.Next() ) {
580         edge1 = TopoDS::Edge( exp.Current() );
581         if ( edge1.Orientation() >= TopAbs_INTERNAL ) edge1.Orientation( TopAbs_FORWARD );
582         TopExp::Vertices( edge1 , VV1[0], VV1[1] );
583         if ( theMap.IsBound( VV1[0] )) {
584           VV2[ 0 ] = TopoDS::Vertex( theMap( VV1[0] ));
585           if ( theMap.IsBound( VV1[1] ) && !VV1[0].IsSame( VV1[1] ))
586             VV2[ 1 ] = TopoDS::Vertex( theMap( VV1[1] ));
587         }
588       }
589       if ( VV2[ 1 ].IsNull() ) // 2 bound vertices not found
590         RETURN_BAD_RESULT("2 bound vertices not found" );
591       // get an edge2 of theShape2 corresponding to edge1
592       TopoDS_Edge edge2 = GetEdgeByVertices( theMesh2, VV2[ 0 ], VV2[ 1 ]);
593       if ( edge2.IsNull() )
594         RETURN_BAD_RESULT("GetEdgeByVertices() failed");
595
596       // build map of edge to faces if shapes are not sub-shapes of main ones
597       bool isSubOfMain = false;
598       if ( SMESHDS_SubMesh * sm = theMesh1->GetMeshDS()->MeshElements( theShape1 ))
599         isSubOfMain = !sm->IsComplexSubmesh();
600       else
601         isSubOfMain = theMesh1->GetMeshDS()->ShapeToIndex( theShape1 );
602       TAncestorMap e2f1, e2f2;
603       const TAncestorMap& edgeToFace1 = isSubOfMain ? theMesh1->GetAncestorMap() : e2f1;
604       const TAncestorMap& edgeToFace2 = isSubOfMain ? theMesh2->GetAncestorMap() : e2f2;
605       if (!isSubOfMain) {
606         TopExp::MapShapesAndAncestors( theShape1, TopAbs_EDGE, TopAbs_FACE, e2f1 );
607         TopExp::MapShapesAndAncestors( theShape2, TopAbs_EDGE, TopAbs_FACE, e2f2 );
608         if ( !edgeToFace1.Contains( edge1 ))
609           RETURN_BAD_RESULT("edge1 does not belong to theShape1");
610         if ( !edgeToFace2.Contains( edge2 ))
611           RETURN_BAD_RESULT("edge2 does not belong to theShape2");
612       }
613       //
614       // Look for 2 corresponing faces:
615       //
616       TopoDS_Shape F1, F2;
617
618       // get a face sharing edge1 (F1)
619       TopoDS_Shape FF2[2];
620       TopTools_ListIteratorOfListOfShape ancestIt1( edgeToFace1.FindFromKey( edge1 ));
621       for ( ; F1.IsNull() && ancestIt1.More(); ancestIt1.Next() )
622         if ( ancestIt1.Value().ShapeType() == TopAbs_FACE )
623           F1 = ancestIt1.Value().Oriented( TopAbs_FORWARD );
624       if ( F1.IsNull() )
625         RETURN_BAD_RESULT(" Face1 not found");
626
627       // get 2 faces sharing edge2 (one of them is F2)
628       TopTools_ListIteratorOfListOfShape ancestIt2( edgeToFace2.FindFromKey( edge2 ));
629       for ( int i = 0; FF2[1].IsNull() && ancestIt2.More(); ancestIt2.Next() )
630         if ( ancestIt2.Value().ShapeType() == TopAbs_FACE )
631           FF2[ i++ ] = ancestIt2.Value().Oriented( TopAbs_FORWARD );
632
633       // get oriented edge1 and edge2 from F1 and FF2[0]
634       for ( exp.Init( F1, TopAbs_EDGE ); exp.More(); exp.Next() )
635         if ( edge1.IsSame( exp.Current() )) {
636           edge1 = TopoDS::Edge( exp.Current() );
637           break;
638         }
639       for ( exp.Init( FF2[ 0 ], TopAbs_EDGE ); exp.More(); exp.Next() )
640         if ( edge2.IsSame( exp.Current() )) {
641           edge2 = TopoDS::Edge( exp.Current() );
642           break;
643         }
644
645       // compare first vertices of edge1 and edge2
646       TopExp::Vertices( edge1, VV1[0], VV1[1], true );
647       TopExp::Vertices( edge2, VV2[0], VV2[1], true );
648       F2 = FF2[ 0 ]; // (F2 !)
649       if ( !VV1[ 0 ].IsSame( theMap( VV2[ 0 ], /*is2=*/true))) {
650         edge2.Reverse();
651         if ( FF2[ 1 ].IsNull() )
652           F2.Reverse();
653         else
654           F2 = FF2[ 1 ];
655       }
656
657       TopTools_MapOfShape boundEdges;
658
659       // association of face sub-shapes and neighbour faces
660       list< pair < TopoDS_Face, TopoDS_Edge > > FE1, FE2;
661       list< pair < TopoDS_Face, TopoDS_Edge > >::iterator fe1, fe2;
662       FE1.push_back( make_pair( TopoDS::Face( F1 ), edge1 ));
663       FE2.push_back( make_pair( TopoDS::Face( F2 ), edge2 ));
664       for ( fe1 = FE1.begin(), fe2 = FE2.begin(); fe1 != FE1.end(); ++fe1, ++fe2 )
665       {
666         const TopoDS_Face& face1 = fe1->first;
667         if ( theMap.IsBound( face1 ) ) continue;
668         const TopoDS_Face& face2 = fe2->first;
669         edge1 = fe1->second;
670         edge2 = fe2->second;
671         TopExp::Vertices( edge1, VV1[0], VV1[1], true );
672         TopExp::Vertices( edge2, VV2[0], VV2[1], true );
673         list< TopoDS_Edge > edges1, edges2;
674         int nbE = FindFaceAssociation( face1, VV1, face2, VV2, edges1, edges2 );
675         if ( !nbE ) RETURN_BAD_RESULT("FindFaceAssociation() failed");
676         InsertAssociation( face1, face2, theMap ); // assoc faces
677         MESSAGE("Assoc FACE " << theMesh1->GetMeshDS()->ShapeToIndex( face1 )<<
678                 " to "        << theMesh2->GetMeshDS()->ShapeToIndex( face2 ));
679         if ( nbE == 2 && (edge1.IsSame( edges1.front())) != (edge2.IsSame( edges2.front())))
680         {
681           Reverse( edges2, nbE );
682         }
683         list< TopoDS_Edge >::iterator eIt1 = edges1.begin();
684         list< TopoDS_Edge >::iterator eIt2 = edges2.begin();
685         for ( ; eIt1 != edges1.end(); ++eIt1, ++eIt2 )
686         {
687           if ( !boundEdges.Add( *eIt1 )) continue; // already associated
688           InsertAssociation( *eIt1, *eIt2, theMap );  // assoc edges
689           MESSAGE("Assoc edge " << theMesh1->GetMeshDS()->ShapeToIndex( *eIt1 )<<
690                   " to "        << theMesh2->GetMeshDS()->ShapeToIndex( *eIt2 ));
691           VV1[0] = TopExp::FirstVertex( *eIt1, true );
692           VV2[0] = TopExp::FirstVertex( *eIt2, true );
693           InsertAssociation( VV1[0], VV2[0], theMap ); // assoc vertices
694           MESSAGE("Assoc vertex " << theMesh1->GetMeshDS()->ShapeToIndex( VV1[0] )<<
695                   " to "          << theMesh2->GetMeshDS()->ShapeToIndex( VV2[0] ));
696
697           // add adjacent faces to process
698           TopoDS_Face nextFace1 = GetNextFace( edgeToFace1, *eIt1, face1 );
699           TopoDS_Face nextFace2 = GetNextFace( edgeToFace2, *eIt2, face2 );
700           if ( !nextFace1.IsNull() && !nextFace2.IsNull() ) {
701             FE1.push_back( make_pair( nextFace1, *eIt1 ));
702             FE2.push_back( make_pair( nextFace2, *eIt2 ));
703           }
704         }
705       }
706       InsertAssociation( theShape1, theShape2, theMap );
707       return true;
708     }
709       // ----------------------------------------------------------------------
710     case TopAbs_COMPOUND: { // GROUP
711       // ----------------------------------------------------------------------
712       // Maybe groups contain only one member
713       TopoDS_Iterator it1( theShape1 ), it2( theShape2 );
714       TopAbs_ShapeEnum memberType = it1.Value().ShapeType();
715       int nbMembers = SMESH_MesherHelper::Count( theShape1, memberType, true );
716       if ( nbMembers == 0 ) return true;
717       if ( nbMembers == 1 ) {
718         return FindSubShapeAssociation( it1.Value(), theMesh1, it2.Value(), theMesh2, theMap );
719       }
720       // Try to make shells of faces
721       //
722       BRep_Builder builder;
723       TopoDS_Shell shell1, shell2;
724       builder.MakeShell(shell1); builder.MakeShell(shell2);
725       if ( memberType == TopAbs_FACE ) {
726         // just add faces of groups to shells
727         for (; it1.More(); it1.Next(), it2.Next() )
728           builder.Add( shell1, it1.Value() ), builder.Add( shell2, it2.Value() );
729       }
730       else if ( memberType == TopAbs_EDGE ) {
731         // Try to add faces sharing more than one edge of a group or
732         // sharing all its vertices with the group
733         TopTools_IndexedMapOfShape groupVertices[2];
734         TopExp::MapShapes( theShape1, TopAbs_VERTEX, groupVertices[0]);
735         TopExp::MapShapes( theShape2, TopAbs_VERTEX, groupVertices[1]);
736         //
737         TopTools_MapOfShape groupEdges[2], addedFaces[2];
738         bool hasInitAssoc = (!theMap.IsEmpty()), initAssocOK = !hasInitAssoc;
739         for (; it1.More(); it1.Next(), it2.Next() ) {
740           groupEdges[0].Add( it1.Value() );
741           groupEdges[1].Add( it2.Value() );
742           if ( !initAssocOK ) {
743             // for shell association there must be an edge with both vertices bound
744             TopoDS_Vertex v1, v2;
745             TopExp::Vertices( TopoDS::Edge( it1.Value().Oriented(TopAbs_FORWARD)), v1, v2 );
746             initAssocOK = ( theMap.IsBound( v1 ) && theMap.IsBound( v2 ));
747           }
748         }
749         for (int is2ndGroup = 0; initAssocOK && is2ndGroup < 2; ++is2ndGroup) {
750           const TopoDS_Shape& group = is2ndGroup ? theShape2: theShape1;
751           SMESH_Mesh*         mesh  = is2ndGroup ? theMesh2 : theMesh1;
752           TopoDS_Shell&       shell = is2ndGroup ? shell2   : shell1;
753           for ( TopoDS_Iterator it( group ); it.More(); it.Next() ) {
754             const TopoDS_Edge& edge = TopoDS::Edge( it.Value() );
755             TopoDS_Face face;
756             for ( int iF = 0; iF < 2; ++iF ) { // loop on 2 faces sharing edge
757               face = GetNextFace(mesh->GetAncestorMap(), edge, face);
758               if ( !face.IsNull() ) {
759                 int nbGroupEdges = 0;
760                 for ( TopExp_Explorer f( face, TopAbs_EDGE ); f.More(); f.Next())
761                   if ( groupEdges[ is2ndGroup ].Contains( f.Current() ))
762                     if ( ++nbGroupEdges > 1 )
763                       break;
764                 bool add = (nbGroupEdges > 1 ||
765                             SMESH_MesherHelper::Count( face, TopAbs_EDGE, true ) == 1 );
766                 if ( !add ) {
767                   add = true;
768                   for ( TopExp_Explorer v( face, TopAbs_VERTEX ); add && v.More(); v.Next())
769                     add = groupVertices[ is2ndGroup ].Contains( v.Current() );
770                 }
771                 if ( add && addedFaces[ is2ndGroup ].Add( face ))
772                   builder.Add( shell, face );
773               }
774             }
775           }
776         }
777       } else {
778         RETURN_BAD_RESULT("Unexpected group type");
779       }
780       // Associate shells
781       //
782       int nbFaces1 = SMESH_MesherHelper:: Count( shell1, TopAbs_FACE, 0 );
783       int nbFaces2 = SMESH_MesherHelper:: Count( shell2, TopAbs_FACE, 0 );
784       if ( nbFaces1 != nbFaces2 )
785         RETURN_BAD_RESULT("Different nb of faces found for shells");
786       if ( nbFaces1 > 0 ) {
787         bool ok = false;
788         if ( nbFaces1 == 1 ) {
789           TopoDS_Shape F1 = TopoDS_Iterator( shell1 ).Value();
790           TopoDS_Shape F2 = TopoDS_Iterator( shell2 ).Value();
791           ok = FindSubShapeAssociation( F1, theMesh1, F2, theMesh2, theMap );
792         }
793         else {
794           ok = FindSubShapeAssociation(shell1, theMesh1, shell2, theMesh2, theMap );
795         }
796         // Check if all members are mapped 
797         if ( ok ) {
798           TopTools_MapOfShape boundMembers[2];
799           TopoDS_Iterator mIt;
800           for ( mIt.Initialize( theShape1 ); mIt.More(); mIt.Next())
801             if ( theMap.IsBound( mIt.Value() )) {
802               boundMembers[0].Add( mIt.Value() );
803               boundMembers[1].Add( theMap( mIt.Value() ));
804             }
805           if ( boundMembers[0].Extent() != nbMembers ) {
806             // make compounds of not bound members
807             TopoDS_Compound comp[2];
808             for ( int is2ndGroup = 0; is2ndGroup < 2; ++is2ndGroup ) {
809               builder.MakeCompound( comp[is2ndGroup] );
810               for ( mIt.Initialize( is2ndGroup ? theShape2:theShape1 ); mIt.More(); mIt.Next())
811                 if ( ! boundMembers[ is2ndGroup ].Contains( mIt.Value() ))
812                   builder.Add( comp[ is2ndGroup ], mIt.Value() );
813             }
814             // check if theMap contains initial association for the comp's
815             bool hasInitialAssoc = false;
816             if ( memberType == TopAbs_EDGE ) {
817               for ( TopExp_Explorer v( comp[0], TopAbs_VERTEX ); v.More(); v.Next())
818                 if ( theMap.IsBound( v.Current() )) {
819                   hasInitialAssoc = true;
820                   break;
821                 }
822             }
823             if ( hasInitialAssoc == bool( !theMap.IsEmpty() ))
824               ok = FindSubShapeAssociation( comp[0], theMesh1, comp[1], theMesh2, theMap );
825             else {
826               TShapeShapeMap tmpMap;
827               ok = FindSubShapeAssociation( comp[0], theMesh1, comp[1], theMesh2, tmpMap );
828               if ( ok ) {
829                 TopTools_DataMapIteratorOfDataMapOfShapeShape mapIt( tmpMap._map1to2 );
830                 for ( ; mapIt.More(); mapIt.Next() )
831                   theMap.Bind( mapIt.Key(), mapIt.Value());
832               }
833             }
834           }
835         }
836         return ok;
837       }
838       // Each edge of an edge group is shared by own faces
839       // ------------------------------------------------------------------
840       //
841       // map vertices to edges sharing them, avoid doubling edges in lists
842       TopTools_DataMapOfShapeListOfShape v2e[2];
843       for (int isFirst = 0; isFirst < 2; ++isFirst ) {
844         const TopoDS_Shape& group = isFirst ? theShape1 : theShape2;
845         TopTools_DataMapOfShapeListOfShape& veMap = v2e[ isFirst ? 0 : 1 ];
846         TopTools_MapOfShape addedEdges;
847         for ( TopExp_Explorer e( group, TopAbs_EDGE ); e.More(); e.Next() ) {
848           const TopoDS_Shape& edge = e.Current();
849           if ( addedEdges.Add( edge )) {
850             for ( TopExp_Explorer v( edge, TopAbs_VERTEX ); v.More(); v.Next()) {
851               const TopoDS_Shape& vertex = v.Current();
852               if ( !veMap.IsBound( vertex )) {
853                 TopTools_ListOfShape l;
854                 veMap.Bind( vertex, l );
855               }
856               veMap( vertex ).Append( edge );
857             }
858           }
859         }   
860       }
861       while ( !v2e[0].IsEmpty() )
862       {
863         // find a bound vertex
864         TopoDS_Vertex V[2];
865         TopTools_DataMapIteratorOfDataMapOfShapeListOfShape v2eIt( v2e[0] );
866         for ( ; v2eIt.More(); v2eIt.Next())
867           if ( theMap.IsBound( v2eIt.Key() )) {
868             V[0] = TopoDS::Vertex( v2eIt.Key() );
869             V[1] = TopoDS::Vertex( theMap( V[0] ));
870             break;
871           }
872         if ( V[0].IsNull() )
873           RETURN_BAD_RESULT("No more bound vertices");
874
875         while ( !V[0].IsNull() && v2e[0].IsBound( V[0] )) {
876           TopTools_ListOfShape& edges0 = v2e[0]( V[0] );
877           TopTools_ListOfShape& edges1 = v2e[1]( V[1] );
878           int nbE0 = edges0.Extent(), nbE1 = edges1.Extent();
879           if ( nbE0 != nbE1 )
880             RETURN_BAD_RESULT("Different nb of edges: "<< nbE0 << " != " << nbE1);
881
882           if ( nbE0 == 1 )
883           {
884             TopoDS_Edge e0 = TopoDS::Edge( edges0.First() );
885             TopoDS_Edge e1 = TopoDS::Edge( edges1.First() );
886             v2e[0].UnBind( V[0] );
887             v2e[1].UnBind( V[1] );
888             InsertAssociation( e0, e1, theMap );
889             MESSAGE("Assoc edge " << theMesh1->GetMeshDS()->ShapeToIndex( e0 )<<
890                     " to "        << theMesh2->GetMeshDS()->ShapeToIndex( e1 ));
891             V[0] = GetNextVertex( e0, V[0] );
892             V[1] = GetNextVertex( e1, V[1] );
893             if ( !V[0].IsNull() ) {
894               InsertAssociation( V[0], V[1], theMap );
895               MESSAGE("Assoc vertex " << theMesh1->GetMeshDS()->ShapeToIndex( V[0] )<<
896                       " to "          << theMesh2->GetMeshDS()->ShapeToIndex( V[1] ));
897             }
898           }
899           else if ( nbE0 == 2 )
900           {
901             // one of edges must have both ends bound
902             TopoDS_Vertex v0e0 = GetNextVertex( TopoDS::Edge( edges0.First() ), V[0] );
903             TopoDS_Vertex v1e0 = GetNextVertex( TopoDS::Edge( edges0.Last() ),  V[0] );
904             TopoDS_Vertex v0e1 = GetNextVertex( TopoDS::Edge( edges1.First() ), V[1] );
905             TopoDS_Vertex v1e1 = GetNextVertex( TopoDS::Edge( edges1.Last() ),  V[1] );
906             TopoDS_Shape e0b, e1b, e0n, e1n, v1b; // bound and not-bound
907             TopoDS_Vertex v0n, v1n;
908             if ( theMap.IsBound( v0e0 )) {
909               v0n = v1e0; e0b = edges0.First(); e0n = edges0.Last(); v1b = theMap( v0e0 );
910             } else if ( theMap.IsBound( v1e0 )) {
911               v0n = v0e0; e0n = edges0.First(); e0b = edges0.Last(); v1b = theMap( v1e0 );
912             } else {
913               RETURN_BAD_RESULT("None of vertices bound");
914             }
915             if ( v1b.IsSame( v1e1 )) {
916               v1n = v0e1; e1n = edges1.First(); e1b = edges1.Last();
917             } else {
918               v1n = v1e1; e1b = edges1.First(); e1n = edges1.Last();
919             }
920             InsertAssociation( e0b, e1b, theMap );
921             InsertAssociation( e0n, e1n, theMap );
922             InsertAssociation( v0n, v1n, theMap );
923             MESSAGE("Assoc edge " << theMesh1->GetMeshDS()->ShapeToIndex( e0b )<<
924                     " to "        << theMesh2->GetMeshDS()->ShapeToIndex( e1b ));
925             MESSAGE("Assoc edge " << theMesh1->GetMeshDS()->ShapeToIndex( e0n )<<
926                     " to "        << theMesh2->GetMeshDS()->ShapeToIndex( e1n ));
927             MESSAGE("Assoc vertex " << theMesh1->GetMeshDS()->ShapeToIndex( v0n )<<
928                     " to "          << theMesh2->GetMeshDS()->ShapeToIndex( v1n ));
929             v2e[0].UnBind( V[0] );
930             v2e[1].UnBind( V[1] );
931             V[0] = v0n;
932             V[1] = v1n;
933           }
934           else {
935             RETURN_BAD_RESULT("Not implemented");
936           }
937         }
938       } //while ( !v2e[0].IsEmpty() )
939       return true;
940     }
941
942     default:
943       RETURN_BAD_RESULT("Unexpected shape type");
944
945     } // end switch by shape type
946   } // end case of available initial vertex association
947
948   //======================================================================
949   // 4) NO INITIAL VERTEX ASSOCIATION
950   //======================================================================
951
952   switch ( theShape1.ShapeType() ) {
953
954   case TopAbs_EDGE: {
955     // ----------------------------------------------------------------------
956     TopoDS_Edge edge1 = TopoDS::Edge( theShape1 );
957     TopoDS_Edge edge2 = TopoDS::Edge( theShape2 );
958     if ( IsPropagationPossible( theMesh1, theMesh2 ))
959     {
960       TopoDS_Edge prpEdge = GetPropagationEdge( theMesh1, edge2, edge1 ).second;
961       if ( !prpEdge.IsNull() )
962       {
963         TopoDS_Vertex VV1[2], VV2[2];
964         TopExp::Vertices( edge1,   VV1[0], VV1[1], true );
965         TopExp::Vertices( prpEdge, VV2[0], VV2[1], true );
966         InsertAssociation( VV1[ 0 ], VV2[ 0 ], theMap );
967         InsertAssociation( VV1[ 1 ], VV2[ 1 ], theMap );
968         if ( VV1[0].IsSame( VV1[1] ) || // one of edges is closed
969              VV2[0].IsSame( VV2[1] ) )
970         {
971           InsertAssociation( edge1, prpEdge, theMap ); // insert with a proper orientation
972         }
973         InsertAssociation( theShape1, theShape2, theMap );
974         return true; // done
975       }
976     }
977     if ( SMESH_MesherHelper::IsClosedEdge( edge1 ) &&
978          SMESH_MesherHelper::IsClosedEdge( edge2 ))
979     {
980       // TODO: find out a proper orientation (is it possible?)
981       InsertAssociation( edge1, edge2, theMap ); // insert with a proper orientation
982       InsertAssociation( TopExp::FirstVertex(edge1), TopExp::FirstVertex(edge2),
983                          theMap );
984       InsertAssociation( theShape1, theShape2, theMap );
985       return true; // done
986     }
987     break; // try by vertex closeness
988   }
989
990   case TopAbs_FACE: {
991     // ----------------------------------------------------------------------
992     if ( IsPropagationPossible( theMesh1, theMesh2 )) // try by propagation in one mesh
993     {
994       TopoDS_Face face1 = TopoDS::Face(theShape1);
995       TopoDS_Face face2 = TopoDS::Face(theShape2);
996       if ( face1.Orientation() >= TopAbs_INTERNAL ) face1.Orientation( TopAbs_FORWARD );
997       if ( face2.Orientation() >= TopAbs_INTERNAL ) face2.Orientation( TopAbs_FORWARD );
998       TopoDS_Edge edge1, edge2;
999       // get outer edge of theShape1
1000       TopoDS_Shape wire = OuterShape( face1, TopAbs_WIRE );
1001       //edge1 = TopoDS::Edge( OuterShape( face1, TopAbs_EDGE ));
1002       map<int,TopoDS_Edge> propag_edges; // use map to find the closest propagation edge
1003       for ( TopoDS_Iterator edgeIt( wire ); edgeIt.More(); edgeIt.Next() )
1004       {
1005         edge1 = TopoDS::Edge( edgeIt.Value() );
1006         // find out if any edge of face2 is a propagation edge of outer edge1
1007         for ( TopExp_Explorer exp( face2, TopAbs_EDGE ); exp.More(); exp.Next() ) {
1008           edge2 = TopoDS::Edge( exp.Current() );
1009           pair<int,TopoDS_Edge> step_edge = GetPropagationEdge( theMesh1, edge2, edge1 );
1010           if ( !step_edge.second.IsNull() ) { // propagation found
1011             propag_edges.insert( step_edge );
1012             if ( step_edge.first == 1 ) break; // most close found
1013           }
1014         }
1015         if ( !propag_edges.empty() && propag_edges.begin()->first == 1 ) break;
1016       }
1017       if ( !propag_edges.empty() ) // propagation found
1018       {
1019         edge2 = propag_edges.begin()->second;
1020         TopoDS_Vertex VV1[2], VV2[2];
1021         TopExp::Vertices( edge1, VV1[0], VV1[1], true );
1022         TopExp::Vertices( edge2, VV2[0], VV2[1], true );
1023         list< TopoDS_Edge > edges1, edges2;
1024         int nbE = FindFaceAssociation( face1, VV1, face2, VV2, edges1, edges2 );
1025         if ( !nbE ) RETURN_BAD_RESULT("FindFaceAssociation() failed");
1026         // take care of proper association of propagated edges
1027         bool same1 = edge1.IsSame( edges1.front() );
1028         bool same2 = edge2.IsSame( edges2.front() );
1029         if ( same1 != same2 )
1030         {
1031           Reverse(edges2, nbE);
1032           if ( nbE != 2 ) // 2 degen edges of 4 (issue 0021144)
1033             edges2.splice( edges2.end(), edges2, edges2.begin());
1034         }
1035         // store association
1036         list< TopoDS_Edge >::iterator eIt1 = edges1.begin();
1037         list< TopoDS_Edge >::iterator eIt2 = edges2.begin();
1038         for ( ; eIt1 != edges1.end(); ++eIt1, ++eIt2 )
1039         {
1040           InsertAssociation( *eIt1, *eIt2, theMap );
1041           VV1[0] = TopExp::FirstVertex( *eIt1, true );
1042           VV2[0] = TopExp::FirstVertex( *eIt2, true );
1043           InsertAssociation( VV1[0], VV2[0], theMap );
1044         }
1045         InsertAssociation( theShape1, theShape2, theMap );
1046         return true;
1047       }
1048     }
1049     break; // try by vertex closeness
1050   }
1051   case TopAbs_COMPOUND: {
1052     // ----------------------------------------------------------------------
1053     if ( IsPropagationPossible( theMesh1, theMesh2 )) {
1054
1055       // try to accosiate all using propagation
1056       if ( AssocGroupsByPropagation( theShape1, theShape2, *theMesh1, theMap ))
1057         return true;
1058
1059       // find a boundary edge of theShape1
1060       TopoDS_Edge E = GetBoundaryEdge( theShape1, *theMesh1 );
1061       if ( E.IsNull() )
1062         break; // try by vertex closeness
1063
1064       // find association for vertices of edge E
1065       TopoDS_Vertex VV1[2], VV2[2];
1066       for(TopExp_Explorer eexp(E, TopAbs_VERTEX); eexp.More(); eexp.Next()) {
1067         TopoDS_Vertex V1 = TopoDS::Vertex( eexp.Current() );
1068         // look for an edge ending in E whose one vertex is in theShape1
1069         // and the other, in theShape2
1070         const TopTools_ListOfShape& Ancestors = theMesh1->GetAncestors(V1);
1071         TopTools_ListIteratorOfListOfShape ita(Ancestors);
1072         for(; ita.More(); ita.Next()) {
1073           if( ita.Value().ShapeType() != TopAbs_EDGE ) continue;
1074           TopoDS_Edge edge = TopoDS::Edge(ita.Value());
1075           bool FromShape1 = false;
1076           for(TopExp_Explorer expe(theShape1, TopAbs_EDGE); expe.More(); expe.Next() ) {
1077             if(edge.IsSame(expe.Current())) {
1078               FromShape1 = true;
1079               break;
1080             }
1081           }
1082           if(!FromShape1) {
1083             // is it an edge between theShape1 and theShape2?
1084             TopExp_Explorer expv(edge, TopAbs_VERTEX);
1085             TopoDS_Vertex V2 = TopoDS::Vertex( expv.Current() );
1086             if(V2.IsSame(V1)) {
1087               expv.Next();
1088               V2 = TopoDS::Vertex( expv.Current() );
1089             }
1090             bool FromShape2 = false;
1091             for ( expv.Init( theShape2, TopAbs_VERTEX ); expv.More(); expv.Next()) {
1092               if ( V2.IsSame( expv.Current() )) {
1093                 FromShape2 = true;
1094                 break;
1095               }
1096             }
1097             if ( FromShape2 ) {
1098               if ( VV1[0].IsNull() )
1099                 VV1[0] = V1, VV2[0] = V2;
1100               else
1101                 VV1[1] = V1, VV2[1] = V2;
1102               break; // from loop on ancestors of V1
1103             }
1104           }
1105         }
1106       }
1107       if ( !VV1[1].IsNull() ) {
1108         InsertAssociation( VV1[0], VV2[0], theMap );
1109         InsertAssociation( VV1[1], VV2[1], theMap );
1110         return FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap);
1111       }
1112     }
1113     break; // try by vertex closeness
1114   }
1115   default:;
1116   }
1117
1118   // 4.b) Find association by closeness of vertices
1119   // ----------------------------------------------
1120
1121   TopTools_IndexedMapOfShape vMap1, vMap2;
1122   TopExp::MapShapes( theShape1, TopAbs_VERTEX, vMap1 );
1123   TopExp::MapShapes( theShape2, TopAbs_VERTEX, vMap2 );
1124   TopoDS_Vertex VV1[2], VV2[2];
1125
1126   if ( vMap1.Extent() != vMap2.Extent() )
1127   {
1128     if ( SMESH_MesherHelper:: Count( theShape1, TopAbs_EDGE, /*ignoreSame=*/false ) !=
1129          SMESH_MesherHelper:: Count( theShape2, TopAbs_EDGE, /*ignoreSame=*/false ))
1130       RETURN_BAD_RESULT("Different nb of vertices");
1131   }
1132
1133   if ( vMap1.Extent() == 1 ) {
1134     InsertAssociation( vMap1(1), vMap2(1), theMap );
1135     if ( theShape1.ShapeType() == TopAbs_EDGE ) {
1136       InsertAssociation( theShape1, theShape2, theMap );
1137       return true;
1138     }
1139     return FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap);
1140   }
1141
1142   // Try to associate by common vertices of an edge
1143   for ( int i = 1; i <= vMap1.Extent(); ++i )
1144   {
1145     const TopoDS_Shape& v1 = vMap1(i);
1146     if ( vMap2.Contains( v1 ))
1147     {
1148       // find an egde sharing v1 and sharing at the same time another common vertex
1149       PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( v1, *theMesh1, TopAbs_EDGE);
1150       bool edgeFound = false;
1151       while ( edgeIt->more() && !edgeFound )
1152       {
1153         TopoDS_Edge edge = TopoDS::Edge( edgeIt->next()->Oriented(TopAbs_FORWARD));
1154         TopExp::Vertices(edge, VV1[0], VV1[1]);
1155         if ( !VV1[0].IsSame( VV1[1] ))
1156           edgeFound = ( vMap2.Contains( VV1[ v1.IsSame(VV1[0]) ? 1:0]));
1157       }
1158       if ( edgeFound )
1159       {
1160         InsertAssociation( VV1[0], VV1[0], theMap );
1161         InsertAssociation( VV1[1], VV1[1], theMap );
1162         if (FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap ))
1163           return true;
1164       }
1165     }
1166   }
1167
1168   // Find transformation to make the shapes be of similar size at same location
1169
1170   Bnd_Box box[2];
1171   for ( int i = 1; i <= vMap1.Extent(); ++i )
1172     box[ 0 ].Add( BRep_Tool::Pnt ( TopoDS::Vertex( vMap1( i ))));
1173   for ( int i = 1; i <= vMap2.Extent(); ++i )
1174     box[ 1 ].Add( BRep_Tool::Pnt ( TopoDS::Vertex( vMap2( i ))));
1175
1176   gp_Pnt gc[2]; // box center
1177   double x0,y0,z0, x1,y1,z1;
1178   box[0].Get( x0,y0,z0, x1,y1,z1 );
1179   gc[0] = 0.5 * ( gp_XYZ( x0,y0,z0 ) + gp_XYZ( x1,y1,z1 ));
1180   box[1].Get( x0,y0,z0, x1,y1,z1 );
1181   gc[1] = 0.5 * ( gp_XYZ( x0,y0,z0 ) + gp_XYZ( x1,y1,z1 ));
1182
1183   // 1 -> 2
1184   gp_Vec vec01( gc[0], gc[1] );
1185   double scale = sqrt( box[1].SquareExtent() / box[0].SquareExtent() );
1186
1187   // Find 2 closest vertices
1188
1189   // get 2 linked vertices of shape 1 not belonging to an inner wire of a face
1190   std::list< TopoDS_Edge > allBndEdges1;
1191   if ( !getOuterEdges( theShape1, *theMesh1, allBndEdges1 ))
1192     RETURN_BAD_RESULT("Edge not found");
1193
1194   std::list< TopoDS_Edge >::iterator edge1 = allBndEdges1.begin();
1195   double minDist = std::numeric_limits<double>::max();
1196   for ( int nbChecked=0; edge1 != allBndEdges1.end() && nbChecked++ < 10; ++edge1 )
1197   {
1198     TopExp::Vertices( TopoDS::Edge( edge1->Oriented(TopAbs_FORWARD)), VV1[0], VV1[1]);
1199     if ( VV1[0].IsSame( VV1[1] ))
1200       continue;//RETURN_BAD_RESULT("Only closed edges");
1201
1202     // find vertices closest to 2 linked vertices of shape 1
1203     double dist2[2] = { 1e+100, 1e+100 };
1204     TopoDS_Vertex edge2VV[2];
1205     for ( int i1 = 0; i1 < 2; ++i1 )
1206     {
1207       gp_Pnt p1 = BRep_Tool::Pnt( VV1[ i1 ]);
1208       p1.Scale( gc[0], scale );
1209       p1.Translate( vec01 );
1210       if ( !i1 ) {
1211         // select a closest vertex among all ones in vMap2
1212         for ( int i2 = 1; i2 <= vMap2.Extent(); ++i2 )
1213         {
1214           TopoDS_Vertex V2 = TopoDS::Vertex( vMap2( i2 ));
1215           gp_Pnt        p2 = BRep_Tool::Pnt ( V2 );
1216           double        d2 = p1.SquareDistance( p2 );
1217           if ( d2 < dist2[ 0 ] && d2 < minDist ) {
1218             edge2VV[ 0 ] = V2;
1219             dist2  [ 0 ] = d2;
1220           }
1221         }
1222       }
1223       else if ( !edge2VV[0].IsNull() ) {
1224         // select a closest vertex among ends of edges meeting at edge2VV[0]
1225         PShapeIteratorPtr edgeIt = SMESH_MesherHelper::GetAncestors( edge2VV[0],
1226                                                                      *theMesh2, TopAbs_EDGE);
1227         while ( const TopoDS_Shape* edge2 = edgeIt->next() )
1228           for ( TopoDS_Iterator itV2( *edge2 ); itV2.More(); itV2.Next() )
1229           {
1230             if ( itV2.Value().IsSame( edge2VV[ 0 ])) continue;
1231             if ( !vMap2.Contains( itV2.Value()    )) continue;
1232             TopoDS_Vertex V2 = TopoDS::Vertex( itV2.Value() );
1233             gp_Pnt        p2 = BRep_Tool::Pnt ( V2 );
1234             double        d2 = p1.SquareDistance( p2 );
1235             if ( d2 < dist2[1] && d2 < minDist ) {
1236               edge2VV[ 1 ] = V2;
1237               dist2  [ 1 ] = d2;
1238             }
1239           }
1240       }
1241     }
1242     if ( dist2[0] + dist2[1] < minDist ) {
1243       VV2[0] = edge2VV[0];
1244       VV2[1] = edge2VV[1];
1245       minDist = dist2[0] + dist2[1];
1246       if ( minDist < 1e-10 )
1247         break;
1248     }
1249   }
1250
1251   InsertAssociation( VV1[ 0 ], VV2[ 0 ], theMap );
1252   InsertAssociation( VV1[ 1 ], VV2[ 1 ], theMap );
1253   MESSAGE("Initial assoc VERT " << theMesh1->GetMeshDS()->ShapeToIndex( VV1[ 0 ] )<<
1254           " to "                << theMesh2->GetMeshDS()->ShapeToIndex( VV2[ 0 ] )<<
1255           "\nand         VERT " << theMesh1->GetMeshDS()->ShapeToIndex( VV1[ 1 ] )<<
1256           " to "                << theMesh2->GetMeshDS()->ShapeToIndex( VV2[ 1 ] ));
1257   if ( theShape1.ShapeType() == TopAbs_EDGE ) {
1258     InsertAssociation( theShape1, theShape2, theMap );
1259     return true;
1260   }
1261
1262   return FindSubShapeAssociation( theShape1, theMesh1, theShape2, theMesh2, theMap );
1263 }
1264
1265 //================================================================================
1266 /*!
1267  * \brief Find association of edges of faces
1268  * \param face1 - face 1
1269  * \param VV1 - vertices of face 1
1270  * \param face2 - face 2
1271  * \param VV2 - vertices of face 2 associated with ones of face 1
1272  * \param edges1 - out list of edges of face 1
1273  * \param edges2 - out list of edges of face 2
1274  * \retval int - nb of edges in an outer wire in a success case, else zero
1275  */
1276 //================================================================================
1277
1278 int StdMeshers_ProjectionUtils::FindFaceAssociation(const TopoDS_Face&    face1,
1279                                                     TopoDS_Vertex         VV1[2],
1280                                                     const TopoDS_Face&    face2,
1281                                                     TopoDS_Vertex         VV2[2],
1282                                                     list< TopoDS_Edge > & edges1,
1283                                                     list< TopoDS_Edge > & edges2)
1284 {
1285   bool OK = false;
1286   list< int > nbEInW1, nbEInW2;
1287   list< TopoDS_Edge >::iterator edgeIt;
1288   int i_ok_wire_algo = -1;
1289   for ( int outer_wire_algo = 0; outer_wire_algo < 2 && !OK; ++outer_wire_algo )
1290   {
1291     edges1.clear();
1292     edges2.clear();
1293
1294     if ( SMESH_Block::GetOrderedEdges( face1, edges1, nbEInW1, VV1[0], outer_wire_algo) !=
1295          SMESH_Block::GetOrderedEdges( face2, edges2, nbEInW2, VV2[0], outer_wire_algo) )
1296       CONT_BAD_RESULT("Different number of wires in faces ");
1297
1298     if ( nbEInW1 != nbEInW2 && outer_wire_algo == 0 &&
1299          ( std::accumulate( nbEInW1.begin(), nbEInW1.end(), 0) !=
1300            std::accumulate( nbEInW2.begin(), nbEInW2.end(), 0)))
1301       RETURN_BAD_RESULT("Different number of edges in faces");
1302
1303     if ( nbEInW1.front() != nbEInW2.front() )
1304       CONT_BAD_RESULT("Different number of edges in the outer wire: " <<
1305                       nbEInW1.front() << " != " << nbEInW2.front());
1306
1307     i_ok_wire_algo = outer_wire_algo;
1308
1309     // Define if we need to reverse one of wires to make edges in lists match each other
1310
1311     bool reverse = false;
1312
1313     if ( !VV1[1].IsSame( TopExp::LastVertex( edges1.front(), true ))) {
1314       reverse = true;
1315       edgeIt = --edges1.end();
1316       // check if the second vertex belongs to the first or last edge in the wire
1317       if ( !VV1[1].IsSame( TopExp::FirstVertex( *edgeIt, true ))) {
1318         bool KO = true; // belongs to none
1319         if ( nbEInW1.size() > 1 ) { // several wires
1320           edgeIt = edges1.begin();
1321           std::advance( edgeIt, nbEInW1.front()-1 );
1322           KO = !VV1[1].IsSame( TopExp::FirstVertex( *edgeIt, true ));
1323         }
1324         if ( KO )
1325           CONT_BAD_RESULT("GetOrderedEdges() failed");
1326       }
1327     }
1328     edgeIt = --edges2.end();
1329     if ( !VV2[1].IsSame( TopExp::LastVertex( edges2.front(), true ))) {
1330       reverse = !reverse;
1331       // check if the second vertex belongs to the first or last edge in the wire
1332       if ( !VV2[1].IsSame( TopExp::FirstVertex( *edgeIt, true ))) {
1333         bool KO = true; // belongs to none
1334         if ( nbEInW2.size() > 1 ) { // several wires
1335           edgeIt = edges2.begin();
1336           std::advance( edgeIt, nbEInW2.front()-1 );
1337           KO = !VV2[1].IsSame( TopExp::FirstVertex( *edgeIt, true ));
1338         }
1339         if ( KO )
1340           CONT_BAD_RESULT("GetOrderedEdges() failed");
1341       }
1342     }
1343     if ( reverse )
1344     {
1345       Reverse( edges2 , nbEInW2.front());
1346       if (( VV1[1].IsSame( TopExp::LastVertex( edges1.front(), true ))) !=
1347           ( VV2[1].IsSame( TopExp::LastVertex( edges2.front(), true ))))
1348         CONT_BAD_RESULT("GetOrderedEdges() failed");
1349     }
1350     OK = true;
1351
1352   } // loop algos getting an outer wire
1353   
1354   // Try to orient all (if !OK) or only internal wires (issue 0020996) by UV similarity
1355
1356   if (( !OK || nbEInW1.size() > 1 ) && i_ok_wire_algo > -1 )
1357   {
1358     // Check that Vec(VV1[0],VV1[1]) in 2D on face1 is the same
1359     // as Vec(VV2[0],VV2[1]) on face2
1360     double vTol = BRep_Tool::Tolerance( VV1[0] );
1361     BRepAdaptor_Surface surface1( face1, false );
1362     double vTolUV =
1363       surface1.UResolution( vTol ) + surface1.VResolution( vTol ); // let's be tolerant
1364     gp_Pnt2d v0f1UV = BRep_Tool::Parameters( VV1[0], face1 );
1365     gp_Pnt2d v0f2UV = BRep_Tool::Parameters( VV2[0], face2 );
1366     gp_Pnt2d v1f1UV = BRep_Tool::Parameters( VV1[1], face1 );
1367     gp_Pnt2d v1f2UV = BRep_Tool::Parameters( VV2[1], face2 );
1368     gp_Vec2d v01f1Vec( v0f1UV, v1f1UV );
1369     gp_Vec2d v01f2Vec( v0f2UV, v1f2UV );
1370     if ( Abs( v01f1Vec.X()-v01f2Vec.X()) < vTolUV &&
1371          Abs( v01f1Vec.Y()-v01f2Vec.Y()) < vTolUV )
1372     {
1373       if ( !OK /*i_ok_wire_algo != 1*/ )
1374       {
1375         edges1.clear();
1376         edges2.clear();
1377         SMESH_Block::GetOrderedEdges( face1, edges1, nbEInW1, VV1[0], i_ok_wire_algo);
1378         SMESH_Block::GetOrderedEdges( face2, edges2, nbEInW2, VV2[0], i_ok_wire_algo);
1379       }
1380       gp_XY dUV = v0f2UV.XY() - v0f1UV.XY(); // UV shift between 2 faces
1381       //
1382       // skip edges of the outer wire (if the outer wire is OK)
1383       list< int >::iterator nbE2, nbE1 = nbEInW1.begin();
1384       list< TopoDS_Edge >::iterator edge2Beg, edge1Beg = edges1.begin();
1385       if ( OK ) std::advance( edge1Beg, *nbE1++ );
1386       // reach an end of edges of a current wire1
1387       list< TopoDS_Edge >::iterator edge2End, edge1End;
1388       //
1389       // find corresponding wires of face2
1390       for ( int iW1 = OK; nbE1 != nbEInW1.end(); ++nbE1, ++iW1 ) // loop on wires of face1
1391       {
1392         // reach an end of edges of a current wire1
1393         edge1End = edge1Beg;
1394         std::advance( edge1End, *nbE1 );
1395         // UV on face1 to find on face2
1396         v0f1UV = BRep_Tool::Parameters( TopExp::FirstVertex(*edge1Beg,true), face1 );
1397         v1f1UV = BRep_Tool::Parameters( TopExp::LastVertex (*edge1Beg,true), face1 );
1398         v0f1UV.ChangeCoord() += dUV;
1399         v1f1UV.ChangeCoord() += dUV;
1400         //
1401         // look through wires of face2
1402         edge2Beg = edges2.begin();
1403         nbE2     = nbEInW2.begin();
1404         if ( OK ) std::advance( edge2Beg, *nbE2++ );
1405         for ( int iW2 = OK; nbE2 != nbEInW2.end(); ++nbE2, ++iW2 ) // loop on wires of face2
1406         {
1407           // reach an end of edges of a current wire2
1408           edge2End = edge2Beg;
1409           std::advance( edge2End, *nbE2 );
1410           if ( *nbE1 == *nbE2 && iW2 >= iW1 )
1411           {
1412             // rotate edge2 untill coincidence with edge1 in 2D
1413             int i = *nbE2;
1414             while ( i-- > 0 && !sameVertexUV( *edge2Beg, face2, 0, v0f1UV, vTolUV ))
1415               // move edge2Beg to place before edge2End
1416               edges2.splice( edge2End, edges2, edge2Beg++ );
1417
1418             if ( sameVertexUV( *edge2Beg, face2, 0, v0f1UV, vTolUV ))
1419             {
1420               if ( iW1 == 0 ) OK = true; // OK is for the first wire
1421               // reverse edges2 if needed
1422               if ( !sameVertexUV( *edge2Beg, face2, 1, v1f1UV, vTolUV ))
1423                 Reverse( edges2 , *nbE2, std::distance( edges2.begin(),edge2Beg ));
1424               // put wire2 at a right place within edges2
1425               if ( iW1 != iW2 ) {
1426                 list< TopoDS_Edge >::iterator place2 = edges2.begin();
1427                 std::advance( place2, std::distance( edges1.begin(), edge1Beg ));
1428                 edges2.splice( place2, edges2, edge2Beg, edge2End );
1429                 // move nbE2 as well
1430                 list< int >::iterator placeNbE2 = nbEInW2.begin();
1431                 std::advance( placeNbE2, iW1 );
1432                 nbEInW2.splice( placeNbE2, nbEInW2, nbE2 );
1433               }
1434               break;
1435             }
1436           }
1437           // prepare to the next wire loop
1438           edge2Beg = edge2End;
1439         }
1440         edge1Beg = edge1End;
1441       }
1442     }
1443   }
1444
1445   const int nbEdges = nbEInW1.front();
1446   if ( OK && nbEdges == 2 )
1447   {
1448     // if wires include 2 edges, it's impossible to associate them using
1449     // topological information only. Try to use length of edges for association.
1450     double l1[2], l2[2];
1451     edgeIt = edges1.begin();
1452     l1[0] = SMESH_Algo::EdgeLength( *edgeIt++ );
1453     l1[1] = SMESH_Algo::EdgeLength( *edgeIt++ );
1454     if ( Abs( l1[0] - l1[1] ) > 0.1 * Max( l1[0], l1[1] ) )
1455     {
1456       edgeIt = edges2.begin();
1457       l2[0] = SMESH_Algo::EdgeLength( *edgeIt++ );
1458       l2[1] = SMESH_Algo::EdgeLength( *edgeIt++ );
1459       if (( l1[0] < l1[1] ) != ( l2[0] < l2[1] ))
1460       {
1461         Reverse( edges2, nbEdges );
1462       }
1463     }
1464   }
1465
1466   return OK ? nbEInW1.front() : 0;
1467 }
1468
1469 //=======================================================================
1470 //function : InitVertexAssociation
1471 //purpose  : 
1472 //=======================================================================
1473
1474 void StdMeshers_ProjectionUtils::InitVertexAssociation( const SMESH_Hypothesis* theHyp,
1475                                                         TShapeShapeMap &        theAssociationMap)
1476 {
1477   string hypName = theHyp->GetName();
1478   if ( hypName == "ProjectionSource1D" ) {
1479     const StdMeshers_ProjectionSource1D * hyp =
1480       static_cast<const StdMeshers_ProjectionSource1D*>( theHyp );
1481     if ( hyp->HasVertexAssociation() )
1482       InsertAssociation( hyp->GetTargetVertex(),hyp->GetSourceVertex(),theAssociationMap );
1483   }
1484   else if ( hypName == "ProjectionSource2D" ) {
1485     const StdMeshers_ProjectionSource2D * hyp =
1486       static_cast<const StdMeshers_ProjectionSource2D*>( theHyp );
1487     if ( hyp->HasVertexAssociation() ) {
1488       InsertAssociation( hyp->GetTargetVertex(1),hyp->GetSourceVertex(1),theAssociationMap);
1489       InsertAssociation( hyp->GetTargetVertex(2),hyp->GetSourceVertex(2),theAssociationMap);
1490     }
1491   }
1492   else if ( hypName == "ProjectionSource3D" ) {
1493     const StdMeshers_ProjectionSource3D * hyp =
1494       static_cast<const StdMeshers_ProjectionSource3D*>( theHyp );
1495     if ( hyp->HasVertexAssociation() ) {
1496       InsertAssociation( hyp->GetTargetVertex(1),hyp->GetSourceVertex(1),theAssociationMap);
1497       InsertAssociation( hyp->GetTargetVertex(2),hyp->GetSourceVertex(2),theAssociationMap);
1498     }
1499   }
1500 }
1501
1502 //=======================================================================
1503 /*!
1504  * \brief Inserts association theShape1 <-> theShape2 to TShapeShapeMap
1505  * \param theShape1 - target shape
1506  * \param theShape2 - source shape
1507  * \param theAssociationMap - association map 
1508  * \retval bool - true if there was no association for these shapes before
1509  */
1510 //=======================================================================
1511
1512 bool StdMeshers_ProjectionUtils::InsertAssociation( const TopoDS_Shape& theShape1, // tgt
1513                                                     const TopoDS_Shape& theShape2, // src
1514                                                     TShapeShapeMap &    theAssociationMap)
1515 {
1516   if ( !theShape1.IsNull() && !theShape2.IsNull() ) {
1517     SHOW_SHAPE(theShape1,"Assoc ");
1518     SHOW_SHAPE(theShape2," to ");
1519     bool isNew = ( theAssociationMap.Bind( theShape1, theShape2 ));
1520     return isNew;
1521   }
1522   else {
1523     throw SALOME_Exception("StdMeshers_ProjectionUtils: attempt to associate NULL shape");
1524   }
1525   return false;
1526 }
1527
1528 //=======================================================================
1529 /*!
1530  * \brief Finds an edge by its vertices in a main shape of the mesh
1531  * \param aMesh - the mesh
1532  * \param V1 - vertex 1
1533  * \param V2 - vertex 2
1534  * \retval TopoDS_Edge - found edge
1535  */
1536 //=======================================================================
1537
1538 TopoDS_Edge StdMeshers_ProjectionUtils::GetEdgeByVertices( SMESH_Mesh*          theMesh,
1539                                                            const TopoDS_Vertex& theV1,
1540                                                            const TopoDS_Vertex& theV2)
1541 {
1542   if ( theMesh && !theV1.IsNull() && !theV2.IsNull() )
1543   {
1544     TopTools_ListIteratorOfListOfShape ancestorIt( theMesh->GetAncestors( theV1 ));
1545     for ( ; ancestorIt.More(); ancestorIt.Next() )
1546       if ( ancestorIt.Value().ShapeType() == TopAbs_EDGE )
1547         for ( TopExp_Explorer expV ( ancestorIt.Value(), TopAbs_VERTEX );
1548               expV.More();
1549               expV.Next() )
1550           if ( theV2.IsSame( expV.Current() ))
1551             return TopoDS::Edge( ancestorIt.Value() );
1552   }
1553   return TopoDS_Edge();
1554 }
1555
1556 //================================================================================
1557 /*!
1558  * \brief Return another face sharing an edge
1559  * \param edgeToFaces - data map of descendants to ancestors
1560  * \param edge - edge
1561  * \param face - face
1562  * \retval TopoDS_Face - found face
1563  */
1564 //================================================================================
1565
1566 TopoDS_Face StdMeshers_ProjectionUtils::GetNextFace( const TAncestorMap& edgeToFaces,
1567                                                      const TopoDS_Edge&  edge,
1568                                                      const TopoDS_Face&  face)
1569 {
1570 //   if ( !edge.IsNull() && !face.IsNull() && edgeToFaces.Contains( edge ))
1571   if ( !edge.IsNull() && edgeToFaces.Contains( edge )) // PAL16202
1572   {
1573     TopTools_ListIteratorOfListOfShape ancestorIt( edgeToFaces.FindFromKey( edge ));
1574     for ( ; ancestorIt.More(); ancestorIt.Next() )
1575       if ( ancestorIt.Value().ShapeType() == TopAbs_FACE &&
1576            !face.IsSame( ancestorIt.Value() ))
1577         return TopoDS::Face( ancestorIt.Value() );
1578   }
1579   return TopoDS_Face();
1580 }
1581
1582 //================================================================================
1583 /*!
1584  * \brief Return other vertex of an edge
1585  */
1586 //================================================================================
1587
1588 TopoDS_Vertex StdMeshers_ProjectionUtils::GetNextVertex(const TopoDS_Edge&   edge,
1589                                                         const TopoDS_Vertex& vertex)
1590 {
1591   TopoDS_Vertex vF,vL;
1592   TopExp::Vertices(edge,vF,vL);
1593   if ( vF.IsSame( vL ))
1594     return TopoDS_Vertex();
1595   return vertex.IsSame( vF ) ? vL : vF; 
1596 }
1597
1598 //================================================================================
1599 /*!
1600  * \brief Return a propagation edge
1601  * \param aMesh - mesh
1602  * \param theEdge - edge to find by propagation
1603  * \param fromEdge - start edge for propagation
1604  * \retval pair<int,TopoDS_Edge> - propagation step and found edge
1605  */
1606 //================================================================================
1607
1608 pair<int,TopoDS_Edge>
1609 StdMeshers_ProjectionUtils::GetPropagationEdge( SMESH_Mesh*        aMesh,
1610                                                 const TopoDS_Edge& theEdge,
1611                                                 const TopoDS_Edge& fromEdge)
1612 {
1613   TopTools_IndexedMapOfShape aChain;
1614   int step = 0;
1615
1616   // List of edges, added to chain on the previous cycle pass
1617   TopTools_ListOfShape listPrevEdges;
1618   listPrevEdges.Append(fromEdge);
1619
1620   // Collect all edges pass by pass
1621   while (listPrevEdges.Extent() > 0) {
1622     step++;
1623     // List of edges, added to chain on this cycle pass
1624     TopTools_ListOfShape listCurEdges;
1625
1626     // Find the next portion of edges
1627     TopTools_ListIteratorOfListOfShape itE (listPrevEdges);
1628     for (; itE.More(); itE.Next()) {
1629       TopoDS_Shape anE = itE.Value();
1630
1631       // Iterate on faces, having edge <anE>
1632       TopTools_ListIteratorOfListOfShape itA (aMesh->GetAncestors(anE));
1633       for (; itA.More(); itA.Next()) {
1634         TopoDS_Shape aW = itA.Value();
1635
1636         // There are objects of different type among the ancestors of edge
1637         if (aW.ShapeType() == TopAbs_WIRE) {
1638           TopoDS_Shape anOppE;
1639
1640           BRepTools_WireExplorer aWE (TopoDS::Wire(aW));
1641           Standard_Integer nb = 1, found = 0;
1642           TopTools_Array1OfShape anEdges (1,4);
1643           for (; aWE.More(); aWE.Next(), nb++) {
1644             if (nb > 4) {
1645               found = 0;
1646               break;
1647             }
1648             anEdges(nb) = aWE.Current();
1649             if (anEdges(nb).IsSame(anE)) found = nb;
1650           }
1651
1652           if (nb == 5 && found > 0) {
1653             // Quadrangle face found, get an opposite edge
1654             Standard_Integer opp = found + 2;
1655             if (opp > 4) opp -= 4;
1656             anOppE = anEdges(opp);
1657
1658             // add anOppE to aChain if ...
1659             if (!aChain.Contains(anOppE)) { // ... anOppE is not in aChain
1660               // Add found edge to the chain oriented so that to
1661               // have it co-directed with a forward MainEdge
1662               TopAbs_Orientation ori = anE.Orientation();
1663               if ( anEdges(opp).Orientation() == anEdges(found).Orientation() )
1664                 ori = TopAbs::Reverse( ori );
1665               anOppE.Orientation( ori );
1666               if ( anOppE.IsSame( theEdge ))
1667                 return make_pair( step, TopoDS::Edge( anOppE ));
1668               aChain.Add(anOppE);
1669               listCurEdges.Append(anOppE);
1670             }
1671           } // if (nb == 5 && found > 0)
1672         } // if (aF.ShapeType() == TopAbs_WIRE)
1673       } // for (; itF.More(); itF.Next())
1674     } // for (; itE.More(); itE.Next())
1675
1676     listPrevEdges = listCurEdges;
1677   } // while (listPrevEdges.Extent() > 0)
1678
1679   return make_pair( INT_MAX, TopoDS_Edge());
1680 }
1681
1682 //================================================================================
1683   /*!
1684    * \brief Find corresponding nodes on two faces
1685     * \param face1 - the first face
1686     * \param mesh1 - mesh containing elements on the first face
1687     * \param face2 - the second face
1688     * \param mesh2 - mesh containing elements on the second face
1689     * \param assocMap - map associating sub-shapes of the faces
1690     * \param node1To2Map - map containing found matching nodes
1691     * \retval bool - is a success
1692    */
1693 //================================================================================
1694
1695 bool StdMeshers_ProjectionUtils::
1696 FindMatchingNodesOnFaces( const TopoDS_Face&     face1,
1697                           SMESH_Mesh*            mesh1,
1698                           const TopoDS_Face&     face2,
1699                           SMESH_Mesh*            mesh2,
1700                           const TShapeShapeMap & assocMap,
1701                           TNodeNodeMap &         node1To2Map)
1702 {
1703   SMESHDS_Mesh* meshDS1 = mesh1->GetMeshDS();
1704   SMESHDS_Mesh* meshDS2 = mesh2->GetMeshDS();
1705   
1706   SMESH_MesherHelper helper1( *mesh1 );
1707   SMESH_MesherHelper helper2( *mesh2 );
1708
1709   // Get corresponding submeshes and roughly check match of meshes
1710
1711   SMESHDS_SubMesh * SM2 = meshDS2->MeshElements( face2 );
1712   SMESHDS_SubMesh * SM1 = meshDS1->MeshElements( face1 );
1713   if ( !SM2 || !SM1 )
1714     RETURN_BAD_RESULT("Empty submeshes");
1715   if ( SM2->NbNodes()    != SM1->NbNodes() ||
1716        SM2->NbElements() != SM1->NbElements() )
1717     RETURN_BAD_RESULT("Different meshes on corresponding faces "
1718                       << meshDS1->ShapeToIndex( face1 ) << " and "
1719                       << meshDS2->ShapeToIndex( face2 ));
1720   if ( SM2->NbElements() == 0 )
1721     RETURN_BAD_RESULT("Empty submeshes");
1722
1723   helper1.SetSubShape( face1 );
1724   helper2.SetSubShape( face2 );
1725   if ( helper1.HasSeam() != helper2.HasSeam() )
1726     RETURN_BAD_RESULT("Different faces' geometry");
1727
1728   // Data to call SMESH_MeshEditor::FindMatchingNodes():
1729
1730   // 1. Nodes of corresponding links:
1731
1732   // get 2 matching edges, try to find not seam ones
1733   TopoDS_Edge edge1, edge2, seam1, seam2, anyEdge1, anyEdge2;
1734   TopExp_Explorer eE( OuterShape( face2, TopAbs_WIRE ), TopAbs_EDGE );
1735   do {
1736     // edge 2
1737     TopoDS_Edge e2 = TopoDS::Edge( eE.Current() );
1738     eE.Next();
1739     // edge 1
1740     if ( !assocMap.IsBound( e2, /*is2nd=*/true ))
1741       RETURN_BAD_RESULT("Association not found for edge " << meshDS2->ShapeToIndex( e2 ));
1742     TopoDS_Edge e1 = TopoDS::Edge( assocMap( e2, /*is2nd=*/true ));
1743     if ( !helper1.IsSubShape( e1, face1 ))
1744       RETURN_BAD_RESULT("Wrong association, edge " << meshDS1->ShapeToIndex( e1 ) <<
1745                         " isn't a sub-shape of face " << meshDS1->ShapeToIndex( face1 ));
1746     // check that there are nodes on edges
1747     SMESHDS_SubMesh * eSM1 = meshDS1->MeshElements( e1 );
1748     SMESHDS_SubMesh * eSM2 = meshDS2->MeshElements( e2 );
1749     bool nodesOnEdges = ( eSM1 && eSM2 && eSM1->NbNodes() && eSM2->NbNodes() );
1750     // check that the nodes on edges belong to faces
1751     // (as NETGEN ignores nodes on the degenerated geom edge)
1752     bool nodesOfFaces = false;
1753     if ( nodesOnEdges ) {
1754       const SMDS_MeshNode* n1 = eSM1->GetNodes()->next();
1755       const SMDS_MeshNode* n2 = eSM2->GetNodes()->next();
1756       nodesOfFaces = ( n1->GetInverseElementIterator(SMDSAbs_Face)->more() &&
1757                        n2->GetInverseElementIterator(SMDSAbs_Face)->more() );
1758     }
1759     if ( nodesOfFaces )
1760     {
1761       if ( helper2.IsRealSeam( e2 )) {
1762         seam1 = e1; seam2 = e2;
1763       }
1764       else {
1765         edge1 = e1; edge2 = e2;
1766       }
1767     }
1768     else {
1769       anyEdge1 = e1; anyEdge2 = e2;
1770     }
1771   } while ( edge2.IsNull() && eE.More() );
1772   //
1773   if ( edge2.IsNull() ) {
1774     edge1 = seam1; edge2 = seam2;
1775   }
1776   bool hasNodesOnEdge = (! edge2.IsNull() );
1777   if ( !hasNodesOnEdge ) {
1778     // 0020338 - nb segments == 1
1779     edge1 = anyEdge1; edge2 = anyEdge2;
1780   }
1781
1782   // get 2 matching vertices
1783   TopoDS_Vertex V2 = TopExp::FirstVertex( TopoDS::Edge( edge2 ));
1784   if ( !assocMap.IsBound( V2, /*is2nd=*/true ))
1785     RETURN_BAD_RESULT("Association not found for vertex " << meshDS2->ShapeToIndex( V2 ));
1786   TopoDS_Vertex V1 = TopoDS::Vertex( assocMap( V2, /*is2nd=*/true ));
1787
1788   // nodes on vertices
1789   const SMDS_MeshNode* vNode1 = SMESH_Algo::VertexNode( V1, meshDS1 );
1790   const SMDS_MeshNode* vNode2 = SMESH_Algo::VertexNode( V2, meshDS2 );
1791   if ( !vNode1 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS1->ShapeToIndex( V1 ));
1792   if ( !vNode2 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS2->ShapeToIndex( V2 ));
1793
1794   // nodes on edges linked with nodes on vertices
1795   const SMDS_MeshNode* nullNode = 0;
1796   vector< const SMDS_MeshNode*> eNode1( 2, nullNode );
1797   vector< const SMDS_MeshNode*> eNode2( 2, nullNode );
1798   if ( hasNodesOnEdge )
1799   {
1800     int nbNodeToGet = 1;
1801     if ( helper1.IsClosedEdge( edge1 ) || helper2.IsClosedEdge( edge2 ) )
1802       nbNodeToGet = 2;
1803     for ( int is2 = 0; is2 < 2; ++is2 )
1804     {
1805       TopoDS_Edge &     edge  = is2 ? edge2 : edge1;
1806       SMESHDS_Mesh *    smDS  = is2 ? meshDS2 : meshDS1;
1807       SMESHDS_SubMesh* edgeSM = smDS->MeshElements( edge );
1808       // nodes linked with ones on vertices
1809       const SMDS_MeshNode*           vNode = is2 ? vNode2 : vNode1;
1810       vector< const SMDS_MeshNode*>& eNode = is2 ? eNode2 : eNode1;
1811       int nbGotNode = 0;
1812       SMDS_ElemIteratorPtr vElem = vNode->GetInverseElementIterator(SMDSAbs_Edge);
1813       while ( vElem->more() && nbGotNode != nbNodeToGet ) {
1814         const SMDS_MeshElement* elem = vElem->next();
1815         if ( edgeSM->Contains( elem ))
1816           eNode[ nbGotNode++ ] = 
1817             ( elem->GetNode(0) == vNode ) ? elem->GetNode(1) : elem->GetNode(0);
1818       }
1819       if ( nbGotNode > 1 ) // sort found nodes by param on edge
1820       {
1821         SMESH_MesherHelper* helper = is2 ? &helper2 : &helper1;
1822         double u0 = helper->GetNodeU( edge, eNode[ 0 ]);
1823         double u1 = helper->GetNodeU( edge, eNode[ 1 ]);
1824         if ( u0 > u1 ) std::swap( eNode[ 0 ], eNode[ 1 ]);
1825       }
1826       if ( nbGotNode == 0 )
1827         RETURN_BAD_RESULT("Found no nodes on edge " << smDS->ShapeToIndex( edge ) <<
1828                           " linked to " << vNode );
1829     }
1830   }
1831   else // 0020338 - nb segments == 1
1832   {
1833     // get 2 other matching vertices
1834     V2 = TopExp::LastVertex( TopoDS::Edge( edge2 ));
1835     if ( !assocMap.IsBound( V2, /*is2nd=*/true ))
1836       RETURN_BAD_RESULT("Association not found for vertex " << meshDS2->ShapeToIndex( V2 ));
1837     V1 = TopoDS::Vertex( assocMap( V2, /*is2nd=*/true ));
1838
1839     // nodes on vertices
1840     eNode1[0] = SMESH_Algo::VertexNode( V1, meshDS1 );
1841     eNode2[0] = SMESH_Algo::VertexNode( V2, meshDS2 );
1842     if ( !eNode1[0] ) RETURN_BAD_RESULT("No node on vertex #" << meshDS1->ShapeToIndex( V1 ));
1843     if ( !eNode2[0] ) RETURN_BAD_RESULT("No node on vertex #" << meshDS2->ShapeToIndex( V2 ));
1844   }
1845
1846   // 2. face sets
1847
1848   set<const SMDS_MeshElement*> Elems1, Elems2;
1849   for ( int is2 = 0; is2 < 2; ++is2 )
1850   {
1851     set<const SMDS_MeshElement*> & elems = is2 ? Elems2 : Elems1;
1852     SMESHDS_SubMesh*                  sm = is2 ? SM2 : SM1;
1853     SMESH_MesherHelper*           helper = is2 ? &helper2 : &helper1;
1854     const TopoDS_Face &             face = is2 ? face2 : face1;
1855     SMDS_ElemIteratorPtr eIt = sm->GetElements();
1856
1857     if ( !helper->IsRealSeam( is2 ? edge2 : edge1 ))
1858     {
1859       while ( eIt->more() ) elems.insert( eIt->next() );
1860     }
1861     else
1862     {
1863       // the only suitable edge is seam, i.e. it is a sphere.
1864       // FindMatchingNodes() will not know which way to go from any edge.
1865       // So we ignore all faces having nodes on edges or vertices except
1866       // one of faces sharing current start nodes
1867
1868       // find a face to keep
1869       const SMDS_MeshElement* faceToKeep = 0;
1870       const SMDS_MeshNode* vNode = is2 ? vNode2 : vNode1;
1871       const SMDS_MeshNode* eNode = is2 ? eNode2[0] : eNode1[0];
1872       TIDSortedElemSet inSet, notInSet;
1873
1874       const SMDS_MeshElement* f1 =
1875         SMESH_MeshEditor::FindFaceInSet( vNode, eNode, inSet, notInSet );
1876       if ( !f1 ) RETURN_BAD_RESULT("The first face on seam not found");
1877       notInSet.insert( f1 );
1878
1879       const SMDS_MeshElement* f2 =
1880         SMESH_MeshEditor::FindFaceInSet( vNode, eNode, inSet, notInSet );
1881       if ( !f2 ) RETURN_BAD_RESULT("The second face on seam not found");
1882
1883       // select a face with less UV of vNode
1884       const SMDS_MeshNode* notSeamNode[2] = {0, 0};
1885       for ( int iF = 0; iF < 2; ++iF ) {
1886         const SMDS_MeshElement* f = ( iF ? f2 : f1 );
1887         for ( int i = 0; !notSeamNode[ iF ] && i < f->NbNodes(); ++i ) {
1888           const SMDS_MeshNode* node = f->GetNode( i );
1889           if ( !helper->IsSeamShape( node->getshapeId() ))
1890             notSeamNode[ iF ] = node;
1891         }
1892       }
1893       gp_Pnt2d uv1 = helper->GetNodeUV( face, vNode, notSeamNode[0] );
1894       gp_Pnt2d uv2 = helper->GetNodeUV( face, vNode, notSeamNode[1] );
1895       if ( uv1.X() + uv1.Y() > uv2.X() + uv2.Y() )
1896         faceToKeep = f2;
1897       else
1898         faceToKeep = f1;
1899
1900       // fill elem set
1901       elems.insert( faceToKeep );
1902       while ( eIt->more() ) {
1903         const SMDS_MeshElement* f = eIt->next();
1904         int nbNodes = f->NbNodes();
1905         if ( f->IsQuadratic() )
1906           nbNodes /= 2;
1907         bool onBnd = false;
1908         for ( int i = 0; !onBnd && i < nbNodes; ++i ) {
1909           const SMDS_MeshNode* node = f->GetNode( i );
1910           onBnd = ( node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE);
1911         }
1912         if ( !onBnd )
1913           elems.insert( f );
1914       }
1915       // add also faces adjacent to faceToKeep
1916       int nbNodes = faceToKeep->NbNodes();
1917       if ( faceToKeep->IsQuadratic() ) nbNodes /= 2;
1918       notInSet.insert( f1 );
1919       notInSet.insert( f2 );
1920       for ( int i = 0; i < nbNodes; ++i ) {
1921         const SMDS_MeshNode* n1 = faceToKeep->GetNode( i );
1922         const SMDS_MeshNode* n2 = faceToKeep->GetNode(( i+1 ) % nbNodes );
1923         f1 = SMESH_MeshEditor::FindFaceInSet( n1, n2, inSet, notInSet );
1924         if ( f1 )
1925           elems.insert( f1 );
1926       }
1927     } // case on a sphere
1928   } // loop on 2 faces
1929
1930   //  int quadFactor = (*Elems1.begin())->IsQuadratic() ? 2 : 1;
1931
1932   node1To2Map.clear();
1933   int res = SMESH_MeshEditor::FindMatchingNodes( Elems1, Elems2,
1934                                                  vNode1, vNode2,
1935                                                  eNode1[0], eNode2[0],
1936                                                  node1To2Map);
1937   if ( res != SMESH_MeshEditor::SEW_OK )
1938     RETURN_BAD_RESULT("FindMatchingNodes() result " << res );
1939
1940   // On a sphere, add matching nodes on the edge
1941
1942   if ( helper1.IsRealSeam( edge1 ))
1943   {
1944     // sort nodes on edges by param on edge
1945     map< double, const SMDS_MeshNode* > u2nodesMaps[2];
1946     for ( int is2 = 0; is2 < 2; ++is2 )
1947     {
1948       TopoDS_Edge &     edge  = is2 ? edge2 : edge1;
1949       SMESHDS_Mesh *    smDS  = is2 ? meshDS2 : meshDS1;
1950       SMESHDS_SubMesh* edgeSM = smDS->MeshElements( edge );
1951       map< double, const SMDS_MeshNode* > & pos2nodes = u2nodesMaps[ is2 ];
1952
1953       SMDS_NodeIteratorPtr nIt = edgeSM->GetNodes();
1954       while ( nIt->more() ) {
1955         const SMDS_MeshNode* node = nIt->next();
1956         const SMDS_EdgePosition* pos =
1957           static_cast<const SMDS_EdgePosition*>(node->GetPosition());
1958         pos2nodes.insert( make_pair( pos->GetUParameter(), node ));
1959       }
1960       if ( pos2nodes.size() != edgeSM->NbNodes() )
1961         RETURN_BAD_RESULT("Equal params of nodes on edge "
1962                           << smDS->ShapeToIndex( edge ) << " of face " << is2 );
1963     }
1964     if ( u2nodesMaps[0].size() != u2nodesMaps[1].size() )
1965       RETURN_BAD_RESULT("Different nb of new nodes on edges or wrong params");
1966
1967     // compare edge orientation
1968     double u1 = helper1.GetNodeU( edge1, vNode1 );
1969     double u2 = helper2.GetNodeU( edge2, vNode2 );
1970     bool isFirst1 = ( u1 < u2nodesMaps[0].begin()->first );
1971     bool isFirst2 = ( u2 < u2nodesMaps[1].begin()->first );
1972     bool reverse ( isFirst1 != isFirst2 );
1973
1974     // associate matching nodes
1975     map< double, const SMDS_MeshNode* >::iterator u_Node1, u_Node2, end1;
1976     map< double, const SMDS_MeshNode* >::reverse_iterator uR_Node2;
1977     u_Node1 = u2nodesMaps[0].begin();
1978     u_Node2 = u2nodesMaps[1].begin();
1979     uR_Node2 = u2nodesMaps[1].rbegin();
1980     end1 = u2nodesMaps[0].end();
1981     for ( ; u_Node1 != end1; ++u_Node1 ) {
1982       const SMDS_MeshNode* n1 = u_Node1->second;
1983       const SMDS_MeshNode* n2 = ( reverse ? (uR_Node2++)->second : (u_Node2++)->second );
1984       node1To2Map.insert( make_pair( n1, n2 ));
1985     }
1986
1987     // associate matching nodes on the last vertices
1988     V2 = TopExp::LastVertex( TopoDS::Edge( edge2 ));
1989     if ( !assocMap.IsBound( V2, /*is2nd=*/true ))
1990       RETURN_BAD_RESULT("Association not found for vertex " << meshDS2->ShapeToIndex( V2 ));
1991     V1 = TopoDS::Vertex( assocMap( V2, /*is2nd=*/true ));
1992     vNode1 = SMESH_Algo::VertexNode( V1, meshDS1 );
1993     vNode2 = SMESH_Algo::VertexNode( V2, meshDS2 );
1994     if ( !vNode1 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS1->ShapeToIndex( V1 ));
1995     if ( !vNode2 ) RETURN_BAD_RESULT("No node on vertex #" << meshDS2->ShapeToIndex( V2 ));
1996     node1To2Map.insert( make_pair( vNode1, vNode2 ));
1997   }
1998
1999 // don't know why this condition is usually true :(
2000 //   if ( node1To2Map.size() * quadFactor < SM1->NbNodes() )
2001 //     MESSAGE("FindMatchingNodes() found too few node pairs starting from nodes ("
2002 //             << vNode1->GetID() << " - " << eNode1[0]->GetID() << ") ("
2003 //             << vNode2->GetID() << " - " << eNode2[0]->GetID() << "):"
2004 //             << node1To2Map.size() * quadFactor << " < " << SM1->NbNodes());
2005   
2006   return true;
2007 }
2008
2009 //================================================================================
2010   /*!
2011    * \brief Return any sub-shape of a face belonging to the outer wire
2012     * \param face - the face
2013     * \param type - type of sub-shape to return
2014     * \retval TopoDS_Shape - the found sub-shape
2015    */
2016 //================================================================================
2017
2018 TopoDS_Shape StdMeshers_ProjectionUtils::OuterShape( const TopoDS_Face& face,
2019                                                      TopAbs_ShapeEnum   type)
2020 {
2021   TopExp_Explorer exp( BRepTools::OuterWire( face ), type );
2022   if ( exp.More() )
2023     return exp.Current();
2024   return TopoDS_Shape();
2025 }
2026
2027 //================================================================================
2028   /*!
2029    * \brief Check that submesh is computed and try to compute it if is not
2030     * \param sm - submesh to compute
2031     * \param iterationNb - int used to stop infinite recursive call
2032     * \retval bool - true if computed
2033    */
2034 //================================================================================
2035
2036 bool StdMeshers_ProjectionUtils::MakeComputed(SMESH_subMesh * sm, const int iterationNb)
2037 {
2038   if ( iterationNb > 10 )
2039     RETURN_BAD_RESULT("Infinite recursive projection");
2040   if ( !sm )
2041     RETURN_BAD_RESULT("NULL submesh");
2042   if ( sm->IsMeshComputed() )
2043     return true;
2044
2045   SMESH_Mesh* mesh = sm->GetFather();
2046   SMESH_Gen* gen   = mesh->GetGen();
2047   SMESH_Algo* algo = sm->GetAlgo();
2048   if ( !algo )
2049   {
2050     if ( sm->GetSubShape().ShapeType() != TopAbs_COMPOUND )
2051       RETURN_BAD_RESULT("No algo assigned to submesh " << sm->GetId());
2052     // group
2053     bool computed = true;
2054     for ( TopoDS_Iterator grMember( sm->GetSubShape() ); grMember.More(); grMember.Next())
2055       if ( SMESH_subMesh* grSub = mesh->GetSubMesh( grMember.Value() ))
2056         if ( !MakeComputed( grSub, iterationNb + 1 ))
2057           computed = false;
2058     return computed;
2059   }
2060
2061   string algoType = algo->GetName();
2062   if ( algoType.substr(0, 11) != "Projection_")
2063     return gen->Compute( *mesh, sm->GetSubShape() );
2064
2065   // try to compute source mesh
2066
2067   const list <const SMESHDS_Hypothesis *> & hyps =
2068     algo->GetUsedHypothesis( *mesh, sm->GetSubShape() );
2069
2070   TopoDS_Shape srcShape;
2071   SMESH_Mesh* srcMesh = 0;
2072   list <const SMESHDS_Hypothesis*>::const_iterator hIt = hyps.begin();
2073   for ( ; srcShape.IsNull() && hIt != hyps.end(); ++hIt ) {
2074     string hypName = (*hIt)->GetName();
2075     if ( hypName == "ProjectionSource1D" ) {
2076       const StdMeshers_ProjectionSource1D * hyp =
2077         static_cast<const StdMeshers_ProjectionSource1D*>( *hIt );
2078       srcShape = hyp->GetSourceEdge();
2079       srcMesh = hyp->GetSourceMesh();
2080     }
2081     else if ( hypName == "ProjectionSource2D" ) {
2082       const StdMeshers_ProjectionSource2D * hyp =
2083         static_cast<const StdMeshers_ProjectionSource2D*>( *hIt );
2084       srcShape = hyp->GetSourceFace();
2085       srcMesh = hyp->GetSourceMesh();
2086     }
2087     else if ( hypName == "ProjectionSource3D" ) {
2088       const StdMeshers_ProjectionSource3D * hyp =
2089         static_cast<const StdMeshers_ProjectionSource3D*>( *hIt );
2090       srcShape = hyp->GetSource3DShape();
2091       srcMesh = hyp->GetSourceMesh();
2092     }
2093   }
2094   if ( srcShape.IsNull() ) // no projection source defined
2095     return gen->Compute( *mesh, sm->GetSubShape() );
2096
2097   if ( srcShape.IsSame( sm->GetSubShape() ))
2098     RETURN_BAD_RESULT("Projection from self");
2099     
2100   if ( !srcMesh )
2101     srcMesh = mesh;
2102
2103   if ( MakeComputed( srcMesh->GetSubMesh( srcShape ), iterationNb + 1 ) &&
2104        gen->Compute( *mesh, sm->GetSubShape() ))
2105     return sm->IsMeshComputed();
2106
2107   return false;
2108 }
2109
2110 //================================================================================
2111 /*!
2112  * \brief Return a boundary EDGE (or all boundary EDGEs) of edgeContainer
2113  */
2114 //================================================================================
2115
2116 TopoDS_Edge StdMeshers_ProjectionUtils::GetBoundaryEdge(const TopoDS_Shape&       edgeContainer,
2117                                                         const SMESH_Mesh&         mesh,
2118                                                         std::list< TopoDS_Edge >* allBndEdges)
2119 {
2120   TopTools_IndexedMapOfShape facesOfEdgeContainer, facesNearEdge;
2121   TopExp::MapShapes( edgeContainer, TopAbs_FACE, facesOfEdgeContainer );
2122
2123   if ( !facesOfEdgeContainer.IsEmpty() ) 
2124     for ( TopExp_Explorer exp(edgeContainer, TopAbs_EDGE); exp.More(); exp.Next() )
2125     {
2126       const TopoDS_Edge& edge = TopoDS::Edge( exp.Current() );
2127       facesNearEdge.Clear();
2128       PShapeIteratorPtr faceIt = SMESH_MesherHelper::GetAncestors( edge, mesh, TopAbs_FACE );
2129       while ( const TopoDS_Shape* face = faceIt->next() )
2130         if ( facesOfEdgeContainer.Contains( *face ))
2131           if ( facesNearEdge.Add( *face ) && facesNearEdge.Extent() > 1 )
2132             break;
2133       if ( facesNearEdge.Extent() == 1 ) {
2134         if ( allBndEdges )
2135           allBndEdges->push_back( edge );
2136         else
2137           return edge;
2138       }
2139     }
2140
2141   return TopoDS_Edge();
2142 }
2143
2144
2145 namespace { // Definition of event listeners
2146
2147   SMESH_subMeshEventListener* GetSrcSubMeshListener();
2148
2149   //================================================================================
2150   /*!
2151    * \brief Listener that resets an event listener on source submesh when 
2152    * "ProjectionSource*D" hypothesis is modified
2153    */
2154   //================================================================================
2155
2156   struct HypModifWaiter: SMESH_subMeshEventListener
2157   {
2158     HypModifWaiter():SMESH_subMeshEventListener(false,// won't be deleted by submesh
2159                                                 "StdMeshers_ProjectionUtils::HypModifWaiter") {}
2160     void ProcessEvent(const int event, const int eventType, SMESH_subMesh* subMesh,
2161                       EventListenerData*, const SMESH_Hypothesis*)
2162     {
2163       if ( event     == SMESH_subMesh::MODIF_HYP &&
2164            eventType == SMESH_subMesh::ALGO_EVENT)
2165       {
2166         // delete current source listener
2167         subMesh->DeleteEventListener( GetSrcSubMeshListener() );
2168         // let algo set a new one
2169         if ( SMESH_Algo* algo = subMesh->GetAlgo() )
2170           algo->SetEventListener( subMesh );
2171       }
2172     }
2173   };
2174   //================================================================================
2175   /*!
2176    * \brief return static HypModifWaiter
2177    */
2178   //================================================================================
2179
2180   SMESH_subMeshEventListener* GetHypModifWaiter() {
2181     static HypModifWaiter aHypModifWaiter;
2182     return &aHypModifWaiter;
2183   }
2184   //================================================================================
2185   /*!
2186    * \brief return static listener for source shape submeshes
2187    */
2188   //================================================================================
2189
2190   SMESH_subMeshEventListener* GetSrcSubMeshListener() {
2191     static SMESH_subMeshEventListener srcListener(false, // won't be deleted by submesh
2192                                                   "StdMeshers_ProjectionUtils::SrcSubMeshListener");
2193     return &srcListener;
2194   }
2195 }
2196
2197 //================================================================================
2198 /*!
2199  * \brief Set event listeners to submesh with projection algo
2200  * \param subMesh - submesh with projection algo
2201  * \param srcShape - source shape
2202  * \param srcMesh - source mesh
2203  */
2204 //================================================================================
2205
2206 void StdMeshers_ProjectionUtils::SetEventListener(SMESH_subMesh* subMesh,
2207                                                   TopoDS_Shape   srcShape,
2208                                                   SMESH_Mesh*    srcMesh)
2209 {
2210   // Set the listener that resets an event listener on source submesh when
2211   // "ProjectionSource*D" hypothesis is modified since source shape can be changed
2212   subMesh->SetEventListener( GetHypModifWaiter(),0,subMesh);
2213
2214   // Set an event listener to submesh of the source shape
2215   if ( !srcShape.IsNull() )
2216   {
2217     if ( !srcMesh )
2218       srcMesh = subMesh->GetFather();
2219
2220     SMESH_subMesh* srcShapeSM = srcMesh->GetSubMesh( srcShape );
2221
2222     if ( srcShapeSM != subMesh ) {
2223       if ( srcShapeSM->GetSubMeshDS() &&
2224            srcShapeSM->GetSubMeshDS()->IsComplexSubmesh() )
2225       {  // source shape is a group
2226         TopExp_Explorer it(srcShapeSM->GetSubShape(), // explore the group into sub-shapes...
2227                            subMesh->GetSubShape().ShapeType()); // ...of target shape type
2228         for (; it.More(); it.Next())
2229         {
2230           SMESH_subMesh* srcSM = srcMesh->GetSubMesh( it.Current() );
2231           if ( srcSM != subMesh )
2232           {
2233             SMESH_subMeshEventListenerData* data =
2234               srcSM->GetEventListenerData(GetSrcSubMeshListener());
2235             if ( data )
2236               data->mySubMeshes.push_back( subMesh );
2237             else
2238               data = SMESH_subMeshEventListenerData::MakeData( subMesh );
2239             subMesh->SetEventListener ( GetSrcSubMeshListener(), data, srcSM );
2240           }
2241         }
2242       }
2243       else
2244       {
2245         subMesh->SetEventListener( GetSrcSubMeshListener(),
2246                                    SMESH_subMeshEventListenerData::MakeData( subMesh ),
2247                                    srcShapeSM );
2248       }
2249     }
2250   }
2251 }