Salome HOME
Issue #1834: Fix length of lines
[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 <Handle_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;
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& aGroupShape = aGroupIt.Value();
315       for(NCollection_List<TopoDS_Shape>::Iterator anUngroupedIt(anUngroupedShapes); 
316           anUngroupedIt.More(); anUngroupedIt.Next()) {
317         const TopoDS_Shape& anUngroupedShape = anUngroupedIt.Value();
318         bool isFound = false;
319         for(TopExp_Explorer aGroupShapeExp(aGroupShape, TopAbs_VERTEX); 
320             aGroupShapeExp.More(); aGroupShapeExp.Next()) {
321           const TopoDS_Shape& aVertex1 = aGroupShapeExp.Current();
322           for(TopExp_Explorer anUngroupedShapeExp(anUngroupedShape, TopAbs_VERTEX); 
323               anUngroupedShapeExp.More(); anUngroupedShapeExp.Next()) {
324             const TopoDS_Shape& aVertex2 = anUngroupedShapeExp.Current();
325             if(aVertex1.IsSame(aVertex2)) {
326               aGroupedShapes.Append(anUngroupedShape);
327               anUngroupedShapes.Remove(anUngroupedIt);
328               isFound = true;
329               break;
330             }
331           }
332           if(isFound) {
333             break;
334           }
335         }
336         if(!anUngroupedIt.More()) {
337           break;
338         }
339       }
340     }
341     aGroups.Append(aGroupedShapes);
342   }
343
344   TopoDS_Compound aCompound;
345   BRep_Builder aBuilder;
346   aBuilder.MakeCompound(aCompound);
347   ListOfShape aCompSolids, aFreeSolids;
348   for(NCollection_Vector<NCollection_List<TopoDS_Shape>>::Iterator 
349       anIt(aGroups); anIt.More(); anIt.Next()) {
350     NCollection_List<TopoDS_Shape> aGroup = anIt.Value();
351     GeomShapePtr aGeomShape(new GeomAPI_Shape());
352     if(aGroup.Size() == 1) {
353       aGeomShape->setImpl(new TopoDS_Shape(aGroup.First()));
354     } else {
355       aGeomShape->setImpl(new TopoDS_Shape(makeCompound(aGroup)));
356       aGeomShape = GeomAlgoAPI_ShapeTools::combineShapes(aGeomShape,
357                                                          GeomAPI_Shape::COMPSOLID,
358                                                          aCompSolids,
359                                                          aFreeSolids);
360     }
361     aBuilder.Add(aCompound, aGeomShape->impl<TopoDS_Shape>());
362   }
363
364   if(!aCompound.IsNull()) {
365     aResult->setImpl(new TopoDS_Shape(aCompound));
366   }
367
368   return aResult;
369 }
370
371 //==================================================================================================
372 std::list<std::shared_ptr<GeomAPI_Pnt> >
373   GeomAlgoAPI_ShapeTools::getBoundingBox(const ListOfShape& theShapes, const double theEnlarge)
374 {
375   // Bounding box of all objects.
376   Bnd_Box aBndBox;
377
378   // Getting box.
379   for (ListOfShape::const_iterator 
380     anObjectsIt = theShapes.begin(); anObjectsIt != theShapes.end(); anObjectsIt++) {
381     const TopoDS_Shape& aShape = (*anObjectsIt)->impl<TopoDS_Shape>();
382     BRepBndLib::Add(aShape, aBndBox);
383   }
384
385   if(theEnlarge != 0.0) {
386     // We enlarge bounding box just to be sure that plane will be large enough to cut all objects.
387     aBndBox.Enlarge(theEnlarge);
388   }
389
390   Standard_Real aXArr[2] = {aBndBox.CornerMin().X(), aBndBox.CornerMax().X()};
391   Standard_Real aYArr[2] = {aBndBox.CornerMin().Y(), aBndBox.CornerMax().Y()};
392   Standard_Real aZArr[2] = {aBndBox.CornerMin().Z(), aBndBox.CornerMax().Z()};
393   std::list<std::shared_ptr<GeomAPI_Pnt> > aResultPoints;
394   int aNum = 0;
395   for(int i = 0; i < 2; i++) {
396     for(int j = 0; j < 2; j++) {
397       for(int k = 0; k < 2; k++) {
398         std::shared_ptr<GeomAPI_Pnt> aPnt(new GeomAPI_Pnt(aXArr[i], aYArr[j], aZArr[k]));
399         aResultPoints.push_back(aPnt);
400       }
401     }
402   }
403
404   return aResultPoints;
405 }
406
407 //==================================================================================================
408 std::shared_ptr<GeomAPI_Shape> 
409   GeomAlgoAPI_ShapeTools::faceToInfinitePlane(const std::shared_ptr<GeomAPI_Shape> theFace)
410 {
411   if (!theFace.get())
412     return std::shared_ptr<GeomAPI_Shape>();
413
414   TopoDS_Face aPlaneFace = TopoDS::Face(theFace->impl<TopoDS_Shape>());
415   if (aPlaneFace.IsNull())
416     return std::shared_ptr<GeomAPI_Shape>();
417
418   Handle(Geom_Plane) aPlane = Handle(Geom_Plane)::DownCast(BRep_Tool::Surface(aPlaneFace));
419   if (aPlane.IsNull())
420     return std::shared_ptr<GeomAPI_Shape>();
421
422   // make an infinity face on the plane
423   TopoDS_Shape anInfiniteFace = BRepBuilderAPI_MakeFace(aPlane->Pln()).Shape();
424
425   std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
426   aResult->setImpl(new TopoDS_Shape(anInfiniteFace));
427   return aResult;
428 }
429
430 //==================================================================================================
431 std::shared_ptr<GeomAPI_Face> GeomAlgoAPI_ShapeTools::fitPlaneToBox(
432   const std::shared_ptr<GeomAPI_Shape> thePlane,
433   const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints)
434 {
435   std::shared_ptr<GeomAPI_Face> aResultFace;
436
437   if(!thePlane.get()) {
438     return aResultFace;
439   }
440
441   const TopoDS_Shape& aShape = thePlane->impl<TopoDS_Shape>();
442   if(aShape.ShapeType() != TopAbs_FACE) {
443     return aResultFace;
444   }
445
446   TopoDS_Face aFace = TopoDS::Face(aShape);
447   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace);
448   if(aSurf.IsNull()) {
449     return aResultFace;
450   }
451
452   GeomLib_IsPlanarSurface isPlanar(aSurf);
453   if(!isPlanar.IsPlanar()) {
454     return aResultFace;
455   }
456
457   if(thePoints.size() != 8) {
458     return aResultFace;
459   }
460
461   const gp_Pln& aFacePln = isPlanar.Plan();
462   Handle(Geom_Plane) aFacePlane = new Geom_Plane(aFacePln);
463   IntAna_Quadric aQuadric(aFacePln);
464   Standard_Real UMin, UMax, VMin, VMax;
465   UMin = UMax = VMin = VMax = 0;
466   for (std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator 
467        aPointsIt = thePoints.begin(); aPointsIt != thePoints.end(); aPointsIt++) {
468     const gp_Pnt& aPnt = (*aPointsIt)->impl<gp_Pnt>();
469     gp_Lin aLin(aPnt, aFacePln.Axis().Direction());
470     IntAna_IntConicQuad anIntAna(aLin, aQuadric);
471     const gp_Pnt& aPntOnFace = anIntAna.Point(1);
472     Standard_Real aPntU(0), aPntV(0);
473     GeomLib_Tool::Parameters(aFacePlane, aPntOnFace, Precision::Confusion(), aPntU, aPntV);
474     if(aPntU < UMin) UMin = aPntU;
475     if(aPntU > UMax) UMax = aPntU;
476     if(aPntV < VMin) VMin = aPntV;
477     if(aPntV > VMax) VMax = aPntV;
478   }
479   aResultFace.reset(new GeomAPI_Face());
480   aResultFace->setImpl(new TopoDS_Face(BRepLib_MakeFace(aFacePln, UMin, UMax, VMin, VMax).Face()));
481
482   return aResultFace;
483 }
484
485 //==================================================================================================
486 void GeomAlgoAPI_ShapeTools::findBounds(const std::shared_ptr<GeomAPI_Shape> theShape,
487                                         std::shared_ptr<GeomAPI_Vertex>& theV1,
488                                         std::shared_ptr<GeomAPI_Vertex>& theV2)
489 {
490   if(!theShape.get()) {
491     std::shared_ptr<GeomAPI_Vertex> aVertex(new GeomAPI_Vertex);
492     aVertex->setImpl(new TopoDS_Vertex());
493     theV1 = aVertex;
494     theV2 = aVertex;
495     return;
496   }
497
498   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
499   TopoDS_Vertex aV1, aV2;
500   ShapeAnalysis::FindBounds(aShape, aV1, aV2);
501
502   std::shared_ptr<GeomAPI_Vertex> aGeomV1(new GeomAPI_Vertex()), aGeomV2(new GeomAPI_Vertex());
503   aGeomV1->setImpl(new TopoDS_Vertex(aV1));
504   aGeomV2->setImpl(new TopoDS_Vertex(aV2));
505   theV1 = aGeomV1;
506   theV2 = aGeomV2;
507 }
508
509 //==================================================================================================
510 void GeomAlgoAPI_ShapeTools::makeFacesWithHoles(const std::shared_ptr<GeomAPI_Pnt> theOrigin,
511                                                 const std::shared_ptr<GeomAPI_Dir> theDirection,
512                                                 const ListOfShape& theWires,
513                                                 ListOfShape& theFaces)
514 {
515   BRepBuilderAPI_MakeFace aMKFace(gp_Pln(theOrigin->impl<gp_Pnt>(),
516                                           theDirection->impl<gp_Dir>()));
517   TopoDS_Face aFace = aMKFace.Face();
518
519   BRepAlgo_FaceRestrictor aFRestrictor;
520   aFRestrictor.Init(aFace, Standard_False, Standard_True);
521   for(ListOfShape::const_iterator anIt = theWires.cbegin();
522       anIt != theWires.cend();
523       ++anIt) {
524     TopoDS_Wire aWire = TopoDS::Wire((*anIt)->impl<TopoDS_Shape>());
525     aFRestrictor.Add(aWire);
526   }
527
528   aFRestrictor.Perform();
529
530   if(!aFRestrictor.IsDone()) {
531     return;
532   }
533
534   for(; aFRestrictor.More(); aFRestrictor.Next()) {
535     GeomShapePtr aShape(new GeomAPI_Shape());
536     aShape->setImpl(new TopoDS_Shape(aFRestrictor.Current()));
537     theFaces.push_back(aShape);
538   }
539 }
540
541 //==================================================================================================
542 std::shared_ptr<GeomAPI_Pln> GeomAlgoAPI_ShapeTools::findPlane(const ListOfShape& theShapes)
543 {
544   TopoDS_Compound aCompound;
545   BRep_Builder aBuilder;
546   aBuilder.MakeCompound(aCompound);
547
548   for(ListOfShape::const_iterator anIt = theShapes.cbegin(); anIt != theShapes.cend(); ++anIt) {
549     aBuilder.Add(aCompound, (*anIt)->impl<TopoDS_Shape>());
550   }
551   BRepBuilderAPI_FindPlane aFindPlane(aCompound);
552
553   if(aFindPlane.Found() != Standard_True) {
554     return std::shared_ptr<GeomAPI_Pln>();
555   }
556
557   Handle(Geom_Plane) aPlane = aFindPlane.Plane();
558   gp_Pnt aLoc = aPlane->Location();
559   gp_Dir aDir = aPlane->Axis().Direction();
560
561   std::shared_ptr<GeomAPI_Pnt> aGeomPnt(new GeomAPI_Pnt(aLoc.X(), aLoc.Y(), aLoc.Z()));
562   std::shared_ptr<GeomAPI_Dir> aGeomDir(new GeomAPI_Dir(aDir.X(), aDir.Y(), aDir.Z()));
563
564   std::shared_ptr<GeomAPI_Pln> aPln(new GeomAPI_Pln(aGeomPnt, aGeomDir));
565
566   return aPln;
567 }
568
569 //==================================================================================================
570 bool GeomAlgoAPI_ShapeTools::isSubShapeInsideShape(
571   const std::shared_ptr<GeomAPI_Shape> theSubShape,
572   const std::shared_ptr<GeomAPI_Shape> theBaseShape)
573 {
574   if(!theSubShape.get() || !theBaseShape.get()) {
575     return false;
576   }
577
578   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
579   const TopoDS_Shape& aBaseShape = theBaseShape->impl<TopoDS_Shape>();
580
581   if(aSubShape.ShapeType() == TopAbs_VERTEX) {
582     // If sub-shape is a vertex check distance to shape. If it is <= Precision::Confusion() then OK.
583     BRepExtrema_DistShapeShape aDist(aBaseShape, aSubShape);
584     aDist.Perform();
585     if(!aDist.IsDone() || aDist.Value() > Precision::Confusion()) {
586       return false;
587     }
588   } else if (aSubShape.ShapeType() == TopAbs_EDGE) {
589     if(aBaseShape.ShapeType() == TopAbs_FACE) {
590       // Check that edge is on face surface.
591       TopoDS_Face aFace = TopoDS::Face(aBaseShape);
592       TopoDS_Edge anEdge = TopoDS::Edge(aSubShape);
593       BRepLib_CheckCurveOnSurface aCheck(anEdge, aFace);
594       aCheck.Perform();
595       if(!aCheck.IsDone() || aCheck.MaxDistance() > Precision::Confusion()) {
596         return false;
597       }
598
599       // Check intersections.
600       TopoDS_Vertex aV1, aV2;
601       ShapeAnalysis::FindBounds(anEdge, aV1, aV2);
602       gp_Pnt aPnt1 = BRep_Tool::Pnt(aV1);
603       gp_Pnt aPnt2 = BRep_Tool::Pnt(aV2);
604       for(TopExp_Explorer anExp(aBaseShape, TopAbs_EDGE); anExp.More(); anExp.Next()) {
605         const TopoDS_Shape& anEdgeOnFace = anExp.Current();
606         BRepExtrema_DistShapeShape aDist(anEdgeOnFace, anEdge);
607         aDist.Perform();
608         if(aDist.IsDone() && aDist.Value() <= Precision::Confusion()) {
609           // Edge intersect face bound. Check that it is not on edge begin or end.
610           for(Standard_Integer anIndex = 1; anIndex <= aDist.NbSolution(); ++anIndex) {
611             gp_Pnt aPntOnSubShape = aDist.PointOnShape2(anIndex);
612             if(aPntOnSubShape.Distance(aPnt1) > Precision::Confusion()
613                 && aPntOnSubShape.Distance(aPnt2) > Precision::Confusion()) {
614               return false;
615             }
616           }
617         }
618       }
619
620       // No intersections found. Edge is inside or outside face. Check it.
621       BRepAdaptor_Curve aCurveAdaptor(anEdge);
622       gp_Pnt aPointToCheck =
623         aCurveAdaptor.Value((aCurveAdaptor.FirstParameter() + 
624                               aCurveAdaptor.LastParameter()) / 2.0);
625       Handle(Geom_Surface) aSurface = BRep_Tool::Surface(aFace);
626       ShapeAnalysis_Surface aSAS(aSurface);
627       gp_Pnt2d aPointOnFace = aSAS.ValueOfUV(aPointToCheck, Precision::Confusion());
628       BRepTopAdaptor_FClass2d aFClass2d(aFace, Precision::Confusion());
629       if(aFClass2d.Perform(aPointOnFace) == TopAbs_OUT) {
630         return false;
631       }
632
633     } else {
634       return false;
635     }
636   } else {
637     return false;
638   }
639
640   return true;
641 }
642
643 //==================================================================================================
644 bool GeomAlgoAPI_ShapeTools::isShapeValid(const std::shared_ptr<GeomAPI_Shape> theShape)
645 {
646   if(!theShape.get()) {
647     return false;
648   }
649
650   BRepCheck_Analyzer aChecker(theShape->impl<TopoDS_Shape>());
651   return (aChecker.IsValid() == Standard_True);
652 }
653
654 //==================================================================================================
655 std::shared_ptr<GeomAPI_Shape> 
656   GeomAlgoAPI_ShapeTools::getFaceOuterWire(const std::shared_ptr<GeomAPI_Shape> theFace)
657 {
658   GeomShapePtr anOuterWire;
659
660   if(!theFace.get() || !theFace->isFace()) {
661     return anOuterWire;
662   }
663
664   TopoDS_Face aFace = TopoDS::Face(theFace->impl<TopoDS_Shape>());
665   TopoDS_Wire aWire = BRepTools::OuterWire(aFace);
666
667   anOuterWire.reset(new GeomAPI_Shape());
668   anOuterWire->setImpl(new TopoDS_Shape(aWire));
669
670   return anOuterWire;
671 }
672
673 //==================================================================================================
674 bool GeomAlgoAPI_ShapeTools::isParallel(const std::shared_ptr<GeomAPI_Edge> theEdge,
675                                         const std::shared_ptr<GeomAPI_Face> theFace)
676 {
677   if(!theEdge.get() || !theFace.get()) {
678     return false;
679   }
680
681   TopoDS_Edge anEdge = TopoDS::Edge(theEdge->impl<TopoDS_Shape>());
682   TopoDS_Face aFace  = TopoDS::Face(theFace->impl<TopoDS_Shape>());
683
684   BRepExtrema_ExtCF anExt(anEdge, aFace);
685   return anExt.IsParallel() == Standard_True;
686 }
687
688 //==================================================================================================
689 void GeomAlgoAPI_ShapeTools::splitShape(const std::shared_ptr<GeomAPI_Shape>& theBaseShape,
690                                           const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
691                                           std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
692 {
693   // General Fuse to split edge by vertices
694   BOPAlgo_Builder aBOP;
695   TopoDS_Edge aBaseEdge = theBaseShape->impl<TopoDS_Edge>();
696   // Rebuild closed edge to place vertex to one of split points.
697   // This will prevent edge to be split on seam vertex.
698   if (BRep_Tool::IsClosed(aBaseEdge))
699   {
700     Standard_Real aFirst, aLast;
701     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aBaseEdge, aFirst, aLast);
702
703     std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPIt = thePoints.begin();
704     gp_Pnt aPoint((*aPIt)->x(), (*aPIt)->y(), (*aPIt)->z());
705
706     TopAbs_Orientation anOrientation = aBaseEdge.Orientation();
707     aBaseEdge = BRepBuilderAPI_MakeEdge(aCurve, aPoint, aPoint).Edge();
708     aBaseEdge.Orientation(anOrientation);
709   }
710   aBOP.AddArgument(aBaseEdge);
711
712   std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPtIt = thePoints.begin();
713   for (; aPtIt != thePoints.end(); ++aPtIt) {
714     std::shared_ptr<GeomAPI_Pnt> aPnt = *aPtIt;
715     TopoDS_Vertex aV = BRepBuilderAPI_MakeVertex(gp_Pnt(aPnt->x(), aPnt->y(), aPnt->z()));
716     aBOP.AddArgument(aV);
717   }
718
719   aBOP.Perform();
720   if (aBOP.ErrorStatus())
721     return;
722   
723   // Collect splits
724   const TopTools_ListOfShape& aSplits = aBOP.Modified(aBaseEdge);
725   TopTools_ListIteratorOfListOfShape anIt(aSplits);
726   for (; anIt.More(); anIt.Next()) {
727     std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
728     anEdge->setImpl(new TopoDS_Shape(anIt.Value()));
729     theShapes.insert(anEdge);
730   }
731 }
732
733 //==================================================================================================
734 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::findShape(
735                                   const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
736                                   const std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
737 {
738   std::shared_ptr<GeomAPI_Shape> aResultShape;
739
740   if (thePoints.size() == 2) {
741     std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPntIt = thePoints.begin();
742     std::shared_ptr<GeomAPI_Pnt> aFirstPoint = *aPntIt;
743     aPntIt++;
744     std::shared_ptr<GeomAPI_Pnt> aLastPoint = *aPntIt;
745
746     std::set<std::shared_ptr<GeomAPI_Shape> >::const_iterator anIt = theShapes.begin(),
747                                                               aLast = theShapes.end();
748     for (; anIt != aLast; anIt++) {
749       GeomShapePtr aShape = *anIt;
750       std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge(aShape));
751       if (anEdge.get()) {
752         std::shared_ptr<GeomAPI_Pnt> anEdgeFirstPoint = anEdge->firstPoint();
753         std::shared_ptr<GeomAPI_Pnt> anEdgeLastPoint = anEdge->lastPoint();
754         if (anEdgeFirstPoint->isEqual(aFirstPoint) &&
755             anEdgeLastPoint->isEqual(aLastPoint))
756             aResultShape = aShape;
757       }
758     }
759   }
760
761   return aResultShape;
762 }