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