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