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