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