Salome HOME
bos #29435 EDF 25081 - wrong prisms
[modules/smesh.git] / src / StdMeshers / StdMeshers_Projection_2D.cxx
1 // Copyright (C) 2007-2021  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 : implementation 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_FaceSide.hxx"
32 #include "StdMeshers_NumberOfSegments.hxx"
33 #include "StdMeshers_ProjectionSource2D.hxx"
34 #include "StdMeshers_ProjectionUtils.hxx"
35 #include "StdMeshers_Quadrangle_2D.hxx"
36 #include "StdMeshers_Regular_1D.hxx"
37
38 #include <ObjectPool.hxx>
39 #include <SMDS_EdgePosition.hxx>
40 #include <SMDS_FacePosition.hxx>
41 #include <SMESHDS_Hypothesis.hxx>
42 #include <SMESHDS_Mesh.hxx>
43 #include <SMESHDS_SubMesh.hxx>
44 #include <SMESH_Block.hxx>
45 #include <SMESH_Comment.hxx>
46 #include <SMESH_Gen.hxx>
47 #include <SMESH_Mesh.hxx>
48 #include <SMESH_MeshAlgos.hxx>
49 #include <SMESH_MeshEditor.hxx>
50 #include <SMESH_MesherHelper.hxx>
51 #include <SMESH_Pattern.hxx>
52 #include <SMESH_subMesh.hxx>
53 #include <SMESH_subMeshEventListener.hxx>
54
55 #include <utilities.h>
56
57 #include <BRepAdaptor_Curve.hxx>
58 #include <BRepAdaptor_Surface.hxx>
59 #include <BRepMesh_Delaun.hxx>
60 #include <BRep_Tool.hxx>
61 #include <Bnd_B2d.hxx>
62 #include <GeomAPI_ExtremaCurveCurve.hxx>
63 #include <GeomAPI_ProjectPointOnSurf.hxx>
64 #include <GeomAdaptor_Curve.hxx>
65 #include <GeomAdaptor_HCurve.hxx>
66 #include <GeomAdaptor_HSurface.hxx>
67 #include <GeomAdaptor_Surface.hxx>
68 #include <GeomLib_IsPlanarSurface.hxx>
69 #include <Geom_Line.hxx>
70 #include <IntCurveSurface_HInter.hxx>
71 #include <Precision.hxx>
72 #include <TopExp.hxx>
73 #include <TopExp_Explorer.hxx>
74 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
75 #include <TopTools_ListIteratorOfListOfShape.hxx>
76 #include <TopTools_MapOfShape.hxx>
77 #include <TopoDS.hxx>
78 #include <TopoDS_Solid.hxx>
79 #include <gp_Ax2.hxx>
80 #include <gp_Ax3.hxx>
81 #include <gp_GTrsf.hxx>
82
83
84 using namespace std;
85
86 #define RETURN_BAD_RESULT(msg) { MESSAGE(")-: Error: " << msg); return false; }
87 #ifdef _DEBUG_
88 // enable printing algo + projection shapes while meshing
89 //#define PRINT_WHO_COMPUTE_WHAT
90 #endif
91
92 namespace TAssocTool = StdMeshers_ProjectionUtils;
93 //typedef StdMeshers_ProjectionUtils TAssocTool;
94
95 // allow range iteration on NCollection_IndexedMap
96 template < class IMAP >
97 typename IMAP::const_iterator begin( const IMAP &  m ) { return m.cbegin(); }
98 template < class IMAP >
99 typename IMAP::const_iterator end( const IMAP &  m ) { return m.cend(); }
100
101 //=======================================================================
102 //function : StdMeshers_Projection_2D
103 //purpose  :
104 //=======================================================================
105
106 StdMeshers_Projection_2D::StdMeshers_Projection_2D(int hypId, SMESH_Gen* gen)
107   :SMESH_2D_Algo(hypId, gen)
108 {
109   _name = "Projection_2D";
110   _compatibleHypothesis.push_back("ProjectionSource2D");
111   _sourceHypo = 0;
112 }
113
114 //================================================================================
115 /*!
116  * \brief Destructor
117  */
118 //================================================================================
119
120 StdMeshers_Projection_2D::~StdMeshers_Projection_2D()
121 {}
122
123 //=======================================================================
124 //function : CheckHypothesis
125 //purpose  :
126 //=======================================================================
127
128 bool StdMeshers_Projection_2D::CheckHypothesis(SMESH_Mesh&                          theMesh,
129                                                const TopoDS_Shape&                  theShape,
130                                                SMESH_Hypothesis::Hypothesis_Status& theStatus)
131 {
132   list <const SMESHDS_Hypothesis * >::const_iterator itl;
133
134   const list <const SMESHDS_Hypothesis * >&hyps = GetUsedHypothesis(theMesh, theShape);
135   if ( hyps.size() == 0 )
136   {
137     theStatus = HYP_MISSING;
138     return false;  // can't work with no hypothesis
139   }
140
141   if ( hyps.size() > 1 )
142   {
143     theStatus = HYP_ALREADY_EXIST;
144     return false;
145   }
146
147   const SMESHDS_Hypothesis *theHyp = hyps.front();
148
149   string hypName = theHyp->GetName();
150
151   theStatus = HYP_OK;
152
153   if (hypName == "ProjectionSource2D")
154   {
155     _sourceHypo = static_cast<const StdMeshers_ProjectionSource2D *>(theHyp);
156
157     // Check hypo parameters
158
159     SMESH_Mesh* srcMesh = _sourceHypo->GetSourceMesh();
160     SMESH_Mesh* tgtMesh = & theMesh;
161     if ( !srcMesh )
162       srcMesh = tgtMesh;
163
164     // check vertices
165     if ( _sourceHypo->HasVertexAssociation() )
166     {
167       // source vertices
168       TopoDS_Shape edge = TAssocTool::GetEdgeByVertices
169         ( srcMesh, _sourceHypo->GetSourceVertex(1), _sourceHypo->GetSourceVertex(2) );
170       if ( edge.IsNull() ||
171            !SMESH_MesherHelper::IsSubShape( edge, srcMesh ) ||
172            !SMESH_MesherHelper::IsSubShape( edge, _sourceHypo->GetSourceFace() ))
173       {
174         theStatus = HYP_BAD_PARAMETER;
175         error("Invalid source vertices");
176         SCRUTE((edge.IsNull()));
177         SCRUTE((SMESH_MesherHelper::IsSubShape( edge, srcMesh )));
178         SCRUTE((SMESH_MesherHelper::IsSubShape( edge, _sourceHypo->GetSourceFace() )));
179       }
180       else
181       {
182         // target vertices
183         edge = TAssocTool::GetEdgeByVertices
184           ( tgtMesh, _sourceHypo->GetTargetVertex(1), _sourceHypo->GetTargetVertex(2) );
185         if ( edge.IsNull() || !SMESH_MesherHelper::IsSubShape( edge, tgtMesh ))
186         {
187           theStatus = HYP_BAD_PARAMETER;
188           error("Invalid target vertices");
189           SCRUTE((edge.IsNull()));
190           SCRUTE((SMESH_MesherHelper::IsSubShape( edge, tgtMesh )));
191         }
192         // PAL16203
193         else if ( !_sourceHypo->IsCompoundSource() &&
194                   !SMESH_MesherHelper::IsSubShape( edge, theShape ))
195         {
196           theStatus = HYP_BAD_PARAMETER;
197           error("Invalid target vertices");
198           SCRUTE((SMESH_MesherHelper::IsSubShape( edge, theShape )));
199         }
200       }
201     }
202     // check a source face
203     if ( !SMESH_MesherHelper::IsSubShape( _sourceHypo->GetSourceFace(), srcMesh ) ||
204          ( srcMesh == tgtMesh && theShape == _sourceHypo->GetSourceFace() ))
205     {
206       theStatus = HYP_BAD_PARAMETER;
207       error("Invalid source face");
208       SCRUTE((SMESH_MesherHelper::IsSubShape( _sourceHypo->GetSourceFace(), srcMesh )));
209       SCRUTE((srcMesh == tgtMesh));
210       SCRUTE(( theShape == _sourceHypo->GetSourceFace() ));
211     }
212   }
213   else
214   {
215     theStatus = HYP_INCOMPATIBLE;
216   }
217   return ( theStatus == HYP_OK );
218 }
219
220 namespace {
221
222   //================================================================================
223   /*!
224    * \brief define if a node is new or old
225    * \param node - node to check
226    * \retval bool - true if the node existed before Compute() is called
227    */
228   //================================================================================
229
230   bool isOldNode( const SMDS_MeshNode* node )
231   {
232     // old nodes are shared by edges and new ones are shared
233     // only by faces created by mapper
234     //if ( is1DComputed )
235     {
236       bool isOld = node->NbInverseElements(SMDSAbs_Edge) > 0;
237       return isOld;
238     }
239     // else
240     // {
241     //   SMDS_ElemIteratorPtr invFace = node->GetInverseElementIterator(SMDSAbs_Face);
242     //   bool isNew = invFace->more();
243     //   return !isNew;
244     // }
245   }
246
247   //================================================================================
248   /*!
249    * \brief Class to remove mesh built by pattern mapper on edges
250    * and vertices in the case of failure of projection algo.
251    * It does it's job at destruction
252    */
253   //================================================================================
254
255   class MeshCleaner {
256     SMESH_subMesh* sm;
257   public:
258     MeshCleaner( SMESH_subMesh* faceSubMesh ): sm(faceSubMesh) {}
259     ~MeshCleaner() { Clean(sm); }
260     void Release() { sm = 0; } // mesh will not be removed
261     static void Clean( SMESH_subMesh* sm, bool withSub=true )
262     {
263       if ( !sm || !sm->GetSubMeshDS() ) return;
264       // PAL16567, 18920. Remove face nodes as well
265 //       switch ( sm->GetSubShape().ShapeType() ) {
266 //       case TopAbs_VERTEX:
267 //       case TopAbs_EDGE: {
268         SMDS_NodeIteratorPtr nIt = sm->GetSubMeshDS()->GetNodes();
269         SMESHDS_Mesh* mesh = sm->GetFather()->GetMeshDS();
270         while ( nIt->more() ) {
271           const SMDS_MeshNode* node = nIt->next();
272           if ( !isOldNode( node ) )
273             mesh->RemoveNode( node );
274         }
275         // do not break but iterate over DependsOn()
276 //       }
277 //       default:
278         if ( !withSub ) return;
279         SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(false,false);
280         while ( smIt->more() )
281           Clean( smIt->next(), false );
282 //       }
283     }
284   };
285
286   //================================================================================
287   /*!
288    * \brief find new nodes belonging to one free border of mesh on face
289     * \param sm - submesh on edge or vertex containing nodes to choose from
290     * \param face - the face bound by the submesh
291     * \param u2nodes - map to fill with nodes
292     * \param seamNodes - set of found nodes
293     * \retval bool - is a success
294    */
295   //================================================================================
296
297   bool getBoundaryNodes ( SMESH_subMesh*                        sm,
298                           const TopoDS_Face&                    /*face*/,
299                           map< double, const SMDS_MeshNode* > & u2nodes,
300                           set< const SMDS_MeshNode* > &         seamNodes)
301   {
302     u2nodes.clear();
303     seamNodes.clear();
304     if ( !sm || !sm->GetSubMeshDS() )
305       RETURN_BAD_RESULT("Null submesh");
306
307     SMDS_NodeIteratorPtr nIt = sm->GetSubMeshDS()->GetNodes();
308     switch ( sm->GetSubShape().ShapeType() ) {
309
310     case TopAbs_VERTEX: {
311       while ( nIt->more() ) {
312         const SMDS_MeshNode* node = nIt->next();
313         if ( isOldNode( node ) ) continue;
314         u2nodes.insert( make_pair( 0., node ));
315         seamNodes.insert( node );
316         return true;
317       }
318       break;
319     }
320     case TopAbs_EDGE: {
321       
322       // Get submeshes of sub-vertices
323       const map< int, SMESH_subMesh * >& subSM = sm->DependsOn();
324       if ( subSM.size() != 2 )
325         RETURN_BAD_RESULT("there must be 2 submeshes of sub-vertices"
326                           " but we have " << subSM.size());
327       SMESH_subMesh* smV1 = subSM.begin()->second;
328       SMESH_subMesh* smV2 = subSM.rbegin()->second;
329       if ( !smV1->IsMeshComputed() || !smV2->IsMeshComputed() )
330         RETURN_BAD_RESULT("Empty vertex submeshes");
331
332       const SMDS_MeshNode* nV1 = 0;
333       const SMDS_MeshNode* nE = 0;
334
335       // Look for nV1 - a new node on V1
336       nIt = smV1->GetSubMeshDS()->GetNodes();
337       while ( nIt->more() && !nE ) {
338         const SMDS_MeshNode* node = nIt->next();
339         if ( isOldNode( node ) ) continue;
340         nV1 = node;
341
342         // Find nE - a new node connected to nV1 and belonging to edge submesh;
343         SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
344         SMDS_ElemIteratorPtr vElems = nV1->GetInverseElementIterator(SMDSAbs_Face);
345         while ( vElems->more() && !nE ) {
346           const SMDS_MeshElement* elem = vElems->next();
347           int nbNodes = elem->NbNodes();
348           if ( elem->IsQuadratic() )
349             nbNodes /= 2;
350           int iV1 = elem->GetNodeIndex( nV1 );
351           // try next after nV1
352           int iE = SMESH_MesherHelper::WrapIndex( iV1 + 1, nbNodes );
353           if ( smDS->Contains( elem->GetNode( iE ) ))
354             nE = elem->GetNode( iE );
355           if ( !nE ) {
356             // try node before nV1
357             iE = SMESH_MesherHelper::WrapIndex( iV1 - 1, nbNodes );
358             if ( smDS->Contains( elem->GetNode( iE )))
359               nE = elem->GetNode( iE );
360           }
361           if ( nE && elem->IsQuadratic() ) { // find medium node between nV1 and nE
362             if ( Abs( iV1 - iE ) == 1 )
363               nE = elem->GetNode( Min ( iV1, iE ) + nbNodes );
364             else
365               nE = elem->GetNode( elem->NbNodes() - 1 );
366           }
367         }
368       }
369       if ( !nV1 )
370         RETURN_BAD_RESULT("No new node found on V1");
371       if ( !nE )
372         RETURN_BAD_RESULT("new node on edge not found");
373
374       // Get the whole free border of a face
375       list< const SMDS_MeshNode* > bordNodes;
376       list< const SMDS_MeshElement* > bordFaces;
377       if ( !SMESH_MeshEditor::FindFreeBorder (nV1, nE, nV1, bordNodes, bordFaces ))
378         RETURN_BAD_RESULT("free border of a face not found by nodes " <<
379                           nV1->GetID() << " " << nE->GetID() );
380
381       // Insert nodes of the free border to the map until node on V2 encountered
382       SMESHDS_SubMesh* v2smDS = smV2->GetSubMeshDS();
383       list< const SMDS_MeshNode* >::iterator bordIt = bordNodes.begin();
384       bordIt++; // skip nV1
385       for ( ; bordIt != bordNodes.end(); ++bordIt ) {
386         const SMDS_MeshNode* node = *bordIt;
387         if ( v2smDS->Contains( node ))
388           break;
389         if ( node->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
390           RETURN_BAD_RESULT("Bad node position type: node " << node->GetID() <<
391                             " pos type " << node->GetPosition()->GetTypeOfPosition());
392         SMDS_EdgePositionPtr pos = node->GetPosition();
393         u2nodes.insert( make_pair( pos->GetUParameter(), node ));
394         seamNodes.insert( node );
395       }
396       if ( u2nodes.size() != seamNodes.size() )
397         RETURN_BAD_RESULT("Bad node params on edge " << sm->GetId() <<
398                           ", " << u2nodes.size() << " != " << seamNodes.size() );
399       return true;
400     }
401     default:;
402     }
403     RETURN_BAD_RESULT ("Unexpected submesh type");
404
405   } // bool getBoundaryNodes()
406
407   //================================================================================
408   /*!
409    * \brief Check if two consecutive EDGEs are connected in 2D
410    *  \param [in] E1 - a well oriented non-seam EDGE
411    *  \param [in] E2 - a possibly well oriented seam EDGE
412    *  \param [in] F - a FACE
413    *  \return bool - result
414    */
415   //================================================================================
416
417   bool are2dConnected( const TopoDS_Edge & E1,
418                        const TopoDS_Edge & E2,
419                        const TopoDS_Face & F )
420   {
421     double f,l;
422     Handle(Geom2d_Curve) c1 = BRep_Tool::CurveOnSurface( E1, F, f, l );
423     gp_Pnt2d uvFirst1 = c1->Value( f );
424     gp_Pnt2d uvLast1  = c1->Value( l );
425
426     Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( E2, F, f, l );
427     gp_Pnt2d uvFirst2 = c2->Value( E2.Orientation() == TopAbs_REVERSED ? l : f );
428     double tol2 = Max( Precision::PConfusion() * Precision::PConfusion(),
429                        1e-5 * uvLast1.SquareDistance( uvFirst1 ));
430
431     return (( uvFirst2.SquareDistance( uvFirst1 ) < tol2 ) ||
432             ( uvFirst2.SquareDistance( uvLast1  ) < tol2 ));
433   }
434
435   //================================================================================
436   /*!
437    * \brief Compose TSideVector for both FACEs keeping matching order of EDGEs
438    *        and fill src2tgtNodes map
439    */
440   //================================================================================
441
442   TError getWires(const TopoDS_Face&                 tgtFace,
443                   const TopoDS_Face&                 srcFace,
444                   SMESH_Mesh *                       tgtMesh,
445                   SMESH_Mesh *                       srcMesh,
446                   SMESH_MesherHelper*                tgtHelper,
447                   const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
448                   TSideVector&                       srcWires,
449                   TSideVector&                       tgtWires,
450                   TAssocTool::TNodeNodeMap&          src2tgtNodes,
451                   bool&                              is1DComputed)
452   {
453     src2tgtNodes.clear();
454
455     // get ordered src EDGEs
456     TError err;
457     srcWires = StdMeshers_FaceSide::GetFaceWires( srcFace, *srcMesh,/*skipMediumNodes=*/0, err );
458     if (( err && !err->IsOK() ) ||
459         ( srcWires.empty() ))
460       return err;
461 #ifdef PRINT_WHO_COMPUTE_WHAT
462     cout << "Projection_2D" <<  " F "
463          << tgtMesh->GetMeshDS()->ShapeToIndex( tgtFace ) << " <- "
464          << srcMesh->GetMeshDS()->ShapeToIndex( srcFace ) << endl;
465 #endif
466
467     // make corresponding sequence of tgt EDGEs
468     tgtWires.resize( srcWires.size() );
469     for ( size_t iW = 0; iW < srcWires.size(); ++iW )
470     {
471       StdMeshers_FaceSidePtr srcWire = srcWires[iW];
472
473       list< TopoDS_Edge > tgtEdges;
474       TopTools_IndexedMapOfShape edgeMap; // to detect seam edges
475       for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
476       {
477         TopoDS_Edge     srcE = srcWire->Edge( iE );
478         TopoDS_Edge     tgtE = TopoDS::Edge( shape2ShapeMap( srcE, /*isSrc=*/true));
479         TopoDS_Shape srcEbis = shape2ShapeMap( tgtE, /*isSrc=*/false );
480         if ( srcE.Orientation() != srcEbis.Orientation() )
481           tgtE.Reverse();
482         // reverse a seam edge encountered for the second time
483         const int index = edgeMap.Add( tgtE );
484         if ( index < edgeMap.Extent() ) // E is a seam
485         {
486           // check which of edges to reverse, E or one already being in tgtEdges
487           if ( are2dConnected( tgtEdges.back(), tgtE, tgtFace ))
488           {
489             list< TopoDS_Edge >::iterator eIt = tgtEdges.begin();
490             std::advance( eIt, index-1 );
491             if ( are2dConnected( tgtEdges.back(), *eIt, tgtFace ))
492               eIt->Reverse();
493           }
494           else
495           {
496             tgtE.Reverse();
497           }
498         }
499         if ( srcWire->NbEdges() == 1 && tgtMesh == srcMesh ) // circle
500         {
501           // try to verify ori by propagation
502           pair<int,TopoDS_Edge> nE =
503             StdMeshers_ProjectionUtils::GetPropagationEdge( srcMesh, tgtE, srcE );
504           if ( !nE.second.IsNull() )
505             tgtE = nE.second;
506         }
507         tgtEdges.push_back( tgtE );
508       }
509
510       tgtWires[ iW ].reset( new StdMeshers_FaceSide( tgtFace, tgtEdges, tgtMesh,
511                                                      /*theIsForward = */ true,
512                                                      /*theIgnoreMediumNodes = */false,
513                                                      tgtHelper ));
514       StdMeshers_FaceSidePtr tgtWire = tgtWires[ iW ];
515
516       // Fill map of src to tgt nodes with nodes on edges
517
518       for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
519       {
520 #ifdef PRINT_WHO_COMPUTE_WHAT
521         if ( tgtMesh->GetSubMesh( tgtWire->Edge(iE) )->IsEmpty() )
522           cout << "Projection_2D" <<  " E "
523                << tgtWire->EdgeID(iE) << " <- " << srcWire->EdgeID(iE) << endl;
524 #endif
525         if ( srcMesh->GetSubMesh( srcWire->Edge(iE) )->IsEmpty() ||
526              tgtMesh->GetSubMesh( tgtWire->Edge(iE) )->IsEmpty() )
527         {
528           // add nodes on VERTEXes for a case of not meshes EDGEs
529           const SMDS_MeshNode* srcN = srcWire->VertexNode( iE );
530           const SMDS_MeshNode* tgtN = tgtWire->VertexNode( iE );
531           if ( srcN && tgtN )
532             src2tgtNodes.insert( make_pair( srcN, tgtN ));
533         }
534         else
535         {
536           const bool skipMedium = true, isFwd = true;
537           StdMeshers_FaceSide srcEdge( srcFace, srcWire->Edge(iE),
538                                        srcMesh, isFwd, skipMedium, srcWires[0]->FaceHelper() );
539           StdMeshers_FaceSide tgtEdge( tgtFace, tgtWire->Edge(iE),
540                                        tgtMesh, isFwd, skipMedium, tgtHelper);
541
542           vector< const SMDS_MeshNode* > srcNodes = srcEdge.GetOrderedNodes();
543           vector< const SMDS_MeshNode* > tgtNodes = tgtEdge.GetOrderedNodes();
544
545           if (( srcNodes.size() != tgtNodes.size() ) && tgtNodes.size() > 0 )
546             return SMESH_ComputeError::New( COMPERR_BAD_INPUT_MESH,
547                                             "Different number of nodes on edges");
548           if ( !tgtNodes.empty() )
549           {
550             vector< const SMDS_MeshNode* >::iterator tn = tgtNodes.begin();
551             //if ( srcWire->Edge(iE).Orientation() == tgtWire->Edge(iE).Orientation() )
552             {
553               vector< const SMDS_MeshNode* >::iterator sn = srcNodes.begin();
554               for ( ; tn != tgtNodes.end(); ++tn, ++sn)
555                 src2tgtNodes.insert( make_pair( *sn, *tn ));
556             }
557             // else
558             // {
559             //   vector< const SMDS_MeshNode* >::reverse_iterator sn = srcNodes.rbegin();
560             //   for ( ; tn != tgtNodes.end(); ++tn, ++sn)
561             //     src2tgtNodes.insert( make_pair( *sn, *tn ));
562             // }
563             is1DComputed = true;
564           }
565         }
566       } // loop on EDGEs of a WIRE
567
568     } // loop on WIREs
569
570     return TError();
571   }
572
573   //================================================================================
574   /*!
575    * \brief Perform projection in case if tgtFace.IsPartner( srcFace ) and in case
576    * if projection by 3D transformation is possible
577    */
578   //================================================================================
579
580   bool projectPartner(const TopoDS_Face&                 tgtFace,
581                       const TopoDS_Face&                 srcFace,
582                       const TSideVector&                 tgtWires,
583                       const TSideVector&                 srcWires,
584                       const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
585                       TAssocTool::TNodeNodeMap&          src2tgtNodes,
586                       const bool                         is1DComputed)
587   {
588     SMESH_Mesh *       tgtMesh = tgtWires[0]->GetMesh();
589     SMESH_Mesh *       srcMesh = srcWires[0]->GetMesh();
590     SMESHDS_Mesh*    tgtMeshDS = tgtMesh->GetMeshDS();
591     SMESHDS_Mesh*    srcMeshDS = srcMesh->GetMeshDS();
592     SMESH_MesherHelper* helper = tgtWires[0]->FaceHelper();
593
594     const double tol = 1.e-7 * srcMeshDS->getMaxDim();
595
596     // transformation to get location of target nodes from source ones
597     StdMeshers_ProjectionUtils::TrsfFinder3D trsf;
598     bool trsfIsOK = false;
599     if ( tgtFace.IsPartner( srcFace ))
600     {
601       gp_GTrsf srcTrsf = srcFace.Location().Transformation();
602       gp_GTrsf tgtTrsf = tgtFace.Location().Transformation();
603       gp_GTrsf t = srcTrsf.Inverted().Multiplied( tgtTrsf );
604       trsf.Set( t );
605       // check
606       gp_Pnt srcP = BRep_Tool::Pnt( srcWires[0]->FirstVertex() );
607       gp_Pnt tgtP = BRep_Tool::Pnt( tgtWires[0]->FirstVertex() );
608       trsfIsOK = ( tgtP.Distance( trsf.Transform( srcP )) < tol );
609       if ( !trsfIsOK )
610       {
611         trsf.Set( tgtTrsf.Inverted().Multiplied( srcTrsf ));
612         trsfIsOK = ( tgtP.Distance( trsf.Transform( srcP )) < tol );
613       }
614     }
615     if ( !trsfIsOK )
616     {
617       // Try to find the 3D transformation
618
619       const int totNbSeg = 50;
620       vector< gp_XYZ > srcPnts, tgtPnts;
621       srcPnts.reserve( totNbSeg );
622       tgtPnts.reserve( totNbSeg );
623       gp_XYZ srcBC( 0,0,0 ), tgtBC( 0,0,0 );
624       for ( size_t iW = 0; iW < srcWires.size(); ++iW )
625       {
626         const double minSegLen = srcWires[iW]->Length() / totNbSeg;
627         for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
628         {
629           size_t nbSeg = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
630           double srcU  = srcWires[iW]->FirstParameter( iE );
631           double tgtU  = tgtWires[iW]->FirstParameter( iE );
632           double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
633           double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
634           for ( size_t i = 0; i < nbSeg; ++i  )
635           {
636             srcPnts.push_back( srcWires[iW]->Value3d( srcU ).XYZ() );
637             tgtPnts.push_back( tgtWires[iW]->Value3d( tgtU ).XYZ() );
638             srcU += srcDu;
639             tgtU += tgtDu;
640             srcBC += srcPnts.back();
641             tgtBC += tgtPnts.back();
642           }
643         }
644       }
645       if ( !trsf.Solve( srcPnts, tgtPnts ))
646         return false;
647
648       // check trsf
649
650       const int nbTestPnt = 20;
651       const size_t  iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
652       // check boundary
653       gp_Pnt trsfTgt = trsf.Transform( srcBC / srcPnts.size() );
654       trsfIsOK = ( trsfTgt.SquareDistance( tgtBC / tgtPnts.size() ) < tol*tol );
655       for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
656       {
657         gp_Pnt trsfTgt = trsf.Transform( srcPnts[i] );
658         trsfIsOK = ( trsfTgt.SquareDistance( tgtPnts[i] ) < tol*tol );
659       }
660       // check an in-FACE point
661       if ( trsfIsOK )
662       {
663         BRepAdaptor_Surface srcSurf( srcFace );
664         gp_Pnt srcP =
665           srcSurf.Value( 0.321 * ( srcSurf.FirstUParameter() + srcSurf.LastUParameter() ),
666                          0.123 * ( srcSurf.FirstVParameter() + srcSurf.LastVParameter() ));
667         gp_Pnt tgtTrsfP = trsf.Transform( srcP );
668         TopLoc_Location loc;
669         GeomAPI_ProjectPointOnSurf& proj = helper->GetProjector( tgtFace, loc, 0.1*tol );
670         if ( !loc.IsIdentity() )
671           tgtTrsfP.Transform( loc.Transformation().Inverted() );
672         proj.Perform( tgtTrsfP );
673         trsfIsOK = ( proj.IsDone() &&
674                      proj.NbPoints() > 0 &&
675                      proj.LowerDistance() < tol );
676       }
677       if ( !trsfIsOK )
678         return false;
679     }
680
681     // Make new faces
682
683     // prepare the helper to adding quadratic elements if necessary
684     helper->IsQuadraticSubMesh( tgtFace );
685
686     SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
687     if ( !is1DComputed && srcSubDS->NbElements() )
688       helper->SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
689
690     SMESH_MesherHelper* srcHelper = srcWires[0]->FaceHelper();
691     SMESH_MesherHelper  edgeHelper( *tgtMesh );
692     edgeHelper.ToFixNodeParameters( true );
693
694     const SMDS_MeshNode* nullNode = 0;
695     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
696
697     // indices of nodes to create properly oriented faces
698     bool isReverse = ( !trsf.IsIdentity() );
699     int tri1 = 1, tri2 = 2, quad1 = 1, quad3 = 3;
700     if ( isReverse )
701       std::swap( tri1, tri2 ), std::swap( quad1, quad3 );
702
703     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
704     vector< const SMDS_MeshNode* > tgtNodes;
705     while ( elemIt->more() ) // loop on all mesh faces on srcFace
706     {
707       const SMDS_MeshElement* elem = elemIt->next();
708       const int nbN = elem->NbCornerNodes(); 
709       tgtNodes.resize( nbN );
710       helper->SetElementsOnShape( false );
711       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
712       {
713         const SMDS_MeshNode* srcNode = elem->GetNode(i);
714         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
715         if ( srcN_tgtN->second == nullNode )
716         {
717           // create a new node
718           gp_Pnt tgtP = trsf.Transform( SMESH_TNodeXYZ( srcNode ));
719           SMDS_MeshNode* n = helper->AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
720           srcN_tgtN->second = n;
721           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
722           {
723           case SMDS_TOP_FACE:
724           {
725             gp_Pnt2d srcUV = srcHelper->GetNodeUV( srcFace, srcNode );
726             tgtMeshDS->SetNodeOnFace( n, helper->GetSubShapeID(), srcUV.X(), srcUV.Y() );
727             break;
728           }
729           case SMDS_TOP_EDGE:
730           {
731             const TopoDS_Edge& srcE = TopoDS::Edge( srcMeshDS->IndexToShape( srcNode->getshapeId()));
732             const TopoDS_Edge& tgtE = TopoDS::Edge( shape2ShapeMap( srcE, /*isSrc=*/true ));
733             double srcU = srcHelper->GetNodeU( srcE, srcNode );
734             tgtMeshDS->SetNodeOnEdge( n, tgtE, srcU );
735             if ( !tgtFace.IsPartner( srcFace ))
736             {
737               edgeHelper.SetSubShape( tgtE );
738               double tol = BRep_Tool::Tolerance( tgtE );
739               bool isOk = edgeHelper.CheckNodeU( tgtE, n, srcU, 2 * tol, /*force=*/true );
740               if ( !isOk ) // projection of n to tgtE failed (23395)
741               {
742                 double sF, sL, tF, tL;
743                 BRep_Tool::Range( srcE, sF, sL );
744                 BRep_Tool::Range( tgtE, tF, tL );
745                 double srcR = ( srcU - sF ) / ( sL - sF );
746                 double tgtU  = tF + srcR * ( tL - tF );
747                 tgtMeshDS->SetNodeOnEdge( n, tgtE, tgtU );
748                 gp_Pnt newP = BRepAdaptor_Curve( tgtE ).Value( tgtU );
749                 double dist = newP.Distance( tgtP );
750                 if ( tol < dist && dist < 1000*tol )
751                   tgtMeshDS->MoveNode( n, newP.X(), newP.Y(), newP.Z() );
752               }
753             }
754             break;
755           }
756           case SMDS_TOP_VERTEX:
757           {
758             const TopoDS_Shape & srcV = srcMeshDS->IndexToShape( srcNode->getshapeId() );
759             const TopoDS_Shape & tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
760             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
761             break;
762           }
763           default:;
764           }
765         }
766         tgtNodes[i] = srcN_tgtN->second;
767       }
768       // create a new face
769       helper->SetElementsOnShape( true );
770       switch ( nbN )
771       {
772       case 3: helper->AddFace(tgtNodes[0], tgtNodes[tri1], tgtNodes[tri2]); break;
773       case 4: helper->AddFace(tgtNodes[0], tgtNodes[quad1], tgtNodes[2], tgtNodes[quad3]); break;
774       default:
775         if ( isReverse ) std::reverse( tgtNodes.begin(), tgtNodes.end() );
776         helper->AddPolygonalFace( tgtNodes );
777       }
778     }
779
780     // check node positions
781
782     // if ( !tgtFace.IsPartner( srcFace ) ) for NETGEN 6 which sets wrong UV
783     {
784       helper->ToFixNodeParameters( true );
785
786       int nbOkPos = 0;
787       const double tol2d = 1e-12;
788       srcN_tgtN = src2tgtNodes.begin();
789       for ( ; srcN_tgtN != src2tgtNodes.end(); ++srcN_tgtN )
790       {
791         const SMDS_MeshNode* n = srcN_tgtN->second;
792         switch ( n->GetPosition()->GetTypeOfPosition() )
793         {
794         case SMDS_TOP_FACE:
795         {
796           if ( nbOkPos > 10 ) break;
797           gp_XY uv = helper->GetNodeUV( tgtFace, n ), uvBis = uv;
798           if (( helper->CheckNodeUV( tgtFace, n, uv, tol )) &&
799               (( uv - uvBis ).SquareModulus() < tol2d ))
800             ++nbOkPos;
801           else
802             nbOkPos = -((int) src2tgtNodes.size() );
803           break;
804         }
805         case SMDS_TOP_EDGE:
806         {
807           // const TopoDS_Edge & tgtE = TopoDS::Edge( tgtMeshDS->IndexToShape( n->getshapeId() ));
808           // edgeHelper.SetSubShape( tgtE );
809           // edgeHelper.GetNodeU( tgtE, n, 0, &toCheck );
810           break;
811         }
812         default:;
813         }
814       }
815     }
816
817     return true;
818
819   } //   bool projectPartner()
820
821   //================================================================================
822   /*!
823    * \brief Perform projection in case if the faces are similar in 2D space
824    */
825   //================================================================================
826
827   bool projectBy2DSimilarity(const TopoDS_Face&                 tgtFace,
828                              const TopoDS_Face&                 srcFace,
829                              const TSideVector&                 tgtWires,
830                              const TSideVector&                 srcWires,
831                              const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
832                              TAssocTool::TNodeNodeMap&          src2tgtNodes,
833                              const bool                         is1DComputed)
834   {
835     SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
836     SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
837
838     // WARNING: we can have problems if the FACE is symmetrical in 2D,
839     // then the projection can be mirrored relating to what is expected
840
841     // 1) Find 2D transformation
842
843     StdMeshers_ProjectionUtils::TrsfFinder2D trsf;
844     {
845       // get 2 pairs of corresponding UVs
846       gp_Pnt2d srcP0 = srcWires[0]->Value2d(0.0);
847       gp_Pnt2d srcP1 = srcWires[0]->Value2d(0.333);
848       gp_Pnt2d tgtP0 = tgtWires[0]->Value2d(0.0);
849       gp_Pnt2d tgtP1 = tgtWires[0]->Value2d(0.333);
850
851       // make transformation
852       gp_Trsf2d fromTgtCS, toSrcCS; // from/to global CS
853       gp_Ax2d srcCS( srcP0, gp_Vec2d( srcP0, srcP1 ));
854       gp_Ax2d tgtCS( tgtP0, gp_Vec2d( tgtP0, tgtP1 ));
855       toSrcCS  .SetTransformation( srcCS );
856       fromTgtCS.SetTransformation( tgtCS );
857       fromTgtCS.Invert();
858       trsf.Set( fromTgtCS * toSrcCS );
859
860       // check transformation
861       bool trsfIsOK = true;
862       const double tol = 1e-5 * gp_Vec2d( srcP0, srcP1 ).Magnitude();
863       for ( double u = 0.12; ( u < 1. && trsfIsOK ); u += 0.1 )
864       {
865         gp_Pnt2d srcUV  = srcWires[0]->Value2d( u );
866         gp_Pnt2d tgtUV  = tgtWires[0]->Value2d( u );
867         gp_Pnt2d tgtUV2 = trsf.Transform( srcUV );
868         trsfIsOK = ( tgtUV.Distance( tgtUV2 ) < tol );
869       }
870
871       // Find trsf using a least-square approximation
872       if ( !trsfIsOK )
873       {
874         // find trsf
875         const int totNbSeg = 50;
876         vector< gp_XY > srcPnts, tgtPnts;
877         srcPnts.reserve( totNbSeg );
878         tgtPnts.reserve( totNbSeg );
879         for ( size_t iW = 0; iW < srcWires.size(); ++iW )
880         {
881           const double minSegLen = srcWires[iW]->Length() / totNbSeg;
882           for ( int iE = 0; iE < srcWires[iW]->NbEdges(); ++iE )
883           {
884             size_t nbSeg = Max( 1, int( srcWires[iW]->EdgeLength( iE ) / minSegLen ));
885             double srcU  = srcWires[iW]->FirstParameter( iE );
886             double tgtU  = tgtWires[iW]->FirstParameter( iE );
887             double srcDu = ( srcWires[iW]->LastParameter( iE )- srcU ) / nbSeg;
888             double tgtDu = ( tgtWires[iW]->LastParameter( iE )- tgtU ) / nbSeg;
889             for ( size_t i = 0; i < nbSeg; ++i, srcU += srcDu, tgtU += tgtDu  )
890             {
891               srcPnts.push_back( srcWires[iW]->Value2d( srcU ).XY() );
892               tgtPnts.push_back( tgtWires[iW]->Value2d( tgtU ).XY() );
893             }
894           }
895         }
896         if ( !trsf.Solve( srcPnts, tgtPnts ))
897           return false;
898
899         // check trsf
900
901         trsfIsOK = true;
902         const int nbTestPnt = 10;
903         const size_t  iStep = Max( 1, int( srcPnts.size() / nbTestPnt ));
904         for ( size_t i = 0; ( i < srcPnts.size() && trsfIsOK ); i += iStep )
905         {
906           gp_Pnt2d trsfTgt = trsf.Transform( srcPnts[i] );
907           trsfIsOK = ( trsfTgt.Distance( tgtPnts[i] ) < tol );
908         }
909         if ( !trsfIsOK )
910           return false;
911       }
912     } // "Find transformation" block
913
914     // 2) Projection
915
916     SMESHDS_SubMesh* srcSubDS = srcMesh->GetMeshDS()->MeshElements( srcFace );
917
918     SMESH_MesherHelper* helper = tgtWires[0]->FaceHelper();
919     if ( is1DComputed )
920       helper->IsQuadraticSubMesh( tgtFace );
921     else
922       helper->SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
923     helper->SetElementsOnShape( true );
924     Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
925     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
926
927     SMESH_MesherHelper* srcHelper = srcWires[0]->FaceHelper();
928
929     const SMDS_MeshNode* nullNode = 0;
930     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
931
932     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
933     vector< const SMDS_MeshNode* > tgtNodes;
934     bool uvOK;
935     while ( elemIt->more() ) // loop on all mesh faces on srcFace
936     {
937       const SMDS_MeshElement* elem = elemIt->next();
938       const int nbN = elem->NbCornerNodes();
939       tgtNodes.resize( nbN );
940       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
941       {
942         const SMDS_MeshNode* srcNode = elem->GetNode(i);
943         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
944         if ( srcN_tgtN->second == nullNode )
945         {
946           // create a new node
947           gp_Pnt2d srcUV = srcHelper->GetNodeUV( srcFace, srcNode,
948                                                  elem->GetNode( helper->WrapIndex(i+1,nbN)), &uvOK);
949           gp_Pnt2d   tgtUV = trsf.Transform( srcUV );
950           gp_Pnt      tgtP = tgtSurface->Value( tgtUV.X(), tgtUV.Y() );
951           SMDS_MeshNode* n = tgtMeshDS->AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
952           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
953           {
954           case SMDS_TOP_FACE: {
955             tgtMeshDS->SetNodeOnFace( n, helper->GetSubShapeID(), tgtUV.X(), tgtUV.Y() );
956             break;
957           }
958           case SMDS_TOP_EDGE: {
959             TopoDS_Shape srcEdge = srcHelper->GetSubShapeByNode( srcNode, srcHelper->GetMeshDS() );
960             TopoDS_Edge  tgtEdge = TopoDS::Edge( shape2ShapeMap( srcEdge, /*isSrc=*/true ));
961             double U = Precision::Infinite();
962             helper->CheckNodeU( tgtEdge, n, U, Precision::PConfusion());
963             tgtMeshDS->SetNodeOnEdge( n, TopoDS::Edge( tgtEdge ), U );
964             break;
965           }
966           case SMDS_TOP_VERTEX: {
967             TopoDS_Shape srcV = srcHelper->GetSubShapeByNode( srcNode, srcHelper->GetMeshDS() );
968             TopoDS_Shape tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
969             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
970             break;
971           }
972           default:;
973           }
974           srcN_tgtN->second = n;
975         }
976         tgtNodes[i] = srcN_tgtN->second;
977       }
978       // create a new face (with reversed orientation)
979       switch ( nbN )
980       {
981       case 3: helper->AddFace(tgtNodes[0], tgtNodes[2], tgtNodes[1]); break;
982       case 4: helper->AddFace(tgtNodes[0], tgtNodes[3], tgtNodes[2], tgtNodes[1]); break;
983       }
984     }  // loop on all mesh faces on srcFace
985
986     return true;
987
988   } // projectBy2DSimilarity()
989
990   //================================================================================
991   /*!
992    * \brief Quadrangle algorithm computing structured triangle mesh
993    */
994   //================================================================================
995
996   struct QuadAlgo : public StdMeshers_Quadrangle_2D
997   {
998     QuadAlgo( int hypId, SMESH_Gen* gen ): StdMeshers_Quadrangle_2D( hypId, gen ) {}
999
1000     bool Compute( SMESH_MesherHelper & theHelper, const StdMeshers_FaceSidePtr& theWire )
1001     {
1002       SMESH_Mesh& theMesh = *theHelper.GetMesh();
1003
1004       // set sides of a quad FACE
1005       FaceQuadStruct::Ptr quad( new FaceQuadStruct );
1006       quad->side.reserve( 4 );
1007       quad->face = theWire->Face();
1008       for ( int i = 0; i < 4; ++i )
1009         quad->side.push_back
1010           ( StdMeshers_FaceSide::New( quad->face, theWire->Edge(i), &theMesh, i < QUAD_TOP_SIDE,
1011                                       /*skipMedium=*/true, theWire->FaceHelper() ));
1012       if ( !setNormalizedGrid( quad ))
1013         return false;
1014
1015       // make internal nodes
1016       SMESHDS_Mesh *  meshDS = theMesh.GetMeshDS();
1017       int         geomFaceID = meshDS->ShapeToIndex( quad->face );
1018       Handle(Geom_Surface) S = BRep_Tool::Surface( quad->face );
1019       for (   int i = 1; i < quad->iSize - 1; i++)
1020         for ( int j = 1; j < quad->jSize - 1; j++)
1021         {
1022           UVPtStruct& uvPnt = quad->UVPt( i, j );
1023           gp_Pnt P          = S->Value( uvPnt.u, uvPnt.v );
1024           uvPnt.node        = meshDS->AddNode(P.X(), P.Y(), P.Z());
1025           meshDS->SetNodeOnFace( uvPnt.node, geomFaceID, uvPnt.u, uvPnt.v );
1026         }
1027
1028       // make triangles
1029       for (   int i = 0; i < quad->iSize-1; i++) {
1030         for ( int j = 0; j < quad->jSize-1; j++)
1031         {
1032           const SMDS_MeshNode* a = quad->uv_grid[ j      * quad->iSize + i    ].node;
1033           const SMDS_MeshNode* b = quad->uv_grid[ j      * quad->iSize + i + 1].node;
1034           const SMDS_MeshNode* c = quad->uv_grid[(j + 1) * quad->iSize + i + 1].node;
1035           const SMDS_MeshNode* d = quad->uv_grid[(j + 1) * quad->iSize + i    ].node;
1036           theHelper.AddFace(a, b, c);
1037           theHelper.AddFace(a, c, d);
1038         }
1039       }
1040       return true;
1041     }
1042   };
1043
1044   //================================================================================
1045   /*!
1046    * \brief Local coordinate system of a triangle. Return barycentric coordinates of a point
1047    */
1048   //================================================================================
1049
1050   struct TriaCoordSys
1051   {
1052     gp_Pnt myO;   //!< origin
1053     gp_Vec myX;   //!< X axis
1054     gp_Vec myY;   //!< Y axis
1055     gp_XY  myUV1; //!< UV of 2nd node in this CS
1056     gp_XY  myUV2; //!< UV of 3d  node in this CS
1057
1058     void Init( const gp_Pnt p1, const gp_Pnt p2, const gp_Pnt p3 )
1059     {
1060       myO = p1;
1061
1062       myX = gp_Vec( p1, p2 );
1063       myUV1.SetCoord( myX.Magnitude(), 0 );
1064       myX /= myUV1.X();
1065
1066       gp_Vec v13( p1, p3 );
1067       myY = myX.CrossCrossed( myX, v13 );
1068       myY.Normalize();
1069       myUV2.SetCoord( v13 * myX, v13 * myY );
1070
1071       return;
1072     }
1073
1074     void GetBaryCoords( const gp_Pnt p, double& bc1, double& bc2, double& bc3 ) const
1075     {
1076       gp_Vec op( myO, p );
1077       gp_XY uv( op * myX, op * myY );
1078
1079       SMESH_MeshAlgos::GetBarycentricCoords( uv,
1080                                              gp::Origin2d().XY(), myUV1, myUV2,
1081                                              bc1, bc2 );
1082       bc3 = 1 - bc1 - bc2;
1083     }
1084   };
1085
1086
1087   //================================================================================
1088   /*!
1089    * \brief Structured 2D mesh of a quadrilateral FACE; is used in projectQuads()
1090    */
1091   //================================================================================
1092
1093   struct QuadMesh : public SMESH_Mesh
1094   {
1095     ObjectPool< TriaCoordSys > _traiLCSPool;
1096     SMESH_ElementSearcher*     _elemSearcher;
1097     SMESH_Gen                  _sgen;
1098     SMESH_MesherHelper         _helper;
1099
1100     QuadMesh(const TopoDS_Face& face):
1101       _elemSearcher( nullptr ), _helper( *this )
1102     {
1103       _meshDS = new SMESHDS_Mesh( 0, true );
1104       _gen = &_sgen;
1105       ShapeToMesh( face );
1106     }
1107     ~QuadMesh() { delete _elemSearcher; }
1108
1109     // --------------------------------------------------------------------------------
1110     /*!
1111      * \brief Compute quadrangle mesh and prepare for face search
1112      */
1113     bool Compute( const TSideVector& wires, int nbSeg1, int nbSeg2, bool isSourceMesh )
1114     {
1115       if ( wires.size() > 1 || wires[0]->NbEdges() != 4 )
1116         return false;
1117
1118       // compute quadrangle mesh
1119
1120       SMESH_Hypothesis* algo1D = new StdMeshers_Regular_1D( _sgen.GetANewId(), &_sgen );
1121       AddHypothesis( GetShapeToMesh(), algo1D->GetID() );
1122
1123       StdMeshers_NumberOfSegments * nbHyp1, *nbHyp2;
1124       nbHyp1 = new StdMeshers_NumberOfSegments( _sgen.GetANewId(), &_sgen );
1125       nbHyp1->SetNumberOfSegments( nbSeg1 );
1126       AddHypothesis( wires[0]->Edge(0), nbHyp1->GetID() );
1127       AddHypothesis( wires[0]->Edge(2), nbHyp1->GetID() );
1128
1129       nbHyp2 = new StdMeshers_NumberOfSegments( _sgen.GetANewId(), &_sgen );
1130       nbHyp2->SetNumberOfSegments( nbSeg2 );
1131       AddHypothesis( wires[0]->Edge(1), nbHyp2->GetID() );
1132       AddHypothesis( wires[0]->Edge(3), nbHyp2->GetID() );
1133
1134       if ( !_sgen.Compute( *this, GetShapeToMesh(), SMESH_Gen::SHAPE_ONLY_UPWARD ))
1135         return false;
1136
1137       QuadAlgo algo2D( _sgen.GetANewId(), &_sgen );
1138       if ( !algo2D.Compute( _helper, wires[0] ))
1139         return false;
1140
1141       // remove edges
1142       // for ( SMDS_ElemIteratorPtr eIt = _meshDS->elementsIterator( SMDSAbs_Edge ); eIt->more(); )
1143       //   _meshDS->RemoveFreeElement( eIt->next(), /*sm=*/0, /*groups=*/false );
1144
1145       // _meshDS->Modified(); // setMyModified();
1146       // _meshDS->CompactMesh();
1147
1148       // create TriaCoordSys for every triangle
1149       if ( isSourceMesh )
1150       {
1151         for ( SMDS_ElemIteratorPtr fIt = _meshDS->elementsIterator( SMDSAbs_Face ); fIt->more(); )
1152         {
1153           const SMDS_MeshElement* tria = fIt->next();
1154           TriaCoordSys* triaLCS = _traiLCSPool.getNew();
1155           triaLCS->Init( SMESH_NodeXYZ( tria->GetNode( 0 )),
1156                          SMESH_NodeXYZ( tria->GetNode( 1 )),
1157                          SMESH_NodeXYZ( tria->GetNode( 2 )));
1158           // int i= tria->GetID() - NbEdges() - 1;
1159           // cout << "ID from TRIA " << i << " - poolSize " << _traiLCSPool.nbElements() <<
1160           //   ( _traiLCSPool[i]!= triaLCS ? " KO" : "" )  << endl;
1161         }
1162         _elemSearcher = SMESH_MeshAlgos::GetElementSearcher( *_meshDS );
1163       }
1164       return true;
1165     }
1166     // --------------------------------------------------------------------------------
1167     /*!
1168      * \brief Find a source triangle including a point and return its barycentric coordinates
1169      */
1170     const SMDS_MeshElement* FindFaceByPoint( const gp_Pnt p,
1171                                              double & bc1, double & bc2, double & bc3 )
1172     {
1173       const SMDS_MeshElement* tria = nullptr;
1174       gp_XYZ projPnt = _elemSearcher->Project( p, SMDSAbs_Face, &tria );
1175
1176       int lcsID = tria->GetID() - NbEdges() - 1;
1177       const TriaCoordSys* triaLCS = _traiLCSPool[ lcsID ];
1178       triaLCS->GetBaryCoords( projPnt, bc1, bc2, bc3 );
1179
1180       return tria;
1181     }
1182     // --------------------------------------------------------------------------------
1183     /*!
1184      * \brief Return a point lying on a corresponding target triangle
1185      */
1186     gp_Pnt GetPoint( const SMDS_MeshElement* srcTria, double & bc1, double & bc2, double & bc3 )
1187     {
1188       const SMDS_MeshElement* tgtTria = _meshDS->FindElement( srcTria->GetID() );
1189       gp_Pnt p = ( bc1 * SMESH_NodeXYZ( tgtTria->GetNode(0) ) +
1190                    bc2 * SMESH_NodeXYZ( tgtTria->GetNode(1) ) +
1191                    bc3 * SMESH_NodeXYZ( tgtTria->GetNode(2) ) );
1192       return p;
1193     }
1194     // --------------------------------------------------------------------------------
1195     /*!
1196      * \brief Return an UV of point lying on a corresponding target triangle
1197      */
1198     gp_XY GetUV( const SMDS_MeshElement* srcTria,
1199                  double & bc1, double & bc2, double & bc3 )
1200     {
1201       const SMDS_MeshElement* tgtTria = _meshDS->FindElement( srcTria->GetID() );
1202       TopoDS_Shape tgtShape = GetShapeToMesh();
1203       const TopoDS_Face& face = TopoDS::Face( tgtShape );
1204
1205       gp_XY p = ( bc1 * _helper.GetNodeUV( face, tgtTria->GetNode(0) ) +
1206                   bc2 * _helper.GetNodeUV( face, tgtTria->GetNode(1) ) +
1207                   bc3 * _helper.GetNodeUV( face, tgtTria->GetNode(2) ) );
1208       return p;
1209     }
1210   };
1211
1212   //================================================================================
1213   /*!
1214    * \brief Calculate average size of faces
1215    *         Actually calculate average of min and max face size
1216    */
1217   //================================================================================
1218
1219   double calcAverageFaceSize( SMESHDS_SubMesh* sm )
1220   {
1221     double minLen = Precision::Infinite(), maxLen = 0;
1222     for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
1223     {
1224       const SMDS_MeshElement* face = fIt->next();
1225       int nbNodes = face->NbCornerNodes();
1226       gp_XYZ pPrev = SMESH_NodeXYZ( face->GetNode( nbNodes - 1 ));
1227       for ( int i = 0; i < nbNodes; ++i )
1228       {
1229         SMESH_NodeXYZ p( face->GetNode( i ));
1230         double len = ( p - pPrev ).SquareModulus();
1231         minLen = Min( len, minLen );
1232         maxLen = Max( len, maxLen );
1233         pPrev = p;
1234       }
1235     }
1236     return 0.5 * ( Sqrt( minLen ) + Sqrt( maxLen ));
1237   }
1238
1239   //================================================================================
1240   /*!
1241    * \brief Perform projection from a quadrilateral FACE to another quadrilateral one
1242    */
1243   //================================================================================
1244
1245   bool projectQuads(const TopoDS_Face&                 tgtFace,
1246                     const TopoDS_Face&                 srcFace,
1247                     const TSideVector&                 tgtWires,
1248                     const TSideVector&                 srcWires,
1249                     const TAssocTool::TShapeShapeMap&  shape2ShapeMap,
1250                     TAssocTool::TNodeNodeMap&          src2tgtNodes,
1251                     const bool                         is1DComputed)
1252   {
1253     SMESH_Mesh * tgtMesh = tgtWires[0]->GetMesh();
1254     SMESH_Mesh * srcMesh = srcWires[0]->GetMesh();
1255     SMESHDS_Mesh * tgtMeshDS = tgtMesh->GetMeshDS();
1256     SMESHDS_Mesh * srcMeshDS = srcMesh->GetMeshDS();
1257
1258     if ( srcWires.size() != 1 || // requirements below can be weaken
1259          SMESH_MesherHelper::Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true) != 4 ||
1260          SMESH_MesherHelper::Count( srcFace, TopAbs_EDGE, /*ignoreSame=*/true) != 4 )
1261       return false;
1262
1263     // make auxiliary structured meshes that will be used to get corresponding
1264     // points on the target FACE
1265     QuadMesh srcQuadMesh( srcFace ), tgtQuadMesh( tgtFace );
1266     double avgSize = calcAverageFaceSize( srcMeshDS->MeshElements( srcFace ));
1267     int nbSeg1 = (int) Max( 2., Max( srcWires[0]->EdgeLength(0),
1268                                      srcWires[0]->EdgeLength(2)) / avgSize );
1269     int nbSeg2 = (int) Max( 2., Max( srcWires[0]->EdgeLength(1),
1270                                      srcWires[0]->EdgeLength(3)) / avgSize );
1271     if ( !srcQuadMesh.Compute( srcWires, nbSeg1, nbSeg2, /*isSrc=*/true ) ||
1272          !tgtQuadMesh.Compute( tgtWires, nbSeg1, nbSeg2, /*isSrc=*/false ))
1273       return false;
1274
1275     // Make new faces
1276
1277     // prepare the helper to adding quadratic elements if necessary
1278     SMESH_MesherHelper* helper = tgtWires[0]->FaceHelper();
1279     helper->IsQuadraticSubMesh( tgtFace );
1280
1281     SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
1282     if ( !is1DComputed && srcSubDS->NbElements() )
1283       helper->SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
1284
1285     SMESH_MesherHelper* srcHelper = srcWires[0]->FaceHelper();
1286     SMESH_MesherHelper  edgeHelper( *tgtMesh );
1287     edgeHelper.ToFixNodeParameters( true );
1288
1289     const SMDS_MeshNode* nullNode = 0;
1290     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
1291
1292     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
1293     vector< const SMDS_MeshNode* > tgtNodes;
1294     while ( elemIt->more() ) // loop on all mesh faces on srcFace
1295     {
1296       const SMDS_MeshElement* elem = elemIt->next();
1297       const int nbN = elem->NbCornerNodes();
1298       tgtNodes.resize( nbN );
1299       helper->SetElementsOnShape( false );
1300       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
1301       {
1302         const SMDS_MeshNode* srcNode = elem->GetNode(i);
1303         srcN_tgtN = src2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
1304         if ( srcN_tgtN->second == nullNode )
1305         {
1306           // create a new node
1307           gp_Pnt srcP = SMESH_TNodeXYZ( srcNode );
1308           double bc[3];
1309           const SMDS_MeshElement* auxF = srcQuadMesh.FindFaceByPoint( srcP, bc[0], bc[1], bc[2] );
1310           gp_Pnt                  tgtP = tgtQuadMesh.GetPoint( auxF, bc[0], bc[1], bc[2] );
1311           SMDS_MeshNode* n = helper->AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
1312           srcN_tgtN->second = n;
1313           switch ( srcNode->GetPosition()->GetTypeOfPosition() )
1314           {
1315           case SMDS_TOP_FACE:
1316           {
1317             gp_XY tgtUV = tgtQuadMesh.GetUV( auxF, bc[0], bc[1], bc[2] );
1318             tgtMeshDS->SetNodeOnFace( n, helper->GetSubShapeID(), tgtUV.X(), tgtUV.Y() );
1319             break;
1320           }
1321           case SMDS_TOP_EDGE:
1322           {
1323             const TopoDS_Edge& srcE = TopoDS::Edge( srcMeshDS->IndexToShape( srcNode->GetShapeID()));
1324             const TopoDS_Edge& tgtE = TopoDS::Edge( shape2ShapeMap( srcE, /*isSrc=*/true ));
1325             double srcU = srcHelper->GetNodeU( srcE, srcNode );
1326             tgtMeshDS->SetNodeOnEdge( n, tgtE, srcU );
1327             edgeHelper.SetSubShape( tgtE );
1328             double tol = BRep_Tool::MaxTolerance( tgtE, TopAbs_VERTEX ), distXYZ[4];
1329             /*isOk = */edgeHelper.CheckNodeU( tgtE, n, srcU, 2 * tol, /*force=*/true, distXYZ );
1330             //if ( isOk )
1331             tgtMeshDS->MoveNode( n, distXYZ[1], distXYZ[2], distXYZ[3] );
1332             SMDS_EdgePositionPtr( n->GetPosition() )->SetUParameter( srcU );
1333             break;
1334           }
1335           case SMDS_TOP_VERTEX:
1336           {
1337             const TopoDS_Shape & srcV = srcMeshDS->IndexToShape( srcNode->getshapeId() );
1338             const TopoDS_Shape & tgtV = shape2ShapeMap( srcV, /*isSrc=*/true );
1339             tgtP = BRep_Tool::Pnt( TopoDS::Vertex( tgtV ));
1340             tgtMeshDS->MoveNode( n, tgtP.X(), tgtP.Y(), tgtP.Z() );
1341             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
1342             break;
1343           }
1344           default:;
1345           }
1346         }
1347         tgtNodes[i] = srcN_tgtN->second;
1348       }
1349       // create a new face
1350       helper->SetElementsOnShape( true );
1351       switch ( nbN )
1352       {
1353       case 3: helper->AddFace(tgtNodes[0], tgtNodes[1], tgtNodes[2]); break;
1354       case 4: helper->AddFace(tgtNodes[0], tgtNodes[1], tgtNodes[2], tgtNodes[3]); break;
1355       default: helper->AddPolygonalFace( tgtNodes );
1356       }
1357     } //  // loop on all mesh faces on srcFace
1358
1359     return true;
1360
1361     // below is projection of a structured source mesh
1362
1363     // if ( !is1DComputed )
1364     //   return false;
1365     // for ( int iE = 0; iE < 4; ++iE )
1366     // {
1367     //   SMESHDS_SubMesh* sm = srcMeshDS->MeshElements( srcWires[0]->Edge( iE ));
1368     //   if ( !sm ) return false;
1369     //   if ( sm->NbNodes() + sm->NbElements() == 0 ) return false;
1370     // }
1371     // if ( BRepAdaptor_Surface( tgtFace ).GetType() != GeomAbs_Plane )
1372     //   return false;
1373     // // if ( BRepAdaptor_Surface( tgtFace ).GetType() == GeomAbs_Plane &&
1374     // //      BRepAdaptor_Surface( srcFace ).GetType() == GeomAbs_Plane )
1375     // //   return false; // too easy
1376
1377     // // load EDGEs to SMESH_Block
1378
1379     // SMESH_Block block;
1380     // TopTools_IndexedMapOfOrientedShape blockSubShapes;
1381     // {
1382     //   const TopoDS_Solid& box = srcMesh->PseudoShape();
1383     //   TopoDS_Shell shell = TopoDS::Shell( TopExp_Explorer( box, TopAbs_SHELL ).Current() );
1384     //   TopoDS_Vertex v;
1385     //   block.LoadBlockShapes( shell, v, v, blockSubShapes ); // fill all since operator[] is missing
1386     // }
1387     // const SMESH_Block::TShapeID srcFaceBID = SMESH_Block::ID_Fxy0;
1388     // const SMESH_Block::TShapeID tgtFaceBID = SMESH_Block::ID_Fxy1;
1389     // vector< int > edgeBID;
1390     // block.GetFaceEdgesIDs( srcFaceBID, edgeBID ); // u0, u1, 0v, 1v
1391     // blockSubShapes.Substitute( edgeBID[0], srcWires[0]->Edge(0) );
1392     // blockSubShapes.Substitute( edgeBID[1], srcWires[0]->Edge(2) );
1393     // blockSubShapes.Substitute( edgeBID[2], srcWires[0]->Edge(3) );
1394     // blockSubShapes.Substitute( edgeBID[3], srcWires[0]->Edge(1) );
1395     // block.GetFaceEdgesIDs( tgtFaceBID, edgeBID ); // u0, u1, 0v, 1v
1396     // blockSubShapes.Substitute( edgeBID[0], tgtWires[0]->Edge(0) );
1397     // blockSubShapes.Substitute( edgeBID[1], tgtWires[0]->Edge(2) );
1398     // blockSubShapes.Substitute( edgeBID[2], tgtWires[0]->Edge(3) );
1399     // blockSubShapes.Substitute( edgeBID[3], tgtWires[0]->Edge(1) );
1400     // block.LoadFace( srcFace, srcFaceBID, blockSubShapes );
1401     // block.LoadFace( tgtFace, tgtFaceBID, blockSubShapes );
1402
1403     // // remember connectivity of new faces in terms of ( node-or-XY )
1404
1405     // typedef std::pair< const SMDS_MeshNode*, gp_XYZ > TNodeOrXY; // node-or-XY
1406     // typedef std::vector< TNodeOrXY* >                 TFaceConn; // face connectivity
1407     // std::vector< TFaceConn >                    newFacesVec;     // connectivity of all faces
1408     // std::map< const SMDS_MeshNode*, TNodeOrXY > srcNode2tgtNXY;  // src node -> node-or-XY
1409
1410     // TAssocTool::TNodeNodeMap::iterator                                       srcN_tgtN;
1411     // std::map< const SMDS_MeshNode*, TNodeOrXY >::iterator                    srcN_tgtNXY;
1412     // std::pair< std::map< const SMDS_MeshNode*, TNodeOrXY >::iterator, bool > n2n_isNew;
1413     // TNodeOrXY nullNXY( (SMDS_MeshNode*)NULL, gp_XYZ(0,0,0) );
1414
1415     // SMESHDS_SubMesh* srcSubDS = srcMeshDS->MeshElements( srcFace );
1416     // newFacesVec.resize( srcSubDS->NbElements() );
1417     // int iFaceSrc = 0;
1418
1419     // SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
1420     // while ( elemIt->more() ) // loop on all mesh faces on srcFace
1421     // {
1422     //   const SMDS_MeshElement* elem = elemIt->next();
1423     //   TFaceConn& tgtNodes = newFacesVec[ iFaceSrc++ ];
1424
1425     //   const int nbN = elem->NbCornerNodes(); 
1426     //   tgtNodes.resize( nbN );
1427     //   for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
1428     //   {
1429     //     const SMDS_MeshNode* srcNode = elem->GetNode(i);
1430     //     n2n_isNew = srcNode2tgtNXY.insert( make_pair( srcNode, nullNXY ));
1431     //     TNodeOrXY & tgtNodeOrXY = n2n_isNew.first->second;
1432     //     if ( n2n_isNew.second ) // new src node encounters
1433     //     {
1434     //       srcN_tgtN = src2tgtNodes.find( srcNode );
1435     //       if ( srcN_tgtN != src2tgtNodes.end() )
1436     //       {
1437     //         tgtNodeOrXY.first = srcN_tgtN->second; // tgt node exists
1438     //       }
1439     //       else 
1440     //       {
1441     //         // find XY of src node within the quadrilateral srcFace
1442     //         if ( !block.ComputeParameters( SMESH_TNodeXYZ( srcNode ),
1443     //                                        tgtNodeOrXY.second, srcFaceBID ))
1444     //           return false;
1445     //       }
1446     //     }
1447     //     tgtNodes[ i ] = & tgtNodeOrXY;
1448     //   }
1449     // }
1450
1451     // // as all XY are computed, create tgt nodes and faces
1452
1453     // SMESH_MesherHelper helper = *tgtWires[0]->FaceHelper();
1454     // if ( is1DComputed )
1455     //   helper.IsQuadraticSubMesh( tgtFace );
1456     // else
1457     //   helper.SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
1458     // helper.SetElementsOnShape( true );
1459     // Handle(Geom_Surface) tgtSurface = BRep_Tool::Surface( tgtFace );
1460
1461     // SMESH_MesherHelper srcHelper = *srcWires[0]->FaceHelper();
1462
1463     // vector< const SMDS_MeshNode* > tgtNodes;
1464     // gp_XY uv;
1465
1466     // for ( size_t iFaceTgt = 0; iFaceTgt < newFacesVec.size(); ++iFaceTgt )
1467     // {
1468     //   TFaceConn& tgtConn = newFacesVec[ iFaceTgt ];
1469     //   tgtNodes.resize( tgtConn.size() );
1470     //   for ( size_t iN = 0; iN < tgtConn.size(); ++iN )
1471     //   {
1472     //     const SMDS_MeshNode* & tgtN = tgtConn[ iN ]->first;
1473     //     if ( !tgtN ) // create a node
1474     //     {
1475     //       if ( !block.FaceUV( tgtFaceBID, tgtConn[iN]->second, uv ))
1476     //         return false;
1477     //       gp_Pnt p = tgtSurface->Value( uv.X(), uv.Y() );
1478     //       tgtN = helper.AddNode( p.X(), p.Y(), p.Z(), uv.X(), uv.Y() );
1479     //     }
1480     //     tgtNodes[ tgtNodes.size() - iN - 1] = tgtN; // reversed orientation
1481     //   }
1482     //   switch ( tgtNodes.size() )
1483     //   {
1484     //   case 3: helper.AddFace(tgtNodes[0], tgtNodes[1], tgtNodes[2]); break;
1485     //   case 4: helper.AddFace(tgtNodes[0], tgtNodes[1], tgtNodes[2], tgtNodes[3]); break;
1486     //   default:
1487     //     if ( tgtNodes.size() > 4 )
1488     //       helper.AddPolygonalFace( tgtNodes );
1489     //   }
1490     // }
1491     return false; //true;
1492
1493   } // bool projectQuads(...)
1494
1495   //================================================================================
1496   /*!
1497    * \brief Fix bad faces by smoothing
1498    */
1499   //================================================================================
1500
1501   bool fixDistortedFaces( SMESH_MesherHelper& helper,
1502                           TSideVector&        tgtWires )
1503   {
1504     SMESH_subMesh* faceSM = helper.GetMesh()->GetSubMesh( helper.GetSubShape() );
1505
1506     //if ( helper.IsDistorted2D( faceSM, /*checkUV=*/true ))
1507     {
1508       SMESH_MeshEditor editor( helper.GetMesh() );
1509       SMESHDS_SubMesh* smDS = faceSM->GetSubMeshDS();
1510       const TopoDS_Face&  F = TopoDS::Face( faceSM->GetSubShape() );
1511
1512       TIDSortedElemSet faces;
1513       SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
1514       for ( faceIt = smDS->GetElements(); faceIt->more(); )
1515         faces.insert( faces.end(), faceIt->next() );
1516
1517       // choose smoothing algo
1518       //SMESH_MeshEditor:: SmoothMethod algo = SMESH_MeshEditor::CENTROIDAL;
1519       bool isConcaveBoundary = false;
1520       for ( size_t iW = 0; iW < tgtWires.size() && !isConcaveBoundary; ++iW )
1521       {
1522         TopoDS_Edge prevEdge = tgtWires[iW]->Edge( tgtWires[iW]->NbEdges() - 1 );
1523         for ( int iE = 0; iE < tgtWires[iW]->NbEdges() && !isConcaveBoundary; ++iE )
1524         {
1525           double angle = helper.GetAngle( prevEdge, tgtWires[iW]->Edge( iE ),
1526                                           F,        tgtWires[iW]->FirstVertex( iE ));
1527           isConcaveBoundary = ( angle < -5. * M_PI / 180. );
1528
1529           prevEdge = tgtWires[iW]->Edge( iE );
1530         }
1531       }
1532       SMESH_MeshEditor:: SmoothMethod algo =
1533         isConcaveBoundary ? SMESH_MeshEditor::CENTROIDAL : SMESH_MeshEditor::LAPLACIAN;
1534
1535       // smooth in 2D or 3D?
1536       TopLoc_Location loc;
1537       Handle(Geom_Surface) surface = BRep_Tool::Surface( F, loc );
1538       bool isPlanar = GeomLib_IsPlanarSurface( surface ).IsPlanar();
1539
1540       // smoothing
1541       set<const SMDS_MeshNode*> fixedNodes;
1542       editor.Smooth( faces, fixedNodes, algo, /*nbIterations=*/ 10,
1543                      /*theTgtAspectRatio=*/1.0, /*the2D=*/!isPlanar);
1544
1545       helper.ToFixNodeParameters( true );
1546
1547       return !helper.IsDistorted2D( faceSM, /*checkUV=*/true );
1548     }
1549     return true;
1550   }
1551
1552   //=======================================================================
1553   /*
1554    * Set initial association of VERTEXes for the case of projection
1555    * from a quadrangle FACE to a closed FACE, where opposite src EDGEs
1556    * have different nb of segments
1557    */
1558   //=======================================================================
1559
1560   void initAssoc4Quad2Closed(const TopoDS_Shape&          tgtFace,
1561                              SMESH_MesherHelper&          tgtHelper,
1562                              const TopoDS_Shape&          srcFace,
1563                              SMESH_Mesh*                  srcMesh,
1564                              TAssocTool::TShapeShapeMap & assocMap)
1565   {
1566     if ( !tgtHelper.HasRealSeam() || srcFace.ShapeType() != TopAbs_FACE )
1567       return; // no seam edge
1568     list< TopoDS_Edge > tgtEdges, srcEdges;
1569     list< int > tgtNbEW, srcNbEW;
1570     int tgtNbW = SMESH_Block::GetOrderedEdges( TopoDS::Face( tgtFace ), tgtEdges, tgtNbEW );
1571     int srcNbW = SMESH_Block::GetOrderedEdges( TopoDS::Face( srcFace ), srcEdges, srcNbEW );
1572     if ( tgtNbW != 1 || srcNbW != 1 ||
1573          tgtNbEW.front() != 4 || srcNbEW.front() != 4 )
1574       return; // not quads
1575
1576     smIdType srcNbSeg[4];
1577     list< TopoDS_Edge >::iterator edgeS = srcEdges.begin(), edgeT = tgtEdges.begin();
1578     for ( int i = 0; edgeS != srcEdges.end(); ++i, ++edgeS )
1579       if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( *edgeS ))
1580         srcNbSeg[ i ] = sm->NbNodes();
1581       else
1582         return; // not meshed
1583     if ( srcNbSeg[0] == srcNbSeg[2] && srcNbSeg[1] == srcNbSeg[3] )
1584       return; // same nb segments
1585     if ( srcNbSeg[0] != srcNbSeg[2] && srcNbSeg[1] != srcNbSeg[3] )
1586       return; // all different nb segments
1587
1588     edgeS = srcEdges.begin();
1589     if ( srcNbSeg[0] != srcNbSeg[2] )
1590       ++edgeS;
1591     TAssocTool::InsertAssociation( tgtHelper.IthVertex( 0,*edgeT ),
1592                                    tgtHelper.IthVertex( 0,*edgeS ), assocMap );
1593     TAssocTool::InsertAssociation( tgtHelper.IthVertex( 1,*edgeT ),
1594                                    tgtHelper.IthVertex( 1,*edgeS ), assocMap );
1595   }
1596
1597   //================================================================================
1598   /*!
1599    * \brief Find sub-shape association such that corresponding VERTEXes of
1600    *        two corresponding FACEs lie on lines parallel to thePiercingLine
1601    */
1602   //================================================================================
1603
1604   bool findSubShapeAssociationByPiercing( const TopoDS_Face&          theTgtFace,
1605                                           SMESH_Mesh *                /*theTgtMesh*/,
1606                                           const TopoDS_Shape&         theSrcShape,
1607                                           SMESH_Mesh*                 theSrcMesh,
1608                                           TAssocTool::TShapeShapeMap& theShape2ShapeMap,
1609                                           Handle(Geom_Line) &         thePiercingLine )
1610   {
1611     list< TopoDS_Edge > tgtEdges, srcEdges;
1612     list< int > tgtNbEW, srcNbEW;
1613     int tgtNbW = SMESH_Block::GetOrderedEdges( TopoDS::Face( theTgtFace ), tgtEdges, tgtNbEW );
1614
1615     TopTools_IndexedMapOfShape tgtVV, srcVV;
1616     for ( const TopoDS_Edge& tgtEdge : tgtEdges )
1617       tgtVV.Add( SMESH_MesherHelper::IthVertex( 0, tgtEdge ));
1618     // if ( tgtVV.Size() < 2 )
1619     //   return false;
1620
1621     const int       nbVV = tgtVV.Size();
1622     const gp_Pnt   tgtP0 = BRep_Tool::Pnt( TopoDS::Vertex( tgtVV( 1 )));
1623     double minVertexDist = Precision::Infinite(), assocTol;
1624     gp_Lin      piercingLine;
1625     TopoDS_Face assocSrcFace;
1626     double      tol;
1627
1628     for ( TopExp_Explorer faceExp( theSrcShape, TopAbs_FACE ); faceExp.More(); faceExp.Next())
1629     {
1630       const TopoDS_Face& srcFace = TopoDS::Face( faceExp.Current() );
1631
1632       int srcNbW = SMESH_Block::GetOrderedEdges( srcFace, srcEdges, srcNbEW );
1633       if ( tgtNbW != srcNbW )
1634         continue;
1635
1636       srcVV.Clear( false );
1637       for ( const TopoDS_Edge& srcEdge : srcEdges )
1638         srcVV.Add( SMESH_MesherHelper::IthVertex( 0, srcEdge ));
1639       if ( srcVV.Extent() != tgtVV.Extent() )
1640         continue;
1641
1642       // make srcFace computed
1643       SMESH_subMesh* srcFaceSM = theSrcMesh->GetSubMesh( srcFace );
1644       if ( !TAssocTool::MakeComputed( srcFaceSM ))
1645         continue;
1646
1647       // compute tolerance
1648       double sumLen = 0, nbEdges = 0;
1649       for ( const TopoDS_Edge& srcEdge : srcEdges )
1650       {
1651         SMESH_subMesh* srcSM = theSrcMesh->GetSubMesh( srcEdge );
1652         if ( !srcSM->GetSubMeshDS() )
1653           continue;
1654         SMDS_ElemIteratorPtr edgeIt = srcSM->GetSubMeshDS()->GetElements();
1655         while ( edgeIt->more() )
1656         {
1657           const SMDS_MeshElement* edge = edgeIt->next();
1658           sumLen += SMESH_NodeXYZ( edge->GetNode( 0 )).Distance( edge->GetNode( 1 ));
1659           nbEdges += 1;
1660         }
1661       }
1662       if ( nbEdges == 0 )
1663         continue;
1664
1665       tol = 0.1 * sumLen / nbEdges;
1666
1667       // try to find corresponding VERTEXes
1668
1669       gp_Lin line;
1670       double vertexDist;
1671       for ( int iSrcV0 = 1; iSrcV0 <= srcVV.Size(); ++iSrcV0 )
1672       {
1673         const gp_Pnt srcP0 = BRep_Tool::Pnt( TopoDS::Vertex( srcVV( iSrcV0 )));
1674         try {
1675           line.SetDirection( gp_Vec( srcP0, tgtP0 ));
1676         }
1677         catch (...) {
1678           continue;
1679         }
1680         bool correspond;
1681         for ( int iDir : { -1, 1 }) // move connected VERTEX forward and backward
1682         {
1683           correspond = true;
1684           vertexDist = 0;
1685           int iTgtV = 0, iSrcV = iSrcV0 - 1;
1686           for ( int i = 1; i < tgtVV.Size() &&   correspond; ++i )
1687           {
1688             iTgtV = ( iTgtV + 1           ) % nbVV;
1689             iSrcV = ( iSrcV + iDir + nbVV ) % nbVV;
1690             gp_Pnt tgtP = BRep_Tool::Pnt( TopoDS::Vertex( tgtVV( iTgtV + 1 )));
1691             gp_Pnt srcP = BRep_Tool::Pnt( TopoDS::Vertex( srcVV( iSrcV + 1 )));
1692             line.SetLocation( tgtP );
1693             correspond = ( line.SquareDistance( srcP ) < tol * tol );
1694             vertexDist += tgtP.SquareDistance( srcP );
1695           }
1696           if ( correspond )
1697             break;
1698         }
1699         if ( correspond )
1700         {
1701           if ( vertexDist < minVertexDist )
1702           {
1703             minVertexDist = vertexDist;
1704             piercingLine    = line;
1705             assocSrcFace  = srcFace;
1706             assocTol      = tol;
1707           }
1708           break;
1709         }
1710       }
1711       continue;
1712
1713     } // loop on src FACEs
1714
1715     if ( Precision::IsInfinite( minVertexDist ))
1716       return false; // no correspondence found
1717
1718     thePiercingLine = new Geom_Line( piercingLine );
1719
1720     // fill theShape2ShapeMap
1721
1722     TAssocTool::InsertAssociation( theTgtFace, assocSrcFace, theShape2ShapeMap );
1723
1724     for ( const TopoDS_Shape& tgtV : tgtVV ) // fill theShape2ShapeMap with VERTEXes
1725     {
1726       gp_Pnt tgtP = BRep_Tool::Pnt( TopoDS::Vertex( tgtV ));
1727       piercingLine.SetLocation( tgtP );
1728       bool found = false;
1729       for ( const TopoDS_Shape& srcV : srcVV )
1730       {
1731         gp_Pnt srcP = BRep_Tool::Pnt( TopoDS::Vertex( srcV ));
1732         if ( piercingLine.SquareDistance( srcP ) < assocTol * assocTol )
1733         {
1734           TAssocTool::InsertAssociation( tgtV, srcV, theShape2ShapeMap );
1735           found = true;
1736           break;
1737         }
1738       }
1739       if ( !found )
1740         return false;
1741     }
1742
1743     TopoDS_Vertex vvT[2], vvS[2], vvMapped[2];
1744     for ( const TopoDS_Edge& tgtEdge : tgtEdges ) // fill theShape2ShapeMap with EDGEs
1745     {
1746       if ( SMESH_Algo::isDegenerated( tgtEdge ))
1747         continue;
1748
1749       TopExp::Vertices( tgtEdge, vvT[0], vvT[1], true );
1750       if ( !theShape2ShapeMap.IsBound( vvT[0] ) ||
1751            !theShape2ShapeMap.IsBound( vvT[1] ))
1752         return false;
1753
1754       vvMapped[0] = TopoDS::Vertex( theShape2ShapeMap( vvT[0] ));
1755       vvMapped[1] = TopoDS::Vertex( theShape2ShapeMap( vvT[1] ));
1756
1757       bool found = false;
1758       for ( TopExp_Explorer eExp( assocSrcFace, TopAbs_EDGE ); eExp.More(); eExp.Next())
1759       {
1760         TopoDS_Edge srcEdge = TopoDS::Edge( eExp.Current() );
1761         TopExp::Vertices( srcEdge, vvS[0], vvS[1], true );
1762         found = (( vvMapped[0].IsSame( vvS[0] ) && vvMapped[1].IsSame( vvS[1] )) ||
1763                  ( vvMapped[0].IsSame( vvS[1] ) && vvMapped[1].IsSame( vvS[0] )));
1764
1765         if ( found && nbVV < 3 )
1766         {
1767           BRepAdaptor_Curve tgtCurve( tgtEdge );
1768           gp_Pnt tgtP = tgtCurve.Value( 0.5 * ( tgtCurve.FirstParameter() +
1769                                                 tgtCurve.LastParameter() ));
1770           thePiercingLine->SetLocation( tgtP );
1771
1772           double f,l;
1773           Handle(Geom_Curve) srcCurve = BRep_Tool::Curve( srcEdge, f,l );
1774           if ( srcCurve.IsNull() )
1775           {
1776             found = false;
1777             continue;
1778           }
1779           GeomAPI_ExtremaCurveCurve extrema( thePiercingLine, srcCurve );
1780           if ( !extrema.Extrema().IsDone() ||
1781                extrema.Extrema().IsParallel() ||
1782                extrema.NbExtrema() == 0 ||
1783                extrema.LowerDistance() > tol )
1784             found = false;
1785         }
1786         if ( found )
1787         {
1788           if ( !vvMapped[0].IsSame( vvS[0] ))
1789             srcEdge.Reverse();
1790           TAssocTool::InsertAssociation( tgtEdge, srcEdge, theShape2ShapeMap );
1791           break;
1792         }
1793       }
1794       if ( !found )
1795         return false;
1796     }
1797
1798     return true;
1799
1800   } // findSubShapeAssociationByPiercing()
1801
1802     //================================================================================
1803   /*!
1804    * \brief Project by piercing theTgtFace by lines parallel to thePiercingLine
1805    */
1806   //================================================================================
1807
1808   bool projectByPiercing(Handle(Geom_Line)                  thePiercingLine,
1809                          const TopoDS_Face&                 theTgtFace,
1810                          const TopoDS_Face&                 theSrcFace,
1811                          const TSideVector&                 theTgtWires,
1812                          const TSideVector&                 theSrcWires,
1813                          const TAssocTool::TShapeShapeMap&  theShape2ShapeMap,
1814                          TAssocTool::TNodeNodeMap&          theSrc2tgtNodes,
1815                          const bool                         theIs1DComputed)
1816   {
1817     SMESH_Mesh * tgtMesh = theTgtWires[0]->GetMesh();
1818     SMESH_Mesh * srcMesh = theSrcWires[0]->GetMesh();
1819
1820     if ( thePiercingLine.IsNull() )
1821     {
1822       // try to set thePiercingLine by VERTEX association of theShape2ShapeMap
1823
1824       const double tol = 0.1 * theSrcWires[0]->Length() / theSrcWires[0]->NbSegments();
1825
1826       for ( TopExp_Explorer vExp( theTgtFace, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1827       {
1828         const TopoDS_Vertex & tgtV = TopoDS::Vertex( vExp.Current() );
1829         const TopoDS_Vertex & srcV = TopoDS::Vertex( theShape2ShapeMap( tgtV ));
1830         gp_Pnt tgtP = BRep_Tool::Pnt( tgtV );
1831         gp_Pnt srcP = BRep_Tool::Pnt( srcV );
1832         if ( thePiercingLine.IsNull() ) // set thePiercingLine
1833         {
1834           gp_Lin line;
1835           try {
1836             line.SetDirection( gp_Vec( srcP, tgtP ));
1837             line.SetLocation( tgtP );
1838             thePiercingLine = new Geom_Line( line );
1839           }
1840           catch ( ... )
1841           {
1842             continue;
1843           }
1844         }
1845         else // check thePiercingLine
1846         {
1847           thePiercingLine->SetLocation( tgtP );
1848           if ( thePiercingLine->Lin().SquareDistance( srcP ) > tol * tol )
1849             return false;
1850         }
1851       }
1852
1853       for ( TopExp_Explorer eExp( theTgtFace, TopAbs_EDGE ); eExp.More(); eExp.Next() )
1854       {
1855         BRepAdaptor_Curve tgtCurve( TopoDS::Edge( eExp.Current() ));
1856         gp_Pnt tgtP = tgtCurve.Value( 0.5 * ( tgtCurve.FirstParameter() +
1857                                               tgtCurve.LastParameter() ));
1858         thePiercingLine->SetLocation( tgtP );
1859
1860         double f,l;
1861         TopoDS_Edge srcEdge = TopoDS::Edge( theShape2ShapeMap( eExp.Current() ));
1862         Handle(Geom_Curve) srcCurve = BRep_Tool::Curve( srcEdge, f,l );
1863         if ( srcCurve.IsNull() )
1864           continue;
1865         GeomAPI_ExtremaCurveCurve extrema( thePiercingLine, srcCurve,
1866                                            -Precision::Infinite(), Precision::Infinite(), f, l );
1867         if ( !extrema.Extrema().IsDone() ||
1868              extrema.Extrema().IsParallel() ||
1869              extrema.NbExtrema() == 0 ||
1870              extrema.LowerDistance() > tol )
1871           return false;
1872       }
1873     } // if ( thePiercingLine.IsNull() )
1874
1875     SMESHDS_SubMesh* srcSubDS = srcMesh->GetMeshDS()->MeshElements( theSrcFace );
1876
1877     SMESH_MesherHelper* helper = theTgtWires[0]->FaceHelper();
1878     if ( theIs1DComputed )
1879       helper->IsQuadraticSubMesh( theTgtFace );
1880     else
1881       helper->SetIsQuadratic( srcSubDS->GetElements()->next()->IsQuadratic() );
1882     helper->SetElementsOnShape( true );
1883     SMESHDS_Mesh* tgtMeshDS = tgtMesh->GetMeshDS();
1884
1885     Handle(Geom_Surface)             tgtSurface = BRep_Tool::Surface( theTgtFace );
1886     Handle(GeomAdaptor_HSurface) tgtSurfAdaptor = new GeomAdaptor_HSurface( tgtSurface );
1887     Handle(GeomAdaptor_HCurve)    piercingCurve = new GeomAdaptor_HCurve( thePiercingLine );
1888     IntCurveSurface_HInter intersect;
1889
1890     SMESH_MesherHelper* srcHelper = theSrcWires[0]->FaceHelper();
1891
1892     const SMDS_MeshNode* nullNode = 0;
1893     TAssocTool::TNodeNodeMap::iterator srcN_tgtN;
1894     vector< const SMDS_MeshNode* > tgtNodes;
1895
1896     SMDS_ElemIteratorPtr elemIt = srcSubDS->GetElements();
1897     while ( elemIt->more() ) // loop on all mesh faces on srcFace
1898     {
1899       const SMDS_MeshElement* elem = elemIt->next();
1900       const int nbN = elem->NbCornerNodes();
1901       tgtNodes.resize( nbN );
1902       for ( int i = 0; i < nbN; ++i ) // loop on nodes of the source element
1903       {
1904         const SMDS_MeshNode* srcNode = elem->GetNode(i);
1905         srcN_tgtN = theSrc2tgtNodes.insert( make_pair( srcNode, nullNode )).first;
1906         if ( srcN_tgtN->second == nullNode )
1907         {
1908           // create a new node
1909           thePiercingLine->SetLocation( SMESH_NodeXYZ( srcNode ));
1910           intersect.Perform( piercingCurve, tgtSurfAdaptor );
1911           bool pierced = ( intersect.IsDone() && intersect.NbPoints() > 0 );
1912           double U, V;
1913           const SMDS_MeshNode* n = nullNode;
1914           if ( pierced )
1915           {
1916             double W, minW = Precision::Infinite();
1917             gp_Pnt tgtP;
1918             for ( int iInt = 1; iInt <= intersect.NbPoints(); ++iInt )
1919             {
1920               W = intersect.Point( iInt ).W();
1921               if ( 0 < W && W < minW )
1922               {
1923                 U    = intersect.Point( iInt ).U();
1924                 V    = intersect.Point( iInt ).V();
1925                 tgtP = intersect.Point( iInt ).Pnt();
1926                 minW = W;
1927               }
1928             }
1929             n = tgtMeshDS->AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
1930           }
1931
1932           SMDS_TypeOfPosition shapeType = srcNode->GetPosition()->GetTypeOfPosition();
1933           TopoDS_Shape        srcShape;
1934           if ( shapeType != SMDS_TOP_FACE )
1935           {
1936             srcShape = srcHelper->GetSubShapeByNode( srcNode, srcHelper->GetMeshDS() );
1937             if ( !theShape2ShapeMap.IsBound( srcShape, /*isSrc=*/true ))
1938             {
1939               if ( n )  // INTERNAL shape w/o corresponding target shape (3D_mesh_Extrusion_02/E0)
1940                 shapeType = SMDS_TOP_FACE;
1941               else
1942                 return false;
1943             }
1944           }
1945
1946           switch ( shapeType )
1947           {
1948           case SMDS_TOP_FACE: {
1949             if ( !n )
1950               return false;
1951             tgtMeshDS->SetNodeOnFace( n, helper->GetSubShapeID(), U, V );
1952             break;
1953           }
1954           case SMDS_TOP_EDGE: {
1955             TopoDS_Edge  tgtEdge = TopoDS::Edge( theShape2ShapeMap( srcShape, /*isSrc=*/true ));
1956             if ( n )
1957             {
1958               U = Precision::Infinite();
1959               helper->CheckNodeU( tgtEdge, n, U, Precision::PConfusion());
1960             }
1961             else
1962             {
1963               Handle(Geom_Curve) tgtCurve = BRep_Tool::Curve( tgtEdge, U,V );
1964               if ( tgtCurve.IsNull() )
1965                 return false;
1966               GeomAPI_ExtremaCurveCurve extrema( thePiercingLine, tgtCurve );
1967               if ( !extrema.Extrema().IsDone() ||
1968                    extrema.Extrema().IsParallel() ||
1969                    extrema.NbExtrema() == 0 )
1970                 return false;
1971               gp_Pnt pOnLine, pOnEdge;
1972               extrema.NearestPoints( pOnLine, pOnEdge );
1973               extrema.LowerDistanceParameters( V, U );
1974               n = tgtMeshDS->AddNode( pOnEdge.X(), pOnEdge.Y(), pOnEdge.Z() );
1975             }
1976             tgtMeshDS->SetNodeOnEdge( n, tgtEdge, U );
1977             break;
1978           }
1979           case SMDS_TOP_VERTEX: {
1980             TopoDS_Shape tgtV = theShape2ShapeMap( srcShape, /*isSrc=*/true );
1981             if ( !n )
1982             {
1983               gp_Pnt tgtP = BRep_Tool::Pnt( TopoDS::Vertex( tgtV ));
1984               n = tgtMeshDS->AddNode( tgtP.X(), tgtP.Y(), tgtP.Z() );
1985             }
1986             tgtMeshDS->SetNodeOnVertex( n, TopoDS::Vertex( tgtV ));
1987             break;
1988           }
1989           default:;
1990           }
1991           srcN_tgtN->second = n;
1992         }
1993         tgtNodes[i] = srcN_tgtN->second;
1994       }
1995       // create a new face (with reversed orientation)
1996       switch ( nbN )
1997       {
1998       case 3: helper->AddFace(tgtNodes[0], tgtNodes[2], tgtNodes[1]); break;
1999       case 4: helper->AddFace(tgtNodes[0], tgtNodes[3], tgtNodes[2], tgtNodes[1]); break;
2000       }
2001     }  // loop on all mesh faces on srcFace
2002
2003     return true;
2004
2005   } // projectByPiercing()
2006
2007
2008
2009 } // namespace
2010
2011
2012 //=======================================================================
2013 //function : Compute
2014 //purpose  :
2015 //=======================================================================
2016
2017 bool StdMeshers_Projection_2D::Compute(SMESH_Mesh& theMesh, const TopoDS_Shape& theShape)
2018 {
2019   _src2tgtNodes.clear();
2020
2021   if ( !_sourceHypo )
2022     return false;
2023
2024   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
2025   SMESH_Mesh * tgtMesh = & theMesh;
2026   if ( !srcMesh )
2027     srcMesh = tgtMesh;
2028
2029   SMESHDS_Mesh * meshDS = theMesh.GetMeshDS();
2030   SMESH_MesherHelper helper( theMesh );
2031
2032   // ---------------------------
2033   // Make sub-shapes association
2034   // ---------------------------
2035
2036   TopoDS_Face   tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
2037   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
2038
2039   helper.SetSubShape( tgtFace );
2040
2041   TAssocTool::TShapeShapeMap shape2ShapeMap;
2042   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
2043   if ( shape2ShapeMap.IsEmpty() )
2044     initAssoc4Quad2Closed( tgtFace, helper, srcShape, srcMesh, shape2ShapeMap );
2045
2046   Handle(Geom_Line) piercingLine;
2047   bool piercingTried = false;
2048
2049   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
2050                                              shape2ShapeMap)  ||
2051        !shape2ShapeMap.IsBound( tgtFace ))
2052   {
2053     piercingTried = true;
2054     if ( !findSubShapeAssociationByPiercing( tgtFace, tgtMesh, srcShape, srcMesh,
2055                                              shape2ShapeMap, piercingLine ))
2056     {
2057       if ( srcShape.ShapeType() == TopAbs_FACE )
2058       {
2059         int nbE1 = helper.Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
2060         int nbE2 = helper.Count( srcShape, TopAbs_EDGE, /*ignoreSame=*/true );
2061         if ( nbE1 != nbE2 )
2062           return error(COMPERR_BAD_SHAPE,
2063                        SMESH_Comment("Different number of edges in source and target faces: ")
2064                        << nbE2 << " and " << nbE1 );
2065       }
2066       return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
2067     }
2068   }
2069   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
2070
2071   // ----------------------------------------------
2072   // Assure that mesh on a source Face is computed
2073   // ----------------------------------------------
2074
2075   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
2076   SMESH_subMesh* tgtSubMesh = tgtMesh->GetSubMesh( tgtFace );
2077
2078   string srcMeshError;
2079   if ( tgtMesh == srcMesh ) {
2080     if ( !TAssocTool::MakeComputed( srcSubMesh ))
2081       srcMeshError = TAssocTool::SourceNotComputedError( srcSubMesh, this );
2082   }
2083   else {
2084     if ( !srcSubMesh->IsMeshComputed() )
2085       srcMeshError = TAssocTool::SourceNotComputedError();
2086   }
2087   if ( !srcMeshError.empty() )
2088     return error(COMPERR_BAD_INPUT_MESH, srcMeshError );
2089
2090   // ===========
2091   // Projection
2092   // ===========
2093
2094   // get ordered src and tgt EDGEs
2095   TSideVector srcWires, tgtWires;
2096   bool is1DComputed = false; // if any tgt EDGE is meshed
2097   TError err = getWires( tgtFace, srcFace, tgtMesh, srcMesh, &helper,
2098                          shape2ShapeMap, srcWires, tgtWires, _src2tgtNodes, is1DComputed );
2099   if ( err && !err->IsOK() )
2100     return error( err );
2101
2102   bool projDone = false;
2103
2104   if ( !projDone && !piercingLine.IsNull() )
2105   {
2106     // project by piercing tgtFace by lines parallel to piercingLine
2107     projDone = projectByPiercing( piercingLine, tgtFace, srcFace, tgtWires, srcWires,
2108                                   shape2ShapeMap, _src2tgtNodes, is1DComputed );
2109     piercingTried = true;
2110   }
2111   if ( !projDone )
2112   {
2113     // try to project from the same face with different location
2114     projDone = projectPartner( tgtFace, srcFace, tgtWires, srcWires,
2115                                shape2ShapeMap, _src2tgtNodes, is1DComputed );
2116   }
2117   if ( !projDone )
2118   {
2119     // projection in case if the faces are similar in 2D space
2120     projDone = projectBy2DSimilarity( tgtFace, srcFace, tgtWires, srcWires,
2121                                       shape2ShapeMap, _src2tgtNodes, is1DComputed );
2122   }
2123   if ( !projDone )
2124   {
2125     // projection in case of quadrilateral faces
2126     projDone = projectQuads( tgtFace, srcFace, tgtWires, srcWires,
2127                              shape2ShapeMap, _src2tgtNodes, is1DComputed);
2128   }
2129   if ( !projDone && !piercingTried )
2130   {
2131     // project by piercing tgtFace by lines parallel to piercingLine
2132     projDone = projectByPiercing( piercingLine, tgtFace, srcFace, tgtWires, srcWires,
2133                                   shape2ShapeMap, _src2tgtNodes, is1DComputed );
2134   }
2135
2136   // it will remove mesh built on edges and vertices in failure case
2137   MeshCleaner cleaner( tgtSubMesh );
2138
2139   if ( !projDone )
2140   {
2141     _src2tgtNodes.clear();
2142     // --------------------
2143     // Prepare to mapping
2144     // --------------------
2145
2146     // Check if node projection to a face is needed
2147     Bnd_B2d uvBox;
2148     SMDS_ElemIteratorPtr faceIt = srcSubMesh->GetSubMeshDS()->GetElements();
2149     set< const SMDS_MeshNode* > faceNodes;
2150     for ( ; faceNodes.size() < 3 && faceIt->more();  ) {
2151       const SMDS_MeshElement* face = faceIt->next();
2152       SMDS_ElemIteratorPtr nodeIt = face->nodesIterator();
2153       while ( nodeIt->more() ) {
2154         const SMDS_MeshNode* node = static_cast<const SMDS_MeshNode*>( nodeIt->next() );
2155         if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE &&
2156              faceNodes.insert( node ).second )
2157           uvBox.Add( helper.GetNodeUV( srcFace, node ));
2158       }
2159     }
2160     bool toProjectNodes = false;
2161     if ( faceNodes.size() == 1 )
2162       toProjectNodes = ( uvBox.IsVoid() || uvBox.CornerMin().IsEqual( gp_XY(0,0), 1e-12 ));
2163     else if ( faceNodes.size() > 1 )
2164       toProjectNodes = ( uvBox.IsVoid() || uvBox.SquareExtent() < DBL_MIN );
2165
2166     // Find the corresponding source and target vertex
2167     // and <theReverse> flag needed to call mapper.Apply()
2168
2169     TopoDS_Vertex srcV1, tgtV1;
2170     bool reverse = false;
2171
2172     TopExp_Explorer vSrcExp( srcFace, TopAbs_VERTEX );
2173     srcV1 = TopoDS::Vertex( vSrcExp.Current() );
2174     tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
2175
2176     list< TopoDS_Edge > tgtEdges, srcEdges;
2177     list< int > nbEdgesInWires;
2178     SMESH_Block::GetOrderedEdges( tgtFace, tgtEdges, nbEdgesInWires, tgtV1 );
2179     SMESH_Block::GetOrderedEdges( srcFace, srcEdges, nbEdgesInWires, srcV1 );
2180
2181     if ( nbEdgesInWires.front() > 1 ) // possible to find out orientation
2182     {
2183       TopoDS_Edge srcE1 = srcEdges.front(), tgtE1 = tgtEdges.front();
2184       TopoDS_Shape srcE1bis = shape2ShapeMap( tgtE1 );
2185       reverse = ( ! srcE1.IsSame( srcE1bis ));
2186       if ( ( reverse || srcE1.Orientation() != srcE1bis.Orientation() ) &&
2187            nbEdgesInWires.front() > 2 &&
2188            helper.IsRealSeam( tgtEdges.front() ))
2189       {
2190         if ( srcE1.Orientation() != srcE1bis.Orientation() )
2191           reverse = true;
2192         // projection to a face with seam EDGE; pb is that GetOrderedEdges()
2193         // always puts a seam EDGE first (if possible) and as a result
2194         // we can't use only theReverse flag to correctly associate source
2195         // and target faces in the mapper. Thus we select srcV1 so that
2196         // GetOrderedEdges() to return EDGEs in a needed order
2197         TopoDS_Face tgtFaceBis = tgtFace;
2198         TopTools_MapOfShape checkedVMap( tgtEdges.size() );
2199         checkedVMap.Add ( srcV1 );
2200         for ( vSrcExp.Next(); vSrcExp.More(); )
2201         {
2202           tgtFaceBis.Reverse();
2203           tgtEdges.clear();
2204           SMESH_Block::GetOrderedEdges( tgtFaceBis, tgtEdges, nbEdgesInWires, tgtV1 );
2205           bool ok = true;
2206           list< TopoDS_Edge >::iterator edgeS = srcEdges.begin(), edgeT = tgtEdges.begin();
2207           for ( ; edgeS != srcEdges.end() && ok ; ++edgeS, ++edgeT )
2208             ok = edgeT->IsSame( shape2ShapeMap( *edgeS, /*isSrc=*/true ));
2209           if ( ok )
2210             break; // FOUND!
2211
2212           reverse = !reverse;
2213           if ( reverse )
2214           {
2215             vSrcExp.Next();
2216             while ( vSrcExp.More() && !checkedVMap.Add( vSrcExp.Current() ))
2217               vSrcExp.Next();
2218           }
2219           else
2220           {
2221             srcV1 = TopoDS::Vertex( vSrcExp.Current() );
2222             tgtV1 = TopoDS::Vertex( shape2ShapeMap( srcV1, /*isSrc=*/true ));
2223             srcEdges.clear();
2224             SMESH_Block::GetOrderedEdges( srcFace, srcEdges, nbEdgesInWires, srcV1 );
2225           }
2226         }
2227       }
2228       // for the case: project to a closed face from a non-closed face w/o vertex assoc;
2229       // avoid projecting to a seam from two EDGEs with different nb nodes on them
2230       // ( test mesh_Projection_2D_01/B1 )
2231       if ( !_sourceHypo->HasVertexAssociation() &&
2232            nbEdgesInWires.front() > 2 &&
2233            helper.IsRealSeam( tgtEdges.front() ))
2234       {
2235         TopoDS_Shape srcEdge1 = shape2ShapeMap( tgtEdges.front() );
2236         list< TopoDS_Edge >::iterator srcEdge2 =
2237           std::find( srcEdges.begin(), srcEdges.end(), srcEdge1);
2238         list< TopoDS_Edge >::iterator srcEdge3 =
2239           std::find( srcEdges.begin(), srcEdges.end(), srcEdge1.Reversed());
2240         if ( srcEdge2 == srcEdges.end() || srcEdge3 == srcEdges.end() ) // srcEdge1 is not a seam
2241         {
2242           // find srcEdge2 which also will be projected to tgtEdges.front()
2243           for ( srcEdge2 = srcEdges.begin(); srcEdge2 != srcEdges.end(); ++srcEdge2 )
2244             if ( !srcEdge1.IsSame( *srcEdge2 ) &&
2245                  tgtEdges.front().IsSame( shape2ShapeMap( *srcEdge2, /*isSrc=*/true )))
2246               break;
2247           // compare nb nodes on srcEdge1 and srcEdge2
2248           if ( srcEdge2 != srcEdges.end() )
2249           {
2250             smIdType nbN1 = 0, nbN2 = 0;
2251             if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( srcEdge1 ))
2252               nbN1 = sm->NbNodes();
2253             if ( SMESHDS_SubMesh* sm = srcMesh->GetMeshDS()->MeshElements( *srcEdge2 ))
2254               nbN2 = sm->NbNodes();
2255             if ( nbN1 != nbN2 )
2256               srcV1 = helper.IthVertex( 1, srcEdges.front() );
2257           }
2258         }
2259       }
2260     }
2261     else if ( nbEdgesInWires.front() == 1 ) // a sole edge in a wire
2262     {
2263       TopoDS_Edge srcE1 = srcEdges.front(), tgtE1 = tgtEdges.front();
2264       for ( size_t iW = 0; iW < srcWires.size(); ++iW )
2265       {
2266         StdMeshers_FaceSidePtr srcWire = srcWires[iW];
2267         for ( int iE = 0; iE < srcWire->NbEdges(); ++iE )
2268           if ( srcE1.IsSame( srcWire->Edge( iE )))
2269           {
2270             reverse = ( tgtE1.Orientation() != tgtWires[iW]->Edge( iE ).Orientation() );
2271             break;
2272           }
2273       }
2274     }
2275     else
2276     {
2277       RETURN_BAD_RESULT("Bad result from SMESH_Block::GetOrderedEdges()");
2278     }
2279
2280     // Load pattern from the source face
2281     SMESH_Pattern mapper;
2282     mapper.Load( srcMesh, srcFace, toProjectNodes, srcV1, /*keepNodes=*/true );
2283     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
2284       return error(COMPERR_BAD_INPUT_MESH,"Can't load mesh pattern from the source face");
2285
2286     // --------------------
2287     // Perform 2D mapping
2288     // --------------------
2289
2290     // Compute mesh on a target face
2291
2292     mapper.Apply( tgtFace, tgtV1, reverse );
2293     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK ) {
2294       // std::ofstream file("/tmp/Pattern.smp" );
2295       // mapper.Save( file );
2296       return error("Can't apply source mesh pattern to the face");
2297     }
2298
2299     // Create the mesh
2300
2301     const bool toCreatePolygons = false, toCreatePolyedrs = false;
2302     mapper.MakeMesh( tgtMesh, toCreatePolygons, toCreatePolyedrs );
2303     if ( mapper.GetErrorCode() != SMESH_Pattern::ERR_OK )
2304       return error("Can't make mesh by source mesh pattern");
2305
2306     // fill _src2tgtNodes
2307     std::vector< const SMDS_MeshNode* > *srcNodes, *tgtNodes;
2308     mapper.GetInOutNodes( srcNodes, tgtNodes );
2309     size_t nbN = std::min( srcNodes->size(), tgtNodes->size() );
2310     for ( size_t i = 0; i < nbN; ++i )
2311       if ( (*srcNodes)[i] && (*tgtNodes)[i] )
2312         _src2tgtNodes.insert( make_pair( (*srcNodes)[i], (*tgtNodes)[i] ));
2313
2314
2315   } // end of projection using Pattern mapping
2316
2317   {
2318     // -------------------------------------------------------------------------
2319     // mapper doesn't take care of nodes already existing on edges and vertices,
2320     // so we must merge nodes created by it with existing ones
2321     // -------------------------------------------------------------------------
2322
2323     SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2324
2325     // Make groups of nodes to merge
2326
2327     // loop on EDGE and VERTEX sub-meshes of a target FACE
2328     SMESH_subMeshIteratorPtr smIt = tgtSubMesh->getDependsOnIterator(/*includeSelf=*/false,
2329                                                                      /*complexShapeFirst=*/false);
2330     while ( smIt->more() )
2331     {
2332       SMESH_subMesh*     sm = smIt->next();
2333       SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2334       if ( !smDS || smDS->NbNodes() == 0 )
2335         continue;
2336       //if ( !is1DComputed && sm->GetSubShape().ShapeType() == TopAbs_EDGE )
2337       //  break;
2338
2339       if ( helper.IsDegenShape( sm->GetId() ) ) // to merge all nodes on degenerated
2340       {
2341         if ( sm->GetSubShape().ShapeType() == TopAbs_EDGE )
2342         {
2343           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
2344           SMESH_subMeshIteratorPtr smDegenIt
2345             = sm->getDependsOnIterator(/*includeSelf=*/true,/*complexShapeFirst=*/false);
2346           while ( smDegenIt->more() )
2347             if (( smDS = smDegenIt->next()->GetSubMeshDS() ))
2348             {
2349               SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2350               while ( nIt->more() )
2351                 groupsOfNodes.back().push_back( nIt->next() );
2352             }
2353         }
2354         continue; // do not treat sm of degen VERTEX
2355       }
2356
2357       // Sort new and old nodes of a sub-mesh separately
2358
2359       bool isSeam = helper.IsRealSeam( sm->GetId() );
2360
2361       enum { NEW_NODES = 0, OLD_NODES };
2362       map< double, const SMDS_MeshNode* > u2nodesMaps[2], u2nodesOnSeam;
2363       map< double, const SMDS_MeshNode* >::iterator u_oldNode, u_newNode, u_newOnSeam, newEnd;
2364       set< const SMDS_MeshNode* > seamNodes;
2365
2366       // mapper changed, no more "mapper puts on a seam edge nodes from 2 edges"
2367       if ( isSeam && ! getBoundaryNodes ( sm, tgtFace, u2nodesOnSeam, seamNodes ))
2368       {
2369         //RETURN_BAD_RESULT("getBoundaryNodes() failed");
2370       }
2371
2372       SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2373       while ( nIt->more() )
2374       {
2375         const SMDS_MeshNode* node = nIt->next();
2376         bool isOld = isOldNode( node );
2377
2378         if ( !isOld && isSeam ) { // new node on a seam edge
2379           if ( seamNodes.count( node ) )
2380             continue; // node is already in the map
2381         }
2382
2383         // sort nodes on edges by their position
2384         map< double, const SMDS_MeshNode* > & pos2nodes = u2nodesMaps[isOld ? OLD_NODES : NEW_NODES];
2385         switch ( node->GetPosition()->GetTypeOfPosition() )
2386         {
2387         case  SMDS_TOP_VERTEX: {
2388           if ( !is1DComputed && !pos2nodes.empty() )
2389             u2nodesMaps[isOld ? NEW_NODES : OLD_NODES].insert( make_pair( 0, node ));
2390           else
2391             pos2nodes.insert( make_pair( 0, node ));
2392           break;
2393         }
2394         case  SMDS_TOP_EDGE:   {
2395           SMDS_EdgePositionPtr pos = node->GetPosition();
2396           pos2nodes.insert( make_pair( pos->GetUParameter(), node ));
2397           break;
2398         }
2399         default:
2400           RETURN_BAD_RESULT("Wrong node position type: "<<
2401                             node->GetPosition()->GetTypeOfPosition());
2402         }
2403       }
2404       const bool mergeNewToOld =
2405         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesMaps[ OLD_NODES ].size() );
2406       const bool mergeSeamToNew =
2407         ( u2nodesMaps[ NEW_NODES ].size() == u2nodesOnSeam.size() );
2408
2409       if ( !mergeNewToOld )
2410         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
2411              u2nodesMaps[ OLD_NODES ].size() > 0 )
2412         {
2413           u_oldNode = u2nodesMaps[ OLD_NODES ].begin();
2414           newEnd    = u2nodesMaps[ OLD_NODES ].end();
2415           for ( ; u_oldNode != newEnd; ++u_oldNode )
2416             SMESH_Algo::addBadInputElement( u_oldNode->second );
2417           return error( COMPERR_BAD_INPUT_MESH,
2418                         SMESH_Comment( "Existing mesh mismatches the projected 2D mesh on " )
2419                         << ( sm->GetSubShape().ShapeType() == TopAbs_EDGE ? "edge" : "vertex" )
2420                         << " #" << sm->GetId() );
2421         }
2422       if ( isSeam && !mergeSeamToNew ) {
2423         const TopoDS_Shape& seam = sm->GetSubShape();
2424         if ( u2nodesMaps[ NEW_NODES ].size() > 0 &&
2425              u2nodesOnSeam.size()            > 0 &&
2426              seam.ShapeType() == TopAbs_EDGE )
2427         {
2428           int nbE1 = helper.Count( tgtFace, TopAbs_EDGE, /*ignoreSame=*/true );
2429           int nbE2 = helper.Count( srcFace, TopAbs_EDGE, /*ignoreSame=*/true );
2430           if ( nbE1 != nbE2 ) // 2 EDGEs are mapped to a seam EDGE
2431           {
2432             // find the 2 EDGEs of srcFace
2433             TopTools_DataMapIteratorOfDataMapOfShapeShape src2tgtIt( shape2ShapeMap._map2to1 );
2434             for ( ; src2tgtIt.More(); src2tgtIt.Next() )
2435               if ( seam.IsSame( src2tgtIt.Value() ))
2436                 SMESH_Algo::addBadInputElements
2437                   ( srcMesh->GetMeshDS()->MeshElements( src2tgtIt.Key() ));
2438             return error( COMPERR_BAD_INPUT_MESH,
2439                           "Different number of nodes on two edges projected to a seam edge" );
2440           }
2441         }
2442       }
2443
2444       // Make groups of nodes to merge
2445
2446       u_oldNode = u2nodesMaps[ OLD_NODES ].begin();
2447       u_newNode = u2nodesMaps[ NEW_NODES ].begin();
2448       newEnd    = u2nodesMaps[ NEW_NODES ].end();
2449       u_newOnSeam = u2nodesOnSeam.begin();
2450       if ( mergeNewToOld )
2451         for ( ; u_newNode != newEnd; ++u_newNode, ++u_oldNode )
2452         {
2453           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
2454           groupsOfNodes.back().push_back( u_oldNode->second );
2455           groupsOfNodes.back().push_back( u_newNode->second );
2456           if ( mergeSeamToNew )
2457             groupsOfNodes.back().push_back( (u_newOnSeam++)->second );
2458         }
2459       else if ( mergeSeamToNew )
2460         for ( ; u_newNode != newEnd; ++u_newNode, ++u_newOnSeam )
2461         {
2462           groupsOfNodes.push_back( list< const SMDS_MeshNode* >() );
2463           groupsOfNodes.back().push_back( u_newNode->second );
2464           groupsOfNodes.back().push_back( u_newOnSeam->second );
2465         }
2466
2467     } // loop on EDGE and VERTEX submeshes of a target FACE
2468
2469     // Merge
2470
2471     SMESH_MeshEditor editor( tgtMesh );
2472     smIdType nbFaceBeforeMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
2473     editor.MergeNodes( groupsOfNodes );
2474     smIdType nbFaceAtferMerge = tgtSubMesh->GetSubMeshDS()->NbElements();
2475     if ( nbFaceBeforeMerge != nbFaceAtferMerge && !helper.HasDegeneratedEdges() )
2476       return error(COMPERR_BAD_INPUT_MESH, "Probably invalid node parameters on geom faces");
2477
2478     // ----------------------------------------------------------------
2479     // The mapper can't create quadratic elements, so convert if needed
2480     // ----------------------------------------------------------------
2481
2482     SMDS_ElemIteratorPtr faceIt;
2483     faceIt         = srcSubMesh->GetSubMeshDS()->GetElements();
2484     bool srcIsQuad = faceIt->next()->IsQuadratic();
2485     faceIt         = tgtSubMesh->GetSubMeshDS()->GetElements();
2486     bool tgtIsQuad = faceIt->next()->IsQuadratic();
2487     if ( srcIsQuad && !tgtIsQuad )
2488     {
2489       TIDSortedElemSet tgtFaces;
2490       faceIt = tgtSubMesh->GetSubMeshDS()->GetElements();
2491       while ( faceIt->more() )
2492         tgtFaces.insert( tgtFaces.end(), faceIt->next() );
2493
2494       editor.ConvertToQuadratic(/*theForce3d=*/false, tgtFaces, false);
2495     }
2496   } // end of coincident nodes and quadratic elements treatment
2497
2498
2499   if ( !projDone || is1DComputed )
2500     // ----------------------------------------------------------------
2501     // The mapper can create distorted faces by placing nodes out of the FACE
2502     // boundary, also bad faces can be created if EDGEs already discretized
2503     // --> fix bad faces by smoothing
2504     // ----------------------------------------------------------------
2505     if ( helper.IsDistorted2D( tgtSubMesh, /*checkUV=*/false, &helper ))
2506     {
2507       TAssocTool::Morph morph( srcWires );
2508       morph.Perform( helper, tgtWires, helper.GetSurface( tgtFace ),
2509                      _src2tgtNodes, /*moveAll=*/true );
2510 #ifdef _DEBUG_
2511       cout << "StdMeshers_Projection_2D: Projection mesh IsDistorted2D() ==> do morph" << endl;
2512 #endif
2513
2514       if ( !fixDistortedFaces( helper, tgtWires )) // smooth and check
2515         return error("Invalid mesh generated");
2516     }
2517   // ---------------------------
2518   // Check elements orientation
2519   // ---------------------------
2520
2521   TopoDS_Face face = TopoDS::Face( theShape );
2522   if ( !theMesh.IsMainShape( tgtFace ))
2523   {
2524     // find the main shape
2525     TopoDS_Shape mainShape = meshDS->ShapeToMesh();
2526     switch ( mainShape.ShapeType() ) {
2527     case TopAbs_SHELL:
2528     case TopAbs_SOLID: break;
2529     default:
2530       TopTools_ListIteratorOfListOfShape ancestIt = theMesh.GetAncestors( face );
2531       for ( ; ancestIt.More(); ancestIt.Next() ) {
2532         TopAbs_ShapeEnum type = ancestIt.Value().ShapeType();
2533         if ( type == TopAbs_SOLID ) {
2534           mainShape = ancestIt.Value();
2535           break;
2536         } else if ( type == TopAbs_SHELL ) {
2537           mainShape = ancestIt.Value();
2538         }
2539       }
2540     }
2541     // find tgtFace in the main solid or shell to know it's true orientation.
2542     TopExp_Explorer exp( mainShape, TopAbs_FACE );
2543     for ( ; exp.More(); exp.Next() ) {
2544       if ( tgtFace.IsSame( exp.Current() )) {
2545         face = TopoDS::Face( exp.Current() );
2546         break;
2547       }
2548     }
2549   }
2550   // Fix orientation
2551   if ( helper.IsReversedSubMesh( face ))
2552   {
2553     SMESH_MeshEditor editor( tgtMesh );
2554     SMDS_ElemIteratorPtr eIt = meshDS->MeshElements( face )->GetElements();
2555     while ( eIt->more() ) {
2556       const SMDS_MeshElement* e = eIt->next();
2557       if ( e->GetType() == SMDSAbs_Face && !editor.Reorient( e ))
2558         RETURN_BAD_RESULT("Pb of SMESH_MeshEditor::Reorient()");
2559     }
2560   }
2561
2562   cleaner.Release(); // not to remove mesh
2563
2564   return true;
2565 }
2566
2567
2568 //=======================================================================
2569 //function : Evaluate
2570 //purpose  :
2571 //=======================================================================
2572
2573 bool StdMeshers_Projection_2D::Evaluate(SMESH_Mesh&         theMesh,
2574                                         const TopoDS_Shape& theShape,
2575                                         MapShapeNbElems&    aResMap)
2576 {
2577   if ( !_sourceHypo )
2578     return false;
2579
2580   SMESH_Mesh * srcMesh = _sourceHypo->GetSourceMesh();
2581   SMESH_Mesh * tgtMesh = & theMesh;
2582   if ( !srcMesh )
2583     srcMesh = tgtMesh;
2584
2585   // ---------------------------
2586   // Make sub-shapes association
2587   // ---------------------------
2588
2589   TopoDS_Face tgtFace = TopoDS::Face( theShape.Oriented(TopAbs_FORWARD));
2590   TopoDS_Shape srcShape = _sourceHypo->GetSourceFace().Oriented(TopAbs_FORWARD);
2591
2592   TAssocTool::TShapeShapeMap shape2ShapeMap;
2593   TAssocTool::InitVertexAssociation( _sourceHypo, shape2ShapeMap );
2594   if ( !TAssocTool::FindSubShapeAssociation( tgtFace, tgtMesh, srcShape, srcMesh,
2595                                              shape2ShapeMap)  ||
2596        !shape2ShapeMap.IsBound( tgtFace ))
2597     return error(COMPERR_BAD_SHAPE,"Topology of source and target faces seems different" );
2598
2599   TopoDS_Face srcFace = TopoDS::Face( shape2ShapeMap( tgtFace ).Oriented(TopAbs_FORWARD));
2600
2601   // -------------------------------------------------------
2602   // Assure that mesh on a source Face is computed/evaluated
2603   // -------------------------------------------------------
2604
2605   std::vector<smIdType> aVec;
2606
2607   SMESH_subMesh* srcSubMesh = srcMesh->GetSubMesh( srcFace );
2608   if ( srcSubMesh->IsMeshComputed() )
2609   {
2610     aVec.resize( SMDSEntity_Last, 0 );
2611     aVec[SMDSEntity_Node] = srcSubMesh->GetSubMeshDS()->NbNodes();
2612
2613     SMDS_ElemIteratorPtr elemIt = srcSubMesh->GetSubMeshDS()->GetElements();
2614     while ( elemIt->more() )
2615       aVec[ elemIt->next()->GetEntityType() ]++;
2616   }
2617   else
2618   {
2619     MapShapeNbElems  tmpResMap;
2620     MapShapeNbElems& srcResMap = (srcMesh == tgtMesh) ? aResMap : tmpResMap;
2621     if ( !_gen->Evaluate( *srcMesh, srcShape, srcResMap ))
2622       return error(COMPERR_BAD_INPUT_MESH,"Source mesh not evaluatable");
2623     aVec = srcResMap[ srcSubMesh ];
2624     if ( aVec.empty() )
2625       return error(COMPERR_BAD_INPUT_MESH,"Source mesh is wrongly evaluated");
2626   }
2627
2628   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
2629   aResMap.insert(std::make_pair(sm,aVec));
2630
2631   return true;
2632 }
2633
2634
2635 //=============================================================================
2636 /*!
2637  * \brief Sets a default event listener to submesh of the source face
2638   * \param subMesh - submesh where algo is set
2639  *
2640  * This method is called when a submesh gets HYP_OK algo_state.
2641  * After being set, event listener is notified on each event of a submesh.
2642  * Arranges that CLEAN event is translated from source submesh to
2643  * the submesh
2644  */
2645 //=============================================================================
2646
2647 void StdMeshers_Projection_2D::SetEventListener(SMESH_subMesh* subMesh)
2648 {
2649   TAssocTool::SetEventListener( subMesh,
2650                                 _sourceHypo->GetSourceFace(),
2651                                 _sourceHypo->GetSourceMesh() );
2652 }