Salome HOME
53225: Viscous Layers hyp: problem with selection of input/output faces
[modules/smesh.git] / src / StdMeshers / StdMeshers_Projection_2D.cxx
1 // Copyright (C) 2007-2016  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  SMESH SMESH : 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     src2tgtNodes.clear();
427
428     // get ordered src EDGEs
429     TError err;
430     srcWires = StdMeshers_FaceSide::GetFaceWires( srcFace, *srcMesh,/*skipMediumNodes=*/0, err);
431     if (( err && !err->IsOK() ) ||
432         ( srcWires.empty() ))
433       return err;
434
435     SMESH_MesherHelper srcHelper( *srcMesh );
436     srcHelper.SetSubShape( srcFace );
437
438     // make corresponding sequence of tgt EDGEs
439     tgtWires.resize( srcWires.size() );
440     for ( size_t iW = 0; iW < srcWires.size(); ++iW )
441     {
442       StdMeshers_FaceSidePtr srcWire = srcWires[iW];
443
444       list< TopoDS_Edge > tgtEdges;
445       TopTools_IndexedMapOfShape edgeMap; // to detect seam edges
446       for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
447       {
448         TopoDS_Edge     srcE = srcWire->Edge( iE );
449         TopoDS_Edge     tgtE = TopoDS::Edge( shape2ShapeMap( srcE, /*isSrc=*/true));
450         TopoDS_Shape srcEbis = shape2ShapeMap( tgtE, /*isSrc=*/false );
451         if ( srcE.Orientation() != srcEbis.Orientation() )
452           tgtE.Reverse();
453         // reverse a seam edge encountered for the second time
454         const int index = edgeMap.Add( tgtE );
455         if ( index < edgeMap.Extent() ) // E is a seam
456         {
457           // check which of edges to reverse, E or one already being in tgtEdges
458           if ( are2dConnected( tgtEdges.back(), tgtE, tgtFace ))
459           {
460             list< TopoDS_Edge >::iterator eIt = tgtEdges.begin();
461             std::advance( eIt, index-1 );
462             if ( are2dConnected( tgtEdges.back(), *eIt, tgtFace ))
463               eIt->Reverse();
464           }
465           else
466           {
467             tgtE.Reverse();
468           }
469         }
470         if ( srcWire->NbEdges() == 1 && tgtMesh == srcMesh ) // circle
471         {
472           // try to verify ori by propagation
473           pair<int,TopoDS_Edge> nE =
474             StdMeshers_ProjectionUtils::GetPropagationEdge( srcMesh, tgtE, srcE );
475           if ( !nE.second.IsNull() )
476             tgtE = nE.second;
477         }
478         tgtEdges.push_back( tgtE );
479       }
480
481       tgtWires[ iW ].reset( new StdMeshers_FaceSide( tgtFace, tgtEdges, tgtMesh,
482                                                      /*theIsForward = */ true,
483                                                      /*theIgnoreMediumNodes = */false));
484       StdMeshers_FaceSidePtr tgtWire = tgtWires[ iW ];
485
486       // Fill map of src to tgt nodes with nodes on edges
487
488       for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
489       {
490         if ( srcMesh->GetSubMesh( srcWire->Edge(iE) )->IsEmpty() ||
491              tgtMesh->GetSubMesh( tgtWire->Edge(iE) )->IsEmpty() )
492         {
493           // add nodes on VERTEXes for a case of not meshes EDGEs
494           const SMDS_MeshNode* srcN = srcWire->VertexNode( iE );
495           const SMDS_MeshNode* tgtN = tgtWire->VertexNode( iE );
496           if ( srcN && tgtN )
497             src2tgtNodes.insert( make_pair( srcN, tgtN ));
498         }
499         else
500         {
501           const bool skipMedium = true, isFwd = true;
502           StdMeshers_FaceSide srcEdge( srcFace, srcWire->Edge(iE), srcMesh, isFwd, skipMedium);
503           StdMeshers_FaceSide tgtEdge( tgtFace, tgtWire->Edge(iE), tgtMesh, isFwd, skipMedium);
504           
505           vector< const SMDS_MeshNode* > srcNodes = srcEdge.GetOrderedNodes();
506           vector< const SMDS_MeshNode* > tgtNodes = tgtEdge.GetOrderedNodes();
507
508           if (( srcNodes.size() != tgtNodes.size() ) && tgtNodes.size() > 0 )
509             return SMESH_ComputeError::New( COMPERR_BAD_INPUT_MESH,
510                                             "Different number of nodes on edges");
511           if ( !tgtNodes.empty() )
512           {
513             vector< const SMDS_MeshNode* >::iterator tn = tgtNodes.begin();
514             //if ( srcWire->Edge(iE).Orientation() == tgtWire->Edge(iE).Orientation() )
515             {
516               vector< const SMDS_MeshNode* >::iterator sn = srcNodes.begin();
517               for ( ; tn != tgtNodes.end(); ++tn, ++sn)
518                 src2tgtNodes.insert( make_pair( *sn, *tn ));
519             }
520             // else
521             // {
522             //   vector< const SMDS_MeshNode* >::reverse_iterator sn = srcNodes.rbegin();
523             //   for ( ; tn != tgtNodes.end(); ++tn, ++sn)
524             //     src2tgtNodes.insert( make_pair( *sn, *tn ));
525             // }
526             is1DComputed = true;
527           }
528         }
529       } // loop on EDGEs of a WIRE
530
531     } // loop on WIREs
532
533     return TError();
534   }
535
536   //================================================================================
537   /*!
538    * \brief Preform projection in case if tgtFace.IsPartner( srcFace ) and in case
539    * if projection by 3D transformation is possible
540    */
541   //================================================================================
542
543   bool projectPartner(const TopoDS_Face&                 tgtFace,
544                       const TopoDS_Face&                 srcFace,
545                       const TSideVector&                 tgtWires,
546                       const TSideVector&                 srcWires,
547                       const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
548                       TAssocTool::TNodeNodeMap&          src2tgtNodes,
549                       const bool                         is1DComputed)
550   {
551     SMESH_Mesh *    tgtMesh = tgtWires[0]->GetMesh();
552     SMESH_Mesh *    srcMesh = srcWires[0]->GetMesh();
553     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
554     SMESHDS_Mesh* srcMeshDS = srcMesh->GetMeshDS();
555     SMESH_MesherHelper helper( *tgtMesh );
556
557     const double tol = 1.e-7 * srcMeshDS->getMaxDim();
558
559     // transformation to get location of target nodes from source ones
560     StdMeshers_ProjectionUtils::TrsfFinder3D trsf;
561     bool trsfIsOK = false;
562     if ( tgtFace.IsPartner( srcFace ))
563     {
564       gp_GTrsf srcTrsf = srcFace.Location().Transformation();
565       gp_GTrsf tgtTrsf = tgtFace.Location().Transformation();
566       gp_GTrsf t = srcTrsf.Inverted().Multiplied( tgtTrsf );
567       trsf.Set( t );
568       // check
569       gp_Pnt srcP = BRep_Tool::Pnt( srcWires[0]->FirstVertex() );
570       gp_Pnt tgtP = BRep_Tool::Pnt( tgtWires[0]->FirstVertex() );
571       trsfIsOK = ( tgtP.Distance( trsf.Transform( srcP )) < tol );
572       if ( !trsfIsOK )
573       {
574         trsf.Set( tgtTrsf.Inverted().Multiplied( srcTrsf ));
575         trsfIsOK = ( tgtP.Distance( trsf.Transform( srcP )) < tol );
576       }
577     }
578     if ( !trsfIsOK )
579     {
580       // Try to find the 3D transformation
581
582       const int totNbSeg = 50;
583       vector< gp_XYZ > srcPnts, tgtPnts;
584       srcPnts.reserve( totNbSeg );
585       tgtPnts.reserve( totNbSeg );
586       gp_XYZ srcBC( 0,0,0 ), tgtBC( 0,0,0 );
587       for ( size_t iW = 0; iW < srcWires.size(); ++iW )
588       {
589         const double minSegLen = srcWires[iW]->Length() / totNbSeg;
590         for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
591         {
592           size_t nbSeg = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
593           double srcU  = srcWires[iW]->FirstParameter( iE );
594           double tgtU  = tgtWires[iW]->FirstParameter( iE );
595           double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
596           double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
597           for ( size_t i = 0; i < nbSeg; ++i  )
598           {
599             srcPnts.push_back( srcWires[iW]->Value3d( srcU ).XYZ() );
600             tgtPnts.push_back( tgtWires[iW]->Value3d( tgtU ).XYZ() );
601             srcU += srcDu;
602             tgtU += tgtDu;
603             srcBC += srcPnts.back();
604             tgtBC += tgtPnts.back();
605           }
606         }
607       }
608       if ( !trsf.Solve( srcPnts, tgtPnts ))
609         return false;
610
611       // check trsf
612
613       const int nbTestPnt = 20;
614       const size_t  iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
615       // check boundary
616       gp_Pnt trsfTgt = trsf.Transform( srcBC / srcPnts.size() );
617       trsfIsOK = ( trsfTgt.SquareDistance( tgtBC / tgtPnts.size() ) < tol*tol );
618       for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
619       {
620         gp_Pnt trsfTgt = trsf.Transform( srcPnts[i] );
621         trsfIsOK = ( trsfTgt.SquareDistance( tgtPnts[i] ) < tol*tol );
622       }
623       // check an in-FACE point
624       if ( trsfIsOK )
625       {
626         BRepAdaptor_Surface srcSurf( srcFace );
627         gp_Pnt srcP =
628           srcSurf.Value( 0.321 * ( srcSurf.FirstUParameter() + srcSurf.LastUParameter() ),
629                          0.123 * ( srcSurf.FirstVParameter() + srcSurf.LastVParameter() ));
630         gp_Pnt tgtTrsfP = trsf.Transform( srcP );
631         TopLoc_Location loc;
632         GeomAPI_ProjectPointOnSurf& proj = helper.GetProjector( tgtFace, loc, 0.1*tol );
633         if ( !loc.IsIdentity() )
634           tgtTrsfP.Transform( loc.Transformation().Inverted() );
635         proj.Perform( tgtTrsfP );
636         trsfIsOK = ( proj.IsDone() &&
637                      proj.NbPoints() > 0 &&
638                      proj.LowerDistance() < tol );
639       }
640       if ( !trsfIsOK )
641         return false;
642     }
643
644     // Make new faces
645
646     // prepare the helper to adding quadratic elements if necessary
647     //helper.SetSubShape( tgtFace );
648     helper.IsQuadraticSubMesh( tgtFace );
649
650     SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
651     if ( !is1DComputed && srcSubDS->NbElements() )
652       helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
653
654     SMESH_MesherHelper srcHelper( *srcMesh );
655     srcHelper.SetSubShape( srcFace );
656
657     const SMDS_MeshNode* nullNode = 0;
658     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
659
660     // indices of nodes to create properly oriented faces
661     bool isReverse = ( !trsf.IsIdentity() );
662     int tri1 = 1, tri2 = 2, quad1 = 1, quad3 = 3;
663     if ( isReverse )
664       std::swap( tri1, tri2 ), std::swap( quad1, quad3 );
665
666     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
667     vector< const SMDS_MeshNode* > tgtNodes;
668     while ( elemIt->more() ) // loop on all mesh faces on srcFace
669     {
670       const SMDS_MeshElement* elem = elemIt->next();
671       const int nbN = elem->NbCornerNodes(); 
672       tgtNodes.resize( nbN );
673       helper.SetElementsOnShape( false );
674       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
675       {
676         const SMDS_MeshNode* srcNode = elem->GetNode(i);
677         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
678         if ( srcN_tgtN->second == nullNode )
679         {
680           // create a new node
681           gp_Pnt tgtP = trsf.Transform( SMESH_TNodeXYZ( srcNode ));
682           SMDS_MeshNode* n = helper.AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
683           srcN_tgtN->second = n;
684           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
685           {
686           case SMDS_TOP_FACE:
687           {
688             gp_Pnt2d srcUV = srcHelper.GetNodeUV( srcFace, srcNode );
689             tgtMeshDS->SetNodeOnFace( n, helper.GetSubShapeID(), srcUV.X(), srcUV.Y() );
690             break;
691           }
692           case SMDS_TOP_EDGE:
693           {
694             const TopoDS_Shape & srcE = srcMeshDS->IndexToShape( srcNode->getshapeId() );
695             const TopoDS_Shape & tgtE = shape2ShapeMap( srcE, /*isSrc=*/true );
696             double srcU = srcHelper.GetNodeU( TopoDS::Edge( srcE ), srcNode );
697             tgtMeshDS->SetNodeOnEdge( n, TopoDS::Edge( tgtE ), srcU );
698             break;
699           }
700           case SMDS_TOP_VERTEX:
701           {
702             const TopoDS_Shape & srcV = srcMeshDS->IndexToShape( srcNode->getshapeId() );
703             const TopoDS_Shape & tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
704             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
705             break;
706           }
707           default:;
708           }
709         }
710         tgtNodes[i] = srcN_tgtN->second;
711       }
712       // create a new face
713       helper.SetElementsOnShape( true );
714       switch ( nbN )
715       {
716       case 3: helper.AddFace(tgtNodes[0], tgtNodes[tri1], tgtNodes[tri2]); break;
717       case 4: helper.AddFace(tgtNodes[0], tgtNodes[quad1], tgtNodes[2], tgtNodes[quad3]); break;
718       default:
719         if ( isReverse ) std::reverse( tgtNodes.begin(), tgtNodes.end() );
720         helper.AddPolygonalFace( tgtNodes );
721       }
722     }
723
724     // check node positions
725
726     if ( !tgtFace.IsPartner( srcFace ) )
727     {
728       SMESH_MesherHelper edgeHelper( *tgtMesh );
729       edgeHelper.ToFixNodeParameters( true );
730       helper.ToFixNodeParameters( true );
731
732       int nbOkPos = 0;
733       bool toCheck = true;
734       const double tol2d = 1e-12;
735       srcN_tgtN = src2tgtNodes.begin();
736       for ( ; srcN_tgtN != src2tgtNodes.end(); ++srcN_tgtN )
737       {
738         const SMDS_MeshNode* n = srcN_tgtN->second;
739         switch ( n->GetPosition()->GetTypeOfPosition() )
740         {
741         case SMDS_TOP_FACE:
742         {
743           if ( nbOkPos > 10 ) break;
744           gp_XY uv = helper.GetNodeUV( tgtFace, n ), uvBis = uv;
745           if (( helper.CheckNodeUV( tgtFace, n, uv, tol )) &&
746               (( uv - uvBis ).SquareModulus() < tol2d ))
747             ++nbOkPos;
748           else
749             nbOkPos = -((int) src2tgtNodes.size() );
750           break;
751         }
752         case SMDS_TOP_EDGE:
753         {
754           const TopoDS_Edge & tgtE = TopoDS::Edge( tgtMeshDS->IndexToShape( n->getshapeId() ));
755           edgeHelper.SetSubShape( tgtE );
756           edgeHelper.GetNodeU( tgtE, n, 0, &toCheck );
757           break;
758         }
759         default:;
760         }
761       }
762     }
763
764     return true;
765
766   } //   bool projectPartner()
767
768   //================================================================================
769   /*!
770    * \brief Preform projection in case if the faces are similar in 2D space
771    */
772   //================================================================================
773
774   bool projectBy2DSimilarity(const TopoDS_Face&                 tgtFace,
775                              const TopoDS_Face&                 srcFace,
776                              const TSideVector&                 tgtWires,
777                              const TSideVector&                 srcWires,
778                              const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
779                              TAssocTool::TNodeNodeMap&          src2tgtNodes,
780                              const bool                         is1DComputed)
781   {
782     SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
783     SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
784
785     // WARNING: we can have problems if the FACE is symmetrical in 2D,
786     // then the projection can be mirrored relating to what is expected
787
788     // 1) Find 2D transformation
789
790     StdMeshers_ProjectionUtils::TrsfFinder2D trsf;
791     {
792       // get 2 pairs of corresponding UVs
793       gp_Pnt2d srcP0 = srcWires[0]->Value2d(0.0);
794       gp_Pnt2d srcP1 = srcWires[0]->Value2d(0.333);
795       gp_Pnt2d tgtP0 = tgtWires[0]->Value2d(0.0);
796       gp_Pnt2d tgtP1 = tgtWires[0]->Value2d(0.333);
797
798       // make transformation
799       gp_Trsf2d fromTgtCS, toSrcCS; // from/to global CS
800       gp_Ax2d srcCS( srcP0, gp_Vec2d( srcP0, srcP1 ));
801       gp_Ax2d tgtCS( tgtP0, gp_Vec2d( tgtP0, tgtP1 ));
802       toSrcCS  .SetTransformation( srcCS );
803       fromTgtCS.SetTransformation( tgtCS );
804       fromTgtCS.Invert();
805       trsf.Set( fromTgtCS * toSrcCS );
806
807       // check transformation
808       bool trsfIsOK = true;
809       const double tol = 1e-5 * gp_Vec2d( srcP0, srcP1 ).Magnitude();
810       for ( double u = 0.12; ( u < 1. && trsfIsOK ); u += 0.1 )
811       {
812         gp_Pnt2d srcUV  = srcWires[0]->Value2d( u );
813         gp_Pnt2d tgtUV  = tgtWires[0]->Value2d( u );
814         gp_Pnt2d tgtUV2 = trsf.Transform( srcUV );
815         trsfIsOK = ( tgtUV.Distance( tgtUV2 ) < tol );
816       }
817
818       // Find trsf using a least-square approximation
819       if ( !trsfIsOK )
820       {
821         // find trsf
822         const int totNbSeg = 50;
823         vector< gp_XY > srcPnts, tgtPnts;
824         srcPnts.reserve( totNbSeg );
825         tgtPnts.reserve( totNbSeg );
826         for ( size_t iW = 0; iW < srcWires.size(); ++iW )
827         {
828           const double minSegLen = srcWires[iW]->Length() / totNbSeg;
829           for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
830           {
831             size_t nbSeg = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
832             double srcU  = srcWires[iW]->FirstParameter( iE );
833             double tgtU  = tgtWires[iW]->FirstParameter( iE );
834             double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
835             double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
836             for ( size_t i = 0; i < nbSeg; ++i, srcU += srcDu, tgtU += tgtDu  )
837             {
838               srcPnts.push_back( srcWires[iW]->Value2d( srcU ).XY() );
839               tgtPnts.push_back( tgtWires[iW]->Value2d( tgtU ).XY() );
840             }
841           }
842         }
843         if ( !trsf.Solve( srcPnts, tgtPnts ))
844           return false;
845
846         // check trsf
847
848         trsfIsOK = true;
849         const int nbTestPnt = 10;
850         const size_t  iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
851         for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
852         {
853           gp_Pnt2d trsfTgt = trsf.Transform( srcPnts[i] );
854           trsfIsOK = ( trsfTgt.Distance( tgtPnts[i] ) < tol );
855         }
856         if ( !trsfIsOK )
857           return false;
858       }
859     } // "Find transformation" block
860
861     // 2) Projection
862
863     SMESHDS_SubMesh* srcSubDS = srcMesh->GetMeshDS()->MeshElements( srcFace );
864
865     SMESH_MesherHelper helper( *tgtMesh );
866     helper.SetSubShape( tgtFace );
867     if ( is1DComputed )
868       helper.IsQuadraticSubMesh( tgtFace );
869     else
870       helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
871     helper.SetElementsOnShape( true );
872     Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
873     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
874
875     SMESH_MesherHelper srcHelper( *srcMesh );
876     srcHelper.SetSubShape( srcFace );
877
878     const SMDS_MeshNode* nullNode = 0;
879     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
880
881     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
882     vector< const SMDS_MeshNode* > tgtNodes;
883     bool uvOK;
884     while ( elemIt->more() ) // loop on all mesh faces on srcFace
885     {
886       const SMDS_MeshElement* elem = elemIt->next();
887       const int nbN = elem->NbCornerNodes(); 
888       tgtNodes.resize( nbN );
889       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
890       {
891         const SMDS_MeshNode* srcNode = elem->GetNode(i);
892         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
893         if ( srcN_tgtN->second == nullNode )
894         {
895           // create a new node
896           gp_Pnt2d srcUV = srcHelper.GetNodeUV( srcFace, srcNode,
897                                                 elem->GetNode( helper.WrapIndex(i+1,nbN)), &uvOK);
898           gp_Pnt2d   tgtUV = trsf.Transform( srcUV );
899           gp_Pnt      tgtP = tgtSurface->Value( tgtUV.X(), tgtUV.Y() );
900           SMDS_MeshNode* n = tgtMeshDS->AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
901           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
902           {
903           case SMDS_TOP_FACE: {
904             tgtMeshDS->SetNodeOnFace( n, helper.GetSubShapeID(), tgtUV.X(), tgtUV.Y() );
905             break;
906           }
907           case SMDS_TOP_EDGE: {
908             TopoDS_Shape srcEdge = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
909             TopoDS_Edge  tgtEdge = TopoDS::Edge( shape2ShapeMap( srcEdge, /*isSrc=*/true ));
910             double U = Precision::Infinite();
911             helper.CheckNodeU( tgtEdge, n, U, Precision::PConfusion());
912             tgtMeshDS->SetNodeOnEdge( n, TopoDS::Edge( tgtEdge ), U );
913             break;
914           }
915           case SMDS_TOP_VERTEX: {
916             TopoDS_Shape srcV = srcHelper.GetSubShapeByNode( srcNode, srcHelper.GetMeshDS() );
917             TopoDS_Shape tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
918             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
919             break;
920           }
921           default:;
922           }
923           srcN_tgtN->second = n;
924         }
925         tgtNodes[i] = srcN_tgtN->second;
926       }
927       // create a new face (with reversed orientation)
928       switch ( nbN )
929       {
930       case 3: helper.AddFace(tgtNodes[0], tgtNodes[2], tgtNodes[1]); break;
931       case 4: helper.AddFace(tgtNodes[0], tgtNodes[3], tgtNodes[2], tgtNodes[1]); break;
932       }
933     }  // loop on all mesh faces on srcFace
934
935     return true;
936   }
937
938   //================================================================================
939   /*!
940    * \brief Preform projection in case of quadrilateral faces
941    */
942   //================================================================================
943
944   bool projectQuads(const TopoDS_Face&                 tgtFace,
945                     const TopoDS_Face&                 srcFace,
946                     const TSideVector&                 tgtWires,
947                     const TSideVector&                 srcWires,
948                     const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
949                     TAssocTool::TNodeNodeMap&          src2tgtNodes,
950                     const bool                         is1DComputed)
951   {
952     SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
953     SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
954     //SMESHDS_Mesh * tgtMeshDS = tgtMesh->GetMeshDS();
955     SMESHDS_Mesh * srcMeshDS = srcMesh->GetMeshDS();
956
957     if ( srcWires[0]->NbEdges() != 4 )
958       return false;
959     if ( !is1DComputed )
960       return false;
961     for ( int iE = 0; iE < 4; ++iE )
962     {
963       SMESHDS_SubMesh* sm = srcMeshDS->MeshElements( srcWires[0]->Edge( iE ));
964       if ( !sm ) return false;
965       if ( sm->NbNodes() + sm->NbElements() == 0 ) return false;
966     }
967     if ( BRepAdaptor_Surface( tgtFace ).GetType() != GeomAbs_Plane )
968       return false;
969     // if ( BRepAdaptor_Surface( tgtFace ).GetType() == GeomAbs_Plane &&
970     //      BRepAdaptor_Surface( srcFace ).GetType() == GeomAbs_Plane )
971     //   return false; // too easy
972
973     // load EDGEs to SMESH_Block
974
975     SMESH_Block block;
976     TopTools_IndexedMapOfOrientedShape blockSubShapes;
977     {
978       const TopoDS_Solid& box = srcMesh->PseudoShape();
979       TopoDS_Shell shell = TopoDS::Shell( TopExp_Explorer( box, TopAbs_SHELL ).Current() );
980       TopoDS_Vertex v;
981       block.LoadBlockShapes( shell, v, v, blockSubShapes ); // fill all since operator[] is missing
982     }
983     const SMESH_Block::TShapeID srcFaceBID = SMESH_Block::ID_Fxy0;
984     const SMESH_Block::TShapeID tgtFaceBID = SMESH_Block::ID_Fxy1;
985     vector< int > edgeBID;
986     block.GetFaceEdgesIDs( srcFaceBID, edgeBID ); // u0, u1, 0v, 1v
987     blockSubShapes.Substitute( edgeBID[0], srcWires[0]->Edge(0) );
988     blockSubShapes.Substitute( edgeBID[1], srcWires[0]->Edge(2) );
989     blockSubShapes.Substitute( edgeBID[2], srcWires[0]->Edge(3) );
990     blockSubShapes.Substitute( edgeBID[3], srcWires[0]->Edge(1) );
991     block.GetFaceEdgesIDs( tgtFaceBID, edgeBID ); // u0, u1, 0v, 1v
992     blockSubShapes.Substitute( edgeBID[0], tgtWires[0]->Edge(0) );
993     blockSubShapes.Substitute( edgeBID[1], tgtWires[0]->Edge(2) );
994     blockSubShapes.Substitute( edgeBID[2], tgtWires[0]->Edge(3) );
995     blockSubShapes.Substitute( edgeBID[3], tgtWires[0]->Edge(1) );
996     block.LoadFace( srcFace, srcFaceBID, blockSubShapes );
997     block.LoadFace( tgtFace, tgtFaceBID, blockSubShapes );
998
999     // remember connectivity of new faces in terms of ( node-or-XY )
1000
1001     typedef std::pair< const SMDS_MeshNode*, gp_XYZ > TNodeOrXY; // node-or-XY
1002     typedef std::vector< TNodeOrXY* >                 TFaceConn; // face connectivity
1003     std::vector< TFaceConn >                    newFacesVec;     // connectivity of all faces
1004     std::map< const SMDS_MeshNode*, TNodeOrXY > srcNode2tgtNXY;  // src node -> node-or-XY
1005
1006     TAssocTool::TNodeNodeMap::iterator                                       srcN_tgtN;
1007     std::map< const SMDS_MeshNode*, TNodeOrXY >::iterator                    srcN_tgtNXY;
1008     std::pair< std::map< const SMDS_MeshNode*, TNodeOrXY >::iterator, bool > n2n_isNew;
1009     TNodeOrXY nullNXY( (SMDS_MeshNode*)NULL, gp_XYZ(0,0,0) );
1010
1011     SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
1012     newFacesVec.resize( srcSubDS->NbElements() );
1013     int iFaceSrc = 0;
1014
1015     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
1016     while ( elemIt->more() ) // loop on all mesh faces on srcFace
1017     {
1018       const SMDS_MeshElement* elem = elemIt->next();
1019       TFaceConn& tgtNodes = newFacesVec[ iFaceSrc++ ];
1020
1021       const int nbN = elem->NbCornerNodes(); 
1022       tgtNodes.resize( nbN );
1023       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
1024       {
1025         const SMDS_MeshNode* srcNode = elem->GetNode(i);
1026         n2n_isNew = srcNode2tgtNXY.insert( make_pair( srcNode, nullNXY ));
1027         TNodeOrXY & tgtNodeOrXY = n2n_isNew.first->second;
1028         if ( n2n_isNew.second ) // new src node encounters
1029         {
1030           srcN_tgtN = src2tgtNodes.find( srcNode );
1031           if ( srcN_tgtN != src2tgtNodes.end() )
1032           {
1033             tgtNodeOrXY.first = srcN_tgtN->second; // tgt node exists
1034           }
1035           else 
1036           {
1037             // find XY of src node withing the quadrilateral srcFace
1038             if ( !block.ComputeParameters( SMESH_TNodeXYZ( srcNode ),
1039                                            tgtNodeOrXY.second, srcFaceBID ))
1040               return false;
1041           }
1042         }
1043         tgtNodes[ i ] = & tgtNodeOrXY;
1044       }
1045     }
1046
1047     // as all XY are computed, create tgt nodes and faces
1048
1049     SMESH_MesherHelper helper( *tgtMesh );
1050     helper.SetSubShape( tgtFace );
1051     if ( is1DComputed )
1052       helper.IsQuadraticSubMesh( tgtFace );
1053     else
1054       helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
1055     helper.SetElementsOnShape( true );
1056     Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
1057
1058     SMESH_MesherHelper srcHelper( *srcMesh );
1059     srcHelper.SetSubShape( srcFace );
1060
1061     vector< const SMDS_MeshNode* > tgtNodes;
1062     gp_XY uv;
1063
1064     for ( size_t iFaceTgt = 0; iFaceTgt < newFacesVec.size(); ++iFaceTgt )
1065     {
1066       TFaceConn& tgtConn = newFacesVec[ iFaceTgt ];
1067       tgtNodes.resize( tgtConn.size() );
1068       for ( size_t iN = 0; iN < tgtConn.size(); ++iN )
1069       {
1070         const SMDS_MeshNode* & tgtN = tgtConn[ iN ]->first;
1071         if ( !tgtN ) // create a node
1072         {
1073           if ( !block.FaceUV( tgtFaceBID, tgtConn[iN]->second, uv ))
1074             return false;
1075           gp_Pnt p = tgtSurface->Value( uv.X(), uv.Y() );
1076           tgtN = helper.AddNode( p.X(), p.Y(), p.Z(), uv.X(), uv.Y() );
1077         }
1078         tgtNodes[ tgtNodes.size() - iN - 1] = tgtN; // reversed orientation
1079       }
1080       switch ( tgtNodes.size() )
1081       {
1082       case 3: helper.AddFace(tgtNodes[0], tgtNodes[1], tgtNodes[2]); break;
1083       case 4: helper.AddFace(tgtNodes[0], tgtNodes[1], tgtNodes[2], tgtNodes[3]); break;
1084       default:
1085         if ( tgtNodes.size() > 4 )
1086           helper.AddPolygonalFace( tgtNodes );
1087       }
1088     }
1089     return true;
1090
1091   } // bool projectQuads(...)
1092
1093   //================================================================================
1094   /*!
1095    * \brief Fix bad faces by smoothing
1096    */
1097   //================================================================================
1098
1099   bool fixDistortedFaces( SMESH_MesherHelper& helper,
1100                           TSideVector&        tgtWires )
1101   {
1102     SMESH_subMesh* faceSM = helper.GetMesh()->GetSubMesh( helper.GetSubShape() );
1103
1104     if ( helper.IsDistorted2D( faceSM, /*checkUV=*/false ))
1105     {
1106       SMESH_MeshEditor editor( helper.GetMesh() );
1107       SMESHDS_SubMesh* smDS = faceSM->GetSubMeshDS();
1108       const TopoDS_Face&  F = TopoDS::Face( faceSM->GetSubShape() );
1109
1110       TIDSortedElemSet faces;
1111       SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
1112       for ( faceIt = smDS->GetElements(); faceIt->more(); )
1113         faces.insert( faces.end(), faceIt->next() );
1114
1115       // choose smoothing algo
1116       //SMESH_MeshEditor:: SmoothMethod algo = SMESH_MeshEditor::CENTROIDAL;
1117       bool isConcaveBoundary = false;
1118       for ( size_t iW = 0; iW < tgtWires.size() && !isConcaveBoundary; ++iW )
1119       {
1120         TopoDS_Edge prevEdge = tgtWires[iW]->Edge( tgtWires[iW]->NbEdges() - 1 );
1121         for ( int iE = 0; iE < tgtWires[iW]->NbEdges() && !isConcaveBoundary; ++iE )
1122         {
1123           double angle = helper.GetAngle( prevEdge, tgtWires[iW]->Edge( iE ),
1124                                           F,        tgtWires[iW]->FirstVertex( iE ));
1125           isConcaveBoundary = ( angle < -5. * M_PI / 180. );
1126
1127           prevEdge = tgtWires[iW]->Edge( iE );
1128         }
1129       }
1130       SMESH_MeshEditor:: SmoothMethod algo =
1131         isConcaveBoundary ? SMESH_MeshEditor::CENTROIDAL : SMESH_MeshEditor::LAPLACIAN;
1132
1133       // smooth in 2D or 3D?
1134       TopLoc_Location loc;
1135       Handle(Geom_Surface) surface = BRep_Tool::Surface( F, loc );
1136       bool isPlanar = GeomLib_IsPlanarSurface( surface ).IsPlanar();
1137
1138       // smoothing
1139       set<const SMDS_MeshNode*> fixedNodes;
1140       editor.Smooth( faces, fixedNodes, algo, /*nbIterations=*/ 10,
1141                      /*theTgtAspectRatio=*/1.0, /*the2D=*/!isPlanar);
1142
1143       helper.ToFixNodeParameters( true );
1144
1145       return !helper.IsDistorted2D( faceSM, /*checkUV=*/true );
1146     }
1147     return true;
1148   }
1149
1150 } // namespace
1151
1152
1153 //=======================================================================
1154 //function : Compute
1155 //purpose  :
1156 //=======================================================================
1157
1158 bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
1159 {
1160   _src2tgtNodes.clear();
1161
1162   if ( !_sourceHypo )
1163     return false;
1164
1165   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
1166   SMESH_Mesh * tgtMesh = & theMesh;
1167   if ( !srcMesh )
1168     srcMesh = tgtMesh;
1169
1170   SMESHDS_Mesh * meshDS = theMesh.GetMeshDS();
1171   SMESH_MesherHelper helper( theMesh );
1172
1173   // ---------------------------
1174   // Make sub-shapes association
1175   // ---------------------------
1176
1177   TopoDS_Face   tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
1178   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
1179
1180   TAssocTool::TShapeShapeMap shape2ShapeMap;
1181   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
1182   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
1183                                              shape2ShapeMap)  ||
1184        !shape2ShapeMap.IsBound( tgtFace ))
1185   {
1186     if ( srcShape.ShapeType() == TopAbs_FACE )
1187     {
1188       int nbE1 = helper.Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
1189       int nbE2 = helper.Count( srcShape, TopAbs_EDGE, /*ignoreSame=*/true );
1190       if ( nbE1 != nbE2 )
1191         return error(COMPERR_BAD_SHAPE,
1192                      SMESH_Comment("Different number of edges in source and target faces: ")
1193                      << nbE2 << " and " << nbE1 );
1194     }
1195     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
1196   }
1197   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
1198
1199   // orient faces
1200   // if ( srcMesh == tgtMesh )
1201   // {
1202   //   TopoDS_Shape solid =
1203   //     helper.GetCommonAncestor( srcFace, tgtFace, *tgtMesh, TopAbs_SOLID );
1204   //   if ( !solid.IsNull() )
1205   //   {
1206   //     srcFace.Orientation( helper.GetSubShapeOri( solid, srcFace ));
1207   //     tgtFace.Orientation( helper.GetSubShapeOri( solid, tgtFace ));
1208   //   }
1209   //   else if ( helper.NbAncestors( srcFace, *tgtMesh, TopAbs_SOLID ) == 1 &&
1210   //             helper.NbAncestors( tgtFace, *tgtMesh, TopAbs_SOLID ) == 1 )
1211   //   {
1212   //     srcFace.Orientation( helper.GetSubShapeOri( tgtMesh->GetShapeToMesh(), srcFace ));
1213   //     tgtFace.Orientation( helper.GetSubShapeOri( tgtMesh->GetShapeToMesh(), tgtFace ));
1214   //   }
1215   // }
1216   // ----------------------------------------------
1217   // Assure that mesh on a source Face is computed
1218   // ----------------------------------------------
1219
1220   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
1221   SMESH_subMesh* tgtSubMesh = tgtMesh->GetSubMesh( tgtFace );
1222
1223   string srcMeshError;
1224   if ( tgtMesh == srcMesh ) {
1225     if ( !TAssocTool::MakeComputed( srcSubMesh ))
1226       srcMeshError = TAssocTool::SourceNotComputedError( srcSubMesh, this );
1227   }
1228   else {
1229     if ( !srcSubMesh->IsMeshComputed() )
1230       srcMeshError = TAssocTool::SourceNotComputedError();
1231   }
1232   if ( !srcMeshError.empty() )
1233     return error(COMPERR_BAD_INPUT_MESH, srcMeshError );
1234
1235   // ===========
1236   // Projection
1237   // ===========
1238
1239   // get ordered src and tgt EDGEs
1240   TSideVector srcWires, tgtWires;
1241   bool is1DComputed = false; // if any tgt EDGE is meshed
1242   TError err = getWires( tgtFace, srcFace, tgtMesh, srcMesh,
1243                          shape2ShapeMap, srcWires, tgtWires, _src2tgtNodes, is1DComputed );
1244   if ( err && !err->IsOK() )
1245     return error( err );
1246
1247   bool projDone = false;
1248
1249   if ( !projDone )
1250   {
1251     // try to project from the same face with different location
1252     projDone = projectPartner( tgtFace, srcFace, tgtWires, srcWires,
1253                                shape2ShapeMap, _src2tgtNodes, is1DComputed );
1254   }
1255   if ( !projDone )
1256   {
1257     // projection in case if the faces are similar in 2D space
1258     projDone = projectBy2DSimilarity( tgtFace, srcFace, tgtWires, srcWires,
1259                                       shape2ShapeMap, _src2tgtNodes, is1DComputed );
1260   }
1261   if ( !projDone )
1262   {
1263     // projection in case of quadrilateral faces
1264     // projDone = projectQuads( tgtFace, srcFace, tgtWires, srcWires,
1265     //                          shape2ShapeMap, _src2tgtNodes, is1DComputed);
1266   }
1267
1268   helper.SetSubShape( tgtFace );
1269
1270   // it will remove mesh built on edges and vertices in failure case
1271   MeshCleaner cleaner( tgtSubMesh );
1272
1273   if ( !projDone )
1274   {
1275     _src2tgtNodes.clear();
1276     // --------------------
1277     // Prepare to mapping 
1278     // --------------------
1279
1280     // Check if node projection to a face is needed
1281     Bnd_B2d uvBox;
1282     SMDS_ElemIteratorPtr faceIt = srcSubMesh->GetSubMeshDS()->GetElements();
1283     set< const SMDS_MeshNode* > faceNodes;
1284     for ( ; faceNodes.size() < 3 && faceIt->more();  ) {
1285       const SMDS_MeshElement* face = faceIt->next();
1286       SMDS_ElemIteratorPtr nodeIt = face->nodesIterator();
1287       while ( nodeIt->more() ) {
1288         const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
1289         if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE &&
1290              faceNodes.insert( node ).second )
1291           uvBox.Add( helper.GetNodeUV( srcFace, node ));
1292       }
1293     }
1294     bool toProjectNodes = false;
1295     if ( faceNodes.size() == 1 )
1296       toProjectNodes = ( uvBox.IsVoid() || uvBox.CornerMin().IsEqual( gp_XY(0,0), 1e-12 ));
1297     else if ( faceNodes.size() > 1 )
1298       toProjectNodes = ( uvBox.IsVoid() || uvBox.SquareExtent() < DBL_MIN );
1299
1300     // Find the corresponding source and target vertex
1301     // and <theReverse> flag needed to call mapper.Apply()
1302
1303     TopoDS_Vertex srcV1, tgtV1;
1304     bool reverse = false;
1305
1306     TopExp_Explorer vSrcExp( srcFace, TopAbs_VERTEX );
1307     srcV1 = TopoDS::Vertex( vSrcExp.Current() );
1308     tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
1309
1310     list< TopoDS_Edge > tgtEdges, srcEdges;
1311     list< int > nbEdgesInWires;
1312     SMESH_Block::GetOrderedEdges( tgtFace, tgtEdges, nbEdgesInWires, tgtV1 );
1313     SMESH_Block::GetOrderedEdges( srcFace, srcEdges, nbEdgesInWires, srcV1 );
1314
1315     if ( nbEdgesInWires.front() > 1 ) // possible to find out orientation
1316     {
1317       TopoDS_Edge srcE1 = srcEdges.front(), tgtE1 = tgtEdges.front();
1318       TopoDS_Shape srcE1bis = shape2ShapeMap( tgtE1 );
1319       reverse = ( ! srcE1.IsSame( srcE1bis ));
1320       if ( reverse &&
1321            //_sourceHypo->HasVertexAssociation() &&
1322            nbEdgesInWires.front() > 2 &&
1323            helper.IsRealSeam( tgtEdges.front() ))
1324       {
1325         // projection to a face with seam EDGE; pb is that GetOrderedEdges()
1326         // always puts a seam EDGE first (if possible) and as a result
1327         // we can't use only theReverse flag to correctly associate source
1328         // and target faces in the mapper. Thus we select srcV1 so that
1329         // GetOrderedEdges() to return EDGEs in a needed order
1330         TopoDS_Face tgtFaceBis = tgtFace;
1331         TopTools_MapOfShape checkedVMap( tgtEdges.size() );
1332         checkedVMap.Add ( srcV1 );
1333         for ( vSrcExp.Next(); vSrcExp.More(); )
1334         {
1335           tgtFaceBis.Reverse();
1336           tgtEdges.clear();
1337           SMESH_Block::GetOrderedEdges( tgtFaceBis, tgtEdges, nbEdgesInWires, tgtV1 );
1338           bool ok = true;
1339           list< TopoDS_Edge >::iterator edgeS = srcEdges.begin(), edgeT = tgtEdges.begin();
1340           for ( ; edgeS != srcEdges.end() && ok ; ++edgeS, ++edgeT )
1341             ok = edgeT->IsSame( shape2ShapeMap( *edgeS, /*isSrc=*/true ));
1342           if ( ok )
1343             break; // FOUND!
1344
1345           reverse = !reverse;
1346           if ( reverse )
1347           {
1348             vSrcExp.Next();
1349             while ( vSrcExp.More() && !checkedVMap.Add( vSrcExp.Current() ))
1350               vSrcExp.Next();
1351           }
1352           else
1353           {
1354             srcV1 = TopoDS::Vertex( vSrcExp.Current() );
1355             tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
1356             srcEdges.clear();
1357             SMESH_Block::GetOrderedEdges( srcFace, srcEdges, nbEdgesInWires, srcV1 );
1358           }
1359         }
1360       }
1361       // for the case: project to a closed face from a non-closed face w/o vertex assoc;
1362       // avoid projecting to a seam from two EDGEs with different nb nodes on them
1363       // ( test mesh_Projection_2D_01/B1 )
1364       if ( !_sourceHypo->HasVertexAssociation() &&
1365            nbEdgesInWires.front() > 2 &&
1366            helper.IsRealSeam( tgtEdges.front() ))
1367       {
1368         TopoDS_Shape srcEdge1 = shape2ShapeMap( tgtEdges.front() );
1369         list< TopoDS_Edge >::iterator srcEdge2 =
1370           std::find( srcEdges.begin(), srcEdges.end(), srcEdge1);
1371         list< TopoDS_Edge >::iterator srcEdge3 =
1372           std::find( srcEdges.begin(), srcEdges.end(), srcEdge1.Reversed());
1373         if ( srcEdge2 == srcEdges.end() || srcEdge3 == srcEdges.end() ) // srcEdge1 is not a seam
1374         {
1375           // find srcEdge2 which also will be projected to tgtEdges.front()
1376           for ( srcEdge2 = srcEdges.begin(); srcEdge2 != srcEdges.end(); ++srcEdge2 )
1377             if ( !srcEdge1.IsSame( *srcEdge2 ) &&
1378                  tgtEdges.front().IsSame( shape2ShapeMap( *srcEdge2, /*isSrc=*/true )))
1379               break;
1380           // compare nb nodes on srcEdge1 and srcEdge2
1381           if ( srcEdge2 != srcEdges.end() )
1382           {
1383             int nbN1 = 0, nbN2 = 0;
1384             if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( srcEdge1 ))
1385               nbN1 = sm->NbNodes();
1386             if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( *srcEdge2 ))
1387               nbN2 = sm->NbNodes();
1388             if ( nbN1 != nbN2 )
1389               srcV1 = helper.IthVertex( 1, srcEdges.front() );
1390           }
1391         }
1392       }
1393     }
1394     else if ( nbEdgesInWires.front() == 1 ) // a sole edge in a wire
1395     {
1396       TopoDS_Edge srcE1 = srcEdges.front(), tgtE1 = tgtEdges.front();
1397       for ( size_t iW = 0; iW < srcWires.size(); ++iW )
1398       {
1399         StdMeshers_FaceSidePtr srcWire = srcWires[iW];
1400         for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
1401           if ( srcE1.IsSame( srcWire->Edge( iE )))
1402           {
1403             reverse = ( tgtE1.Orientation() != tgtWires[iW]->Edge( iE ).Orientation() );
1404             break;
1405           }
1406       }
1407     }
1408     else
1409     {
1410       RETURN_BAD_RESULT("Bad result from SMESH_Block::GetOrderedEdges()");
1411     }
1412
1413     // Load pattern from the source face
1414     SMESH_Pattern mapper;
1415     mapper.Load( srcMesh, srcFace, toProjectNodes, srcV1 );
1416     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
1417       return error(COMPERR_BAD_INPUT_MESH,"Can't load mesh pattern from the source face");
1418
1419     // --------------------
1420     // Perform 2D mapping
1421     // --------------------
1422
1423     // Compute mesh on a target face
1424
1425     mapper.Apply( tgtFace, tgtV1, reverse );
1426     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK ) {
1427       // std::ofstream file("/tmp/Pattern.smp" );
1428       // mapper.Save( file );
1429       return error("Can't apply source mesh pattern to the face");
1430     }
1431
1432     // Create the mesh
1433
1434     const bool toCreatePolygons = false, toCreatePolyedrs = false;
1435     mapper.MakeMesh( tgtMesh, toCreatePolygons, toCreatePolyedrs );
1436     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
1437       return error("Can't make mesh by source mesh pattern");
1438
1439   } // end of projection using Pattern mapping
1440
1441   {
1442     // -------------------------------------------------------------------------
1443     // mapper doesn't take care of nodes already existing on edges and vertices,
1444     // so we must merge nodes created by it with existing ones
1445     // -------------------------------------------------------------------------
1446
1447     SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
1448
1449     // Make groups of nodes to merge
1450
1451     // loop on EDGE and VERTEX sub-meshes of a target FACE
1452     SMESH_subMeshIteratorPtr smIt = tgtSubMesh->getDependsOnIterator(/*includeSelf=*/false,
1453                                                                      /*complexShapeFirst=*/false);
1454     while ( smIt->more() )
1455     {
1456       SMESH_subMesh*     sm = smIt->next();
1457       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
1458       if ( !smDS || smDS->NbNodes() == 0 )
1459         continue;
1460       //if ( !is1DComputed && sm->GetSubShape().ShapeType() == TopAbs_EDGE )
1461       //  break;
1462
1463       if ( helper.IsDegenShape( sm->GetId() ) ) // to merge all nodes on degenerated
1464       {
1465         if ( sm->GetSubShape().ShapeType() == TopAbs_EDGE )
1466         {
1467           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1468           SMESH_subMeshIteratorPtr smDegenIt
1469             = sm->getDependsOnIterator(/*includeSelf=*/true,/*complexShapeFirst=*/false);
1470           while ( smDegenIt->more() )
1471             if (( smDS = smDegenIt->next()->GetSubMeshDS() ))
1472             {
1473               SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1474               while ( nIt->more() )
1475                 groupsOfNodes.back().push_back( nIt->next() );
1476             }
1477         }
1478         continue; // do not treat sm of degen VERTEX
1479       }
1480
1481       // Sort new and old nodes of a sub-mesh separately
1482
1483       bool isSeam = helper.IsRealSeam( sm->GetId() );
1484
1485       enum { NEW_NODES = 0, OLD_NODES };
1486       map< double, const SMDS_MeshNode* > u2nodesMaps[2], u2nodesOnSeam;
1487       map< double, const SMDS_MeshNode* >::iterator u_oldNode, u_newNode, u_newOnSeam, newEnd;
1488       set< const SMDS_MeshNode* > seamNodes;
1489
1490       // mapper changed, no more "mapper puts on a seam edge nodes from 2 edges"
1491       if ( isSeam && ! getBoundaryNodes ( sm, tgtFace, u2nodesOnSeam, seamNodes ))
1492         ;//RETURN_BAD_RESULT("getBoundaryNodes() failed");
1493
1494       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
1495       while ( nIt->more() )
1496       {
1497         const SMDS_MeshNode* node = nIt->next();
1498         bool isOld = isOldNode( node );
1499
1500         if ( !isOld && isSeam ) { // new node on a seam edge
1501           if ( seamNodes.count( node ) )
1502             continue; // node is already in the map
1503         }
1504
1505         // sort nodes on edges by their position
1506         map< double, const SMDS_MeshNode* > & pos2nodes = u2nodesMaps[isOld ? OLD_NODES : NEW_NODES];
1507         switch ( node->GetPosition()->GetTypeOfPosition() )
1508         {
1509         case  SMDS_TOP_VERTEX: {
1510           if ( !is1DComputed && !pos2nodes.empty() )
1511             u2nodesMaps[isOld ? NEW_NODES : OLD_NODES].insert( make_pair( 0, node ));
1512           else
1513             pos2nodes.insert( make_pair( 0, node ));
1514           break;
1515         }
1516         case  SMDS_TOP_EDGE:   {
1517           const SMDS_EdgePosition* pos =
1518             static_cast<const SMDS_EdgePosition*>(node->GetPosition());
1519           pos2nodes.insert( make_pair( pos->GetUParameter(), node ));
1520           break;
1521         }
1522         default:
1523           RETURN_BAD_RESULT("Wrong node position type: "<<
1524                             node->GetPosition()->GetTypeOfPosition());
1525         }
1526       }
1527       const bool mergeNewToOld =
1528         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesMaps[ OLD_NODES ].size() );
1529       const bool mergeSeamToNew =
1530         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesOnSeam.size() );
1531
1532       if ( !mergeNewToOld )
1533         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1534              u2nodesMaps[ OLD_NODES ].size() > 0 )
1535         {
1536           u_oldNode = u2nodesMaps[ OLD_NODES ].begin(); 
1537           newEnd    = u2nodesMaps[ OLD_NODES ].end();
1538           for ( ; u_oldNode != newEnd; ++u_oldNode )
1539             SMESH_Algo::addBadInputElement( u_oldNode->second );
1540           return error( COMPERR_BAD_INPUT_MESH,
1541                         SMESH_Comment( "Existing mesh mismatches the projected 2D mesh on " )
1542                         << ( sm->GetSubShape().ShapeType() == TopAbs_EDGE ? "edge" : "vertex" )
1543                         << " #" << sm->GetId() );
1544         }
1545       if ( isSeam && !mergeSeamToNew ) {
1546         const TopoDS_Shape& seam = sm->GetSubShape();
1547         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
1548              u2nodesOnSeam.size()            > 0 &&
1549              seam.ShapeType() == TopAbs_EDGE )
1550         {
1551           int nbE1 = helper.Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
1552           int nbE2 = helper.Count( srcFace, TopAbs_EDGE, /*ignoreSame=*/true );
1553           if ( nbE1 != nbE2 ) // 2 EDGEs are mapped to a seam EDGE
1554           {
1555             // find the 2 EDGEs of srcFace
1556             TopTools_DataMapIteratorOfDataMapOfShapeShape src2tgtIt( shape2ShapeMap._map2to1 );
1557             for ( ; src2tgtIt.More(); src2tgtIt.Next() )
1558               if ( seam.IsSame( src2tgtIt.Value() ))
1559                 SMESH_Algo::addBadInputElements
1560                   ( srcMesh->GetMeshDS()->MeshElements( src2tgtIt.Key() ));
1561             return error( COMPERR_BAD_INPUT_MESH,
1562                           "Different number of nodes on two edges projected to a seam edge" );
1563           }
1564         }
1565       }
1566
1567       // Make groups of nodes to merge
1568
1569       u_oldNode = u2nodesMaps[ OLD_NODES ].begin(); 
1570       u_newNode = u2nodesMaps[ NEW_NODES ].begin();
1571       newEnd    = u2nodesMaps[ NEW_NODES ].end();
1572       u_newOnSeam = u2nodesOnSeam.begin();
1573       if ( mergeNewToOld )
1574         for ( ; u_newNode != newEnd; ++u_newNode, ++u_oldNode )
1575         {
1576           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1577           groupsOfNodes.back().push_back( u_oldNode->second );
1578           groupsOfNodes.back().push_back( u_newNode->second );
1579           if ( mergeSeamToNew )
1580             groupsOfNodes.back().push_back( (u_newOnSeam++)->second );
1581         }
1582       else if ( mergeSeamToNew )
1583         for ( ; u_newNode != newEnd; ++u_newNode, ++u_newOnSeam )
1584         {
1585           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
1586           groupsOfNodes.back().push_back( u_newNode->second );
1587           groupsOfNodes.back().push_back( u_newOnSeam->second );
1588         }
1589
1590     } // loop on EDGE and VERTEX submeshes of a target FACE
1591
1592     // Merge
1593
1594     SMESH_MeshEditor editor( tgtMesh );
1595     int nbFaceBeforeMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1596     editor.MergeNodes( groupsOfNodes );
1597     int nbFaceAtferMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
1598     if ( nbFaceBeforeMerge != nbFaceAtferMerge && !helper.HasDegeneratedEdges() )
1599       return error(COMPERR_BAD_INPUT_MESH, "Probably invalid node parameters on geom faces");
1600
1601     // ----------------------------------------------------------------
1602     // The mapper can't create quadratic elements, so convert if needed
1603     // ----------------------------------------------------------------
1604
1605     SMDS_ElemIteratorPtr faceIt;
1606     faceIt         = srcSubMesh->GetSubMeshDS()->GetElements();
1607     bool srcIsQuad = faceIt->next()->IsQuadratic();
1608     faceIt         = tgtSubMesh->GetSubMeshDS()->GetElements();
1609     bool tgtIsQuad = faceIt->next()->IsQuadratic();
1610     if ( srcIsQuad && !tgtIsQuad )
1611     {
1612       TIDSortedElemSet tgtFaces;
1613       faceIt = tgtSubMesh->GetSubMeshDS()->GetElements();
1614       while ( faceIt->more() )
1615         tgtFaces.insert( tgtFaces.end(), faceIt->next() );
1616
1617       editor.ConvertToQuadratic(/*theForce3d=*/false, tgtFaces, false);
1618     }
1619   } // end of coincident nodes and quadratic elements treatment
1620
1621
1622   if ( !projDone || is1DComputed )
1623     // ----------------------------------------------------------------
1624     // The mapper can create distorted faces by placing nodes out of the FACE
1625     // boundary, also bad face can be created if EDGEs already discretized
1626     // --> fix bad faces by smoothing
1627     // ----------------------------------------------------------------
1628     if ( !fixDistortedFaces( helper, tgtWires ))
1629       return error("Invalid mesh generated");
1630
1631   // ---------------------------
1632   // Check elements orientation
1633   // ---------------------------
1634
1635   TopoDS_Face face = TopoDS::Face( theShape );
1636   if ( !theMesh.IsMainShape( tgtFace ))
1637   {
1638     // find the main shape
1639     TopoDS_Shape mainShape = meshDS->ShapeToMesh();
1640     switch ( mainShape.ShapeType() ) {
1641     case TopAbs_SHELL:
1642     case TopAbs_SOLID: break;
1643     default:
1644       TopTools_ListIteratorOfListOfShape ancestIt = theMesh.GetAncestors( face );
1645       for ( ; ancestIt.More(); ancestIt.Next() ) {
1646         TopAbs_ShapeEnum type = ancestIt.Value().ShapeType();
1647         if ( type == TopAbs_SOLID ) {
1648           mainShape = ancestIt.Value();
1649           break;
1650         } else if ( type == TopAbs_SHELL ) {
1651           mainShape = ancestIt.Value();
1652         }
1653       }
1654     }
1655     // find tgtFace in the main solid or shell to know it's true orientation.
1656     TopExp_Explorer exp( mainShape, TopAbs_FACE );
1657     for ( ; exp.More(); exp.Next() ) {
1658       if ( tgtFace.IsSame( exp.Current() )) {
1659         face = TopoDS::Face( exp.Current() );
1660         break;
1661       }
1662     }
1663   }
1664   // Fix orientation
1665   if ( helper.IsReversedSubMesh( face ))
1666   {
1667     SMESH_MeshEditor editor( tgtMesh );
1668     SMDS_ElemIteratorPtr eIt = meshDS->MeshElements( face )->GetElements();
1669     while ( eIt->more() ) {
1670       const SMDS_MeshElement* e = eIt->next();
1671       if ( e->GetType() == SMDSAbs_Face && !editor.Reorient( e ))
1672         RETURN_BAD_RESULT("Pb of SMESH_MeshEditor::Reorient()");
1673     }
1674   }
1675
1676   cleaner.Release(); // not to remove mesh
1677
1678   return true;
1679 }
1680
1681
1682 //=======================================================================
1683 //function : Evaluate
1684 //purpose  : 
1685 //=======================================================================
1686
1687 bool StdMeshers_Projection_2D::Evaluate(SMESH_Mesh&         theMesh,
1688                                         const TopoDS_Shape& theShape,
1689                                         MapShapeNbElems&    aResMap)
1690 {
1691   if ( !_sourceHypo )
1692     return false;
1693
1694   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
1695   SMESH_Mesh * tgtMesh = & theMesh;
1696   if ( !srcMesh )
1697     srcMesh = tgtMesh;
1698
1699   // ---------------------------
1700   // Make sub-shapes association
1701   // ---------------------------
1702
1703   TopoDS_Face tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
1704   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
1705
1706   TAssocTool::TShapeShapeMap shape2ShapeMap;
1707   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
1708   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
1709                                              shape2ShapeMap)  ||
1710        !shape2ShapeMap.IsBound( tgtFace ))
1711     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
1712
1713   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
1714
1715   // -------------------------------------------------------
1716   // Assure that mesh on a source Face is computed/evaluated
1717   // -------------------------------------------------------
1718
1719   std::vector<int> aVec;
1720
1721   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
1722   if ( srcSubMesh->IsMeshComputed() )
1723   {
1724     aVec.resize( SMDSEntity_Last, 0 );
1725     aVec[SMDSEntity_Node] = srcSubMesh->GetSubMeshDS()->NbNodes();
1726
1727     SMDS_ElemIteratorPtr elemIt = srcSubMesh->GetSubMeshDS()->GetElements();
1728     while ( elemIt->more() )
1729       aVec[ elemIt->next()->GetEntityType() ]++;
1730   }
1731   else
1732   {
1733     MapShapeNbElems  tmpResMap;
1734     MapShapeNbElems& srcResMap = (srcMesh == tgtMesh) ? aResMap : tmpResMap;
1735     if ( !_gen->Evaluate( *srcMesh, srcShape, srcResMap ))
1736       return error(COMPERR_BAD_INPUT_MESH,"Source mesh not evaluatable");
1737     aVec = srcResMap[ srcSubMesh ];
1738     if ( aVec.empty() )
1739       return error(COMPERR_BAD_INPUT_MESH,"Source mesh is wrongly evaluated");
1740   }
1741
1742   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
1743   aResMap.insert(std::make_pair(sm,aVec));
1744
1745   return true;
1746 }
1747
1748
1749 //=============================================================================
1750 /*!
1751  * \brief Sets a default event listener to submesh of the source face
1752   * \param subMesh - submesh where algo is set
1753  *
1754  * This method is called when a submesh gets HYP_OK algo_state.
1755  * After being set, event listener is notified on each event of a submesh.
1756  * Arranges that CLEAN event is translated from source submesh to
1757  * the submesh
1758  */
1759 //=============================================================================
1760
1761 void StdMeshers_Projection_2D::SetEventListener(SMESH_subMesh* subMesh)
1762 {
1763   TAssocTool::SetEventListener( subMesh,
1764                                 _sourceHypo->GetSourceFace(),
1765                                 _sourceHypo->GetSourceMesh() );
1766 }