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