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