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