Salome HOME
Copyright update 2021
[modules/shaper.git] / src / GeomAlgoAPI / GeomAlgoAPI_ShapeTools.cpp
1 // Copyright (C) 2014-2021  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19
20 #include "GeomAlgoAPI_ShapeTools.h"
21
22 #include "GeomAlgoAPI_SketchBuilder.h"
23
24 #include <GeomAPI_Ax1.h>
25 #include <GeomAPI_Edge.h>
26 #include <GeomAPI_Dir.h>
27 #include <GeomAPI_Face.h>
28 #include <GeomAPI_Pln.h>
29 #include <GeomAPI_Pnt.h>
30 #include <GeomAPI_Wire.h>
31
32 #include <Bnd_Box.hxx>
33
34 #include <BRep_Tool.hxx>
35 #include <BRep_Builder.hxx>
36 #include <BRepAlgo.hxx>
37 #include <BRepAlgo_FaceRestrictor.hxx>
38 #include <BRepAdaptor_Curve.hxx>
39 #include <BRepBndLib.hxx>
40 #include <BRepBuilderAPI_Copy.hxx>
41 #include <BRepBuilderAPI_FindPlane.hxx>
42 #include <BRepBuilderAPI_MakeEdge.hxx>
43 #include <BRepBuilderAPI_MakeFace.hxx>
44 #include <BRepBuilderAPI_MakeVertex.hxx>
45 #include <BRepBuilderAPI_MakeWire.hxx>
46 #include <BRepCheck_Analyzer.hxx>
47 #include <BRepExtrema_DistShapeShape.hxx>
48 #include <BRepExtrema_ExtCF.hxx>
49 #include <BRepGProp.hxx>
50 #include <BRepTools.hxx>
51 #include <BRepTools_WireExplorer.hxx>
52 #include <BRepTopAdaptor_FClass2d.hxx>
53 #include <BRepClass_FaceClassifier.hxx>
54 #include <BRepLib_CheckCurveOnSurface.hxx>
55 #include <BRepLProp.hxx>
56
57 #include <BOPAlgo_Builder.hxx>
58
59 #include <Geom2d_Curve.hxx>
60 #include <Geom2d_Curve.hxx>
61
62 #include <Geom_CylindricalSurface.hxx>
63 #include <Geom_Line.hxx>
64 #include <Geom_Plane.hxx>
65 #include <Geom_RectangularTrimmedSurface.hxx>
66
67 #include <GeomAPI_ProjectPointOnCurve.hxx>
68 #include <GeomAPI_ShapeIterator.h>
69
70 #include <GeomLib_IsPlanarSurface.hxx>
71 #include <GeomLib_Tool.hxx>
72 #include <GeomAPI_IntCS.hxx>
73
74 #include <gp_Pln.hxx>
75 #include <GProp_GProps.hxx>
76
77 #include <IntAna_IntConicQuad.hxx>
78 #include <IntAna_Quadric.hxx>
79
80 #include <ShapeAnalysis.hxx>
81 #include <ShapeAnalysis_Surface.hxx>
82
83 #include <TopoDS.hxx>
84 #include <TopoDS_Edge.hxx>
85 #include <TopoDS_Face.hxx>
86 #include <TopoDS_Shape.hxx>
87 #include <TopoDS_Shell.hxx>
88 #include <TopoDS_Vertex.hxx>
89 #include <TopoDS_Builder.hxx>
90
91 #include <TopExp.hxx>
92 #include <TopExp_Explorer.hxx>
93
94 #include <TopTools_ListIteratorOfListOfShape.hxx>
95
96 #include <NCollection_Vector.hxx>
97
98 //==================================================================================================
99 static GProp_GProps props(const TopoDS_Shape& theShape)
100 {
101   GProp_GProps aGProps;
102
103   if (theShape.ShapeType() == TopAbs_EDGE || theShape.ShapeType() == TopAbs_WIRE)
104   {
105     BRepGProp::LinearProperties(theShape, aGProps);
106   }
107   else if (theShape.ShapeType() == TopAbs_FACE || theShape.ShapeType() == TopAbs_SHELL)
108   {
109     const Standard_Real anEps = 1.e-6;
110     BRepGProp::SurfaceProperties(theShape, aGProps, anEps);
111   }
112   else if (theShape.ShapeType() == TopAbs_SOLID || theShape.ShapeType() == TopAbs_COMPSOLID)
113   {
114     BRepGProp::VolumeProperties(theShape, aGProps);
115   }
116   else if (theShape.ShapeType() == TopAbs_COMPOUND)
117   {
118     for (TopoDS_Iterator anIt(theShape); anIt.More(); anIt.Next())
119     {
120       aGProps.Add(props(anIt.Value()));
121     }
122   }
123
124   return aGProps;
125 }
126
127 //==================================================================================================
128 double GeomAlgoAPI_ShapeTools::length(const std::shared_ptr<GeomAPI_Shape> theShape)
129 {
130   GProp_GProps aGProps;
131   if(!theShape.get()) {
132     return 0.0;
133   }
134   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
135   if(aShape.IsNull()) {
136     return 0.0;
137   }
138
139   BRepGProp::LinearProperties(aShape, aGProps, Standard_True);
140   return  aGProps.Mass();
141 }
142
143 //==================================================================================================
144 double GeomAlgoAPI_ShapeTools::volume(const std::shared_ptr<GeomAPI_Shape> theShape)
145 {
146   if(!theShape.get()) {
147     return 0.0;
148   }
149   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
150   if(aShape.IsNull()) {
151     return 0.0;
152   }
153   const Standard_Real anEps = 1.e-6;
154   double aVolume = 0.0;
155   for (TopExp_Explorer anExp(aShape, TopAbs_SOLID); anExp.More(); anExp.Next()) {
156     GProp_GProps aGProps;
157     BRepGProp::VolumeProperties(anExp.Current(), aGProps, anEps);
158     aVolume += aGProps.Mass();
159   }
160   return aVolume;
161 }
162
163 //==================================================================================================
164 double GeomAlgoAPI_ShapeTools::area (const std::shared_ptr<GeomAPI_Shape> theShape)
165 {
166   GProp_GProps aGProps;
167   if(!theShape.get()) {
168     return 0.0;
169   }
170   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
171   if(aShape.IsNull()) {
172     return 0.0;
173   }
174   const Standard_Real anEps = 1.e-6;
175
176   BRepGProp::SurfaceProperties(aShape, aGProps, anEps);
177   return aGProps.Mass();
178 }
179
180 //==================================================================================================
181 std::shared_ptr<GeomAPI_Pnt>
182   GeomAlgoAPI_ShapeTools::centreOfMass(const std::shared_ptr<GeomAPI_Shape> theShape)
183 {
184   GProp_GProps aGProps;
185   if(!theShape) {
186     return std::shared_ptr<GeomAPI_Pnt>();
187   }
188   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
189   if(aShape.IsNull()) {
190     return std::shared_ptr<GeomAPI_Pnt>();
191   }
192   gp_Pnt aCentre;
193   if(aShape.ShapeType() == TopAbs_VERTEX) {
194     aCentre = BRep_Tool::Pnt(TopoDS::Vertex(aShape));
195   } else {
196     aGProps = props(aShape);
197     aCentre = aGProps.CentreOfMass();
198   }
199
200   return std::shared_ptr<GeomAPI_Pnt>(new GeomAPI_Pnt(aCentre.X(), aCentre.Y(), aCentre.Z()));
201 }
202
203 //==================================================================================================
204 double GeomAlgoAPI_ShapeTools::radius(const std::shared_ptr<GeomAPI_Face>& theCylinder)
205 {
206   double aRadius = -1.0;
207   if (theCylinder->isCylindrical()) {
208     const TopoDS_Shape& aShape = theCylinder->impl<TopoDS_Shape>();
209     Handle(Geom_Surface) aSurf = BRep_Tool::Surface(TopoDS::Face(aShape));
210     Handle(Geom_CylindricalSurface) aCyl = Handle(Geom_CylindricalSurface)::DownCast(aSurf);
211     if (!aCyl.IsNull())
212       aRadius = aCyl->Radius();
213   }
214   return aRadius;
215 }
216
217 //==================================================================================================
218 double GeomAlgoAPI_ShapeTools::minimalDistance(const GeomShapePtr& theShape1,
219                                                const GeomShapePtr& theShape2)
220 {
221   const TopoDS_Shape& aShape1 = theShape1->impl<TopoDS_Shape>();
222   const TopoDS_Shape& aShape2 = theShape2->impl<TopoDS_Shape>();
223
224   BRepExtrema_DistShapeShape aDist(aShape1, aShape2);
225   aDist.Perform();
226   return aDist.IsDone() ? aDist.Value() : Precision::Infinite();
227 }
228
229 //==================================================================================================
230 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::combineShapes(
231   const std::shared_ptr<GeomAPI_Shape> theCompound,
232   const GeomAPI_Shape::ShapeType theType,
233   ListOfShape& theResuts)
234 {
235
236   ListOfShape aResCombinedShapes;
237   ListOfShape aResFreeShapes;
238
239   GeomShapePtr aResult = theCompound;
240
241   if(!theCompound.get()) {
242     return aResult;
243   }
244
245   if(theType != GeomAPI_Shape::SHELL && theType != GeomAPI_Shape::COMPSOLID) {
246     return aResult;
247   }
248
249   TopAbs_ShapeEnum aTS = TopAbs_EDGE;
250   TopAbs_ShapeEnum aTA = TopAbs_FACE;
251   if(theType == GeomAPI_Shape::COMPSOLID) {
252     aTS = TopAbs_FACE;
253     aTA = TopAbs_SOLID;
254   }
255
256   // map from the resulting shapes to minimal index of the used shape from theCompound list
257   std::map<GeomShapePtr, int> anInputOrder;
258   // map from ancestors-shapes to the index of shapes in theCompound
259   NCollection_DataMap<TopoDS_Shape, int> anAncestorsOrder;
260
261   // Get free shapes.
262   int anOrder = 0;
263   const TopoDS_Shape& aShapesComp = theCompound->impl<TopoDS_Shape>();
264   for(TopoDS_Iterator anIter(aShapesComp); anIter.More(); anIter.Next(), anOrder++) {
265     const TopoDS_Shape& aShape = anIter.Value();
266     if(aShape.ShapeType() > aTA) {
267       std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
268       aGeomShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
269       aResFreeShapes.push_back(aGeomShape);
270       anInputOrder[aGeomShape] = anOrder;
271     } else {
272       for(TopExp_Explorer anExp(aShape, aTA); anExp.More(); anExp.Next()) {
273         anAncestorsOrder.Bind(anExp.Current(), anOrder);
274       }
275     }
276   }
277
278   // Map sub-shapes and shapes.
279   TopTools_IndexedDataMapOfShapeListOfShape aMapSA;
280   TopExp::MapShapesAndAncestors(aShapesComp, aTS, aTA, aMapSA);
281   if(aMapSA.IsEmpty()) {
282     return aResult;
283   }
284   theResuts.clear();
285
286   // Get all shapes with common sub-shapes and free shapes.
287   NCollection_Map<TopoDS_Shape> aFreeShapes;
288   NCollection_Vector<NCollection_Map<TopoDS_Shape>> aShapesWithCommonSubshapes;
289   for(TopTools_IndexedDataMapOfShapeListOfShape::Iterator
290       anIter(aMapSA); anIter.More(); anIter.Next()) {
291     TopTools_ListOfShape& aListOfShape = anIter.ChangeValue();
292     if(aListOfShape.IsEmpty()) {
293       continue;
294     }
295     else if(aListOfShape.Size() == 1) {
296       const TopoDS_Shape& aF = aListOfShape.First();
297       aFreeShapes.Add(aF);
298       aListOfShape.Clear();
299     } else {
300       NCollection_List<TopoDS_Shape> aTempList;
301       NCollection_Map<TopoDS_Shape> aTempMap;
302       for (TopTools_ListOfShape::Iterator aListIt(aListOfShape); aListIt.More(); aListIt.Next()) {
303         aTempList.Append(aListIt.Value());
304         aTempMap.Add(aListIt.Value());
305         aFreeShapes.Remove(aListIt.Value());
306       }
307       aListOfShape.Clear();
308       for(NCollection_List<TopoDS_Shape>::Iterator
309           aTempIter(aTempList); aTempIter.More(); aTempIter.Next()) {
310         const TopoDS_Shape& aTempShape = aTempIter.Value();
311         for(TopTools_IndexedDataMapOfShapeListOfShape::Iterator
312             anIter2(aMapSA); anIter2.More(); anIter2.Next()) {
313           TopTools_ListOfShape& aTempListOfShape = anIter2.ChangeValue();
314           if(aTempListOfShape.IsEmpty()) {
315             continue;
316           } else if(aTempListOfShape.Size() == 1 && aTempListOfShape.First() == aTempShape) {
317             aTempListOfShape.Clear();
318           } else if(aTempListOfShape.Size() > 1) {
319             TopTools_ListOfShape::Iterator anIt1(aTempListOfShape);
320             for (; anIt1.More(); anIt1.Next()) {
321               if (anIt1.Value() == aTempShape) {
322                 TopTools_ListOfShape::Iterator anIt2(aTempListOfShape);
323                 for (; anIt2.More(); anIt2.Next())
324                 {
325                   if (anIt2.Value() != anIt1.Value()) {
326                     if (aTempMap.Add(anIt2.Value())) {
327                       aTempList.Append(anIt2.Value());
328                       aFreeShapes.Remove(anIt2.Value());
329                     }
330                   }
331                 }
332                 aTempListOfShape.Clear();
333                 break;
334               }
335             }
336           }
337         }
338       }
339       aShapesWithCommonSubshapes.Append(aTempMap);
340     }
341   }
342
343   // Combine shapes with common sub-shapes.
344   for(NCollection_Vector<NCollection_Map<TopoDS_Shape>>::Iterator
345       anIter(aShapesWithCommonSubshapes); anIter.More(); anIter.Next()) {
346     TopoDS_Shell aShell;
347     TopoDS_CompSolid aCSolid;
348     TopoDS_Builder aBuilder;
349     anOrder = -1;
350     theType ==
351       GeomAPI_Shape::COMPSOLID ? aBuilder.MakeCompSolid(aCSolid) : aBuilder.MakeShell(aShell);
352     NCollection_Map<TopoDS_Shape>& aShapesMap = anIter.ChangeValue();
353     for(TopExp_Explorer anExp(aShapesComp, aTA); anExp.More(); anExp.Next()) {
354       const TopoDS_Shape& aShape = anExp.Current();
355       if(aShapesMap.Contains(aShape)) {
356         theType ==
357           GeomAPI_Shape::COMPSOLID ? aBuilder.Add(aCSolid, aShape) : aBuilder.Add(aShell, aShape);
358         aShapesMap.Remove(aShape);
359         int aThisOrder = anAncestorsOrder.Find(aShape);
360         if (anOrder == -1 || aThisOrder < anOrder)
361           anOrder = aThisOrder; // take the minimum order position
362       }
363     }
364     std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
365     TopoDS_Shape* aSh = theType == GeomAPI_Shape::COMPSOLID ? new TopoDS_Shape(aCSolid) :
366                                                               new TopoDS_Shape(aShell);
367     aGeomShape->setImpl<TopoDS_Shape>(aSh);
368     aResCombinedShapes.push_back(aGeomShape);
369     anInputOrder[aGeomShape] = anOrder;
370   }
371
372   // Adding free shapes.
373   for(TopExp_Explorer anExp(aShapesComp, aTA); anExp.More(); anExp.Next()) {
374     const TopoDS_Shape& aShape = anExp.Current();
375     if(aFreeShapes.Contains(aShape)) {
376       std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
377       aGeomShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
378       aResFreeShapes.push_back(aGeomShape);
379       anInputOrder[aGeomShape] = anAncestorsOrder.Find(aShape);
380     }
381   }
382
383   if(aResCombinedShapes.size() == 1 && aResFreeShapes.size() == 0) {
384     aResult = aResCombinedShapes.front();
385     theResuts.push_back(aResult);
386   } else if(aResCombinedShapes.size() == 0 && aResFreeShapes.size() == 1) {
387     aResult = aResFreeShapes.front();
388     theResuts.push_back(aResult);
389   } else {
390     TopoDS_Compound aResultComp;
391     TopoDS_Builder aBuilder;
392     aBuilder.MakeCompound(aResultComp);
393     // put to result compound and result list in accordance to the order numbers
394     std::map<GeomShapePtr, int>::iterator anInputIter = anInputOrder.begin();
395     std::map<int, GeomShapePtr> aNums;
396     for(; anInputIter != anInputOrder.end(); anInputIter++)
397       aNums[anInputIter->second] = anInputIter->first;
398     std::map<int, GeomShapePtr>::iterator aNumsIter = aNums.begin();
399     for(; aNumsIter != aNums.end(); aNumsIter++) {
400       aBuilder.Add(aResultComp, (aNumsIter->second)->impl<TopoDS_Shape>());
401       theResuts.push_back(aNumsIter->second);
402     }
403     aResult->setImpl(new TopoDS_Shape(aResultComp));
404   }
405
406   return aResult;
407 }
408
409 //==================================================================================================
410 static void addSimpleShapeToList(const TopoDS_Shape& theShape,
411                                  NCollection_List<TopoDS_Shape>& theList)
412 {
413   if(theShape.IsNull()) {
414     return;
415   }
416
417   if(theShape.ShapeType() == TopAbs_COMPOUND) {
418     for(TopoDS_Iterator anIt(theShape); anIt.More(); anIt.Next()) {
419       addSimpleShapeToList(anIt.Value(), theList);
420     }
421   } else {
422     theList.Append(theShape);
423   }
424 }
425
426 //==================================================================================================
427 static TopoDS_Compound makeCompound(const NCollection_List<TopoDS_Shape> theShapes)
428 {
429   TopoDS_Compound aCompound;
430
431   BRep_Builder aBuilder;
432   aBuilder.MakeCompound(aCompound);
433
434   for(NCollection_List<TopoDS_Shape>::Iterator anIt(theShapes); anIt.More(); anIt.Next()) {
435     aBuilder.Add(aCompound, anIt.Value());
436   }
437
438   return aCompound;
439 }
440
441 //==================================================================================================
442 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::groupSharedTopology(
443   const std::shared_ptr<GeomAPI_Shape> theCompound)
444 {
445   GeomShapePtr aResult = theCompound;
446
447   if (!theCompound.get()) {
448     return aResult;
449   }
450
451   TopoDS_Shape anInShape = aResult->impl<TopoDS_Shape>();
452   NCollection_List<TopoDS_Shape> anUngroupedShapes, aStillUngroupedShapes;
453   addSimpleShapeToList(anInShape, anUngroupedShapes);
454
455   // Iterate over all shapes and find shapes with shared vertices.
456   TopTools_ListOfShape allVertices;
457   TopTools_DataMapOfShapeListOfShape aVertexShapesMap;
458   for (NCollection_List<TopoDS_Shape>::Iterator aShapesIt(anUngroupedShapes);
459     aShapesIt.More();
460     aShapesIt.Next()) {
461     const TopoDS_Shape& aShape = aShapesIt.Value();
462     for (TopExp_Explorer aShapeExp(aShape, TopAbs_VERTEX);
463       aShapeExp.More();
464       aShapeExp.Next()) {
465       const TopoDS_Shape& aVertex = aShapeExp.Current();
466       if (!aVertexShapesMap.IsBound(aVertex)) {
467         NCollection_List<TopoDS_Shape> aList;
468         aList.Append(aShape);
469         allVertices.Append(aVertex);
470         aVertexShapesMap.Bind(aVertex, aList);
471       }
472       else {
473         if (!aVertexShapesMap.ChangeFind(aVertex).Contains(aShape)) {
474           aVertexShapesMap.ChangeFind(aVertex).Append(aShape);
475         }
476       }
477     }
478   }
479
480   // Iterate over the map and group shapes.
481   NCollection_Vector<TopTools_MapOfShape> aGroups; // groups of shapes connected by vertices
482   while (!allVertices.IsEmpty()) {
483     // Get first group of shapes in map, and then unbind it.
484     const TopoDS_Shape& aKey = allVertices.First();
485     TopTools_ListOfShape aConnectedShapes = aVertexShapesMap.Find(aKey);
486     aVertexShapesMap.UnBind(aKey);
487     allVertices.Remove(aKey);
488     // Iterate over shapes in this group and add to it shapes from groups in map.
489     for (TopTools_ListOfShape::Iterator aConnectedIt(aConnectedShapes);
490       aConnectedIt.More(); aConnectedIt.Next()) {
491       const TopoDS_Shape& aConnected = aConnectedIt.Value();
492       TopTools_ListOfShape aKeysToUnbind;
493       for (TopTools_ListOfShape::Iterator aKeysIt(allVertices);
494         aKeysIt.More();
495         aKeysIt.Next()) {
496         const TopTools_ListOfShape& anOtherConnected = aVertexShapesMap(aKeysIt.Value());
497         if (!anOtherConnected.Contains(aConnected)) {
498           // Other connected group does not contain shape from our connected group
499           continue;
500         }
501         // Other is connected to our, so add them to our connected
502         for (TopTools_ListOfShape::Iterator anOtherIt(anOtherConnected);
503           anOtherIt.More();
504           anOtherIt.Next()) {
505           const TopoDS_Shape& aShape = anOtherIt.Value();
506           if (!aConnectedShapes.Contains(aShape)) {
507             aConnectedShapes.Append(aShape);
508           }
509         }
510         // Save key to unbind from this map.
511         aKeysToUnbind.Append(aKeysIt.Value());
512       }
513       // Unbind groups from map that we added to our group.
514       for (TopTools_ListOfShape::Iterator aKeysIt(aKeysToUnbind);
515         aKeysIt.More();
516         aKeysIt.Next()) {
517         aVertexShapesMap.UnBind(aKeysIt.Value());
518         allVertices.Remove(aKeysIt.Value());
519       }
520     }
521     // Sort shapes from the most complicated to the simplest ones
522     TopTools_MapOfShape aSortedGroup;
523     for (int aST = TopAbs_COMPOUND; aST <= TopAbs_SHAPE; ++aST) {
524       TopTools_ListOfShape::Iterator anIt(aConnectedShapes);
525       while (anIt.More()) {
526         if (anIt.Value().ShapeType() == aST) {
527           aSortedGroup.Add(anIt.Value());
528           aConnectedShapes.Remove(anIt);
529         }
530         else {
531           anIt.Next();
532         }
533       }
534     }
535     aGroups.Append(aSortedGroup);
536   }
537
538   TopoDS_Compound aCompound;
539   BRep_Builder aBuilder;
540   aBuilder.MakeCompound(aCompound);
541   ListOfShape aSolids;
542   for (NCollection_Vector<TopTools_MapOfShape>::Iterator anIt(aGroups); anIt.More(); anIt.Next()) {
543     const TopTools_MapOfShape& aGroup = anIt.ChangeValue();
544     GeomShapePtr aGeomShape(new GeomAPI_Shape());
545     if(aGroup.Size() == 1) {
546       TopTools_MapOfShape::Iterator aOneShapeIter(aGroup);
547       aGeomShape->setImpl(new TopoDS_Shape(aOneShapeIter.Value()));
548     } else {
549       // make sub-shapes in the group have order same as in original shape
550       TopTools_ListOfShape anOrderedGoup;
551       NCollection_List<TopoDS_Shape>::Iterator anUngrouped(anUngroupedShapes);
552       for (; anUngrouped.More(); anUngrouped.Next()) {
553         if (aGroup.Contains(anUngrouped.Value()))
554           anOrderedGoup.Append(anUngrouped.Value());
555       }
556       aGeomShape->setImpl(new TopoDS_Shape(makeCompound(anOrderedGoup)));
557       aGeomShape = GeomAlgoAPI_ShapeTools::combineShapes(aGeomShape,
558                                                          GeomAPI_Shape::COMPSOLID,
559                                                          aSolids);
560     }
561     aBuilder.Add(aCompound, aGeomShape->impl<TopoDS_Shape>());
562   }
563
564   if(!aCompound.IsNull()) {
565     aResult->setImpl(new TopoDS_Shape(aCompound));
566   }
567
568   return aResult;
569 }
570
571 //==================================================================================================
572 bool GeomAlgoAPI_ShapeTools::hasSharedTopology(const ListOfShape& theShapes,
573                                                const GeomAPI_Shape::ShapeType theShapeType)
574 {
575   TopTools_IndexedMapOfShape aSubs;
576   for (ListOfShape::const_iterator anIt = theShapes.begin(); anIt != theShapes.end(); ++anIt) {
577     TopTools_IndexedMapOfShape aCurSubs;
578     TopExp::MapShapes((*anIt)->impl<TopoDS_Shape>(), (TopAbs_ShapeEnum)theShapeType, aCurSubs);
579     for (TopTools_IndexedMapOfShape::Iterator aSubIt(aCurSubs); aSubIt.More(); aSubIt.Next()) {
580       if (aSubs.Contains(aSubIt.Value()))
581         return true;
582       else
583         aSubs.Add(aSubIt.Value());
584     }
585   }
586   return false;
587 }
588
589 //==================================================================================================
590 std::list<std::shared_ptr<GeomAPI_Pnt> >
591   GeomAlgoAPI_ShapeTools::getBoundingBox(const ListOfShape& theShapes, const double theEnlarge)
592 {
593   // Bounding box of all objects.
594   Bnd_Box aBndBox;
595
596   // Getting box.
597   for (ListOfShape::const_iterator
598     anObjectsIt = theShapes.begin(); anObjectsIt != theShapes.end(); anObjectsIt++) {
599     const TopoDS_Shape& aShape = (*anObjectsIt)->impl<TopoDS_Shape>();
600     BRepBndLib::Add(aShape, aBndBox);
601   }
602
603   if(theEnlarge != 0.0) {
604     // We enlarge bounding box just to be sure that plane will be large enough to cut all objects.
605     aBndBox.Enlarge(theEnlarge);
606   }
607
608   Standard_Real aXArr[2] = {aBndBox.CornerMin().X(), aBndBox.CornerMax().X()};
609   Standard_Real aYArr[2] = {aBndBox.CornerMin().Y(), aBndBox.CornerMax().Y()};
610   Standard_Real aZArr[2] = {aBndBox.CornerMin().Z(), aBndBox.CornerMax().Z()};
611   std::list<std::shared_ptr<GeomAPI_Pnt> > aResultPoints;
612   for(int i = 0; i < 2; i++) {
613     for(int j = 0; j < 2; j++) {
614       for(int k = 0; k < 2; k++) {
615         std::shared_ptr<GeomAPI_Pnt> aPnt(new GeomAPI_Pnt(aXArr[i], aYArr[j], aZArr[k]));
616         aResultPoints.push_back(aPnt);
617       }
618     }
619   }
620
621   return aResultPoints;
622 }
623
624 //==================================================================================================
625 std::shared_ptr<GeomAPI_Face> GeomAlgoAPI_ShapeTools::fitPlaneToBox(
626   const std::shared_ptr<GeomAPI_Shape> thePlane,
627   const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints)
628 {
629   std::shared_ptr<GeomAPI_Face> aResultFace;
630
631   if(!thePlane.get()) {
632     return aResultFace;
633   }
634
635   const TopoDS_Shape& aShape = thePlane->impl<TopoDS_Shape>();
636   if(aShape.ShapeType() != TopAbs_FACE) {
637     return aResultFace;
638   }
639
640   TopoDS_Face aFace = TopoDS::Face(aShape);
641   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace);
642   if(aSurf.IsNull()) {
643     return aResultFace;
644   }
645
646   GeomLib_IsPlanarSurface isPlanar(aSurf);
647   if(!isPlanar.IsPlanar()) {
648     return aResultFace;
649   }
650
651   if(thePoints.size() != 8) {
652     return aResultFace;
653   }
654
655   const gp_Pln& aFacePln = isPlanar.Plan();
656   Handle(Geom_Plane) aFacePlane = new Geom_Plane(aFacePln);
657   IntAna_Quadric aQuadric(aFacePln);
658   Standard_Real UMin, UMax, VMin, VMax;
659   UMin = UMax = VMin = VMax = 0;
660   for (std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator
661        aPointsIt = thePoints.begin(); aPointsIt != thePoints.end(); aPointsIt++) {
662     const gp_Pnt& aPnt = (*aPointsIt)->impl<gp_Pnt>();
663     gp_Lin aLin(aPnt, aFacePln.Axis().Direction());
664     IntAna_IntConicQuad anIntAna(aLin, aQuadric);
665     const gp_Pnt& aPntOnFace = anIntAna.Point(1);
666     Standard_Real aPntU(0), aPntV(0);
667     GeomLib_Tool::Parameters(aFacePlane, aPntOnFace, Precision::Confusion(), aPntU, aPntV);
668     if(aPntU < UMin) UMin = aPntU;
669     if(aPntU > UMax) UMax = aPntU;
670     if(aPntV < VMin) VMin = aPntV;
671     if(aPntV > VMax) VMax = aPntV;
672   }
673   aResultFace.reset(new GeomAPI_Face());
674   aResultFace->setImpl(new TopoDS_Face(BRepLib_MakeFace(aFacePln, UMin, UMax, VMin, VMax).Face()));
675
676   return aResultFace;
677 }
678
679 //==================================================================================================
680 void GeomAlgoAPI_ShapeTools::findBounds(const std::shared_ptr<GeomAPI_Shape> theShape,
681                                         std::shared_ptr<GeomAPI_Vertex>& theV1,
682                                         std::shared_ptr<GeomAPI_Vertex>& theV2)
683 {
684   static GeomVertexPtr aVertex;
685   if (!aVertex) {
686     aVertex = GeomVertexPtr(new GeomAPI_Vertex);
687     aVertex->setImpl(new TopoDS_Vertex());
688   }
689
690   theV1 = aVertex;
691   theV2 = aVertex;
692
693   if (theShape) {
694     const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
695     TopoDS_Vertex aV1, aV2;
696     ShapeAnalysis::FindBounds(aShape, aV1, aV2);
697
698     std::shared_ptr<GeomAPI_Vertex> aGeomV1(new GeomAPI_Vertex()), aGeomV2(new GeomAPI_Vertex());
699     aGeomV1->setImpl(new TopoDS_Vertex(aV1));
700     aGeomV2->setImpl(new TopoDS_Vertex(aV2));
701     theV1 = aGeomV1;
702     theV2 = aGeomV2;
703   }
704 }
705
706 //==================================================================================================
707 void GeomAlgoAPI_ShapeTools::makeFacesWithHoles(const std::shared_ptr<GeomAPI_Pnt> theOrigin,
708                                                 const std::shared_ptr<GeomAPI_Dir> theDirection,
709                                                 const ListOfShape& theWires,
710                                                 ListOfShape& theFaces)
711 {
712   BRepBuilderAPI_MakeFace aMKFace(gp_Pln(theOrigin->impl<gp_Pnt>(),
713                                           theDirection->impl<gp_Dir>()));
714   TopoDS_Face aFace = aMKFace.Face();
715
716   BRepAlgo_FaceRestrictor aFRestrictor;
717   aFRestrictor.Init(aFace, Standard_False, Standard_True);
718   for(ListOfShape::const_iterator anIt = theWires.cbegin();
719       anIt != theWires.cend();
720       ++anIt) {
721     TopoDS_Wire aWire = TopoDS::Wire((*anIt)->impl<TopoDS_Shape>());
722     aFRestrictor.Add(aWire);
723   }
724
725   aFRestrictor.Perform();
726
727   if(!aFRestrictor.IsDone()) {
728     return;
729   }
730
731   for(; aFRestrictor.More(); aFRestrictor.Next()) {
732     GeomShapePtr aShape(new GeomAPI_Shape());
733     aShape->setImpl(new TopoDS_Shape(aFRestrictor.Current()));
734     theFaces.push_back(aShape);
735   }
736 }
737
738 //==================================================================================================
739 std::shared_ptr<GeomAPI_Pln> GeomAlgoAPI_ShapeTools::findPlane(const ListOfShape& theShapes)
740 {
741   TopoDS_Compound aCompound;
742   BRep_Builder aBuilder;
743   aBuilder.MakeCompound(aCompound);
744
745   for(ListOfShape::const_iterator anIt = theShapes.cbegin(); anIt != theShapes.cend(); ++anIt) {
746     aBuilder.Add(aCompound, (*anIt)->impl<TopoDS_Shape>());
747   }
748   BRepBuilderAPI_FindPlane aFindPlane(aCompound);
749
750   if(aFindPlane.Found() != Standard_True) {
751     return std::shared_ptr<GeomAPI_Pln>();
752   }
753
754   Handle(Geom_Plane) aPlane = aFindPlane.Plane();
755   gp_Pnt aLoc = aPlane->Location();
756   gp_Dir aDir = aPlane->Axis().Direction();
757
758   std::shared_ptr<GeomAPI_Pnt> aGeomPnt(new GeomAPI_Pnt(aLoc.X(), aLoc.Y(), aLoc.Z()));
759   std::shared_ptr<GeomAPI_Dir> aGeomDir(new GeomAPI_Dir(aDir.X(), aDir.Y(), aDir.Z()));
760
761   std::shared_ptr<GeomAPI_Pln> aPln(new GeomAPI_Pln(aGeomPnt, aGeomDir));
762
763   return aPln;
764 }
765
766 //==================================================================================================
767 bool GeomAlgoAPI_ShapeTools::isSubShapeInsideShape(
768   const std::shared_ptr<GeomAPI_Shape> theSubShape,
769   const std::shared_ptr<GeomAPI_Shape> theBaseShape)
770 {
771   if(!theSubShape.get() || !theBaseShape.get()) {
772     return false;
773   }
774
775   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
776   const TopoDS_Shape& aBaseShape = theBaseShape->impl<TopoDS_Shape>();
777
778   if(aSubShape.ShapeType() == TopAbs_VERTEX) {
779     // If sub-shape is a vertex check distance to shape. If it is <= Precision::Confusion() then OK.
780     BRepExtrema_DistShapeShape aDist(aBaseShape, aSubShape);
781     aDist.Perform();
782     if(!aDist.IsDone() || aDist.Value() > Precision::Confusion()) {
783       return false;
784     }
785   } else if (aSubShape.ShapeType() == TopAbs_EDGE) {
786     if(aBaseShape.ShapeType() == TopAbs_FACE) {
787       // Check that edge is on face surface.
788       TopoDS_Face aFace = TopoDS::Face(aBaseShape);
789       TopoDS_Edge anEdge = TopoDS::Edge(aSubShape);
790       BRepLib_CheckCurveOnSurface aCheck(anEdge, aFace);
791       aCheck.Perform();
792       if(!aCheck.IsDone() || aCheck.MaxDistance() > Precision::Confusion()) {
793         return false;
794       }
795
796       // Check intersections.
797       TopoDS_Vertex aV1, aV2;
798       ShapeAnalysis::FindBounds(anEdge, aV1, aV2);
799       gp_Pnt aPnt1 = BRep_Tool::Pnt(aV1);
800       gp_Pnt aPnt2 = BRep_Tool::Pnt(aV2);
801       for(TopExp_Explorer anExp(aBaseShape, TopAbs_EDGE); anExp.More(); anExp.Next()) {
802         const TopoDS_Shape& anEdgeOnFace = anExp.Current();
803         BRepExtrema_DistShapeShape aDist(anEdgeOnFace, anEdge);
804         aDist.Perform();
805         if(aDist.IsDone() && aDist.Value() <= Precision::Confusion()) {
806           // Edge intersect face bound. Check that it is not on edge begin or end.
807           for(Standard_Integer anIndex = 1; anIndex <= aDist.NbSolution(); ++anIndex) {
808             gp_Pnt aPntOnSubShape = aDist.PointOnShape2(anIndex);
809             if(aPntOnSubShape.Distance(aPnt1) > Precision::Confusion()
810                 && aPntOnSubShape.Distance(aPnt2) > Precision::Confusion()) {
811               return false;
812             }
813           }
814         }
815       }
816
817       // No intersections found. Edge is inside or outside face. Check it.
818       BRepAdaptor_Curve aCurveAdaptor(anEdge);
819       gp_Pnt aPointToCheck =
820         aCurveAdaptor.Value((aCurveAdaptor.FirstParameter() +
821                               aCurveAdaptor.LastParameter()) / 2.0);
822       Handle(Geom_Surface) aSurface = BRep_Tool::Surface(aFace);
823       ShapeAnalysis_Surface aSAS(aSurface);
824       gp_Pnt2d aPointOnFace = aSAS.ValueOfUV(aPointToCheck, Precision::Confusion());
825       BRepTopAdaptor_FClass2d aFClass2d(aFace, Precision::Confusion());
826       if(aFClass2d.Perform(aPointOnFace) == TopAbs_OUT) {
827         return false;
828       }
829
830     } else {
831       return false;
832     }
833   } else {
834     return false;
835   }
836
837   return true;
838 }
839
840 //==================================================================================================
841 bool GeomAlgoAPI_ShapeTools::isShapeValid(const std::shared_ptr<GeomAPI_Shape> theShape)
842 {
843   if(!theShape.get()) {
844     return false;
845   }
846
847   BRepCheck_Analyzer aChecker(theShape->impl<TopoDS_Shape>());
848   return (aChecker.IsValid() == Standard_True);
849 }
850
851 //==================================================================================================
852 std::shared_ptr<GeomAPI_Shape>
853   GeomAlgoAPI_ShapeTools::getFaceOuterWire(const std::shared_ptr<GeomAPI_Shape> theFace)
854 {
855   GeomShapePtr anOuterWire;
856
857   if(!theFace.get() || !theFace->isFace()) {
858     return anOuterWire;
859   }
860
861   TopoDS_Face aFace = TopoDS::Face(theFace->impl<TopoDS_Shape>());
862   TopoDS_Wire aWire = BRepTools::OuterWire(aFace);
863
864   anOuterWire.reset(new GeomAPI_Shape());
865   anOuterWire->setImpl(new TopoDS_Shape(aWire));
866
867   return anOuterWire;
868 }
869
870 //==================================================================================================
871 static bool boundaryOfEdge(const std::shared_ptr<GeomAPI_Edge> theEdge,
872                           const std::shared_ptr<GeomAPI_Vertex> theVertex,
873                           double& theParam)
874 {
875   GeomPointPtr aPoint = theVertex->point();
876   GeomPointPtr aFirstPnt = theEdge->firstPoint();
877   double aFirstPntTol = theEdge->firstPointTolerance();
878   GeomPointPtr aLastPnt = theEdge->lastPoint();
879   double aLastPntTol = theEdge->lastPointTolerance();
880
881   double aFirst, aLast;
882   theEdge->getRange(aFirst, aLast);
883
884   bool isFirst = aPoint->distance(aFirstPnt) <= aFirstPntTol;
885   bool isLast = aPoint->distance(aLastPnt) <= aLastPntTol;
886   if (isFirst)
887     theParam = aFirst;
888   else if (isLast)
889     theParam = aLast;
890
891   return isFirst != isLast;
892 }
893
894 bool GeomAlgoAPI_ShapeTools::isTangent(const std::shared_ptr<GeomAPI_Edge> theEdge1,
895                                        const std::shared_ptr<GeomAPI_Edge> theEdge2,
896                                        const std::shared_ptr<GeomAPI_Vertex> theTgPoint)
897 {
898   double aParE1 = 0, aParE2 = 0;
899   if (!boundaryOfEdge(theEdge1, theTgPoint, aParE1) ||
900       !boundaryOfEdge(theEdge2, theTgPoint, aParE2))
901     return false;
902
903   BRepAdaptor_Curve aC1(theEdge1->impl<TopoDS_Edge>());
904   BRepAdaptor_Curve aC2(theEdge2->impl<TopoDS_Edge>());
905   return BRepLProp::Continuity(aC1, aC2, aParE1, aParE2) >= GeomAbs_G1;
906 }
907
908 //==================================================================================================
909 bool GeomAlgoAPI_ShapeTools::isParallel(const std::shared_ptr<GeomAPI_Edge> theEdge,
910                                         const std::shared_ptr<GeomAPI_Face> theFace)
911 {
912   if(!theEdge.get() || !theFace.get()) {
913     return false;
914   }
915
916   TopoDS_Edge anEdge = TopoDS::Edge(theEdge->impl<TopoDS_Shape>());
917   TopoDS_Face aFace  = TopoDS::Face(theFace->impl<TopoDS_Shape>());
918
919   BRepExtrema_ExtCF anExt(anEdge, aFace);
920   return anExt.IsParallel() == Standard_True;
921 }
922
923 //==================================================================================================
924 std::list<std::shared_ptr<GeomAPI_Vertex> > GeomAlgoAPI_ShapeTools::intersect(
925   const std::shared_ptr<GeomAPI_Edge> theEdge, const std::shared_ptr<GeomAPI_Face> theFace)
926 {
927   std::list<std::shared_ptr<GeomAPI_Vertex> > aResult;
928   if(!theEdge.get() || !theFace.get()) {
929     return aResult;
930   }
931
932   TopoDS_Edge anEdge = TopoDS::Edge(theEdge->impl<TopoDS_Shape>());
933   double aFirstOnCurve, aLastOnCurve;
934   Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirstOnCurve, aLastOnCurve);
935
936   TopoDS_Face aFace  = TopoDS::Face(theFace->impl<TopoDS_Shape>());
937   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace);
938
939   GeomAPI_IntCS anIntAlgo(aCurve, aSurf);
940   if (!anIntAlgo.IsDone())
941     return aResult;
942   // searching for points-intersection
943   for(int anIntNum = 1; anIntNum <= anIntAlgo.NbPoints() + anIntAlgo.NbSegments(); anIntNum++) {
944     gp_Pnt anInt;
945     if (anIntNum <= anIntAlgo.NbPoints()) {
946       anInt = anIntAlgo.Point(anIntNum);
947     } else { // take the middle point on the segment of the intersection
948       Handle(Geom_Curve) anIntCurve = anIntAlgo.Segment(anIntNum - anIntAlgo.NbPoints());
949       anIntCurve->D0((anIntCurve->FirstParameter() + anIntCurve->LastParameter()) / 2., anInt);
950     }
951     aResult.push_back(std::shared_ptr<GeomAPI_Vertex>(
952       new GeomAPI_Vertex(anInt.X(), anInt.Y(), anInt.Z())));
953   }
954   return aResult;
955 }
956
957 //==================================================================================================
958 void GeomAlgoAPI_ShapeTools::splitShape(const std::shared_ptr<GeomAPI_Shape>& theBaseShape,
959                                       const GeomAlgoAPI_ShapeTools::PointToRefsMap& thePointsInfo,
960                                       std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
961 {
962   // to split shape at least one point should be presented in the points container
963   if (thePointsInfo.empty())
964     return;
965
966     // General Fuse to split edge by vertices
967   BOPAlgo_Builder aBOP;
968   TopoDS_Edge aBaseEdge = theBaseShape->impl<TopoDS_Edge>();
969   // Rebuild closed edge to place vertex to one of split points.
970   // This will prevent edge to be split on same vertex.
971   if (BRep_Tool::IsClosed(aBaseEdge))
972   {
973     Standard_Real aFirst, aLast;
974     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aBaseEdge, aFirst, aLast);
975
976     PointToRefsMap::const_iterator aPIt = thePointsInfo.begin();
977     std::shared_ptr<GeomAPI_Pnt> aPnt = aPIt->first;
978     gp_Pnt aPoint(aPnt->x(), aPnt->y(), aPnt->z());
979
980     TopAbs_Orientation anOrientation = aBaseEdge.Orientation();
981     aBaseEdge = BRepBuilderAPI_MakeEdge(aCurve, aPoint, aPoint).Edge();
982     aBaseEdge.Orientation(anOrientation);
983   }
984   aBOP.AddArgument(aBaseEdge);
985
986   PointToRefsMap::const_iterator aPIt = thePointsInfo.begin();
987   for (; aPIt != thePointsInfo.end(); ++aPIt) {
988     std::shared_ptr<GeomAPI_Pnt> aPnt = aPIt->first;
989     TopoDS_Vertex aV = BRepBuilderAPI_MakeVertex(gp_Pnt(aPnt->x(), aPnt->y(), aPnt->z()));
990     aBOP.AddArgument(aV);
991   }
992
993   aBOP.Perform();
994   if (aBOP.HasErrors())
995     return;
996
997   // Collect splits
998   const TopTools_ListOfShape& aSplits = aBOP.Modified(aBaseEdge);
999   TopTools_ListIteratorOfListOfShape anIt(aSplits);
1000   for (; anIt.More(); anIt.Next()) {
1001     std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
1002     anEdge->setImpl(new TopoDS_Shape(anIt.Value()));
1003     theShapes.insert(anEdge);
1004   }
1005 }
1006
1007 //==================================================================================================
1008 void GeomAlgoAPI_ShapeTools::splitShape_p(const std::shared_ptr<GeomAPI_Shape>& theBaseShape,
1009                                           const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
1010                                           std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
1011 {
1012   // General Fuse to split edge by vertices
1013   BOPAlgo_Builder aBOP;
1014   TopoDS_Edge aBaseEdge = theBaseShape->impl<TopoDS_Edge>();
1015   // Rebuild closed edge to place vertex to one of split points.
1016   // This will prevent edge to be split on seam vertex.
1017   if (BRep_Tool::IsClosed(aBaseEdge))
1018   {
1019     Standard_Real aFirst, aLast;
1020     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aBaseEdge, aFirst, aLast);
1021
1022     std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPIt = thePoints.begin();
1023     gp_Pnt aPoint((*aPIt)->x(), (*aPIt)->y(), (*aPIt)->z());
1024
1025     TopAbs_Orientation anOrientation = aBaseEdge.Orientation();
1026     aBaseEdge = BRepBuilderAPI_MakeEdge(aCurve, aPoint, aPoint).Edge();
1027     aBaseEdge.Orientation(anOrientation);
1028   }
1029   aBOP.AddArgument(aBaseEdge);
1030
1031   std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPtIt = thePoints.begin();
1032   for (; aPtIt != thePoints.end(); ++aPtIt) {
1033     std::shared_ptr<GeomAPI_Pnt> aPnt = *aPtIt;
1034     TopoDS_Vertex aV = BRepBuilderAPI_MakeVertex(gp_Pnt(aPnt->x(), aPnt->y(), aPnt->z()));
1035     aBOP.AddArgument(aV);
1036   }
1037
1038   aBOP.Perform();
1039   if (aBOP.HasErrors())
1040     return;
1041
1042   // Collect splits
1043   const TopTools_ListOfShape& aSplits = aBOP.Modified(aBaseEdge);
1044   TopTools_ListIteratorOfListOfShape anIt(aSplits);
1045   for (; anIt.More(); anIt.Next()) {
1046     std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
1047     anEdge->setImpl(new TopoDS_Shape(anIt.Value()));
1048     theShapes.insert(anEdge);
1049   }
1050 }
1051
1052 //==================================================================================================
1053 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::findShape(
1054                                   const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
1055                                   const std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
1056 {
1057   std::shared_ptr<GeomAPI_Shape> aResultShape;
1058
1059   if (thePoints.size() == 2) {
1060     std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPntIt = thePoints.begin();
1061     std::shared_ptr<GeomAPI_Pnt> aFirstPoint = *aPntIt;
1062     aPntIt++;
1063     std::shared_ptr<GeomAPI_Pnt> aLastPoint = *aPntIt;
1064
1065     std::set<std::shared_ptr<GeomAPI_Shape> >::const_iterator anIt = theShapes.begin(),
1066                                                               aLast = theShapes.end();
1067     for (; anIt != aLast; anIt++) {
1068       GeomShapePtr aShape = *anIt;
1069       std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge(aShape));
1070       if (anEdge.get()) {
1071         std::shared_ptr<GeomAPI_Pnt> anEdgeFirstPoint = anEdge->firstPoint();
1072         std::shared_ptr<GeomAPI_Pnt> anEdgeLastPoint = anEdge->lastPoint();
1073         if (anEdgeFirstPoint->isEqual(aFirstPoint) &&
1074             anEdgeLastPoint->isEqual(aLastPoint))
1075             aResultShape = aShape;
1076       }
1077     }
1078   }
1079
1080   return aResultShape;
1081 }
1082
1083 //==================================================================================================
1084 #ifdef FEATURE_MULTIROTATION_TWO_DIRECTIONS
1085 std::shared_ptr<GeomAPI_Dir> GeomAlgoAPI_ShapeTools::buildDirFromAxisAndShape(
1086                                     const std::shared_ptr<GeomAPI_Shape> theBaseShape,
1087                                     const std::shared_ptr<GeomAPI_Ax1> theAxis)
1088 {
1089   gp_Pnt aCentreOfMassPoint =
1090     GeomAlgoAPI_ShapeTools::centreOfMass(theBaseShape)->impl<gp_Pnt>();
1091   Handle(Geom_Line) aLine = new Geom_Line(theAxis->impl<gp_Ax1>());
1092   GeomAPI_ProjectPointOnCurve aPrjTool(aCentreOfMassPoint, aLine);
1093   gp_Pnt aPoint = aPrjTool.NearestPoint();
1094
1095   std::shared_ptr<GeomAPI_Dir> aDir(new GeomAPI_Dir(aCentreOfMassPoint.X()-aPoint.X(),
1096                                                     aCentreOfMassPoint.Y()-aPoint.Y(),
1097                                                     aCentreOfMassPoint.Z()-aPoint.Z()));
1098   return aDir;
1099 }
1100 #endif
1101
1102 //==================================================================================================
1103 static TopoDS_Wire fixParametricGaps(const TopoDS_Wire& theWire)
1104 {
1105   TopoDS_Wire aFixedWire;
1106   Handle(Geom_Curve) aPrevCurve;
1107   double aPrevLastParam = -Precision::Infinite();
1108
1109   BRep_Builder aBuilder;
1110   aBuilder.MakeWire(aFixedWire);
1111
1112   BRepTools_WireExplorer aWExp(theWire);
1113   for (; aWExp.More(); aWExp.Next()) {
1114     TopoDS_Edge anEdge = aWExp.Current();
1115     double aFirst, aLast;
1116     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
1117     if (aCurve == aPrevCurve && Abs(aFirst - aPrevLastParam) > Precision::Confusion()) {
1118       // if parametric gap occurs, create new edge based on the copied curve
1119       aCurve = Handle(Geom_Curve)::DownCast(aCurve->Copy());
1120       TopoDS_Vertex aV1, aV2;
1121       TopExp::Vertices(anEdge, aV1, aV2);
1122       anEdge = TopoDS::Edge(anEdge.EmptyCopied());
1123       aBuilder.UpdateEdge(anEdge, aCurve, BRep_Tool::Tolerance(anEdge));
1124       aBuilder.Add(anEdge, aV1);
1125       aBuilder.Add(anEdge, aV2);
1126     }
1127
1128     aBuilder.Add(aFixedWire, anEdge);
1129
1130     aPrevCurve = aCurve;
1131     aPrevLastParam = aLast;
1132   }
1133
1134   return aFixedWire;
1135 }
1136
1137 //==================================================================================================
1138 std::shared_ptr<GeomAPI_Edge> GeomAlgoAPI_ShapeTools::wireToEdge(
1139       const std::shared_ptr<GeomAPI_Wire>& theWire)
1140 {
1141   GeomEdgePtr anEdge;
1142   if (theWire) {
1143     TopoDS_Wire aWire = theWire->impl<TopoDS_Wire>();
1144     BRepTools_WireExplorer aWExp(aWire);
1145     TopoDS_Edge aNewEdge = aWExp.Current();
1146     aWExp.Next();
1147     if (aWExp.More()) {
1148       // Workaround for the closed wire to avoid jumping of its start point:
1149       // split this wire for two parts, convert them to edges, then compose together
1150       if (BRep_Tool::IsClosed(aWire)) {
1151         aWire = TopoDS::Wire(BRepBuilderAPI_Copy(aWire).Shape());
1152         aWExp.Init(aWire);
1153         aNewEdge = aWExp.Current();
1154
1155         BRep_Builder().Remove(aWire, aNewEdge);
1156         GeomWirePtr aSplitWire(new GeomAPI_Wire);
1157         aSplitWire->setImpl(new TopoDS_Wire(aWire));
1158         GeomEdgePtr aMergedEdge = wireToEdge(aSplitWire);
1159
1160         aWire = BRepBuilderAPI_MakeWire(aNewEdge, aMergedEdge->impl<TopoDS_Edge>());
1161       }
1162
1163       // Workaround: when concatenate a wire consisting of two edges based on the same B-spline
1164       // curve (non-periodic, but having equal start and end points), first of which is placed
1165       // at the end on the curve and second is placed at the start, this workaround copies
1166       // second curve to avoid treating these edges as a single curve by setting trim parameters.
1167       aWire = fixParametricGaps(aWire);
1168       aWire = BRepAlgo::ConcatenateWire(aWire, GeomAbs_G1); // join smooth parts of wire
1169       aNewEdge = BRepAlgo::ConcatenateWireC0(aWire); // join C0 parts of wire
1170     }
1171     anEdge = GeomEdgePtr(new GeomAPI_Edge);
1172     anEdge->setImpl(new TopoDS_Edge(aNewEdge));
1173   }
1174   return anEdge;
1175 }
1176
1177 //==================================================================================================
1178 ListOfShape GeomAlgoAPI_ShapeTools::getLowLevelSubShapes(const GeomShapePtr& theShape)
1179 {
1180   ListOfShape aSubShapes;
1181
1182   if (!theShape->isCompound() && !theShape->isCompSolid() &&
1183       !theShape->isShell() && !theShape->isWire()) {
1184     return aSubShapes;
1185   }
1186
1187   for (GeomAPI_ShapeIterator anIt(theShape); anIt.more(); anIt.next()) {
1188     GeomShapePtr aSubShape = anIt.current();
1189     if (aSubShape->isVertex() || aSubShape->isEdge() ||
1190         aSubShape->isFace() || aSubShape->isSolid()) {
1191       aSubShapes.push_back(aSubShape);
1192     } else {
1193       aSubShapes.splice(aSubShapes.end(), getLowLevelSubShapes(aSubShape));
1194     }
1195   }
1196
1197   return aSubShapes;
1198 }
1199
1200 //==================================================================================================
1201 static void getMinMaxPointsOnLine(const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
1202                                   const gp_Dir theDir,
1203                                   double& theMin, double& theMax)
1204 {
1205   theMin = RealLast();
1206   theMax = RealFirst();
1207   // Project bounding points on theDir
1208   for (std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator
1209          aPointsIt = thePoints.begin(); aPointsIt != thePoints.end(); aPointsIt++) {
1210     const gp_Pnt& aPnt = (*aPointsIt)->impl<gp_Pnt>();
1211     gp_Dir aPntDir (aPnt.XYZ());
1212     Standard_Real proj = (theDir*aPntDir) * aPnt.XYZ().Modulus();
1213     if (proj < theMin) theMin = proj;
1214     if (proj > theMax) theMax = proj;
1215   }
1216 }
1217
1218 //==================================================================================================
1219 void GeomAlgoAPI_ShapeTools::computeThroughAll(const ListOfShape& theObjects,
1220                                                const ListOfShape& theBaseShapes,
1221                                                const std::shared_ptr<GeomAPI_Dir> theDir,
1222                                                double& theToSize, double& theFromSize)
1223 {
1224   // Bounding box of objects
1225   std::list<std::shared_ptr<GeomAPI_Pnt> > aBndObjs =
1226       GeomAlgoAPI_ShapeTools::getBoundingBox(theObjects);
1227   if (aBndObjs.size() != 8) {
1228     return;
1229   }
1230
1231   // the value to enlarge the bounding box of each object to make the extruded shape
1232   // a little bit larger than overall objects to get the correct result of Boolean CUT operation
1233   double anEnlargement = 0.1 * aBndObjs.front()->distance(aBndObjs.back());
1234
1235   // Prism direction
1236   if (theDir.get()) {
1237     // One direction for all prisms
1238     gp_Dir aDir = theDir->impl<gp_Dir>();
1239
1240     // Bounding box of the base
1241     std::list<std::shared_ptr<GeomAPI_Pnt> > aBndBases =
1242         GeomAlgoAPI_ShapeTools::getBoundingBox(theBaseShapes);
1243     if (aBndBases.size() != 8) {
1244       return;
1245     }
1246
1247     // Objects bounds
1248     Standard_Real lowBnd, upperBnd;
1249     getMinMaxPointsOnLine(aBndObjs, aDir, lowBnd, upperBnd);
1250
1251     // Base bounds
1252     Standard_Real lowBase, upperBase;
1253     getMinMaxPointsOnLine(aBndBases, aDir, lowBase, upperBase);
1254
1255     // ----------.-----.---------.--------------.-----------> theDir
1256     //       lowBnd   lowBase   upperBase    upperBnd
1257
1258     theToSize = upperBnd - lowBase;
1259     theFromSize = upperBase - lowBnd;
1260   } else {
1261     // Direction is a normal to each base shape (different normals to bases)
1262     // So we calculate own sizes for each base shape
1263     theToSize = 0.0;
1264     theFromSize = 0.0;
1265
1266     for (ListOfShape::const_iterator anIt = theBaseShapes.begin();
1267          anIt != theBaseShapes.end(); ++anIt) {
1268       const GeomShapePtr& aBaseShape_i = (*anIt);
1269       ListOfShape aBaseShapes_i;
1270       aBaseShapes_i.push_back(aBaseShape_i);
1271
1272       // Bounding box of the base
1273       std::list<std::shared_ptr<GeomAPI_Pnt> > aBndBases =
1274           GeomAlgoAPI_ShapeTools::getBoundingBox(aBaseShapes_i, anEnlargement);
1275       if (aBndBases.size() != 8) {
1276         return;
1277       }
1278
1279       // Direction (normal to aBaseShapes_i)
1280       // Code like in GeomAlgoAPI_Prism
1281       gp_Dir aDir;
1282       const TopoDS_Shape& aBaseShape = aBaseShape_i->impl<TopoDS_Shape>();
1283       BRepBuilderAPI_FindPlane aFindPlane(aBaseShape);
1284       if (aFindPlane.Found() == Standard_True) {
1285         Handle(Geom_Plane) aPlane;
1286         if (aBaseShape.ShapeType() == TopAbs_FACE || aBaseShape.ShapeType() == TopAbs_SHELL) {
1287           TopExp_Explorer anExp(aBaseShape, TopAbs_FACE);
1288           const TopoDS_Shape& aFace = anExp.Current();
1289           Handle(Geom_Surface) aSurface = BRep_Tool::Surface(TopoDS::Face(aFace));
1290           if(aSurface->DynamicType() == STANDARD_TYPE(Geom_RectangularTrimmedSurface)) {
1291             Handle(Geom_RectangularTrimmedSurface) aTrimSurface =
1292               Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurface);
1293             aSurface = aTrimSurface->BasisSurface();
1294           }
1295           if(aSurface->DynamicType() != STANDARD_TYPE(Geom_Plane)) {
1296             return;
1297           }
1298           aPlane = Handle(Geom_Plane)::DownCast(aSurface);
1299         } else {
1300           aPlane = aFindPlane.Plane();
1301         }
1302         aDir = aPlane->Axis().Direction();
1303       } else {
1304         return;
1305       }
1306
1307       // Objects bounds
1308       Standard_Real lowBnd, upperBnd;
1309       getMinMaxPointsOnLine(aBndObjs, aDir, lowBnd, upperBnd);
1310
1311       // Base bounds
1312       Standard_Real lowBase, upperBase;
1313       getMinMaxPointsOnLine(aBndBases, aDir, lowBase, upperBase);
1314
1315       // ----------.-----.---------.--------------.-----------> theDir
1316       //       lowBnd   lowBase   upperBase    upperBnd
1317
1318       double aToSize_i = upperBnd - lowBase;
1319       double aFromSize_i = upperBase - lowBnd;
1320
1321       if (aToSize_i > theToSize) theToSize = aToSize_i;
1322       if (aFromSize_i > theFromSize) theFromSize = aFromSize_i;
1323     }
1324   }
1325 }