Salome HOME
60b776254489ad854f7f7dd9452386aa3491ceb2
[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
196   Handle(Geom_Surface) surface = BRep_Tool::Surface( geomFace );
197   const bool reverse =
198     ( helper.GetSubShapeOri( tgtMesh->ShapeToMesh(), geomFace ) == TopAbs_REVERSED );
199   gp_Pnt p; gp_Vec du, dv;
200
201   // BRepClass_FaceClassifier is most time consuming, so minimize its usage
202   BRepClass_FaceClassifier classifier;
203   Bnd_B2d bndBox2d;
204   Bnd_Box bndBox3d;
205   {
206     Standard_Real umin,umax,vmin,vmax;
207     BRepTools::UVBounds(geomFace,umin,umax,vmin,vmax);
208     gp_XY pmin( umin,vmin ), pmax( umax,vmax );
209     bndBox2d.Add( pmin );
210     bndBox2d.Add( pmax );
211     if ( helper.HasSeam() )
212     {
213       const int i = helper.GetPeriodicIndex();
214       pmin.SetCoord( i, helper.GetOtherParam( pmin.Coord( i )));
215       pmax.SetCoord( i, helper.GetOtherParam( pmax.Coord( i )));
216       bndBox2d.Add( pmin );
217       bndBox2d.Add( pmax );
218     }
219     bndBox2d.Enlarge( 1e-2 * Sqrt( bndBox2d.SquareExtent() ));
220
221     BRepBndLib::Add( geomFace, bndBox3d );
222     bndBox3d.Enlarge( 1e-5 * sqrt( bndBox3d.SquareExtent() ));
223   }
224
225   set<int> subShapeIDs;
226   subShapeIDs.insert( shapeID );
227
228   // nodes already existing on sub-shapes of the FACE
229   TIDSortedNodeSet existingNodes;
230
231   // get/make nodes on vertices and add them to existingNodes
232   TopExp_Explorer exp( theShape, TopAbs_VERTEX );
233   for ( ; exp.More(); exp.Next() )
234   {
235     const TopoDS_Vertex& v = TopoDS::Vertex( exp.Current() );
236     if ( !subShapeIDs.insert( tgtMesh->ShapeToIndex( v )).second )
237       continue;
238     const SMDS_MeshNode* n = SMESH_Algo::VertexNode( v, tgtMesh );
239     if ( !n )
240     {
241       _gen->Compute(theMesh,v,/*anUpward=*/true);
242       n = SMESH_Algo::VertexNode( v, tgtMesh );
243       if ( !n ) return false; // very strange
244     }
245     existingNodes.insert( n );
246   }
247
248   // get EDGEs and their ids and get existing nodes on EDGEs
249   vector< TopoDS_Edge > edges;
250   for ( exp.Init( theShape, TopAbs_EDGE ); exp.More(); exp.Next() )
251   {
252     const TopoDS_Edge & edge = TopoDS::Edge( exp.Current() );
253     if ( !SMESH_Algo::isDegenerated( edge ))
254       if ( subShapeIDs.insert( tgtMesh->ShapeToIndex( edge )).second )
255       {
256         edges.push_back( edge );
257         if ( SMESHDS_SubMesh* eSM = tgtMesh->MeshElements( edge ))
258         {
259           typedef SMDS_StdIterator< const SMDS_MeshNode*, SMDS_NodeIteratorPtr > iterator;
260           existingNodes.insert( iterator( eSM->GetNodes() ), iterator() );
261         }
262       }
263   }
264   // octree to find existing nodes
265   SMESH_OctreeNode existingNodeOcTr( existingNodes );
266   std::map<double, const SMDS_MeshNode*> dist2foundNodes;
267
268   // to count now many times a link between nodes encounters
269   map<TLink, int> linkCount;
270   map<TLink, int>::iterator link2Nb;
271   double minGroupTol = Precision::Infinite();
272
273   // =========================
274   // Import faces from groups
275   // =========================
276
277   StdMeshers_Import_1D::TNodeNodeMap* n2n;
278   StdMeshers_Import_1D::TElemElemMap* e2e;
279   vector<TopAbs_State>         nodeState;
280   vector<const SMDS_MeshNode*> newNodes; // of a face
281   set   <const SMDS_MeshNode*> bndNodes; // nodes classified ON
282   vector<bool>                 isNodeIn; // nodes classified IN, by node ID
283
284   for ( size_t iG = 0; iG < srcGroups.size(); ++iG )
285   {
286     const SMESHDS_GroupBase* srcGroup = srcGroups[iG]->GetGroupDS();
287
288     const int meshID = srcGroup->GetMesh()->GetPersistentId();
289     const SMESH_Mesh* srcMesh = GetMeshByPersistentID( meshID );
290     if ( !srcMesh ) continue;
291     StdMeshers_Import_1D::getMaps( srcMesh, &theMesh, n2n, e2e );
292
293     const double groupTol = 0.5 * sqrt( getMinElemSize2( srcGroup ));
294     minGroupTol = std::min( groupTol, minGroupTol );
295
296     //GeomAdaptor_Surface S( surface );
297     // const double clsfTol = Min( S.UResolution( 0.1 * groupTol ), -- issue 0023092
298     //                             S.VResolution( 0.1 * groupTol ));
299     const double clsfTol = BRep_Tool::Tolerance( geomFace );
300
301     StdMeshers_Import_1D::TNodeNodeMap::iterator n2nIt;
302     pair< StdMeshers_Import_1D::TNodeNodeMap::iterator, bool > it_isnew;
303
304     SMDS_ElemIteratorPtr srcElems = srcGroup->GetElements();
305     while ( srcElems->more() ) // loop on group contents
306     {
307       const SMDS_MeshElement* face = srcElems->next();
308
309       SMDS_MeshElement::iterator node = face->begin_nodes();
310       if ( bndBox3d.IsOut( SMESH_TNodeXYZ( *node )))
311         continue;
312
313       // find or create nodes of a new face
314       nodeState.resize( face->NbNodes() );
315       newNodes.resize( nodeState.size() );
316       newNodes.back() = 0;
317       int nbCreatedNodes = 0;
318       bool isOut = false, isIn = false; // if at least one node isIn - do not classify other nodes
319       for ( size_t i = 0; i < newNodes.size(); ++i, ++node )
320       {
321         SMESH_TNodeXYZ nXYZ = *node;
322         nodeState[ i ] = TopAbs_UNKNOWN;
323         newNodes [ i ] = 0;
324
325         it_isnew = n2n->insert( make_pair( *node, (SMDS_MeshNode*)0 ));
326         n2nIt    = it_isnew.first;
327
328         const SMDS_MeshNode* & newNode = n2nIt->second;
329         if ( !it_isnew.second && !newNode )
330           break; // a node is mapped to NULL - it is OUT of the FACE
331
332         if ( newNode )
333         {
334           if ( !subShapeIDs.count( newNode->getshapeId() ))
335             break; // node is Imported onto other FACE
336           if ( newNode->GetID() < (int) isNodeIn.size() &&
337                isNodeIn[ newNode->GetID() ])
338             isIn = true;
339           if ( !isIn && bndNodes.count( *node ))
340             nodeState[ i ] = TopAbs_ON;
341         }
342         else
343         {
344           // find a node pre-existing on EDGE or VERTEX
345           dist2foundNodes.clear();
346           existingNodeOcTr.NodesAround( nXYZ, dist2foundNodes, groupTol );
347           if ( !dist2foundNodes.empty() )
348           {
349             newNode = dist2foundNodes.begin()->second;
350             nodeState[ i ] = TopAbs_ON;
351           }
352         }
353
354         if ( !newNode )
355         {
356           // find out if node lies on the surface of theShape
357           gp_XY uv( Precision::Infinite(), 0 );
358           isOut = ( !helper.CheckNodeUV( geomFace, *node, uv, groupTol, /*force=*/true ) ||
359                     bndBox2d.IsOut( uv ));
360           if ( !isOut && !isIn ) // classify
361           {
362             classifier.Perform( geomFace, uv, clsfTol );
363             nodeState[i] = classifier.State();
364             isOut = ( nodeState[i] == TopAbs_OUT );
365           }
366           if ( !isOut ) // create a new node
367           {
368             newNode = tgtMesh->AddNode( nXYZ.X(), nXYZ.Y(), nXYZ.Z());
369             tgtMesh->SetNodeOnFace( newNode, shapeID, uv.X(), uv.Y() );
370             nbCreatedNodes++;
371             if ( newNode->GetID() >= (int) isNodeIn.size() )
372             {
373               isNodeIn.push_back( false ); // allow allocate more than newNode->GetID()
374               isNodeIn.resize( newNode->GetID() + 1, false );
375             }
376             if ( nodeState[i] == TopAbs_ON )
377               bndNodes.insert( *node );
378             else
379               isNodeIn[ newNode->GetID() ] = isIn = true;
380           }
381         }
382         if ( !(newNodes[i] = newNode ) || isOut )
383           break;
384       }
385
386       if ( !newNodes.back() )
387         continue; // not all nodes of the face lie on theShape
388
389       if ( !isIn ) // if all nodes are on FACE boundary, a mesh face can be OUT
390       {
391         // check state of nodes created for other faces
392         for ( size_t i = 0; i < nodeState.size() && !isIn; ++i )
393         {
394           if ( nodeState[i] != TopAbs_UNKNOWN ) continue;
395           gp_XY uv = helper.GetNodeUV( geomFace, newNodes[i] );
396           classifier.Perform( geomFace, uv, clsfTol );
397           nodeState[i] = classifier.State();
398           isIn = ( nodeState[i] == TopAbs_IN );
399         }
400         if ( !isIn ) // classify face center
401         {
402           gp_XYZ gc( 0., 0., 0 );
403           for ( size_t i = 0; i < newNodes.size(); ++i )
404             gc += SMESH_TNodeXYZ( newNodes[i] );
405           gc /= newNodes.size();
406
407           TopLoc_Location loc;
408           GeomAPI_ProjectPointOnSurf& proj = helper.GetProjector( geomFace,
409                                                                   loc,
410                                                                   helper.MaxTolerance( geomFace ));
411           if ( !loc.IsIdentity() ) loc.Transformation().Inverted().Transforms( gc );
412           proj.Perform( gc );
413           if ( !proj.IsDone() || proj.NbPoints() < 1 )
414             continue;
415           Quantity_Parameter U,V;
416           proj.LowerDistanceParameters(U,V);
417           gp_XY uv( U,V );
418           classifier.Perform( geomFace, uv, clsfTol );
419           if ( classifier.State() != TopAbs_IN )
420             continue;
421         }
422       }
423
424       // try to find already created face
425       SMDS_MeshElement * newFace = 0;
426       if ( nbCreatedNodes == 0 &&
427            tgtMesh->FindElement(newNodes, SMDSAbs_Face, /*noMedium=*/false))
428         continue; // repeated face in source groups already created
429
430       // check future face orientation
431       const int nbCorners = face->NbCornerNodes();
432       const bool isQuad   = ( nbCorners != (int) newNodes.size() );
433       if ( toCheckOri )
434       {
435         int iNode = -1;
436         gp_Vec geomNorm;
437         do
438         {
439           gp_XY uv = helper.GetNodeUV( geomFace, newNodes[++iNode] );
440           surface->D1( uv.X(),uv.Y(), p, du,dv );
441           geomNorm = reverse ? dv^du : du^dv;
442         }
443         while ( geomNorm.SquareMagnitude() < 1e-6 && iNode+1 < nbCorners );
444
445         int iNext = helper.WrapIndex( iNode+1, nbCorners );
446         int iPrev = helper.WrapIndex( iNode-1, nbCorners );
447
448         SMESH_TNodeXYZ prevNode( newNodes[iPrev] );
449         SMESH_TNodeXYZ curNode ( newNodes[iNode] );
450         SMESH_TNodeXYZ nextNode( newNodes[iNext] );
451         gp_Vec n1n0( prevNode - curNode);
452         gp_Vec n1n2( nextNode - curNode );
453         gp_Vec meshNorm = n1n2 ^ n1n0;
454
455         if ( geomNorm * meshNorm < 0 )
456           SMDS_MeshCell::applyInterlace
457             ( SMDS_MeshCell::reverseSmdsOrder( face->GetEntityType(), newNodes.size() ), newNodes );
458       }
459
460       // make a new face
461       if ( face->IsPoly() )
462         newFace = tgtMesh->AddPolygonalFace( newNodes );
463       else
464         switch ( newNodes.size() )
465         {
466         case 3:
467           newFace = tgtMesh->AddFace( newNodes[0], newNodes[1], newNodes[2] );
468           break;
469         case 4:
470           newFace = tgtMesh->AddFace( newNodes[0], newNodes[1], newNodes[2], newNodes[3] );
471           break;
472         case 6:
473           newFace = tgtMesh->AddFace( newNodes[0], newNodes[1], newNodes[2],
474                                       newNodes[3], newNodes[4], newNodes[5]);
475           break;
476         case 8:
477           newFace = tgtMesh->AddFace( newNodes[0], newNodes[1], newNodes[2], newNodes[3],
478                                       newNodes[4], newNodes[5], newNodes[6], newNodes[7]);
479           break;
480         default: continue;
481         }
482       tgtMesh->SetMeshElementOnShape( newFace, shapeID );
483       e2e->insert( make_pair( face, newFace ));
484
485       // collect links
486       const SMDS_MeshNode* medium = 0;
487       for ( int i = 0; i < nbCorners; ++i )
488       {
489         const SMDS_MeshNode* n1 = newNodes[i];
490         const SMDS_MeshNode* n2 = newNodes[ (i+1)%nbCorners ];
491         if ( isQuad ) // quadratic face
492           medium = newNodes[i+nbCorners];
493         link2Nb = linkCount.insert( make_pair( TLink( n1, n2, medium ), 0)).first;
494         ++link2Nb->second;
495         // if ( link2Nb->second == 1 )
496         // {
497         //   // measure link length
498         //   double len2 = SMESH_TNodeXYZ( n1 ).SquareDistance( n2 );
499         //   if ( len2 < minGroupTol )
500         //     minGroupTol = len2;
501         // }
502       }
503     }
504     // Remove OUT nodes from n2n map
505     for ( n2nIt = n2n->begin(); n2nIt != n2n->end(); )
506       if ( !n2nIt->second )
507         n2n->erase( n2nIt++ );
508       else
509         ++n2nIt;
510   }
511
512
513   // ==========================================================
514   // Put nodes on geom edges and create edges on them;
515   // check if the whole geom face is covered by imported faces
516   // ==========================================================
517
518   // use large tolerance for projection of nodes to edges because of
519   // BLSURF mesher specifics (issue 0020918, Study2.hdf)
520   const double projTol = minGroupTol;
521
522   bool isFaceMeshed = false;
523   SMESHDS_SubMesh* tgtFaceSM = tgtMesh->MeshElements( theShape );
524   if ( tgtFaceSM )
525   {
526     // the imported mesh is valid if all external links (encountered once)
527     // lie on geom edges
528     subShapeIDs.erase( shapeID ); // to contain edges and vertices only
529     double u, f, l;
530     for ( link2Nb = linkCount.begin(); link2Nb != linkCount.end(); ++link2Nb)
531     {
532       const TLink& link = (*link2Nb).first;
533       int nbFaces = link2Nb->second;
534       if ( nbFaces == 1 )
535       {
536         // check if a not shared link lies on face boundary
537         bool nodesOnBoundary = true;
538         list< TopoDS_Shape > bndShapes;
539         for ( int is1stN = 0; is1stN < 2 && nodesOnBoundary; ++is1stN )
540         {
541           const SMDS_MeshNode* n = is1stN ? link.node1() : link.node2();
542           if ( !subShapeIDs.count( n->getshapeId() )) // n is assigned to FACE
543           {
544             for ( size_t iE = 0; iE < edges.size(); ++iE )
545               if ( helper.CheckNodeU( edges[iE], n, u=0, projTol, /*force=*/true ))
546               {
547                 BRep_Tool::Range(edges[iE],f,l);
548                 if ( Abs(u-f) < 2 * faceTol || Abs(u-l) < 2 * faceTol )
549                   // duplicated node on vertex
550                   return error("Source elements overlap one another");
551                 tgtFaceSM->RemoveNode( n, /*isNodeDeleted=*/false );
552                 tgtMesh->SetNodeOnEdge( n, edges[iE], u );
553                 break;
554               }
555             nodesOnBoundary = subShapeIDs.count( n->getshapeId());
556           }
557           if ( nodesOnBoundary )
558           {
559             TopoDS_Shape s = helper.GetSubShapeByNode( n, tgtMesh );
560             if ( s.ShapeType() == TopAbs_VERTEX )
561               bndShapes.push_front( s ); // vertex first
562             else
563               bndShapes.push_back( s ); // edges last
564           }
565         }
566         if ( !nodesOnBoundary )
567         {
568           error("free internal link"); // just for an easier debug
569           break;
570         }
571         if ( bndShapes.front().ShapeType() == TopAbs_EDGE && // all link nodes are on EDGEs
572              bndShapes.front() != bndShapes.back() )
573           // link nodes on different geom edges
574           return error(COMPERR_BAD_INPUT_MESH, "Source nodes mismatch target vertices");
575
576         // find geom edge the link is on
577         if ( bndShapes.back().ShapeType() != TopAbs_EDGE ) // all link nodes are on VERTEXes
578         {
579           // find geom edge by two vertices
580           TopoDS_Shape geomEdge = helper.GetCommonAncestor( bndShapes.back(),
581                                                             bndShapes.front(),
582                                                             theMesh, TopAbs_EDGE );
583           if ( geomEdge.IsNull() )
584           {
585             error("free internal link");
586             break; // vertices belong to different edges
587           }
588           bndShapes.push_back( geomEdge );
589         }
590
591         // create an edge if not yet exists
592         newNodes.resize(2);
593         newNodes[0] = link.node1(), newNodes[1] = link.node2();
594         const SMDS_MeshElement* edge = tgtMesh->FindElement( newNodes, SMDSAbs_Edge );
595         if ( edge ) continue;
596
597         if ( link._reversed ) std::swap( newNodes[0], newNodes[1] );
598         if ( link._medium )
599         {
600           edge = tgtMesh->AddEdge( newNodes[0], newNodes[1], link._medium );
601
602           TopoDS_Edge geomEdge = TopoDS::Edge(bndShapes.back());
603           helper.CheckNodeU( geomEdge, link._medium, u, projTol, /*force=*/true );
604           tgtFaceSM->RemoveNode( link._medium, /*isNodeDeleted=*/false );
605           tgtMesh->SetNodeOnEdge( (SMDS_MeshNode*)link._medium, geomEdge, u );
606         }
607         else
608         {
609           edge = tgtMesh->AddEdge( newNodes[0], newNodes[1]);
610         }
611         if ( !edge )
612           return false;
613
614         tgtMesh->SetMeshElementOnShape( edge, bndShapes.back() );
615       }
616       else if ( nbFaces > 2 )
617       {
618         return error( COMPERR_BAD_INPUT_MESH, "Non-manifold source mesh");
619       }
620     }
621     isFaceMeshed = ( link2Nb == linkCount.end() && !linkCount.empty());
622     if ( isFaceMeshed )
623     {
624       // check that source faces do not overlap:
625       // there must be only two edges sharing each vertex and bound to sub-edges of theShape
626       SMESH_MeshEditor editor( &theMesh );
627       set<int>::iterator subID = subShapeIDs.begin();
628       for ( ; subID != subShapeIDs.end(); ++subID )
629       {
630         const TopoDS_Shape& s = tgtMesh->IndexToShape( *subID );
631         if ( s.ShapeType() != TopAbs_VERTEX ) continue;
632         const SMDS_MeshNode* n = SMESH_Algo::VertexNode( TopoDS::Vertex(s), tgtMesh );
633         SMDS_ElemIteratorPtr eIt = n->GetInverseElementIterator(SMDSAbs_Edge);
634         int nbEdges = 0;
635         while ( eIt->more() )
636         {
637           const SMDS_MeshElement* edge = eIt->next();
638           int sId = editor.FindShape( edge );
639           nbEdges += subShapeIDs.count( sId );
640         }
641         if ( nbEdges < 2 && !helper.IsRealSeam( s ))
642           return false; // weird
643         if ( nbEdges > 2 )
644           return error( COMPERR_BAD_INPUT_MESH, "Source elements overlap one another");
645       }
646     }
647   }
648   if ( !isFaceMeshed )
649     return error( COMPERR_BAD_INPUT_MESH,
650                   "Source elements don't cover totally the geometrical face" );
651
652   if ( helper.HasSeam() )
653   {
654     // links on seam edges are shared by two faces, so no edges were created on them
655     // by the previous detection of 2D mesh boundary
656     for ( size_t iE = 0; iE < edges.size(); ++iE )
657     {
658       if ( !helper.IsRealSeam( edges[iE] )) continue;
659       const TopoDS_Edge& seamEdge = edges[iE];
660       // to find nodes lying on the seamEdge we check nodes of mesh faces sharing a node on one
661       // of its vertices; after finding another node on seamEdge we continue the same way
662       // until finding all nodes.
663       TopoDS_Vertex      seamVertex = helper.IthVertex( 0, seamEdge );
664       const SMDS_MeshNode* vertNode = SMESH_Algo::VertexNode( seamVertex, tgtMesh );
665       set< const SMDS_MeshNode* > checkedNodes; checkedNodes.insert( vertNode );
666       set< const SMDS_MeshElement* > checkedFaces;
667       // as a face can have more than one node on the seamEdge, there is a difficulty in selecting
668       // one of those nodes to treat next; so we simply find all nodes on the seamEdge and
669       // then sort them by U on edge
670       typedef list< pair< double, const SMDS_MeshNode* > > TUNodeList;
671       TUNodeList nodesOnSeam;
672       double u = helper.GetNodeU( seamEdge, vertNode );
673       nodesOnSeam.push_back( make_pair( u, vertNode ));
674       TUNodeList::iterator u2nIt = nodesOnSeam.begin();
675       for ( ; u2nIt != nodesOnSeam.end(); ++u2nIt )
676       {
677         const SMDS_MeshNode* startNode = (*u2nIt).second;
678         SMDS_ElemIteratorPtr faceIt = startNode->GetInverseElementIterator( SMDSAbs_Face );
679         while ( faceIt->more() )
680         {
681           const SMDS_MeshElement* face = faceIt->next();
682           if ( !checkedFaces.insert( face ).second ) continue;
683           for ( int i = 0, nbNodes = face->NbCornerNodes(); i < nbNodes; ++i )
684           {
685             const SMDS_MeshNode* n = face->GetNode( i );
686             if ( n == startNode || !checkedNodes.insert( n ).second ) continue;
687             if ( helper.CheckNodeU( seamEdge, n, u=0, projTol, /*force=*/true ))
688               nodesOnSeam.push_back( make_pair( u, n ));
689           }
690         }
691       }
692       // sort the found nodes by U on the seamEdge; most probably they are in a good order,
693       // so we can use the hint to spead-up map filling
694       map< double, const SMDS_MeshNode* > u2nodeMap;
695       for ( u2nIt = nodesOnSeam.begin(); u2nIt != nodesOnSeam.end(); ++u2nIt )
696         u2nodeMap.insert( u2nodeMap.end(), *u2nIt );
697
698       // create edges
699       {
700         SMESH_MesherHelper seamHelper( theMesh );
701         seamHelper.SetSubShape( edges[ iE ]);
702         seamHelper.SetElementsOnShape( true );
703
704         if ( !checkedFaces.empty() && (*checkedFaces.begin())->IsQuadratic() )
705           for ( set< const SMDS_MeshElement* >::iterator fIt = checkedFaces.begin();
706                 fIt != checkedFaces.end(); ++fIt )
707             seamHelper.AddTLinks( static_cast<const SMDS_MeshFace*>( *fIt ));
708
709         map< double, const SMDS_MeshNode* >::iterator n1, n2, u2nEnd = u2nodeMap.end();
710         for ( n2 = u2nodeMap.begin(), n1 = n2++; n2 != u2nEnd; ++n1, ++n2 )
711         {
712           const SMDS_MeshNode* node1 = n1->second;
713           const SMDS_MeshNode* node2 = n2->second;
714           seamHelper.AddEdge( node1, node2 );
715           if ( node2->getshapeId() == helper.GetSubShapeID() )
716           {
717             tgtFaceSM->RemoveNode( node2, /*isNodeDeleted=*/false );
718             tgtMesh->SetNodeOnEdge( const_cast<SMDS_MeshNode*>( node2 ), seamEdge, n2->first );
719           }
720         }
721       }
722     } // loop on edges to find seam ones
723   } // if ( helper.HasSeam() )
724
725   // notify sub-meshes of edges on computation
726   for ( size_t iE = 0; iE < edges.size(); ++iE )
727   {
728     SMESH_subMesh * sm = theMesh.GetSubMesh( edges[iE] );
729     // if ( SMESH_Algo::isDegenerated( edges[iE] ))
730     //   sm->SetIsAlwaysComputed( true );
731     sm->ComputeStateEngine(SMESH_subMesh::CHECK_COMPUTE_STATE);
732     if ( sm->GetComputeState() != SMESH_subMesh::COMPUTE_OK )
733       return error(SMESH_Comment("Failed to create segments on the edge #") << sm->GetId());
734   }
735
736   // ============
737   // Copy meshes
738   // ============
739
740   vector<SMESH_Mesh*> srcMeshes = _sourceHyp->GetSourceMeshes();
741   for ( size_t i = 0; i < srcMeshes.size(); ++i )
742     StdMeshers_Import_1D::importMesh( srcMeshes[i], theMesh, _sourceHyp, theShape );
743
744   return true;
745 }
746
747 //=============================================================================
748 /*!
749  * \brief Set needed event listeners and create a submesh for a copied mesh
750  *
751  * This method is called only if a submesh has HYP_OK algo_state.
752  */
753 //=============================================================================
754
755 void StdMeshers_Import_1D2D::SetEventListener(SMESH_subMesh* subMesh)
756 {
757   if ( !_sourceHyp )
758   {
759     const TopoDS_Shape& tgtShape = subMesh->GetSubShape();
760     SMESH_Mesh*         tgtMesh  = subMesh->GetFather();
761     Hypothesis_Status aStatus;
762     CheckHypothesis( *tgtMesh, tgtShape, aStatus );
763   }
764   StdMeshers_Import_1D::setEventListener( subMesh, _sourceHyp );
765 }
766 void StdMeshers_Import_1D2D::SubmeshRestored(SMESH_subMesh* subMesh)
767 {
768   SetEventListener(subMesh);
769 }
770
771 //=============================================================================
772 /*!
773  * Predict nb of mesh entities created by Compute()
774  */
775 //=============================================================================
776
777 bool StdMeshers_Import_1D2D::Evaluate(SMESH_Mesh &         theMesh,
778                                       const TopoDS_Shape & theShape,
779                                       MapShapeNbElems&     aResMap)
780 {
781   if ( !_sourceHyp ) return false;
782
783   const vector<SMESH_Group*>& srcGroups = _sourceHyp->GetGroups();
784   if ( srcGroups.empty() )
785     return error("Invalid source groups");
786
787   vector<int> aVec(SMDSEntity_Last,0);
788
789   bool toCopyMesh, toCopyGroups;
790   _sourceHyp->GetCopySourceMesh(toCopyMesh, toCopyGroups);
791   if ( toCopyMesh ) // the whole mesh is copied
792   {
793     vector<SMESH_Mesh*> srcMeshes = _sourceHyp->GetSourceMeshes();
794     for ( unsigned i = 0; i < srcMeshes.size(); ++i )
795     {
796       SMESH_subMesh* sm = StdMeshers_Import_1D::getSubMeshOfCopiedMesh( theMesh, *srcMeshes[i]);
797       if ( !sm || aResMap.count( sm )) continue; // already counted
798       const SMDS_MeshInfo& aMeshInfo = srcMeshes[i]->GetMeshDS()->GetMeshInfo();
799       for (int i = 0; i < SMDSEntity_Last; i++)
800         aVec[i] = aMeshInfo.NbEntities((SMDSAbs_EntityType)i);
801     }
802   }
803   else
804   {
805     // std-like iterator used to get coordinates of nodes of mesh element
806     typedef SMDS_StdIterator< SMESH_TNodeXYZ, SMDS_ElemIteratorPtr > TXyzIterator;
807
808     SMESH_MesherHelper helper(theMesh);
809     helper.SetSubShape(theShape);
810
811     const TopoDS_Face& geomFace = TopoDS::Face( theShape );
812
813     // take into account nodes on vertices
814     TopExp_Explorer exp( theShape, TopAbs_VERTEX );
815     for ( ; exp.More(); exp.Next() )
816       theMesh.GetSubMesh( exp.Current())->Evaluate( aResMap );
817
818     // to count now many times a link between nodes encounters,
819     // negative nb additionally means that a link is quadratic
820     map<SMESH_TLink, int> linkCount;
821     map<SMESH_TLink, int>::iterator link2Nb;
822
823     // count faces and nodes imported from groups
824     set<const SMDS_MeshNode* > allNodes;
825     gp_XY uv;
826     double minGroupTol = 1e100;
827     for ( int iG = 0; iG < srcGroups.size(); ++iG )
828     {
829       const SMESHDS_GroupBase* srcGroup = srcGroups[iG]->GetGroupDS();
830       const double groupTol = 0.5 * sqrt( getMinElemSize2( srcGroup ));
831       minGroupTol = std::min( groupTol, minGroupTol );
832       SMDS_ElemIteratorPtr srcElems = srcGroup->GetElements();
833       SMDS_MeshNode *tmpNode =helper.AddNode(0,0,0);
834       while ( srcElems->more() ) // loop on group contents
835       {
836         const SMDS_MeshElement* face = srcElems->next();
837         // find out if face is located on geomEdge by projecting
838         // a gravity center of face to geomFace
839         gp_XYZ gc(0,0,0);
840         gc = accumulate( TXyzIterator(face->nodesIterator()), TXyzIterator(), gc)/face->NbNodes();
841         tmpNode->setXYZ( gc.X(), gc.Y(), gc.Z());
842         if ( helper.CheckNodeUV( geomFace, tmpNode, uv, groupTol, /*force=*/true ))
843         {
844           ++aVec[ face->GetEntityType() ];
845
846           // collect links
847           int nbConers = face->NbCornerNodes();
848           for ( int i = 0; i < face->NbNodes(); ++i )
849           {
850             const SMDS_MeshNode* n1 = face->GetNode(i);
851             allNodes.insert( n1 );
852             if ( i < nbConers )
853             {
854               const SMDS_MeshNode* n2 = face->GetNode( (i+1)%nbConers );
855               link2Nb = linkCount.insert( make_pair( SMESH_TLink( n1, n2 ), 0)).first;
856               if ( (*link2Nb).second )
857                 link2Nb->second += (link2Nb->second < 0 ) ? -1 : 1;
858               else
859                 link2Nb->second += ( face->IsQuadratic() ) ? -1 : 1;
860             }
861           }
862         }
863       }
864       helper.GetMeshDS()->RemoveNode(tmpNode);
865     }
866
867     int nbNodes = allNodes.size();
868     allNodes.clear();
869
870     // count nodes and edges on geom edges
871
872     double u;
873     for ( exp.Init(theShape, TopAbs_EDGE); exp.More(); exp.Next() )
874     {
875       TopoDS_Edge geomEdge = TopoDS::Edge( exp.Current() );
876       SMESH_subMesh* sm = theMesh.GetSubMesh( geomEdge );
877       vector<int>& edgeVec = aResMap[sm];
878       if ( edgeVec.empty() )
879       {
880         edgeVec.resize(SMDSEntity_Last,0);
881         for ( link2Nb = linkCount.begin(); link2Nb != linkCount.end(); )
882         {
883           const SMESH_TLink& link = (*link2Nb).first;
884           int nbFacesOfLink = Abs( link2Nb->second );
885           bool eraseLink = ( nbFacesOfLink != 1 );
886           if ( nbFacesOfLink == 1 )
887           {
888             if ( helper.CheckNodeU( geomEdge, link.node1(), u, minGroupTol, /*force=*/true )&&
889                  helper.CheckNodeU( geomEdge, link.node2(), u, minGroupTol, /*force=*/true ))
890             {
891               bool isQuadratic = ( link2Nb->second < 0 );
892               ++edgeVec[ isQuadratic ? SMDSEntity_Quad_Edge : SMDSEntity_Edge ];
893               ++edgeVec[ SMDSEntity_Node ];
894               --nbNodes;
895               eraseLink = true;
896             }
897           }
898           if ( eraseLink )
899             linkCount.erase(link2Nb++);
900           else
901             link2Nb++;
902         }
903         if ( edgeVec[ SMDSEntity_Node] > 0 )
904           --edgeVec[ SMDSEntity_Node ]; // for one node on vertex
905       }
906       else if ( !helper.IsSeamShape( geomEdge ) ||
907                 geomEdge.Orientation() == TopAbs_FORWARD )
908       {
909         nbNodes -= 1+edgeVec[ SMDSEntity_Node ];
910       }
911     }
912
913     aVec[SMDSEntity_Node] = nbNodes;
914   }
915
916   SMESH_subMesh * sm = theMesh.GetSubMesh(theShape);
917   aResMap.insert(make_pair(sm,aVec));
918
919   return true;
920 }