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