Salome HOME
5941efbec62f9f9085b84df486587b98e3936733
[modules/shaper.git] / src / GeomAlgoAPI / GeomAlgoAPI_SketchBuilder.cpp
1 // File:        GeomAlgoAPI_SketchBuilder.cpp
2 // Created:     02 Jun 2014
3 // Author:      Artem ZHIDKOV
4
5 #include <GeomAlgoAPI_SketchBuilder.h>
6
7 #include <set>
8
9 #include <gp_Dir.hxx>
10 #include <gp_Pln.hxx>
11
12 #include <BOPAlgo_Builder.hxx>
13 #include <BOPAlgo_Operation.hxx>
14 #include <BOPAlgo_PaveFiller.hxx>
15 #include <BOPTools.hxx>
16 #include <BRep_Builder.hxx>
17 #include <BRep_Curve3D.hxx>
18 #include <BRep_TEdge.hxx>
19 #include <BRep_TVertex.hxx>
20 #include <BRepAlgoAPI_Cut.hxx>
21 #include <BRepBuilderAPI_MakeFace.hxx>
22 #include <BRepClass_FaceClassifier.hxx>
23 #include <Geom_Curve.hxx>
24 #include <Geom_Plane.hxx>
25 #include <TopExp.hxx>
26 #include <TopExp_Explorer.hxx>
27 #include <TopoDS_Edge.hxx>
28 #include <TopoDS_Face.hxx>
29 #include <TopoDS_Vertex.hxx>
30 #include <TopoDS_Wire.hxx>
31
32 #include <Precision.hxx>
33
34 #ifndef DBL_MAX
35 #define DBL_MAX 1.7976931348623158e+308 
36 #endif
37
38
39 const double tolerance = Precision::Confusion();
40 // This value helps to find direction on the boundaries of curve.
41 // It is not significant for lines, but is used for circles to avoid 
42 // wrong directions of movement (when two edges are tangent on the certain vertex)
43 const double shift     = acos(1.0 - 2.0 * tolerance);
44
45 /// \brief Search first vertex - the vertex with lowest x coordinate, which is used in 2 edges at least
46 static const TopoDS_Shape& findStartVertex(
47           const BOPCol_IndexedDataMapOfShapeListOfShape& theMapVE,
48           const gp_Dir& theDirX, const gp_Dir& theDirY);
49
50 /// \brief Search the vertex on the sketch candidate to be the next one in the loop
51 static void findNextVertex(
52           const TopoDS_Shape&                            theStartVertex, 
53           const BOPCol_IndexedDataMapOfShapeListOfShape& theVertexEdgeMap,
54           const gp_Dir&                                  theStartDir,
55           const gp_Dir&                                  theNormal,
56                 TopoDS_Shape&                            theNextVertex,
57                 TopoDS_Shape&                            theNextEdge,
58                 gp_Dir&                                  theNextDir);
59
60 /// \brief Create planar face using the edges surrounding it
61 static void createFace(const TopoDS_Shape&                      theStartVertex,
62                        const std::list<TopoDS_Shape>::iterator& theStartEdge,
63                        const std::list<TopoDS_Shape>::iterator& theEndOfEdges,
64                        const gp_Pln&                            thePlane,
65                              TopoDS_Face&                       theResFace);
66
67 /// \bief Create planar wire
68 static void createWireList(const TopoDS_Shape&                      theStartVertex,
69                            const std::list<TopoDS_Shape>::iterator& theStartEdge,
70                            const std::list<TopoDS_Shape>::iterator& theEndOfEdges,
71                            const std::set<Handle(TopoDS_TShape)>&   theEdgesInLoops,
72                                  std::list<TopoDS_Wire>&            theResWires);
73
74 /// \brief Calculate outer tengency on the edge in specified vertex
75 static gp_Dir getOuterEdgeDirection(const TopoDS_Shape& theEdge,
76                                     const TopoDS_Shape& theVertex);
77
78 /// \brief Unnecessary edges will be removed from the map.
79 ///        Positions of iterator will be updated
80 static void removeWasteEdges(
81                 std::list<TopoDS_Shape>::iterator&  theStartVertex,
82                 std::list<TopoDS_Shape>::iterator&  theStartEdge,
83           const std::list<TopoDS_Shape>::iterator&  theEndOfVertexes,
84           const std::list<TopoDS_Shape>::iterator&  theEndOfEdges,
85           BOPCol_IndexedDataMapOfShapeListOfShape&  theMapVE);
86
87
88
89
90 void GeomAlgoAPI_SketchBuilder::createFaces(
91           const boost::shared_ptr<GeomAPI_Pnt>&                theOrigin,
92           const boost::shared_ptr<GeomAPI_Dir>&                theDirX,
93           const boost::shared_ptr<GeomAPI_Dir>&                theDirY,
94           const boost::shared_ptr<GeomAPI_Dir>&                theNorm,
95           const std::list< boost::shared_ptr<GeomAPI_Shape> >& theFeatures,
96                 std::list< boost::shared_ptr<GeomAPI_Shape> >& theResultFaces,
97                 std::list< boost::shared_ptr<GeomAPI_Shape> >& theResultWires)
98 {
99   if (theFeatures.empty())
100     return ;
101
102   // Create the list of edges with shared vertexes
103   BOPAlgo_Builder aBuilder;
104   BOPAlgo_PaveFiller aPF;
105   TopoDS_Shape aFeaturesCompound;
106
107   if (theFeatures.size() == 1)
108   { // If there is only one feature, BOPAlgo_Builder will decline to work. Need to process it anyway
109     aFeaturesCompound = theFeatures.front()->impl<TopoDS_Shape>();
110   }
111   else
112   {
113     std::list< boost::shared_ptr<GeomAPI_Shape> >::const_iterator anIt = theFeatures.begin();
114     for (; anIt != theFeatures.end(); anIt++)
115     {
116       boost::shared_ptr<GeomAPI_Shape> aPreview(*anIt);
117       aBuilder.AddArgument(aPreview->impl<TopoDS_Edge>());
118     }
119     aPF.SetArguments(aBuilder.Arguments());
120     aPF.Perform();
121     int aErr = aPF.ErrorStatus();
122     if (aErr) return ;
123     aBuilder.PerformWithFiller(aPF);
124     aErr = aBuilder.ErrorStatus();
125     if (aErr) return ;
126     aFeaturesCompound = aBuilder.Shape();
127   }
128
129   BOPCol_IndexedDataMapOfShapeListOfShape aMapVE; // map between vertexes and edges
130   BOPTools::MapShapesAndAncestors(aFeaturesCompound, TopAbs_VERTEX, TopAbs_EDGE, aMapVE);
131
132   gp_Dir aDirX = theDirX->impl<gp_Dir>();
133   gp_Dir aDirY = theDirY->impl<gp_Dir>();
134   gp_Dir aNorm = theNorm->impl<gp_Dir>();
135
136   gp_Pln aPlane(theOrigin->impl<gp_Pnt>(), aNorm);
137
138   // Set of edges used in loops
139   std::set<Handle(TopoDS_TShape)> anEdgesInLoops;
140   // Lists for processed vertexes and edges
141   std::list<TopoDS_Shape> aProcVertexes;
142   std::list<TopoDS_Shape> aProcEdges;
143
144   // Search the start vertex
145   TopoDS_Shape aStartVertex = findStartVertex(aMapVE, aDirX, aDirY);
146   aProcVertexes.push_back(aStartVertex);
147
148   TopoDS_Shape aCurVertex = aStartVertex;
149   gp_Dir aCurDir = aDirY.Reversed();
150   gp_Dir aCurNorm = aNorm.Reversed();
151
152   // Go through the edges and find loops
153   TopoDS_Shape aNextVertex;
154   TopoDS_Shape aBindingEdge;
155   gp_Dir aNextDir;
156   while (aMapVE.Extent() > 0)
157   {
158     findNextVertex(aCurVertex, aMapVE, aCurDir, aCurNorm, aNextVertex, aBindingEdge, aNextDir);
159     aCurNorm = aNorm;
160
161     // Try to find next vertex in the list of already processed
162     std::list<TopoDS_Shape>::iterator          aVertIter = aProcVertexes.begin();
163     std::list<TopoDS_Shape>::iterator          anEdgeIter = aProcEdges.begin();
164     for ( ; aVertIter != aProcVertexes.end(); aVertIter++)
165     {
166       if (aVertIter->TShape() == aNextVertex.TShape())
167         break;
168       if (anEdgeIter != aProcEdges.end())
169         anEdgeIter++;
170     }
171
172     aProcVertexes.push_back(aNextVertex);
173     aProcEdges.push_back(aBindingEdge);
174
175     // The loop was found
176     if (aVertIter != aProcVertexes.end())
177     {
178       // If the binding edge is a full circle, then the list may be empty before addition. Need to update edge iterator
179       if (aProcEdges.size() == 1)
180         anEdgeIter = aProcEdges.begin();
181
182       if (aVertIter != aProcVertexes.begin())
183       {
184         // Check the orientation of the loop
185         gp_Dir aCN = getOuterEdgeDirection(*anEdgeIter, *aVertIter);
186         gp_Dir aCP = getOuterEdgeDirection(aProcEdges.back(), *aVertIter);
187         aCN.Reverse();
188         aCP.Reverse();
189         if (aCN.DotCross(aCP, aNorm) < -tolerance)
190         {
191           // The found loop has wrong orientation and may contain sub-loops.
192           // Need to check it onle again with another initial direction.
193           aCurVertex = *aVertIter;
194           do {
195             aProcVertexes.pop_back();
196             aProcEdges.pop_back();
197           } while (aCurVertex != aProcVertexes.back());
198           aCurDir = getOuterEdgeDirection(aProcEdges.back(), aCurVertex);
199           aCurNorm = aNorm.Reversed();
200           continue;
201         }
202       }
203
204       // When the orientation is correct or the edges looped through
205       // the first element, create new face and remove unnecessary edges.
206       TopoDS_Face aPatch;
207       createFace(*aVertIter, anEdgeIter, aProcEdges.end(), aPlane, aPatch);
208       if (!aPatch.IsNull())
209       {
210         boost::shared_ptr<GeomAPI_Shape> aFace(new GeomAPI_Shape);
211         aFace->setImpl(new TopoDS_Shape(aPatch));
212         theResultFaces.push_back(aFace);
213       }
214       // push the edges used in the loop to the map
215       std::list<TopoDS_Shape>::iterator anIter;
216       for (anIter = anEdgeIter; anIter != aProcEdges.end(); anIter++)
217         anEdgesInLoops.insert(anIter->TShape());
218       // remove unnecessary edges
219       std::list<TopoDS_Shape>::iterator aCopyVLoop = aVertIter;
220       std::list<TopoDS_Shape>::iterator aCopyELoop = anEdgeIter;
221       removeWasteEdges(aVertIter, anEdgeIter, aProcVertexes.end(), aProcEdges.end(), aMapVE);
222
223       // revert the list of remaining edges
224       std::list<TopoDS_Shape> aRemainVertexes;
225       for ( ; aVertIter != aProcVertexes.end(); aVertIter++)
226         aRemainVertexes.push_front(*aVertIter);
227       std::list<TopoDS_Shape> aRemainEdges;
228       for ( ; anEdgeIter != aProcEdges.end(); anEdgeIter++)
229         aRemainEdges.push_front(*anEdgeIter);
230       // remove edges and vertexes used in the loop and add remaining ones
231       aProcVertexes.erase(aCopyVLoop, aProcVertexes.end());
232       aProcVertexes.insert(aProcVertexes.end(), aRemainVertexes.begin(), aRemainVertexes.end());
233       aProcEdges.erase(aCopyELoop, aProcEdges.end());
234       aProcEdges.insert(aProcEdges.end(), aRemainEdges.begin(), aRemainEdges.end());
235
236       // Recalculate current vertex and current direction
237       if (!aProcVertexes.empty())
238       {
239         aNextVertex = aProcVertexes.back();
240         if (!aProcEdges.empty())
241           aNextDir = getOuterEdgeDirection(aProcEdges.back(), aNextVertex);
242         else aNextDir = aDirY;
243       }
244     }
245
246     // if next vertex connected only to alone edge, this is a part of wire (not a closed loop),
247     // we need to go back through the list of already checked edges to find a branching vertex
248     if (!aMapVE.IsEmpty() && aMapVE.Contains(aNextVertex) && 
249         aMapVE.FindFromKey(aNextVertex).Size() == 1)
250     {
251       std::list<TopoDS_Shape>::reverse_iterator aVRIter = aProcVertexes.rbegin();
252       std::list<TopoDS_Shape>::reverse_iterator aERIter = aProcEdges.rbegin();
253       for (++aERIter, ++aVRIter; aERIter != aProcEdges.rend(); aERIter++, aVRIter++)
254         if (aMapVE.FindFromKey(*aVRIter).Size() > 2)
255           break;
256       if (aERIter != aProcEdges.rend() || aMapVE.FindFromKey(*aVRIter).Size() == 1)
257       { // the branching vertex was found or current list of edges is a wire without branches
258         std::list<TopoDS_Shape>::iterator aEIter;
259         TopoDS_Shape aCurEdge;
260         if (aERIter != aProcEdges.rend())
261         {
262           aEIter = aERIter.base();
263           aCurEdge = *aERIter;
264         }
265         else
266           aEIter = aProcEdges.begin();
267         std::list<TopoDS_Wire> aTail;
268         createWireList(*aVRIter, aEIter, aProcEdges.end(), anEdgesInLoops, aTail);
269         std::list<TopoDS_Wire>::const_iterator aTailIter = aTail.begin();
270         for ( ; aTailIter != aTail.end(); aTailIter++)
271           if (!aTailIter->IsNull())
272           {
273             boost::shared_ptr<GeomAPI_Shape> aWire(new GeomAPI_Shape);
274             aWire->setImpl(new TopoDS_Shape(*aTailIter));
275             theResultWires.push_back(aWire);
276           }
277         std::list<TopoDS_Shape>::iterator aVIter = aVRIter.base();
278         std::list<TopoDS_Shape>::iterator aEItCopy = aEIter;
279         removeWasteEdges(--aVIter, aEItCopy, aProcVertexes.end(), aProcEdges.end(), aMapVE);
280
281         aProcEdges.erase(aEIter, aProcEdges.end());
282         aVIter = aVRIter.base();
283         aProcVertexes.erase(aVIter, aProcVertexes.end());
284
285         if (!aProcVertexes.empty())
286         {
287           aNextVertex = aProcVertexes.back();
288           if (!aCurEdge.IsNull())
289             aNextDir = getOuterEdgeDirection(aCurEdge, aNextVertex);
290         }
291       }
292       else
293       { // there is no branching vertex in the list of proceeded,
294         // so we should revert the list and go the opposite way
295         aProcVertexes.reverse();
296         aProcEdges.reverse();
297         aNextVertex = aProcVertexes.back();
298         aNextDir = getOuterEdgeDirection(aProcEdges.back(), aNextVertex);
299       }
300     }
301
302     // When all edges of current component of connectivity are processed,
303     // we should repeat procedure for finding initial vertex in the remaining
304     if (!aMapVE.IsEmpty() && !aMapVE.Contains(aNextVertex))
305     {
306       aProcVertexes.clear();
307       aProcEdges.clear();
308
309       TopoDS_Shape aStartEdge;
310       aStartVertex = findStartVertex(aMapVE, aDirX, aDirY);
311       aProcVertexes.push_back(aStartVertex);
312       aNextVertex = aStartVertex;
313       aNextDir = aDirY.Reversed();
314       aCurNorm = aNorm.Reversed();
315     }
316
317     aCurVertex = aNextVertex;
318     aCurDir = aNextDir;
319   }
320
321   if (theResultFaces.size() > 1)
322     fixIntersections(theResultFaces);
323 }
324
325 void GeomAlgoAPI_SketchBuilder::fixIntersections(
326           std::list< boost::shared_ptr<GeomAPI_Shape> >& theFaces)
327 {
328   BRepClass_FaceClassifier aClassifier;
329
330   std::list< boost::shared_ptr<GeomAPI_Shape> >::iterator anIter1 = theFaces.begin();
331   std::list< boost::shared_ptr<GeomAPI_Shape> >::iterator anIter2;
332   for ( ; anIter1 != theFaces.end(); anIter1++)
333   {
334     anIter2 = anIter1;
335     for (++anIter2; anIter2 != theFaces.end(); anIter2++)
336     {
337       const TopoDS_Face& aF1 = (*anIter1)->impl<TopoDS_Face>();
338       TopExp_Explorer aVert2((*anIter2)->impl<TopoDS_Shape>(), TopAbs_VERTEX);
339       for ( ; aVert2.More(); aVert2.Next())
340       {
341         Handle(BRep_TVertex) aV = Handle(BRep_TVertex)::DownCast(aVert2.Current().TShape());
342         aClassifier.Perform(aF1, aV->Pnt(), tolerance);
343         if (aClassifier.State() != TopAbs_IN)
344           break;
345       }
346       if (aVert2.More())
347       { // second shape is not inside first, change the shapes order and repeat comparision
348         const TopoDS_Face& aF2 = (*anIter2)->impl<TopoDS_Face>();
349         TopExp_Explorer aVert1((*anIter1)->impl<TopoDS_Shape>(), TopAbs_VERTEX);
350         for ( ; aVert1.More(); aVert1.Next())
351         {
352           Handle(BRep_TVertex) aV = Handle(BRep_TVertex)::DownCast(aVert1.Current().TShape());
353           aClassifier.Perform(aF2, aV->Pnt(), tolerance);
354           if (aClassifier.State() != TopAbs_IN)
355             break;
356         }
357         if (!aVert1.More())
358         { // first shape should be cut from the second
359           BRepAlgoAPI_Cut aCut((*anIter2)->impl<TopoDS_Shape>(),
360                                (*anIter1)->impl<TopoDS_Shape>());
361           (*anIter2)->setImpl(new TopoDS_Shape(aCut.Shape()));
362         }
363       }
364       else
365       { // second shape should be cut from the first
366         BRepAlgoAPI_Cut aCut((*anIter1)->impl<TopoDS_Shape>(),
367                              (*anIter2)->impl<TopoDS_Shape>());
368         (*anIter1)->setImpl(new TopoDS_Shape(aCut.Shape()));
369       }
370     }
371   }
372 }
373
374
375 // =================== Auxiliary functions ====================================
376 const TopoDS_Shape& findStartVertex(
377           const BOPCol_IndexedDataMapOfShapeListOfShape& theMapVE,
378           const gp_Dir& theDirX, const gp_Dir& theDirY)
379 {
380   int aStartVertexInd = 1;
381   double aMaxX = -DBL_MAX;
382   double aMaxY = -DBL_MAX;
383   int aNbVert = theMapVE.Extent();
384   for (int i = 1; i <= aNbVert; i++)
385   {
386     const TopoDS_Vertex& aV = (const TopoDS_Vertex&)theMapVE.FindKey(i);
387     const Handle(BRep_TVertex)& aVert = (const Handle(BRep_TVertex)&)aV.TShape();
388     const gp_Pnt& aVertPnt = aVert->Pnt();
389
390     double aX = aVertPnt.XYZ().Dot(theDirX.XYZ());
391     double aY = aVertPnt.XYZ().Dot(theDirY.XYZ());
392     if ((aX > aMaxX || (fabs(aX - aMaxX) < tolerance && aY > aMaxY)) && 
393         theMapVE.FindFromIndex(i).Extent() > 1)
394     {
395       aMaxX = aX;
396       aMaxY = aY;
397       aStartVertexInd = i;
398     }
399   }
400   return theMapVE.FindKey(aStartVertexInd);
401 }
402
403 void findNextVertex(
404           const TopoDS_Shape&                            theStartVertex,
405           const BOPCol_IndexedDataMapOfShapeListOfShape& theVertexEdgeMap,
406           const gp_Dir&                                  theStartDir,
407           const gp_Dir&                                  theNormal,
408                 TopoDS_Shape&                            theNextVertex,
409                 TopoDS_Shape&                            theNextEdge,
410                 gp_Dir&                                  theNextDir)
411 {
412   const BOPCol_ListOfShape& anEdgesList = theVertexEdgeMap.FindFromKey(theStartVertex);
413   BOPCol_ListOfShape::Iterator aEdIter(anEdgesList);
414   double aBestEdgeProj = DBL_MAX;
415   for ( ; aEdIter.More(); aEdIter.Next())
416   {
417     gp_Dir aTang = getOuterEdgeDirection(aEdIter.Value(), theStartVertex);
418     aTang.Reverse();
419
420     // The projection is normalized in segment (-1, 1),
421     // where (-1, 0] corresponds to the angles (pi/2, 0] between theStartDir and aTang
422     // and [0, 1) corresponds to the angles [0, -pi/2)
423     double aProj = (aTang.Dot(theStartDir) - 1.0) * 0.5;
424     if (fabs(fabs(aProj) - 1) < tolerance)
425       continue;
426     if (theStartDir.DotCross(aTang, theNormal) < tolerance)
427       aProj *= -1.0;
428
429     if (aProj < aBestEdgeProj)
430     {
431       aBestEdgeProj = aProj;
432       theNextEdge = aEdIter.Value();
433       TopExp_Explorer aVertExp(theNextEdge, TopAbs_VERTEX);
434       for ( ; aVertExp.More(); aVertExp.Next())
435         if (aVertExp.Current().TShape() != theStartVertex.TShape())
436         {
437           theNextVertex = aVertExp.Current();
438           theNextDir = getOuterEdgeDirection(aEdIter.Value(), theNextVertex);
439           break;
440         }
441       if (!aVertExp.More())
442       { // This edge is a full circle
443         TopoDS_Vertex aV1, aV2;
444         TopExp::Vertices(*(const TopoDS_Edge*)(&theNextEdge), aV1, aV2);
445         if (aV1.Orientation() == theStartVertex.Orientation())
446           theNextVertex = aV2;
447         else
448           theNextVertex = aV1;
449         theNextDir = getOuterEdgeDirection(aEdIter.Value(), theNextVertex);
450       }
451     }
452   }
453 }
454
455 static void addEdgeToWire(const TopoDS_Edge&  theEdge,
456                           const BRep_Builder& theBuilder,
457                                 TopoDS_Shape& theSpliceVertex,
458                                 TopoDS_Wire&  theWire)
459 {
460   TopoDS_Edge anEdge = theEdge;
461   bool isCurVertChanged = false;
462   TopoDS_Shape aCurVertChanged;
463
464   TopExp_Explorer aVertExp(theEdge, TopAbs_VERTEX);
465   for ( ; aVertExp.More(); aVertExp.Next())
466   {
467     const TopoDS_Shape& aVertex = aVertExp.Current();
468     if (aVertex.TShape() == theSpliceVertex.TShape() && 
469         aVertex.Orientation() != theEdge.Orientation())
470     { // Current vertex is the last for the edge, so its orientation is wrong, need to revert the edge
471       anEdge.Reverse();
472       break;
473     }
474     if (aVertex.TShape() != theSpliceVertex.TShape())
475     {
476       aCurVertChanged = aVertex;
477       isCurVertChanged = true;
478     }
479   }
480   theSpliceVertex = isCurVertChanged ? aCurVertChanged : aVertExp.Current();
481
482   theBuilder.Add(theWire, anEdge);
483 }
484
485 void createFace(const TopoDS_Shape&                      theStartVertex,
486                 const std::list<TopoDS_Shape>::iterator& theStartEdge,
487                 const std::list<TopoDS_Shape>::iterator& theEndOfEdges,
488                 const gp_Pln&                            thePlane,
489                       TopoDS_Face&                       theResFace)
490 {
491   TopoDS_Wire aResWire;
492   BRep_Builder aBuilder;
493   aBuilder.MakeWire(aResWire);
494
495   TopoDS_Shape aCurVertex = theStartVertex;
496   std::list<TopoDS_Shape>::const_iterator anEdgeIter = theStartEdge;
497   for ( ; anEdgeIter != theEndOfEdges; anEdgeIter++)
498   {
499     TopoDS_Edge anEdge = *((TopoDS_Edge*)(&(*anEdgeIter)));
500     addEdgeToWire(anEdge, aBuilder, aCurVertex, aResWire);
501   }
502
503   BRepBuilderAPI_MakeFace aFaceBuilder(thePlane, aResWire);
504   if (aFaceBuilder.Error() == BRepBuilderAPI_FaceDone)
505     theResFace = aFaceBuilder.Face();
506 }
507
508 void createWireList(const TopoDS_Shape&                      theStartVertex,
509                     const std::list<TopoDS_Shape>::iterator& theStartEdge,
510                     const std::list<TopoDS_Shape>::iterator& theEndOfEdges,
511                     const std::set<Handle(TopoDS_TShape)>&   theEdgesInLoops,
512                           std::list<TopoDS_Wire>&            theResWires)
513 {
514   BRep_Builder aBuilder;
515   bool needNewWire = true;
516   TopoDS_Shape aCurVertex = theStartVertex;
517
518   std::list<TopoDS_Shape>::iterator anIter = theStartEdge;
519   while (anIter != theEndOfEdges)
520   {
521     while (anIter != theEndOfEdges && needNewWire && 
522            theEdgesInLoops.count(anIter->TShape()) != 0)
523     {
524       TopExp_Explorer aVertExp(*anIter, TopAbs_VERTEX);
525       for ( ; aVertExp.More(); aVertExp.Next())
526         if (aVertExp.Current().TShape() != aCurVertex.TShape())
527         {
528           aCurVertex = aVertExp.Current();
529           break;
530         }
531       anIter++;
532     }
533     if (anIter == theEndOfEdges)
534       break;
535
536     if (needNewWire)
537     { // The new wire should be created
538       TopoDS_Wire aWire;
539       aBuilder.MakeWire(aWire);
540       theResWires.push_back(aWire);
541       needNewWire = false;
542     }
543     else if (theEdgesInLoops.count(anIter->TShape()) != 0)
544     { // There was found the edge already used in loop.
545       // Current wire should be released and new one should started
546       needNewWire = true;
547       continue;
548     }
549
550     TopoDS_Edge anEdge = *((TopoDS_Edge*)(&(*anIter)));
551     addEdgeToWire(anEdge, aBuilder, aCurVertex, theResWires.back());
552     anIter++;
553   }
554 }
555
556
557 gp_Dir getOuterEdgeDirection(const TopoDS_Shape& theEdge,
558                              const TopoDS_Shape& theVertex)
559 {
560   const Handle(BRep_TVertex)& aVertex = (const Handle(BRep_TVertex)&)theVertex.TShape();
561   gp_Pnt aVertexPnt = aVertex->Pnt();
562
563   const Handle(BRep_TEdge)& anEdge = (const Handle(BRep_TEdge)&)theEdge.TShape();
564
565   // Convert the edge to the curve to calculate the tangency.
566   // There should be only one curve in the edge.
567   Handle(BRep_Curve3D) aEdCurve = 
568     Handle(BRep_Curve3D)::DownCast(anEdge->Curves().First());
569   double aFirst, aLast;
570   aEdCurve->Range(aFirst, aLast);
571   Handle(Geom_Curve) aCurve = aEdCurve->Curve3D();
572
573   gp_Pnt aPnt;
574   gp_Vec aTang;
575   aCurve->D1(aFirst + shift, aPnt, aTang);
576   aCurve->D0(aFirst, aPnt);
577   if (aVertexPnt.IsEqual(aPnt, tolerance))
578     return gp_Dir(aTang.Reversed());
579
580   aCurve->D1(aLast - shift, aPnt, aTang);
581   return gp_Dir(aTang);
582 }
583
584 void removeWasteEdges(
585                 std::list<TopoDS_Shape>::iterator&  theStartVertex,
586                 std::list<TopoDS_Shape>::iterator&  theStartEdge,
587           const std::list<TopoDS_Shape>::iterator&  theEndOfVertexes,
588           const std::list<TopoDS_Shape>::iterator&  theEndOfEdges,
589           BOPCol_IndexedDataMapOfShapeListOfShape&  theMapVE)
590 {
591   bool isVertStep = true;
592   while (theStartVertex != theEndOfVertexes && theStartEdge != theEndOfEdges)
593   {
594     BOPCol_ListOfShape& aBunch = theMapVE.ChangeFromKey(*theStartVertex);
595     BOPCol_ListOfShape::Iterator anApprEdge(aBunch);
596     for ( ; anApprEdge.More(); anApprEdge.Next())
597       if (anApprEdge.Value() == *theStartEdge)
598         break;
599     if (anApprEdge.More())
600       aBunch.Remove(anApprEdge);
601
602     if (isVertStep)
603       theStartVertex++;
604     else
605     {
606       theStartEdge++;
607       // check current vertex to be a branching point
608       // if so, it will be a new starting point to find a loop
609       if (aBunch.Size() > 1)
610         break;
611     }
612     isVertStep = !isVertStep;
613   }
614
615   // The map of vertex-edges may be changed
616   BOPCol_IndexedDataMapOfShapeListOfShape aMapVECopy;
617   BOPCol_IndexedDataMapOfShapeListOfShape::Iterator aMapIter(theMapVE);
618   for (int ind = 1; aMapIter.More(); aMapIter.Next(), ind++)
619     if (!aMapIter.Value().IsEmpty())
620       aMapVECopy.Add(theMapVE.FindKey(ind), aMapIter.Value());
621   theMapVE.Clear();
622   theMapVE.Exchange(aMapVECopy);
623 }
624