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