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