Salome HOME
Fixes for Boolean operations;
[modules/shaper.git] / src / GeomAlgoAPI / GeomAlgoAPI_ShapeTools.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:        GeomAlgoAPI_ShapeTools.h
4 // Created:     3 August 2015
5 // Author:      Dmitry Bobylev
6
7 #include "GeomAlgoAPI_ShapeTools.h"
8
9 #include "GeomAlgoAPI_SketchBuilder.h"
10
11 #include <GeomAPI_Dir.h>
12 #include <GeomAPI_Face.h>
13 #include <GeomAPI_PlanarEdges.h>
14 #include <GeomAPI_Pln.h>
15 #include <GeomAPI_Pnt.h>
16
17 #include <Bnd_Box.hxx>
18 #include <BOPTools.hxx>
19 #include <BRep_Builder.hxx>
20 #include <BRepAdaptor_Curve.hxx>
21 #include <BRepAlgo_FaceRestrictor.hxx>
22 #include <BRepBndLib.hxx>
23 #include <BRepBuilderAPI_FindPlane.hxx>
24 #include <BRepBuilderAPI_MakeEdge.hxx>
25 #include <BRepBuilderAPI_MakeFace.hxx>
26 #include <BRepCheck_Analyzer.hxx>
27 #include <BRepExtrema_DistShapeShape.hxx>
28 #include <BRepExtrema_ExtCF.hxx>
29 #include <BRepGProp.hxx>
30 #include <BRepTools.hxx>
31 #include <BRepTopAdaptor_FClass2d.hxx>
32 #include <Geom_Curve.hxx>
33 #include <Geom2d_Curve.hxx>
34 #include <BRepLib_CheckCurveOnSurface.hxx>
35 #include <BRep_Tool.hxx>
36 #include <Geom_Plane.hxx>
37 #include <GeomLib_IsPlanarSurface.hxx>
38 #include <GeomLib_Tool.hxx>
39 #include <GeomProjLib.hxx>
40 #include <gp_Pln.hxx>
41 #include <GProp_GProps.hxx>
42 #include <IntAna_IntConicQuad.hxx>
43 #include <IntAna_Quadric.hxx>
44 #include <NCollection_Vector.hxx>
45 #include <ShapeAnalysis.hxx>
46 #include <ShapeAnalysis_Surface.hxx>
47 #include <TopoDS_Builder.hxx>
48 #include <TopoDS_Edge.hxx>
49 #include <TopoDS_Face.hxx>
50 #include <TopoDS_Shape.hxx>
51 #include <TopoDS_Shell.hxx>
52 #include <TopoDS_Vertex.hxx>
53 #include <TopoDS.hxx>
54 #include <TopExp_Explorer.hxx>
55
56 //==================================================================================================
57 double GeomAlgoAPI_ShapeTools::volume(const std::shared_ptr<GeomAPI_Shape> theShape)
58 {
59   GProp_GProps aGProps;
60   if(!theShape.get()) {
61     return 0.0;
62   }
63   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
64   if(aShape.IsNull()) {
65     return 0.0;
66   }
67   const Standard_Real anEps = 1.e-6;
68   BRepGProp::VolumeProperties(aShape, aGProps, anEps);
69   return aGProps.Mass();
70 }
71
72 //==================================================================================================
73 std::shared_ptr<GeomAPI_Pnt> GeomAlgoAPI_ShapeTools::centreOfMass(const std::shared_ptr<GeomAPI_Shape> theShape)
74 {
75   GProp_GProps aGProps;
76   if(!theShape) {
77     return std::shared_ptr<GeomAPI_Pnt>();
78   }
79   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
80   if(aShape.IsNull()) {
81     return std::shared_ptr<GeomAPI_Pnt>();
82   }
83   gp_Pnt aCentre;
84   if(aShape.ShapeType() == TopAbs_VERTEX) {
85     aCentre = BRep_Tool::Pnt(TopoDS::Vertex(aShape));
86   } else if(aShape.ShapeType() == TopAbs_EDGE || aShape.ShapeType() == TopAbs_WIRE) {
87     BRepGProp::LinearProperties(aShape, aGProps);
88     aCentre = aGProps.CentreOfMass();
89   } else {
90     BRepGProp::SurfaceProperties(aShape, aGProps);
91     aCentre = aGProps.CentreOfMass();
92   }
93   return std::shared_ptr<GeomAPI_Pnt>(new GeomAPI_Pnt(aCentre.X(), aCentre.Y(), aCentre.Z()));
94 }
95
96 //==================================================================================================
97 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::combineShapes(const std::shared_ptr<GeomAPI_Shape> theCompound,
98                                                                      const GeomAPI_Shape::ShapeType theType,
99                                                                      ListOfShape& theCombinedShapes,
100                                                                      ListOfShape& theFreeShapes)
101 {
102   GeomShapePtr aResult = theCompound;
103
104   if(!theCompound.get()) {
105     return aResult;
106   }
107
108   if(theType != GeomAPI_Shape::SHELL && theType != GeomAPI_Shape::COMPSOLID) {
109     return aResult;
110   }
111
112   TopAbs_ShapeEnum aTS = TopAbs_EDGE;
113   TopAbs_ShapeEnum aTA = TopAbs_FACE;
114   if(theType == GeomAPI_Shape::COMPSOLID) {
115     aTS = TopAbs_FACE;
116     aTA = TopAbs_SOLID;
117   }
118
119   theCombinedShapes.clear();
120   theFreeShapes.clear();
121
122   // Get free shapes.
123   const TopoDS_Shape& aShapesComp = theCompound->impl<TopoDS_Shape>();
124   for(TopoDS_Iterator anIter(aShapesComp); anIter.More(); anIter.Next() ) {
125     const TopoDS_Shape& aShape = anIter.Value();
126     if(aShape.ShapeType() > aTA) {
127       std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
128       aGeomShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
129       theFreeShapes.push_back(aGeomShape);
130     }
131   }
132
133   // Map subshapes and shapes.
134   BOPCol_IndexedDataMapOfShapeListOfShape aMapSA;
135   BOPTools::MapShapesAndAncestors(aShapesComp, aTS, aTA, aMapSA);
136   if(aMapSA.IsEmpty()) {
137     return aResult;
138   }
139
140   // Get all shapes with common subshapes and free shapes.
141   NCollection_Map<TopoDS_Shape> aFreeShapes;
142   NCollection_Vector<NCollection_Map<TopoDS_Shape>> aShapesWithCommonSubshapes;
143   for(BOPCol_IndexedDataMapOfShapeListOfShape::Iterator anIter(aMapSA); anIter.More(); anIter.Next()) {
144     const TopoDS_Shape& aShape = anIter.Key();
145     BOPCol_ListOfShape& aListOfShape = anIter.ChangeValue();
146     if(aListOfShape.IsEmpty()) {
147       continue;
148     }
149     else if(aListOfShape.Size() == 1) {
150       const TopoDS_Shape& aF = aListOfShape.First();
151       aFreeShapes.Add(aF);
152       aListOfShape.Clear();
153     } else {
154       NCollection_List<TopoDS_Shape> aTempList;
155       NCollection_Map<TopoDS_Shape> aTempMap;
156       const TopoDS_Shape& aF = aListOfShape.First();
157       const TopoDS_Shape& aL = aListOfShape.Last();
158       aTempList.Append(aF);
159       aTempList.Append(aL);
160       aTempMap.Add(aF);
161       aTempMap.Add(aL);
162       aFreeShapes.Remove(aF);
163       aFreeShapes.Remove(aL);
164       aListOfShape.Clear();
165       for(NCollection_List<TopoDS_Shape>::Iterator aTempIter(aTempList); aTempIter.More(); aTempIter.Next()) {
166         const TopoDS_Shape& aTempShape = aTempIter.Value();
167         for(BOPCol_IndexedDataMapOfShapeListOfShape::Iterator anIter(aMapSA); anIter.More(); anIter.Next()) {
168           BOPCol_ListOfShape& aTempListOfShape = anIter.ChangeValue();
169           if(aTempListOfShape.IsEmpty()) {
170             continue;
171           } else if(aTempListOfShape.Size() == 1 && aTempListOfShape.First() == aTempShape) {
172             aTempListOfShape.Clear();
173           } else if(aTempListOfShape.Size() > 1) {
174             if(aTempListOfShape.First() == aTempShape) {
175               const TopoDS_Shape& aTL = aTempListOfShape.Last();
176               if(aTempMap.Add(aTL)) {
177                 aTempList.Append(aTL);
178                 aFreeShapes.Remove(aTL);
179               }
180               aTempListOfShape.Clear();
181             } else if(aTempListOfShape.Last() == aTempShape) {
182               const TopoDS_Shape& aTF = aTempListOfShape.First();
183               if(aTempMap.Add(aTF)) {
184                 aTempList.Append(aTF);
185                 aFreeShapes.Remove(aTF);
186               }
187               aTempListOfShape.Clear();
188             }
189           }
190         }
191       }
192       aShapesWithCommonSubshapes.Append(aTempMap);
193     }
194   }
195
196   // Combine shapes with common subshapes.
197   for(NCollection_Vector<NCollection_Map<TopoDS_Shape>>::Iterator anIter(aShapesWithCommonSubshapes); anIter.More(); anIter.Next()) {
198     TopoDS_Shell aShell;
199     TopoDS_CompSolid aCSolid;
200     TopoDS_Builder aBuilder;
201     theType == GeomAPI_Shape::COMPSOLID ? aBuilder.MakeCompSolid(aCSolid) : aBuilder.MakeShell(aShell);
202     NCollection_Map<TopoDS_Shape>& aShapesMap = anIter.ChangeValue();
203     for(TopExp_Explorer anExp(aShapesComp, aTA); anExp.More(); anExp.Next()) {
204       const TopoDS_Shape& aShape = anExp.Current();
205       if(aShapesMap.Contains(aShape)) {
206         theType == GeomAPI_Shape::COMPSOLID ? aBuilder.Add(aCSolid, aShape) : aBuilder.Add(aShell, aShape);
207         aShapesMap.Remove(aShape);
208       }
209     }
210     std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
211     TopoDS_Shape* aSh = theType == GeomAPI_Shape::COMPSOLID ? new TopoDS_Shape(aCSolid) : new TopoDS_Shape(aShell);
212     aGeomShape->setImpl<TopoDS_Shape>(aSh);
213     theCombinedShapes.push_back(aGeomShape);
214   }
215
216   // Adding free shapes.
217   for(TopExp_Explorer anExp(aShapesComp, aTA); anExp.More(); anExp.Next()) {
218     const TopoDS_Shape& aShape = anExp.Current();
219     if(aFreeShapes.Contains(aShape)) {
220       std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
221       aGeomShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
222       theFreeShapes.push_back(aGeomShape);
223     }
224   }
225
226   if(theCombinedShapes.size() == 1 && theFreeShapes.size() == 0) {
227     aResult = theCombinedShapes.front();
228   } else if(theCombinedShapes.size() == 0 && theFreeShapes.size() == 1) {
229     aResult = theFreeShapes.front();
230   } else {
231     TopoDS_Compound aResultComp;
232     TopoDS_Builder aBuilder;
233     aBuilder.MakeCompound(aResultComp);
234     for(ListOfShape::const_iterator anIter = theCombinedShapes.cbegin(); anIter != theCombinedShapes.cend(); anIter++) {
235       aBuilder.Add(aResultComp, (*anIter)->impl<TopoDS_Shape>());
236     }
237     for(ListOfShape::const_iterator anIter = theFreeShapes.cbegin(); anIter != theFreeShapes.cend(); anIter++) {
238       aBuilder.Add(aResultComp, (*anIter)->impl<TopoDS_Shape>());
239     }
240     aResult->setImpl(new TopoDS_Shape(aResultComp));
241   }
242
243   return aResult;
244 }
245
246 //==================================================================================================
247 static void addSimpleShapeToList(const TopoDS_Shape& theShape, NCollection_List<TopoDS_Shape>& theList)
248 {
249   if(theShape.IsNull()) {
250     return;
251   }
252
253   if(theShape.ShapeType() == TopAbs_COMPOUND) {
254     for(TopoDS_Iterator anIt(theShape); anIt.More(); anIt.Next()) {
255       addSimpleShapeToList(anIt.Value(), theList);
256     }
257   } else {
258     theList.Append(theShape);
259   }
260 }
261
262 //==================================================================================================
263 static TopoDS_Compound makeCompound(const NCollection_List<TopoDS_Shape> theShapes)
264 {
265   TopoDS_Compound aCompound;
266
267   BRep_Builder aBuilder;
268   aBuilder.MakeCompound(aCompound);
269
270   for(NCollection_List<TopoDS_Shape>::Iterator anIt(theShapes); anIt.More(); anIt.Next()) {
271     aBuilder.Add(aCompound, anIt.Value());
272   }
273
274   return aCompound;
275 }
276
277 //==================================================================================================
278 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::groupSharedTopology(const std::shared_ptr<GeomAPI_Shape> theCompound)
279 {
280   GeomShapePtr aResult = theCompound;
281
282   if(!theCompound.get()) {
283     return aResult;
284   }
285
286   TopoDS_Shape anInShape = aResult->impl<TopoDS_Shape>();
287   NCollection_List<TopoDS_Shape> anUngroupedShapes;
288   addSimpleShapeToList(anInShape, anUngroupedShapes);
289
290   NCollection_Vector<NCollection_List<TopoDS_Shape>> aGroups;
291   while(!anUngroupedShapes.IsEmpty()) {
292     NCollection_List<TopoDS_Shape> aGroupedShapes;
293     aGroupedShapes.Append(anUngroupedShapes.First());
294     anUngroupedShapes.RemoveFirst();
295     for(NCollection_List<TopoDS_Shape>::Iterator aGroupIt(aGroupedShapes); aGroupIt.More(); aGroupIt.Next()) {
296       const TopoDS_Shape& aGroupShape = aGroupIt.Value();
297       for(NCollection_List<TopoDS_Shape>::Iterator anUngroupedIt(anUngroupedShapes); anUngroupedIt.More(); anUngroupedIt.Next()) {
298         const TopoDS_Shape& anUngroupedShape = anUngroupedIt.Value();
299         bool isFound = false;
300         for(TopExp_Explorer aGroupShapeExp(aGroupShape, TopAbs_VERTEX); aGroupShapeExp.More(); aGroupShapeExp.Next()) {
301           const TopoDS_Shape& aVertex1 = aGroupShapeExp.Current();
302           for(TopExp_Explorer anUngroupedShapeExp(anUngroupedShape, TopAbs_VERTEX); anUngroupedShapeExp.More(); anUngroupedShapeExp.Next()) {
303             const TopoDS_Shape& aVertex2 = anUngroupedShapeExp.Current();
304             if(aVertex1.IsSame(aVertex2)) {
305               aGroupedShapes.Append(anUngroupedShape);
306               anUngroupedShapes.Remove(anUngroupedIt);
307               isFound = true;
308               break;
309             }
310           }
311           if(isFound) {
312             break;
313           }
314         }
315         if(!anUngroupedIt.More()) {
316           break;
317         }
318       }
319     }
320     aGroups.Append(aGroupedShapes);
321   }
322
323   if(aGroups.Size() == 1) {
324     NCollection_List<TopoDS_Shape> aGroup = aGroups.First();
325     GeomShapePtr aGeomShape(new GeomAPI_Shape());
326     aGeomShape->setImpl(new TopoDS_Shape(makeCompound(aGroup)));
327     ListOfShape aCompSolids, aFreeSolids;
328     aGeomShape = GeomAlgoAPI_ShapeTools::combineShapes(aGeomShape,
329                                                         GeomAPI_Shape::COMPSOLID,
330                                                         aCompSolids,
331                                                         aFreeSolids);
332     aResult = aGeomShape;
333   } else {
334     TopoDS_Compound aCompound;
335     BRep_Builder aBuilder;
336     aBuilder.MakeCompound(aCompound);
337     ListOfShape aCompSolids, aFreeSolids;
338     for(NCollection_Vector<NCollection_List<TopoDS_Shape>>::Iterator anIt(aGroups); anIt.More(); anIt.Next()) {
339       NCollection_List<TopoDS_Shape> aGroup = anIt.Value();
340       GeomShapePtr aGeomShape(new GeomAPI_Shape());
341       if(aGroup.Size() == 1) {
342         aGeomShape->setImpl(new TopoDS_Shape(aGroup.First()));
343       } else {
344         aGeomShape->setImpl(new TopoDS_Shape(makeCompound(aGroup)));
345         aGeomShape = GeomAlgoAPI_ShapeTools::combineShapes(aGeomShape,
346                                                            GeomAPI_Shape::COMPSOLID,
347                                                            aCompSolids,
348                                                            aFreeSolids);
349       }
350       aBuilder.Add(aCompound, aGeomShape->impl<TopoDS_Shape>());
351     }
352
353     if(!aCompound.IsNull()) {
354       aResult->setImpl(new TopoDS_Shape(aCompound));
355     }
356   }
357
358   return aResult;
359 }
360
361 //==================================================================================================
362 std::list<std::shared_ptr<GeomAPI_Pnt> > GeomAlgoAPI_ShapeTools::getBoundingBox(const ListOfShape& theShapes, const double theEnlarge)
363 {
364   // Bounding box of all objects.
365   Bnd_Box aBndBox;
366
367   // Getting box.
368   for (ListOfShape::const_iterator anObjectsIt = theShapes.begin(); anObjectsIt != theShapes.end(); anObjectsIt++) {
369     const TopoDS_Shape& aShape = (*anObjectsIt)->impl<TopoDS_Shape>();
370     BRepBndLib::Add(aShape, aBndBox);
371   }
372
373   if(theEnlarge != 0.0) {
374     // We enlarge bounding box just to be sure that plane will be large enough to cut all objects.
375     aBndBox.Enlarge(theEnlarge);
376   }
377
378   Standard_Real aXArr[2] = {aBndBox.CornerMin().X(), aBndBox.CornerMax().X()};
379   Standard_Real aYArr[2] = {aBndBox.CornerMin().Y(), aBndBox.CornerMax().Y()};
380   Standard_Real aZArr[2] = {aBndBox.CornerMin().Z(), aBndBox.CornerMax().Z()};
381   std::list<std::shared_ptr<GeomAPI_Pnt> > aResultPoints;
382   int aNum = 0;
383   for(int i = 0; i < 2; i++) {
384     for(int j = 0; j < 2; j++) {
385       for(int k = 0; k < 2; k++) {
386         std::shared_ptr<GeomAPI_Pnt> aPnt(new GeomAPI_Pnt(aXArr[i], aYArr[j], aZArr[k]));
387         aResultPoints.push_back(aPnt);
388       }
389     }
390   }
391
392   return aResultPoints;
393 }
394
395 //==================================================================================================
396 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::faceToInfinitePlane(const std::shared_ptr<GeomAPI_Shape> theFace)
397 {
398   if (!theFace.get())
399     return std::shared_ptr<GeomAPI_Shape>();
400
401   TopoDS_Face aPlaneFace = TopoDS::Face(theFace->impl<TopoDS_Shape>());
402   if (aPlaneFace.IsNull())
403     return std::shared_ptr<GeomAPI_Shape>();
404
405   Handle(Geom_Plane) aPlane = Handle(Geom_Plane)::DownCast(BRep_Tool::Surface(aPlaneFace));
406   if (aPlane.IsNull())
407     return std::shared_ptr<GeomAPI_Shape>();
408
409   // make an infinity face on the plane
410   TopoDS_Shape anInfiniteFace = BRepBuilderAPI_MakeFace(aPlane->Pln()).Shape();
411
412   std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
413   aResult->setImpl(new TopoDS_Shape(anInfiniteFace));
414   return aResult;
415 }
416
417 //==================================================================================================
418 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::fitPlaneToBox(const std::shared_ptr<GeomAPI_Shape> thePlane,
419                                                                      const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints)
420 {
421   std::shared_ptr<GeomAPI_Shape> aResultShape;
422
423   if(!thePlane.get()) {
424     return aResultShape;
425   }
426
427   const TopoDS_Shape& aShape = thePlane->impl<TopoDS_Shape>();
428   if(aShape.ShapeType() != TopAbs_FACE) {
429     return aResultShape;
430   }
431
432   TopoDS_Face aFace = TopoDS::Face(aShape);
433   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace);
434   if(aSurf.IsNull()) {
435     return aResultShape;
436   }
437
438   GeomLib_IsPlanarSurface isPlanar(aSurf);
439   if(!isPlanar.IsPlanar()) {
440     return aResultShape;
441   }
442
443   if(thePoints.size() != 8) {
444     return aResultShape;
445   }
446
447   const gp_Pln& aFacePln = isPlanar.Plan();
448   Handle(Geom_Plane) aFacePlane = new Geom_Plane(aFacePln);
449   IntAna_Quadric aQuadric(aFacePln);
450   Standard_Real UMin, UMax, VMin, VMax;
451   UMin = UMax = VMin = VMax = 0;
452   for (std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPointsIt = thePoints.begin(); aPointsIt != thePoints.end(); aPointsIt++) {
453     const gp_Pnt& aPnt = (*aPointsIt)->impl<gp_Pnt>();
454     gp_Lin aLin(aPnt, aFacePln.Axis().Direction());
455     IntAna_IntConicQuad anIntAna(aLin, aQuadric);
456     const gp_Pnt& aPntOnFace = anIntAna.Point(1);
457     Standard_Real aPntU(0), aPntV(0);
458     GeomLib_Tool::Parameters(aFacePlane, aPntOnFace, Precision::Confusion(), aPntU, aPntV);
459     if(aPntU < UMin) UMin = aPntU;
460     if(aPntU > UMax) UMax = aPntU;
461     if(aPntV < VMin) VMin = aPntV;
462     if(aPntV > VMax) VMax = aPntV;
463   }
464   aResultShape.reset(new GeomAPI_Shape);
465   aResultShape->setImpl(new TopoDS_Shape(BRepLib_MakeFace(aFacePln, UMin, UMax, VMin, VMax).Face()));
466
467   return aResultShape;
468 }
469
470 //==================================================================================================
471 void GeomAlgoAPI_ShapeTools::findBounds(const std::shared_ptr<GeomAPI_Shape> theShape,
472                                         std::shared_ptr<GeomAPI_Vertex>& theV1,
473                                         std::shared_ptr<GeomAPI_Vertex>& theV2)
474 {
475   if(!theShape.get()) {
476     std::shared_ptr<GeomAPI_Vertex> aVertex(new GeomAPI_Vertex);
477     aVertex->setImpl(new TopoDS_Vertex());
478     theV1 = aVertex;
479     theV2 = aVertex;
480     return;
481   }
482
483   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
484   TopoDS_Vertex aV1, aV2;
485   ShapeAnalysis::FindBounds(aShape, aV1, aV2);
486
487   std::shared_ptr<GeomAPI_Vertex> aGeomV1(new GeomAPI_Vertex()), aGeomV2(new GeomAPI_Vertex());
488   aGeomV1->setImpl(new TopoDS_Vertex(aV1));
489   aGeomV2->setImpl(new TopoDS_Vertex(aV2));
490   theV1 = aGeomV1;
491   theV2 = aGeomV2;
492 }
493
494 //==================================================================================================
495 void GeomAlgoAPI_ShapeTools::makeFacesWithHoles(const std::shared_ptr<GeomAPI_Pnt> theOrigin,
496                                                 const std::shared_ptr<GeomAPI_Dir> theDirection,
497                                                 const ListOfShape& theWires,
498                                                 ListOfShape& theFaces)
499 {
500   BRepBuilderAPI_MakeFace aMKFace(gp_Pln(theOrigin->impl<gp_Pnt>(),
501                                           theDirection->impl<gp_Dir>()));
502   TopoDS_Face aFace = aMKFace.Face();
503
504   BRepAlgo_FaceRestrictor aFRestrictor;
505   aFRestrictor.Init(aFace, Standard_False, Standard_True);
506   for(ListOfShape::const_iterator anIt = theWires.cbegin();
507       anIt != theWires.cend();
508       ++anIt) {
509     TopoDS_Wire aWire = TopoDS::Wire((*anIt)->impl<TopoDS_Shape>());
510     aFRestrictor.Add(aWire);
511   }
512
513   aFRestrictor.Perform();
514
515   if(!aFRestrictor.IsDone()) {
516     return;
517   }
518
519   for(; aFRestrictor.More(); aFRestrictor.Next()) {
520     GeomShapePtr aShape(new GeomAPI_Shape());
521     aShape->setImpl(new TopoDS_Shape(aFRestrictor.Current()));
522     theFaces.push_back(aShape);
523   }
524 }
525
526 //==================================================================================================
527 std::shared_ptr<GeomAPI_Pln> GeomAlgoAPI_ShapeTools::findPlane(const ListOfShape& theShapes)
528 {
529   TopoDS_Compound aCompound;
530   BRep_Builder aBuilder;
531   aBuilder.MakeCompound(aCompound);
532
533   for(ListOfShape::const_iterator anIt = theShapes.cbegin(); anIt != theShapes.cend(); ++anIt) {
534     aBuilder.Add(aCompound, (*anIt)->impl<TopoDS_Shape>());
535   }
536   BRepBuilderAPI_FindPlane aFindPlane(aCompound);
537
538   if(aFindPlane.Found() != Standard_True) {
539     return std::shared_ptr<GeomAPI_Pln>();
540   }
541
542   Handle(Geom_Plane) aPlane = aFindPlane.Plane();
543   gp_Pnt aLoc = aPlane->Location();
544   gp_Dir aDir = aPlane->Axis().Direction();
545
546   std::shared_ptr<GeomAPI_Pnt> aGeomPnt(new GeomAPI_Pnt(aLoc.X(), aLoc.Y(), aLoc.Z()));
547   std::shared_ptr<GeomAPI_Dir> aGeomDir(new GeomAPI_Dir(aDir.X(), aDir.Y(), aDir.Z()));
548
549   std::shared_ptr<GeomAPI_Pln> aPln(new GeomAPI_Pln(aGeomPnt, aGeomDir));
550
551   return aPln;
552 }
553
554 //==================================================================================================
555 bool GeomAlgoAPI_ShapeTools::isSubShapeInsideShape(const std::shared_ptr<GeomAPI_Shape> theSubShape,
556                                                    const std::shared_ptr<GeomAPI_Shape> theBaseShape)
557 {
558   if(!theSubShape.get() || !theBaseShape.get()) {
559     return false;
560   }
561
562   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
563   const TopoDS_Shape& aBaseShape = theBaseShape->impl<TopoDS_Shape>();
564
565   if(aSubShape.ShapeType() == TopAbs_VERTEX) {
566     // If sub-shape is a vertex check distance to shape. If it is <= Precision::Confusion() then OK.
567     BRepExtrema_DistShapeShape aDist(aBaseShape, aSubShape);
568     aDist.Perform();
569     if(!aDist.IsDone() || aDist.Value() > Precision::Confusion()) {
570       return false;
571     }
572   } else if (aSubShape.ShapeType() == TopAbs_EDGE) {
573     if(aBaseShape.ShapeType() == TopAbs_FACE) {
574       // Check that edge is on face surface.
575       TopoDS_Face aFace = TopoDS::Face(aBaseShape);
576       TopoDS_Edge anEdge = TopoDS::Edge(aSubShape);
577       BRepLib_CheckCurveOnSurface aCheck(anEdge, aFace);
578       aCheck.Perform();
579       if(!aCheck.IsDone() || aCheck.MaxDistance() > Precision::Confusion()) {
580         return false;
581       }
582
583       // Check intersections.
584       TopoDS_Vertex aV1, aV2;
585       ShapeAnalysis::FindBounds(anEdge, aV1, aV2);
586       gp_Pnt aPnt1 = BRep_Tool::Pnt(aV1);
587       gp_Pnt aPnt2 = BRep_Tool::Pnt(aV2);
588       for(TopExp_Explorer anExp(aBaseShape, TopAbs_EDGE); anExp.More(); anExp.Next()) {
589         const TopoDS_Shape& anEdgeOnFace = anExp.Current();
590         BRepExtrema_DistShapeShape aDist(anEdgeOnFace, anEdge);
591         aDist.Perform();
592         if(aDist.IsDone() && aDist.Value() <= Precision::Confusion()) {
593           // Edge intersect face bound. Check that it is not on edge begin or end.
594           for(Standard_Integer anIndex = 1; anIndex <= aDist.NbSolution(); ++anIndex) {
595             gp_Pnt aPntOnSubShape = aDist.PointOnShape2(anIndex);
596             if(aPntOnSubShape.Distance(aPnt1) > Precision::Confusion()
597                 && aPntOnSubShape.Distance(aPnt2) > Precision::Confusion()) {
598               return false;
599             }
600           }
601         }
602       }
603
604       // No intersections found. Edge is inside or outside face. Check it.
605       BRepAdaptor_Curve aCurveAdaptor(anEdge);
606       gp_Pnt aPointToCheck = aCurveAdaptor.Value((aCurveAdaptor.FirstParameter() + aCurveAdaptor.LastParameter()) / 2.0);
607       Handle(Geom_Surface) aSurface = BRep_Tool::Surface(aFace);
608       ShapeAnalysis_Surface aSAS(aSurface);
609       gp_Pnt2d aPointOnFace = aSAS.ValueOfUV(aPointToCheck, Precision::Confusion());
610       BRepTopAdaptor_FClass2d aFClass2d(aFace, Precision::Confusion());
611       if(aFClass2d.Perform(aPointOnFace) == TopAbs_OUT) {
612         return false;
613       }
614
615     } else {
616       return false;
617     }
618   } else {
619     return false;
620   }
621
622   return true;
623 }
624
625 //==================================================================================================
626 bool GeomAlgoAPI_ShapeTools::isShapeValid(const std::shared_ptr<GeomAPI_Shape> theShape)
627 {
628   if(!theShape.get()) {
629     return false;
630   }
631
632   BRepCheck_Analyzer aChecker(theShape->impl<TopoDS_Shape>());
633   return (aChecker.IsValid() == Standard_True);
634 }
635
636 //==================================================================================================
637 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::getFaceOuterWire(const std::shared_ptr<GeomAPI_Shape> theFace)
638 {
639   GeomShapePtr anOuterWire;
640
641   if(!theFace.get() || !theFace->isFace()) {
642     return anOuterWire;
643   }
644
645   TopoDS_Face aFace = TopoDS::Face(theFace->impl<TopoDS_Shape>());
646   TopoDS_Wire aWire = BRepTools::OuterWire(aFace);
647
648   anOuterWire.reset(new GeomAPI_Shape());
649   anOuterWire->setImpl(new TopoDS_Shape(aWire));
650
651   return anOuterWire;
652 }
653
654 //==================================================================================================
655 bool GeomAlgoAPI_ShapeTools::isParallel(const std::shared_ptr<GeomAPI_Edge> theEdge,
656                                         const std::shared_ptr<GeomAPI_Face> theFace)
657 {
658   if(!theEdge.get() || !theFace.get()) {
659     return false;
660   }
661
662   TopoDS_Edge anEdge = TopoDS::Edge(theEdge->impl<TopoDS_Shape>());
663   TopoDS_Face aFace  = TopoDS::Face(theFace->impl<TopoDS_Shape>());
664
665   BRepExtrema_ExtCF anExt(anEdge, aFace);
666   return anExt.IsParallel() == Standard_True;
667 }