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