Salome HOME
Merge branch 'master' into cgt/devCEA
[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 <Geom2d_Curve.hxx>
48 #include <Geom2d_Curve.hxx>
49 #include <BRepLib_CheckCurveOnSurface.hxx>
50 #include <BRep_Tool.hxx>
51 #include <Geom_Line.hxx>
52 #include <Geom_Plane.hxx>
53 #include <GeomAPI_ProjectPointOnCurve.hxx>
54 #include <GeomLib_IsPlanarSurface.hxx>
55 #include <GeomLib_Tool.hxx>
56 #include <gp_Pln.hxx>
57 #include <GProp_GProps.hxx>
58 #include <IntAna_IntConicQuad.hxx>
59 #include <IntAna_Quadric.hxx>
60 #include <NCollection_Vector.hxx>
61 #include <ShapeAnalysis.hxx>
62 #include <ShapeAnalysis_Surface.hxx>
63 #include <TopoDS_Builder.hxx>
64 #include <TopoDS_Edge.hxx>
65 #include <TopoDS_Face.hxx>
66 #include <TopoDS_Shape.hxx>
67 #include <TopoDS_Shell.hxx>
68 #include <TopoDS_Vertex.hxx>
69 #include <TopoDS.hxx>
70 #include <TopExp_Explorer.hxx>
71 #include <TopTools_ListIteratorOfListOfShape.hxx>
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   // Iterate over all shapes and find shapes with shared vertices.
325   TopTools_ListOfShape aMapOrder;
326   BOPCol_DataMapOfShapeListOfShape aVertexShapesMap;
327   for(NCollection_List<TopoDS_Shape>::Iterator aShapesIt(anUngroupedShapes);
328       aShapesIt.More();
329       aShapesIt.Next()) {
330     const TopoDS_Shape& aShape = aShapesIt.Value();
331     for(TopExp_Explorer aShapeExp(aShape, TopAbs_VERTEX);
332         aShapeExp.More();
333         aShapeExp.Next()) {
334       const TopoDS_Shape& aVertex = aShapeExp.Current();
335       if (!aVertexShapesMap.IsBound(aVertex)) {
336         NCollection_List<TopoDS_Shape> aList;
337         aList.Append(aShape);
338         aMapOrder.Append(aVertex);
339         aVertexShapesMap.Bind(aVertex, aList);
340       } else {
341         if(!aVertexShapesMap.ChangeFind(aVertex).Contains(aShape)) {
342           aVertexShapesMap.ChangeFind(aVertex).Append(aShape);
343         }
344       }
345     }
346   }
347
348   // Iterate over the map and group shapes.
349   NCollection_Vector<TopTools_ListOfShape> aGroups;
350   while (!aMapOrder.IsEmpty()) {
351     // Get first group of shapes in map, and then unbind it.
352     const TopoDS_Shape& aKey = aMapOrder.First();
353     TopTools_ListOfShape aGroupedShapes = aVertexShapesMap.Find(aKey);
354     aVertexShapesMap.UnBind(aKey);
355     aMapOrder.Remove(aKey);
356     // Iterate over shapes in this group and add to it shapes from groups in map.
357     for(TopTools_ListOfShape::Iterator aGroupIt(aGroupedShapes);
358         aGroupIt.More(); aGroupIt.Next()) {
359       const TopoDS_Shape& aGroupedShape = aGroupIt.Value();
360       TopTools_ListOfShape aKeysToUnbind;
361       for(TopTools_ListOfShape::Iterator aKeysIt(aMapOrder);
362           aKeysIt.More();
363           aKeysIt.Next()) {
364         const TopTools_ListOfShape& aGroupInMap = aVertexShapesMap(aKeysIt.Value());
365         if(!aGroupInMap.Contains(aGroupedShape)) {
366           // Group in map does not containt shape from our group, so go to the next group in map.
367           continue;
368         }
369         // Iterate over shape in group in map, and add new shapes into our group.
370         for(TopTools_ListOfShape::Iterator aGroupInMapIt(aGroupInMap);
371             aGroupInMapIt.More();
372             aGroupInMapIt.Next()) {
373           const TopoDS_Shape& aShape = aGroupInMapIt.Value();
374           if (!aGroupedShapes.Contains(aShape)) {
375             aGroupedShapes.Append(aShape);
376           }
377         }
378         // Save key to unbind from this map.
379         aKeysToUnbind.Append(aKeysIt.Value());
380       }
381       // Unbind groups from map that we added to our group.
382       for(TopTools_ListOfShape::Iterator aKeysIt(aKeysToUnbind);
383           aKeysIt.More();
384           aKeysIt.Next()) {
385         aVertexShapesMap.UnBind(aKeysIt.Value());
386         aMapOrder.Remove(aKeysIt.Value());
387       }
388     }
389     // Sort shapes.
390     TopTools_ListOfShape aSortedGroup;
391     for(int aST = TopAbs_COMPOUND; aST <= TopAbs_SHAPE; ++aST) {
392       TopTools_ListOfShape::Iterator anIt(aGroupedShapes);
393       while (anIt.More()) {
394         if(anIt.Value().ShapeType() == aST) {
395           aSortedGroup.Append(anIt.Value());
396           aGroupedShapes.Remove(anIt);
397         } else {
398           anIt.Next();
399         }
400       }
401     }
402     aGroups.Append(aSortedGroup);
403   }
404
405   TopoDS_Compound aCompound;
406   BRep_Builder aBuilder;
407   aBuilder.MakeCompound(aCompound);
408   ListOfShape aCompSolids, aFreeSolids;
409   for(NCollection_Vector<NCollection_List<TopoDS_Shape>>::Iterator
410       anIt(aGroups); anIt.More(); anIt.Next()) {
411     NCollection_List<TopoDS_Shape> aGroup = anIt.Value();
412     GeomShapePtr aGeomShape(new GeomAPI_Shape());
413     if(aGroup.Size() == 1) {
414       aGeomShape->setImpl(new TopoDS_Shape(aGroup.First()));
415     } else {
416       aGeomShape->setImpl(new TopoDS_Shape(makeCompound(aGroup)));
417       aGeomShape = GeomAlgoAPI_ShapeTools::combineShapes(aGeomShape,
418                                                          GeomAPI_Shape::COMPSOLID,
419                                                          aCompSolids,
420                                                          aFreeSolids);
421     }
422     aBuilder.Add(aCompound, aGeomShape->impl<TopoDS_Shape>());
423   }
424
425   if(!aCompound.IsNull()) {
426     aResult->setImpl(new TopoDS_Shape(aCompound));
427   }
428
429   return aResult;
430 }
431
432 //==================================================================================================
433 std::list<std::shared_ptr<GeomAPI_Pnt> >
434   GeomAlgoAPI_ShapeTools::getBoundingBox(const ListOfShape& theShapes, const double theEnlarge)
435 {
436   // Bounding box of all objects.
437   Bnd_Box aBndBox;
438
439   // Getting box.
440   for (ListOfShape::const_iterator
441     anObjectsIt = theShapes.begin(); anObjectsIt != theShapes.end(); anObjectsIt++) {
442     const TopoDS_Shape& aShape = (*anObjectsIt)->impl<TopoDS_Shape>();
443     BRepBndLib::Add(aShape, aBndBox);
444   }
445
446   if(theEnlarge != 0.0) {
447     // We enlarge bounding box just to be sure that plane will be large enough to cut all objects.
448     aBndBox.Enlarge(theEnlarge);
449   }
450
451   Standard_Real aXArr[2] = {aBndBox.CornerMin().X(), aBndBox.CornerMax().X()};
452   Standard_Real aYArr[2] = {aBndBox.CornerMin().Y(), aBndBox.CornerMax().Y()};
453   Standard_Real aZArr[2] = {aBndBox.CornerMin().Z(), aBndBox.CornerMax().Z()};
454   std::list<std::shared_ptr<GeomAPI_Pnt> > aResultPoints;
455   int aNum = 0;
456   for(int i = 0; i < 2; i++) {
457     for(int j = 0; j < 2; j++) {
458       for(int k = 0; k < 2; k++) {
459         std::shared_ptr<GeomAPI_Pnt> aPnt(new GeomAPI_Pnt(aXArr[i], aYArr[j], aZArr[k]));
460         aResultPoints.push_back(aPnt);
461       }
462     }
463   }
464
465   return aResultPoints;
466 }
467
468 //==================================================================================================
469 std::shared_ptr<GeomAPI_Shape>
470   GeomAlgoAPI_ShapeTools::faceToInfinitePlane(const std::shared_ptr<GeomAPI_Shape> theFace)
471 {
472   if (!theFace.get())
473     return std::shared_ptr<GeomAPI_Shape>();
474
475   TopoDS_Face aPlaneFace = TopoDS::Face(theFace->impl<TopoDS_Shape>());
476   if (aPlaneFace.IsNull())
477     return std::shared_ptr<GeomAPI_Shape>();
478
479   Handle(Geom_Plane) aPlane = Handle(Geom_Plane)::DownCast(BRep_Tool::Surface(aPlaneFace));
480   if (aPlane.IsNull())
481     return std::shared_ptr<GeomAPI_Shape>();
482
483   // make an infinity face on the plane
484   TopoDS_Shape anInfiniteFace = BRepBuilderAPI_MakeFace(aPlane->Pln()).Shape();
485
486   std::shared_ptr<GeomAPI_Shape> aResult(new GeomAPI_Shape);
487   aResult->setImpl(new TopoDS_Shape(anInfiniteFace));
488   return aResult;
489 }
490
491 //==================================================================================================
492 std::shared_ptr<GeomAPI_Face> GeomAlgoAPI_ShapeTools::fitPlaneToBox(
493   const std::shared_ptr<GeomAPI_Shape> thePlane,
494   const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints)
495 {
496   std::shared_ptr<GeomAPI_Face> aResultFace;
497
498   if(!thePlane.get()) {
499     return aResultFace;
500   }
501
502   const TopoDS_Shape& aShape = thePlane->impl<TopoDS_Shape>();
503   if(aShape.ShapeType() != TopAbs_FACE) {
504     return aResultFace;
505   }
506
507   TopoDS_Face aFace = TopoDS::Face(aShape);
508   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace);
509   if(aSurf.IsNull()) {
510     return aResultFace;
511   }
512
513   GeomLib_IsPlanarSurface isPlanar(aSurf);
514   if(!isPlanar.IsPlanar()) {
515     return aResultFace;
516   }
517
518   if(thePoints.size() != 8) {
519     return aResultFace;
520   }
521
522   const gp_Pln& aFacePln = isPlanar.Plan();
523   Handle(Geom_Plane) aFacePlane = new Geom_Plane(aFacePln);
524   IntAna_Quadric aQuadric(aFacePln);
525   Standard_Real UMin, UMax, VMin, VMax;
526   UMin = UMax = VMin = VMax = 0;
527   for (std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator
528        aPointsIt = thePoints.begin(); aPointsIt != thePoints.end(); aPointsIt++) {
529     const gp_Pnt& aPnt = (*aPointsIt)->impl<gp_Pnt>();
530     gp_Lin aLin(aPnt, aFacePln.Axis().Direction());
531     IntAna_IntConicQuad anIntAna(aLin, aQuadric);
532     const gp_Pnt& aPntOnFace = anIntAna.Point(1);
533     Standard_Real aPntU(0), aPntV(0);
534     GeomLib_Tool::Parameters(aFacePlane, aPntOnFace, Precision::Confusion(), aPntU, aPntV);
535     if(aPntU < UMin) UMin = aPntU;
536     if(aPntU > UMax) UMax = aPntU;
537     if(aPntV < VMin) VMin = aPntV;
538     if(aPntV > VMax) VMax = aPntV;
539   }
540   aResultFace.reset(new GeomAPI_Face());
541   aResultFace->setImpl(new TopoDS_Face(BRepLib_MakeFace(aFacePln, UMin, UMax, VMin, VMax).Face()));
542
543   return aResultFace;
544 }
545
546 //==================================================================================================
547 void GeomAlgoAPI_ShapeTools::findBounds(const std::shared_ptr<GeomAPI_Shape> theShape,
548                                         std::shared_ptr<GeomAPI_Vertex>& theV1,
549                                         std::shared_ptr<GeomAPI_Vertex>& theV2)
550 {
551   if(!theShape.get()) {
552     std::shared_ptr<GeomAPI_Vertex> aVertex(new GeomAPI_Vertex);
553     aVertex->setImpl(new TopoDS_Vertex());
554     theV1 = aVertex;
555     theV2 = aVertex;
556     return;
557   }
558
559   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
560   TopoDS_Vertex aV1, aV2;
561   ShapeAnalysis::FindBounds(aShape, aV1, aV2);
562
563   std::shared_ptr<GeomAPI_Vertex> aGeomV1(new GeomAPI_Vertex()), aGeomV2(new GeomAPI_Vertex());
564   aGeomV1->setImpl(new TopoDS_Vertex(aV1));
565   aGeomV2->setImpl(new TopoDS_Vertex(aV2));
566   theV1 = aGeomV1;
567   theV2 = aGeomV2;
568 }
569
570 //==================================================================================================
571 void GeomAlgoAPI_ShapeTools::makeFacesWithHoles(const std::shared_ptr<GeomAPI_Pnt> theOrigin,
572                                                 const std::shared_ptr<GeomAPI_Dir> theDirection,
573                                                 const ListOfShape& theWires,
574                                                 ListOfShape& theFaces)
575 {
576   BRepBuilderAPI_MakeFace aMKFace(gp_Pln(theOrigin->impl<gp_Pnt>(),
577                                           theDirection->impl<gp_Dir>()));
578   TopoDS_Face aFace = aMKFace.Face();
579
580   BRepAlgo_FaceRestrictor aFRestrictor;
581   aFRestrictor.Init(aFace, Standard_False, Standard_True);
582   for(ListOfShape::const_iterator anIt = theWires.cbegin();
583       anIt != theWires.cend();
584       ++anIt) {
585     TopoDS_Wire aWire = TopoDS::Wire((*anIt)->impl<TopoDS_Shape>());
586     aFRestrictor.Add(aWire);
587   }
588
589   aFRestrictor.Perform();
590
591   if(!aFRestrictor.IsDone()) {
592     return;
593   }
594
595   for(; aFRestrictor.More(); aFRestrictor.Next()) {
596     GeomShapePtr aShape(new GeomAPI_Shape());
597     aShape->setImpl(new TopoDS_Shape(aFRestrictor.Current()));
598     theFaces.push_back(aShape);
599   }
600 }
601
602 //==================================================================================================
603 std::shared_ptr<GeomAPI_Pln> GeomAlgoAPI_ShapeTools::findPlane(const ListOfShape& theShapes)
604 {
605   TopoDS_Compound aCompound;
606   BRep_Builder aBuilder;
607   aBuilder.MakeCompound(aCompound);
608
609   for(ListOfShape::const_iterator anIt = theShapes.cbegin(); anIt != theShapes.cend(); ++anIt) {
610     aBuilder.Add(aCompound, (*anIt)->impl<TopoDS_Shape>());
611   }
612   BRepBuilderAPI_FindPlane aFindPlane(aCompound);
613
614   if(aFindPlane.Found() != Standard_True) {
615     return std::shared_ptr<GeomAPI_Pln>();
616   }
617
618   Handle(Geom_Plane) aPlane = aFindPlane.Plane();
619   gp_Pnt aLoc = aPlane->Location();
620   gp_Dir aDir = aPlane->Axis().Direction();
621
622   std::shared_ptr<GeomAPI_Pnt> aGeomPnt(new GeomAPI_Pnt(aLoc.X(), aLoc.Y(), aLoc.Z()));
623   std::shared_ptr<GeomAPI_Dir> aGeomDir(new GeomAPI_Dir(aDir.X(), aDir.Y(), aDir.Z()));
624
625   std::shared_ptr<GeomAPI_Pln> aPln(new GeomAPI_Pln(aGeomPnt, aGeomDir));
626
627   return aPln;
628 }
629
630 //==================================================================================================
631 bool GeomAlgoAPI_ShapeTools::isSubShapeInsideShape(
632   const std::shared_ptr<GeomAPI_Shape> theSubShape,
633   const std::shared_ptr<GeomAPI_Shape> theBaseShape)
634 {
635   if(!theSubShape.get() || !theBaseShape.get()) {
636     return false;
637   }
638
639   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
640   const TopoDS_Shape& aBaseShape = theBaseShape->impl<TopoDS_Shape>();
641
642   if(aSubShape.ShapeType() == TopAbs_VERTEX) {
643     // If sub-shape is a vertex check distance to shape. If it is <= Precision::Confusion() then OK.
644     BRepExtrema_DistShapeShape aDist(aBaseShape, aSubShape);
645     aDist.Perform();
646     if(!aDist.IsDone() || aDist.Value() > Precision::Confusion()) {
647       return false;
648     }
649   } else if (aSubShape.ShapeType() == TopAbs_EDGE) {
650     if(aBaseShape.ShapeType() == TopAbs_FACE) {
651       // Check that edge is on face surface.
652       TopoDS_Face aFace = TopoDS::Face(aBaseShape);
653       TopoDS_Edge anEdge = TopoDS::Edge(aSubShape);
654       BRepLib_CheckCurveOnSurface aCheck(anEdge, aFace);
655       aCheck.Perform();
656       if(!aCheck.IsDone() || aCheck.MaxDistance() > Precision::Confusion()) {
657         return false;
658       }
659
660       // Check intersections.
661       TopoDS_Vertex aV1, aV2;
662       ShapeAnalysis::FindBounds(anEdge, aV1, aV2);
663       gp_Pnt aPnt1 = BRep_Tool::Pnt(aV1);
664       gp_Pnt aPnt2 = BRep_Tool::Pnt(aV2);
665       for(TopExp_Explorer anExp(aBaseShape, TopAbs_EDGE); anExp.More(); anExp.Next()) {
666         const TopoDS_Shape& anEdgeOnFace = anExp.Current();
667         BRepExtrema_DistShapeShape aDist(anEdgeOnFace, anEdge);
668         aDist.Perform();
669         if(aDist.IsDone() && aDist.Value() <= Precision::Confusion()) {
670           // Edge intersect face bound. Check that it is not on edge begin or end.
671           for(Standard_Integer anIndex = 1; anIndex <= aDist.NbSolution(); ++anIndex) {
672             gp_Pnt aPntOnSubShape = aDist.PointOnShape2(anIndex);
673             if(aPntOnSubShape.Distance(aPnt1) > Precision::Confusion()
674                 && aPntOnSubShape.Distance(aPnt2) > Precision::Confusion()) {
675               return false;
676             }
677           }
678         }
679       }
680
681       // No intersections found. Edge is inside or outside face. Check it.
682       BRepAdaptor_Curve aCurveAdaptor(anEdge);
683       gp_Pnt aPointToCheck =
684         aCurveAdaptor.Value((aCurveAdaptor.FirstParameter() +
685                               aCurveAdaptor.LastParameter()) / 2.0);
686       Handle(Geom_Surface) aSurface = BRep_Tool::Surface(aFace);
687       ShapeAnalysis_Surface aSAS(aSurface);
688       gp_Pnt2d aPointOnFace = aSAS.ValueOfUV(aPointToCheck, Precision::Confusion());
689       BRepTopAdaptor_FClass2d aFClass2d(aFace, Precision::Confusion());
690       if(aFClass2d.Perform(aPointOnFace) == TopAbs_OUT) {
691         return false;
692       }
693
694     } else {
695       return false;
696     }
697   } else {
698     return false;
699   }
700
701   return true;
702 }
703
704 //==================================================================================================
705 bool GeomAlgoAPI_ShapeTools::isShapeValid(const std::shared_ptr<GeomAPI_Shape> theShape)
706 {
707   if(!theShape.get()) {
708     return false;
709   }
710
711   BRepCheck_Analyzer aChecker(theShape->impl<TopoDS_Shape>());
712   return (aChecker.IsValid() == Standard_True);
713 }
714
715 //==================================================================================================
716 std::shared_ptr<GeomAPI_Shape>
717   GeomAlgoAPI_ShapeTools::getFaceOuterWire(const std::shared_ptr<GeomAPI_Shape> theFace)
718 {
719   GeomShapePtr anOuterWire;
720
721   if(!theFace.get() || !theFace->isFace()) {
722     return anOuterWire;
723   }
724
725   TopoDS_Face aFace = TopoDS::Face(theFace->impl<TopoDS_Shape>());
726   TopoDS_Wire aWire = BRepTools::OuterWire(aFace);
727
728   anOuterWire.reset(new GeomAPI_Shape());
729   anOuterWire->setImpl(new TopoDS_Shape(aWire));
730
731   return anOuterWire;
732 }
733
734 //==================================================================================================
735 bool GeomAlgoAPI_ShapeTools::isParallel(const std::shared_ptr<GeomAPI_Edge> theEdge,
736                                         const std::shared_ptr<GeomAPI_Face> theFace)
737 {
738   if(!theEdge.get() || !theFace.get()) {
739     return false;
740   }
741
742   TopoDS_Edge anEdge = TopoDS::Edge(theEdge->impl<TopoDS_Shape>());
743   TopoDS_Face aFace  = TopoDS::Face(theFace->impl<TopoDS_Shape>());
744
745   BRepExtrema_ExtCF anExt(anEdge, aFace);
746   return anExt.IsParallel() == Standard_True;
747 }
748
749 //==================================================================================================
750 void GeomAlgoAPI_ShapeTools::splitShape(const std::shared_ptr<GeomAPI_Shape>& theBaseShape,
751                                       const GeomAlgoAPI_ShapeTools::PointToRefsMap& thePointsInfo,
752                                       std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
753 {
754   // to split shape at least one point should be presented in the points container
755   if (thePointsInfo.empty())
756     return;
757
758     // General Fuse to split edge by vertices
759   BOPAlgo_Builder aBOP;
760   TopoDS_Edge aBaseEdge = theBaseShape->impl<TopoDS_Edge>();
761   // Rebuild closed edge to place vertex to one of split points.
762   // This will prevent edge to be split on same vertex.
763   if (BRep_Tool::IsClosed(aBaseEdge))
764   {
765     Standard_Real aFirst, aLast;
766     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aBaseEdge, aFirst, aLast);
767
768     PointToRefsMap::const_iterator aPIt = thePointsInfo.begin();
769     std::shared_ptr<GeomAPI_Pnt> aPnt = aPIt->first;
770     gp_Pnt aPoint(aPnt->x(), aPnt->y(), aPnt->z());
771
772     TopAbs_Orientation anOrientation = aBaseEdge.Orientation();
773     aBaseEdge = BRepBuilderAPI_MakeEdge(aCurve, aPoint, aPoint).Edge();
774     aBaseEdge.Orientation(anOrientation);
775   }
776   aBOP.AddArgument(aBaseEdge);
777
778   PointToRefsMap::const_iterator aPIt = thePointsInfo.begin();
779   for (; aPIt != thePointsInfo.end(); ++aPIt) {
780     std::shared_ptr<GeomAPI_Pnt> aPnt = aPIt->first;
781     TopoDS_Vertex aV = BRepBuilderAPI_MakeVertex(gp_Pnt(aPnt->x(), aPnt->y(), aPnt->z()));
782     aBOP.AddArgument(aV);
783   }
784
785   aBOP.Perform();
786   if (aBOP.ErrorStatus())
787     return;
788
789   // Collect splits
790   const TopTools_ListOfShape& aSplits = aBOP.Modified(aBaseEdge);
791   TopTools_ListIteratorOfListOfShape anIt(aSplits);
792   for (; anIt.More(); anIt.Next()) {
793     std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
794     anEdge->setImpl(new TopoDS_Shape(anIt.Value()));
795     theShapes.insert(anEdge);
796   }
797 }
798
799 //==================================================================================================
800 void GeomAlgoAPI_ShapeTools::splitShape_p(const std::shared_ptr<GeomAPI_Shape>& theBaseShape,
801                                           const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
802                                           std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
803 {
804   // General Fuse to split edge by vertices
805   BOPAlgo_Builder aBOP;
806   TopoDS_Edge aBaseEdge = theBaseShape->impl<TopoDS_Edge>();
807   // Rebuild closed edge to place vertex to one of split points.
808   // This will prevent edge to be split on seam vertex.
809   if (BRep_Tool::IsClosed(aBaseEdge))
810   {
811     Standard_Real aFirst, aLast;
812     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aBaseEdge, aFirst, aLast);
813
814     std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPIt = thePoints.begin();
815     gp_Pnt aPoint((*aPIt)->x(), (*aPIt)->y(), (*aPIt)->z());
816
817     TopAbs_Orientation anOrientation = aBaseEdge.Orientation();
818     aBaseEdge = BRepBuilderAPI_MakeEdge(aCurve, aPoint, aPoint).Edge();
819     aBaseEdge.Orientation(anOrientation);
820   }
821   aBOP.AddArgument(aBaseEdge);
822
823   std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPtIt = thePoints.begin();
824   for (; aPtIt != thePoints.end(); ++aPtIt) {
825     std::shared_ptr<GeomAPI_Pnt> aPnt = *aPtIt;
826     TopoDS_Vertex aV = BRepBuilderAPI_MakeVertex(gp_Pnt(aPnt->x(), aPnt->y(), aPnt->z()));
827     aBOP.AddArgument(aV);
828   }
829
830   aBOP.Perform();
831   if (aBOP.ErrorStatus())
832     return;
833
834   // Collect splits
835   const TopTools_ListOfShape& aSplits = aBOP.Modified(aBaseEdge);
836   TopTools_ListIteratorOfListOfShape anIt(aSplits);
837   for (; anIt.More(); anIt.Next()) {
838     std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
839     anEdge->setImpl(new TopoDS_Shape(anIt.Value()));
840     theShapes.insert(anEdge);
841   }
842 }
843
844 //==================================================================================================
845 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::findShape(
846                                   const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
847                                   const std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
848 {
849   std::shared_ptr<GeomAPI_Shape> aResultShape;
850
851   if (thePoints.size() == 2) {
852     std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPntIt = thePoints.begin();
853     std::shared_ptr<GeomAPI_Pnt> aFirstPoint = *aPntIt;
854     aPntIt++;
855     std::shared_ptr<GeomAPI_Pnt> aLastPoint = *aPntIt;
856
857     std::set<std::shared_ptr<GeomAPI_Shape> >::const_iterator anIt = theShapes.begin(),
858                                                               aLast = theShapes.end();
859     for (; anIt != aLast; anIt++) {
860       GeomShapePtr aShape = *anIt;
861       std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge(aShape));
862       if (anEdge.get()) {
863         std::shared_ptr<GeomAPI_Pnt> anEdgeFirstPoint = anEdge->firstPoint();
864         std::shared_ptr<GeomAPI_Pnt> anEdgeLastPoint = anEdge->lastPoint();
865         if (anEdgeFirstPoint->isEqual(aFirstPoint) &&
866             anEdgeLastPoint->isEqual(aLastPoint))
867             aResultShape = aShape;
868       }
869     }
870   }
871
872   return aResultShape;
873 }
874
875 //==================================================================================================
876 std::shared_ptr<GeomAPI_Dir> GeomAlgoAPI_ShapeTools::buildDirFromAxisAndShape(
877                                     const std::shared_ptr<GeomAPI_Shape> theBaseShape,
878                                     const std::shared_ptr<GeomAPI_Ax1> theAxis)
879 {
880   gp_Pnt aCentreOfMassPoint =
881     GeomAlgoAPI_ShapeTools::centreOfMass(theBaseShape)->impl<gp_Pnt>();
882   Handle(Geom_Line) aLine = new Geom_Line(theAxis->impl<gp_Ax1>());
883   GeomAPI_ProjectPointOnCurve aPrjTool(aCentreOfMassPoint, aLine);
884   gp_Pnt aPoint = aPrjTool.NearestPoint();
885
886   std::shared_ptr<GeomAPI_Dir> aDir(new GeomAPI_Dir(aCentreOfMassPoint.X()-aPoint.X(),
887                                                     aCentreOfMassPoint.Y()-aPoint.Y(),
888                                                     aCentreOfMassPoint.Z()-aPoint.Z()));
889   return aDir;
890 }