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