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