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