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