Salome HOME
Issue #2024: Redesign of circle and arc of circle
[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_Edge.h>
12 #include <GeomAPI_Dir.h>
13 #include <GeomAPI_Face.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 <Geom2d_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 <gp_Pln.hxx>
40 #include <GProp_GProps.hxx>
41 #include <IntAna_IntConicQuad.hxx>
42 #include <IntAna_Quadric.hxx>
43 #include <NCollection_Vector.hxx>
44 #include <ShapeAnalysis.hxx>
45 #include <ShapeAnalysis_Surface.hxx>
46 #include <TopoDS_Builder.hxx>
47 #include <TopoDS_Edge.hxx>
48 #include <TopoDS_Face.hxx>
49 #include <TopoDS_Shape.hxx>
50 #include <TopoDS_Shell.hxx>
51 #include <TopoDS_Vertex.hxx>
52 #include <TopoDS.hxx>
53 #include <TopExp_Explorer.hxx>
54 #include <TopTools_ListIteratorOfListOfShape.hxx>
55
56 #include <BOPAlgo_Builder.hxx>
57 #include <BRepBuilderAPI_MakeVertex.hxx>
58 #include <TopoDS_Edge.hxx>
59
60 //==================================================================================================
61 double GeomAlgoAPI_ShapeTools::volume(const std::shared_ptr<GeomAPI_Shape> theShape)
62 {
63   GProp_GProps aGProps;
64   if(!theShape.get()) {
65     return 0.0;
66   }
67   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
68   if(aShape.IsNull()) {
69     return 0.0;
70   }
71   const Standard_Real anEps = 1.e-6;
72   BRepGProp::VolumeProperties(aShape, aGProps, anEps);
73   return aGProps.Mass();
74 }
75
76 //==================================================================================================
77 std::shared_ptr<GeomAPI_Pnt>
78   GeomAlgoAPI_ShapeTools::centreOfMass(const std::shared_ptr<GeomAPI_Shape> theShape)
79 {
80   GProp_GProps aGProps;
81   if(!theShape) {
82     return std::shared_ptr<GeomAPI_Pnt>();
83   }
84   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
85   if(aShape.IsNull()) {
86     return std::shared_ptr<GeomAPI_Pnt>();
87   }
88   gp_Pnt aCentre;
89   if(aShape.ShapeType() == TopAbs_VERTEX) {
90     aCentre = BRep_Tool::Pnt(TopoDS::Vertex(aShape));
91   } else if(aShape.ShapeType() == TopAbs_EDGE || aShape.ShapeType() == TopAbs_WIRE) {
92     BRepGProp::LinearProperties(aShape, aGProps);
93     aCentre = aGProps.CentreOfMass();
94   } else {
95     BRepGProp::SurfaceProperties(aShape, aGProps);
96     aCentre = aGProps.CentreOfMass();
97   }
98   return std::shared_ptr<GeomAPI_Pnt>(new GeomAPI_Pnt(aCentre.X(), aCentre.Y(), aCentre.Z()));
99 }
100
101 //==================================================================================================
102 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::combineShapes(
103   const std::shared_ptr<GeomAPI_Shape> theCompound,
104   const GeomAPI_Shape::ShapeType theType,
105   ListOfShape& theCombinedShapes,
106   ListOfShape& theFreeShapes)
107 {
108   GeomShapePtr aResult = theCompound;
109
110   if(!theCompound.get()) {
111     return aResult;
112   }
113
114   if(theType != GeomAPI_Shape::SHELL && theType != GeomAPI_Shape::COMPSOLID) {
115     return aResult;
116   }
117
118   TopAbs_ShapeEnum aTS = TopAbs_EDGE;
119   TopAbs_ShapeEnum aTA = TopAbs_FACE;
120   if(theType == GeomAPI_Shape::COMPSOLID) {
121     aTS = TopAbs_FACE;
122     aTA = TopAbs_SOLID;
123   }
124
125   theCombinedShapes.clear();
126   theFreeShapes.clear();
127
128   // Get free shapes.
129   const TopoDS_Shape& aShapesComp = theCompound->impl<TopoDS_Shape>();
130   for(TopoDS_Iterator anIter(aShapesComp); anIter.More(); anIter.Next() ) {
131     const TopoDS_Shape& aShape = anIter.Value();
132     if(aShape.ShapeType() > aTA) {
133       std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
134       aGeomShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
135       theFreeShapes.push_back(aGeomShape);
136     }
137   }
138
139   // Map subshapes and shapes.
140   BOPCol_IndexedDataMapOfShapeListOfShape aMapSA;
141   BOPTools::MapShapesAndAncestors(aShapesComp, aTS, aTA, aMapSA);
142   if(aMapSA.IsEmpty()) {
143     return aResult;
144   }
145
146   // Get all shapes with common subshapes and free shapes.
147   NCollection_Map<TopoDS_Shape> aFreeShapes;
148   NCollection_Vector<NCollection_Map<TopoDS_Shape>> aShapesWithCommonSubshapes;
149   for(BOPCol_IndexedDataMapOfShapeListOfShape::Iterator
150       anIter(aMapSA); anIter.More(); anIter.Next()) {
151     const TopoDS_Shape& aShape = anIter.Key();
152     BOPCol_ListOfShape& aListOfShape = anIter.ChangeValue();
153     if(aListOfShape.IsEmpty()) {
154       continue;
155     }
156     else if(aListOfShape.Size() == 1) {
157       const TopoDS_Shape& aF = aListOfShape.First();
158       aFreeShapes.Add(aF);
159       aListOfShape.Clear();
160     } else {
161       NCollection_List<TopoDS_Shape> aTempList;
162       NCollection_Map<TopoDS_Shape> aTempMap;
163       const TopoDS_Shape& aF = aListOfShape.First();
164       const TopoDS_Shape& aL = aListOfShape.Last();
165       aTempList.Append(aF);
166       aTempList.Append(aL);
167       aTempMap.Add(aF);
168       aTempMap.Add(aL);
169       aFreeShapes.Remove(aF);
170       aFreeShapes.Remove(aL);
171       aListOfShape.Clear();
172       for(NCollection_List<TopoDS_Shape>::Iterator
173           aTempIter(aTempList); aTempIter.More(); aTempIter.Next()) {
174         const TopoDS_Shape& aTempShape = aTempIter.Value();
175         for(BOPCol_IndexedDataMapOfShapeListOfShape::Iterator
176             anIter(aMapSA); anIter.More(); anIter.Next()) {
177           BOPCol_ListOfShape& aTempListOfShape = anIter.ChangeValue();
178           if(aTempListOfShape.IsEmpty()) {
179             continue;
180           } else if(aTempListOfShape.Size() == 1 && aTempListOfShape.First() == aTempShape) {
181             aTempListOfShape.Clear();
182           } else if(aTempListOfShape.Size() > 1) {
183             if(aTempListOfShape.First() == aTempShape) {
184               const TopoDS_Shape& aTL = aTempListOfShape.Last();
185               if(aTempMap.Add(aTL)) {
186                 aTempList.Append(aTL);
187                 aFreeShapes.Remove(aTL);
188               }
189               aTempListOfShape.Clear();
190             } else if(aTempListOfShape.Last() == aTempShape) {
191               const TopoDS_Shape& aTF = aTempListOfShape.First();
192               if(aTempMap.Add(aTF)) {
193                 aTempList.Append(aTF);
194                 aFreeShapes.Remove(aTF);
195               }
196               aTempListOfShape.Clear();
197             }
198           }
199         }
200       }
201       aShapesWithCommonSubshapes.Append(aTempMap);
202     }
203   }
204
205   // Combine shapes with common subshapes.
206   for(NCollection_Vector<NCollection_Map<TopoDS_Shape>>::Iterator
207       anIter(aShapesWithCommonSubshapes); anIter.More(); anIter.Next()) {
208     TopoDS_Shell aShell;
209     TopoDS_CompSolid aCSolid;
210     TopoDS_Builder aBuilder;
211     theType ==
212       GeomAPI_Shape::COMPSOLID ? aBuilder.MakeCompSolid(aCSolid) : aBuilder.MakeShell(aShell);
213     NCollection_Map<TopoDS_Shape>& aShapesMap = anIter.ChangeValue();
214     for(TopExp_Explorer anExp(aShapesComp, aTA); anExp.More(); anExp.Next()) {
215       const TopoDS_Shape& aShape = anExp.Current();
216       if(aShapesMap.Contains(aShape)) {
217         theType ==
218           GeomAPI_Shape::COMPSOLID ? aBuilder.Add(aCSolid, aShape) : aBuilder.Add(aShell, aShape);
219         aShapesMap.Remove(aShape);
220       }
221     }
222     std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
223     TopoDS_Shape* aSh = theType == GeomAPI_Shape::COMPSOLID ? new TopoDS_Shape(aCSolid) :
224                                                               new TopoDS_Shape(aShell);
225     aGeomShape->setImpl<TopoDS_Shape>(aSh);
226     theCombinedShapes.push_back(aGeomShape);
227   }
228
229   // Adding free shapes.
230   for(TopExp_Explorer anExp(aShapesComp, aTA); anExp.More(); anExp.Next()) {
231     const TopoDS_Shape& aShape = anExp.Current();
232     if(aFreeShapes.Contains(aShape)) {
233       std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
234       aGeomShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
235       theFreeShapes.push_back(aGeomShape);
236     }
237   }
238
239   if(theCombinedShapes.size() == 1 && theFreeShapes.size() == 0) {
240     aResult = theCombinedShapes.front();
241   } else if(theCombinedShapes.size() == 0 && theFreeShapes.size() == 1) {
242     aResult = theFreeShapes.front();
243   } else {
244     TopoDS_Compound aResultComp;
245     TopoDS_Builder aBuilder;
246     aBuilder.MakeCompound(aResultComp);
247     for(ListOfShape::const_iterator anIter = theCombinedShapes.cbegin();
248         anIter != theCombinedShapes.cend(); anIter++) {
249       aBuilder.Add(aResultComp, (*anIter)->impl<TopoDS_Shape>());
250     }
251     for(ListOfShape::const_iterator anIter = theFreeShapes.cbegin();
252         anIter != theFreeShapes.cend(); anIter++) {
253       aBuilder.Add(aResultComp, (*anIter)->impl<TopoDS_Shape>());
254     }
255     aResult->setImpl(new TopoDS_Shape(aResultComp));
256   }
257
258   return aResult;
259 }
260
261 //==================================================================================================
262 static void addSimpleShapeToList(const TopoDS_Shape& theShape,
263                                  NCollection_List<TopoDS_Shape>& theList)
264 {
265   if(theShape.IsNull()) {
266     return;
267   }
268
269   if(theShape.ShapeType() == TopAbs_COMPOUND) {
270     for(TopoDS_Iterator anIt(theShape); anIt.More(); anIt.Next()) {
271       addSimpleShapeToList(anIt.Value(), theList);
272     }
273   } else {
274     theList.Append(theShape);
275   }
276 }
277
278 //==================================================================================================
279 static TopoDS_Compound makeCompound(const NCollection_List<TopoDS_Shape> theShapes)
280 {
281   TopoDS_Compound aCompound;
282
283   BRep_Builder aBuilder;
284   aBuilder.MakeCompound(aCompound);
285
286   for(NCollection_List<TopoDS_Shape>::Iterator anIt(theShapes); anIt.More(); anIt.Next()) {
287     aBuilder.Add(aCompound, anIt.Value());
288   }
289
290   return aCompound;
291 }
292
293 //==================================================================================================
294 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::groupSharedTopology(
295   const std::shared_ptr<GeomAPI_Shape> theCompound)
296 {
297   GeomShapePtr aResult = theCompound;
298
299   if(!theCompound.get()) {
300     return aResult;
301   }
302
303   TopoDS_Shape anInShape = aResult->impl<TopoDS_Shape>();
304   NCollection_List<TopoDS_Shape> anUngroupedShapes, aStillUngroupedShapes;
305   addSimpleShapeToList(anInShape, anUngroupedShapes);
306
307   NCollection_Vector<NCollection_List<TopoDS_Shape>> aGroups;
308   while(!anUngroupedShapes.IsEmpty()) {
309     NCollection_List<TopoDS_Shape> aGroupedShapes;
310     aGroupedShapes.Append(anUngroupedShapes.First());
311     anUngroupedShapes.RemoveFirst();
312     for(NCollection_List<TopoDS_Shape>::Iterator aGroupIt(aGroupedShapes);
313         aGroupIt.More(); aGroupIt.Next()) {
314       const TopoDS_Shape& aGroupedShape = aGroupIt.Value();
315       for(TopExp_Explorer aGroupShapeExp(aGroupedShape, TopAbs_VERTEX);
316           aGroupShapeExp.More();
317           aGroupShapeExp.Next()) {
318         // Find all shapes which have same vertex.
319         aStillUngroupedShapes.Clear();
320         const TopoDS_Shape& aVertex1 = aGroupShapeExp.Current();
321         for(NCollection_List<TopoDS_Shape>::Iterator anUngroupedIt(anUngroupedShapes);
322             anUngroupedIt.More();
323             anUngroupedIt.Next()) {
324           const TopoDS_Shape& anUngroupedShape = anUngroupedIt.Value();
325           bool isAdded = false;
326           for(TopExp_Explorer anUgroupedShapeExp(anUngroupedShape, TopAbs_VERTEX);
327               anUgroupedShapeExp.More();
328               anUgroupedShapeExp.Next()) {
329             const TopoDS_Shape& aVertex2 = anUgroupedShapeExp.Current();
330             if(aVertex1.IsSame(aVertex2)) {
331               aGroupedShapes.Append(anUngroupedShape);
332               isAdded = true;
333               break;
334             }
335           }
336           if(!isAdded) {
337             aStillUngroupedShapes.Append(anUngroupedShape);
338           }
339         }
340         anUngroupedShapes = aStillUngroupedShapes;
341         if(anUngroupedShapes.IsEmpty()) {
342           break;
343         }
344       }
345       if(anUngroupedShapes.IsEmpty()) {
346         break;
347       }
348     }
349     aGroups.Append(aGroupedShapes);
350   }
351
352   TopoDS_Compound aCompound;
353   BRep_Builder aBuilder;
354   aBuilder.MakeCompound(aCompound);
355   ListOfShape aCompSolids, aFreeSolids;
356   for(NCollection_Vector<NCollection_List<TopoDS_Shape>>::Iterator
357       anIt(aGroups); anIt.More(); anIt.Next()) {
358     NCollection_List<TopoDS_Shape> aGroup = anIt.Value();
359     GeomShapePtr aGeomShape(new GeomAPI_Shape());
360     if(aGroup.Size() == 1) {
361       aGeomShape->setImpl(new TopoDS_Shape(aGroup.First()));
362     } else {
363       aGeomShape->setImpl(new TopoDS_Shape(makeCompound(aGroup)));
364       aGeomShape = GeomAlgoAPI_ShapeTools::combineShapes(aGeomShape,
365                                                          GeomAPI_Shape::COMPSOLID,
366                                                          aCompSolids,
367                                                          aFreeSolids);
368     }
369     aBuilder.Add(aCompound, aGeomShape->impl<TopoDS_Shape>());
370   }
371
372   if(!aCompound.IsNull()) {
373     aResult->setImpl(new TopoDS_Shape(aCompound));
374   }
375
376   return aResult;
377 }
378
379 //==================================================================================================
380 std::list<std::shared_ptr<GeomAPI_Pnt> >
381   GeomAlgoAPI_ShapeTools::getBoundingBox(const ListOfShape& theShapes, const double theEnlarge)
382 {
383   // Bounding box of all objects.
384   Bnd_Box aBndBox;
385
386   // Getting box.
387   for (ListOfShape::const_iterator
388     anObjectsIt = theShapes.begin(); anObjectsIt != theShapes.end(); anObjectsIt++) {
389     const TopoDS_Shape& aShape = (*anObjectsIt)->impl<TopoDS_Shape>();
390     BRepBndLib::Add(aShape, aBndBox);
391   }
392
393   if(theEnlarge != 0.0) {
394     // We enlarge bounding box just to be sure that plane will be large enough to cut all objects.
395     aBndBox.Enlarge(theEnlarge);
396   }
397
398   Standard_Real aXArr[2] = {aBndBox.CornerMin().X(), aBndBox.CornerMax().X()};
399   Standard_Real aYArr[2] = {aBndBox.CornerMin().Y(), aBndBox.CornerMax().Y()};
400   Standard_Real aZArr[2] = {aBndBox.CornerMin().Z(), aBndBox.CornerMax().Z()};
401   std::list<std::shared_ptr<GeomAPI_Pnt> > aResultPoints;
402   int aNum = 0;
403   for(int i = 0; i < 2; i++) {
404     for(int j = 0; j < 2; j++) {
405       for(int k = 0; k < 2; k++) {
406         std::shared_ptr<GeomAPI_Pnt> aPnt(new GeomAPI_Pnt(aXArr[i], aYArr[j], aZArr[k]));
407         aResultPoints.push_back(aPnt);
408       }
409     }
410   }
411
412   return aResultPoints;
413 }
414
415 //==================================================================================================
416 std::shared_ptr<GeomAPI_Shape>
417   GeomAlgoAPI_ShapeTools::faceToInfinitePlane(const std::shared_ptr<GeomAPI_Shape> theFace)
418 {
419   if (!theFace.get())
420     return std::shared_ptr<GeomAPI_Shape>();
421
422   TopoDS_Face aPlaneFace = TopoDS::Face(theFace->impl<TopoDS_Shape>());
423   if (aPlaneFace.IsNull())
424     return std::shared_ptr<GeomAPI_Shape>();
425
426   Handle(Geom_Plane) aPlane = Handle(Geom_Plane)::DownCast(BRep_Tool::Surface(aPlaneFace));
427   if (aPlane.IsNull())
428     return std::shared_ptr<GeomAPI_Shape>();
429
430   // make an infinity face on the plane
431   TopoDS_Shape anInfiniteFace = BRepBuilderAPI_MakeFace(aPlane->Pln()).Shape();
432
433   std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
434   aResult->setImpl(new TopoDS_Shape(anInfiniteFace));
435   return aResult;
436 }
437
438 //==================================================================================================
439 std::shared_ptr<GeomAPI_Face> GeomAlgoAPI_ShapeTools::fitPlaneToBox(
440   const std::shared_ptr<GeomAPI_Shape> thePlane,
441   const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints)
442 {
443   std::shared_ptr<GeomAPI_Face> aResultFace;
444
445   if(!thePlane.get()) {
446     return aResultFace;
447   }
448
449   const TopoDS_Shape& aShape = thePlane->impl<TopoDS_Shape>();
450   if(aShape.ShapeType() != TopAbs_FACE) {
451     return aResultFace;
452   }
453
454   TopoDS_Face aFace = TopoDS::Face(aShape);
455   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace);
456   if(aSurf.IsNull()) {
457     return aResultFace;
458   }
459
460   GeomLib_IsPlanarSurface isPlanar(aSurf);
461   if(!isPlanar.IsPlanar()) {
462     return aResultFace;
463   }
464
465   if(thePoints.size() != 8) {
466     return aResultFace;
467   }
468
469   const gp_Pln& aFacePln = isPlanar.Plan();
470   Handle(Geom_Plane) aFacePlane = new Geom_Plane(aFacePln);
471   IntAna_Quadric aQuadric(aFacePln);
472   Standard_Real UMin, UMax, VMin, VMax;
473   UMin = UMax = VMin = VMax = 0;
474   for (std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator
475        aPointsIt = thePoints.begin(); aPointsIt != thePoints.end(); aPointsIt++) {
476     const gp_Pnt& aPnt = (*aPointsIt)->impl<gp_Pnt>();
477     gp_Lin aLin(aPnt, aFacePln.Axis().Direction());
478     IntAna_IntConicQuad anIntAna(aLin, aQuadric);
479     const gp_Pnt& aPntOnFace = anIntAna.Point(1);
480     Standard_Real aPntU(0), aPntV(0);
481     GeomLib_Tool::Parameters(aFacePlane, aPntOnFace, Precision::Confusion(), aPntU, aPntV);
482     if(aPntU < UMin) UMin = aPntU;
483     if(aPntU > UMax) UMax = aPntU;
484     if(aPntV < VMin) VMin = aPntV;
485     if(aPntV > VMax) VMax = aPntV;
486   }
487   aResultFace.reset(new GeomAPI_Face());
488   aResultFace->setImpl(new TopoDS_Face(BRepLib_MakeFace(aFacePln, UMin, UMax, VMin, VMax).Face()));
489
490   return aResultFace;
491 }
492
493 //==================================================================================================
494 void GeomAlgoAPI_ShapeTools::findBounds(const std::shared_ptr<GeomAPI_Shape> theShape,
495                                         std::shared_ptr<GeomAPI_Vertex>& theV1,
496                                         std::shared_ptr<GeomAPI_Vertex>& theV2)
497 {
498   if(!theShape.get()) {
499     std::shared_ptr<GeomAPI_Vertex> aVertex(new GeomAPI_Vertex);
500     aVertex->setImpl(new TopoDS_Vertex());
501     theV1 = aVertex;
502     theV2 = aVertex;
503     return;
504   }
505
506   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
507   TopoDS_Vertex aV1, aV2;
508   ShapeAnalysis::FindBounds(aShape, aV1, aV2);
509
510   std::shared_ptr<GeomAPI_Vertex> aGeomV1(new GeomAPI_Vertex()), aGeomV2(new GeomAPI_Vertex());
511   aGeomV1->setImpl(new TopoDS_Vertex(aV1));
512   aGeomV2->setImpl(new TopoDS_Vertex(aV2));
513   theV1 = aGeomV1;
514   theV2 = aGeomV2;
515 }
516
517 //==================================================================================================
518 void GeomAlgoAPI_ShapeTools::makeFacesWithHoles(const std::shared_ptr<GeomAPI_Pnt> theOrigin,
519                                                 const std::shared_ptr<GeomAPI_Dir> theDirection,
520                                                 const ListOfShape& theWires,
521                                                 ListOfShape& theFaces)
522 {
523   BRepBuilderAPI_MakeFace aMKFace(gp_Pln(theOrigin->impl<gp_Pnt>(),
524                                           theDirection->impl<gp_Dir>()));
525   TopoDS_Face aFace = aMKFace.Face();
526
527   BRepAlgo_FaceRestrictor aFRestrictor;
528   aFRestrictor.Init(aFace, Standard_False, Standard_True);
529   for(ListOfShape::const_iterator anIt = theWires.cbegin();
530       anIt != theWires.cend();
531       ++anIt) {
532     TopoDS_Wire aWire = TopoDS::Wire((*anIt)->impl<TopoDS_Shape>());
533     aFRestrictor.Add(aWire);
534   }
535
536   aFRestrictor.Perform();
537
538   if(!aFRestrictor.IsDone()) {
539     return;
540   }
541
542   for(; aFRestrictor.More(); aFRestrictor.Next()) {
543     GeomShapePtr aShape(new GeomAPI_Shape());
544     aShape->setImpl(new TopoDS_Shape(aFRestrictor.Current()));
545     theFaces.push_back(aShape);
546   }
547 }
548
549 //==================================================================================================
550 std::shared_ptr<GeomAPI_Pln> GeomAlgoAPI_ShapeTools::findPlane(const ListOfShape& theShapes)
551 {
552   TopoDS_Compound aCompound;
553   BRep_Builder aBuilder;
554   aBuilder.MakeCompound(aCompound);
555
556   for(ListOfShape::const_iterator anIt = theShapes.cbegin(); anIt != theShapes.cend(); ++anIt) {
557     aBuilder.Add(aCompound, (*anIt)->impl<TopoDS_Shape>());
558   }
559   BRepBuilderAPI_FindPlane aFindPlane(aCompound);
560
561   if(aFindPlane.Found() != Standard_True) {
562     return std::shared_ptr<GeomAPI_Pln>();
563   }
564
565   Handle(Geom_Plane) aPlane = aFindPlane.Plane();
566   gp_Pnt aLoc = aPlane->Location();
567   gp_Dir aDir = aPlane->Axis().Direction();
568
569   std::shared_ptr<GeomAPI_Pnt> aGeomPnt(new GeomAPI_Pnt(aLoc.X(), aLoc.Y(), aLoc.Z()));
570   std::shared_ptr<GeomAPI_Dir> aGeomDir(new GeomAPI_Dir(aDir.X(), aDir.Y(), aDir.Z()));
571
572   std::shared_ptr<GeomAPI_Pln> aPln(new GeomAPI_Pln(aGeomPnt, aGeomDir));
573
574   return aPln;
575 }
576
577 //==================================================================================================
578 bool GeomAlgoAPI_ShapeTools::isSubShapeInsideShape(
579   const std::shared_ptr<GeomAPI_Shape> theSubShape,
580   const std::shared_ptr<GeomAPI_Shape> theBaseShape)
581 {
582   if(!theSubShape.get() || !theBaseShape.get()) {
583     return false;
584   }
585
586   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
587   const TopoDS_Shape& aBaseShape = theBaseShape->impl<TopoDS_Shape>();
588
589   if(aSubShape.ShapeType() == TopAbs_VERTEX) {
590     // If sub-shape is a vertex check distance to shape. If it is <= Precision::Confusion() then OK.
591     BRepExtrema_DistShapeShape aDist(aBaseShape, aSubShape);
592     aDist.Perform();
593     if(!aDist.IsDone() || aDist.Value() > Precision::Confusion()) {
594       return false;
595     }
596   } else if (aSubShape.ShapeType() == TopAbs_EDGE) {
597     if(aBaseShape.ShapeType() == TopAbs_FACE) {
598       // Check that edge is on face surface.
599       TopoDS_Face aFace = TopoDS::Face(aBaseShape);
600       TopoDS_Edge anEdge = TopoDS::Edge(aSubShape);
601       BRepLib_CheckCurveOnSurface aCheck(anEdge, aFace);
602       aCheck.Perform();
603       if(!aCheck.IsDone() || aCheck.MaxDistance() > Precision::Confusion()) {
604         return false;
605       }
606
607       // Check intersections.
608       TopoDS_Vertex aV1, aV2;
609       ShapeAnalysis::FindBounds(anEdge, aV1, aV2);
610       gp_Pnt aPnt1 = BRep_Tool::Pnt(aV1);
611       gp_Pnt aPnt2 = BRep_Tool::Pnt(aV2);
612       for(TopExp_Explorer anExp(aBaseShape, TopAbs_EDGE); anExp.More(); anExp.Next()) {
613         const TopoDS_Shape& anEdgeOnFace = anExp.Current();
614         BRepExtrema_DistShapeShape aDist(anEdgeOnFace, anEdge);
615         aDist.Perform();
616         if(aDist.IsDone() && aDist.Value() <= Precision::Confusion()) {
617           // Edge intersect face bound. Check that it is not on edge begin or end.
618           for(Standard_Integer anIndex = 1; anIndex <= aDist.NbSolution(); ++anIndex) {
619             gp_Pnt aPntOnSubShape = aDist.PointOnShape2(anIndex);
620             if(aPntOnSubShape.Distance(aPnt1) > Precision::Confusion()
621                 && aPntOnSubShape.Distance(aPnt2) > Precision::Confusion()) {
622               return false;
623             }
624           }
625         }
626       }
627
628       // No intersections found. Edge is inside or outside face. Check it.
629       BRepAdaptor_Curve aCurveAdaptor(anEdge);
630       gp_Pnt aPointToCheck =
631         aCurveAdaptor.Value((aCurveAdaptor.FirstParameter() +
632                               aCurveAdaptor.LastParameter()) / 2.0);
633       Handle(Geom_Surface) aSurface = BRep_Tool::Surface(aFace);
634       ShapeAnalysis_Surface aSAS(aSurface);
635       gp_Pnt2d aPointOnFace = aSAS.ValueOfUV(aPointToCheck, Precision::Confusion());
636       BRepTopAdaptor_FClass2d aFClass2d(aFace, Precision::Confusion());
637       if(aFClass2d.Perform(aPointOnFace) == TopAbs_OUT) {
638         return false;
639       }
640
641     } else {
642       return false;
643     }
644   } else {
645     return false;
646   }
647
648   return true;
649 }
650
651 //==================================================================================================
652 bool GeomAlgoAPI_ShapeTools::isShapesIntersects(
653   const std::shared_ptr<GeomAPI_Shape> theShape1,
654   const std::shared_ptr<GeomAPI_Shape> theShape2)
655 {
656   if(!theShape1.get() || !theShape2.get()) {
657     return false;
658   }
659
660   const TopoDS_Shape& aShape1 = theShape1->impl<TopoDS_Shape>();
661   const TopoDS_Shape& aShape2 = theShape2->impl<TopoDS_Shape>();
662
663   BRepExtrema_DistShapeShape aDist(aShape1, aShape2);
664   aDist.Perform();
665   if(aDist.IsDone() && aDist.Value() < Precision::Confusion()) {
666     return true;
667   }
668
669   return false;
670 }
671
672 //==================================================================================================
673 bool GeomAlgoAPI_ShapeTools::isShapeValid(const std::shared_ptr<GeomAPI_Shape> theShape)
674 {
675   if(!theShape.get()) {
676     return false;
677   }
678
679   BRepCheck_Analyzer aChecker(theShape->impl<TopoDS_Shape>());
680   return (aChecker.IsValid() == Standard_True);
681 }
682
683 //==================================================================================================
684 std::shared_ptr<GeomAPI_Shape>
685   GeomAlgoAPI_ShapeTools::getFaceOuterWire(const std::shared_ptr<GeomAPI_Shape> theFace)
686 {
687   GeomShapePtr anOuterWire;
688
689   if(!theFace.get() || !theFace->isFace()) {
690     return anOuterWire;
691   }
692
693   TopoDS_Face aFace = TopoDS::Face(theFace->impl<TopoDS_Shape>());
694   TopoDS_Wire aWire = BRepTools::OuterWire(aFace);
695
696   anOuterWire.reset(new GeomAPI_Shape());
697   anOuterWire->setImpl(new TopoDS_Shape(aWire));
698
699   return anOuterWire;
700 }
701
702 //==================================================================================================
703 bool GeomAlgoAPI_ShapeTools::isParallel(const std::shared_ptr<GeomAPI_Edge> theEdge,
704                                         const std::shared_ptr<GeomAPI_Face> theFace)
705 {
706   if(!theEdge.get() || !theFace.get()) {
707     return false;
708   }
709
710   TopoDS_Edge anEdge = TopoDS::Edge(theEdge->impl<TopoDS_Shape>());
711   TopoDS_Face aFace  = TopoDS::Face(theFace->impl<TopoDS_Shape>());
712
713   BRepExtrema_ExtCF anExt(anEdge, aFace);
714   return anExt.IsParallel() == Standard_True;
715 }
716
717 //==================================================================================================
718 void GeomAlgoAPI_ShapeTools::splitShape(const std::shared_ptr<GeomAPI_Shape>& theBaseShape,
719                                       const GeomAlgoAPI_ShapeTools::PointToRefsMap& thePointsInfo,
720                                       std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
721 {
722   // General Fuse to split edge by vertices
723   BOPAlgo_Builder aBOP;
724   TopoDS_Edge aBaseEdge = theBaseShape->impl<TopoDS_Edge>();
725   // Rebuild closed edge to place vertex to one of split points.
726   // This will prevent edge to be split on same vertex.
727   if (BRep_Tool::IsClosed(aBaseEdge))
728   {
729     Standard_Real aFirst, aLast;
730     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aBaseEdge, aFirst, aLast);
731
732     PointToRefsMap::const_iterator aPIt = thePointsInfo.begin();
733     std::shared_ptr<GeomAPI_Pnt> aPnt = aPIt->first;
734     gp_Pnt aPoint(aPnt->x(), aPnt->y(), aPnt->z());
735
736     TopAbs_Orientation anOrientation = aBaseEdge.Orientation();
737     aBaseEdge = BRepBuilderAPI_MakeEdge(aCurve, aPoint, aPoint).Edge();
738     aBaseEdge.Orientation(anOrientation);
739   }
740   aBOP.AddArgument(aBaseEdge);
741
742   PointToRefsMap::const_iterator aPIt = thePointsInfo.begin();
743   for (; aPIt != thePointsInfo.end(); ++aPIt) {
744     std::shared_ptr<GeomAPI_Pnt> aPnt = aPIt->first;
745     TopoDS_Vertex aV = BRepBuilderAPI_MakeVertex(gp_Pnt(aPnt->x(), aPnt->y(), aPnt->z()));
746     aBOP.AddArgument(aV);
747   }
748
749   aBOP.Perform();
750   if (aBOP.ErrorStatus())
751     return;
752
753   // Collect splits
754   const TopTools_ListOfShape& aSplits = aBOP.Modified(aBaseEdge);
755   TopTools_ListIteratorOfListOfShape anIt(aSplits);
756   for (; anIt.More(); anIt.Next()) {
757     std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
758     anEdge->setImpl(new TopoDS_Shape(anIt.Value()));
759     theShapes.insert(anEdge);
760   }
761 }
762
763 //==================================================================================================
764 void GeomAlgoAPI_ShapeTools::splitShape_p(const std::shared_ptr<GeomAPI_Shape>& theBaseShape,
765                                           const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
766                                           std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
767 {
768   // General Fuse to split edge by vertices
769   BOPAlgo_Builder aBOP;
770   TopoDS_Edge aBaseEdge = theBaseShape->impl<TopoDS_Edge>();
771   // Rebuild closed edge to place vertex to one of split points.
772   // This will prevent edge to be split on seam vertex.
773   if (BRep_Tool::IsClosed(aBaseEdge))
774   {
775     Standard_Real aFirst, aLast;
776     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aBaseEdge, aFirst, aLast);
777
778     std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPIt = thePoints.begin();
779     gp_Pnt aPoint((*aPIt)->x(), (*aPIt)->y(), (*aPIt)->z());
780
781     TopAbs_Orientation anOrientation = aBaseEdge.Orientation();
782     aBaseEdge = BRepBuilderAPI_MakeEdge(aCurve, aPoint, aPoint).Edge();
783     aBaseEdge.Orientation(anOrientation);
784   }
785   aBOP.AddArgument(aBaseEdge);
786
787   std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPtIt = thePoints.begin();
788   for (; aPtIt != thePoints.end(); ++aPtIt) {
789     std::shared_ptr<GeomAPI_Pnt> aPnt = *aPtIt;
790     TopoDS_Vertex aV = BRepBuilderAPI_MakeVertex(gp_Pnt(aPnt->x(), aPnt->y(), aPnt->z()));
791     aBOP.AddArgument(aV);
792   }
793
794   aBOP.Perform();
795   if (aBOP.ErrorStatus())
796     return;
797
798   // Collect splits
799   const TopTools_ListOfShape& aSplits = aBOP.Modified(aBaseEdge);
800   TopTools_ListIteratorOfListOfShape anIt(aSplits);
801   for (; anIt.More(); anIt.Next()) {
802     std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
803     anEdge->setImpl(new TopoDS_Shape(anIt.Value()));
804     theShapes.insert(anEdge);
805   }
806 }
807
808 //==================================================================================================
809 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::findShape(
810                                   const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
811                                   const std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
812 {
813   std::shared_ptr<GeomAPI_Shape> aResultShape;
814
815   if (thePoints.size() == 2) {
816     std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPntIt = thePoints.begin();
817     std::shared_ptr<GeomAPI_Pnt> aFirstPoint = *aPntIt;
818     aPntIt++;
819     std::shared_ptr<GeomAPI_Pnt> aLastPoint = *aPntIt;
820
821     std::set<std::shared_ptr<GeomAPI_Shape> >::const_iterator anIt = theShapes.begin(),
822                                                               aLast = theShapes.end();
823     for (; anIt != aLast; anIt++) {
824       GeomShapePtr aShape = *anIt;
825       std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge(aShape));
826       if (anEdge.get()) {
827         std::shared_ptr<GeomAPI_Pnt> anEdgeFirstPoint = anEdge->firstPoint();
828         std::shared_ptr<GeomAPI_Pnt> anEdgeLastPoint = anEdge->lastPoint();
829         if (anEdgeFirstPoint->isEqual(aFirstPoint) &&
830             anEdgeLastPoint->isEqual(aLastPoint))
831             aResultShape = aShape;
832       }
833     }
834   }
835
836   return aResultShape;
837 }