Salome HOME
Fix regressions bugs_14/P9 (Prism 3D) and bugs_19/X1 (Projection 2D)
[modules/smesh.git] / src / StdMeshers / StdMeshers_Projection_2D.cxx
1 // Copyright (C) 2007-2015  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  SMESH SMESH : implementaion of SMESH idl descriptions
24 // File      : StdMeshers_Projection_2D.cxx
25 // Module    : SMESH
26 // Created   : Fri Oct 20 11:37:07 2006
27 // Author    : Edward AGAPOV (eap)
28 //
29 #include "StdMeshers_Projection_2D.hxx"
30
31 #include "StdMeshers_ProjectionSource2D.hxx"
32 #include "StdMeshers_ProjectionUtils.hxx"
33 #include "StdMeshers_FaceSide.hxx"
34
35 #include "SMDS_EdgePosition.hxx"
36 #include "SMDS_FacePosition.hxx"
37 #include "SMESHDS_Hypothesis.hxx"
38 #include "SMESHDS_SubMesh.hxx"
39 #include "SMESH_Block.hxx"
40 #include "SMESH_Comment.hxx"
41 #include "SMESH_Gen.hxx"
42 #include "SMESH_Mesh.hxx"
43 #include "SMESH_MesherHelper.hxx"
44 #include "SMESH_Pattern.hxx"
45 #include "SMESH_subMesh.hxx"
46 #include "SMESH_subMeshEventListener.hxx"
47
48 #include "utilities.h"
49
50 #include <BRepAdaptor_Surface.hxx>
51 #include <BRep_Tool.hxx>
52 #include <Bnd_B2d.hxx>
53 #include <GeomAPI_ProjectPointOnSurf.hxx>
54 #include <GeomLib_IsPlanarSurface.hxx>
55 #include <TopExp.hxx>
56 #include <TopExp_Explorer.hxx>
57 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
58 #include <TopTools_ListIteratorOfListOfShape.hxx>
59 #include <TopTools_MapOfShape.hxx>
60 #include <TopoDS.hxx>
61 #include <TopoDS_Solid.hxx>
62 #include <gp_Ax2.hxx>
63 #include <gp_Ax3.hxx>
64 #include <gp_GTrsf.hxx>
65
66
67 using namespace std;
68
69 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
70
71 namespace TAssocTool = StdMeshers_ProjectionUtils;
72 //typedef StdMeshers_ProjectionUtils TAssocTool;
73
74 //=======================================================================
75 //function : StdMeshers_Projection_2D
76 //purpose  : 
77 //=======================================================================
78
79 StdMeshers_Projection_2D::StdMeshers_Projection_2D(int hypId, int studyId, SMESH_Gen* gen)
80   :SMESH_2D_Algo(hypId, studyId, gen)
81 {
82   _name = "Projection_2D";
83   _compatibleHypothesis.push_back("ProjectionSource2D");
84   _sourceHypo = 0;
85 }
86
87 //================================================================================
88 /*!
89  * \brief Destructor
90  */
91 //================================================================================
92
93 StdMeshers_Projection_2D::~StdMeshers_Projection_2D()
94 {}
95
96 //=======================================================================
97 //function : CheckHypothesis
98 //purpose  : 
99 //=======================================================================
100
101 bool StdMeshers_Projection_2D::CheckHypothesis(SMESH_Mesh&                          theMesh,
102                                                const TopoDS_Shape&                  theShape,
103                                                SMESH_Hypothesis::Hypothesis_Status& theStatus)
104 {
105   list <const SMESHDS_Hypothesis * >::const_iterator itl;
106
107   const list <const SMESHDS_Hypothesis * >&hyps = GetUsedHypothesis(theMesh, theShape);
108   if ( hyps.size() == 0 )
109   {
110     theStatus = HYP_MISSING;
111     return false;  // can't work with no hypothesis
112   }
113
114   if ( hyps.size() > 1 )
115   {
116     theStatus = HYP_ALREADY_EXIST;
117     return false;
118   }
119
120   const SMESHDS_Hypothesis *theHyp = hyps.front();
121
122   string hypName = theHyp->GetName();
123
124   theStatus = HYP_OK;
125
126   if (hypName == "ProjectionSource2D")
127   {
128     _sourceHypo = static_cast<const StdMeshers_ProjectionSource2D *>(theHyp);
129
130     // Check hypo parameters
131
132     SMESH_Mesh* srcMesh = _sourceHypo->GetSourceMesh();
133     SMESH_Mesh* tgtMesh = & theMesh;
134     if ( !srcMesh )
135       srcMesh = tgtMesh;
136
137     // check vertices
138     if ( _sourceHypo->HasVertexAssociation() )
139     {
140       // source vertices
141       TopoDS_Shape edge = TAssocTool::GetEdgeByVertices
142         ( srcMesh, _sourceHypo->GetSourceVertex(1), _sourceHypo->GetSourceVertex(2) );
143       if ( edge.IsNull() ||
144            !SMESH_MesherHelper::IsSubShape( edge, srcMesh ) ||
145            !SMESH_MesherHelper::IsSubShape( edge, _sourceHypo->GetSourceFace() ))
146       {
147         theStatus = HYP_BAD_PARAMETER;
148         error("Invalid source vertices");
149         SCRUTE((edge.IsNull()));
150         SCRUTE((SMESH_MesherHelper::IsSubShape( edge, srcMesh )));
151         SCRUTE((SMESH_MesherHelper::IsSubShape( edge, _sourceHypo->GetSourceFace() )));
152       }
153       else
154       {
155         // target vertices
156         edge = TAssocTool::GetEdgeByVertices
157           ( tgtMesh, _sourceHypo->GetTargetVertex(1), _sourceHypo->GetTargetVertex(2) );
158         if ( edge.IsNull() || !SMESH_MesherHelper::IsSubShape( edge, tgtMesh ))
159         {
160           theStatus = HYP_BAD_PARAMETER;
161           error("Invalid target vertices");
162           SCRUTE((edge.IsNull()));
163           SCRUTE((SMESH_MesherHelper::IsSubShape( edge, tgtMesh )));
164         }
165         // PAL16203
166         else if ( !_sourceHypo->IsCompoundSource() &&
167                   !SMESH_MesherHelper::IsSubShape( edge, theShape ))
168         {
169           theStatus = HYP_BAD_PARAMETER;
170           error("Invalid target vertices");
171           SCRUTE((SMESH_MesherHelper::IsSubShape( edge, theShape )));
172         }
173       }
174     }
175     // check a source face
176     if ( !SMESH_MesherHelper::IsSubShape( _sourceHypo->GetSourceFace(), srcMesh ) ||
177          ( srcMesh == tgtMesh && theShape == _sourceHypo->GetSourceFace() ))
178     {
179       theStatus = HYP_BAD_PARAMETER;
180       error("Invalid source face");
181       SCRUTE((SMESH_MesherHelper::IsSubShape( _sourceHypo->GetSourceFace(), srcMesh )));
182       SCRUTE((srcMesh == tgtMesh));
183       SCRUTE(( theShape == _sourceHypo->GetSourceFace() ));
184     }
185   }
186   else
187   {
188     theStatus = HYP_INCOMPATIBLE;
189   }
190   return ( theStatus == HYP_OK );
191 }
192
193 namespace {
194
195   //================================================================================
196   /*!
197    * \brief define if a node is new or old
198    * \param node - node to check
199    * \retval bool - true if the node existed before Compute() is called
200    */
201   //================================================================================
202
203   bool isOldNode( const SMDS_MeshNode* node )
204   {
205     // old nodes are shared by edges and new ones are shared
206     // only by faces created by mapper
207     //if ( is1DComputed )
208     {
209       bool isOld = node->NbInverseElements(SMDSAbs_Edge) > 0;
210       return isOld;
211     }
212     // else
213     // {
214     //   SMDS_ElemIteratorPtr invFace = node->GetInverseElementIterator(SMDSAbs_Face);
215     //   bool isNew = invFace->more();
216     //   return !isNew;
217     // }
218   }
219
220   //================================================================================
221   /*!
222    * \brief Class to remove mesh built by pattern mapper on edges
223    * and vertices in the case of failure of projection algo.
224    * It does it's job at destruction
225    */
226   //================================================================================
227
228   class MeshCleaner {
229     SMESH_subMesh* sm;
230   public:
231     MeshCleaner( SMESH_subMesh* faceSubMesh ): sm(faceSubMesh) {}
232     ~MeshCleaner() { Clean(sm); }
233     void Release() { sm = 0; } // mesh will not be removed
234     static void Clean( SMESH_subMesh* sm, bool withSub=true )
235     {
236       if ( !sm || !sm->GetSubMeshDS() ) return;
237       // PAL16567, 18920. Remove face nodes as well
238 //       switch ( sm->GetSubShape().ShapeType() ) {
239 //       case TopAbs_VERTEX:
240 //       case TopAbs_EDGE: {
241         SMDS_NodeIteratorPtr nIt = sm->GetSubMeshDS()->GetNodes();
242         SMESHDS_Mesh* mesh = sm->GetFather()->GetMeshDS();
243         while ( nIt->more() ) {
244           const SMDS_MeshNode* node = nIt->next();
245           if ( !isOldNode( node ) )
246             mesh->RemoveNode( node );
247         }
248         // do not break but iterate over DependsOn()
249 //       }
250 //       default:
251         if ( !withSub ) return;
252         SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(false,false);
253         while ( smIt->more() )
254           Clean( smIt->next(), false );
255 //       }
256     }
257   };
258
259   //================================================================================
260   /*!
261    * \brief find new nodes belonging to one free border of mesh on face
262     * \param sm - submesh on edge or vertex containg nodes to choose from
263     * \param face - the face bound by the submesh
264     * \param u2nodes - map to fill with nodes
265     * \param seamNodes - set of found nodes
266     * \retval bool - is a success
267    */
268   //================================================================================
269
270   bool getBoundaryNodes ( SMESH_subMesh*                        sm,
271                           const TopoDS_Face&                    face,
272                           map< double, const SMDS_MeshNode* > & u2nodes,
273                           set< const SMDS_MeshNode* > &         seamNodes)
274   {
275     u2nodes.clear();
276     seamNodes.clear();
277     if ( !sm || !sm->GetSubMeshDS() )
278       RETURN_BAD_RESULT("Null submesh");
279
280     SMDS_NodeIteratorPtr nIt = sm->GetSubMeshDS()->GetNodes();
281     switch ( sm->GetSubShape().ShapeType() ) {
282
283     case TopAbs_VERTEX: {
284       while ( nIt->more() ) {
285         const SMDS_MeshNode* node = nIt->next();
286         if ( isOldNode( node ) ) continue;
287         u2nodes.insert( make_pair( 0., node ));
288         seamNodes.insert( node );
289         return true;
290       }
291       break;
292     }
293     case TopAbs_EDGE: {
294       
295       // Get submeshes of sub-vertices
296       const map< int, SMESH_subMesh * >& subSM = sm->DependsOn();
297       if ( subSM.size() != 2 )
298         RETURN_BAD_RESULT("there must be 2 submeshes of sub-vertices"
299                           " but we have " << subSM.size());
300       SMESH_subMesh* smV1 = subSM.begin()->second;
301       SMESH_subMesh* smV2 = subSM.rbegin()->second;
302       if ( !smV1->IsMeshComputed() || !smV2->IsMeshComputed() )
303         RETURN_BAD_RESULT("Empty vertex submeshes");
304
305       const SMDS_MeshNode* nV1 = 0;
306       const SMDS_MeshNode* nE = 0;
307
308       // Look for nV1 - a new node on V1
309       nIt = smV1->GetSubMeshDS()->GetNodes();
310       while ( nIt->more() && !nE ) {
311         const SMDS_MeshNode* node = nIt->next();
312         if ( isOldNode( node ) ) continue;
313         nV1 = node;
314
315         // Find nE - a new node connected to nV1 and belonging to edge submesh;
316         SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
317         SMDS_ElemIteratorPtr vElems = nV1->GetInverseElementIterator(SMDSAbs_Face);
318         while ( vElems->more() && !nE ) {
319           const SMDS_MeshElement* elem = vElems->next();
320           int nbNodes = elem->NbNodes();
321           if ( elem->IsQuadratic() )
322             nbNodes /= 2;
323           int iV1 = elem->GetNodeIndex( nV1 );
324           // try next after nV1
325           int iE = SMESH_MesherHelper::WrapIndex( iV1 + 1, nbNodes );
326           if ( smDS->Contains( elem->GetNode( iE ) ))
327             nE = elem->GetNode( iE );
328           if ( !nE ) {
329             // try node before nV1
330             iE = SMESH_MesherHelper::WrapIndex( iV1 - 1, nbNodes );
331             if ( smDS->Contains( elem->GetNode( iE )))
332               nE = elem->GetNode( iE );
333           }
334           if ( nE && elem->IsQuadratic() ) { // find medium node between nV1 and nE
335             if ( Abs( iV1 - iE ) == 1 )
336               nE = elem->GetNode( Min ( iV1, iE ) + nbNodes );
337             else
338               nE = elem->GetNode( elem->NbNodes() - 1 );
339           }
340         }
341       }
342       if ( !nV1 )
343         RETURN_BAD_RESULT("No new node found on V1");
344       if ( !nE )
345         RETURN_BAD_RESULT("new node on edge not found");
346
347       // Get the whole free border of a face
348       list< const SMDS_MeshNode* > bordNodes;
349       list< const SMDS_MeshElement* > bordFaces;
350       if ( !SMESH_MeshEditor::FindFreeBorder (nV1, nE, nV1, bordNodes, bordFaces ))
351         RETURN_BAD_RESULT("free border of a face not found by nodes " <<
352                           nV1->GetID() << " " << nE->GetID() );
353
354       // Insert nodes of the free border to the map until node on V2 encountered
355       SMESHDS_SubMesh* v2smDS = smV2->GetSubMeshDS();
356       list< const SMDS_MeshNode* >::iterator bordIt = bordNodes.begin();
357       bordIt++; // skip nV1
358       for ( ; bordIt != bordNodes.end(); ++bordIt ) {
359         const SMDS_MeshNode* node = *bordIt;
360         if ( v2smDS->Contains( node ))
361           break;
362         if ( node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
363           RETURN_BAD_RESULT("Bad node position type: node " << node->GetID() <<
364                             " pos type " << node->GetPosition()->GetTypeOfPosition());
365         const SMDS_EdgePosition* pos =
366           static_cast<const SMDS_EdgePosition*>(node->GetPosition());
367         u2nodes.insert( make_pair( pos->GetUParameter(), node ));
368         seamNodes.insert( node );
369       }
370       if ( u2nodes.size() != seamNodes.size() )
371         RETURN_BAD_RESULT("Bad node params on edge " << sm->GetId() <<
372                           ", " << u2nodes.size() << " != " << seamNodes.size() );
373       return true;
374     }
375     default:;
376     }
377     RETURN_BAD_RESULT ("Unexpected submesh type");
378
379   } // bool getBoundaryNodes()
380
381   //================================================================================
382   /*!
383    * \brief Check if two consecutive EDGEs are connected in 2D
384    *  \param [in] E1 - a well oriented non-seam EDGE
385    *  \param [in] E2 - a possibly well oriented seam EDGE
386    *  \param [in] F - a FACE
387    *  \return bool - result
388    */
389   //================================================================================
390
391   bool are2dConnected( const TopoDS_Edge & E1,
392                        const TopoDS_Edge & E2,
393                        const TopoDS_Face & F )
394   {
395     double f,l;
396     Handle(Geom2d_Curve) c1 = BRep_Tool::CurveOnSurface( E1, F, f, l );
397     gp_Pnt2d uvFirst1 = c1->Value( f );
398     gp_Pnt2d uvLast1  = c1->Value( l );
399
400     Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( E2, F, f, l );
401     gp_Pnt2d uvFirst2 = c2->Value( E2.Orientation() == TopAbs_REVERSED ? l : f );
402     double tol2 = Max( Precision::PConfusion() * Precision::PConfusion(),
403                        1e-5 * uvLast1.SquareDistance( uvFirst1 ));
404
405     return (( uvFirst2.SquareDistance( uvFirst1 ) < tol2 ) ||
406             ( uvFirst2.SquareDistance( uvLast1  ) < tol2 ));
407   }
408
409   //================================================================================
410   /*!
411    * \brief Compose TSideVector for both FACEs keeping matching order of EDGEs
412    *        and fill src2tgtNodes map
413    */
414   //================================================================================
415
416   TError getWires(const TopoDS_Face&                 tgtFace,
417                   const TopoDS_Face&                 srcFace,
418                   SMESH_Mesh *                       tgtMesh,
419                   SMESH_Mesh *                       srcMesh,
420                   const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
421                   TSideVector&                       srcWires,
422                   TSideVector&                       tgtWires,
423                   TAssocTool::TNodeNodeMap&          src2tgtNodes,
424                   bool&                              is1DComputed)
425   {
426     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
427     SMESHDS_Mesh* srcMeshDS = srcMesh->GetMeshDS();
428
429     src2tgtNodes.clear();
430
431     // get ordered src EDGEs
432     TError err;
433     srcWires = StdMeshers_FaceSide::GetFaceWires( srcFace, *srcMesh,/*skipMediumNodes=*/0, err);
434     if ( err && !err->IsOK() || srcWires.empty() )
435       return err;
436
437     SMESH_MesherHelper srcHelper( *srcMesh );
438     srcHelper.SetSubShape( srcFace );
439
440     // make corresponding sequence of tgt EDGEs
441     tgtWires.resize( srcWires.size() );
442     for ( size_t iW = 0; iW < srcWires.size(); ++iW )
443     {
444       // check ori
445       //bool reverse = false;
446       StdMeshers_FaceSidePtr srcWire = srcWires[iW];
447       // for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
448       // {
449       //   if ( srcHelper.IsRealSeam( srcWire->EdgeID( iE )))
450       //     continue;
451       //   TopoDS_Shape srcE = srcWire->Edge( iE );
452       //   TopoDS_Shape tgtE = shape2ShapeMap( srcE, /*isSrc=*/true);
453       //   if ( shape2ShapeMap._assocType == TShapeShapeMap::PROPAGATION ||
454       //        shape2ShapeMap._assocType == TShapeShapeMap::PROPAGATION)
455       //   {
456       //     reverse = false;
457       //   }
458       //   else if ( tgtMesh == srcMesh )
459       //   {
460       //     reverse = (( srcE.Orientation() == srcHelper.GetSubShapeOri( srcFace, srcE )) !=
461       //                ( tgtE.Orientation() == srcHelper.GetSubShapeOri( tgtFace, tgtE )));
462       //   }
463       //   else
464       //   {
465       //     TopoDS_Shape srcEbis = shape2ShapeMap( tgtE, /*isSrc=*/false );
466       //     reverse = ( srcE.Orientation() != srcEbis.Orientation() );
467       //   }
468       //   break;
469       // }
470
471       list< TopoDS_Edge > tgtEdges;
472       TopTools_IndexedMapOfShape edgeMap; // to detect seam edges
473       for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
474       {
475         TopoDS_Edge     srcE = srcWire->Edge( iE );
476         TopoDS_Edge     tgtE = TopoDS::Edge( shape2ShapeMap( srcE, /*isSrc=*/true));
477         TopoDS_Shape srcEbis = shape2ShapeMap( tgtE, /*isSrc=*/false );
478         if ( srcE.Orientation() != srcEbis.Orientation() )
479           //if ( reverse )
480           tgtE.Reverse();
481         // reverse a seam edge encountered for the second time
482         const int index = edgeMap.Add( tgtE );
483         if ( index < edgeMap.Extent() ) // E is a seam
484         {
485           // check which of edges to reverse, E or one already being in tgtEdges
486           if ( are2dConnected( tgtEdges.back(), tgtE, tgtFace ))
487           {
488             list< TopoDS_Edge >::iterator eIt = tgtEdges.begin();
489             std::advance( eIt, index-1 );
490             if ( are2dConnected( tgtEdges.back(), *eIt, tgtFace ))
491               eIt->Reverse();
492           }
493           else
494           {
495             tgtE.Reverse();
496           }
497         }
498         if ( srcWire->NbEdges() == 1 && tgtMesh == srcMesh ) // circle
499         {
500           // try to verify ori by propagation
501           pair<int,TopoDS_Edge> nE =
502             StdMeshers_ProjectionUtils::GetPropagationEdge( srcMesh, tgtE, srcE );
503           if ( !nE.second.IsNull() )
504             tgtE = nE.second;
505         }
506         tgtEdges.push_back( tgtE );
507
508
509         // Fill map of src to tgt nodes with nodes on edges
510
511         if ( srcMesh->GetSubMesh( srcE )->IsEmpty() ||
512              tgtMesh->GetSubMesh( tgtE )->IsEmpty() )
513         {
514           // add nodes on VERTEXes for a case of not meshes EDGEs
515           const TopoDS_Shape&  srcV = SMESH_MesherHelper::IthVertex( 0, srcE );
516           const TopoDS_Shape&  tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
517           const SMDS_MeshNode* srcN = SMESH_Algo::VertexNode( TopoDS::Vertex( srcV ), srcMeshDS );
518           const SMDS_MeshNode* tgtN = SMESH_Algo::VertexNode( TopoDS::Vertex( tgtV ), tgtMeshDS );
519           if ( srcN && tgtN )
520             src2tgtNodes.insert( make_pair( srcN, tgtN ));
521         }
522         else
523         {
524           const bool skipMediumNodes = true;
525           map< double, const SMDS_MeshNode* > srcNodes, tgtNodes;
526           if ( !SMESH_Algo::GetSortedNodesOnEdge( srcMeshDS, srcE, skipMediumNodes, srcNodes) ||
527                !SMESH_Algo::GetSortedNodesOnEdge( tgtMeshDS, tgtE, skipMediumNodes, tgtNodes ))
528             return SMESH_ComputeError::New( COMPERR_BAD_INPUT_MESH,
529                                             "Invalid node parameters on edges");
530
531           if (( srcNodes.size() != tgtNodes.size() ) && tgtNodes.size() > 0 )
532             return SMESH_ComputeError::New( COMPERR_BAD_INPUT_MESH,
533                                             "Different number of nodes on edges");
534           if ( !tgtNodes.empty() )
535           {
536             map< double, const SMDS_MeshNode* >::iterator u_tn = tgtNodes.begin();
537             if ( srcE.Orientation() == tgtE.Orientation() )
538             {
539               map< double, const SMDS_MeshNode* >::iterator u_sn = srcNodes.begin();
540               for ( ; u_tn != tgtNodes.end(); ++u_tn, ++u_sn)
541                 src2tgtNodes.insert( make_pair( u_sn->second, u_tn->second ));
542             }
543             else
544             {
545               map< double, const SMDS_MeshNode* >::reverse_iterator u_sn = srcNodes.rbegin();
546               for ( ; u_tn != tgtNodes.end(); ++u_tn, ++u_sn)
547                 src2tgtNodes.insert( make_pair( u_sn->second, u_tn->second ));
548             }
549             is1DComputed = true;
550           }
551         }
552       } // loop on EDGEs of a WIRE
553
554       tgtWires[ iW ].reset( new StdMeshers_FaceSide( tgtFace, tgtEdges, tgtMesh,
555                                                      /*theIsForward = */ true,
556                                                      /*theIgnoreMediumNodes = */false));
557     } // loop on WIREs
558
559     return TError();
560   }
561
562   //================================================================================
563   /*!
564    * \brief Preform projection in case if tgtFace.IsPartner( srcFace ) and in case
565    * if projection by 3D transformation is possible
566    */
567   //================================================================================
568
569   bool projectPartner(const TopoDS_Face&                 tgtFace,
570                       const TopoDS_Face&                 srcFace,
571                       const TSideVector&                 tgtWires,
572                       const TSideVector&                 srcWires,
573                       const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
574                       TAssocTool::TNodeNodeMap&          src2tgtNodes,
575                       const bool                         is1DComputed)
576   {
577     SMESH_Mesh *    tgtMesh = tgtWires[0]->GetMesh();
578     SMESH_Mesh *    srcMesh = srcWires[0]->GetMesh();
579     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
580     SMESHDS_Mesh* srcMeshDS = srcMesh->GetMeshDS();
581     SMESH_MesherHelper helper( *tgtMesh );
582
583     const double tol = 1.e-7 * srcMeshDS->getMaxDim();
584
585     // transformation to get location of target nodes from source ones
586     StdMeshers_ProjectionUtils::TrsfFinder3D trsf;
587     bool trsfIsOK = false;
588     if ( tgtFace.IsPartner( srcFace ))
589     {
590       gp_GTrsf srcTrsf = srcFace.Location().Transformation();
591       gp_GTrsf tgtTrsf = tgtFace.Location().Transformation();
592       gp_GTrsf t = srcTrsf.Inverted().Multiplied( tgtTrsf );
593       trsf.Set( t );
594       // check
595       gp_Pnt srcP = BRep_Tool::Pnt( srcWires[0]->FirstVertex() );
596       gp_Pnt tgtP = BRep_Tool::Pnt( tgtWires[0]->FirstVertex() );
597       trsfIsOK = ( tgtP.Distance( trsf.Transform( srcP )) < tol );
598       if ( !trsfIsOK )
599       {
600         trsf.Set( tgtTrsf.Inverted().Multiplied( srcTrsf ));
601         trsfIsOK = ( tgtP.Distance( trsf.Transform( srcP )) < tol );
602       }
603     }
604     if ( !trsfIsOK )
605     {
606       // Try to find the 3D transformation
607
608       const int totNbSeg = 50;
609       vector< gp_XYZ > srcPnts, tgtPnts;
610       srcPnts.reserve( totNbSeg );
611       tgtPnts.reserve( totNbSeg );
612       gp_XYZ srcBC( 0,0,0 ), tgtBC( 0,0,0 );
613       for ( size_t iW = 0; iW < srcWires.size(); ++iW )
614       {
615         const double minSegLen = srcWires[iW]->Length() / totNbSeg;
616         for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
617         {
618           int nbSeg    = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
619           double srcU  = srcWires[iW]->FirstParameter( iE );
620           double tgtU  = tgtWires[iW]->FirstParameter( iE );
621           double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
622           double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
623           for ( size_t i = 0; i < nbSeg; ++i  )
624           {
625             srcPnts.push_back( srcWires[iW]->Value3d( srcU ).XYZ() );
626             tgtPnts.push_back( tgtWires[iW]->Value3d( tgtU ).XYZ() );
627             srcU += srcDu;
628             tgtU += tgtDu;
629             srcBC += srcPnts.back();
630             tgtBC += tgtPnts.back();
631           }
632         }
633       }
634       if ( !trsf.Solve( srcPnts, tgtPnts ))
635         return false;
636
637       // check trsf
638
639       const int nbTestPnt = 20;
640       const size_t  iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
641       // check boundary
642       gp_Pnt trsfTgt = trsf.Transform( srcBC / srcPnts.size() );
643       trsfIsOK = ( trsfTgt.SquareDistance( tgtBC / tgtPnts.size() ) < tol*tol );
644       for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
645       {
646         gp_Pnt trsfTgt = trsf.Transform( srcPnts[i] );
647         trsfIsOK = ( trsfTgt.SquareDistance( tgtPnts[i] ) < tol*tol );
648       }
649       // check an in-FACE point
650       if ( trsfIsOK )
651       {
652         BRepAdaptor_Surface srcSurf( srcFace );
653         gp_Pnt srcP =
654           srcSurf.Value( 0.321 * ( srcSurf.FirstUParameter() + srcSurf.LastUParameter() ),
655                          0.123 * ( srcSurf.FirstVParameter() + srcSurf.LastVParameter() ));
656         gp_Pnt tgtTrsfP = trsf.Transform( srcP );
657         TopLoc_Location loc;
658         GeomAPI_ProjectPointOnSurf& proj = helper.GetProjector( tgtFace, loc, 0.1*tol );
659         if ( !loc.IsIdentity() )
660           tgtTrsfP.Transform( loc.Transformation().Inverted() );
661         proj.Perform( tgtTrsfP );
662         trsfIsOK = ( proj.IsDone() &&
663                      proj.NbPoints() > 0 &&
664                      proj.LowerDistance() < tol );
665       }
666       if ( !trsfIsOK )
667         return false;
668     }
669
670     // Make new faces
671
672     // prepare the helper to adding quadratic elements if necessary
673     helper.SetSubShape( tgtFace );
674     helper.IsQuadraticSubMesh( tgtFace );
675
676     SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
677     if ( !is1DComputed && srcSubDS->NbElements() )
678       helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
679
680     SMESH_MesherHelper srcHelper( *srcMesh );
681     srcHelper.SetSubShape( srcFace );
682
683     const SMDS_MeshNode* nullNode = 0;
684     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
685
686     // indices of nodes to create properly oriented faces
687     bool isReverse = ( !trsf.IsIdentity() );
688     int tri1 = 1, tri2 = 2, quad1 = 1, quad3 = 3;
689     if ( isReverse )
690       std::swap( tri1, tri2 ), std::swap( quad1, quad3 );
691
692     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
693     vector< const SMDS_MeshNode* > tgtNodes;
694     while ( elemIt->more() ) // loop on all mesh faces on srcFace
695     {
696       const SMDS_MeshElement* elem = elemIt->next();
697       const int nbN = elem->NbCornerNodes(); 
698       tgtNodes.resize( nbN );
699       helper.SetElementsOnShape( false );
700       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
701       {
702         const SMDS_MeshNode* srcNode = elem->GetNode(i);
703         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
704         if ( srcN_tgtN->second == nullNode )
705         {
706           // create a new node
707           gp_Pnt tgtP = trsf.Transform( SMESH_TNodeXYZ( srcNode ));
708           SMDS_MeshNode* n = helper.AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
709           srcN_tgtN->second = n;
710           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
711           {
712           case SMDS_TOP_FACE:
713           {
714             gp_Pnt2d srcUV = srcHelper.GetNodeUV( srcFace, srcNode );
715             tgtMeshDS->SetNodeOnFace( n, helper.GetSubShapeID(), srcUV.X(), srcUV.Y() );
716             break;
717           }
718           case SMDS_TOP_EDGE:
719           {
720             const TopoDS_Shape & srcE = srcMeshDS->IndexToShape( srcNode->getshapeId() );
721             const TopoDS_Shape & tgtE = shape2ShapeMap( srcE, /*isSrc=*/true );
722             double srcU = srcHelper.GetNodeU( TopoDS::Edge( srcE ), srcNode );
723             tgtMeshDS->SetNodeOnEdge( n, TopoDS::Edge( tgtE ), srcU );
724             break;
725           }
726           case SMDS_TOP_VERTEX:
727           {
728             const TopoDS_Shape & srcV = srcMeshDS->IndexToShape( srcNode->getshapeId() );
729             const TopoDS_Shape & tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
730             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
731             break;
732           }
733           default:;
734           }
735         }
736         tgtNodes[i] = srcN_tgtN->second;
737       }
738       // create a new face
739       helper.SetElementsOnShape( true );
740       switch ( nbN )
741       {
742       case 3: helper.AddFace(tgtNodes[0], tgtNodes[tri1], tgtNodes[tri2]); break;
743       case 4: helper.AddFace(tgtNodes[0], tgtNodes[quad1], tgtNodes[2], tgtNodes[quad3]); break;
744       default:
745         if ( isReverse ) std::reverse( tgtNodes.begin(), tgtNodes.end() );
746         helper.AddPolygonalFace( tgtNodes );
747       }
748     }
749
750     // check node positions
751
752     if ( !tgtFace.IsPartner( srcFace ) )
753     {
754       SMESH_MesherHelper edgeHelper( *tgtMesh );
755       edgeHelper.ToFixNodeParameters( true );
756       helper.ToFixNodeParameters( true );
757
758       int nbOkPos = 0;
759       bool toCheck = true;
760       const double tol2d = 1e-12;
761       srcN_tgtN = src2tgtNodes.begin();
762       for ( ; srcN_tgtN != src2tgtNodes.end(); ++srcN_tgtN )
763       {
764         const SMDS_MeshNode* n = srcN_tgtN->second;
765         switch ( n->GetPosition()->GetTypeOfPosition() )
766         {
767         case SMDS_TOP_FACE:
768         {
769           if ( nbOkPos > 10 ) break;
770           gp_XY uv = helper.GetNodeUV( tgtFace, n ), uvBis = uv;
771           if (( helper.CheckNodeUV( tgtFace, n, uv, tol )) &&
772               (( uv - uvBis ).SquareModulus() < tol2d ))
773             ++nbOkPos;
774           else
775             nbOkPos = -((int) src2tgtNodes.size() );
776           break;
777         }
778         case SMDS_TOP_EDGE:
779         {
780           const TopoDS_Edge & tgtE = TopoDS::Edge( tgtMeshDS->IndexToShape( n->getshapeId() ));
781           edgeHelper.SetSubShape( tgtE );
782           edgeHelper.GetNodeU( tgtE, n, 0, &toCheck );
783           break;
784         }
785         default:;
786         }
787       }
788     }
789
790     return true;
791
792   } //   bool projectPartner()
793
794   //================================================================================
795   /*!
796    * \brief Preform projection in case if the faces are similar in 2D space
797    */
798   //================================================================================
799
800   bool projectBy2DSimilarity(const TopoDS_Face&                 tgtFace,
801                              const TopoDS_Face&                 srcFace,
802                              const TSideVector&                 tgtWires,
803                              const TSideVector&                 srcWires,
804                              const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
805                              TAssocTool::TNodeNodeMap&          src2tgtNodes,
806                              const bool                         is1DComputed)
807   {
808     SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
809     SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
810
811     // WARNING: we can have problems if the FACE is symmetrical in 2D,
812     // then the projection can be mirrored relating to what is expected
813
814     // 1) Find 2D transformation
815
816     StdMeshers_ProjectionUtils::TrsfFinder2D trsf;
817     {
818       // get 2 pairs of corresponding UVs
819       gp_Pnt2d srcP0 = srcWires[0]->Value2d(0.0);
820       gp_Pnt2d srcP1 = srcWires[0]->Value2d(0.333);
821       gp_Pnt2d tgtP0 = tgtWires[0]->Value2d(0.0);
822       gp_Pnt2d tgtP1 = tgtWires[0]->Value2d(0.333);
823
824       // make transformation
825       gp_Trsf2d fromTgtCS, toSrcCS; // from/to global CS
826       gp_Ax2d srcCS( srcP0, gp_Vec2d( srcP0, srcP1 ));
827       gp_Ax2d tgtCS( tgtP0, gp_Vec2d( tgtP0, tgtP1 ));
828       toSrcCS  .SetTransformation( srcCS );
829       fromTgtCS.SetTransformation( tgtCS );
830       fromTgtCS.Invert();
831       trsf.Set( fromTgtCS * toSrcCS );
832
833       // check transformation
834       bool trsfIsOK = true;
835       const double tol = 1e-5 * gp_Vec2d( srcP0, srcP1 ).Magnitude();
836       for ( double u = 0.12; ( u < 1. && trsfIsOK ); u += 0.1 )
837       {
838         gp_Pnt2d srcUV  = srcWires[0]->Value2d( u );
839         gp_Pnt2d tgtUV  = tgtWires[0]->Value2d( u );
840         gp_Pnt2d tgtUV2 = trsf.Transform( srcUV );
841         trsfIsOK = ( tgtUV.Distance( tgtUV2 ) < tol );
842       }
843
844       // Find trsf using a least-square approximation
845       if ( !trsfIsOK )
846       {
847         // find trsf
848         const int totNbSeg = 50;
849         vector< gp_XY > srcPnts, tgtPnts;
850         srcPnts.resize( totNbSeg );
851         tgtPnts.resize( totNbSeg );
852         for ( size_t iW = 0; iW < srcWires.size(); ++iW )
853         {
854           const double minSegLen = srcWires[iW]->Length() / totNbSeg;
855           for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
856           {
857             int nbSeg    = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
858             double srcU  = srcWires[iW]->FirstParameter( iE );
859             double tgtU  = tgtWires[iW]->FirstParameter( iE );
860             double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
861             double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
862             for ( size_t i = 0; i < nbSeg; ++i, srcU += srcDu, tgtU += tgtDu  )
863             {
864               srcPnts.push_back( srcWires[iW]->Value2d( srcU ).XY() );
865               tgtPnts.push_back( tgtWires[iW]->Value2d( tgtU ).XY() );
866             }
867           }
868         }
869         if ( !trsf.Solve( srcPnts, tgtPnts ))
870           return false;
871
872         // check trsf
873
874         trsfIsOK = true;
875         const int nbTestPnt = 10;
876         const size_t  iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
877         for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
878         {
879           gp_Pnt2d trsfTgt = trsf.Transform( srcPnts[i] );
880           trsfIsOK = ( trsfTgt.Distance( tgtPnts[i] ) < tol );
881         }
882         if ( !trsfIsOK )
883           return false;
884       }
885     } // "Find transformation" block
886
887     // 2) Projection
888
889     SMESHDS_SubMesh* srcSubDS = srcMesh->GetMeshDS()->MeshElements( srcFace );
890
891     SMESH_MesherHelper helper( *tgtMesh );
892     helper.SetSubShape( tgtFace );
893     if ( is1DComputed )
894       helper.IsQuadraticSubMesh( tgtFace );
895     else
896       helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
897     helper.SetElementsOnShape( true );
898     Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
899     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
900
901     SMESH_MesherHelper srcHelper( *srcMesh );
902     srcHelper.SetSubShape( srcFace );
903
904     const SMDS_MeshNode* nullNode = 0;
905     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
906
907     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
908     vector< const SMDS_MeshNode* > tgtNodes;
909     bool uvOK;
910     while ( elemIt->more() ) // loop on all mesh faces on srcFace
911     {
912       const SMDS_MeshElement* elem = elemIt->next();
913       const int nbN = elem->NbCornerNodes(); 
914       tgtNodes.resize( nbN );
915       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
916       {
917         const SMDS_MeshNode* srcNode = elem->GetNode(i);
918         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
919         if ( srcN_tgtN->second == nullNode )
920         {
921           // create a new node
922           gp_Pnt2d srcUV = srcHelper.GetNodeUV( srcFace, srcNode,
923                                                 elem->GetNode( helper.WrapIndex(i+1,nbN)), &uvOK);
924           gp_Pnt2d   tgtUV = trsf.Transform( srcUV );
925           gp_Pnt      tgtP = tgtSurface->Value( tgtUV.X(), tgtUV.Y() );
926           SMDS_MeshNode* n = tgtMeshDS->AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
927           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
928           {
929           case SMDS_TOP_FACE: {
930             tgtMeshDS->SetNodeOnFace( n, helper.GetSubShapeID(), tgtUV.X(), tgtUV.Y() );
931             break;
932           }
933           case SMDS_TOP_EDGE: {
934             TopoDS_Shape srcEdge = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
935             TopoDS_Edge  tgtEdge = TopoDS::Edge( shape2ShapeMap( srcEdge, /*isSrc=*/true ));
936             double U = Precision::Infinite();
937             helper.CheckNodeU( tgtEdge, n, U, Precision::PConfusion());
938             tgtMeshDS->SetNodeOnEdge( n, TopoDS::Edge( tgtEdge ), U );
939             break;
940           }
941           case SMDS_TOP_VERTEX: {
942             TopoDS_Shape srcV = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
943             TopoDS_Shape tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
944             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
945             break;
946           }
947           }
948           srcN_tgtN->second = n;
949         }
950         tgtNodes[i] = srcN_tgtN->second;
951       }
952       // create a new face (with reversed orientation)
953       switch ( nbN )
954       {
955       case 3: helper.AddFace(tgtNodes[0], tgtNodes[2], tgtNodes[1]); break;
956       case 4: helper.AddFace(tgtNodes[0], tgtNodes[3], tgtNodes[2], tgtNodes[1]); break;
957       }
958     }  // loop on all mesh faces on srcFace
959
960     return true;
961   }
962
963   //================================================================================
964   /*!
965    * \brief Preform projection in case of quadrilateral faces
966    */
967   //================================================================================
968
969   bool projectQuads(const TopoDS_Face&                 tgtFace,
970                     const TopoDS_Face&                 srcFace,
971                     const TSideVector&                 tgtWires,
972                     const TSideVector&                 srcWires,
973                     const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
974                     TAssocTool::TNodeNodeMap&          src2tgtNodes,
975                     const bool                         is1DComputed)
976   {
977     SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
978     SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
979     SMESHDS_Mesh * tgtMeshDS = tgtMesh->GetMeshDS();
980     SMESHDS_Mesh * srcMeshDS = srcMesh->GetMeshDS();
981
982     if ( srcWires[0]->NbEdges() != 4 )
983       return false;
984     if ( !is1DComputed )
985       return false;
986     for ( int iE = 0; iE < 4; ++iE )
987     {
988       SMESHDS_SubMesh* sm = srcMeshDS->MeshElements( srcWires[0]->Edge( iE ));
989       if ( !sm ) return false;
990       if ( sm->NbNodes() + sm->NbElements() == 0 ) return false;
991     }
992     if ( BRepAdaptor_Surface( tgtFace ).GetType() != GeomAbs_Plane )
993       return false;
994     // if ( BRepAdaptor_Surface( tgtFace ).GetType() == GeomAbs_Plane &&
995     //      BRepAdaptor_Surface( srcFace ).GetType() == GeomAbs_Plane )
996     //   return false; // too easy
997
998     // load EDGEs to SMESH_Block
999
1000     SMESH_Block block;
1001     TopTools_IndexedMapOfOrientedShape blockSubShapes;
1002     {
1003       const TopoDS_Solid& box = srcMesh->PseudoShape();
1004       TopoDS_Shell shell = TopoDS::Shell( TopExp_Explorer( box, TopAbs_SHELL ).Current() );
1005       TopoDS_Vertex v;
1006       block.LoadBlockShapes( shell, v, v, blockSubShapes ); // fill all since operator[] is missing
1007     }
1008     const SMESH_Block::TShapeID srcFaceBID = SMESH_Block::ID_Fxy0;
1009     const SMESH_Block::TShapeID tgtFaceBID = SMESH_Block::ID_Fxy1;
1010     vector< int > edgeBID;
1011     block.GetFaceEdgesIDs( srcFaceBID, edgeBID ); // u0, u1, 0v, 1v
1012     blockSubShapes.Substitute( edgeBID[0], srcWires[0]->Edge(0) );
1013     blockSubShapes.Substitute( edgeBID[1], srcWires[0]->Edge(2) );
1014     blockSubShapes.Substitute( edgeBID[2], srcWires[0]->Edge(3) );
1015     blockSubShapes.Substitute( edgeBID[3], srcWires[0]->Edge(1) );
1016     block.GetFaceEdgesIDs( tgtFaceBID, edgeBID ); // u0, u1, 0v, 1v
1017     blockSubShapes.Substitute( edgeBID[0], tgtWires[0]->Edge(0) );
1018     blockSubShapes.Substitute( edgeBID[1], tgtWires[0]->Edge(2) );
1019     blockSubShapes.Substitute( edgeBID[2], tgtWires[0]->Edge(3) );
1020     blockSubShapes.Substitute( edgeBID[3], tgtWires[0]->Edge(1) );
1021     block.LoadFace( srcFace, srcFaceBID, blockSubShapes );
1022     block.LoadFace( tgtFace, tgtFaceBID, blockSubShapes );
1023
1024     // remember connectivity of new faces in terms of ( node-or-XY )
1025
1026     typedef std::pair< const SMDS_MeshNode*, gp_XYZ > TNodeOrXY; // node-or-XY
1027     typedef std::vector< TNodeOrXY* >                 TFaceConn; // face connectivity
1028     std::vector< TFaceConn >                    newFacesVec;     // connectivity of all faces
1029     std::map< const SMDS_MeshNode*, TNodeOrXY > srcNode2tgtNXY;  // src node -> node-or-XY
1030
1031     TAssocTool::TNodeNodeMap::iterator                                       srcN_tgtN;
1032     std::map< const SMDS_MeshNode*, TNodeOrXY >::iterator                    srcN_tgtNXY;
1033     std::pair< std::map< const SMDS_MeshNode*, TNodeOrXY >::iterator, bool > n2n_isNew;
1034     TNodeOrXY nullNXY( 0, gp_XYZ(0,0,0) );
1035
1036     SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
1037     newFacesVec.resize( srcSubDS->NbElements() );
1038     int iFaceSrc = 0;
1039
1040     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
1041     while ( elemIt->more() ) // loop on all mesh faces on srcFace
1042     {
1043       const SMDS_MeshElement* elem = elemIt->next();
1044       TFaceConn& tgtNodes = newFacesVec[ iFaceSrc++ ];
1045
1046       const int nbN = elem->NbCornerNodes(); 
1047       tgtNodes.resize( nbN );
1048       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
1049       {
1050         const SMDS_MeshNode* srcNode = elem->GetNode(i);
1051         n2n_isNew = srcNode2tgtNXY.insert( make_pair( srcNode, nullNXY ));
1052         TNodeOrXY & tgtNodeOrXY = n2n_isNew.first->second;
1053         if ( n2n_isNew.second ) // new src node encounters
1054         {
1055           srcN_tgtN = src2tgtNodes.find( srcNode );
1056           if ( srcN_tgtN != src2tgtNodes.end() )
1057           {
1058             tgtNodeOrXY.first = srcN_tgtN->second; // tgt node exists
1059           }
1060           else 
1061           {
1062             // find XY of src node withing the quadrilateral srcFace
1063             if ( !block.ComputeParameters( SMESH_TNodeXYZ( srcNode ),
1064                                            tgtNodeOrXY.second, srcFaceBID ))
1065               return false;
1066           }
1067         }
1068         tgtNodes[ i ] = & tgtNodeOrXY;
1069       }
1070     }
1071
1072     // as all XY are computed, create tgt nodes and faces
1073
1074     SMESH_MesherHelper helper( *tgtMesh );
1075     helper.SetSubShape( tgtFace );
1076     if ( is1DComputed )
1077       helper.IsQuadraticSubMesh( tgtFace );
1078     else
1079       helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
1080     helper.SetElementsOnShape( true );
1081     Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
1082
1083     SMESH_MesherHelper srcHelper( *srcMesh );
1084     srcHelper.SetSubShape( srcFace );
1085
1086     vector< const SMDS_MeshNode* > tgtNodes;
1087     gp_XY uv;
1088
1089     for ( size_t iFaceTgt = 0; iFaceTgt < newFacesVec.size(); ++iFaceTgt )
1090     {
1091       TFaceConn& tgtConn = newFacesVec[ iFaceTgt ];
1092       tgtNodes.resize( tgtConn.size() );
1093       for ( size_t iN = 0; iN < tgtConn.size(); ++iN )
1094       {
1095         const SMDS_MeshNode* & tgtN = tgtConn[ iN ]->first;
1096         if ( !tgtN ) // create a node
1097         {
1098           if ( !block.FaceUV( tgtFaceBID, tgtConn[iN]->second, uv ))
1099             return false;
1100           gp_Pnt p = tgtSurface->Value( uv.X(), uv.Y() );
1101           tgtN = helper.AddNode( p.X(), p.Y(), p.Z(), uv.X(), uv.Y() );
1102         }
1103         tgtNodes[ tgtNodes.size() - iN - 1] = tgtN; // reversed orientation
1104       }
1105       switch ( tgtNodes.size() )
1106       {
1107       case 3: helper.AddFace(tgtNodes[0], tgtNodes[1], tgtNodes[2]); break;
1108       case 4: helper.AddFace(tgtNodes[0], tgtNodes[1], tgtNodes[2], tgtNodes[3]); break;
1109       default:
1110         if ( tgtNodes.size() > 4 )
1111           helper.AddPolygonalFace( tgtNodes );
1112       }
1113     }
1114     return true;
1115
1116   } // bool projectQuads(...)
1117
1118   //================================================================================
1119   /*!
1120    * \brief Fix bad faces by smoothing
1121    */
1122   //================================================================================
1123
1124   bool fixDistortedFaces( SMESH_MesherHelper& helper,
1125                           TSideVector&        tgtWires )
1126   {
1127     SMESH_subMesh* faceSM = helper.GetMesh()->GetSubMesh( helper.GetSubShape() );
1128
1129     if ( helper.IsDistorted2D( faceSM, /*checkUV=*/false ))
1130     {
1131       SMESH_MeshEditor editor( helper.GetMesh() );
1132       SMESHDS_SubMesh* smDS = faceSM->GetSubMeshDS();
1133       const TopoDS_Face&  F = TopoDS::Face( faceSM->GetSubShape() );
1134
1135       TIDSortedElemSet faces;
1136       SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
1137       for ( faceIt = smDS->GetElements(); faceIt->more(); )
1138         faces.insert( faces.end(), faceIt->next() );
1139
1140       // choose smoothing algo
1141       //SMESH_MeshEditor:: SmoothMethod algo = SMESH_MeshEditor::CENTROIDAL;
1142       bool isConcaveBoundary = false;
1143       for ( size_t iW = 0; iW < tgtWires.size() && !isConcaveBoundary; ++iW )
1144       {
1145         TopoDS_Edge prevEdge = tgtWires[iW]->Edge( tgtWires[iW]->NbEdges() - 1 );
1146         for ( int iE = 0; iE < tgtWires[iW]->NbEdges() && !isConcaveBoundary; ++iE )
1147         {
1148           double angle = helper.GetAngle( prevEdge, tgtWires[iW]->Edge( iE ),
1149                                           F,        tgtWires[iW]->FirstVertex( iE ));
1150           isConcaveBoundary = ( angle < -5. * M_PI / 180. );
1151
1152           prevEdge = tgtWires[iW]->Edge( iE );
1153         }
1154       }
1155       SMESH_MeshEditor:: SmoothMethod algo =
1156         isConcaveBoundary ? SMESH_MeshEditor::CENTROIDAL : SMESH_MeshEditor::LAPLACIAN;
1157
1158       // smooth in 2D or 3D?
1159       TopLoc_Location loc;
1160       Handle(Geom_Surface) surface = BRep_Tool::Surface( F, loc );
1161       bool isPlanar = GeomLib_IsPlanarSurface( surface ).IsPlanar();
1162
1163       // smoothing
1164       set<const SMDS_MeshNode*> fixedNodes;
1165       editor.Smooth( faces, fixedNodes, algo, /*nbIterations=*/ 10,
1166                      /*theTgtAspectRatio=*/1.0, /*the2D=*/!isPlanar);
1167
1168       helper.ToFixNodeParameters( true );
1169
1170       return !helper.IsDistorted2D( faceSM, /*checkUV=*/true );
1171     }
1172     return true;
1173   }
1174
1175 } // namespace
1176
1177
1178 //=======================================================================
1179 //function : Compute
1180 //purpose  :
1181 //=======================================================================
1182
1183 bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
1184 {
1185   _src2tgtNodes.clear();
1186
1187   MESSAGE("Projection_2D Compute");
1188   if ( !_sourceHypo )
1189     return false;
1190
1191   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
1192   SMESH_Mesh * tgtMesh = & theMesh;
1193   if ( !srcMesh )
1194     srcMesh = tgtMesh;
1195
1196   SMESHDS_Mesh * meshDS = theMesh.GetMeshDS();
1197   SMESH_MesherHelper helper( theMesh );
1198
1199   // ---------------------------
1200   // Make sub-shapes association
1201   // ---------------------------
1202
1203   TopoDS_Face   tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
1204   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
1205
1206   TAssocTool::TShapeShapeMap shape2ShapeMap;
1207   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
1208   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
1209                                              shape2ShapeMap)  ||
1210        !shape2ShapeMap.IsBound( tgtFace ))
1211   {
1212     if ( srcShape.ShapeType() == TopAbs_FACE )
1213     {
1214       int nbE1 = helper.Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
1215       int nbE2 = helper.Count( srcShape, TopAbs_EDGE, /*ignoreSame=*/true );
1216       if ( nbE1 != nbE2 )
1217         return error(COMPERR_BAD_SHAPE,
1218                      SMESH_Comment("Different number of edges in source and target faces: ")
1219                      << nbE2 << " and " << nbE1 );
1220     }
1221     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
1222   }
1223   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
1224
1225   // orient faces
1226   // if ( srcMesh == tgtMesh )
1227   // {
1228   //   TopoDS_Shape solid =
1229   //     helper.GetCommonAncestor( srcFace, tgtFace, *tgtMesh, TopAbs_SOLID );
1230   //   if ( !solid.IsNull() )
1231   //   {
1232   //     srcFace.Orientation( helper.GetSubShapeOri( solid, srcFace ));
1233   //     tgtFace.Orientation( helper.GetSubShapeOri( solid, tgtFace ));
1234   //   }
1235   //   else if ( helper.NbAncestors( srcFace, *tgtMesh, TopAbs_SOLID ) == 1 &&
1236   //             helper.NbAncestors( tgtFace, *tgtMesh, TopAbs_SOLID ) == 1 )
1237   //   {
1238   //     srcFace.Orientation( helper.GetSubShapeOri( tgtMesh->GetShapeToMesh(), srcFace ));
1239   //     tgtFace.Orientation( helper.GetSubShapeOri( tgtMesh->GetShapeToMesh(), tgtFace ));
1240   //   }
1241   // }
1242   // ----------------------------------------------
1243   // Assure that mesh on a source Face is computed
1244   // ----------------------------------------------
1245
1246   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
1247   SMESH_subMesh* tgtSubMesh = tgtMesh->GetSubMesh( tgtFace );
1248
1249   string srcMeshError;
1250   if ( tgtMesh == srcMesh ) {
1251     if ( !TAssocTool::MakeComputed( srcSubMesh ))
1252       srcMeshError = TAssocTool::SourceNotComputedError( srcSubMesh, this );
1253   }
1254   else {
1255     if ( !srcSubMesh->IsMeshComputed() )
1256       srcMeshError = TAssocTool::SourceNotComputedError();
1257   }
1258   if ( !srcMeshError.empty() )
1259     return error(COMPERR_BAD_INPUT_MESH, srcMeshError );
1260
1261   // ===========
1262   // Projection
1263   // ===========
1264
1265   // get ordered src and tgt EDGEs
1266   TSideVector srcWires, tgtWires;
1267   bool is1DComputed = false; // if any tgt EDGE is meshed
1268   TError err = getWires( tgtFace, srcFace, tgtMesh, srcMesh,
1269                          shape2ShapeMap, srcWires, tgtWires, _src2tgtNodes, is1DComputed );
1270   if ( err && !err->IsOK() )
1271     return error( err );
1272
1273   bool projDone = false;
1274
1275   if ( !projDone )
1276   {
1277     // try to project from the same face with different location
1278     projDone = projectPartner( tgtFace, srcFace, tgtWires, srcWires,
1279                                shape2ShapeMap, _src2tgtNodes, is1DComputed );
1280   }
1281   if ( !projDone )
1282   {
1283     // projection in case if the faces are similar in 2D space
1284     projDone = projectBy2DSimilarity( tgtFace, srcFace, tgtWires, srcWires,
1285                                       shape2ShapeMap, _src2tgtNodes, is1DComputed);
1286   }
1287   if ( !projDone )
1288   {
1289     // projection in case of quadrilateral faces
1290     // projDone = projectQuads( tgtFace, srcFace, tgtWires, srcWires,
1291     //                          shape2ShapeMap, _src2tgtNodes, is1DComputed);
1292   }
1293
1294   helper.SetSubShape( tgtFace );
1295
1296   // it will remove mesh built on edges and vertices in failure case
1297   MeshCleaner cleaner( tgtSubMesh );
1298
1299   if ( !projDone )
1300   {
1301     _src2tgtNodes.clear();
1302     // --------------------
1303     // Prepare to mapping 
1304     // --------------------
1305
1306     // Check if node projection to a face is needed
1307     Bnd_B2d uvBox;
1308     SMDS_ElemIteratorPtr faceIt = srcSubMesh->GetSubMeshDS()->GetElements();
1309     set< const SMDS_MeshNode* > faceNodes;
1310     for ( ; faceNodes.size() < 3 && faceIt->more();  ) {
1311       const SMDS_MeshElement* face = faceIt->next();
1312       SMDS_ElemIteratorPtr nodeIt = face->nodesIterator();
1313       while ( nodeIt->more() ) {
1314         const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
1315         if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE &&
1316              faceNodes.insert( node ).second )
1317           uvBox.Add( helper.GetNodeUV( srcFace, node ));
1318       }
1319     }
1320     bool toProjectNodes = false;
1321     if ( faceNodes.size() == 1 )
1322       toProjectNodes = ( uvBox.IsVoid() || uvBox.CornerMin().IsEqual( gp_XY(0,0), 1e-12 ));
1323     else if ( faceNodes.size() > 1 )
1324       toProjectNodes = ( uvBox.IsVoid() || uvBox.SquareExtent() < DBL_MIN );
1325
1326     // Find the corresponding source and target vertex
1327     // and <theReverse> flag needed to call mapper.Apply()
1328
1329     TopoDS_Vertex srcV1, tgtV1;
1330     bool reverse = false;
1331
1332     TopExp_Explorer vSrcExp( srcFace, TopAbs_VERTEX );
1333     srcV1 = TopoDS::Vertex( vSrcExp.Current() );
1334     tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
1335
1336     list< TopoDS_Edge > tgtEdges, srcEdges;
1337     list< int > nbEdgesInWires;
1338     SMESH_Block::GetOrderedEdges( tgtFace, tgtEdges, nbEdgesInWires, tgtV1 );
1339     SMESH_Block::GetOrderedEdges( srcFace, srcEdges, nbEdgesInWires, srcV1 );
1340
1341     if ( nbEdgesInWires.front() > 1 ) // possible to find out orientation
1342     {
1343       TopoDS_Edge srcE1 = srcEdges.front(), tgtE1 = tgtEdges.front();
1344       TopoDS_Shape srcE1bis = shape2ShapeMap( tgtE1 );
1345       reverse = ( ! srcE1.IsSame( srcE1bis ));
1346       if ( reverse &&
1347            //_sourceHypo->HasVertexAssociation() &&
1348            nbEdgesInWires.front() > 2 &&
1349            helper.IsRealSeam( tgtEdges.front() ))
1350       {
1351         // projection to a face with seam EDGE; pb is that GetOrderedEdges()
1352         // always puts a seam EDGE first (if possible) and as a result
1353         // we can't use only theReverse flag to correctly associate source
1354         // and target faces in the mapper. Thus we select srcV1 so that
1355         // GetOrderedEdges() to return EDGEs in a needed order
1356         TopoDS_Face tgtFaceBis = tgtFace;
1357         TopTools_MapOfShape checkedVMap( tgtEdges.size() );
1358         checkedVMap.Add ( srcV1 );
1359         for ( vSrcExp.Next(); vSrcExp.More(); )
1360         {
1361           tgtFaceBis.Reverse();
1362           tgtEdges.clear();
1363           SMESH_Block::GetOrderedEdges( tgtFaceBis, tgtEdges, nbEdgesInWires, tgtV1 );
1364           bool ok = true;
1365           list< TopoDS_Edge >::iterator edgeS = srcEdges.begin(), edgeT = tgtEdges.begin();
1366           for ( ; edgeS != srcEdges.end() && ok ; ++edgeS, ++edgeT )
1367             ok = edgeT->IsSame( shape2ShapeMap( *edgeS, /*isSrc=*/true ));
1368           if ( ok )
1369             break; // FOUND!
1370
1371           reverse = !reverse;
1372           if ( reverse )
1373           {
1374             vSrcExp.Next();
1375             while ( vSrcExp.More() && !checkedVMap.Add( vSrcExp.Current() ))
1376               vSrcExp.Next();
1377           }
1378           else
1379           {
1380             srcV1 = TopoDS::Vertex( vSrcExp.Current() );
1381             tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
1382             srcEdges.clear();
1383             SMESH_Block::GetOrderedEdges( srcFace, srcEdges, nbEdgesInWires, srcV1 );
1384           }
1385         }
1386       }
1387       // for the case: project to a closed face from a non-closed face w/o vertex assoc;
1388       // avoid projecting to a seam from two EDGEs with different nb nodes on them
1389       // ( test mesh_Projection_2D_01/B1 )
1390       if ( !_sourceHypo->HasVertexAssociation() &&
1391            nbEdgesInWires.front() > 2 &&
1392            helper.IsRealSeam( tgtEdges.front() ))
1393       {
1394         TopoDS_Shape srcEdge1 = shape2ShapeMap( tgtEdges.front() );
1395         list< TopoDS_Edge >::iterator srcEdge2 =
1396           std::find( srcEdges.begin(), srcEdges.end(), srcEdge1);
1397         list< TopoDS_Edge >::iterator srcEdge3 =
1398           std::find( srcEdges.begin(), srcEdges.end(), srcEdge1.Reversed());
1399         if ( srcEdge2 == srcEdges.end() || srcEdge3 == srcEdges.end() ) // srcEdge1 is not a seam
1400         {
1401           // find srcEdge2 which also will be projected to tgtEdges.front()
1402           for ( srcEdge2 = srcEdges.begin(); srcEdge2 != srcEdges.end(); ++srcEdge2 )
1403             if ( !srcEdge1.IsSame( *srcEdge2 ) &&
1404                  tgtEdges.front().IsSame( shape2ShapeMap( *srcEdge2, /*isSrc=*/true )))
1405               break;
1406           // compare nb nodes on srcEdge1 and srcEdge2
1407           if ( srcEdge2 != srcEdges.end() )
1408           {
1409             int nbN1 = 0, nbN2 = 0;
1410             if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( srcEdge1 ))
1411               nbN1 = sm->NbNodes();
1412             if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( *srcEdge2 ))
1413               nbN2 = sm->NbNodes();
1414             if ( nbN1 != nbN2 )
1415               srcV1 = helper.IthVertex( 1, srcEdges.front() );
1416           }
1417         }
1418       }
1419     }
1420     else if ( nbEdgesInWires.front() == 1 )
1421     {
1422       // TODO::Compare orientation of curves in a sole edge
1423       //RETURN_BAD_RESULT("Not implemented case");
1424     }
1425     else
1426     {
1427       RETURN_BAD_RESULT("Bad result from SMESH_Block::GetOrderedEdges()");
1428     }
1429
1430     // Load pattern from the source face
1431     SMESH_Pattern mapper;
1432     mapper.Load( srcMesh, srcFace, toProjectNodes, srcV1 );
1433     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
1434       return error(COMPERR_BAD_INPUT_MESH,"Can't load mesh pattern from the source face");
1435
1436     // --------------------
1437     // Perform 2D mapping
1438     // --------------------
1439
1440     // Compute mesh on a target face
1441
1442     mapper.Apply( tgtFace, tgtV1, reverse );
1443     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK ) {
1444       // std::ofstream file("/tmp/Pattern.smp" );
1445       // mapper.Save( file );
1446       return error("Can't apply source mesh pattern to the face");
1447     }
1448
1449     // Create the mesh
1450
1451     const bool toCreatePolygons = false, toCreatePolyedrs = false;
1452     mapper.MakeMesh( tgtMesh, toCreatePolygons, toCreatePolyedrs );
1453     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
1454       return error("Can't make mesh by source mesh pattern");
1455
1456     // -------------------------------------------------------------------------
1457     // mapper doesn't take care of nodes already existing on edges and vertices,
1458     // so we must merge nodes created by it with existing ones
1459     // -------------------------------------------------------------------------
1460
1461     SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
1462
1463     // Make groups of nodes to merge
1464
1465     // loop on EDGE and VERTEX sub-meshes of a target FACE
1466     SMESH_subMeshIteratorPtr smIt = tgtSubMesh->getDependsOnIterator(/*includeSelf=*/false,
1467                                                                      /*complexShapeFirst=*/false);
1468     while ( smIt->more() )
1469     {
1470       SMESH_subMesh*     sm = smIt->next();
1471       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
1472       if ( !smDS || smDS->NbNodes() == 0 )
1473         continue;
1474       //if ( !is1DComputed && sm->GetSubShape().ShapeType() == TopAbs_EDGE )
1475       //  break;
1476
1477       if ( helper.IsDegenShape( sm->GetId() ) ) // to merge all nodes on degenerated
1478       {
1479         if ( sm->GetSubShape().ShapeType() == TopAbs_EDGE )
1480         {
1481           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1482           SMESH_subMeshIteratorPtr smDegenIt
1483             = sm->getDependsOnIterator(/*includeSelf=*/true,/*complexShapeFirst=*/false);
1484           while ( smDegenIt->more() )
1485             if (( smDS = smDegenIt->next()->GetSubMeshDS() ))
1486             {
1487               SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1488               while ( nIt->more() )
1489                 groupsOfNodes.back().push_back( nIt->next() );
1490             }
1491         }
1492         continue; // do not treat sm of degen VERTEX
1493       }
1494
1495       // Sort new and old nodes of a submesh separately
1496
1497       bool isSeam = helper.IsRealSeam( sm->GetId() );
1498
1499       enum { NEW_NODES = 0, OLD_NODES };
1500       map< double, const SMDS_MeshNode* > u2nodesMaps[2], u2nodesOnSeam;
1501       map< double, const SMDS_MeshNode* >::iterator u_oldNode, u_newNode, u_newOnSeam, newEnd;
1502       set< const SMDS_MeshNode* > seamNodes;
1503
1504       // mapper changed, no more "mapper puts on a seam edge nodes from 2 edges"
1505       if ( isSeam && ! getBoundaryNodes ( sm, tgtFace, u2nodesOnSeam, seamNodes ))
1506         ;//RETURN_BAD_RESULT("getBoundaryNodes() failed");
1507
1508       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1509       while ( nIt->more() )
1510       {
1511         const SMDS_MeshNode* node = nIt->next();
1512         bool isOld = isOldNode( node );
1513
1514         if ( !isOld && isSeam ) { // new node on a seam edge
1515           if ( seamNodes.count( node ) )
1516             continue; // node is already in the map
1517         }
1518
1519         // sort nodes on edges by their position
1520         map< double, const SMDS_MeshNode* > & pos2nodes = u2nodesMaps[isOld ? OLD_NODES : NEW_NODES];
1521         switch ( node->GetPosition()->GetTypeOfPosition() )
1522         {
1523         case  SMDS_TOP_VERTEX: {
1524           if ( !is1DComputed && !pos2nodes.empty() )
1525             u2nodesMaps[isOld ? NEW_NODES : OLD_NODES].insert( make_pair( 0, node ));
1526           else
1527             pos2nodes.insert( make_pair( 0, node ));
1528           break;
1529         }
1530         case  SMDS_TOP_EDGE:   {
1531           const SMDS_EdgePosition* pos =
1532             static_cast<const SMDS_EdgePosition*>(node->GetPosition());
1533           pos2nodes.insert( make_pair( pos->GetUParameter(), node ));
1534           break;
1535         }
1536         default:
1537           RETURN_BAD_RESULT("Wrong node position type: "<<
1538                             node->GetPosition()->GetTypeOfPosition());
1539         }
1540       }
1541       const bool mergeNewToOld =
1542         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesMaps[ OLD_NODES ].size() );
1543       const bool mergeSeamToNew =
1544         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesOnSeam.size() );
1545
1546       if ( !mergeNewToOld )
1547         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1548              u2nodesMaps[ OLD_NODES ].size() > 0 )
1549         {
1550           u_oldNode = u2nodesMaps[ OLD_NODES ].begin(); 
1551           newEnd    = u2nodesMaps[ OLD_NODES ].end();
1552           for ( ; u_oldNode != newEnd; ++u_oldNode )
1553             SMESH_Algo::addBadInputElement( u_oldNode->second );
1554           return error( COMPERR_BAD_INPUT_MESH,
1555                         SMESH_Comment( "Existing mesh mismatches the projected 2D mesh on " )
1556                         << ( sm->GetSubShape().ShapeType() == TopAbs_EDGE ? "edge" : "vertex" )
1557                         << " #" << sm->GetId() );
1558         }
1559       if ( isSeam && !mergeSeamToNew ) {
1560         const TopoDS_Shape& seam = sm->GetSubShape();
1561         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1562              u2nodesOnSeam.size()            > 0 &&
1563              seam.ShapeType() == TopAbs_EDGE )
1564         {
1565           int nbE1 = helper.Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
1566           int nbE2 = helper.Count( srcFace, TopAbs_EDGE, /*ignoreSame=*/true );
1567           if ( nbE1 != nbE2 ) // 2 EDGEs are mapped to a seam EDGE
1568           {
1569             // find the 2 EDGEs of srcFace
1570             TopTools_DataMapIteratorOfDataMapOfShapeShape src2tgtIt( shape2ShapeMap._map2to1 );
1571             for ( ; src2tgtIt.More(); src2tgtIt.Next() )
1572               if ( seam.IsSame( src2tgtIt.Value() ))
1573                 SMESH_Algo::addBadInputElements
1574                   ( srcMesh->GetMeshDS()->MeshElements( src2tgtIt.Key() ));
1575             return error( COMPERR_BAD_INPUT_MESH,
1576                           "Different number of nodes on two edges projected to a seam edge" );
1577           }
1578         }
1579       }
1580
1581       // Make groups of nodes to merge
1582
1583       u_oldNode = u2nodesMaps[ OLD_NODES ].begin(); 
1584       u_newNode = u2nodesMaps[ NEW_NODES ].begin();
1585       newEnd    = u2nodesMaps[ NEW_NODES ].end();
1586       u_newOnSeam = u2nodesOnSeam.begin();
1587       if ( mergeNewToOld )
1588         for ( ; u_newNode != newEnd; ++u_newNode, ++u_oldNode )
1589         {
1590           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1591           groupsOfNodes.back().push_back( u_oldNode->second );
1592           groupsOfNodes.back().push_back( u_newNode->second );
1593           if ( mergeSeamToNew )
1594             groupsOfNodes.back().push_back( (u_newOnSeam++)->second );
1595         }
1596       else if ( mergeSeamToNew )
1597         for ( ; u_newNode != newEnd; ++u_newNode, ++u_newOnSeam )
1598         {
1599           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1600           groupsOfNodes.back().push_back( u_newNode->second );
1601           groupsOfNodes.back().push_back( u_newOnSeam->second );
1602         }
1603
1604     } // loop on EDGE and VERTEX submeshes of a target FACE
1605
1606     // Merge
1607
1608     SMESH_MeshEditor editor( tgtMesh );
1609     int nbFaceBeforeMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1610     editor.MergeNodes( groupsOfNodes );
1611     int nbFaceAtferMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1612     if ( nbFaceBeforeMerge != nbFaceAtferMerge && !helper.HasDegeneratedEdges() )
1613       return error(COMPERR_BAD_INPUT_MESH, "Probably invalid node parameters on geom faces");
1614
1615     // ----------------------------------------------------------------
1616     // The mapper can't create quadratic elements, so convert if needed
1617     // ----------------------------------------------------------------
1618
1619     faceIt         = srcSubMesh->GetSubMeshDS()->GetElements();
1620     bool srcIsQuad = faceIt->next()->IsQuadratic();
1621     faceIt         = tgtSubMesh->GetSubMeshDS()->GetElements();
1622     bool tgtIsQuad = faceIt->next()->IsQuadratic();
1623     if ( srcIsQuad && !tgtIsQuad )
1624     {
1625       TIDSortedElemSet tgtFaces;
1626       faceIt = tgtSubMesh->GetSubMeshDS()->GetElements();
1627       while ( faceIt->more() )
1628         tgtFaces.insert( tgtFaces.end(), faceIt->next() );
1629
1630       editor.ConvertToQuadratic(/*theForce3d=*/false, tgtFaces, false);
1631     }
1632
1633   } // end of projection using Pattern mapping
1634
1635
1636   if ( !projDone || is1DComputed )
1637     // ----------------------------------------------------------------
1638     // The mapper can create distorted faces by placing nodes out of the FACE
1639     // boundary, also bad face can be created if EDGEs already discretized
1640     // --> fix bad faces by smoothing
1641     // ----------------------------------------------------------------
1642     if ( !fixDistortedFaces( helper, tgtWires ))
1643       return error("Invalid mesh generated");
1644
1645   // ---------------------------
1646   // Check elements orientation
1647   // ---------------------------
1648
1649   TopoDS_Face face = TopoDS::Face( theShape );
1650   if ( !theMesh.IsMainShape( tgtFace ))
1651   {
1652     // find the main shape
1653     TopoDS_Shape mainShape = meshDS->ShapeToMesh();
1654     switch ( mainShape.ShapeType() ) {
1655     case TopAbs_SHELL:
1656     case TopAbs_SOLID: break;
1657     default:
1658       TopTools_ListIteratorOfListOfShape ancestIt = theMesh.GetAncestors( face );
1659       for ( ; ancestIt.More(); ancestIt.Next() ) {
1660         TopAbs_ShapeEnum type = ancestIt.Value().ShapeType();
1661         if ( type == TopAbs_SOLID ) {
1662           mainShape = ancestIt.Value();
1663           break;
1664         } else if ( type == TopAbs_SHELL ) {
1665           mainShape = ancestIt.Value();
1666         }
1667       }
1668     }
1669     // find tgtFace in the main solid or shell to know it's true orientation.
1670     TopExp_Explorer exp( mainShape, TopAbs_FACE );
1671     for ( ; exp.More(); exp.Next() ) {
1672       if ( tgtFace.IsSame( exp.Current() )) {
1673         face = TopoDS::Face( exp.Current() );
1674         break;
1675       }
1676     }
1677   }
1678   // Fix orientation
1679   if ( helper.IsReversedSubMesh( face ))
1680   {
1681     SMESH_MeshEditor editor( tgtMesh );
1682     SMDS_ElemIteratorPtr eIt = meshDS->MeshElements( face )->GetElements();
1683     while ( eIt->more() ) {
1684       const SMDS_MeshElement* e = eIt->next();
1685       if ( e->GetType() == SMDSAbs_Face && !editor.Reorient( e ))
1686         RETURN_BAD_RESULT("Pb of SMESH_MeshEditor::Reorient()");
1687     }
1688   }
1689
1690   cleaner.Release(); // not to remove mesh
1691
1692   return true;
1693 }
1694
1695
1696 //=======================================================================
1697 //function : Evaluate
1698 //purpose  : 
1699 //=======================================================================
1700
1701 bool StdMeshers_Projection_2D::Evaluate(SMESH_Mesh&         theMesh,
1702                                         const TopoDS_Shape& theShape,
1703                                         MapShapeNbElems&    aResMap)
1704 {
1705   if ( !_sourceHypo )
1706     return false;
1707
1708   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
1709   SMESH_Mesh * tgtMesh = & theMesh;
1710   if ( !srcMesh )
1711     srcMesh = tgtMesh;
1712
1713   // ---------------------------
1714   // Make sub-shapes association
1715   // ---------------------------
1716
1717   TopoDS_Face tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
1718   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
1719
1720   TAssocTool::TShapeShapeMap shape2ShapeMap;
1721   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
1722   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
1723                                              shape2ShapeMap)  ||
1724        !shape2ShapeMap.IsBound( tgtFace ))
1725     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
1726
1727   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
1728
1729   // -------------------------------------------------------
1730   // Assure that mesh on a source Face is computed/evaluated
1731   // -------------------------------------------------------
1732
1733   std::vector<int> aVec;
1734
1735   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
1736   if ( srcSubMesh->IsMeshComputed() )
1737   {
1738     aVec.resize( SMDSEntity_Last, 0 );
1739     aVec[SMDSEntity_Node] = srcSubMesh->GetSubMeshDS()->NbNodes();
1740
1741     SMDS_ElemIteratorPtr elemIt = srcSubMesh->GetSubMeshDS()->GetElements();
1742     while ( elemIt->more() )
1743       aVec[ elemIt->next()->GetEntityType() ]++;
1744   }
1745   else
1746   {
1747     MapShapeNbElems  tmpResMap;
1748     MapShapeNbElems& srcResMap = (srcMesh == tgtMesh) ? aResMap : tmpResMap;
1749     if ( !_gen->Evaluate( *srcMesh, srcShape, srcResMap ))
1750       return error(COMPERR_BAD_INPUT_MESH,"Source mesh not evaluatable");
1751     aVec = srcResMap[ srcSubMesh ];
1752     if ( aVec.empty() )
1753       return error(COMPERR_BAD_INPUT_MESH,"Source mesh is wrongly evaluated");
1754   }
1755
1756   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1757   aResMap.insert(std::make_pair(sm,aVec));
1758
1759   return true;
1760 }
1761
1762
1763 //=============================================================================
1764 /*!
1765  * \brief Sets a default event listener to submesh of the source face
1766   * \param subMesh - submesh where algo is set
1767  *
1768  * This method is called when a submesh gets HYP_OK algo_state.
1769  * After being set, event listener is notified on each event of a submesh.
1770  * Arranges that CLEAN event is translated from source submesh to
1771  * the submesh
1772  */
1773 //=============================================================================
1774
1775 void StdMeshers_Projection_2D::SetEventListener(SMESH_subMesh* subMesh)
1776 {
1777   TAssocTool::SetEventListener( subMesh,
1778                                 _sourceHypo->GetSourceFace(),
1779                                 _sourceHypo->GetSourceMesh() );
1780 }