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