Salome HOME
Fix SALOME_TESTS/Grids/smesh/imps_09/K0
[modules/smesh.git] / src / SMESHUtils / SMESH_Offset.cxx
1 // Copyright (C) 2007-2019  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 // File      : SMESH_Offset.cxx
23 // Created   : Mon Dec 25 15:52:38 2017
24 // Author    : Edward AGAPOV (eap)
25
26 #include "SMESH_MeshAlgos.hxx"
27
28 #include <SMDS_PolygonalFaceOfNodes.hxx>
29 #include "SMDS_Mesh.hxx"
30
31 #include <Utils_SALOME_Exception.hxx>
32
33 #include <Bnd_B3d.hxx>
34 #include <NCollection_Map.hxx>
35 #include <gp_Lin.hxx>
36 #include <gp_Pln.hxx>
37
38 #include <boost/container/flat_set.hpp>
39 #include <boost/dynamic_bitset.hpp>
40
41 namespace
42 {
43   const int theMaxNbFaces = 256; // max number of faces sharing a node
44
45   typedef NCollection_DataMap< const SMDS_MeshNode*, const SMDS_MeshNode*, SMESH_Hasher > TNNMap;
46   typedef NCollection_Map< SMESH_Link, SMESH_Link >                                       TLinkMap;
47
48   //--------------------------------------------------------------------------------
49   /*!
50    * \brief Intersected face side storing a node created at this intersection
51    *        and a intersected face
52    */
53   struct CutLink
54   {
55     bool                     myReverse;
56     const SMDS_MeshNode*     myNode[2]; // side nodes. WARNING: don't set them directly, use Set()
57     mutable SMESH_NodeXYZ    myIntNode; // intersection node
58     const SMDS_MeshElement*  myFace;    // cutter face
59     int                      myIndex;   // index of a node on the same link
60
61     CutLink(const SMDS_MeshNode*    node1=0,
62             const SMDS_MeshNode*    node2=0,
63             const SMDS_MeshElement* face=0,
64             const int               index=0) { Set ( node1, node2, face, index ); }
65
66     void Set( const SMDS_MeshNode*    node1,
67               const SMDS_MeshNode*    node2,
68               const SMDS_MeshElement* face,
69               const int               index=0)
70     {
71       myNode[0] = node1; myNode[1] = node2; myFace = face; myIndex = index; myReverse = false;
72       if ( myNode[0] && ( myReverse = ( myNode[0]->GetID() > myNode[1]->GetID() )))
73         std::swap( myNode[0], myNode[1] );
74     }
75     const SMDS_MeshNode* IntNode() const { return myIntNode.Node(); }
76     const SMDS_MeshNode* Node1() const { return myNode[ myReverse ]; }
77     const SMDS_MeshNode* Node2() const { return myNode[ !myReverse ]; }
78
79     static Standard_Integer HashCode(const CutLink&         link,
80                                      const Standard_Integer upper)
81     {
82       Standard_Integer n = ( link.myNode[0]->GetID() +
83                              link.myNode[1]->GetID() +
84                              link.myIndex );
85       return ::HashCode( n, upper );
86     }
87     static Standard_Boolean IsEqual(const CutLink& link1, const CutLink& link2 )
88     {
89       return ( link1.myNode[0] == link2.myNode[0] &&
90                link1.myNode[1] == link2.myNode[1] &&
91                link1.myIndex == link2.myIndex );
92     }
93   };
94
95   typedef NCollection_Map< CutLink, CutLink > TCutLinkMap;
96
97   //--------------------------------------------------------------------------------
98   /*!
99    * \brief Part of a divided face edge
100    */
101   struct EdgePart
102   {
103     const SMDS_MeshNode*    myNode1;
104     const SMDS_MeshNode*    myNode2;
105     int                     myIndex; // positive -> side index, negative -> State
106     const SMDS_MeshElement* myFace;
107
108     enum State { _INTERNAL = -1, _COPLANAR = -2 };
109
110     void Set( const SMDS_MeshNode*    Node1,
111               const SMDS_MeshNode*    Node2,
112               const SMDS_MeshElement* Face = 0,
113               int                     EdgeIndex = _INTERNAL )
114     { myNode1 = Node1; myNode2 = Node2; myIndex = EdgeIndex; myFace = Face; }
115
116     // bool HasSameNode( const EdgePart& other ) { return ( myNode1 == other.myNode1 ||
117     //                                                      myNode1 == other.myNode2 ||
118     //                                                      myNode2 == other.myNode1 ||
119     //                                                      myNode2 == other.myNode2 );
120     // }
121     bool IsInternal() const { return myIndex < 0; }
122     bool IsTwin( const EdgePart& e ) const { return myNode1 == e.myNode2 && myNode2 == e.myNode1; }
123     bool IsSame( const EdgePart& e ) const {
124       return (( myNode1 == e.myNode2 && myNode2 == e.myNode1 ) ||
125               ( myNode1 == e.myNode1 && myNode2 == e.myNode2 )); }
126     bool ReplaceCoplanar( const EdgePart& e );
127     operator SMESH_Link() const { return SMESH_Link( myNode1, myNode2 ); }
128     operator gp_Vec() const { return SMESH_NodeXYZ( myNode2 ) - SMESH_NodeXYZ( myNode1 ); }
129   };
130
131   //--------------------------------------------------------------------------------
132   /*!
133    * \brief Loop of EdgePart's forming a new face which is a part of CutFace
134    */
135   struct EdgeLoop : public SMDS_PolygonalFaceOfNodes
136   {
137     std::vector< const EdgePart* > myLinks;
138     bool                           myIsBndConnected; //!< is there a path to CutFace side edges
139     bool                           myHasPending;     //!< an edge encounters twice
140
141     EdgeLoop() : SMDS_PolygonalFaceOfNodes( std::vector<const SMDS_MeshNode *>() ) {}
142     void Clear() { myLinks.clear(); myIsBndConnected = false; myHasPending = false; }
143     bool SetConnected() { bool was = myIsBndConnected; myIsBndConnected = true; return !was; }
144     size_t Contains( const SMDS_MeshNode* n ) const
145     {
146       for ( size_t i = 0; i < myLinks.size(); ++i )
147         if ( myLinks[i]->myNode1 == n ) return i + 1;
148       return 0;
149     }
150     virtual int NbNodes() const { return myLinks.size(); }
151     virtual SMDS_ElemIteratorPtr nodesIterator() const
152     {
153       return setNodes(), SMDS_PolygonalFaceOfNodes::nodesIterator();
154     }
155     virtual SMDS_NodeIteratorPtr nodeIterator() const
156     {
157       return setNodes(), SMDS_PolygonalFaceOfNodes::nodeIterator();
158     }
159     void setNodes() const //!< set nodes to SMDS_PolygonalFaceOfNodes
160     {
161       EdgeLoop* me = const_cast<EdgeLoop*>( this );
162       me->myNodes.resize( NbNodes() );
163       size_t iMin = 0;
164       for ( size_t i = 1; i < myNodes.size(); ++i ) {
165         if ( myLinks[ i ]->myNode1->GetID() < myLinks[ iMin ]->myNode1->GetID() )
166           iMin = i;
167       }
168       for ( size_t i = 0; i < myNodes.size(); ++i )
169         me->myNodes[ i ] = myLinks[ ( iMin + i ) % myNodes.size() ]->myNode1;
170     }
171   };
172
173   //--------------------------------------------------------------------------------
174   /*!
175    * \brief Set of EdgeLoop's constructed from a CutFace
176    */
177   struct EdgeLoopSet
178   {
179     std::vector< EdgeLoop >  myLoops;       //!< buffer of EdgeLoop's
180     size_t                   myNbLoops;     //!< number of constructed loops
181
182     const EdgePart*          myEdge0;       //!< & CutFace.myLinks[0]
183     size_t                   myNbUsedEdges; //!< nb of EdgePart's added to myLoops
184     boost::dynamic_bitset<>  myIsUsedEdge;  //!< is i-th EdgePart of CutFace is in any EdgeLoop
185     std::vector< EdgeLoop* > myLoopOfEdge;  //!< EdgeLoop of CutFace.myLinks[i]
186     std::vector< EdgePart* > myCandidates;  //!< EdgePart's starting at the same node
187
188     EdgeLoopSet(): myLoops(100) {}
189
190     void Init( const std::vector< EdgePart >& edges )
191     {
192       size_t nb = edges.size();
193       myEdge0 = & edges[0];
194       myNbLoops = 0;
195       myNbUsedEdges = 0;
196       myIsUsedEdge.reset();
197       myIsUsedEdge.resize( nb, false );
198       myLoopOfEdge.clear();
199       myLoopOfEdge.resize( nb, (EdgeLoop*) 0 );
200     }
201     EdgeLoop& AddNewLoop()
202     {
203       if ( ++myNbLoops >= myLoops.size() )
204         myLoops.resize( myNbLoops + 10 );
205       myLoops[ myNbLoops-1 ].Clear();
206       return myLoops[ myNbLoops-1 ];
207     }
208     bool AllEdgesUsed() const { return myNbUsedEdges == myLoopOfEdge.size(); }
209
210     bool AddEdge( EdgePart& edge )
211     {
212       size_t i = Index( edge );
213       if ( myIsUsedEdge[ i ])
214         return false;
215       myLoops[ myNbLoops-1 ].myLinks.push_back( &edge );
216       myLoopOfEdge[ i ] = & myLoops[ myNbLoops-1 ];
217       myIsUsedEdge[ i ] = true;
218       ++myNbUsedEdges;
219       return true;
220     }
221     void Erase( EdgeLoop* loop )
222     {
223       for ( size_t iE = 0; iE < loop->myLinks.size(); ++iE )
224         myLoopOfEdge[ Index( *loop->myLinks[ iE ] )] = 0;
225       loop->Clear();
226     }
227     void Join( EdgeLoop& loop1, size_t iAfterConcact,
228                EdgeLoop& loop2, size_t iFromEdge2 )
229     {
230       std::vector< const EdgePart* > linksAfterContact( loop1.myLinks.begin() + iAfterConcact,
231                                                         loop1.myLinks.end() );
232       loop1.myLinks.reserve( loop2.myLinks.size() + loop1.myLinks.size() );
233       loop1.myLinks.resize( iAfterConcact );
234       loop1.myLinks.insert( loop1.myLinks.end(),
235                             loop2.myLinks.begin() + iFromEdge2, loop2.myLinks.end() );
236       loop1.myLinks.insert( loop1.myLinks.end(),
237                             loop2.myLinks.begin(), loop2.myLinks.begin() + iFromEdge2 );
238       loop1.myLinks.insert( loop1.myLinks.end(),
239                             linksAfterContact.begin(), linksAfterContact.end() );
240       loop1.myIsBndConnected = loop2.myIsBndConnected;
241       loop2.Clear();
242       for ( size_t iE = 0; iE < loop1.myLinks.size(); ++iE )
243         myLoopOfEdge[ Index( *loop1.myLinks[ iE ] )] = & loop1;
244     }
245     size_t    Index( const EdgePart& edge ) const { return &edge - myEdge0; }
246     EdgeLoop* GetLoopOf( const EdgePart* edge ) { return myLoopOfEdge[ Index( *edge )]; }
247   };
248
249   //--------------------------------------------------------------------------------
250   /*!
251    * \brief Intersections of a face
252    */
253   struct CutFace
254   {
255     mutable std::vector< EdgePart > myLinks;
256     const SMDS_MeshElement*         myInitFace;
257
258     CutFace( const SMDS_MeshElement* face ): myInitFace( face ) {}
259     void AddEdge( const CutLink&          p1,
260                   const CutLink&          p2,
261                   const SMDS_MeshElement* cutter,
262                   const int               nbOnPlane,
263                   const int               iNotOnPlane = -1) const;
264     void AddPoint( const CutLink& p1, const CutLink& p2, double tol ) const;
265     bool ReplaceNodes( const TNNMap& theRm2KeepMap ) const;
266     bool IsCut() const;
267     int  NbInternalEdges() const;
268     void MakeLoops( EdgeLoopSet& loops, const gp_XYZ& theFaceNorm ) const;
269     bool RemoveInternalLoops( EdgeLoopSet& theLoops ) const;
270     void CutOffLoops( EdgeLoopSet&                 theLoops,
271                       const double                 theSign,
272                       const std::vector< gp_XYZ >& theNormals,
273                       std::vector< EdgePart >&     theCutOffLinks,
274                       TLinkMap&                    theCutOffCoplanarLinks) const;
275     void InitLinks() const;
276     bool IsCoplanar( const EdgePart* edge ) const;
277
278     static Standard_Integer HashCode(const CutFace& f, const Standard_Integer upper)
279     {
280       return ::HashCode( f.myInitFace->GetID(), upper );
281     }
282     static Standard_Boolean IsEqual(const CutFace& f1, const CutFace& f2 )
283     {
284       return f1.myInitFace == f2.myInitFace;
285     }
286     void Dump() const;
287
288   private:
289
290     EdgePart* getTwin( const EdgePart* edge ) const;
291   };
292
293   typedef NCollection_Map< CutFace, CutFace > TCutFaceMap;
294
295   //--------------------------------------------------------------------------------
296   /*!
297    * \brief Intersection point of two edges of co-planar triangles
298    */
299   struct IntPoint2D
300   {
301     size_t        myEdgeInd[2]; //!< edge indices of triangles
302     double        myU      [2]; //!< parameter [0,1] on edges of triangles
303     SMESH_NodeXYZ myNode;       //!< intersection node
304     bool          myIsCollinear;//!< edges are collinear
305
306     IntPoint2D() : myIsCollinear( false ) {}
307
308     void InitLink( CutLink& link, int iFace, const std::vector< SMESH_NodeXYZ >& nodes ) const
309     {
310       link.Set( nodes[  myEdgeInd[ iFace ]                      ].Node(),
311                 nodes[( myEdgeInd[ iFace ] + 1 ) % nodes.size() ].Node(),
312                 link.myFace );
313       link.myIntNode = myNode;
314     }
315     const SMDS_MeshNode* Node() const { return myNode.Node(); }
316   };
317   struct IntPoint2DCompare
318   {
319     int myI;
320     IntPoint2DCompare( int iFace=0 ): myI( iFace ) {}
321     bool operator() ( const IntPoint2D* ip1, const IntPoint2D* ip2 ) const
322     {
323       return ip1->myU[ myI ] < ip2->myU[ myI ];
324     }
325     bool operator() ( const IntPoint2D& ip1, const IntPoint2D& ip2 ) const
326     {
327       return ip1.myU[ myI ] < ip2.myU[ myI ];
328     }
329   };
330   typedef boost::container::flat_set< IntPoint2D, IntPoint2DCompare >  TIntPointSet;
331   typedef boost::container::flat_set< IntPoint2D*, IntPoint2DCompare > TIntPointPtrSet;
332
333   //--------------------------------------------------------------------------------
334   /*!
335    * \brief Face used to find translated position of the node
336    */
337   struct Face
338   {
339     const SMDS_MeshElement* myFace;
340     SMESH_TNodeXYZ          myNode1; //!< nodes neighboring another node of myFace
341     SMESH_TNodeXYZ          myNode2;
342     const gp_XYZ*           myNorm;
343     bool                    myNodeRightOrder;
344     void operator=(const SMDS_MeshElement* f) { myFace = f; }
345     const SMDS_MeshElement* operator->() { return myFace; }
346     void SetNodes( int i0, int i1 ) //!< set myNode's
347     {
348       myNode1.Set( myFace->GetNode( i1 ));
349       int i2 = ( i0 - 1 + myFace->NbCornerNodes() ) % myFace->NbCornerNodes();
350       if ( i2 == i1 )
351         i2 = ( i0 + 1 ) % myFace->NbCornerNodes();
352       myNode2.Set( myFace->GetNode( i2 ));
353       myNodeRightOrder = ( Abs( i2-i1 ) == 1 ) ?  i2 > i1  :  i2 < i1;
354     }
355     void SetOldNodes( const SMDS_Mesh& theSrcMesh )
356     {
357       myNode1.Set( theSrcMesh.FindNode( myNode1->GetID() ));
358       myNode2.Set( theSrcMesh.FindNode( myNode2->GetID() ));
359     }
360     bool SetNormal( const std::vector< gp_XYZ >& faceNormals )
361     {
362       myNorm = & faceNormals[ myFace->GetID() ];
363       return ( myNorm->SquareModulus() > gp::Resolution() * gp::Resolution() );
364     }
365     const gp_XYZ& Norm() const { return *myNorm; }
366   };
367
368   //--------------------------------------------------------------------------------
369   /*!
370    * \brief Offset plane used to find translated position of the node
371    */
372   struct OffsetPlane
373   {
374     gp_XYZ myNode;
375     Face*  myFace;
376     gp_Pln myPln;
377     gp_Lin myLines[2]; //!< line of intersection with neighbor OffsetPlane's
378     bool   myIsLineOk[2];
379     double myWeight[2];
380
381     void   Init( const gp_XYZ& node, Face& tria, double offset )
382     {
383       myNode = node;
384       myFace = & tria;
385       myPln  = gp_Pln( node + tria.Norm() * offset, tria.Norm() );
386       myIsLineOk[0] = myIsLineOk[1] = false;
387       myWeight[0] = myWeight[1] = 0;
388     }
389     bool   ComputeIntersectionLine( OffsetPlane& pln );
390     void   SetSkewLine( const gp_Lin& line );
391     gp_XYZ GetCommonPoint( int & nbOkPoints, double& sumWeight );
392     gp_XYZ ProjectNodeOnLine( int & nbOkPoints );
393     double Weight() const { return myWeight[0] + myWeight[1]; }
394   };
395
396   //================================================================================
397   /*!
398    * \brief Set the second line
399    */
400   //================================================================================
401
402   void OffsetPlane::SetSkewLine( const gp_Lin& line )
403   {
404     myLines[1] = line;
405     gp_XYZ n = myLines[0].Direction().XYZ() ^ myLines[1].Direction().XYZ();
406     if (( myIsLineOk[1] = n.SquareModulus() > gp::Resolution() ))
407       myPln = gp_Pln( myPln.Location(), n );
408   }
409
410   //================================================================================
411   /*!
412    * \brief Project myNode on myLine[0]
413    */
414   //================================================================================
415
416   gp_XYZ OffsetPlane::ProjectNodeOnLine( int & nbOkPoints )
417   {
418     gp_XYZ p = gp::Origin().XYZ();
419     if ( myIsLineOk[0] )
420     {
421       gp_Vec l2n( myLines[0].Location(), myNode );
422       double u = l2n * myLines[0].Direction();
423       p = myLines[0].Location().XYZ() + u * myLines[0].Direction().XYZ();
424       ++nbOkPoints;
425     }
426     return p;
427   }
428
429   //================================================================================
430   /*!
431    * \brief Computes intersection point of myLines
432    */
433   //================================================================================
434
435   gp_XYZ OffsetPlane::GetCommonPoint( int & nbOkPoints, double& sumWeight )
436   {
437     if ( !myIsLineOk[0] || !myIsLineOk[1] )
438     {
439       // sumWeight += myWeight[0];
440       // return ProjectNodeOnLine( nbOkPoints ) * myWeight[0];
441       return gp::Origin().XYZ();
442     }
443
444     gp_XYZ p;
445
446     gp_Vec lPerp0 = myLines[0].Direction().XYZ() ^ myPln.Axis().Direction().XYZ();
447     double  dot01 = lPerp0 * myLines[1].Direction().XYZ();
448     if ( Abs( dot01 ) > 0.05 )
449     {
450       gp_Vec l0l1 = myLines[1].Location().XYZ() - myLines[0].Location().XYZ();
451       double   u1 = - ( lPerp0 * l0l1 ) / dot01;
452       p = ( myLines[1].Location().XYZ() + myLines[1].Direction().XYZ() * u1 );
453     }
454     else
455     {
456       gp_Vec  lv0( myLines[0].Location(), myNode),  lv1(myLines[1].Location(), myNode );
457       double dot0( lv0 * myLines[0].Direction() ), dot1( lv1 * myLines[1].Direction() );
458       p  = 0.5 * ( myLines[0].Location().XYZ() + myLines[0].Direction().XYZ() * dot0 );
459       p += 0.5 * ( myLines[1].Location().XYZ() + myLines[1].Direction().XYZ() * dot1 );
460     }
461
462     sumWeight += Weight();
463     ++nbOkPoints;
464
465     return p * Weight();
466   }
467
468   //================================================================================
469   /*!
470    * \brief Compute line of intersection of 2 planes
471    */
472   //================================================================================
473
474   bool OffsetPlane::ComputeIntersectionLine( OffsetPlane& theNextPln )
475   {
476     const gp_XYZ& n1 = myFace->Norm();
477     const gp_XYZ& n2 = theNextPln.myFace->Norm();
478
479     gp_XYZ lineDir = n1 ^ n2;
480     gp_Pnt linePos;
481
482     double x = Abs( lineDir.X() );
483     double y = Abs( lineDir.Y() );
484     double z = Abs( lineDir.Z() );
485
486     int cooMax; // max coordinate
487     if (x > y) {
488       if (x > z) cooMax = 1;
489       else       cooMax = 3;
490     }
491     else {
492       if (y > z) cooMax = 2;
493       else       cooMax = 3;
494     }
495
496     bool ok = true;
497     if ( Abs( lineDir.Coord( cooMax )) < 0.05 )
498     {
499       // parallel planes - intersection is an offset of the common edge
500       linePos  = 0.5 * ( myPln.Location().XYZ() + theNextPln.myPln.Location().XYZ() );
501       lineDir  = myNode - myFace->myNode2;
502       ok       = false;
503       myWeight[0] = 0;
504     }
505     else
506     {
507       // the constants in the 2 plane equations
508       double d1 = - ( n1 * myPln.Location().XYZ() );
509       double d2 = - ( n2 * theNextPln.myPln.Location().XYZ() );
510
511       switch ( cooMax ) {
512       case 1:
513         linePos.SetX(  0 );
514         linePos.SetY(( d2*n1.Z() - d1*n2.Z()) / lineDir.X() );
515         linePos.SetZ(( d1*n2.Y() - d2*n1.Y()) / lineDir.X() );
516         break;
517       case 2:
518         linePos.SetX(( d1*n2.Z() - d2*n1.Z()) / lineDir.Y() );
519         linePos.SetY(  0 );
520         linePos.SetZ(( d2*n1.X() - d1*n2.X()) / lineDir.Y() );
521         break;
522       case 3:
523         linePos.SetX(( d2*n1.Y() - d1*n2.Y()) / lineDir.Z() );
524         linePos.SetY(( d1*n2.X() - d2*n1.X()) / lineDir.Z() );
525         linePos.SetZ(  0 );
526       }
527       myWeight[0] = lineDir.SquareModulus();
528       if ( n1 * n2 < 0 )
529         myWeight[0] = 2. - myWeight[0];
530     }
531     myLines   [ 0 ].SetDirection( lineDir );
532     myLines   [ 0 ].SetLocation ( linePos );
533     myIsLineOk[ 0 ] = ok;
534
535     theNextPln.myLines   [ 1 ] = myLines[ 0 ];
536     theNextPln.myIsLineOk[ 1 ] = ok;
537     theNextPln.myWeight  [ 1 ] = myWeight[ 0 ];
538
539     return ok;
540   }
541
542   //================================================================================
543   /*!
544    * \brief Return a translated position of a node
545    *  \param [in] new2OldNodes - new and old nodes
546    *  \param [in] faceNormals - normals to input faces
547    *  \param [in] theSrcMesh - initial mesh
548    *  \param [in] theNewPos - a computed normal
549    *  \return bool - true if theNewPos is computed
550    */
551   //================================================================================
552
553   bool getTranslatedPosition( const SMDS_MeshNode*         theNewNode,
554                               const double                 theOffset,
555                               const double                 theTol,
556                               const double                 theSign,
557                               const std::vector< gp_XYZ >& theFaceNormals,
558                               SMDS_Mesh&                   theSrcMesh,
559                               gp_XYZ&                      theNewPos)
560   {
561     bool useOneNormal = true;
562
563     // check if theNewNode needs an average position, i.e. theNewNode is convex
564     // SMDS_ElemIteratorPtr faceIt = theNewNode->GetInverseElementIterator();
565     // const SMDS_MeshElement*  f0 = faceIt->next();
566     // const gp_XYZ&         norm0 = theFaceNormals[ f0->GetID() ];
567     // const SMESH_NodeXYZ nodePos = theNewNode;
568     // while ( faceIt->more() )
569     // {
570     //   const SMDS_MeshElement* f = faceIt->next();
571     //   const int         nodeInd = f->GetNodeIndex( theNewNode );
572     //   SMESH_NodeXYZ    nodePos2 = f->GetWrapNode( nodeInd + 1 );
573     //   try {
574     //     const gp_XYZ      nnDir = ( nodePos2 - nodePos ).Normalized();
575     //   }
576     //   catch {
577     //     continue;
578     //   }
579     //   const double dot = norm0 * nnDir;
580     //   bool isConvex = 
581
582
583
584     // get faces surrounding theNewNode and sort them
585     Face faces[ theMaxNbFaces ];
586     SMDS_ElemIteratorPtr faceIt = theNewNode->GetInverseElementIterator();
587     faces[0] = faceIt->next();
588     while ( !faces[0].SetNormal( theFaceNormals ) && faceIt->more() )
589       faces[0] = faceIt->next();
590     int i0 = faces[0]->GetNodeIndex( theNewNode );
591     int i1 = ( i0 + 1 ) % faces[0]->NbCornerNodes();
592     faces[0].SetNodes( i0, i1 );
593     TIDSortedElemSet elemSet, avoidSet;
594     int iFace = 0;
595     const SMDS_MeshElement* f;
596     for ( ; faceIt->more() && iFace < theMaxNbFaces; faceIt->next() )
597     {
598       avoidSet.insert( faces[ iFace ].myFace );
599       f = SMESH_MeshAlgos::FindFaceInSet( theNewNode, faces[ iFace ].myNode2.Node(),
600                                           elemSet, avoidSet, &i0, &i1 );
601       if ( !f )
602       {
603         std::reverse( &faces[0], &faces[0] + iFace + 1 );
604         for ( int i = 0; i <= iFace; ++i )
605         {
606           std::swap( faces[i].myNode1, faces[i].myNode2 );
607           faces[i].myNodeRightOrder = !faces[i].myNodeRightOrder;
608         }
609         f = SMESH_MeshAlgos::FindFaceInSet( theNewNode, faces[ iFace ].myNode2.Node(),
610                                             elemSet, avoidSet, &i0, &i1 );
611         if ( !f )
612           break;
613       }
614       faces[ ++iFace ] = f;
615       faces[ iFace ].SetNodes( i0, i1 );
616       faces[ iFace ].SetNormal( theFaceNormals );
617     }
618     int nbFaces = iFace + 1;
619
620     theNewPos.SetCoord( 0, 0, 0 );
621     gp_XYZ oldXYZ = SMESH_NodeXYZ( theNewNode );
622
623     // check if all faces are co-planar
624     bool isPlanar = true;
625     const double tol = 1e-2;
626     for ( int i = 1; i < nbFaces &&  isPlanar;  ++i )
627       isPlanar = ( faces[i].Norm() - faces[i-1].Norm() ).SquareModulus() < tol*tol;
628
629     if ( isPlanar )
630     {
631       theNewPos = oldXYZ + faces[0].Norm() * theOffset;
632       return useOneNormal;
633     }
634
635     // prepare OffsetPlane's
636     OffsetPlane pln[ theMaxNbFaces ];
637     for ( int i = 0; i < nbFaces; ++i )
638     {
639       faces[i].SetOldNodes( theSrcMesh );
640       pln[i].Init( oldXYZ, faces[i], theOffset );
641     }
642     // intersect neighboring OffsetPlane's
643     int nbOkPoints = 0;
644     for ( int i = 1; i < nbFaces; ++i )
645       nbOkPoints += pln[ i-1 ].ComputeIntersectionLine( pln[ i ]);
646     nbOkPoints += pln[ nbFaces-1 ].ComputeIntersectionLine( pln[ 0 ]);
647
648     // move intersection lines to over parallel planes
649     if ( nbOkPoints > 1 )
650       for ( int i = 0; i < nbFaces; ++i )
651         if ( pln[i].myIsLineOk[0] && !pln[i].myIsLineOk[1] )
652           for ( int j = 1; j < nbFaces &&  !pln[i].myIsLineOk[1]; ++j )
653           {
654             int i2 = ( i + j ) % nbFaces;
655             if ( pln[i2].myIsLineOk[0] )
656               pln[i].SetSkewLine( pln[i2].myLines[0] );
657           }
658
659     // get the translated position
660     nbOkPoints = 0;
661     double sumWegith = 0;
662     const double minWeight = Sin( 30 * M_PI / 180. ) * Sin( 30 * M_PI / 180. );
663     for ( int i = 0; i < nbFaces; ++i )
664       if ( pln[ i ].Weight() > minWeight )
665         theNewPos += pln[ i ].GetCommonPoint( nbOkPoints, sumWegith );
666
667     if ( nbOkPoints == 0 )
668     {
669       // there is only one feature edge;
670       // find the theNewPos by projecting oldXYZ to any intersection line
671       for ( int i = 0; i < nbFaces; ++i )
672         theNewPos += pln[ i ].ProjectNodeOnLine( nbOkPoints );
673
674       if ( nbOkPoints == 0 )
675       {
676         theNewPos = oldXYZ + faces[0].Norm() * theOffset;
677         return useOneNormal;
678       }
679       sumWegith = nbOkPoints;
680     }
681     theNewPos /= sumWegith;
682
683
684     // mark theNewNode if it is concave
685     useOneNormal = false;
686     gp_Vec moveVec( oldXYZ, theNewPos );
687     for ( int i = 0, iPrev = nbFaces-1; i < nbFaces; iPrev = i++ )
688     {
689       gp_Vec nodeVec( oldXYZ, faces[ i ].myNode1 );
690       double u = ( moveVec * nodeVec ) / nodeVec.SquareMagnitude();
691       if ( u > 0.5 ) // param [0,1] on nodeVec
692       {
693         theNewNode->setIsMarked( true );
694       }
695       if ( !useOneNormal )
696       {
697         gp_XYZ inFaceVec = faces[ i ].Norm() ^ nodeVec.XYZ();
698         double       dot = inFaceVec * faces[ iPrev ].Norm();
699         if ( !faces[ i ].myNodeRightOrder )
700           dot *= -1;
701         if ( dot * theSign < 0 )
702         {
703           gp_XYZ p1 = oldXYZ + faces[ i ].Norm()     * theOffset;
704           gp_XYZ p2 = oldXYZ + faces[ iPrev ].Norm() * theOffset;
705           useOneNormal = ( p1 - p2 ).SquareModulus() > 1e-12;
706         }
707       }
708       if ( useOneNormal && theNewNode->isMarked() )
709         break;
710     }
711
712     return useOneNormal;
713   }
714
715 } // namespace
716
717 namespace SMESH_MeshAlgos
718 {
719   //--------------------------------------------------------------------------------
720   /*!
721    * \brief Intersect faces of a mesh
722    */
723   struct Intersector::Algo
724   {
725     SMDS_Mesh*                   myMesh;
726     double                       myTol, myEps;
727     const std::vector< gp_XYZ >& myNormals;
728     TCutLinkMap                  myCutLinks; //!< assure sharing of new nodes
729     TCutFaceMap                  myCutFaces;
730     TNNMap                       myRemove2KeepNodes; //!< node merge map
731
732     // data to intersect 2 faces
733     const SMDS_MeshElement*      myFace1;
734     const SMDS_MeshElement*      myFace2;
735     std::vector< SMESH_NodeXYZ > myNodes1, myNodes2;
736     std::vector< double >        myDist1,  myDist2;
737     int                          myInd1, myInd2; // coordinate indices on an axis-aligned plane
738     int                          myNbOnPlane1, myNbOnPlane2;
739     TIntPointSet                 myIntPointSet;
740
741     Algo( SMDS_Mesh* mesh, double tol, const std::vector< gp_XYZ >& normals )
742       : myMesh( mesh ),
743         myTol( tol ),
744         myEps( 1e-100 ),
745         //myEps( Sqrt( std::numeric_limits<double>::min() )),
746         //myEps( gp::Resolution() ),
747         myNormals( normals )
748     {}
749     void Cut( const SMDS_MeshElement* face1,
750               const SMDS_MeshElement* face2,
751               const int               nbCommonNodes );
752     void Cut( const SMDS_MeshElement* face,
753               SMESH_NodeXYZ&          lineEnd1,
754               int                     edgeIndex1,
755               SMESH_NodeXYZ&          lineEnd2,
756               int                     edgeIndex2 );
757     void MakeNewFaces( TElemIntPairVec& theNew2OldFaces,
758                        TNodeIntPairVec& theNew2OldNodes,
759                        const double     theSign,
760                        const bool       theOptimize );
761
762     //! Cut a face by planes, whose normals point to parts to keep
763     bool CutByPlanes(const SMDS_MeshElement*        face,
764                      const std::vector< gp_Ax1 > &  planes,
765                      std::vector< SMESH_NodeXYZ > & newConnectivity );
766
767   private:
768
769     bool isPlaneIntersected( const gp_XYZ&                       n2,
770                              const double                        d2,
771                              const std::vector< SMESH_NodeXYZ >& nodes1,
772                              std::vector< double > &             dist1,
773                              int &                               nbOnPlane1,
774                              int &                               iNotOnPlane1);
775     void computeIntervals( const std::vector< SMESH_NodeXYZ >& nodes,
776                            const std::vector< double >&        dist,
777                            const int                           nbOnPln,
778                            const int                           iMaxCoo,
779                            double *                            u,
780                            int*                                iE);
781     void cutCoplanar();
782     void addLink ( CutLink& link );
783     bool findLink( CutLink& link );
784     bool coincide( const gp_XYZ& p1, const gp_XYZ& p2, const double tol ) const
785     {
786       return ( p1 - p2 ).SquareModulus() < tol * tol;
787     }
788     gp_XY p2D( const gp_XYZ& p ) const { return gp_XY( p.Coord( myInd1 ), p.Coord( myInd2 )); }
789
790     void intersectLink( const std::vector< SMESH_NodeXYZ >& nodes1,
791                         const std::vector< double > &       dist1,
792                         const int                           iEdge1,
793                         const SMDS_MeshElement*             face2,
794                         CutLink&                            link1);
795     void findIntPointOnPlane( const std::vector< SMESH_NodeXYZ >& nodes,
796                               const std::vector< double > &       dist,
797                               CutLink&                            link );
798     void replaceIntNode( const SMDS_MeshNode* nToKeep, const SMDS_MeshNode* nToRemove );
799     void computeIntPoint( const double           u1,
800                           const double           u2,
801                           const int              iE1,
802                           const int              iE2,
803                           CutLink &              link,
804                           const SMDS_MeshNode* & node1,
805                           const SMDS_MeshNode* & node2);
806     void cutCollinearLink( const int                           iNotOnPlane1,
807                            const std::vector< SMESH_NodeXYZ >& nodes1,
808                            const SMDS_MeshElement*             face2,
809                            const CutLink&                      link1,
810                            const CutLink&                      link2);
811     void setPlaneIndices( const gp_XYZ& planeNorm );
812     bool intersectEdgeEdge( const gp_XY s1p0, const gp_XY s1p1,
813                             const gp_XY s2p0, const gp_XY s2p1,
814                             double &    t1,   double &    t2,
815                             bool &      isCollinear  );
816     bool intersectEdgeEdge( int iE1, int iE2, IntPoint2D& intPoint );
817     bool isPointInTriangle( const gp_XYZ& p, const std::vector< SMESH_NodeXYZ >& nodes );
818     void intersectNewEdges( const CutFace& theCFace );
819     const SMDS_MeshNode* createNode( const gp_XYZ& p );
820   };
821
822   //================================================================================
823   /*!
824    * \brief Return coordinate index with maximal abs value
825    */
826   //================================================================================
827
828   int MaxIndex( const gp_XYZ& x )
829   {
830     int iMaxCoo = ( Abs( x.X()) < Abs( x.Y() )) + 1;
831     if ( Abs( x.Coord( iMaxCoo )) < Abs( x.Z() ))
832       iMaxCoo = 3;
833     return iMaxCoo;
834   }
835   //================================================================================
836   /*!
837    * \brief Store a CutLink
838    */
839   //================================================================================
840
841   const SMDS_MeshNode* Intersector::Algo::createNode( const gp_XYZ& p )
842   {
843     const SMDS_MeshNode* n = myMesh->AddNode( p.X(), p.Y(), p.Z() );
844     n->setIsMarked( true ); // cut nodes are marked
845     return n;
846   }
847
848   //================================================================================
849   /*!
850    * \brief Store a CutLink
851    */
852   //================================================================================
853
854   void Intersector::Algo::addLink( CutLink& link )
855   {
856     link.myIndex = 0;
857     const CutLink* added = & myCutLinks.Added( link );
858     while ( added->myIntNode.Node() != link.myIntNode.Node() )
859     {
860       if ( !added->myIntNode )
861       {
862         added->myIntNode = link.myIntNode;
863         break;
864       }
865       else
866       {
867         link.myIndex++;
868         added = & myCutLinks.Added( link );
869       }
870     }
871     link.myIndex = 0;
872   }
873
874   //================================================================================
875   /*!
876    * \brief Find a CutLink with an intersection point coincident with that of a given link
877    */
878   //================================================================================
879
880   bool Intersector::Algo::findLink( CutLink& link )
881   {
882     link.myIndex = 0;
883     while ( myCutLinks.Contains( link ))
884     {
885       const CutLink* added = & myCutLinks.Added( link );
886       if ( !!added->myIntNode && coincide( added->myIntNode, link.myIntNode, myTol ))
887       {
888         link.myIntNode = added->myIntNode;
889         return true;
890       }
891       link.myIndex++;
892     }
893     return false;
894   }
895
896   //================================================================================
897   /*!
898    * \brief Check if a triangle intersects the plane of another triangle
899    *  \param [in] nodes1 - nodes of triangle 1
900    *  \param [in] n2 - normal of triangle 2
901    *  \param [in] d2 - a constant of the plane equation 2
902    *  \param [out] dist1 - distance of nodes1 from the plane 2
903    *  \param [out] nbOnPlane - number of nodes1 lying on the plane 2
904    *  \return bool - true if the triangle intersects the plane 2
905    */
906   //================================================================================
907
908   bool Intersector::Algo::isPlaneIntersected( const gp_XYZ&                       n2,
909                                               const double                        d2,
910                                               const std::vector< SMESH_NodeXYZ >& nodes1,
911                                               std::vector< double > &             dist1,
912                                               int &                               nbOnPlane1,
913                                               int &                               iNotOnPlane1)
914   {
915     iNotOnPlane1 = nbOnPlane1 = 0;
916     dist1.resize( nodes1.size() );
917     for ( size_t i = 0; i < nodes1.size(); ++i )
918     {
919       dist1[i] = n2 * nodes1[i] + d2;
920       if ( Abs( dist1[i] ) < myTol )
921       {
922         ++nbOnPlane1;
923         dist1[i] = 0.;
924       }
925       else
926       {
927         iNotOnPlane1 = i;
928       }
929     }
930     if ( nbOnPlane1 == 0 )
931       for ( size_t i = 0; i < nodes1.size(); ++i )
932         if ( dist1[iNotOnPlane1] * dist1[i] < 0 )
933           return true;
934
935     return nbOnPlane1;
936   }
937
938   //================================================================================
939   /*!
940    * \brief Compute parameters on the plane intersection line of intersections
941    *        of edges of a triangle
942    *  \param [in] nodes - triangle nodes
943    *  \param [in] dist - distance of triangle nodes from the plane of another triangle
944    *  \param [in] nbOnPln - number of nodes lying on the plane of another triangle
945    *  \param [in] iMaxCoo - index of coordinate of max component of the plane intersection line
946    *  \param [out] u - two computed parameters on the plane intersection line
947    *  \param [out] iE - indices of intersected edges
948    */
949   //================================================================================
950
951   void Intersector::Algo::computeIntervals( const std::vector< SMESH_NodeXYZ >& nodes,
952                                             const std::vector< double >&        dist,
953                                             const int                           nbOnPln,
954                                             const int                           iMaxCoo,
955                                             double *                            u,
956                                             int*                                iE)
957   {
958     if ( nbOnPln == 3 )
959     {
960       u[0] = u[1] = 1e+100;
961       return;
962     }
963     int nb = 0;
964     int i1 = 2, i2 = 0;
965     if ( nbOnPln == 1 && ( dist[i1] == 0. || dist[i2] == 0 ))
966     {
967       int i = dist[i1] == 0 ? i1 : i2;
968       u [ 1 ] = nodes[ i ].Coord( iMaxCoo );
969       iE[ 1 ] = i;
970       i1 = i2++;
971     }
972     for ( ; i2 < 3 && nb < 2;  i1 = i2++ )
973     {
974       double dd = dist[i1] - dist[i2];
975       if ( dd != 0. && dist[i2] * dist[i1] <= 0. )
976       {
977         double x1 = nodes[i1].Coord( iMaxCoo );
978         double x2 = nodes[i2].Coord( iMaxCoo );
979         u [ nb ] = x1 + ( x2 - x1 ) * dist[i1] / dd;
980         iE[ nb ] = i1;
981         ++nb;
982       }
983     }
984     if ( u[0] > u[1] )
985     {
986       std::swap( u [0], u [1] );
987       std::swap( iE[0], iE[1] );
988     }
989   }
990
991   //================================================================================
992   /*!
993    * \brief Try to find an intersection node on a link collinear with the plane intersection line
994    */
995   //================================================================================
996
997   void Intersector::Algo::findIntPointOnPlane( const std::vector< SMESH_NodeXYZ >& nodes,
998                                                const std::vector< double > &       dist,
999                                                CutLink&                            link )
1000   {
1001     int i1 = ( dist[0] == 0 ? 0 : 1 ), i2 = ( dist[2] == 0 ? 2 : 1 );
1002     CutLink link2 = link;
1003     link2.Set( nodes[i1].Node(), nodes[i2].Node(), 0 );
1004     if ( findLink( link2 ))
1005       link.myIntNode = link2.myIntNode;
1006   }
1007
1008   //================================================================================
1009   /*!
1010    * \brief Compute intersection point of a link1 with a face2
1011    */
1012   //================================================================================
1013
1014   void Intersector::Algo::intersectLink( const std::vector< SMESH_NodeXYZ >& nodes1,
1015                                          const std::vector< double > &       dist1,
1016                                          const int                           iEdge1,
1017                                          const SMDS_MeshElement*             face2,
1018                                          CutLink&                            link1)
1019   {
1020     const int iEdge2 = ( iEdge1 + 1 ) % nodes1.size();
1021     const SMESH_NodeXYZ& p1 = nodes1[ iEdge1 ];
1022     const SMESH_NodeXYZ& p2 = nodes1[ iEdge2 ];
1023
1024     link1.Set( p1.Node(), p2.Node(), face2 );
1025     const CutLink* link = & myCutLinks.Added( link1 );
1026     if ( !link->IntNode() )
1027     {
1028       if      ( dist1[ iEdge1 ] == 0. ) link1.myIntNode = p1;
1029       else if ( dist1[ iEdge2 ] == 0. ) link1.myIntNode = p2;
1030       else
1031       {
1032         gp_XYZ p = p1 + ( p2 - p1 ) * dist1[ iEdge1 ] / ( dist1[ iEdge1 ] - dist1[ iEdge2 ]);
1033         (gp_XYZ&)link1.myIntNode = p;
1034       }
1035     }
1036     else
1037     {
1038       gp_XYZ p = p1 + ( p2 - p1 ) * dist1[ iEdge1 ] / ( dist1[ iEdge1 ] - dist1[ iEdge2 ]);
1039       while ( link->IntNode() )
1040       {
1041         if ( coincide( p, link->myIntNode, myTol ))
1042         {
1043           link1.myIntNode = link->myIntNode;
1044           break;
1045         }
1046         link1.myIndex++;
1047         link = & myCutLinks.Added( link1 );
1048       }
1049       if ( !link1.IntNode() )
1050       {
1051         if      ( dist1[ iEdge1 ] == 0. ) link1.myIntNode = p1;
1052         else if ( dist1[ iEdge2 ] == 0. ) link1.myIntNode = p2;
1053         else                     (gp_XYZ&)link1.myIntNode = p;
1054       }
1055     }
1056   }
1057
1058   //================================================================================
1059   /*!
1060    * \brief Store node replacement in myCutFaces
1061    */
1062   //================================================================================
1063
1064   void Intersector::Algo::replaceIntNode( const SMDS_MeshNode* nToKeep,
1065                                           const SMDS_MeshNode* nToRemove )
1066   {
1067     if ( nToKeep == nToRemove )
1068       return;
1069     if ( nToRemove->GetID() < nToKeep->GetID() ) // keep node with lower ID
1070       myRemove2KeepNodes.Bind( nToKeep, nToRemove );
1071     else
1072       myRemove2KeepNodes.Bind( nToRemove, nToKeep );
1073   }
1074
1075   //================================================================================
1076   /*!
1077    * \brief Compute intersection point on a link of either of faces by choosing
1078    *        a link whose parameter on the intersection line in maximal
1079    *  \param [in] u1 - parameter on the intersection line of link iE1 of myFace1
1080    *  \param [in] u2 - parameter on the intersection line of link iE2 of myFace2
1081    *  \param [in] iE1 - index of a link myFace1
1082    *  \param [in] iE2 - index of a link myFace2
1083    *  \param [out] link - CutLink storing the intersection point
1084    *  \param [out] node1 - a node of the 2nd link if two links intersect
1085    *  \param [out] node2 - a node of the 2nd link if two links intersect
1086    */
1087   //================================================================================
1088
1089   void Intersector::Algo::computeIntPoint( const double           u1,
1090                                            const double           u2,
1091                                            const int              iE1,
1092                                            const int              iE2,
1093                                            CutLink &              link,
1094                                            const SMDS_MeshNode* & node1,
1095                                            const SMDS_MeshNode* & node2)
1096   {
1097     if      ( u1 > u2 + myTol )
1098     {
1099       intersectLink( myNodes1, myDist1, iE1, myFace2, link );
1100       node1 = node2 = 0;
1101       if ( myNbOnPlane2 == 2 )
1102         findIntPointOnPlane( myNodes2, myDist2, link );
1103     }
1104     else if ( u2 > u1 + myTol )
1105     {
1106       intersectLink( myNodes2, myDist2, iE2, myFace1, link );
1107       node1 = node2 = 0;
1108       if ( myNbOnPlane1 == 2 )
1109         findIntPointOnPlane( myNodes1, myDist1, link );
1110     }
1111     else // edges of two faces intersect the line at the same point
1112     {
1113       CutLink link2;
1114       intersectLink( myNodes1, myDist1, iE1, myFace2, link );
1115       intersectLink( myNodes2, myDist2, iE2, myFace1, link2 );
1116       node1 = link2.Node1();
1117       node2 = link2.Node2();
1118
1119       if      ( !link.IntNode() && link2.IntNode() )
1120         link.myIntNode = link2.myIntNode;
1121
1122       else if ( !link.IntNode() && !link2.IntNode() )
1123         (gp_XYZ&)link.myIntNode = 0.5 * ( link.myIntNode + link2.myIntNode );
1124
1125       else if ( link.IntNode() && link2.IntNode() )
1126         replaceIntNode( link.IntNode(), link2.IntNode() );
1127     }
1128   }
1129
1130   //================================================================================
1131   /*!
1132    * \brief Add intersections to a link collinear with the intersection line
1133    */
1134   //================================================================================
1135
1136   void Intersector::Algo::cutCollinearLink( const int                           iNotOnPlane1,
1137                                             const std::vector< SMESH_NodeXYZ >& nodes1,
1138                                             const SMDS_MeshElement*             face2,
1139                                             const CutLink&                      link1,
1140                                             const CutLink&                      link2)
1141
1142   {
1143     int iN1 = ( iNotOnPlane1 + 1 ) % 3;
1144     int iN2 = ( iNotOnPlane1 + 2 ) % 3;
1145     CutLink link( nodes1[ iN1 ].Node(), nodes1[ iN2 ].Node(), face2 );
1146     if ( link1.myFace != face2 )
1147     {
1148       link.myIntNode = link1.myIntNode;
1149       addLink( link );
1150     }
1151     if ( link2.myFace != face2 )
1152     {
1153       link.myIntNode = link2.myIntNode;
1154       addLink( link );
1155     }
1156   }
1157
1158   //================================================================================
1159   /*!
1160    * \brief Choose indices on an axis-aligned plane
1161    */
1162   //================================================================================
1163
1164   void Intersector::Algo::setPlaneIndices( const gp_XYZ& planeNorm )
1165   {
1166     switch ( MaxIndex( planeNorm )) {
1167     case 1: myInd1 = 2; myInd2 = 3; break;
1168     case 2: myInd1 = 3; myInd2 = 1; break;
1169     case 3: myInd1 = 1; myInd2 = 2; break;
1170     }
1171   }
1172
1173   //================================================================================
1174   /*!
1175    * \brief Intersect two faces
1176    */
1177   //================================================================================
1178
1179   void Intersector::Algo::Cut( const SMDS_MeshElement* face1,
1180                                const SMDS_MeshElement* face2,
1181                                const int               nbCommonNodes)
1182   {
1183     myFace1 = face1;
1184     myFace2 = face2;
1185     myNodes1.assign( face1->begin_nodes(), face1->end_nodes() );
1186     myNodes2.assign( face2->begin_nodes(), face2->end_nodes() );
1187
1188     const gp_XYZ& n1 = myNormals[ face1->GetID() ];
1189     const gp_XYZ& n2 = myNormals[ face2->GetID() ];
1190
1191     // check if triangles intersect
1192     int iNotOnPlane1, iNotOnPlane2;
1193     const double d2 = -( n2 * myNodes2[0]);
1194     if ( !isPlaneIntersected( n2, d2, myNodes1, myDist1, myNbOnPlane1, iNotOnPlane1 ))
1195       return;
1196     const double d1 = -( n1 * myNodes1[0]);
1197     if ( !isPlaneIntersected( n1, d1, myNodes2, myDist2, myNbOnPlane2, iNotOnPlane2 ))
1198       return;
1199
1200     if ( myNbOnPlane1 == 3 || myNbOnPlane2 == 3 )// triangles are co-planar
1201     {
1202       setPlaneIndices( myNbOnPlane1 == 3 ? n2 : n1 ); // choose indices on an axis-aligned plane
1203       cutCoplanar();
1204     }
1205     else if ( nbCommonNodes < 2 ) // triangle planes intersect
1206     {
1207       gp_XYZ lineDir = n1 ^ n2; // intersection line
1208
1209       // check if intervals of intersections of triangles with lineDir overlap
1210
1211       double u1[2], u2 [2]; // parameters on lineDir of edge intersection points { minU, maxU }
1212       int   iE1[2], iE2[2]; // indices of edges
1213       int iMaxCoo = MaxIndex( lineDir );
1214       computeIntervals( myNodes1, myDist1, myNbOnPlane1, iMaxCoo, u1, iE1 );
1215       computeIntervals( myNodes2, myDist2, myNbOnPlane2, iMaxCoo, u2, iE2 );
1216       if ( u1[1] < u2[0] - myTol || u2[1] < u1[0] - myTol )
1217         return; // intervals do not overlap
1218
1219       // make intersection nodes
1220
1221       const SMDS_MeshNode *l1n1, *l1n2, *l2n1, *l2n2;
1222       CutLink link1; // intersection with smaller u on lineDir
1223       computeIntPoint( u1[0], u2[0], iE1[0], iE2[0], link1, l1n1, l1n2 );
1224       CutLink link2; // intersection with larger u on lineDir
1225       computeIntPoint( -u1[1], -u2[1], iE1[1], iE2[1], link2, l2n1, l2n2 );
1226
1227       const CutFace& cf1 = myCutFaces.Added( CutFace( face1 ));
1228       const CutFace& cf2 = myCutFaces.Added( CutFace( face2 ));
1229
1230       if ( coincide( link1.myIntNode, link2.myIntNode, myTol ))
1231       {
1232         // intersection is a point
1233         if ( link1.IntNode() && link2.IntNode() )
1234           replaceIntNode( link1.IntNode(), link2.IntNode() );
1235
1236         CutLink* link = link2.IntNode() ? &link2 : &link1;
1237         if ( !link->IntNode() )
1238         {
1239           gp_XYZ p = 0.5 * ( link1.myIntNode + link2.myIntNode );
1240           link->myIntNode.Set( createNode( p ));
1241         }
1242         if ( !link1.IntNode() ) link1.myIntNode = link2.myIntNode;
1243         if ( !link2.IntNode() ) link2.myIntNode = link1.myIntNode;
1244
1245         cf1.AddPoint( link1, link2, myTol );
1246         cf2.AddPoint( link1, link2, myTol );
1247       }
1248       else
1249       {
1250         // intersection is a line segment
1251         if ( !link1.IntNode() )
1252           link1.myIntNode.Set( createNode( link1.myIntNode ));
1253         if ( !link2.IntNode() )
1254           link2.myIntNode.Set( createNode( link2.myIntNode ));
1255
1256         cf1.AddEdge( link1, link2, face2, myNbOnPlane1, iNotOnPlane1 );
1257         if ( l1n1 ) link1.Set( l1n1, l1n2, face2 );
1258         if ( l2n1 ) link2.Set( l2n1, l2n2, face2 );
1259         cf2.AddEdge( link1, link2, face1, myNbOnPlane2, iNotOnPlane2 );
1260
1261         // add intersections to a link collinear with the intersection line
1262         if ( myNbOnPlane1 == 2 && ( link1.myFace != face2 || link2.myFace != face2 ))
1263           cutCollinearLink( iNotOnPlane1, myNodes1, face2, link1, link2 );
1264
1265         if ( myNbOnPlane2 == 2 && ( link1.myFace != face1 || link2.myFace != face1 ))
1266           cutCollinearLink( iNotOnPlane2, myNodes2, face1, link1, link2 );
1267       }
1268
1269       addLink( link1 );
1270       addLink( link2 );
1271
1272     } // non co-planar case
1273
1274     return;
1275   }
1276
1277   //================================================================================
1278   /*!
1279    * \brief Store a face cut by a line given by its ends
1280    *        accompanied by indices of intersected face edges.
1281    *        Edge index is <0 if a line end is inside the face.
1282    *  \param [in] face - a face to cut
1283    *  \param [inout] lineEnd1 - line end coordinates + optional node existing at this point
1284    *  \param [in] edgeIndex1 - index of face edge cut by lineEnd1
1285    *  \param [inout] lineEnd2 - line end coordinates + optional node existing at this point
1286    *  \param [in] edgeIndex2 - index of face edge cut by lineEnd2
1287    */
1288   //================================================================================
1289
1290   void Intersector::Algo::Cut( const SMDS_MeshElement* face,
1291                                SMESH_NodeXYZ&          lineEnd1,
1292                                int                     edgeIndex1,
1293                                SMESH_NodeXYZ&          lineEnd2,
1294                                int                     edgeIndex2 )
1295   {
1296     if ( lineEnd1.Node() && lineEnd2.Node() &&
1297          face->GetNodeIndex( lineEnd1.Node() ) >= 0 &&
1298          face->GetNodeIndex( lineEnd2.Node() ) >= 0 )
1299       return; // intersection at a face node or edge
1300
1301     if ((int) myNormals.size() <= face->GetID() )
1302       const_cast< std::vector< gp_XYZ >& >( myNormals ).resize( face->GetID() + 1 );
1303
1304     const CutFace& cf = myCutFaces.Added( CutFace( face ));
1305     cf.InitLinks();
1306
1307     // look for intersection nodes coincident with line ends
1308     CutLink links[2];
1309     for ( int is2nd = 0; is2nd < 2; ++is2nd )
1310     {
1311       SMESH_NodeXYZ& lineEnd = is2nd ? lineEnd2 : lineEnd1;
1312       int          edgeIndex = is2nd ? edgeIndex2 : edgeIndex1;
1313       CutLink &         link = links[ is2nd ];
1314
1315       link.myIntNode = lineEnd;
1316
1317       for ( size_t i = ( edgeIndex < 0 ? 3 : 0  ); i < cf.myLinks.size(); ++i )
1318         if ( coincide( lineEnd, SMESH_NodeXYZ( cf.myLinks[i].myNode1 ), myTol ))
1319         {
1320           link.myIntNode = cf.myLinks[i].myNode1;
1321           break;
1322         }
1323
1324       if ( edgeIndex >= 0 )
1325       {
1326         link.Set( face->GetNode    ( edgeIndex ),
1327                   face->GetNodeWrap( edgeIndex + 1 ),
1328                   /*cuttingFace=*/0);
1329         findLink( link );
1330       }
1331
1332       if ( !link.myIntNode )
1333         link.myIntNode.Set( createNode( lineEnd ));
1334
1335       lineEnd._node = link.IntNode();
1336
1337       if ( link.myNode[0] )
1338         addLink( link );
1339     }
1340
1341     cf.AddEdge( links[0], links[1], /*face=*/0, /*nbOnPlane=*/0, /*iNotOnPlane=*/-1 );
1342   }
1343
1344   //================================================================================
1345   /*!
1346    * \brief Intersect two 2D line segments
1347    */
1348   //================================================================================
1349
1350   bool Intersector::Algo::intersectEdgeEdge( const gp_XY s1p0, const gp_XY s1p1,
1351                                              const gp_XY s2p0, const gp_XY s2p1,
1352                                              double &    t1,   double &    t2,
1353                                              bool &      isCollinear )
1354   {
1355     gp_XY u = s1p1 - s1p0;
1356     gp_XY v = s2p1 - s2p0;
1357     gp_XY w = s1p0 - s2p0;
1358     double perpDotUV = u * gp_XY( -v.Y(), v.X() );
1359     double perpDotVW = v * gp_XY( -w.Y(), w.X() );
1360     double perpDotUW = u * gp_XY( -w.Y(), w.X() );
1361     double        u2 = u.SquareModulus();
1362     double        v2 = v.SquareModulus();
1363     if ( u2 < myEps * myEps || v2 < myEps * myEps )
1364       return false;
1365     if ( perpDotUV * perpDotUV / u2 / v2 < 1e-6 ) // cos ^ 2
1366     {
1367       if ( !isCollinear )
1368         return false; // no need in collinear solution
1369       if ( perpDotUW * perpDotUW / u2 > myTol * myTol )
1370         return false; // parallel
1371
1372       // collinear
1373       gp_XY w2 = s1p1 - s2p0;
1374       if ( Abs( v.X()) + Abs( u.X()) > Abs( v.Y()) + Abs( u.Y())) {
1375         t1 = w.X() / v.X();  // params on segment 2
1376         t2 = w2.X() / v.X();
1377       }
1378       else {
1379         t1 = w.Y() / v.Y();
1380         t2 = w2.Y() / v.Y();
1381       }
1382       if ( Max( t1,t2 ) <= 0 || Min( t1,t2 ) >= 1 )
1383         return false; // no overlap
1384       return true;
1385     }
1386     isCollinear = false;
1387
1388     t1 = perpDotVW / perpDotUV; // param on segment 1
1389     if ( t1 < 0. || t1 > 1. )
1390       return false; // intersection not within the segment
1391
1392     t2 = perpDotUW / perpDotUV; // param on segment 2
1393     if ( t2 < 0. || t2 > 1. )
1394       return false; // intersection not within the segment
1395
1396     return true;
1397   }
1398
1399   //================================================================================
1400   /*!
1401    * \brief Intersect two edges of co-planar triangles
1402    *  \param [inout] iE1 - edge index of triangle 1
1403    *  \param [inout] iE2 - edge index of triangle 2
1404    *  \param [inout] intPoints - intersection points
1405    *  \param [inout] nbIntPoints - nb of found intersection points
1406    */
1407   //================================================================================
1408
1409   bool Intersector::Algo::intersectEdgeEdge( int iE1, int iE2, IntPoint2D& intPoint )
1410   {
1411     int i01 = iE1, i11 = ( iE1 + 1 ) % 3;
1412     int i02 = iE2, i12 = ( iE2 + 1 ) % 3;
1413     if (( !intPoint.myIsCollinear ) &&
1414         ( myNodes1[ i01 ] == myNodes2[ i02 ] ||
1415           myNodes1[ i01 ] == myNodes2[ i12 ] ||
1416           myNodes1[ i11 ] == myNodes2[ i02 ] ||
1417           myNodes1[ i11 ] == myNodes2[ i12 ] ))
1418       return false;
1419
1420     // segment 1
1421     gp_XY s1p0 = p2D( myNodes1[ i01 ]);
1422     gp_XY s1p1 = p2D( myNodes1[ i11 ]);
1423
1424     // segment 2
1425     gp_XY s2p0 = p2D( myNodes2[ i02 ]);
1426     gp_XY s2p1 = p2D( myNodes2[ i12 ]);
1427
1428     double t1, t2;
1429     if ( !intersectEdgeEdge( s1p0,s1p1, s2p0,s2p1, t1, t2, intPoint.myIsCollinear ))
1430       return false;
1431
1432     intPoint.myEdgeInd[0] = iE1;
1433     intPoint.myEdgeInd[1] = iE2;
1434     intPoint.myU[0] = t1;
1435     intPoint.myU[1] = t2;
1436     (gp_XYZ&)intPoint.myNode = myNodes1[i01] * ( 1 - t1 ) + myNodes1[i11] * t1;
1437
1438     if ( intPoint.myIsCollinear )
1439       return true;
1440
1441     // try to find existing node at intPoint.myNode
1442
1443     if ( myNodes1[ i01 ] == myNodes2[ i02 ] ||
1444          myNodes1[ i01 ] == myNodes2[ i12 ] ||
1445          myNodes1[ i11 ] == myNodes2[ i02 ] ||
1446          myNodes1[ i11 ] == myNodes2[ i12 ] )
1447       return false;
1448
1449     const double coincTol = myTol * 1e-3;
1450
1451     CutLink link1( myNodes1[i01].Node(), myNodes1[i11].Node(), myFace2 );
1452     CutLink link2( myNodes2[i02].Node(), myNodes2[i12].Node(), myFace1 );
1453
1454     SMESH_NodeXYZ& n1 = myNodes1[ t1 < 0.5 ? i01 : i11 ];
1455     bool same1 = coincide( n1, intPoint.myNode, coincTol );
1456     if ( same1 )
1457     {
1458       link2.myIntNode = intPoint.myNode = n1;
1459       addLink( link2 );
1460     }
1461     SMESH_NodeXYZ& n2 = myNodes2[ t2 < 0.5 ? i02 : i12 ];
1462     bool same2 = coincide( n2, intPoint.myNode, coincTol );
1463     if ( same2 )
1464     {
1465       link1.myIntNode = intPoint.myNode = n2;
1466       addLink( link1 );
1467       if ( same1 )
1468       {
1469         replaceIntNode( n1.Node(), n2.Node() );
1470         return false;
1471       }
1472       return true;
1473     }
1474     if ( same1 )
1475       return true;
1476
1477     link1.myIntNode = intPoint.myNode;
1478     if ( findLink( link1 ))
1479     {
1480       intPoint.myNode = link2.myIntNode = link1.myIntNode;
1481       addLink( link2 );
1482       return true;
1483     }
1484
1485     link2.myIntNode = intPoint.myNode;
1486     if ( findLink( link2 ))
1487     {
1488       intPoint.myNode = link1.myIntNode = link2.myIntNode;
1489       addLink( link1 );
1490       return true;
1491     }
1492
1493     for ( int is2nd = 0; is2nd < 2; ++is2nd )
1494     {
1495       const SMDS_MeshElement* f = is2nd ? myFace1 : myFace2;
1496       if ( !f ) continue;
1497       const CutFace& cf = myCutFaces.Added( CutFace( is2nd ? myFace2 : myFace1 ));
1498       for ( size_t i = 0; i < cf.myLinks.size(); ++i )
1499         if ( cf.myLinks[i].myFace == f &&
1500              //cf.myLinks[i].myIndex != EdgePart::_COPLANAR &&
1501              coincide( intPoint.myNode, SMESH_NodeXYZ( cf.myLinks[i].myNode1 ), coincTol ))
1502         {
1503           intPoint.myNode.Set( cf.myLinks[i].myNode1 );
1504           return true;
1505         }
1506     }
1507
1508     // make a new node
1509
1510     intPoint.myNode._node = createNode( intPoint.myNode );
1511     link1.myIntNode = link2.myIntNode = intPoint.myNode;
1512     addLink( link1 );
1513     addLink( link2 );
1514
1515     return true;
1516   }
1517
1518
1519   //================================================================================
1520   /*!
1521    * \brief Check if a point is contained in a triangle
1522    */
1523   //================================================================================
1524
1525   bool Intersector::Algo::isPointInTriangle( const gp_XYZ& p, const std::vector< SMESH_NodeXYZ >& nodes )
1526   {
1527     double bc1, bc2;
1528     SMESH_MeshAlgos::GetBarycentricCoords( p2D( p ),
1529                                            p2D( nodes[0] ), p2D( nodes[1] ), p2D( nodes[2] ),
1530                                            bc1, bc2 );
1531     return ( 0. < bc1 && 0. < bc2 && bc1 + bc2 < 1. );
1532   }
1533
1534   //================================================================================
1535   /*!
1536    * \brief Intersect two co-planar faces
1537    */
1538   //================================================================================
1539
1540   void Intersector::Algo::cutCoplanar()
1541   {
1542     // find intersections of edges
1543
1544     IntPoint2D intPoints[ 6 ];
1545     int      nbIntPoints = 0;
1546     for ( int iE1 = 0; iE1 < 3; ++iE1 )
1547     {
1548       int maxNbIntPoints = nbIntPoints + 2;
1549       for ( int iE2 = 0; iE2 < 3 &&  nbIntPoints < maxNbIntPoints; ++iE2 )
1550         nbIntPoints += intersectEdgeEdge( iE1, iE2, intPoints[ nbIntPoints ]);
1551     }
1552     const int minNbOnPlane = Min( myNbOnPlane1, myNbOnPlane2 );
1553
1554     if ( nbIntPoints == 0 ) // no intersections of edges
1555     {
1556       bool is1in2;
1557       if      ( isPointInTriangle( myNodes1[0], myNodes2 )) // face2 includes face1
1558         is1in2 = true;
1559       else if ( isPointInTriangle( myNodes2[0], myNodes1 )) // face1 includes face2
1560         is1in2 = false;
1561       else
1562         return;
1563
1564       // add edges of an inner triangle to an outer one
1565
1566       const std::vector< SMESH_NodeXYZ >& nodesIn = is1in2 ? myNodes1 : myNodes2;
1567       const SMDS_MeshElement*             faceOut = is1in2 ? myFace2  : myFace1;
1568       const SMDS_MeshElement*              faceIn = is1in2 ? myFace1  : myFace2;
1569
1570       const CutFace& outFace = myCutFaces.Added( CutFace( faceOut ));
1571       CutLink link1( nodesIn.back().Node(), nodesIn.back().Node(), faceOut );
1572       CutLink link2( nodesIn.back().Node(), nodesIn.back().Node(), faceOut );
1573
1574       link1.myIntNode = nodesIn.back();
1575       for ( size_t i = 0; i < nodesIn.size(); ++i )
1576       {
1577         link2.myIntNode = nodesIn[ i ];
1578         outFace.AddEdge( link1, link2, faceIn, minNbOnPlane );
1579         link1.myIntNode = link2.myIntNode;
1580       }
1581     }
1582     else
1583     {
1584       // add parts of edges to a triangle including them
1585
1586       CutLink link1, link2;
1587       IntPoint2D ip0, ip1;
1588       ip0.myU[0] = ip0.myU[1] = 0.;
1589       ip1.myU[0] = ip1.myU[1] = 1.;
1590       ip0.myEdgeInd[0] = ip0.myEdgeInd[1] = ip1.myEdgeInd[0] = ip1.myEdgeInd[1] = 0;
1591
1592       for ( int isFromFace1 = 0; isFromFace1 < 2; ++isFromFace1 )
1593       {
1594         const SMDS_MeshElement*                faceTo = isFromFace1 ? myFace2  : myFace1;
1595         const SMDS_MeshElement*              faceFrom = isFromFace1 ? myFace1  : myFace2;
1596         const std::vector< SMESH_NodeXYZ >&   nodesTo = isFromFace1 ? myNodes2 : myNodes1;
1597         const std::vector< SMESH_NodeXYZ >& nodesFrom = isFromFace1 ? myNodes1 : myNodes2;
1598         const int                                 iTo = isFromFace1 ? 1 : 0;
1599         const int                               iFrom = isFromFace1 ? 0 : 1;
1600         //const int                       nbOnPlaneFrom = isFromFace1 ? myNbOnPlane1 : myNbOnPlane2;
1601
1602         const CutFace* cutFaceTo   = & myCutFaces.Added( CutFace( faceTo ));
1603         // const CutFace* cutFaceFrom = 0;
1604         // if ( nbOnPlaneFrom > minNbOnPlane )
1605         //   cutFaceFrom = & myCutFaces.Added( CutFace( faceTo ));
1606
1607         link1.myFace = link2.myFace = faceTo;
1608
1609         IntPoint2DCompare ipCompare( iFrom );
1610         TIntPointPtrSet pointsOnEdge( ipCompare ); // IntPoint2D sorted by parameter on edge
1611
1612         for ( size_t iE = 0; iE < nodesFrom.size(); ++iE )
1613         {
1614           // get parts of an edge iE
1615
1616           ip0.myEdgeInd[ iTo ] = iE;
1617           ip1.myEdgeInd[ iTo ] = ( iE + 1 ) % nodesFrom.size();
1618           ip0.myNode = nodesFrom[ ip0.myEdgeInd[ iTo ]];
1619           ip1.myNode = nodesFrom[ ip1.myEdgeInd[ iTo ]];
1620
1621           pointsOnEdge.clear();
1622
1623           for ( int iP = 0; iP < nbIntPoints; ++iP )
1624             if ( intPoints[ iP ].myEdgeInd[ iFrom ] == iE )
1625               pointsOnEdge.insert( & intPoints[ iP ] );
1626
1627           pointsOnEdge.insert( pointsOnEdge.begin(), & ip0 );
1628           pointsOnEdge.insert( pointsOnEdge.end(),   & ip1 );
1629
1630           // add edge parts to faceTo
1631
1632           TIntPointPtrSet::iterator ipIt = pointsOnEdge.begin() + 1;
1633           for ( ; ipIt != pointsOnEdge.end(); ++ipIt )
1634           {
1635             const IntPoint2D* p1 = *(ipIt-1);
1636             const IntPoint2D* p2 = *ipIt;
1637             gp_XYZ middle = 0.5 * ( p1->myNode + p2->myNode );
1638             if ( isPointInTriangle( middle, nodesTo ))
1639             {
1640               p1->InitLink( link1, iTo, ( p1 != & ip0 ) ? nodesTo : nodesFrom );
1641               p2->InitLink( link2, iTo, ( p2 != & ip1 ) ? nodesTo : nodesFrom );
1642               cutFaceTo->AddEdge( link1, link2, faceFrom, minNbOnPlane );
1643
1644               // if ( cutFaceFrom )
1645               // {
1646               //   p1->InitLink( link1, iFrom, nodesFrom );
1647               //   p2->InitLink( link2, iFrom, nodesFrom );
1648               //   cutFaceTo->AddEdge( link1, link2, faceTo, minNbOnPlane );
1649               // }
1650             }
1651           }
1652         }
1653       }
1654     }
1655     return;
1656
1657   } // Intersector::Algo::cutCoplanar()
1658
1659   //================================================================================
1660   /*!
1661    * \brief Intersect edges added to myCutFaces
1662    */
1663   //================================================================================
1664
1665   void Intersector::Algo::intersectNewEdges( const CutFace& cf )
1666   {
1667     IntPoint2D intPoint;
1668
1669     if ( cf.NbInternalEdges() < 2 )
1670       return;
1671
1672     if ( myNodes1.empty() )
1673     {
1674       myNodes1.resize(2);
1675       myNodes2.resize(2);
1676     }
1677
1678     const gp_XYZ& faceNorm = myNormals[ cf.myInitFace->GetID() ];
1679     setPlaneIndices( faceNorm ); // choose indices on an axis-aligned plane
1680
1681     size_t limit = cf.myLinks.size() * cf.myLinks.size() * 2;
1682
1683     for ( size_t i1 = 3; i1 < cf.myLinks.size(); ++i1 )
1684     {
1685       if ( !cf.myLinks[i1].IsInternal() )
1686         continue;
1687
1688       myIntPointSet.clear();
1689       for ( size_t i2 = i1 + 2; i2 < cf.myLinks.size(); ++i2 )
1690       {
1691         if ( !cf.myLinks[i2].IsInternal() )
1692           continue;
1693
1694         // prepare to intersection
1695         myFace1     = cf.myLinks[i1].myFace;
1696         myNodes1[0] = cf.myLinks[i1].myNode1;
1697         myNodes1[1] = cf.myLinks[i1].myNode2;
1698         myFace2     = cf.myLinks[i2].myFace;
1699         myNodes2[0] = cf.myLinks[i2].myNode1;
1700         myNodes2[1] = cf.myLinks[i2].myNode2;
1701
1702         // intersect
1703         intPoint.myIsCollinear = true; // to find collinear solutions
1704         if ( intersectEdgeEdge( 0, 0, intPoint ))
1705         {
1706           if ( cf.myLinks[i1].IsSame( cf.myLinks[i2] )) // remove i2
1707           {
1708             cf.myLinks[i1].ReplaceCoplanar( cf.myLinks[i2] );
1709             cf.myLinks.erase( cf.myLinks.begin() + i2, cf.myLinks.begin() + i2 + 2 );
1710             --i2;
1711             continue;
1712           }
1713           if ( !intPoint.myIsCollinear )
1714           {
1715             intPoint.myEdgeInd[1] = i2;
1716             myIntPointSet.insert( intPoint );
1717           }
1718           else // if ( intPoint.myIsCollinear ) // overlapping edges
1719           {
1720             myIntPointSet.clear(); // to recompute
1721
1722             if ( intPoint.myU[0] > intPoint.myU[1] ) // orient in same direction
1723             {
1724               std::swap( intPoint.myU[0], intPoint.myU[1] );
1725               std::swap( myNodes1[0], myNodes1[1] );
1726             }
1727             // replace _COPLANAR by _INTERNAL
1728             cf.myLinks[i1].ReplaceCoplanar( cf.myLinks[i1+1] );
1729             cf.myLinks[i2].ReplaceCoplanar( cf.myLinks[i2+1] );
1730
1731             if ( coincide( myNodes1[0], myNodes2[0], myTol ) &&
1732                  coincide( myNodes1[1], myNodes2[1], myTol ))
1733             {
1734               cf.myLinks.erase( cf.myLinks.begin() + i2, cf.myLinks.begin() + i2 + 2 );
1735               --i2;
1736               continue;
1737             }
1738
1739             EdgePart common = cf.myLinks[i1];
1740             common.ReplaceCoplanar( cf.myLinks[i2] );
1741
1742             const SMDS_MeshNode* n1 = myNodes1[0].Node(); // end nodes of an overlapping part
1743             const SMDS_MeshNode* n2 = myNodes1[1].Node();
1744             size_t i3 = cf.myLinks.size();
1745
1746             if ( myNodes1[0] != myNodes2[0] ) // a part before the overlapping one
1747             {
1748               if ( intPoint.myU[0] < 0 )
1749                 cf.myLinks[i1].Set( myNodes1[0].Node(), myNodes2[0].Node(),
1750                                     cf.myLinks[i1].myFace, cf.myLinks[i1].myIndex );
1751               else
1752                 cf.myLinks[i1].Set( myNodes2[0].Node(), myNodes1[0].Node(),
1753                                     cf.myLinks[i2].myFace, cf.myLinks[i2].myIndex );
1754
1755               cf.myLinks[i1+1].Set( cf.myLinks[i1].myNode2,
1756                                     cf.myLinks[i1].myNode1,
1757                                     cf.myLinks[i1].myFace,
1758                                     cf.myLinks[i1].myIndex);
1759               n1 = cf.myLinks[i1].myNode2;
1760             }
1761             else
1762               i3 = i1;
1763
1764             if ( myNodes1[1] != myNodes2[1] ) // a part after the overlapping one
1765             {
1766               if ( intPoint.myU[1] < 1 )
1767                 cf.myLinks[i2].Set( myNodes1[1].Node(), myNodes2[1].Node(),
1768                                     cf.myLinks[i2].myFace, cf.myLinks[i2].myIndex );
1769               else
1770                 cf.myLinks[i2].Set( myNodes2[1].Node(), myNodes1[1].Node(),
1771                                     cf.myLinks[i1].myFace, cf.myLinks[i1].myIndex );
1772
1773               cf.myLinks[i2+1].Set( cf.myLinks[i2].myNode2,
1774                                     cf.myLinks[i2].myNode1,
1775                                     cf.myLinks[i2].myFace,
1776                                     cf.myLinks[i2].myIndex);
1777               n2 = cf.myLinks[i2].myNode1;
1778             }
1779             else
1780               i3 = i2;
1781
1782             if ( i3 == cf.myLinks.size() )
1783               cf.myLinks.resize( i3 + 2 );
1784
1785             cf.myLinks[i3].Set  ( n1, n2, common.myFace, common.myIndex );
1786             cf.myLinks[i3+1].Set( n2, n1, common.myFace, common.myIndex );
1787
1788             i2 = i1 + 1; // recheck modified i1
1789             continue;
1790           }
1791           //else
1792           // {
1793           //   // remember a new node
1794           //   CutLink link1( myNodes1[0].Node(), myNodes1[1].Node(), cf.myInitFace );
1795           //   CutLink link2( myNodes2[0].Node(), myNodes2[1].Node(), cf.myInitFace );
1796           //   link2.myIntNode = link1.myIntNode = intPoint.myNode;
1797           //   addLink( link1 );
1798           //   addLink( link2 );
1799
1800           //   // split edges
1801           //   size_t i = cf.myLinks.size();
1802           //   if ( intPoint.myNode != cf.myLinks[ i1 ].myNode1 &&
1803           //        intPoint.myNode != cf.myLinks[ i1 ].myNode2 )
1804           //   {
1805           //     cf.myLinks.push_back( cf.myLinks[ i1 ]);
1806           //     cf.myLinks.push_back( cf.myLinks[ i1 + 1 ]);
1807           //     cf.myLinks[ i1 ].myNode2 = cf.myLinks[ i1 + 1 ].myNode1 = intPoint.Node();
1808           //     cf.myLinks[ i  ].myNode1 = cf.myLinks[ i  + 1 ].myNode2 = intPoint.Node();
1809           //   }
1810           //   if ( intPoint.myNode != cf.myLinks[ i2 ].myNode1 &&
1811           //        intPoint.myNode != cf.myLinks[ i2 ].myNode2 )
1812           //   {
1813           //     i = cf.myLinks.size();
1814           //     cf.myLinks.push_back( cf.myLinks[ i2 ]);
1815           //     cf.myLinks.push_back( cf.myLinks[ i2 + 1 ]);
1816           //     cf.myLinks[ i2 ].myNode2 = cf.myLinks[ i2 + 1 ].myNode1 = intPoint.Node();
1817           //     cf.myLinks[ i  ].myNode1 = cf.myLinks[ i  + 1 ].myNode2 = intPoint.Node();
1818           //   }
1819           // }
1820
1821         } // if ( intersectEdgeEdge( 0, 0, intPoint ))
1822
1823         ++i2;
1824         --limit;
1825       }
1826
1827       // split i1 edge and all edges it intersects
1828       // don't do it inside intersection loop in order not to loose direction of i1 edge
1829       if ( !myIntPointSet.empty() )
1830       {
1831         cf.myLinks.reserve( cf.myLinks.size() + myIntPointSet.size() * 2 + 2 );
1832
1833         EdgePart* edge1 = &cf.myLinks[ i1 ];
1834         EdgePart* twin1 = &cf.myLinks[ i1 + 1 ];
1835
1836         TIntPointSet::iterator ipIt = myIntPointSet.begin();
1837         for ( ; ipIt != myIntPointSet.end(); ++ipIt ) // int points sorted on i1 edge
1838         {
1839           size_t i = cf.myLinks.size();
1840           if ( ipIt->myNode != edge1->myNode1 &&
1841                ipIt->myNode != edge1->myNode2 )
1842           {
1843             cf.myLinks.push_back( *edge1 );
1844             cf.myLinks.push_back( *twin1 );
1845             edge1->myNode2          = twin1->myNode1              = ipIt->Node();
1846             cf.myLinks[ i ].myNode1 = cf.myLinks[ i + 1 ].myNode2 = ipIt->Node();
1847             edge1 = & cf.myLinks[ i ];
1848             twin1 = & cf.myLinks[ i + 1 ];
1849           }
1850           size_t i2 = ipIt->myEdgeInd[1];
1851           if ( ipIt->myNode != cf.myLinks[ i2 ].myNode1 &&
1852                ipIt->myNode != cf.myLinks[ i2 ].myNode2 )
1853           {
1854             i = cf.myLinks.size();
1855             cf.myLinks.push_back( cf.myLinks[ i2 ]);
1856             cf.myLinks.push_back( cf.myLinks[ i2 + 1 ]);
1857             cf.myLinks[ i2 ].myNode2 = cf.myLinks[ i2 + 1 ].myNode1 = ipIt->Node();
1858             cf.myLinks[ i  ].myNode1 = cf.myLinks[ i  + 1 ].myNode2 = ipIt->Node();
1859           }
1860         }
1861         if ( cf.myLinks.size() >= limit )
1862           throw SALOME_Exception( "Infinite loop in Intersector::Algo::intersectNewEdges()" );
1863       }
1864       ++i1; // each internal edge encounters twice
1865     }
1866     return;
1867   }
1868
1869   //================================================================================
1870   /*!
1871    * \brief Split intersected faces
1872    */
1873   //================================================================================
1874
1875   void Intersector::Algo::MakeNewFaces( SMESH_MeshAlgos::TElemIntPairVec& theNew2OldFaces,
1876                                         SMESH_MeshAlgos::TNodeIntPairVec& theNew2OldNodes,
1877                                         const double                      theSign,
1878                                         const bool                        theOptimize)
1879   {
1880     // fill theNew2OldFaces if empty
1881     TCutFaceMap::const_iterator cutFacesIt = myCutFaces.cbegin();
1882     if ( theNew2OldFaces.empty() )
1883       for ( ; cutFacesIt != myCutFaces.cend(); ++cutFacesIt )
1884       {
1885         const CutFace& cf = *cutFacesIt;
1886         int index = cf.myInitFace->GetID(); // index in theNew2OldFaces
1887         if ((int) theNew2OldFaces.size() <= index )
1888           theNew2OldFaces.resize( index + 1 );
1889         theNew2OldFaces[ index ] = std::make_pair( cf.myInitFace, index );
1890       }
1891
1892     // unmark all nodes except intersection ones
1893
1894     for ( SMDS_NodeIteratorPtr nIt = myMesh->nodesIterator(); nIt->more(); )
1895     {
1896       const SMDS_MeshNode* n = nIt->next();
1897       if ( n->isMarked() && n->GetID()-1 < (int) theNew2OldNodes.size() )
1898         n->setIsMarked( false );
1899     }
1900     // SMESH_MeshAlgos::MarkElems( myMesh->nodesIterator(), false );
1901
1902     TCutLinkMap::const_iterator cutLinksIt = myCutLinks.cbegin();
1903     // for ( ; cutLinksIt != myCutLinks.cend(); ++cutLinksIt )
1904     // {
1905     //   const CutLink& link = *cutLinksIt;
1906     //   if ( link.IntNode() && link.IntNode()->GetID()-1 < (int) theNew2OldNodes.size() )
1907     //     link.IntNode()->setIsMarked( true );
1908     // }
1909
1910     // intersect edges added to myCutFaces
1911
1912     for ( cutFacesIt = myCutFaces.cbegin(); cutFacesIt != myCutFaces.cend(); ++cutFacesIt )
1913     {
1914       const CutFace& cf = *cutFacesIt;
1915       cf.ReplaceNodes( myRemove2KeepNodes );
1916       intersectNewEdges( cf );
1917     }
1918
1919     // make new faces
1920
1921     EdgeLoopSet                            loopSet;
1922     SMESH_MeshAlgos::Triangulate           triangulator( theOptimize );
1923     std::vector< EdgePart >                cutOffLinks;
1924     TLinkMap                               cutOffCoplanarLinks;
1925     std::vector< const CutFace* >          touchedFaces;
1926     SMESH_MeshAlgos::TElemIntPairVec::value_type new2OldTria;
1927     CutFace                                cutFace(0);
1928     std::vector< const SMDS_MeshNode* >    nodes;
1929     std::vector<const SMDS_MeshElement *>  faces;
1930
1931     cutOffLinks.reserve( myCutFaces.Extent() * 2 );
1932
1933     for ( cutFacesIt = myCutFaces.cbegin(); cutFacesIt != myCutFaces.cend(); ++cutFacesIt )
1934     {
1935       const CutFace& cf = *cutFacesIt;
1936       if ( !cf.IsCut() )
1937       {
1938         touchedFaces.push_back( & cf );
1939         continue;
1940       }
1941
1942       const gp_XYZ& normal = myNormals[ cf.myInitFace->GetID() ];
1943
1944       // form loops of new faces
1945       cf.ReplaceNodes( myRemove2KeepNodes );
1946       cf.MakeLoops( loopSet, normal );
1947
1948       // avoid loops that are not connected to boundary edges of cf.myInitFace
1949       if ( cf.RemoveInternalLoops( loopSet ))
1950       {
1951         intersectNewEdges( cf );
1952         cf.MakeLoops( loopSet, normal );
1953       }
1954       // erase loops that are cut off by face intersections
1955       cf.CutOffLoops( loopSet, theSign, myNormals, cutOffLinks, cutOffCoplanarLinks );
1956
1957       int index = cf.myInitFace->GetID(); // index in theNew2OldFaces
1958
1959       const SMDS_MeshElement* tria;
1960       for ( size_t iL = 0; iL < loopSet.myNbLoops; ++iL )
1961       {
1962         EdgeLoop& loop = loopSet.myLoops[ iL ];
1963         if ( loop.myLinks.size() == 0 )
1964           continue;
1965
1966         int nbTria  = triangulator.GetTriangles( &loop, nodes );
1967         int nbNodes = 3 * nbTria;
1968         for ( int i = 0; i < nbNodes; i += 3 )
1969         {
1970           if ( nodes[i] == nodes[i+1] || nodes[i] == nodes[i+2] || nodes[i+1] == nodes[i+2] )
1971           {
1972 #ifdef _DEBUG_
1973             std::cerr << "BAD tria" << std::endl;
1974             cf.Dump();
1975 #endif
1976             continue;
1977           }
1978           if (!( tria = myMesh->FindFace( nodes[i], nodes[i+1], nodes[i+2] )))
1979             tria = myMesh->AddFace( nodes[i], nodes[i+1], nodes[i+2] );
1980           tria->setIsMarked( true ); // not to remove it
1981
1982           new2OldTria = std::make_pair( tria, theNew2OldFaces[ index ].second );
1983           if ( tria->GetID() < (int)theNew2OldFaces.size() )
1984             theNew2OldFaces[ tria->GetID() ] = new2OldTria;
1985           else
1986             theNew2OldFaces.push_back( new2OldTria );
1987
1988           if ( index == tria->GetID() )
1989             index = 0; // do not remove tria
1990         }
1991       }
1992       theNew2OldFaces[ index ].first = 0;
1993     }
1994
1995     // remove split faces
1996     for ( size_t id = 1; id < theNew2OldFaces.size(); ++id )
1997     {
1998       if ( theNew2OldFaces[id].first ||
1999            theNew2OldFaces[id].second == 0 )
2000         continue;
2001       if ( const SMDS_MeshElement* f = myMesh->FindElement( id ))
2002         myMesh->RemoveFreeElement( f );
2003     }
2004
2005     // remove faces connected to cut off parts of cf.myInitFace
2006
2007     nodes.resize(2);
2008     for ( size_t i = 0; i < cutOffLinks.size(); ++i )
2009     {
2010       //break;
2011       nodes[0] = cutOffLinks[i].myNode1;
2012       nodes[1] = cutOffLinks[i].myNode2;
2013
2014       if ( nodes[0] != nodes[1] &&
2015            myMesh->GetElementsByNodes( nodes, faces ))
2016       {
2017         if ( cutOffLinks[i].myFace &&
2018              cutOffLinks[i].myIndex != EdgePart::_COPLANAR &&
2019              faces.size() == 2 )
2020           continue;
2021         for ( size_t iF = 0; iF < faces.size(); ++iF )
2022         {
2023           int index = faces[iF]->GetID();
2024           // if ( //faces[iF]->isMarked()         ||  // kept part of cutFace
2025           //      !theNew2OldFaces[ index ].first ) // already removed
2026           //   continue;
2027           cutFace.myInitFace = faces[iF];
2028           // if ( myCutFaces.Contains( cutFace )) // keep cutting faces needed in CutOffLoops()
2029           // {
2030           //   if ( !myCutFaces.Added( cutFace ).IsCut() )
2031           //     theNew2OldFaces[ index ].first = 0;
2032           //   continue;
2033           // }
2034           cutFace.myLinks.clear();
2035           cutFace.InitLinks();
2036           for ( size_t iL = 0; iL < cutFace.myLinks.size(); ++iL )
2037             if ( !cutOffLinks[i].IsSame( cutFace.myLinks[ iL ]))
2038               cutOffLinks.push_back( cutFace.myLinks[ iL ]);
2039
2040           theNew2OldFaces[ index ].first = 0;
2041           myMesh->RemoveFreeElement( faces[iF] );
2042         }
2043       }
2044     }
2045
2046     // replace nodes in touched faces
2047
2048     // treat touched faces
2049     for ( size_t i = 0; i < touchedFaces.size(); ++i )
2050     {
2051       const CutFace& cf = *touchedFaces[i];
2052
2053       int index = cf.myInitFace->GetID(); // index in theNew2OldFaces
2054       if ( !theNew2OldFaces[ index ].first )
2055         continue; // already cut off
2056
2057       if ( !cf.ReplaceNodes( myRemove2KeepNodes ))
2058         continue; // just keep as is
2059
2060       if ( cf.myLinks.size() == 3 )
2061       {
2062         const SMDS_MeshElement* tria = myMesh->AddFace( cf.myLinks[0].myNode1,
2063                                                         cf.myLinks[1].myNode1,
2064                                                         cf.myLinks[2].myNode1 );
2065         new2OldTria = std::make_pair( tria, theNew2OldFaces[ index ].second );
2066         if ( tria->GetID() < (int)theNew2OldFaces.size() )
2067           theNew2OldFaces[ tria->GetID() ] = new2OldTria;
2068         else
2069           theNew2OldFaces.push_back( new2OldTria );
2070       }
2071       theNew2OldFaces[ index ].first = 0;
2072     }
2073
2074
2075     // add used new nodes to theNew2OldNodes
2076     SMESH_MeshAlgos::TNodeIntPairVec::value_type new2OldNode;
2077     new2OldNode.second = 0;
2078     for ( cutLinksIt = myCutLinks.cbegin(); cutLinksIt != myCutLinks.cend(); ++cutLinksIt )
2079     {
2080       const CutLink& link = *cutLinksIt;
2081       if ( link.IntNode() ) // && link.IntNode()->NbInverseElements() > 0 )
2082       {
2083         new2OldNode.first = link.IntNode();
2084         theNew2OldNodes.push_back( new2OldNode );
2085       }
2086     }
2087
2088     return;
2089   }
2090
2091   //================================================================================
2092   Intersector::Intersector( SMDS_Mesh* mesh, double tol, const std::vector< gp_XYZ >& normals )
2093   {
2094     myAlgo = new Algo( mesh, tol, normals );
2095   }
2096   //================================================================================
2097   Intersector::~Intersector()
2098   {
2099     delete myAlgo;
2100   }
2101   //================================================================================
2102   //! compute cut of two faces of the mesh
2103   void Intersector::Cut( const SMDS_MeshElement* face1,
2104                          const SMDS_MeshElement* face2,
2105                          const int               nbCommonNodes )
2106   {
2107     myAlgo->Cut( face1, face2, nbCommonNodes );
2108   }
2109   //================================================================================
2110   //! store a face cut by a line given by its ends
2111   //  accompanied by indices of intersected face edges.
2112   //  Edge index is <0 if a line end is inside the face.
2113   void Intersector::Cut( const SMDS_MeshElement* face,
2114                          SMESH_NodeXYZ&          lineEnd1,
2115                          int                     edgeIndex1,
2116                          SMESH_NodeXYZ&          lineEnd2,
2117                          int                     edgeIndex2 )
2118   {
2119     myAlgo->Cut( face, lineEnd1, edgeIndex1, lineEnd2, edgeIndex2 );
2120   }
2121   //================================================================================
2122   //! split all face intersected by Cut() methods
2123   void Intersector::MakeNewFaces( SMESH_MeshAlgos::TElemIntPairVec& theNew2OldFaces,
2124                                   SMESH_MeshAlgos::TNodeIntPairVec& theNew2OldNodes,
2125                                   const double                      theSign,
2126                                   const bool                        theOptimize )
2127   {
2128     myAlgo->MakeNewFaces( theNew2OldFaces, theNew2OldNodes, theSign, theOptimize );
2129   }
2130   //================================================================================
2131   //! Cut a face by planes, whose normals point to parts to keep
2132   bool Intersector::CutByPlanes(const SMDS_MeshElement*        theFace,
2133                                 const std::vector< gp_Ax1 > &  thePlanes,
2134                                 const double                   theTol,
2135                                 std::vector< TFace > &         theNewFaceConnectivity )
2136   {
2137     theNewFaceConnectivity.clear();
2138
2139     // check if theFace is wholly cut off
2140     std::vector< SMESH_NodeXYZ > facePoints( theFace->begin_nodes(), theFace->end_nodes() );
2141     facePoints.resize( theFace->NbCornerNodes() );
2142     for ( size_t iP = 0; iP < thePlanes.size(); ++iP )
2143     {
2144       size_t nbOut = 0;
2145       const gp_Pnt& O = thePlanes[iP].Location();
2146       for ( size_t i = 0; i < facePoints.size(); ++i )
2147       {
2148         gp_Vec Op( O, facePoints[i] );
2149         nbOut += ( Op * thePlanes[iP].Direction() <= 0 );
2150       }
2151       if ( nbOut == facePoints.size() )
2152         return true;
2153     }
2154
2155     // copy theFace into a temporary mesh
2156     SMDS_Mesh mesh;
2157     Bnd_B3d faceBox;
2158     std::vector< const SMDS_MeshNode* > faceNodes;
2159     faceNodes.resize( facePoints.size() );
2160     for ( size_t i = 0; i < facePoints.size(); ++i )
2161     {
2162       const SMESH_NodeXYZ& n = facePoints[i];
2163       faceNodes[i] = mesh.AddNode( n.X(), n.Y(), n.Z() );
2164       faceBox.Add( n );
2165     }
2166     const SMDS_MeshElement* faceToCut = 0;
2167     switch ( theFace->NbCornerNodes() )
2168     {
2169     case 3:
2170       faceToCut = mesh.AddFace( faceNodes[0], faceNodes[1], faceNodes[2] );
2171       break;
2172     case 4:
2173       faceToCut = mesh.AddFace( faceNodes[0], faceNodes[1], faceNodes[2], faceNodes[3] );
2174       break;
2175     default:
2176       faceToCut = mesh.AddPolygonalFace( faceNodes );
2177     }
2178
2179     std::vector< gp_XYZ > normals( 2 + thePlanes.size() );
2180     SMESH_MeshAlgos::FaceNormal( faceToCut, normals[ faceToCut->GetID() ]);
2181
2182     // add faces corresponding to thePlanes
2183     std::vector< const SMDS_MeshElement* > planeFaces;
2184     double faceSize = Sqrt( faceBox.SquareExtent() );
2185     gp_XYZ   center = 0.5 * ( faceBox.CornerMin() + faceBox.CornerMax() );
2186     for ( size_t i = 0; i < thePlanes.size(); ++i )
2187     {
2188       gp_Ax2 plnAx( thePlanes[i].Location(), thePlanes[i].Direction() );
2189       gp_XYZ O = plnAx.Location().XYZ();
2190       gp_XYZ X = plnAx.XDirection().XYZ();
2191       gp_XYZ Y = plnAx.YDirection().XYZ();
2192       gp_XYZ Z = plnAx.Direction().XYZ();
2193
2194       double dot = ( O - center ) * Z;
2195       gp_XYZ o = center + Z * dot; // center projected to a plane
2196
2197       gp_XYZ p1 = o + X * faceSize * 2;
2198       gp_XYZ p2 = o + Y * faceSize * 2;
2199       gp_XYZ p3 = o - (X + Y ) * faceSize * 2;
2200
2201       const SMDS_MeshNode* n1 = mesh.AddNode( p1.X(), p1.Y(), p1.Z() );
2202       const SMDS_MeshNode* n2 = mesh.AddNode( p2.X(), p2.Y(), p2.Z() );
2203       const SMDS_MeshNode* n3 = mesh.AddNode( p3.X(), p3.Y(), p3.Z() );
2204       planeFaces.push_back( mesh.AddFace( n1, n2, n3 ));
2205
2206       normals[ planeFaces.back()->GetID() ] = thePlanes[i].Direction().XYZ();
2207     }
2208
2209     // cut theFace
2210     Algo algo ( &mesh, theTol, normals );
2211     for ( size_t i = 0; i < planeFaces.size(); ++i )
2212     {
2213       algo.Cut( faceToCut, planeFaces[i], 0 );
2214     }
2215
2216     // retrieve a result
2217     SMESH_MeshAlgos::TElemIntPairVec new2OldFaces;
2218     SMESH_MeshAlgos::TNodeIntPairVec new2OldNodes;
2219     TCutFaceMap::const_iterator cutFacesIt= algo.myCutFaces.cbegin();
2220     for ( ; cutFacesIt != algo.myCutFaces.cend(); ++cutFacesIt )
2221     {
2222       const CutFace& cf = *cutFacesIt;
2223       if ( cf.myInitFace != faceToCut )
2224         continue;
2225
2226       if ( !cf.IsCut() )
2227       {
2228         theNewFaceConnectivity.push_back( facePoints );
2229         break;
2230       }
2231       // form loops of new faces
2232       EdgeLoopSet loopSet;
2233       cf.MakeLoops( loopSet, normals[ faceToCut->GetID() ]);
2234
2235       // erase loops that are cut off by thePlanes
2236       const double sign = 1;
2237       std::vector< EdgePart > cutOffLinks;
2238       TLinkMap                cutOffCoplanarLinks;
2239       cf.CutOffLoops( loopSet, sign, normals, cutOffLinks, cutOffCoplanarLinks );
2240
2241       for ( size_t iL = 0; iL < loopSet.myNbLoops; ++iL )
2242       {
2243         EdgeLoop& loop = loopSet.myLoops[ iL ];
2244         if ( loop.myLinks.size() > 0 )
2245         {
2246           facePoints.clear();
2247           for ( SMDS_NodeIteratorPtr nIt = loop.nodeIterator(); nIt->more(); )
2248           {
2249             const SMDS_MeshNode* n = nIt->next();
2250             facePoints.push_back( n );
2251             int iN = faceToCut->GetNodeIndex( n );
2252             if ( iN < 0 )
2253               facePoints.back()._node = 0; // an intersection point
2254             else
2255               facePoints.back()._node = theFace->GetNode( iN );
2256           }
2257           theNewFaceConnectivity.push_back( facePoints );
2258         }
2259       }
2260       break;
2261     }
2262
2263     return theNewFaceConnectivity.empty();
2264   }
2265
2266 } // namespace SMESH_MeshAlgos
2267
2268 namespace
2269 {
2270   //================================================================================
2271   /*!
2272    * \brief Debug
2273    */
2274   //================================================================================
2275
2276   void CutFace::Dump() const
2277   {
2278     std::cout << std::endl << "INI F " << myInitFace->GetID() << std::endl;
2279     for ( size_t i = 0; i < myLinks.size(); ++i )
2280       std::cout << "[" << i << "] ("
2281                 << char(( myLinks[i].IsInternal() ? 'j' : '0' ) + myLinks[i].myIndex ) << ") "
2282                 << myLinks[i].myNode1->GetID() << " - " << myLinks[i].myNode2->GetID()
2283                 << " " << ( myLinks[i].myFace ? 'F' : 'C' )
2284                 << ( myLinks[i].myFace ? myLinks[i].myFace->GetID() : 0 ) << " " << std::endl;
2285   }
2286
2287   //================================================================================
2288   /*!
2289    * \brief Add an edge cutting this face
2290    *  \param [in] p1 - start point of the edge
2291    *  \param [in] p2 - end point of the edge
2292    *  \param [in] cutter - a face producing the added cut edge.
2293    *  \param [in] nbOnPlane - nb of triangle nodes lying on the plane of the cutter face
2294    */
2295   //================================================================================
2296
2297   void CutFace::AddEdge( const CutLink&          p1,
2298                          const CutLink&          p2,
2299                          const SMDS_MeshElement* cutterFace,
2300                          const int               nbOnPlane,
2301                          const int               iNotOnPlane) const
2302   {
2303     int iN[2] = { myInitFace->GetNodeIndex( p1.IntNode() ),
2304                   myInitFace->GetNodeIndex( p2.IntNode() ) };
2305     if ( iN[0] >= 0 && iN[1] >= 0 )
2306     {
2307       // the cutting edge is a whole side
2308       if ((  cutterFace && nbOnPlane < 3 ) &&
2309           !( cutterFace->GetNodeIndex( p1.IntNode() ) >= 0 &&
2310              cutterFace->GetNodeIndex( p2.IntNode() ) >= 0 ))
2311       {
2312         InitLinks();
2313         myLinks[ Abs( iN[0] - iN[1] ) == 1 ? Min( iN[0], iN[1] ) : 2 ].myFace = cutterFace;
2314       }
2315       return;
2316     }
2317
2318     if ( p1.IntNode() == p2.IntNode() )
2319     {
2320       AddPoint( p1, p2, 1e-10 );
2321       return;
2322     }
2323
2324     InitLinks();
2325
2326     // cut side edges by a new one
2327
2328     int iEOnPlane = ( nbOnPlane == 2 ) ? ( iNotOnPlane + 1 ) % 3  :  -1;
2329
2330     double dist[2];
2331     for ( int is2nd = 0; is2nd < 2; ++is2nd )
2332     {
2333       const CutLink& p = is2nd ? p2 : p1;
2334       dist[ is2nd ] = 0;
2335       if ( iN[ is2nd ] >= 0 )
2336         continue;
2337
2338       int iE = Max( iEOnPlane, myInitFace->GetNodeIndex( p.Node1() ));
2339       if ( iE < 0 )
2340         continue; // link of other face
2341
2342       SMESH_NodeXYZ n0 = myLinks[iE].myNode1;
2343       dist[ is2nd ]    = ( n0 - p.myIntNode ).SquareModulus();
2344
2345       for ( size_t i = 0; i < myLinks.size(); ++i )
2346         if ( myLinks[i].myIndex == iE )
2347         {
2348           double d1 = n0.SquareDistance( myLinks[i].myNode1 );
2349           if ( d1 < dist[ is2nd ] )
2350           {
2351             double d2 = n0.SquareDistance( myLinks[i].myNode2 );
2352             if ( dist[ is2nd ] < d2 )
2353             {
2354               myLinks.push_back( myLinks[i] );
2355               myLinks.back().myNode1 = myLinks[i].myNode2 = p.IntNode();
2356               break;
2357             }
2358           }
2359         }
2360     }
2361
2362     int state = nbOnPlane == 3 ? EdgePart::_COPLANAR : EdgePart::_INTERNAL;
2363
2364     // look for an existing equal edge
2365     if ( nbOnPlane == 2 )
2366     {
2367       SMESH_NodeXYZ n0 = myLinks[ iEOnPlane ].myNode1;
2368       if ( iN[0] >= 0 ) dist[0] = ( n0 - p1.myIntNode ).SquareModulus();
2369       if ( iN[1] >= 0 ) dist[1] = ( n0 - p2.myIntNode ).SquareModulus();
2370       if ( dist[0] > dist[1] )
2371         std::swap( dist[0], dist[1] );
2372       for ( size_t i = 0; i < myLinks.size(); ++i )
2373       {
2374         if ( myLinks[i].myIndex != iEOnPlane )
2375           continue;
2376         gp_XYZ mid = 0.5 * ( SMESH_NodeXYZ( myLinks[i].myNode1 ) +
2377                              SMESH_NodeXYZ( myLinks[i].myNode2 ));
2378         double d = ( n0 - mid ).SquareModulus();
2379         if ( dist[0] < d && d < dist[1] )
2380           myLinks[i].myFace = cutterFace;
2381       }
2382       return;
2383     }
2384     else
2385     {
2386       EdgePart newEdge; newEdge.Set( p1.IntNode(), p2.IntNode(), cutterFace, state );
2387       for ( size_t i = 0; i < myLinks.size(); ++i )
2388       {
2389         if ( myLinks[i].IsSame( newEdge ))
2390         {
2391           // if ( !myLinks[i].IsInternal() )
2392           //   myLinks[ i ].myFace = cutterFace;
2393           // else
2394           myLinks[ i   ].ReplaceCoplanar( newEdge );
2395           myLinks[ i+1 ].ReplaceCoplanar( newEdge );
2396           return;
2397         }
2398         i += myLinks[i].IsInternal();
2399       }
2400     }
2401
2402     size_t  i = myLinks.size();
2403     myLinks.resize( i + 2 );
2404     myLinks[ i   ].Set( p1.IntNode(), p2.IntNode(), cutterFace, state );
2405     myLinks[ i+1 ].Set( p2.IntNode(), p1.IntNode(), cutterFace, state );
2406   }
2407
2408   //================================================================================
2409   /*!
2410    * \brief Add a point cutting this face
2411    */
2412   //================================================================================
2413
2414   void CutFace::AddPoint( const CutLink& p1, const CutLink& p2, double tol ) const
2415   {
2416     if ( myInitFace->GetNodeIndex( p1.IntNode() ) >= 0 ||
2417          myInitFace->GetNodeIndex( p2.IntNode() ) >= 0 )
2418       return;
2419
2420     InitLinks();
2421
2422     const CutLink* link = &p1;
2423     int iE = myInitFace->GetNodeIndex( link->Node1() );
2424     if ( iE < 0 )
2425     {
2426       link = &p2;
2427       iE = myInitFace->GetNodeIndex( link->Node1() );
2428     }
2429     if ( iE >= 0 )
2430     {
2431       // cut an existing edge by the point
2432       SMESH_NodeXYZ n0 = link->Node1();
2433       double         d = ( n0 - link->myIntNode ).SquareModulus();
2434
2435       for ( size_t i = 0; i < myLinks.size(); ++i )
2436         if ( myLinks[i].myIndex == iE )
2437         {
2438           double d1 = n0.SquareDistance( myLinks[i].myNode1 );
2439           if ( d1 < d )
2440           {
2441             double d2 = n0.SquareDistance( myLinks[i].myNode2 );
2442             if ( d < d2 )
2443             {
2444               myLinks.push_back( myLinks[i] );
2445               myLinks.back().myNode1 = myLinks[i].myNode2 = link->IntNode();
2446               return;
2447             }
2448           }
2449         }
2450     }
2451     else // point is inside the triangle
2452     {
2453       // // check if a point already added
2454       // for ( size_t i = 3; i < myLinks.size(); ++i )
2455       //   if ( myLinks[i].myNode1 == p1.IntNode() )
2456       //     return;
2457
2458       // // create a link between the point and the closest corner node
2459       // const SMDS_MeshNode* closeNode = myLinks[0].myNode1;
2460       // double minDist = p1.myIntNode.SquareDistance( closeNode );
2461       // for ( int i = 1; i < 3; ++i )
2462       // {
2463       //   double dist = p1.myIntNode.SquareDistance( myLinks[i].myNode1 );
2464       //   if ( dist < minDist )
2465       //   {
2466       //     minDist = dist;
2467       //     closeNode = myLinks[i].myNode1;
2468       //   }
2469       // }
2470       // if ( minDist > tol * tol )
2471       // {
2472       //   size_t i = myLinks.size();
2473       //   myLinks.resize( i + 2 );
2474       //   myLinks[ i   ].Set( p1.IntNode(), closeNode );
2475       //   myLinks[ i+1 ].Set( closeNode, p1.IntNode() );
2476       // }
2477     }
2478   }
2479
2480   //================================================================================
2481   /*!
2482    * \brief Perform node replacement
2483    */
2484   //================================================================================
2485
2486   bool CutFace::ReplaceNodes( const TNNMap& theRm2KeepMap ) const
2487   {
2488     bool replaced = false;
2489     for ( size_t i = 0; i < myLinks.size(); ++i )
2490     {
2491       while ( theRm2KeepMap.IsBound( myLinks[i].myNode1 ))
2492         replaced = ( myLinks[i].myNode1 = theRm2KeepMap( myLinks[i].myNode1 ));
2493
2494       while ( theRm2KeepMap.IsBound( myLinks[i].myNode2 ))
2495         replaced = ( myLinks[i].myNode2 = theRm2KeepMap( myLinks[i].myNode2 ));
2496     }
2497
2498     //if ( replaced ) // remove equal links
2499     {
2500       for ( size_t i1 = 0; i1 < myLinks.size(); ++i1 )
2501       {
2502         if ( myLinks[i1].myNode1 == myLinks[i1].myNode2 )
2503         {
2504           myLinks.erase( myLinks.begin() + i1,
2505                          myLinks.begin() + i1 + 1 + myLinks[i1].IsInternal() );
2506           --i1;
2507           continue;
2508         }
2509         size_t i2 = i1 + 1 + myLinks[i1].IsInternal();
2510         for ( ; i2 < myLinks.size(); ++i2 )
2511         {
2512           if ( !myLinks[i2].IsInternal() )
2513             continue;
2514           if ( myLinks[i1].IsSame( myLinks[i2] ))
2515           {
2516             myLinks[i1].  ReplaceCoplanar( myLinks[i2] );
2517             if ( myLinks[i1].IsInternal() )
2518               myLinks[i1+1].ReplaceCoplanar( myLinks[i2+1] );
2519             if ( !myLinks[i1].myFace && myLinks[i2].myFace )
2520             {
2521               myLinks[i1].  myFace = myLinks[i2].myFace;
2522               if ( myLinks[i1].IsInternal() )
2523                 myLinks[i1+1].myFace = myLinks[i2+1].myFace;
2524             }
2525             myLinks.erase( myLinks.begin() + i2,
2526                            myLinks.begin() + i2 + 2 );
2527             --i2;
2528             continue;
2529           }
2530           ++i2;
2531         }
2532         i1 += myLinks[i1].IsInternal();
2533       }
2534     }
2535
2536     return replaced;
2537   }
2538
2539   //================================================================================
2540   /*!
2541    * \brief Initialize myLinks with edges of myInitFace
2542    */
2543   //================================================================================
2544
2545   void CutFace::InitLinks() const
2546   {
2547     if ( !myLinks.empty() ) return;
2548
2549     int nbNodes = myInitFace->NbNodes();
2550     myLinks.reserve( nbNodes * 2 );
2551     myLinks.resize( nbNodes );
2552
2553     for ( int i = 0; i < nbNodes; ++i )
2554     {
2555       const SMDS_MeshNode* n1 = myInitFace->GetNode( i );
2556       const SMDS_MeshNode* n2 = myInitFace->GetNodeWrap( i + 1);
2557       myLinks[i].Set( n1, n2, 0, i );
2558     }
2559   }
2560   
2561   //================================================================================
2562   /*!
2563    * \brief Return number of internal edges
2564    */
2565   //================================================================================
2566
2567   int CutFace::NbInternalEdges() const
2568   {
2569     int nb = 0;
2570     for ( size_t i = 3; i < myLinks.size(); ++i )
2571       nb += myLinks[i].IsInternal();
2572
2573     return nb / 2; // each internal edge encounters twice
2574   }
2575
2576   //================================================================================
2577   /*!
2578    * \brief Remove loops that are not connected to boundary edges of myFace by
2579    *        adding edges connecting these loops to the boundary.
2580    *        Such loops must be removed as they form polygons with ring topology.
2581    */
2582   //================================================================================
2583
2584   bool CutFace::RemoveInternalLoops( EdgeLoopSet& theLoops ) const
2585   {
2586     size_t nbReachedLoops = 0;
2587
2588     // count loops including boundary EdgeParts
2589     for ( size_t iL = 0; iL < theLoops.myNbLoops; ++iL )
2590     {
2591       EdgeLoop& loop = theLoops.myLoops[ iL ];
2592
2593       for ( size_t iE = 0; iE < loop.myLinks.size(); ++iE )
2594         if ( !loop.myLinks[ iE ]->IsInternal() )
2595         {
2596           nbReachedLoops += loop.SetConnected();
2597           break;
2598         }
2599     }
2600     if ( nbReachedLoops == theLoops.myNbLoops )
2601       return false; // no unreachable loops
2602
2603
2604     // try to reach all loops by propagating via internal edges shared by loops
2605     size_t prevNbReached;
2606     do
2607     {
2608       prevNbReached = nbReachedLoops;
2609
2610       for ( size_t iL = 0; iL < theLoops.myNbLoops; ++iL )
2611       {
2612         EdgeLoop& loop = theLoops.myLoops[ iL ];
2613         if ( !loop.myIsBndConnected )
2614           continue;
2615
2616         for ( size_t iE = 0; iE < loop.myLinks.size(); ++iE )
2617           if ( loop.myLinks[ iE ]->IsInternal() )
2618           {
2619             const EdgePart* twinEdge = getTwin( loop.myLinks[ iE ]);
2620             EdgeLoop*          loop2 = theLoops.GetLoopOf( twinEdge );
2621             if ( loop2->SetConnected() && ++nbReachedLoops == theLoops.myNbLoops )
2622               return false; // no unreachable loops
2623           }
2624       }
2625     }
2626     while ( prevNbReached < nbReachedLoops );
2627
2628
2629
2630     for ( size_t iL = 0; iL < theLoops.myNbLoops; ++iL )
2631     {
2632       EdgeLoop& loop = theLoops.myLoops[ iL ];
2633       if ( loop.myIsBndConnected || loop.myLinks.size() == 0 )
2634         continue;
2635
2636       if ( loop.myHasPending )
2637       {
2638         // try to join the loop to another one, with which it contacts at a node
2639
2640         // look for a node where the loop reverses
2641         const EdgePart* edgePrev = loop.myLinks.back();
2642         for ( size_t iE = 0; iE < loop.myLinks.size(); edgePrev = loop.myLinks[ iE++ ] )
2643         {
2644           if ( !edgePrev->IsTwin( *loop.myLinks[ iE ]))
2645             continue;
2646           const SMDS_MeshNode* reverseNode = edgePrev->myNode2;
2647
2648           // look for a loop including reverseNode
2649           size_t iContactEdge2; // index(+1) of edge starting at reverseNode
2650           for ( size_t iL2 = 0; iL2 < theLoops.myNbLoops; ++iL2 )
2651           {
2652             if ( iL == iL2 )
2653               continue;
2654             EdgeLoop& loop2 = theLoops.myLoops[ iL2 ];
2655             if ( ! ( iContactEdge2 = loop2.Contains( reverseNode )))
2656               continue;
2657
2658             // insert loop2 into the loop
2659             theLoops.Join( loop, iE, loop2, iContactEdge2 - 1 );
2660             break;
2661           }
2662           if ( loop.myIsBndConnected )
2663             break;
2664         }
2665
2666         if ( loop.myIsBndConnected )
2667           continue;
2668       }
2669
2670       // add links connecting internal loops with the boundary ones
2671
2672       // find a pair of closest nodes
2673       const SMDS_MeshNode *closestNode1, *closestNode2;
2674       double minDist = 1e100;
2675       for ( size_t iE = 0; iE < loop.myLinks.size(); ++iE )
2676       {
2677         SMESH_NodeXYZ n1 = loop.myLinks[ iE ]->myNode1;
2678
2679         for ( size_t i = 0; i < myLinks.size(); ++i )
2680         {
2681           if ( !loop.Contains( myLinks[i].myNode1 ))
2682           {
2683             double dist = n1.SquareDistance( myLinks[i].myNode1 );
2684             if ( dist < minDist )
2685             {
2686               minDist = dist;
2687               closestNode1 = loop.myLinks[ iE ]->myNode1;
2688               closestNode2 = myLinks[i].myNode1;
2689             }
2690           }
2691           if ( myLinks[i].IsInternal() )
2692             ++i;
2693         }
2694       }
2695
2696       size_t i = myLinks.size();
2697       myLinks.resize( i + 2 );
2698       myLinks[ i   ].Set( closestNode1, closestNode2 );
2699       myLinks[ i+1 ].Set( closestNode2, closestNode1 );
2700     }
2701
2702     return true;
2703   }
2704
2705   //================================================================================
2706   /*!
2707    * \brief Return equal reversed edge
2708    */
2709   //================================================================================
2710
2711   EdgePart* CutFace::getTwin( const EdgePart* edge ) const
2712   {
2713     size_t i = edge - & myLinks[0];
2714
2715     if ( i > 2 && myLinks[ i-1 ].IsTwin( *edge ))
2716       return & myLinks[ i-1 ];
2717
2718     if ( i+1 < myLinks.size() &&
2719          myLinks[ i+1 ].IsTwin( *edge ))
2720       return & myLinks[ i+1 ];
2721
2722     return 0;
2723   }
2724
2725   //================================================================================
2726   /*!
2727    * \brief Fill loops of edges
2728    */
2729   //================================================================================
2730
2731   void CutFace::MakeLoops( EdgeLoopSet& theLoops, const gp_XYZ& theFaceNorm ) const
2732   {
2733     theLoops.Init( myLinks );
2734
2735     if ( myLinks.size() == 3 )
2736     {
2737       theLoops.AddNewLoop();
2738       theLoops.AddEdge( myLinks[0] );
2739       theLoops.AddEdge( myLinks[1] );
2740       theLoops.AddEdge( myLinks[2] );
2741       return;
2742     }
2743
2744     while ( !theLoops.AllEdgesUsed() )
2745     {
2746       EdgeLoop& loop = theLoops.AddNewLoop();
2747
2748       // add 1st edge to a new loop
2749       size_t i1;
2750       for ( i1 = theLoops.myNbLoops - 1; i1 < myLinks.size(); ++i1 )
2751         if ( theLoops.AddEdge( myLinks[i1] ))
2752           break;
2753
2754       EdgePart*             lastEdge = & myLinks[ i1 ];
2755       EdgePart*             twinEdge = getTwin( lastEdge );
2756       const SMDS_MeshNode* firstNode = lastEdge->myNode1;
2757       const SMDS_MeshNode*  lastNode = lastEdge->myNode2;
2758
2759       do // add the rest edges
2760       {
2761         theLoops.myCandidates.clear(); // edges starting at lastNode
2762         int nbInternal = 0;
2763
2764         // find candidate edges
2765         for ( size_t i = i1 + 1; i < myLinks.size(); ++i )
2766           if ( myLinks[ i ].myNode1 == lastNode &&
2767                &myLinks[ i ] != twinEdge &&
2768                !theLoops.myIsUsedEdge[ i ])
2769           {
2770             theLoops.myCandidates.push_back( & myLinks[ i ]);
2771             nbInternal += myLinks[ i ].IsInternal();
2772           }
2773
2774         // choose among candidates
2775         if ( theLoops.myCandidates.size() == 0 )
2776         {
2777           loop.myHasPending = bool( twinEdge );
2778           lastEdge = twinEdge;
2779         }
2780         else if ( theLoops.myCandidates.size() == 1 )
2781         {
2782           lastEdge = theLoops.myCandidates[0];
2783         }
2784         else if ( nbInternal == 1 && !lastEdge->IsInternal() )
2785         {
2786           lastEdge = theLoops.myCandidates[ !theLoops.myCandidates[0]->IsInternal() ];
2787         }
2788         else
2789         {
2790           gp_Vec  lastVec = *lastEdge;
2791           double maxAngle = -2 * M_PI;
2792           for ( size_t i = 0; i < theLoops.myCandidates.size(); ++i )
2793           {
2794             double angle = lastVec.AngleWithRef( *theLoops.myCandidates[i], theFaceNorm );
2795             if ( angle > maxAngle )
2796             {
2797               maxAngle = angle;
2798               lastEdge = theLoops.myCandidates[i];
2799             }
2800           }
2801         }
2802         theLoops.AddEdge( *lastEdge );
2803         lastNode = lastEdge->myNode2;
2804         twinEdge = getTwin( lastEdge );
2805       }
2806       while ( lastNode != firstNode );
2807
2808
2809       if ( twinEdge == & myLinks[ i1 ])
2810         loop.myHasPending = true;
2811
2812     } // while ( !theLoops.AllEdgesUsed() )
2813
2814     return;
2815   }
2816
2817   //================================================================================
2818   /*!
2819    * \brief Erase loops that are cut off by face intersections
2820    */
2821   //================================================================================
2822
2823   void CutFace::CutOffLoops( EdgeLoopSet&                 theLoops,
2824                              const double                 theSign,
2825                              const std::vector< gp_XYZ >& theNormals,
2826                              std::vector< EdgePart >&     theCutOffLinks,
2827                              TLinkMap&                    theCutOffCoplanarLinks) const
2828   {
2829     EdgePart sideEdge;
2830     for ( size_t i = 0; i < myLinks.size(); ++i )
2831     {
2832       if ( !myLinks[i].myFace )
2833         continue;
2834
2835       EdgeLoop* loop = theLoops.GetLoopOf( & myLinks[i] );
2836       if ( !loop || loop->myLinks.empty() || loop->myHasPending )
2837         continue;
2838
2839       bool toErase, isCoplanar = ( myLinks[i].myIndex == EdgePart::_COPLANAR );
2840
2841       gp_Vec iniNorm = theNormals[ myInitFace->GetID() ];
2842       if ( isCoplanar )
2843       {
2844         toErase = ( myLinks[i].myFace->GetID() > myInitFace->GetID() );
2845
2846         const EdgePart* twin = getTwin( & myLinks[i] );
2847         if ( !twin || twin->myFace == myLinks[i].myFace )
2848         {
2849           // only one co-planar face includes myLinks[i]
2850           gp_Vec inFaceDir = iniNorm ^ myLinks[i];
2851           gp_XYZ   edgePnt = SMESH_NodeXYZ( myLinks[i].myNode1 );
2852           for ( int iN = 0; iN < 3; ++iN )
2853           {
2854             gp_Vec inCutFaceDir = ( SMESH_NodeXYZ( myLinks[i].myFace->GetNode( iN )) - edgePnt );
2855             if ( inCutFaceDir * inFaceDir < 0 )
2856             {
2857               toErase = false;
2858               break;
2859             }
2860           }
2861         }
2862       }
2863       else
2864       {
2865         gp_Vec   cutNorm = theNormals[ myLinks[i].myFace->GetID() ];
2866         gp_Vec inFaceDir = iniNorm ^ myLinks[i];
2867
2868         toErase = inFaceDir * cutNorm * theSign < 0;
2869         if ( !toErase )
2870         {
2871           // erase a neighboring loop
2872           loop = 0;
2873           if ( const EdgePart* twin = getTwin( & myLinks[i] ))
2874             loop = theLoops.GetLoopOf( twin );
2875           toErase = ( loop && !loop->myLinks.empty() );
2876         }
2877       }
2878
2879       if ( toErase )
2880       {
2881         if ( !isCoplanar )
2882         {
2883           // remember whole sides of myInitFace that are cut off
2884           for ( size_t iE = 0; iE < loop->myLinks.size(); ++iE )
2885           {
2886             if ( !loop->myLinks[ iE ]->myFace              &&
2887                  !loop->myLinks[ iE ]->IsInternal()     )//   &&
2888                  // !loop->myLinks[ iE ]->myNode1->isMarked() && // cut nodes are marked
2889                  // !loop->myLinks[ iE ]->myNode2->isMarked() )
2890             {
2891               int i = loop->myLinks[ iE ]->myIndex;
2892               sideEdge.Set( myInitFace->GetNode    ( i   ),
2893                             myInitFace->GetNodeWrap( i+1 ));
2894               theCutOffLinks.push_back( sideEdge );
2895
2896               if ( !sideEdge.IsSame( *loop->myLinks[ iE ] )) // nodes replaced
2897               {
2898                 theCutOffLinks.push_back( *loop->myLinks[ iE ] );
2899               }
2900             }
2901             else if ( IsCoplanar( loop->myLinks[ iE ]))
2902             {
2903               // propagate erasure to a co-planar face
2904               theCutOffLinks.push_back( *loop->myLinks[ iE ]);
2905             }
2906             else if ( loop->myLinks[ iE ]->myFace &&
2907                       loop->myLinks[ iE ]->IsInternal() )
2908               theCutOffLinks.push_back( *loop->myLinks[ iE ]);
2909           }
2910
2911           // clear the loop
2912           theLoops.Erase( loop );
2913         }
2914       }
2915     }
2916     return;
2917   }
2918
2919   //================================================================================
2920   /*!
2921    * \brief Check if the face has cut edges
2922    */
2923   //================================================================================
2924
2925   bool CutFace::IsCut() const
2926   {
2927     if ( myLinks.size() > 3 )
2928       return true;
2929
2930     if ( myLinks.size() == 3 )
2931       for ( size_t i = 0; i < 3; ++i )
2932         if ( myLinks[i].myFace )
2933           return true;
2934
2935     return false;
2936   }
2937
2938   //================================================================================
2939   /*!
2940    * \brief Check if an edge is produced by a co-planar cut
2941    */
2942   //================================================================================
2943
2944   bool CutFace::IsCoplanar( const EdgePart* edge ) const
2945   {
2946     if ( edge->myIndex == EdgePart::_COPLANAR )
2947     {
2948       const EdgePart* twin = getTwin( edge );
2949       return ( !twin || twin->myIndex == EdgePart::_COPLANAR );
2950     }
2951     return false;
2952   }
2953
2954   //================================================================================
2955   /*!
2956    * \brief Replace _COPLANAR cut edge by _INTERNAL or vice versa
2957    */
2958   //================================================================================
2959
2960   bool EdgePart::ReplaceCoplanar( const EdgePart& e )
2961   {
2962     if ( myIndex + e.myIndex == _COPLANAR + _INTERNAL )
2963     {
2964       //check if the faces are connected
2965       int nbCommonNodes = SMESH_MeshAlgos::GetCommonNodes( e.myFace, myFace ).size();
2966       bool toReplace = (( myIndex == _INTERNAL && nbCommonNodes > 1 ) ||
2967                         ( myIndex == _COPLANAR && nbCommonNodes < 2 ));
2968       if ( toReplace )
2969       {
2970         myIndex = e.myIndex;
2971         myFace  = e.myFace;
2972         return true;
2973       }
2974     }
2975     return false;
2976   }
2977
2978 } // namespace
2979
2980 //================================================================================
2981 /*!
2982  * \brief Create an offsetMesh of given faces
2983  *  \param [in] faceIt - the input faces
2984  *  \param [out] new2OldFaces - history of faces (new face -> old face ID)
2985  *  \param [out] new2OldNodes - history of nodes (new node -> old node ID)
2986  *  \return SMDS_Mesh* - the new offset mesh, a caller should delete
2987  */
2988 //================================================================================
2989
2990 SMDS_Mesh* SMESH_MeshAlgos::MakeOffset( SMDS_ElemIteratorPtr theFaceIt,
2991                                         SMDS_Mesh&           theSrcMesh,
2992                                         const double         theOffset,
2993                                         const bool           theFixIntersections,
2994                                         TElemIntPairVec&     theNew2OldFaces,
2995                                         TNodeIntPairVec&     theNew2OldNodes)
2996 {
2997   if ( theSrcMesh.GetMeshInfo().NbFaces( ORDER_QUADRATIC ) > 0 )
2998     throw SALOME_Exception( "Offset of quadratic mesh not supported" );
2999   if ( theSrcMesh.GetMeshInfo().NbFaces() > theSrcMesh.GetMeshInfo().NbTriangles() )
3000     throw SALOME_Exception( "Offset of non-triangular mesh not supported" );
3001
3002   SMDS_Mesh* newMesh = new SMDS_Mesh;
3003   theNew2OldFaces.clear();
3004   theNew2OldNodes.clear();
3005   theNew2OldFaces.push_back
3006     ( std::make_pair(( const SMDS_MeshElement*) 0, 0)); // to have index == face->GetID()
3007
3008   // copy input faces to the newMesh keeping IDs of nodes
3009
3010   double minNodeDist = 1e100;
3011
3012   std::vector< const SMDS_MeshNode* > nodes;
3013   while ( theFaceIt->more() )
3014   {
3015     const SMDS_MeshElement* face = theFaceIt->next();
3016     if ( face->GetType() != SMDSAbs_Face ) continue;
3017
3018     // copy nodes
3019     nodes.assign( face->begin_nodes(), face->end_nodes() );
3020     for ( size_t i = 0; i < nodes.size(); ++i )
3021     {
3022       const SMDS_MeshNode* newNode = newMesh->FindNode( nodes[i]->GetID() );
3023       if ( !newNode )
3024       {
3025         SMESH_NodeXYZ xyz( nodes[i] );
3026         newNode = newMesh->AddNodeWithID( xyz.X(), xyz.Y(), xyz.Z(), nodes[i]->GetID() );
3027         theNew2OldNodes.push_back( std::make_pair( newNode, nodes[i]->GetID() ));
3028         nodes[i] = newNode;
3029       }
3030     }
3031     const SMDS_MeshElement* newFace = 0;
3032     switch ( face->GetEntityType() )
3033     {
3034     case SMDSEntity_Triangle:
3035       newFace = newMesh->AddFace( nodes[0],nodes[1],nodes[2] );
3036       break;
3037     case SMDSEntity_Quad_Triangle:
3038       newFace = newMesh->AddFace( nodes[0],nodes[1],nodes[2],
3039                                   nodes[3],nodes[4],nodes[5] );
3040       break;
3041     case SMDSEntity_BiQuad_Triangle:
3042       newFace = newMesh->AddFace( nodes[0],nodes[1],nodes[2],
3043                                   nodes[3],nodes[4],nodes[5],nodes[6] );
3044       break;
3045     case SMDSEntity_Quadrangle:
3046       newFace = newMesh->AddFace( nodes[0],nodes[1],nodes[2],nodes[3] );
3047       break;
3048     case SMDSEntity_Quad_Quadrangle:
3049       newFace = newMesh->AddFace( nodes[0],nodes[1],nodes[2],nodes[3],
3050                                   nodes[4],nodes[5],nodes[6],nodes[7] );
3051       break;
3052     case SMDSEntity_BiQuad_Quadrangle:
3053       newFace = newMesh->AddFace( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4],
3054                                   nodes[5],nodes[6],nodes[7],nodes[8] );
3055       break;
3056     case SMDSEntity_Polygon:
3057       newFace = newMesh->AddPolygonalFace( nodes );
3058       break;
3059     case SMDSEntity_Quad_Polygon:
3060       newFace = newMesh->AddQuadPolygonalFace( nodes );
3061       break;
3062     default:
3063       continue;
3064     }
3065     theNew2OldFaces.push_back( std::make_pair( newFace, face->GetID() ));
3066
3067     SMESH_NodeXYZ pPrev = nodes.back(), p;
3068     for ( size_t i = 0; i < nodes.size(); ++i )
3069     {
3070       p.Set( nodes[i] );
3071       double dist = ( pPrev - p ).SquareModulus();
3072       if ( dist > std::numeric_limits<double>::min() )
3073         minNodeDist = dist;
3074       pPrev = p;
3075     }
3076   } // while ( faceIt->more() )
3077
3078
3079   // compute normals to faces
3080   std::vector< gp_XYZ > normals( theNew2OldFaces.size() );
3081   for ( size_t i = 1; i < normals.size(); ++i )
3082   {
3083     if ( !SMESH_MeshAlgos::FaceNormal( theNew2OldFaces[i].first, normals[i] ))
3084       normals[i].SetCoord( 0,0,0 ); // TODO find norm by neighbors
3085   }
3086
3087   const double sign = ( theOffset < 0 ? -1 : +1 );
3088   const double  tol = Min( 1e-3 * Sqrt( minNodeDist ),
3089                            1e-2 * theOffset * sign );
3090
3091   // translate new nodes by normal to input faces
3092   gp_XYZ newXYZ;
3093   std::vector< const SMDS_MeshNode* > multiNormalNodes;
3094   for ( size_t i = 0; i < theNew2OldNodes.size(); ++i )
3095   {
3096     const SMDS_MeshNode* newNode = theNew2OldNodes[i].first;
3097
3098     if ( getTranslatedPosition( newNode, theOffset, tol*10., sign, normals, theSrcMesh, newXYZ ))
3099       newMesh->MoveNode( newNode, newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
3100     else
3101       multiNormalNodes.push_back( newNode );
3102   }
3103   // make multi-normal translation
3104   std::vector< SMESH_NodeXYZ > multiPos(10);
3105   for ( size_t i = 0; i < multiNormalNodes.size(); ++i )
3106   {
3107     const SMDS_MeshNode* newNode = multiNormalNodes[i];
3108     newNode->setIsMarked( true );
3109     SMESH_NodeXYZ oldXYZ = newNode;
3110     multiPos.clear();
3111     for ( SMDS_ElemIteratorPtr fIt = newNode->GetInverseElementIterator(); fIt->more(); )
3112     {
3113       const SMDS_MeshElement* newFace = fIt->next();
3114       const int             faceIndex = newFace->GetID();
3115       const gp_XYZ&           oldNorm = normals[ faceIndex ];
3116       const gp_XYZ             newXYZ = oldXYZ + oldNorm * theOffset;
3117       if ( multiPos.empty() )
3118       {
3119         newMesh->MoveNode( newNode, newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
3120         multiPos.emplace_back( newNode );
3121       }
3122       else
3123       {
3124         newNode = 0;
3125         for ( size_t iP = 0; iP < multiPos.size() &&  !newNode; ++iP )
3126           if (( multiPos[iP] - newXYZ ).SquareModulus() < tol * tol )
3127             newNode = multiPos[iP].Node();
3128         if ( !newNode )
3129         {
3130           newNode = newMesh->AddNode( newXYZ.X(), newXYZ.Y(), newXYZ.Z() );
3131           newNode->setIsMarked( true );
3132           theNew2OldNodes.push_back( std::make_pair( newNode, 0 ));
3133           multiPos.emplace_back( newNode );
3134         }
3135       }
3136       if ( newNode != oldXYZ.Node() )
3137       {
3138         nodes.assign( newFace->begin_nodes(), newFace->end_nodes() );
3139         nodes[ newFace->GetNodeIndex( oldXYZ.Node() )] = newNode;
3140         newMesh->ChangeElementNodes( newFace, & nodes[0], nodes.size() );
3141       }
3142     }
3143   }
3144
3145   if ( !theFixIntersections )
3146     return newMesh;
3147
3148
3149   // remove new faces around concave nodes (they are marked) if the faces are inverted
3150   gp_XYZ faceNorm;
3151   for ( size_t i = 0; i < theNew2OldNodes.size(); ++i )
3152   {
3153     const SMDS_MeshNode* newNode = theNew2OldNodes[i].first;
3154     //const SMDS_MeshNode* oldNode = theNew2OldNodes[i].second;
3155     if ( newNode->isMarked() )
3156     {
3157       //gp_XYZ moveVec = sign * ( SMESH_NodeXYZ( newNode ) - SMESH_NodeXYZ( oldNode ));
3158
3159       //bool haveInverseFace = false;
3160       for ( SMDS_ElemIteratorPtr fIt = newNode->GetInverseElementIterator(); fIt->more(); )
3161       {
3162         const SMDS_MeshElement* newFace = fIt->next();
3163         const int             faceIndex = newFace->GetID();
3164         const gp_XYZ&           oldNorm = normals[ faceIndex ];
3165         if ( !SMESH_MeshAlgos::FaceNormal( newFace, faceNorm, /*normalize=*/false ) ||
3166              //faceNorm * moveVec < 0 )
3167              faceNorm * oldNorm < 0 )
3168         {
3169           //haveInverseFace = true;
3170           theNew2OldFaces[ faceIndex ].first = 0;
3171           newMesh->RemoveFreeElement( newFace );
3172           //break;
3173         }
3174       }
3175       // if ( haveInverseFace )
3176       // {
3177       //   newMesh->MoveNode( newNode, oldNode->X(), oldNode->Y(), oldNode->Z() );
3178
3179       //   for ( SMDS_ElemIteratorPtr fIt = newNode->GetInverseElementIterator(); fIt->more(); )
3180       //   {
3181       //     const SMDS_MeshElement* newFace = fIt->next();
3182       //     if ( !SMESH_MeshAlgos::FaceNormal( newFace, normals[ newFace->GetID() ] ))
3183       //       normals[i].SetCoord( 0,0,0 ); // TODO find norm by neighbors
3184       //   }
3185       // }
3186     }
3187     // mark all new nodes located closer than theOffset from theSrcMesh
3188   }
3189
3190   // ==================================================
3191   // find self-intersections of new faces and fix them
3192   // ==================================================
3193
3194   std::unique_ptr< SMESH_ElementSearcher > fSearcher
3195     ( SMESH_MeshAlgos::GetElementSearcher( *newMesh, tol ));
3196
3197   Intersector intersector( newMesh, tol, normals );
3198
3199   std::vector< const SMDS_MeshElement* > closeFaces;
3200   std::vector< const SMDS_MeshNode* >    faceNodes;
3201   Bnd_B3d faceBox;
3202   for ( size_t iF = 1; iF < theNew2OldFaces.size(); ++iF )
3203   {
3204     const SMDS_MeshElement* newFace = theNew2OldFaces[iF].first;
3205     if ( !newFace ) continue;
3206     faceNodes.assign( newFace->begin_nodes(), newFace->end_nodes() );
3207
3208     bool isConcaveNode1 = false;
3209     for ( size_t iN = 0; iN < faceNodes.size() && !isConcaveNode1; ++iN )
3210       isConcaveNode1 = faceNodes[iN]->isMarked();
3211
3212     // get faces close to a newFace
3213     closeFaces.clear();
3214     faceBox.Clear();
3215     for ( size_t i = 0; i < faceNodes.size(); ++i )
3216       faceBox.Add( SMESH_NodeXYZ( faceNodes[i] ));
3217     faceBox.Enlarge( tol );
3218
3219     fSearcher->GetElementsInBox( faceBox, SMDSAbs_Face, closeFaces );
3220
3221     // intersect the newFace with closeFaces
3222
3223     for ( size_t i = 0; i < closeFaces.size(); ++i )
3224     {
3225       const SMDS_MeshElement* closeFace = closeFaces[i];
3226       if ( closeFace->GetID() <= newFace->GetID() )
3227         continue; // this pair already treated
3228
3229       // do not intersect connected faces if they have no concave nodes
3230       int nbCommonNodes = 0;
3231       for ( size_t iN = 0; iN < faceNodes.size(); ++iN )
3232         nbCommonNodes += ( closeFace->GetNodeIndex( faceNodes[iN] ) >= 0 );
3233
3234       if ( !isConcaveNode1 )
3235       {
3236         bool isConcaveNode2 = false;
3237         for ( SMDS_ElemIteratorPtr nIt = closeFace->nodesIterator(); nIt->more(); )
3238           if (( isConcaveNode2 = nIt->next()->isMarked() ))
3239             break;
3240
3241         if ( !isConcaveNode2 && nbCommonNodes > 0 )
3242           continue;
3243       }
3244
3245       intersector.Cut( newFace, closeFace, nbCommonNodes );
3246     }
3247   }
3248   intersector.MakeNewFaces( theNew2OldFaces, theNew2OldNodes, sign );
3249
3250   return newMesh;
3251 }