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