Salome HOME
23092: EDF 10836 SMESH: UseExisting2DElements fails when geometry contains more than...
[modules/smesh.git] / src / StdMeshers / StdMeshers_Import_1D2D.cxx
1 // Copyright (C) 2007-2015  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 //  SMESH SMESH : implementaion of SMESH idl descriptions
24 //  File   : StdMeshers_Import_1D2D.cxx
25 //  Module : SMESH
26 //
27 #include "StdMeshers_Import_1D2D.hxx"
28
29 #include "StdMeshers_Import_1D.hxx"
30 #include "StdMeshers_ImportSource.hxx"
31
32 #include "SMDS_MeshElement.hxx"
33 #include "SMDS_MeshNode.hxx"
34 #include "SMESHDS_Group.hxx"
35 #include "SMESHDS_Mesh.hxx"
36 #include "SMESH_Comment.hxx"
37 #include "SMESH_Gen.hxx"
38 #include "SMESH_Group.hxx"
39 #include "SMESH_Mesh.hxx"
40 #include "SMESH_MesherHelper.hxx"
41 #include "SMESH_OctreeNode.hxx"
42 #include "SMESH_subMesh.hxx"
43
44 #include "Utils_SALOME_Exception.hxx"
45 #include "utilities.h"
46
47 #include <BRepBndLib.hxx>
48 #include <BRepClass_FaceClassifier.hxx>
49 #include <BRepTools.hxx>
50 #include <BRep_Builder.hxx>
51 #include <BRep_Tool.hxx>
52 #include <Bnd_B2d.hxx>
53 #include <Bnd_Box.hxx>
54 #include <GeomAPI_ProjectPointOnSurf.hxx>
55 #include <GeomAdaptor_Surface.hxx>
56 #include <Precision.hxx>
57 #include <TopExp.hxx>
58 #include <TopExp_Explorer.hxx>
59 #include <TopoDS.hxx>
60 #include <TopoDS_Compound.hxx>
61 #include <TopoDS_Edge.hxx>
62 #include <TopoDS_Vertex.hxx>
63
64 #include <numeric>
65
66 using namespace std;
67
68 namespace
69 {
70   double getMinElemSize2( const SMESHDS_GroupBase* srcGroup )
71   {
72     double minSize2 = 1e100;
73     SMDS_ElemIteratorPtr srcElems = srcGroup->GetElements();
74     while ( srcElems->more() ) // loop on group contents
75     {
76       const SMDS_MeshElement* face = srcElems->next();
77       int nbN = face->NbCornerNodes();
78
79       SMESH_TNodeXYZ prevN( face->GetNode( nbN-1 ));
80       for ( int i = 0; i < nbN; ++i )
81       {
82         SMESH_TNodeXYZ n( face->GetNode( i ) );
83         double size2 = ( n - prevN ).SquareModulus();
84         minSize2 = std::min( minSize2, size2 );
85         prevN = n;
86       }
87     }
88     return minSize2;
89   }
90 }
91
92 //=============================================================================
93 /*!
94  * Creates StdMeshers_Import_1D2D
95  */
96 //=============================================================================
97
98 StdMeshers_Import_1D2D::StdMeshers_Import_1D2D(int hypId, int studyId, SMESH_Gen * gen)
99   :SMESH_2D_Algo(hypId, studyId, gen), _sourceHyp(0)
100 {
101   MESSAGE("StdMeshers_Import_1D2D::StdMeshers_Import_1D2D");
102   _name = "Import_1D2D";
103   _shapeType = (1 << TopAbs_FACE);
104
105   _compatibleHypothesis.push_back("ImportSource2D");
106   _requireDiscreteBoundary = false;
107   _supportSubmeshes = true;
108 }
109
110 //=============================================================================
111 /*!
112  * Check presence of a hypothesis
113  */
114 //=============================================================================
115
116 bool StdMeshers_Import_1D2D::CheckHypothesis
117                          (SMESH_Mesh&                          aMesh,
118                           const TopoDS_Shape&                  aShape,
119                           SMESH_Hypothesis::Hypothesis_Status& aStatus)
120 {
121   _sourceHyp = 0;
122
123   const list <const SMESHDS_Hypothesis * >&hyps = GetUsedHypothesis(aMesh, aShape);
124   if ( hyps.size() == 0 )
125   {
126     aStatus = SMESH_Hypothesis::HYP_MISSING;
127     return false;  // can't work with no hypothesis
128   }
129
130   if ( hyps.size() > 1 )
131   {
132     aStatus = SMESH_Hypothesis::HYP_ALREADY_EXIST;
133     return false;
134   }
135
136   const SMESHDS_Hypothesis *theHyp = hyps.front();
137
138   string hypName = theHyp->GetName();
139
140   if (hypName == _compatibleHypothesis.front())
141   {
142     _sourceHyp = (StdMeshers_ImportSource1D *)theHyp;
143     aStatus = SMESH_Hypothesis::HYP_OK;
144     return true;
145   }
146
147   aStatus = SMESH_Hypothesis::HYP_INCOMPATIBLE;
148   return true;
149 }
150
151 namespace
152 {
153   /*!
154    * \brief OrientedLink additionally storing a medium node
155    */
156   struct TLink : public SMESH_OrientedLink
157   {
158     const SMDS_MeshNode* _medium;
159     TLink( const SMDS_MeshNode* n1,
160            const SMDS_MeshNode* n2,
161            const SMDS_MeshNode* medium=0)
162       : SMESH_OrientedLink( n1,n2 ), _medium( medium ) {}
163   };
164 }
165
166 //=============================================================================
167 /*!
168  * Import elements from the other mesh 
169  */
170 //=============================================================================
171
172 bool StdMeshers_Import_1D2D::Compute(SMESH_Mesh & theMesh, const TopoDS_Shape & theShape)
173 {
174   if ( !_sourceHyp ) return false;
175
176   const vector<SMESH_Group*>& srcGroups = _sourceHyp->GetGroups(/*loaded=*/true);
177   if ( srcGroups.empty() )
178     return error("Invalid source groups");
179
180   bool allGroupsEmpty = true;
181   for ( size_t iG = 0; iG < srcGroups.size() && allGroupsEmpty; ++iG )
182     allGroupsEmpty = srcGroups[iG]->GetGroupDS()->IsEmpty();
183   if ( allGroupsEmpty )
184     return error("No faces in source groups");
185
186   SMESH_MesherHelper helper(theMesh);
187   helper.SetSubShape(theShape);
188   SMESHDS_Mesh* tgtMesh = theMesh.GetMeshDS();
189
190   const TopoDS_Face& geomFace = TopoDS::Face( theShape );
191   const double faceTol = helper.MaxTolerance( geomFace );
192   const int shapeID = tgtMesh->ShapeToIndex( geomFace );
193   const bool toCheckOri = (helper.NbAncestors( geomFace, theMesh, TopAbs_SOLID ) == 1 );
194
195   Handle(Geom_Surface) surface = BRep_Tool::Surface( geomFace );
196   const bool reverse =
197     ( helper.GetSubShapeOri( tgtMesh->ShapeToMesh(), geomFace ) == TopAbs_REVERSED );
198   gp_Pnt p; gp_Vec du, dv;
199
200   BRepClass_FaceClassifier classifier;
201   Bnd_B2d bndBox2d;
202   Bnd_Box bndBox3d;
203   {
204     Standard_Real umin,umax,vmin,vmax;
205     BRepTools::UVBounds(geomFace,umin,umax,vmin,vmax);
206     gp_XY pmin( umin,vmin ), pmax( umax,vmax );
207     bndBox2d.Add( pmin );
208     bndBox2d.Add( pmax );
209     if ( helper.HasSeam() )
210     {
211       const int i = helper.GetPeriodicIndex();
212       pmin.SetCoord( i, helper.GetOtherParam( pmin.Coord( i )));
213       pmax.SetCoord( i, helper.GetOtherParam( pmax.Coord( i )));
214       bndBox2d.Add( pmin );
215       bndBox2d.Add( pmax );
216     }
217     bndBox2d.Enlarge( 1e-2 * Sqrt( bndBox2d.SquareExtent() ));
218
219     BRepBndLib::Add( geomFace, bndBox3d );
220     bndBox3d.Enlarge( 1e-4 * sqrt( bndBox3d.SquareExtent() ));
221   }
222
223   set<int> subShapeIDs;
224   subShapeIDs.insert( shapeID );
225
226   // nodes already existing on sub-shapes of the FACE
227   TIDSortedNodeSet existingNodes;
228
229   // get/make nodes on vertices and add them to existingNodes
230   TopExp_Explorer exp( theShape, TopAbs_VERTEX );
231   for ( ; exp.More(); exp.Next() )
232   {
233     const TopoDS_Vertex& v = TopoDS::Vertex( exp.Current() );
234     if ( !subShapeIDs.insert( tgtMesh->ShapeToIndex( v )).second )
235       continue;
236     const SMDS_MeshNode* n = SMESH_Algo::VertexNode( v, tgtMesh );
237     if ( !n )
238     {
239       _gen->Compute(theMesh,v,/*anUpward=*/true);
240       n = SMESH_Algo::VertexNode( v, tgtMesh );
241       if ( !n ) return false; // very strange
242     }
243     existingNodes.insert( n );
244   }
245
246   // get EDGEs and their ids and get existing nodes on EDGEs
247   vector< TopoDS_Edge > edges;
248   for ( exp.Init( theShape, TopAbs_EDGE ); exp.More(); exp.Next() )
249   {
250     const TopoDS_Edge & edge = TopoDS::Edge( exp.Current() );
251     if ( !SMESH_Algo::isDegenerated( edge ))
252       if ( subShapeIDs.insert( tgtMesh->ShapeToIndex( edge )).second )
253       {
254         edges.push_back( edge );
255         if ( SMESHDS_SubMesh* eSM = tgtMesh->MeshElements( edge ))
256         {
257           typedef SMDS_StdIterator< const SMDS_MeshNode*, SMDS_NodeIteratorPtr > iterator;
258           existingNodes.insert( iterator( eSM->GetNodes() ), iterator() );
259         }
260       }
261   }
262   // octree to find existing nodes
263   SMESH_OctreeNode existingNodeOcTr( existingNodes );
264   std::map<double, const SMDS_MeshNode*> dist2foundNodes;
265
266   // to count now many times a link between nodes encounters
267   map<TLink, int> linkCount;
268   map<TLink, int>::iterator link2Nb;
269   double minGroupTol = Precision::Infinite();
270
271   // =========================
272   // Import faces from groups
273   // =========================
274
275   StdMeshers_Import_1D::TNodeNodeMap* n2n;
276   StdMeshers_Import_1D::TElemElemMap* e2e;
277   vector<TopAbs_State>         nodeState;
278   vector<const SMDS_MeshNode*> newNodes; // of a face
279   set   <const SMDS_MeshNode*> bndNodes; // nodes classified ON
280
281   for ( size_t iG = 0; iG < srcGroups.size(); ++iG )
282   {
283     const SMESHDS_GroupBase* srcGroup = srcGroups[iG]->GetGroupDS();
284
285     const int meshID = srcGroup->GetMesh()->GetPersistentId();
286     const SMESH_Mesh* srcMesh = GetMeshByPersistentID( meshID );
287     if ( !srcMesh ) continue;
288     StdMeshers_Import_1D::getMaps( srcMesh, &theMesh, n2n, e2e );
289
290     const double groupTol = 0.5 * sqrt( getMinElemSize2( srcGroup ));
291     minGroupTol = std::min( groupTol, minGroupTol );
292
293     //GeomAdaptor_Surface S( surface );
294     // const double clsfTol = Min( S.UResolution( 0.1 * groupTol ), -- issue 0023092
295     //                             S.VResolution( 0.1 * groupTol ));
296     const double clsfTol = BRep_Tool::Tolerance( geomFace );
297
298     StdMeshers_Import_1D::TNodeNodeMap::iterator n2nIt;
299     pair< StdMeshers_Import_1D::TNodeNodeMap::iterator, bool > it_isnew;
300
301     SMDS_ElemIteratorPtr srcElems = srcGroup->GetElements();
302     while ( srcElems->more() ) // loop on group contents
303     {
304       const SMDS_MeshElement* face = srcElems->next();
305
306       SMDS_MeshElement::iterator node = face->begin_nodes();
307       if ( bndBox3d.IsOut( SMESH_TNodeXYZ( *node )))
308         continue;
309
310       // find or create nodes of a new face
311       nodeState.resize( face->NbNodes() );
312       newNodes.resize( nodeState.size() );
313       newNodes.back() = 0;
314       int nbCreatedNodes = 0;
315       bool isOut = false, isIn = false; // if at least one node isIn - do not classify other nodes
316       for ( size_t i = 0; i < newNodes.size(); ++i, ++node )
317       {
318         SMESH_TNodeXYZ nXYZ = *node;
319         nodeState[ i ] = TopAbs_UNKNOWN;
320         newNodes [ i ] = 0;
321
322         it_isnew = n2n->insert( make_pair( *node, (SMDS_MeshNode*)0 ));
323         n2nIt    = it_isnew.first;
324
325         const SMDS_MeshNode* & newNode = n2nIt->second;
326         if ( !it_isnew.second && !newNode )
327           break; // a node is mapped to NULL - it is OUT of the FACE
328
329         if ( newNode )
330         {
331           if ( !subShapeIDs.count( newNode->getshapeId() ))
332             break; // node is Imported onto other FACE
333           if ( !isIn && bndNodes.count( *node ))
334             nodeState[ i ] = TopAbs_ON;
335         }
336         else
337         {
338           // find a node pre-existing on EDGE or VERTEX
339           dist2foundNodes.clear();
340           existingNodeOcTr.NodesAround( nXYZ, dist2foundNodes, groupTol );
341           if ( !dist2foundNodes.empty() )
342           {
343             newNode = dist2foundNodes.begin()->second;
344             nodeState[ i ] = TopAbs_ON;
345           }
346         }
347
348         if ( !newNode )
349         {
350           // find out if node lies on the surface of theShape
351           gp_XY uv( Precision::Infinite(), 0 );
352           isOut = ( !helper.CheckNodeUV( geomFace, *node, uv, groupTol, /*force=*/true ) ||
353                     bndBox2d.IsOut( uv ));
354           if ( !isOut && !isIn ) // classify
355           {
356             classifier.Perform( geomFace, uv, clsfTol );
357             nodeState[i] = classifier.State();
358             isOut = ( nodeState[i] == TopAbs_OUT );
359           }
360           if ( !isOut ) // create a new node
361           {
362             newNode = tgtMesh->AddNode( nXYZ.X(), nXYZ.Y(), nXYZ.Z());
363             tgtMesh->SetNodeOnFace( newNode, shapeID, uv.X(), uv.Y() );
364             nbCreatedNodes++;
365             if ( nodeState[i] == TopAbs_ON )
366               bndNodes.insert( *node );
367             else
368               isIn = true;
369           }
370         }
371         if ( !(newNodes[i] = newNode ) || isOut )
372           break;
373       }
374
375       if ( !newNodes.back() )
376         continue; // not all nodes of the face lie on theShape
377
378       if ( !isIn ) // if all nodes are on FACE boundary, a mesh face can be OUT
379       {
380         // check state of nodes created for other faces
381         for ( size_t i = 0; i < nodeState.size() && !isIn; ++i )
382         {
383           if ( nodeState[i] != TopAbs_UNKNOWN ) continue;
384           gp_XY uv = helper.GetNodeUV( geomFace, newNodes[i] );
385           classifier.Perform( geomFace, uv, clsfTol );
386           nodeState[i] = classifier.State();
387           isIn = ( nodeState[i] == TopAbs_IN );
388         }
389         if ( !isIn ) // classify face center
390         {
391           gp_XYZ gc( 0., 0., 0 );
392           for ( size_t i = 0; i < newNodes.size(); ++i )
393             gc += SMESH_TNodeXYZ( newNodes[i] );
394           gc /= newNodes.size();
395
396           TopLoc_Location loc;
397           GeomAPI_ProjectPointOnSurf& proj = helper.GetProjector( geomFace,
398                                                                   loc,
399                                                                   helper.MaxTolerance( geomFace ));
400           if ( !loc.IsIdentity() ) loc.Transformation().Inverted().Transforms( gc );
401           proj.Perform( gc );
402           if ( !proj.IsDone() || proj.NbPoints() < 1 )
403             continue;
404           Quantity_Parameter U,V;
405           proj.LowerDistanceParameters(U,V);
406           gp_XY uv( U,V );
407           classifier.Perform( geomFace, uv, clsfTol );
408           if ( classifier.State() != TopAbs_IN )
409             continue;
410         }
411       }
412
413       // try to find already created face
414       SMDS_MeshElement * newFace = 0;
415       if ( nbCreatedNodes == 0 &&
416            tgtMesh->FindElement(newNodes, SMDSAbs_Face, /*noMedium=*/false))
417         continue; // repeated face in source groups already created
418
419       // check future face orientation
420       const int nbCorners = face->NbCornerNodes();
421       const bool isQuad   = ( nbCorners != (int) newNodes.size() );
422       if ( toCheckOri )
423       {
424         int iNode = -1;
425         gp_Vec geomNorm;
426         do
427         {
428           gp_XY uv = helper.GetNodeUV( geomFace, newNodes[++iNode] );
429           surface->D1( uv.X(),uv.Y(), p, du,dv );
430           geomNorm = reverse ? dv^du : du^dv;
431         }
432         while ( geomNorm.SquareMagnitude() < 1e-6 && iNode+1 < nbCorners );
433
434         int iNext = helper.WrapIndex( iNode+1, nbCorners );
435         int iPrev = helper.WrapIndex( iNode-1, nbCorners );
436
437         SMESH_TNodeXYZ prevNode( newNodes[iPrev] );
438         SMESH_TNodeXYZ curNode ( newNodes[iNode] );
439         SMESH_TNodeXYZ nextNode( newNodes[iNext] );
440         gp_Vec n1n0( prevNode - curNode);
441         gp_Vec n1n2( nextNode - curNode );
442         gp_Vec meshNorm = n1n2 ^ n1n0;
443
444         if ( geomNorm * meshNorm < 0 )
445           SMDS_MeshCell::applyInterlace
446             ( SMDS_MeshCell::reverseSmdsOrder( face->GetEntityType() ), newNodes );
447       }
448
449       // make a new face
450       if ( face->IsPoly() )
451         newFace = tgtMesh->AddPolygonalFace( newNodes );
452       else
453         switch ( newNodes.size() )
454         {
455         case 3:
456           newFace = tgtMesh->AddFace( newNodes[0], newNodes[1], newNodes[2] );
457           break;
458         case 4:
459           newFace = tgtMesh->AddFace( newNodes[0], newNodes[1], newNodes[2], newNodes[3] );
460           break;
461         case 6:
462           newFace = tgtMesh->AddFace( newNodes[0], newNodes[1], newNodes[2],
463                                       newNodes[3], newNodes[4], newNodes[5]);
464           break;
465         case 8:
466           newFace = tgtMesh->AddFace( newNodes[0], newNodes[1], newNodes[2], newNodes[3],
467                                       newNodes[4], newNodes[5], newNodes[6], newNodes[7]);
468           break;
469         default: continue;
470         }
471       tgtMesh->SetMeshElementOnShape( newFace, shapeID );
472       e2e->insert( make_pair( face, newFace ));
473
474       // collect links
475       const SMDS_MeshNode* medium = 0;
476       for ( int i = 0; i < nbCorners; ++i )
477       {
478         const SMDS_MeshNode* n1 = newNodes[i];
479         const SMDS_MeshNode* n2 = newNodes[ (i+1)%nbCorners ];
480         if ( isQuad ) // quadratic face
481           medium = newNodes[i+nbCorners];
482         link2Nb = linkCount.insert( make_pair( TLink( n1, n2, medium ), 0)).first;
483         ++link2Nb->second;
484         // if ( link2Nb->second == 1 )
485         // {
486         //   // measure link length
487         //   double len2 = SMESH_TNodeXYZ( n1 ).SquareDistance( n2 );
488         //   if ( len2 < minGroupTol )
489         //     minGroupTol = len2;
490         // }
491       }
492     }
493     // Remove OUT nodes from n2n map
494     for ( n2nIt = n2n->begin(); n2nIt != n2n->end(); )
495       if ( !n2nIt->second )
496         n2n->erase( n2nIt++ );
497       else
498         ++n2nIt;
499   }
500
501
502   // ==========================================================
503   // Put nodes on geom edges and create edges on them;
504   // check if the whole geom face is covered by imported faces
505   // ==========================================================
506
507   // use large tolerance for projection of nodes to edges because of
508   // BLSURF mesher specifics (issue 0020918, Study2.hdf)
509   const double projTol = minGroupTol;
510
511   bool isFaceMeshed = false;
512   SMESHDS_SubMesh* tgtFaceSM = tgtMesh->MeshElements( theShape );
513   if ( tgtFaceSM )
514   {
515     // the imported mesh is valid if all external links (encountered once)
516     // lie on geom edges
517     subShapeIDs.erase( shapeID ); // to contain edges and vertices only
518     double u, f, l;
519     for ( link2Nb = linkCount.begin(); link2Nb != linkCount.end(); ++link2Nb)
520     {
521       const TLink& link = (*link2Nb).first;
522       int nbFaces = link2Nb->second;
523       if ( nbFaces == 1 )
524       {
525         // check if a not shared link lies on face boundary
526         bool nodesOnBoundary = true;
527         list< TopoDS_Shape > bndShapes;
528         for ( int is1stN = 0; is1stN < 2 && nodesOnBoundary; ++is1stN )
529         {
530           const SMDS_MeshNode* n = is1stN ? link.node1() : link.node2();
531           if ( !subShapeIDs.count( n->getshapeId() )) // n is assigned to FACE
532           {
533             for ( size_t iE = 0; iE < edges.size(); ++iE )
534               if ( helper.CheckNodeU( edges[iE], n, u=0, projTol, /*force=*/true ))
535               {
536                 BRep_Tool::Range(edges[iE],f,l);
537                 if ( Abs(u-f) < 2 * faceTol || Abs(u-l) < 2 * faceTol )
538                   // duplicated node on vertex
539                   return error("Source elements overlap one another");
540                 tgtFaceSM->RemoveNode( n, /*isNodeDeleted=*/false );
541                 tgtMesh->SetNodeOnEdge( n, edges[iE], u );
542                 break;
543               }
544             nodesOnBoundary = subShapeIDs.count( n->getshapeId());
545           }
546           if ( nodesOnBoundary )
547           {
548             TopoDS_Shape s = helper.GetSubShapeByNode( n, tgtMesh );
549             if ( s.ShapeType() == TopAbs_VERTEX )
550               bndShapes.push_front( s ); // vertex first
551             else
552               bndShapes.push_back( s ); // edges last
553           }
554         }
555         if ( !nodesOnBoundary )
556         {
557           error("free internal link"); // just for an easier debug
558           break;
559         }
560         if ( bndShapes.front().ShapeType() == TopAbs_EDGE && // all link nodes are on EDGEs
561              bndShapes.front() != bndShapes.back() )
562           // link nodes on different geom edges
563           return error(COMPERR_BAD_INPUT_MESH, "Source nodes mismatch target vertices");
564
565         // find geom edge the link is on
566         if ( bndShapes.back().ShapeType() != TopAbs_EDGE ) // all link nodes are on VERTEXes
567         {
568           // find geom edge by two vertices
569           TopoDS_Shape geomEdge = helper.GetCommonAncestor( bndShapes.back(),
570                                                             bndShapes.front(),
571                                                             theMesh, TopAbs_EDGE );
572           if ( geomEdge.IsNull() )
573           {
574             error("free internal link");
575             break; // vertices belong to different edges
576           }
577           bndShapes.push_back( geomEdge );
578         }
579
580         // create an edge if not yet exists
581         newNodes.resize(2);
582         newNodes[0] = link.node1(), newNodes[1] = link.node2();
583         const SMDS_MeshElement* edge = tgtMesh->FindElement( newNodes, SMDSAbs_Edge );
584         if ( edge ) continue;
585
586         if ( link._reversed ) std::swap( newNodes[0], newNodes[1] );
587         if ( link._medium )
588         {
589           edge = tgtMesh->AddEdge( newNodes[0], newNodes[1], link._medium );
590
591           TopoDS_Edge geomEdge = TopoDS::Edge(bndShapes.back());
592           helper.CheckNodeU( geomEdge, link._medium, u, projTol, /*force=*/true );
593           tgtFaceSM->RemoveNode( link._medium, /*isNodeDeleted=*/false );
594           tgtMesh->SetNodeOnEdge( (SMDS_MeshNode*)link._medium, geomEdge, u );
595         }
596         else
597         {
598           edge = tgtMesh->AddEdge( newNodes[0], newNodes[1]);
599         }
600         if ( !edge )
601           return false;
602
603         tgtMesh->SetMeshElementOnShape( edge, bndShapes.back() );
604       }
605       else if ( nbFaces > 2 )
606       {
607         return error( COMPERR_BAD_INPUT_MESH, "Non-manifold source mesh");
608       }
609     }
610     isFaceMeshed = ( link2Nb == linkCount.end() && !linkCount.empty());
611     if ( isFaceMeshed )
612     {
613       // check that source faces do not overlap:
614       // there must be only two edges sharing each vertex and bound to sub-edges of theShape
615       SMESH_MeshEditor editor( &theMesh );
616       set<int>::iterator subID = subShapeIDs.begin();
617       for ( ; subID != subShapeIDs.end(); ++subID )
618       {
619         const TopoDS_Shape& s = tgtMesh->IndexToShape( *subID );
620         if ( s.ShapeType() != TopAbs_VERTEX ) continue;
621         const SMDS_MeshNode* n = SMESH_Algo::VertexNode( TopoDS::Vertex(s), tgtMesh );
622         SMDS_ElemIteratorPtr eIt = n->GetInverseElementIterator(SMDSAbs_Edge);
623         int nbEdges = 0;
624         while ( eIt->more() )
625         {
626           const SMDS_MeshElement* edge = eIt->next();
627           int sId = editor.FindShape( edge );
628           nbEdges += subShapeIDs.count( sId );
629         }
630         if ( nbEdges < 2 && !helper.IsRealSeam( s ))
631           return false; // weird
632         if ( nbEdges > 2 )
633           return error( COMPERR_BAD_INPUT_MESH, "Source elements overlap one another");
634       }
635     }
636   }
637   if ( !isFaceMeshed )
638     return error( COMPERR_BAD_INPUT_MESH,
639                   "Source elements don't cover totally the geometrical face" );
640
641   if ( helper.HasSeam() )
642   {
643     // links on seam edges are shared by two faces, so no edges were created on them
644     // by the previous detection of 2D mesh boundary
645     for ( size_t iE = 0; iE < edges.size(); ++iE )
646     {
647       if ( !helper.IsRealSeam( edges[iE] )) continue;
648       const TopoDS_Edge& seamEdge = edges[iE];
649       // to find nodes lying on the seamEdge we check nodes of mesh faces sharing a node on one
650       // of its vertices; after finding another node on seamEdge we continue the same way
651       // until finding all nodes.
652       TopoDS_Vertex      seamVertex = helper.IthVertex( 0, seamEdge );
653       const SMDS_MeshNode* vertNode = SMESH_Algo::VertexNode( seamVertex, tgtMesh );
654       set< const SMDS_MeshNode* > checkedNodes; checkedNodes.insert( vertNode );
655       set< const SMDS_MeshElement* > checkedFaces;
656       // as a face can have more than one node on the seamEdge, there is a difficulty in selecting
657       // one of those nodes to treat next; so we simply find all nodes on the seamEdge and
658       // then sort them by U on edge
659       typedef list< pair< double, const SMDS_MeshNode* > > TUNodeList;
660       TUNodeList nodesOnSeam;
661       double u = helper.GetNodeU( seamEdge, vertNode );
662       nodesOnSeam.push_back( make_pair( u, vertNode ));
663       TUNodeList::iterator u2nIt = nodesOnSeam.begin();
664       for ( ; u2nIt != nodesOnSeam.end(); ++u2nIt )
665       {
666         const SMDS_MeshNode* startNode = (*u2nIt).second;
667         SMDS_ElemIteratorPtr faceIt = startNode->GetInverseElementIterator( SMDSAbs_Face );
668         while ( faceIt->more() )
669         {
670           const SMDS_MeshElement* face = faceIt->next();
671           if ( !checkedFaces.insert( face ).second ) continue;
672           for ( int i = 0, nbNodes = face->NbCornerNodes(); i < nbNodes; ++i )
673           {
674             const SMDS_MeshNode* n = face->GetNode( i );
675             if ( n == startNode || !checkedNodes.insert( n ).second ) continue;
676             if ( helper.CheckNodeU( seamEdge, n, u=0, projTol, /*force=*/true ))
677               nodesOnSeam.push_back( make_pair( u, n ));
678           }
679         }
680       }
681       // sort the found nodes by U on the seamEdge; most probably they are in a good order,
682       // so we can use the hint to spead-up map filling
683       map< double, const SMDS_MeshNode* > u2nodeMap;
684       for ( u2nIt = nodesOnSeam.begin(); u2nIt != nodesOnSeam.end(); ++u2nIt )
685         u2nodeMap.insert( u2nodeMap.end(), *u2nIt );
686
687       // create edges
688       {
689         SMESH_MesherHelper seamHelper( theMesh );
690         seamHelper.SetSubShape( edges[ iE ]);
691         seamHelper.SetElementsOnShape( true );
692
693         if ( !checkedFaces.empty() && (*checkedFaces.begin())->IsQuadratic() )
694           for ( set< const SMDS_MeshElement* >::iterator fIt = checkedFaces.begin();
695                 fIt != checkedFaces.end(); ++fIt )
696             seamHelper.AddTLinks( static_cast<const SMDS_MeshFace*>( *fIt ));
697
698         map< double, const SMDS_MeshNode* >::iterator n1, n2, u2nEnd = u2nodeMap.end();
699         for ( n2 = u2nodeMap.begin(), n1 = n2++; n2 != u2nEnd; ++n1, ++n2 )
700         {
701           const SMDS_MeshNode* node1 = n1->second;
702           const SMDS_MeshNode* node2 = n2->second;
703           seamHelper.AddEdge( node1, node2 );
704           if ( node2->getshapeId() == helper.GetSubShapeID() )
705           {
706             tgtFaceSM->RemoveNode( node2, /*isNodeDeleted=*/false );
707             tgtMesh->SetNodeOnEdge( const_cast<SMDS_MeshNode*>( node2 ), seamEdge, n2->first );
708           }
709         }
710       }
711     } // loop on edges to find seam ones
712   } // if ( helper.HasSeam() )
713
714   // notify sub-meshes of edges on computation
715   for ( size_t iE = 0; iE < edges.size(); ++iE )
716   {
717     SMESH_subMesh * sm = theMesh.GetSubMesh( edges[iE] );
718     // if ( SMESH_Algo::isDegenerated( edges[iE] ))
719     //   sm->SetIsAlwaysComputed( true );
720     sm->ComputeStateEngine(SMESH_subMesh::CHECK_COMPUTE_STATE);
721     if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
722       return error(SMESH_Comment("Failed to create segments on the edge #") << sm->GetId());
723   }
724
725   // ============
726   // Copy meshes
727   // ============
728
729   vector<SMESH_Mesh*> srcMeshes = _sourceHyp->GetSourceMeshes();
730   for ( size_t i = 0; i < srcMeshes.size(); ++i )
731     StdMeshers_Import_1D::importMesh( srcMeshes[i], theMesh, _sourceHyp, theShape );
732
733   return true;
734 }
735
736 //=============================================================================
737 /*!
738  * \brief Set needed event listeners and create a submesh for a copied mesh
739  *
740  * This method is called only if a submesh has HYP_OK algo_state.
741  */
742 //=============================================================================
743
744 void StdMeshers_Import_1D2D::SetEventListener(SMESH_subMesh* subMesh)
745 {
746   if ( !_sourceHyp )
747   {
748     const TopoDS_Shape& tgtShape = subMesh->GetSubShape();
749     SMESH_Mesh*         tgtMesh  = subMesh->GetFather();
750     Hypothesis_Status aStatus;
751     CheckHypothesis( *tgtMesh, tgtShape, aStatus );
752   }
753   StdMeshers_Import_1D::setEventListener( subMesh, _sourceHyp );
754 }
755 void StdMeshers_Import_1D2D::SubmeshRestored(SMESH_subMesh* subMesh)
756 {
757   SetEventListener(subMesh);
758 }
759
760 //=============================================================================
761 /*!
762  * Predict nb of mesh entities created by Compute()
763  */
764 //=============================================================================
765
766 bool StdMeshers_Import_1D2D::Evaluate(SMESH_Mesh &         theMesh,
767                                       const TopoDS_Shape & theShape,
768                                       MapShapeNbElems&     aResMap)
769 {
770   if ( !_sourceHyp ) return false;
771
772   const vector<SMESH_Group*>& srcGroups = _sourceHyp->GetGroups();
773   if ( srcGroups.empty() )
774     return error("Invalid source groups");
775
776   vector<int> aVec(SMDSEntity_Last,0);
777
778   bool toCopyMesh, toCopyGroups;
779   _sourceHyp->GetCopySourceMesh(toCopyMesh, toCopyGroups);
780   if ( toCopyMesh ) // the whole mesh is copied
781   {
782     vector<SMESH_Mesh*> srcMeshes = _sourceHyp->GetSourceMeshes();
783     for ( unsigned i = 0; i < srcMeshes.size(); ++i )
784     {
785       SMESH_subMesh* sm = StdMeshers_Import_1D::getSubMeshOfCopiedMesh( theMesh, *srcMeshes[i]);
786       if ( !sm || aResMap.count( sm )) continue; // already counted
787       const SMDS_MeshInfo& aMeshInfo = srcMeshes[i]->GetMeshDS()->GetMeshInfo();
788       for (int i = 0; i < SMDSEntity_Last; i++)
789         aVec[i] = aMeshInfo.NbEntities((SMDSAbs_EntityType)i);
790     }
791   }
792   else
793   {
794     // std-like iterator used to get coordinates of nodes of mesh element
795     typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
796
797     SMESH_MesherHelper helper(theMesh);
798     helper.SetSubShape(theShape);
799
800     const TopoDS_Face& geomFace = TopoDS::Face( theShape );
801
802     // take into account nodes on vertices
803     TopExp_Explorer exp( theShape, TopAbs_VERTEX );
804     for ( ; exp.More(); exp.Next() )
805       theMesh.GetSubMesh( exp.Current())->Evaluate( aResMap );
806
807     // to count now many times a link between nodes encounters,
808     // negative nb additionally means that a link is quadratic
809     map<SMESH_TLink, int> linkCount;
810     map<SMESH_TLink, int>::iterator link2Nb;
811
812     // count faces and nodes imported from groups
813     set<const SMDS_MeshNode* > allNodes;
814     gp_XY uv;
815     double minGroupTol = 1e100;
816     for ( int iG = 0; iG < srcGroups.size(); ++iG )
817     {
818       const SMESHDS_GroupBase* srcGroup = srcGroups[iG]->GetGroupDS();
819       const double groupTol = 0.5 * sqrt( getMinElemSize2( srcGroup ));
820       minGroupTol = std::min( groupTol, minGroupTol );
821       SMDS_ElemIteratorPtr srcElems = srcGroup->GetElements();
822       SMDS_MeshNode *tmpNode =helper.AddNode(0,0,0);
823       while ( srcElems->more() ) // loop on group contents
824       {
825         const SMDS_MeshElement* face = srcElems->next();
826         // find out if face is located on geomEdge by projecting
827         // a gravity center of face to geomFace
828         gp_XYZ gc(0,0,0);
829         gc = accumulate( TXyzIterator(face->nodesIterator()), TXyzIterator(), gc)/face->NbNodes();
830         tmpNode->setXYZ( gc.X(), gc.Y(), gc.Z());
831         if ( helper.CheckNodeUV( geomFace, tmpNode, uv, groupTol, /*force=*/true ))
832         {
833           ++aVec[ face->GetEntityType() ];
834
835           // collect links
836           int nbConers = face->NbCornerNodes();
837           for ( int i = 0; i < face->NbNodes(); ++i )
838           {
839             const SMDS_MeshNode* n1 = face->GetNode(i);
840             allNodes.insert( n1 );
841             if ( i < nbConers )
842             {
843               const SMDS_MeshNode* n2 = face->GetNode( (i+1)%nbConers );
844               link2Nb = linkCount.insert( make_pair( SMESH_TLink( n1, n2 ), 0)).first;
845               if ( (*link2Nb).second )
846                 link2Nb->second += (link2Nb->second < 0 ) ? -1 : 1;
847               else
848                 link2Nb->second += ( face->IsQuadratic() ) ? -1 : 1;
849             }
850           }
851         }
852       }
853       helper.GetMeshDS()->RemoveNode(tmpNode);
854     }
855
856     int nbNodes = allNodes.size();
857     allNodes.clear();
858
859     // count nodes and edges on geom edges
860
861     double u;
862     for ( exp.Init(theShape, TopAbs_EDGE); exp.More(); exp.Next() )
863     {
864       TopoDS_Edge geomEdge = TopoDS::Edge( exp.Current() );
865       SMESH_subMesh* sm = theMesh.GetSubMesh( geomEdge );
866       vector<int>& edgeVec = aResMap[sm];
867       if ( edgeVec.empty() )
868       {
869         edgeVec.resize(SMDSEntity_Last,0);
870         for ( link2Nb = linkCount.begin(); link2Nb != linkCount.end(); )
871         {
872           const SMESH_TLink& link = (*link2Nb).first;
873           int nbFacesOfLink = Abs( link2Nb->second );
874           bool eraseLink = ( nbFacesOfLink != 1 );
875           if ( nbFacesOfLink == 1 )
876           {
877             if ( helper.CheckNodeU( geomEdge, link.node1(), u, minGroupTol, /*force=*/true )&&
878                  helper.CheckNodeU( geomEdge, link.node2(), u, minGroupTol, /*force=*/true ))
879             {
880               bool isQuadratic = ( link2Nb->second < 0 );
881               ++edgeVec[ isQuadratic ? SMDSEntity_Quad_Edge : SMDSEntity_Edge ];
882               ++edgeVec[ SMDSEntity_Node ];
883               --nbNodes;
884               eraseLink = true;
885             }
886           }
887           if ( eraseLink )
888             linkCount.erase(link2Nb++);
889           else
890             link2Nb++;
891         }
892         if ( edgeVec[ SMDSEntity_Node] > 0 )
893           --edgeVec[ SMDSEntity_Node ]; // for one node on vertex
894       }
895       else if ( !helper.IsSeamShape( geomEdge ) ||
896                 geomEdge.Orientation() == TopAbs_FORWARD )
897       {
898         nbNodes -= 1+edgeVec[ SMDSEntity_Node ];
899       }
900     }
901
902     aVec[SMDSEntity_Node] = nbNodes;
903   }
904
905   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
906   aResMap.insert(make_pair(sm,aVec));
907
908   return true;
909 }