Salome HOME
updated copyright message
[modules/shaper.git] / src / GeomAlgoAPI / GeomAlgoAPI_ShapeTools.cpp
1 // Copyright (C) 2014-2023  CEA, EDF
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
18 //
19
20 #include "GeomAlgoAPI_ShapeTools.h"
21
22 #include "GeomAlgoAPI_SketchBuilder.h"
23
24 #include <Basics_OCCTVersion.hxx>
25
26 #include <GeomAPI_Ax1.h>
27 #include <GeomAPI_Edge.h>
28 #include <GeomAPI_Dir.h>
29 #include <GeomAPI_Face.h>
30 #include <GeomAPI_Pln.h>
31 #include <GeomAPI_Pnt.h>
32 #include <GeomAPI_Wire.h>
33
34 #include <Approx_CurvilinearParameter.hxx>
35
36 #include <Bnd_Box.hxx>
37
38 #include <BRep_Tool.hxx>
39 #include <BRep_Builder.hxx>
40 #include <BRepAlgo.hxx>
41 #include <BRepAlgo_FaceRestrictor.hxx>
42 #include <BRepAdaptor_Curve.hxx>
43 #include <BRepBndLib.hxx>
44 #include <BRepBuilderAPI_Copy.hxx>
45 #include <BRepBuilderAPI_FindPlane.hxx>
46 #include <BRepBuilderAPI_MakeEdge.hxx>
47 #include <BRepBuilderAPI_MakeFace.hxx>
48 #include <BRepBuilderAPI_MakeVertex.hxx>
49 #include <BRepBuilderAPI_MakeWire.hxx>
50 #include <BRepCheck_Analyzer.hxx>
51 #include <BRepExtrema_DistShapeShape.hxx>
52 #include <BRepExtrema_ExtCF.hxx>
53 #include <BRepExtrema_ShapeProximity.hxx>
54 #include <BRepGProp.hxx>
55 #include <BRepMesh_IncrementalMesh.hxx>
56 #include <BRepTools.hxx>
57 #include <BRepTools_WireExplorer.hxx>
58 #include <BRepTopAdaptor_FClass2d.hxx>
59 #include <BRepClass_FaceClassifier.hxx>
60 #include <BRepLib_CheckCurveOnSurface.hxx>
61 #include <BRepLProp.hxx>
62
63 #include <BOPAlgo_Builder.hxx>
64
65 #include <Extrema_GenLocateExtCS.hxx>
66 #include <Extrema_GenLocateExtSS.hxx>
67 #include <Extrema_GenLocateExtPS.hxx>
68 #include <Extrema_LocateExtCC.hxx>
69 #include <Extrema_LocateExtPC.hxx>
70
71 #include <Geom2d_Curve.hxx>
72 #include <Geom2d_Curve.hxx>
73
74 #include <Geom_BSplineCurve.hxx>
75 #include <Geom_CylindricalSurface.hxx>
76 #include <Geom_Line.hxx>
77 #include <Geom_Plane.hxx>
78 #include <Geom_RectangularTrimmedSurface.hxx>
79
80 #if OCC_VERSION_LARGE < 0x07070000
81 #include <GeomAdaptor_HCurve.hxx>
82 #else
83 #include <GeomAdaptor_Curve.hxx>
84 #endif
85
86 #include <GeomAPI_ProjectPointOnCurve.hxx>
87 #include <GeomAPI_ShapeIterator.h>
88
89 #include <GeomLib_IsPlanarSurface.hxx>
90 #include <GeomLib_Tool.hxx>
91 #include <GeomAPI_IntCS.hxx>
92
93 #include <gp_Pln.hxx>
94 #include <GProp_GProps.hxx>
95
96 #include <IntAna_IntConicQuad.hxx>
97 #include <IntAna_Quadric.hxx>
98
99 #include <ShapeAnalysis.hxx>
100 #include <ShapeAnalysis_Surface.hxx>
101
102 #include <TopoDS.hxx>
103 #include <TopoDS_Edge.hxx>
104 #include <TopoDS_Face.hxx>
105 #include <TopoDS_Shape.hxx>
106 #include <TopoDS_Shell.hxx>
107 #include <TopoDS_Vertex.hxx>
108 #include <TopoDS_Builder.hxx>
109
110 #include <TopExp.hxx>
111 #include <TopExp_Explorer.hxx>
112
113 #include <TopTools_ListIteratorOfListOfShape.hxx>
114
115 #include <NCollection_Vector.hxx>
116
117 #include <LocalAnalysis_SurfaceContinuity.hxx>
118 #include<array>
119
120 //==================================================================================================
121 static GProp_GProps props(const TopoDS_Shape& theShape)
122 {
123   GProp_GProps aGProps;
124
125   if (theShape.ShapeType() == TopAbs_EDGE || theShape.ShapeType() == TopAbs_WIRE)
126   {
127     BRepGProp::LinearProperties(theShape, aGProps);
128   }
129   else if (theShape.ShapeType() == TopAbs_FACE || theShape.ShapeType() == TopAbs_SHELL)
130   {
131     const Standard_Real anEps = 1.e-6;
132     BRepGProp::SurfaceProperties(theShape, aGProps, anEps);
133   }
134   else if (theShape.ShapeType() == TopAbs_SOLID || theShape.ShapeType() == TopAbs_COMPSOLID)
135   {
136     BRepGProp::VolumeProperties(theShape, aGProps);
137   }
138   else if (theShape.ShapeType() == TopAbs_COMPOUND)
139   {
140     for (TopoDS_Iterator anIt(theShape); anIt.More(); anIt.Next())
141     {
142       aGProps.Add(props(anIt.Value()));
143     }
144   }
145
146   return aGProps;
147 }
148
149 //==================================================================================================
150 double GeomAlgoAPI_ShapeTools::length(const std::shared_ptr<GeomAPI_Shape> theShape)
151 {
152   GProp_GProps aGProps;
153   if (!theShape.get()) {
154     return 0.0;
155   }
156   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
157   if (aShape.IsNull()) {
158     return 0.0;
159   }
160
161   BRepGProp::LinearProperties(aShape, aGProps, Standard_True);
162   return  aGProps.Mass();
163 }
164
165 //==================================================================================================
166 double GeomAlgoAPI_ShapeTools::volume(const std::shared_ptr<GeomAPI_Shape> theShape)
167 {
168   if (!theShape.get()) {
169     return 0.0;
170   }
171   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
172   if (aShape.IsNull()) {
173     return 0.0;
174   }
175   const Standard_Real anEps = 1.e-6;
176   double aVolume = 0.0;
177   for (TopExp_Explorer anExp(aShape, TopAbs_SOLID); anExp.More(); anExp.Next()) {
178     GProp_GProps aGProps;
179     BRepGProp::VolumeProperties(anExp.Current(), aGProps, anEps);
180     aVolume += aGProps.Mass();
181   }
182   return aVolume;
183 }
184
185 //==================================================================================================
186 double GeomAlgoAPI_ShapeTools::area (const std::shared_ptr<GeomAPI_Shape> theShape)
187 {
188   GProp_GProps aGProps;
189   if (!theShape.get()) {
190     return 0.0;
191   }
192   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
193   if (aShape.IsNull()) {
194     return 0.0;
195   }
196   const Standard_Real anEps = 1.e-6;
197
198   BRepGProp::SurfaceProperties(aShape, aGProps, anEps);
199   return aGProps.Mass();
200 }
201
202 //==================================================================================================
203 bool GeomAlgoAPI_ShapeTools::isContinuousFaces(const GeomShapePtr& theFace1,
204                                                const GeomShapePtr& theFace2,
205                                                const GeomPointPtr& thePoint,
206                                                const double & theAngle,
207                                                std::string& theError)
208 {
209
210   #ifdef _DEBUG
211   std::cout << "isContinuousFaces " << std::endl;
212   #endif
213
214   if (!thePoint.get()) {
215       theError = "isContinuousFaces : An invalid argument";
216       return false;
217   }
218   const gp_Pnt& aPoint = thePoint->impl<gp_Pnt>();
219
220   // Getting base shape.
221   if (!theFace1.get()) {
222     theError = "isContinuousFaces : An invalid argument";
223     return false;
224   }
225
226   TopoDS_Shape aShape1 = theFace1->impl<TopoDS_Shape>();
227
228   if (aShape1.IsNull()) {
229     theError = "isContinuousFaces : An invalid argument";
230     return false;
231   }
232
233   // Getting base shape.
234   if (!theFace2.get()) {
235     theError = "isContinuousFaces : An invalid argument";
236     return false;
237   }
238
239   TopoDS_Shape aShape2 = theFace2->impl<TopoDS_Shape>();
240
241   if (aShape2.IsNull()) {
242     theError = "isContinuousFaces : An invalid argument";
243     return false;
244   }
245
246   TopoDS_Face aFace1 = TopoDS::Face(aShape1);
247   if (aFace1.IsNull()) {
248     theError = "isContinuousFaces : An invalid argument";
249     return false;
250   }
251
252   Handle(Geom_Surface) aSurf1 = BRep_Tool::Surface(aFace1);
253   if (aSurf1.IsNull()) {
254     theError = "isContinuousFaces : An invalid surface";
255     return false;
256   }
257
258   ShapeAnalysis_Surface aSAS1(aSurf1);
259   gp_Pnt2d aPointOnFace1 = aSAS1.ValueOfUV(aPoint, Precision::Confusion());
260
261   TopoDS_Face aFace2 = TopoDS::Face(aShape2);
262   if (aFace2.IsNull()) {
263     theError = "isContinuousFaces : An invalid argument";
264     return false;
265   }
266
267   Handle(Geom_Surface) aSurf2 = BRep_Tool::Surface(aFace2);
268   if (aSurf2.IsNull()) {
269     theError = "isContinuousFaces : An invalid surface";
270     return false;
271   }
272
273   ShapeAnalysis_Surface aSAS2(aSurf2);
274   gp_Pnt2d aPointOnFace2= aSAS2.ValueOfUV(aPoint, Precision::Confusion());
275
276   bool aRes = false;
277   try {
278     OCC_CATCH_SIGNALS;
279     LocalAnalysis_SurfaceContinuity aLocAnal(aSurf1,
280                                              aPointOnFace1.X(),
281                                              aPointOnFace1.Y(),
282                                              aSurf2,
283                                              aPointOnFace2.X(),
284                                              aPointOnFace2.Y(),
285                                              GeomAbs_Shape::GeomAbs_G1, // Order
286                                              0.001, // EpsNul
287                                              0.001, // EpsC0
288                                              0.001, // EpsC1
289                                              0.001, // EpsC2
290                                              theAngle * M_PI / 180.0); //EpsG1
291     aRes = aLocAnal.IsG1();
292   }
293   catch (Standard_Failure const& anException) {
294     theError = "LocalAnalysis_SurfaceContinuity error :";
295     theError += anException.GetMessageString();
296   }
297
298   return aRes;
299 }
300
301 //==================================================================================================
302 std::shared_ptr<GeomAPI_Pnt>
303   GeomAlgoAPI_ShapeTools::centreOfMass(const std::shared_ptr<GeomAPI_Shape> theShape)
304 {
305   GProp_GProps aGProps;
306   if (!theShape) {
307     return std::shared_ptr<GeomAPI_Pnt>();
308   }
309   const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
310   if (aShape.IsNull()) {
311     return std::shared_ptr<GeomAPI_Pnt>();
312   }
313   gp_Pnt aCentre;
314   if (aShape.ShapeType() == TopAbs_VERTEX) {
315     aCentre = BRep_Tool::Pnt(TopoDS::Vertex(aShape));
316   } else {
317     aGProps = props(aShape);
318     aCentre = aGProps.CentreOfMass();
319   }
320
321   return std::shared_ptr<GeomAPI_Pnt>(new GeomAPI_Pnt(aCentre.X(), aCentre.Y(), aCentre.Z()));
322 }
323
324 //==================================================================================================
325 double GeomAlgoAPI_ShapeTools::radius(const std::shared_ptr<GeomAPI_Face>& theCylinder)
326 {
327   double aRadius = -1.0;
328   if (theCylinder->isCylindrical()) {
329     const TopoDS_Shape& aShape = theCylinder->impl<TopoDS_Shape>();
330     Handle(Geom_Surface) aSurf = BRep_Tool::Surface(TopoDS::Face(aShape));
331     Handle(Geom_CylindricalSurface) aCyl = Handle(Geom_CylindricalSurface)::DownCast(aSurf);
332     if (!aCyl.IsNull())
333       aRadius = aCyl->Radius();
334   }
335   return aRadius;
336 }
337
338 //==================================================================================================
339 namespace {
340
341 auto getExtemaDistShape = [](const GeomShapePtr& theShape1,
342     const GeomShapePtr& theShape2) -> BRepExtrema_DistShapeShape
343 {
344   const TopoDS_Shape& aShape1 = theShape1->impl<TopoDS_Shape>();
345   const TopoDS_Shape& aShape2 = theShape2->impl<TopoDS_Shape>();
346
347   BRepExtrema_DistShapeShape aDist(aShape1, aShape2);
348   aDist.Perform();
349   return aDist;
350 };
351
352 static void tessellateShape(const TopoDS_Shape& theShape)
353 {
354   Standard_Boolean isTessellate = Standard_False;
355   TopLoc_Location aLoc;
356   for (TopExp_Explorer anExp(theShape, TopAbs_FACE); anExp.More() && !isTessellate; anExp.Next()) {
357     Handle(Poly_Triangulation) aTria = BRep_Tool::Triangulation(TopoDS::Face(anExp.Value()), aLoc);
358     isTessellate = aTria.IsNull();
359   }
360   for (TopExp_Explorer anExp(theShape, TopAbs_EDGE); anExp.More() && !isTessellate; anExp.Next()) {
361     Handle(Poly_Polygon3D) aPoly = BRep_Tool::Polygon3D(TopoDS::Edge(anExp.Value()), aLoc);
362     isTessellate = aPoly.IsNull();
363   }
364
365   if (isTessellate) {
366     BRepMesh_IncrementalMesh aMesher(theShape, 0.1);
367     Standard_ProgramError_Raise_if(!aMesher.IsDone(), "Meshing failed");
368   }
369 }
370
371 static Standard_Real paramOnCurve(const BRepAdaptor_Curve& theCurve,
372                                   const gp_Pnt&            thePoint,
373                                   const Standard_Real      theTol)
374 {
375   Extrema_ExtPC aParamSearch(thePoint,
376                              theCurve,
377                              theCurve.FirstParameter(),
378                              theCurve.LastParameter());
379   if (aParamSearch.IsDone()) {
380     Standard_Integer anIndMin = 0, aNbExt = aParamSearch.NbExt();
381     Standard_Real aSqDistMin = RealLast();
382     for (Standard_Integer i = 1; i <= aNbExt; ++i) {
383       if (aParamSearch.SquareDistance(i) < aSqDistMin) {
384         anIndMin = i;
385         aSqDistMin = aParamSearch.SquareDistance(i);
386       }
387     }
388     if (anIndMin != 0 && aSqDistMin <= theTol * theTol)
389       return aParamSearch.Point(anIndMin).Parameter();
390   }
391   return 0.5 * (theCurve.FirstParameter() + theCurve.LastParameter());
392 }
393
394 static void paramsOnSurf(const BRepAdaptor_Surface& theSurf,
395                          const gp_Pnt&              thePoint,
396                          const Standard_Real        theTol,
397                          Standard_Real&             theU,
398                          Standard_Real&             theV)
399 {
400   Extrema_ExtPS aParamSearch(thePoint, theSurf, Precision::PConfusion(), Precision::PConfusion());
401   if (aParamSearch.IsDone()) {
402     Standard_Integer anIndMin = 0, aNbExt = aParamSearch.NbExt();
403     Standard_Real aSqDistMin = RealLast();
404     for (Standard_Integer i = 1; i <= aNbExt; ++i) {
405       if (aParamSearch.SquareDistance(i) < aSqDistMin) {
406         anIndMin = i;
407         aSqDistMin = aParamSearch.SquareDistance(i);
408       }
409     }
410     if (anIndMin != 0 && aSqDistMin <= theTol * theTol)
411       return aParamSearch.Point(anIndMin).Parameter(theU, theV);
412   }
413   theU = 0.5 * (theSurf.FirstUParameter() + theSurf.LastUParameter());
414   theV = 0.5 * (theSurf.FirstVParameter() + theSurf.LastVParameter());
415 }
416
417 static Standard_Real extremaEE(const TopoDS_Edge& theEdge1,
418                                const TopoDS_Edge& theEdge2,
419                                const gp_Pnt&      thePoint1,
420                                const gp_Pnt&      thePoint2)
421 {
422   BRepAdaptor_Curve aCurve1(theEdge1);
423   BRepAdaptor_Curve aCurve2(theEdge2);
424
425   Standard_Real aU1 = paramOnCurve(aCurve1, thePoint1, BRep_Tool::Tolerance(theEdge1));
426   Standard_Real aU2 = paramOnCurve(aCurve2, thePoint2, BRep_Tool::Tolerance(theEdge2));
427
428   Standard_Real aValue = -1.0;
429   Extrema_LocateExtCC anExtr(aCurve1, aCurve2, aU1, aU2);
430   if (anExtr.IsDone() && aValue > Precision::Confusion())
431     aValue = Sqrt(anExtr.SquareDistance());
432   return aValue;
433 }
434
435 static Standard_Real extremaPE(const gp_Pnt&      thePoint,
436                                const TopoDS_Edge& theEdge,
437                                gp_Pnt&            thePointOnEdge)
438 {
439   BRepAdaptor_Curve aCurve (theEdge);
440
441   TopLoc_Location aLoc;
442   Standard_Real aTol = BRep_Tool::Tolerance(theEdge);
443   Handle(Poly_Polygon3D) aPoly = BRep_Tool::Polygon3D (theEdge, aLoc);
444   if (!aPoly.IsNull())
445     aTol = Max (aTol, aPoly->Deflection());
446
447   Standard_Real aParam = paramOnCurve (aCurve, thePointOnEdge, 2*aTol);
448
449   Standard_Real aValue = -1.0;
450   Extrema_LocateExtPC anExtr (thePoint, aCurve, aParam, Precision::PConfusion());
451   if (anExtr.IsDone())
452   {
453     aValue = Sqrt(anExtr.SquareDistance());
454
455     Extrema_POnCurv aPointOnCurve = anExtr.Point();
456     thePointOnEdge = aPointOnCurve.Value();
457   }
458   return aValue;
459 }
460   
461 static Standard_Real extremaPF(const gp_Pnt&      thePoint,
462                                const TopoDS_Face& theFace,
463                                gp_Pnt&            thePointOnFace)
464 {
465   BRepAdaptor_Surface aSurf (theFace);
466
467   TopLoc_Location aLoc;
468   Standard_Real aTol = BRep_Tool::Tolerance(theFace);
469   Handle(Poly_Triangulation) aTria = BRep_Tool::Triangulation (theFace, aLoc);
470   if (!aTria.IsNull())
471     aTol = Max (aTol, aTria->Deflection());
472
473   Standard_Real aU, aV;
474   paramsOnSurf(aSurf, thePointOnFace, 2*aTol, aU, aV);
475
476   Standard_Real aValue = -1.0;
477   Extrema_GenLocateExtPS anExtr (aSurf);
478   anExtr.Perform (thePoint, aU, aV);
479   if (anExtr.IsDone())
480   {
481     aValue = Sqrt(anExtr.SquareDistance());
482
483     Extrema_POnSurf aPointOnSurf = anExtr.Point();
484     thePointOnFace = aPointOnSurf.Value();
485   }
486   return aValue;
487 }
488
489 static Standard_Real extremaEF(const TopoDS_Edge& theEdge,
490                                const TopoDS_Face& theFace,
491                                const gp_Pnt&      thePonE,
492                                const gp_Pnt&      thePonF)
493 {
494   BRepAdaptor_Curve aCurve(theEdge);
495   BRepAdaptor_Surface aSurf(theFace);
496
497   Standard_Real aP = paramOnCurve(aCurve, thePonE, BRep_Tool::Tolerance(theEdge));
498   Standard_Real aU, aV;
499   paramsOnSurf(aSurf, thePonF, BRep_Tool::Tolerance(theFace), aU, aV);
500
501   Standard_Real aValue = -1.0;
502   Extrema_GenLocateExtCS anExtr(aCurve, aSurf, aP, aU, aV, Precision::PConfusion(), Precision::PConfusion());
503   if (anExtr.IsDone() && aValue > Precision::Confusion())
504     aValue = Sqrt(anExtr.SquareDistance());
505   return aValue;
506 }
507
508 static Standard_Real extremaFF(const TopoDS_Face& theFace1,
509                                const TopoDS_Face& theFace2,
510                                const gp_Pnt&      thePoint1,
511                                const gp_Pnt&      thePoint2)
512 {
513   BRepAdaptor_Surface aSurf1(theFace1);
514   BRepAdaptor_Surface aSurf2(theFace2);
515
516   Standard_Real aU1, aV1;
517   paramsOnSurf(aSurf1, thePoint1, BRep_Tool::Tolerance(theFace1), aU1, aV1);
518   Standard_Real aU2, aV2;
519   paramsOnSurf(aSurf2, thePoint2, BRep_Tool::Tolerance(theFace2), aU2, aV2);
520
521   Standard_Real aValue = -1.0;
522   Extrema_GenLocateExtSS anExtr(aSurf1, aSurf2, aU1, aV1, aU2, aV2, Precision::PConfusion(), Precision::PConfusion());
523   if (anExtr.IsDone() && aValue > Precision::Confusion())
524     aValue = Sqrt(anExtr.SquareDistance());
525   return aValue;
526 }
527
528 } // namespace
529
530 double GeomAlgoAPI_ShapeTools::minimalDistance(const GeomShapePtr& theShape1,
531                                                const GeomShapePtr& theShape2)
532 {
533   BRepExtrema_DistShapeShape aDist = getExtemaDistShape(theShape1, theShape2);
534   return aDist.IsDone() ? aDist.Value() : Precision::Infinite();
535 }
536
537 double GeomAlgoAPI_ShapeTools::minimalDistance(const GeomShapePtr& theShape1,
538                                                const GeomShapePtr& theShape2,
539                                                std::array<double, 3> & fromShape1To2)
540 {
541   BRepExtrema_DistShapeShape aDist = getExtemaDistShape(theShape1, theShape2);
542   const auto & pt1 = aDist.PointOnShape1(1);
543   const auto & pt2 = aDist.PointOnShape2(1) ;
544   fromShape1To2[0] = pt2.X() - pt1.X();
545   fromShape1To2[1] = pt2.Y() - pt1.Y();
546   fromShape1To2[2] = pt2.Z() - pt1.Z();
547   return aDist.IsDone() ? aDist.Value() : Precision::Infinite();
548 }
549
550 //==================================================================================================
551 double GeomAlgoAPI_ShapeTools::shapeProximity(const GeomShapePtr& theShape1,
552                                               const GeomShapePtr& theShape2)
553 {
554   double aResult = -1.0;
555   if (!theShape1.get() || !theShape2.get())
556     return aResult;
557
558   const TopoDS_Shape& aShape1 = theShape1->impl<TopoDS_Shape>();
559   const TopoDS_Shape& aShape2 = theShape2->impl<TopoDS_Shape>();
560
561   TopAbs_ShapeEnum aType1 = aShape1.ShapeType();
562   TopAbs_ShapeEnum aType2 = aShape2.ShapeType();
563
564   // tessellate shapes if there is no mesh exists
565   tessellateShape(aShape1);
566   tessellateShape(aShape2);
567
568   BRepExtrema_ShapeProximity aDist (aShape1, aShape2);
569   aDist.Perform();
570   if (aDist.IsDone()) {
571     aResult = aDist.Proximity();
572
573     // refine the result
574     gp_Pnt aPnt1 = aDist.ProximityPoint1();
575     gp_Pnt aPnt2 = aDist.ProximityPoint2();
576
577     BRepExtrema_ProximityDistTool::ProxPnt_Status aStatus1 = aDist.ProxPntStatus1();
578     BRepExtrema_ProximityDistTool::ProxPnt_Status aStatus2 = aDist.ProxPntStatus2();
579
580     double aValue = -1.0;
581
582     if (aType1 == TopAbs_EDGE)
583     {
584       if (aType2 == TopAbs_EDGE)
585       {
586         if (aStatus1 == BRepExtrema_ProximityDistTool::ProxPnt_Status_MIDDLE &&
587             aStatus2 == BRepExtrema_ProximityDistTool::ProxPnt_Status_MIDDLE)
588         {
589           aValue = extremaEE(TopoDS::Edge(aShape1), TopoDS::Edge(aShape2), aPnt1, aPnt2);
590         }
591         else if (aStatus1 == BRepExtrema_ProximityDistTool::ProxPnt_Status_BORDER &&
592                  aStatus2 == BRepExtrema_ProximityDistTool::ProxPnt_Status_MIDDLE)
593         {
594           aValue = extremaPE(aPnt1, TopoDS::Edge(aShape2), aPnt2);
595         }
596         else if (aStatus1 == BRepExtrema_ProximityDistTool::ProxPnt_Status_MIDDLE &&
597                  aStatus2 == BRepExtrema_ProximityDistTool::ProxPnt_Status_BORDER)
598         {
599           aValue = extremaPE(aPnt2, TopoDS::Edge(aShape1), aPnt1);
600         }
601       }
602       else if (aType2 == TopAbs_FACE)
603       {
604         if (aStatus1 == BRepExtrema_ProximityDistTool::ProxPnt_Status_MIDDLE &&
605             aStatus2 == BRepExtrema_ProximityDistTool::ProxPnt_Status_MIDDLE)
606         {
607           aValue = extremaEF(TopoDS::Edge(aShape1), TopoDS::Face(aShape2), aPnt1, aPnt2);
608         }
609         else if (aStatus1 == BRepExtrema_ProximityDistTool::ProxPnt_Status_BORDER &&
610                  aStatus2 == BRepExtrema_ProximityDistTool::ProxPnt_Status_MIDDLE)
611         {
612           aValue = extremaPF(aPnt1, TopoDS::Face(aShape2), aPnt2);
613         }
614         else if (aStatus1 == BRepExtrema_ProximityDistTool::ProxPnt_Status_MIDDLE &&
615                  aStatus2 == BRepExtrema_ProximityDistTool::ProxPnt_Status_BORDER)
616         {
617           aValue = extremaPE(aPnt2, TopoDS::Edge(aShape1), aPnt1);
618         }
619       }
620     }
621     else if (aType1 == TopAbs_FACE)
622     {
623       if (aType2 == TopAbs_EDGE)
624       {
625         if (aStatus1 == BRepExtrema_ProximityDistTool::ProxPnt_Status_MIDDLE &&
626             aStatus2 == BRepExtrema_ProximityDistTool::ProxPnt_Status_MIDDLE)
627         {
628           aValue = extremaEF(TopoDS::Edge(aShape2), TopoDS::Face(aShape1), aPnt2, aPnt1);
629         }
630         else if (aStatus1 == BRepExtrema_ProximityDistTool::ProxPnt_Status_BORDER &&
631                  aStatus2 == BRepExtrema_ProximityDistTool::ProxPnt_Status_MIDDLE)
632         {
633           aValue = extremaPE(aPnt1, TopoDS::Edge(aShape2), aPnt2);
634         }
635         else if (aStatus1 == BRepExtrema_ProximityDistTool::ProxPnt_Status_MIDDLE &&
636                  aStatus2 == BRepExtrema_ProximityDistTool::ProxPnt_Status_BORDER)
637         {
638           aValue = extremaPF(aPnt2, TopoDS::Face(aShape1), aPnt1);
639         }
640       }
641       else if (aType2 == TopAbs_FACE)
642       {
643         if (aStatus1 == BRepExtrema_ProximityDistTool::ProxPnt_Status_MIDDLE &&
644             aStatus2 == BRepExtrema_ProximityDistTool::ProxPnt_Status_MIDDLE)
645         {
646           aValue = extremaFF(TopoDS::Face(aShape1), TopoDS::Face(aShape2), aPnt1, aPnt2);
647         }
648         else if (aStatus1 == BRepExtrema_ProximityDistTool::ProxPnt_Status_BORDER &&
649                  aStatus2 == BRepExtrema_ProximityDistTool::ProxPnt_Status_MIDDLE)
650         {
651           aValue = extremaPF(aPnt1, TopoDS::Face(aShape2), aPnt2);
652         }
653         else if (aStatus1 == BRepExtrema_ProximityDistTool::ProxPnt_Status_MIDDLE &&
654                  aStatus2 == BRepExtrema_ProximityDistTool::ProxPnt_Status_BORDER)
655         {
656           aValue = extremaPF(aPnt2, TopoDS::Face(aShape1), aPnt1);
657         }
658       }
659     }
660
661     if (aValue > 0.0)
662       aResult = aValue;
663   }
664   return aResult;
665 }
666
667 //==================================================================================================
668 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::combineShapes(
669   const std::shared_ptr<GeomAPI_Shape> theCompound,
670   const GeomAPI_Shape::ShapeType theType,
671   ListOfShape& theResuts)
672 {
673
674   ListOfShape aResCombinedShapes;
675   ListOfShape aResFreeShapes;
676
677   GeomShapePtr aResult = theCompound;
678
679   if (!theCompound.get()) {
680     return aResult;
681   }
682
683   if (theType != GeomAPI_Shape::SHELL && theType != GeomAPI_Shape::COMPSOLID) {
684     return aResult;
685   }
686
687   TopAbs_ShapeEnum aTS = TopAbs_EDGE;
688   TopAbs_ShapeEnum aTA = TopAbs_FACE;
689   if (theType == GeomAPI_Shape::COMPSOLID) {
690     aTS = TopAbs_FACE;
691     aTA = TopAbs_SOLID;
692   }
693
694   // map from the resulting shapes to minimal index of the used shape from theCompound list
695   std::map<GeomShapePtr, int> anInputOrder;
696   // map from ancestors-shapes to the index of shapes in theCompound
697   NCollection_DataMap<TopoDS_Shape, int> anAncestorsOrder;
698
699   // Get free shapes.
700   int anOrder = 0;
701   const TopoDS_Shape& aShapesComp = theCompound->impl<TopoDS_Shape>();
702   for (TopoDS_Iterator anIter(aShapesComp); anIter.More(); anIter.Next(), anOrder++) {
703     const TopoDS_Shape& aShape = anIter.Value();
704     if (aShape.ShapeType() > aTA) {
705       std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
706       aGeomShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
707       aResFreeShapes.push_back(aGeomShape);
708       anInputOrder[aGeomShape] = anOrder;
709     } else {
710       for (TopExp_Explorer anExp(aShape, aTA); anExp.More(); anExp.Next()) {
711         anAncestorsOrder.Bind(anExp.Current(), anOrder);
712       }
713     }
714   }
715
716   // Map sub-shapes and shapes.
717   TopTools_IndexedDataMapOfShapeListOfShape aMapSA;
718   TopExp::MapShapesAndAncestors(aShapesComp, aTS, aTA, aMapSA);
719   if (aMapSA.IsEmpty()) {
720     return aResult;
721   }
722   theResuts.clear();
723
724   // Get all shapes with common sub-shapes and free shapes.
725   NCollection_Map<TopoDS_Shape> aFreeShapes;
726   NCollection_Vector<NCollection_Map<TopoDS_Shape>> aShapesWithCommonSubshapes;
727   for (TopTools_IndexedDataMapOfShapeListOfShape::Iterator
728       anIter(aMapSA); anIter.More(); anIter.Next()) {
729     TopTools_ListOfShape& aListOfShape = anIter.ChangeValue();
730     if (aListOfShape.IsEmpty()) {
731       continue;
732     }
733     else if (aListOfShape.Size() == 1) {
734       const TopoDS_Shape& aF = aListOfShape.First();
735       aFreeShapes.Add(aF);
736       aListOfShape.Clear();
737     } else {
738       NCollection_List<TopoDS_Shape> aTempList;
739       NCollection_Map<TopoDS_Shape> aTempMap;
740       for (TopTools_ListOfShape::Iterator aListIt(aListOfShape); aListIt.More(); aListIt.Next()) {
741         aTempList.Append(aListIt.Value());
742         aTempMap.Add(aListIt.Value());
743         aFreeShapes.Remove(aListIt.Value());
744       }
745       aListOfShape.Clear();
746       for (NCollection_List<TopoDS_Shape>::Iterator
747           aTempIter(aTempList); aTempIter.More(); aTempIter.Next()) {
748         const TopoDS_Shape& aTempShape = aTempIter.Value();
749         for (TopTools_IndexedDataMapOfShapeListOfShape::Iterator
750             anIter2(aMapSA); anIter2.More(); anIter2.Next()) {
751           TopTools_ListOfShape& aTempListOfShape = anIter2.ChangeValue();
752           if (aTempListOfShape.IsEmpty()) {
753             continue;
754           } else if (aTempListOfShape.Size() == 1 && aTempListOfShape.First() == aTempShape) {
755             aTempListOfShape.Clear();
756           } else if (aTempListOfShape.Size() > 1) {
757             TopTools_ListOfShape::Iterator anIt1(aTempListOfShape);
758             for (; anIt1.More(); anIt1.Next()) {
759               if (anIt1.Value() == aTempShape) {
760                 TopTools_ListOfShape::Iterator anIt2(aTempListOfShape);
761                 for (; anIt2.More(); anIt2.Next())
762                 {
763                   if (anIt2.Value() != anIt1.Value()) {
764                     if (aTempMap.Add(anIt2.Value())) {
765                       aTempList.Append(anIt2.Value());
766                       aFreeShapes.Remove(anIt2.Value());
767                     }
768                   }
769                 }
770                 aTempListOfShape.Clear();
771                 break;
772               }
773             }
774           }
775         }
776       }
777       aShapesWithCommonSubshapes.Append(aTempMap);
778     }
779   }
780
781   // Combine shapes with common sub-shapes.
782   for (NCollection_Vector<NCollection_Map<TopoDS_Shape>>::Iterator
783       anIter(aShapesWithCommonSubshapes); anIter.More(); anIter.Next()) {
784     TopoDS_Shell aShell;
785     TopoDS_CompSolid aCSolid;
786     TopoDS_Builder aBuilder;
787     anOrder = -1;
788     theType ==
789       GeomAPI_Shape::COMPSOLID ? aBuilder.MakeCompSolid(aCSolid) : aBuilder.MakeShell(aShell);
790     NCollection_Map<TopoDS_Shape>& aShapesMap = anIter.ChangeValue();
791     for (TopExp_Explorer anExp(aShapesComp, aTA); anExp.More(); anExp.Next()) {
792       const TopoDS_Shape& aShape = anExp.Current();
793       if (aShapesMap.Contains(aShape)) {
794         theType ==
795           GeomAPI_Shape::COMPSOLID ? aBuilder.Add(aCSolid, aShape) : aBuilder.Add(aShell, aShape);
796         aShapesMap.Remove(aShape);
797         int aThisOrder = anAncestorsOrder.Find(aShape);
798         if (anOrder == -1 || aThisOrder < anOrder)
799           anOrder = aThisOrder; // take the minimum order position
800       }
801     }
802     std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
803     TopoDS_Shape* aSh = theType == GeomAPI_Shape::COMPSOLID ? new TopoDS_Shape(aCSolid) :
804                                                               new TopoDS_Shape(aShell);
805     aGeomShape->setImpl<TopoDS_Shape>(aSh);
806     aResCombinedShapes.push_back(aGeomShape);
807     anInputOrder[aGeomShape] = anOrder;
808   }
809
810   // Adding free shapes.
811   for (TopExp_Explorer anExp(aShapesComp, aTA); anExp.More(); anExp.Next()) {
812     const TopoDS_Shape& aShape = anExp.Current();
813     if (aFreeShapes.Contains(aShape)) {
814       std::shared_ptr<GeomAPI_Shape> aGeomShape(new GeomAPI_Shape);
815       aGeomShape->setImpl<TopoDS_Shape>(new TopoDS_Shape(aShape));
816       aResFreeShapes.push_back(aGeomShape);
817       anInputOrder[aGeomShape] = anAncestorsOrder.Find(aShape);
818     }
819   }
820
821   if (aResCombinedShapes.size() == 1 && aResFreeShapes.size() == 0) {
822     aResult = aResCombinedShapes.front();
823     theResuts.push_back(aResult);
824   } else if (aResCombinedShapes.size() == 0 && aResFreeShapes.size() == 1) {
825     aResult = aResFreeShapes.front();
826     theResuts.push_back(aResult);
827   } else {
828     TopoDS_Compound aResultComp;
829     TopoDS_Builder aBuilder;
830     aBuilder.MakeCompound(aResultComp);
831     // put to result compound and result list in accordance to the order numbers
832     std::map<GeomShapePtr, int>::iterator anInputIter = anInputOrder.begin();
833     std::map<int, GeomShapePtr> aNums;
834     for (; anInputIter != anInputOrder.end(); anInputIter++)
835       aNums[anInputIter->second] = anInputIter->first;
836     std::map<int, GeomShapePtr>::iterator aNumsIter = aNums.begin();
837     for (; aNumsIter != aNums.end(); aNumsIter++) {
838       aBuilder.Add(aResultComp, (aNumsIter->second)->impl<TopoDS_Shape>());
839       theResuts.push_back(aNumsIter->second);
840     }
841     aResult->setImpl(new TopoDS_Shape(aResultComp));
842   }
843
844   return aResult;
845 }
846
847 //==================================================================================================
848 static void addSimpleShapeToList(const TopoDS_Shape& theShape,
849                                  NCollection_List<TopoDS_Shape>& theList)
850 {
851   if (theShape.IsNull()) {
852     return;
853   }
854
855   if (theShape.ShapeType() == TopAbs_COMPOUND) {
856     for (TopoDS_Iterator anIt(theShape); anIt.More(); anIt.Next()) {
857       addSimpleShapeToList(anIt.Value(), theList);
858     }
859   } else {
860     theList.Append(theShape);
861   }
862 }
863
864 //==================================================================================================
865 static TopoDS_Compound makeCompound(const NCollection_List<TopoDS_Shape> theShapes)
866 {
867   TopoDS_Compound aCompound;
868
869   BRep_Builder aBuilder;
870   aBuilder.MakeCompound(aCompound);
871
872   for (NCollection_List<TopoDS_Shape>::Iterator anIt(theShapes); anIt.More(); anIt.Next()) {
873     aBuilder.Add(aCompound, anIt.Value());
874   }
875
876   return aCompound;
877 }
878
879 //==================================================================================================
880 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::groupSharedTopology(
881   const std::shared_ptr<GeomAPI_Shape> theCompound)
882 {
883   GeomShapePtr aResult = theCompound;
884
885   if (!theCompound.get()) {
886     return aResult;
887   }
888
889   TopoDS_Shape anInShape = aResult->impl<TopoDS_Shape>();
890   NCollection_List<TopoDS_Shape> anUngroupedShapes, aStillUngroupedShapes;
891   addSimpleShapeToList(anInShape, anUngroupedShapes);
892
893   // Iterate over all shapes and find shapes with shared vertices.
894   TopTools_ListOfShape allVertices;
895   TopTools_DataMapOfShapeListOfShape aVertexShapesMap;
896   for (NCollection_List<TopoDS_Shape>::Iterator aShapesIt(anUngroupedShapes);
897     aShapesIt.More();
898     aShapesIt.Next()) {
899     const TopoDS_Shape& aShape = aShapesIt.Value();
900     for (TopExp_Explorer aShapeExp(aShape, TopAbs_VERTEX);
901       aShapeExp.More();
902       aShapeExp.Next()) {
903       const TopoDS_Shape& aVertex = aShapeExp.Current();
904       if (!aVertexShapesMap.IsBound(aVertex)) {
905         NCollection_List<TopoDS_Shape> aList;
906         aList.Append(aShape);
907         allVertices.Append(aVertex);
908         aVertexShapesMap.Bind(aVertex, aList);
909       }
910       else {
911         if (!aVertexShapesMap.ChangeFind(aVertex).Contains(aShape)) {
912           aVertexShapesMap.ChangeFind(aVertex).Append(aShape);
913         }
914       }
915     }
916   }
917
918   // Iterate over the map and group shapes.
919   NCollection_Vector<TopTools_MapOfShape> aGroups; // groups of shapes connected by vertices
920   while (!allVertices.IsEmpty()) {
921     // Get first group of shapes in map, and then unbind it.
922     const TopoDS_Shape& aKey = allVertices.First();
923     TopTools_ListOfShape aConnectedShapes = aVertexShapesMap.Find(aKey);
924     aVertexShapesMap.UnBind(aKey);
925     allVertices.Remove(aKey);
926     // Iterate over shapes in this group and add to it shapes from groups in map.
927     for (TopTools_ListOfShape::Iterator aConnectedIt(aConnectedShapes);
928       aConnectedIt.More(); aConnectedIt.Next()) {
929       const TopoDS_Shape& aConnected = aConnectedIt.Value();
930       TopTools_ListOfShape aKeysToUnbind;
931       for (TopTools_ListOfShape::Iterator aKeysIt(allVertices);
932         aKeysIt.More();
933         aKeysIt.Next()) {
934         const TopTools_ListOfShape& anOtherConnected = aVertexShapesMap(aKeysIt.Value());
935         if (!anOtherConnected.Contains(aConnected)) {
936           // Other connected group does not contain shape from our connected group
937           continue;
938         }
939         // Other is connected to our, so add them to our connected
940         for (TopTools_ListOfShape::Iterator anOtherIt(anOtherConnected);
941           anOtherIt.More();
942           anOtherIt.Next()) {
943           const TopoDS_Shape& aShape = anOtherIt.Value();
944           if (!aConnectedShapes.Contains(aShape)) {
945             aConnectedShapes.Append(aShape);
946           }
947         }
948         // Save key to unbind from this map.
949         aKeysToUnbind.Append(aKeysIt.Value());
950       }
951       // Unbind groups from map that we added to our group.
952       for (TopTools_ListOfShape::Iterator aKeysIt(aKeysToUnbind);
953         aKeysIt.More();
954         aKeysIt.Next()) {
955         aVertexShapesMap.UnBind(aKeysIt.Value());
956         allVertices.Remove(aKeysIt.Value());
957       }
958     }
959     // Sort shapes from the most complicated to the simplest ones
960     TopTools_MapOfShape aSortedGroup;
961     for (int aST = TopAbs_COMPOUND; aST <= TopAbs_SHAPE; ++aST) {
962       TopTools_ListOfShape::Iterator anIt(aConnectedShapes);
963       while (anIt.More()) {
964         if (anIt.Value().ShapeType() == aST) {
965           aSortedGroup.Add(anIt.Value());
966           aConnectedShapes.Remove(anIt);
967         }
968         else {
969           anIt.Next();
970         }
971       }
972     }
973     aGroups.Append(aSortedGroup);
974   }
975
976   TopoDS_Compound aCompound;
977   BRep_Builder aBuilder;
978   aBuilder.MakeCompound(aCompound);
979   ListOfShape aSolids;
980   for (NCollection_Vector<TopTools_MapOfShape>::Iterator anIt(aGroups); anIt.More(); anIt.Next()) {
981     const TopTools_MapOfShape& aGroup = anIt.ChangeValue();
982     GeomShapePtr aGeomShape(new GeomAPI_Shape());
983     if (aGroup.Size() == 1) {
984       TopTools_MapOfShape::Iterator aOneShapeIter(aGroup);
985       aGeomShape->setImpl(new TopoDS_Shape(aOneShapeIter.Value()));
986     } else {
987       // make sub-shapes in the group have order same as in original shape
988       TopTools_ListOfShape anOrderedGoup;
989       NCollection_List<TopoDS_Shape>::Iterator anUngrouped(anUngroupedShapes);
990       for (; anUngrouped.More(); anUngrouped.Next()) {
991         if (aGroup.Contains(anUngrouped.Value()))
992           anOrderedGoup.Append(anUngrouped.Value());
993       }
994       aGeomShape->setImpl(new TopoDS_Shape(makeCompound(anOrderedGoup)));
995       aGeomShape = GeomAlgoAPI_ShapeTools::combineShapes(aGeomShape,
996                                                          GeomAPI_Shape::COMPSOLID,
997                                                          aSolids);
998     }
999     aBuilder.Add(aCompound, aGeomShape->impl<TopoDS_Shape>());
1000   }
1001
1002   if (!aCompound.IsNull()) {
1003     aResult->setImpl(new TopoDS_Shape(aCompound));
1004   }
1005
1006   return aResult;
1007 }
1008
1009 //==================================================================================================
1010 bool GeomAlgoAPI_ShapeTools::hasSharedTopology(const ListOfShape& theShapes,
1011                                                const GeomAPI_Shape::ShapeType theShapeType)
1012 {
1013   TopTools_IndexedMapOfShape aSubs;
1014   for (ListOfShape::const_iterator anIt = theShapes.begin(); anIt != theShapes.end(); ++anIt) {
1015     TopTools_IndexedMapOfShape aCurSubs;
1016     TopExp::MapShapes((*anIt)->impl<TopoDS_Shape>(), (TopAbs_ShapeEnum)theShapeType, aCurSubs);
1017     for (TopTools_IndexedMapOfShape::Iterator aSubIt(aCurSubs); aSubIt.More(); aSubIt.Next()) {
1018       if (aSubs.Contains(aSubIt.Value()))
1019         return true;
1020       else
1021         aSubs.Add(aSubIt.Value());
1022     }
1023   }
1024   return false;
1025 }
1026
1027 //==================================================================================================
1028 std::list<std::shared_ptr<GeomAPI_Pnt> >
1029   GeomAlgoAPI_ShapeTools::getBoundingBox(const ListOfShape& theShapes, const double theEnlarge)
1030 {
1031   // Bounding box of all objects.
1032   Bnd_Box aBndBox;
1033
1034   // Getting box.
1035   for (ListOfShape::const_iterator
1036     anObjectsIt = theShapes.begin(); anObjectsIt != theShapes.end(); anObjectsIt++) {
1037     const TopoDS_Shape& aShape = (*anObjectsIt)->impl<TopoDS_Shape>();
1038     BRepBndLib::Add(aShape, aBndBox);
1039   }
1040
1041   if (theEnlarge != 0.0) {
1042     // We enlarge bounding box just to be sure that plane will be large enough to cut all objects.
1043     aBndBox.Enlarge(theEnlarge);
1044   }
1045
1046   Standard_Real aXArr[2] = {aBndBox.CornerMin().X(), aBndBox.CornerMax().X()};
1047   Standard_Real aYArr[2] = {aBndBox.CornerMin().Y(), aBndBox.CornerMax().Y()};
1048   Standard_Real aZArr[2] = {aBndBox.CornerMin().Z(), aBndBox.CornerMax().Z()};
1049   std::list<std::shared_ptr<GeomAPI_Pnt> > aResultPoints;
1050   for (int i = 0; i < 2; i++) {
1051     for (int j = 0; j < 2; j++) {
1052       for (int k = 0; k < 2; k++) {
1053         std::shared_ptr<GeomAPI_Pnt> aPnt(new GeomAPI_Pnt(aXArr[i], aYArr[j], aZArr[k]));
1054         aResultPoints.push_back(aPnt);
1055       }
1056     }
1057   }
1058
1059   return aResultPoints;
1060 }
1061
1062 //==================================================================================================
1063 std::shared_ptr<GeomAPI_Face> GeomAlgoAPI_ShapeTools::fitPlaneToBox(
1064   const std::shared_ptr<GeomAPI_Shape> thePlane,
1065   const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints)
1066 {
1067   std::shared_ptr<GeomAPI_Face> aResultFace;
1068
1069   if (!thePlane.get()) {
1070     return aResultFace;
1071   }
1072
1073   const TopoDS_Shape& aShape = thePlane->impl<TopoDS_Shape>();
1074   if (aShape.ShapeType() != TopAbs_FACE) {
1075     return aResultFace;
1076   }
1077
1078   TopoDS_Face aFace = TopoDS::Face(aShape);
1079   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace);
1080   if (aSurf.IsNull()) {
1081     return aResultFace;
1082   }
1083
1084   GeomLib_IsPlanarSurface isPlanar(aSurf);
1085   if (!isPlanar.IsPlanar()) {
1086     return aResultFace;
1087   }
1088
1089   if (thePoints.size() != 8) {
1090     return aResultFace;
1091   }
1092
1093   const gp_Pln& aFacePln = isPlanar.Plan();
1094   Handle(Geom_Plane) aFacePlane = new Geom_Plane(aFacePln);
1095   IntAna_Quadric aQuadric(aFacePln);
1096   Standard_Real UMin, UMax, VMin, VMax;
1097   UMin = UMax = VMin = VMax = 0;
1098   for (std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator
1099        aPointsIt = thePoints.begin(); aPointsIt != thePoints.end(); aPointsIt++) {
1100     const gp_Pnt& aPnt = (*aPointsIt)->impl<gp_Pnt>();
1101     gp_Lin aLin(aPnt, aFacePln.Axis().Direction());
1102     IntAna_IntConicQuad anIntAna(aLin, aQuadric);
1103     const gp_Pnt& aPntOnFace = anIntAna.Point(1);
1104     Standard_Real aPntU(0), aPntV(0);
1105     GeomLib_Tool::Parameters(aFacePlane, aPntOnFace, Precision::Confusion(), aPntU, aPntV);
1106     if (aPntU < UMin) UMin = aPntU;
1107     if (aPntU > UMax) UMax = aPntU;
1108     if (aPntV < VMin) VMin = aPntV;
1109     if (aPntV > VMax) VMax = aPntV;
1110   }
1111   aResultFace.reset(new GeomAPI_Face());
1112   aResultFace->setImpl(new TopoDS_Face(BRepLib_MakeFace(aFacePln, UMin, UMax, VMin, VMax).Face()));
1113
1114   return aResultFace;
1115 }
1116
1117 //==================================================================================================
1118 void GeomAlgoAPI_ShapeTools::findBounds(const std::shared_ptr<GeomAPI_Shape> theShape,
1119                                         std::shared_ptr<GeomAPI_Vertex>& theV1,
1120                                         std::shared_ptr<GeomAPI_Vertex>& theV2)
1121 {
1122   static GeomVertexPtr aVertex;
1123   if (!aVertex) {
1124     aVertex = GeomVertexPtr(new GeomAPI_Vertex);
1125     aVertex->setImpl(new TopoDS_Vertex());
1126   }
1127
1128   theV1 = aVertex;
1129   theV2 = aVertex;
1130
1131   if (theShape) {
1132     const TopoDS_Shape& aShape = theShape->impl<TopoDS_Shape>();
1133     TopoDS_Vertex aV1, aV2;
1134     ShapeAnalysis::FindBounds(aShape, aV1, aV2);
1135
1136     std::shared_ptr<GeomAPI_Vertex> aGeomV1(new GeomAPI_Vertex()), aGeomV2(new GeomAPI_Vertex());
1137     aGeomV1->setImpl(new TopoDS_Vertex(aV1));
1138     aGeomV2->setImpl(new TopoDS_Vertex(aV2));
1139     theV1 = aGeomV1;
1140     theV2 = aGeomV2;
1141   }
1142 }
1143
1144 //==================================================================================================
1145 void GeomAlgoAPI_ShapeTools::makeFacesWithHoles(const std::shared_ptr<GeomAPI_Pnt> theOrigin,
1146                                                 const std::shared_ptr<GeomAPI_Dir> theDirection,
1147                                                 const ListOfShape& theWires,
1148                                                 ListOfShape& theFaces)
1149 {
1150   BRepBuilderAPI_MakeFace aMKFace(gp_Pln(theOrigin->impl<gp_Pnt>(),
1151                                           theDirection->impl<gp_Dir>()));
1152   TopoDS_Face aFace = aMKFace.Face();
1153
1154   BRepAlgo_FaceRestrictor aFRestrictor;
1155   aFRestrictor.Init(aFace, Standard_False, Standard_True);
1156   for (ListOfShape::const_iterator anIt = theWires.cbegin();
1157       anIt != theWires.cend();
1158       ++anIt) {
1159     TopoDS_Wire aWire = TopoDS::Wire((*anIt)->impl<TopoDS_Shape>());
1160     aFRestrictor.Add(aWire);
1161   }
1162
1163   aFRestrictor.Perform();
1164
1165   if (!aFRestrictor.IsDone()) {
1166     return;
1167   }
1168
1169   for (; aFRestrictor.More(); aFRestrictor.Next()) {
1170     GeomShapePtr aShape(new GeomAPI_Shape());
1171     aShape->setImpl(new TopoDS_Shape(aFRestrictor.Current()));
1172     theFaces.push_back(aShape);
1173   }
1174 }
1175
1176 //==================================================================================================
1177 std::shared_ptr<GeomAPI_Pln> GeomAlgoAPI_ShapeTools::findPlane(const ListOfShape& theShapes)
1178 {
1179   TopoDS_Compound aCompound;
1180   BRep_Builder aBuilder;
1181   aBuilder.MakeCompound(aCompound);
1182
1183   for (ListOfShape::const_iterator anIt = theShapes.cbegin(); anIt != theShapes.cend(); ++anIt) {
1184     aBuilder.Add(aCompound, (*anIt)->impl<TopoDS_Shape>());
1185   }
1186   BRepBuilderAPI_FindPlane aFindPlane(aCompound);
1187
1188   if (aFindPlane.Found() != Standard_True) {
1189     return std::shared_ptr<GeomAPI_Pln>();
1190   }
1191
1192   Handle(Geom_Plane) aPlane = aFindPlane.Plane();
1193   gp_Pnt aLoc = aPlane->Location();
1194   gp_Dir aDir = aPlane->Axis().Direction();
1195
1196   std::shared_ptr<GeomAPI_Pnt> aGeomPnt(new GeomAPI_Pnt(aLoc.X(), aLoc.Y(), aLoc.Z()));
1197   std::shared_ptr<GeomAPI_Dir> aGeomDir(new GeomAPI_Dir(aDir.X(), aDir.Y(), aDir.Z()));
1198
1199   std::shared_ptr<GeomAPI_Pln> aPln(new GeomAPI_Pln(aGeomPnt, aGeomDir));
1200
1201   return aPln;
1202 }
1203
1204 //==================================================================================================
1205 bool GeomAlgoAPI_ShapeTools::isSubShapeInsideShape(
1206   const std::shared_ptr<GeomAPI_Shape> theSubShape,
1207   const std::shared_ptr<GeomAPI_Shape> theBaseShape)
1208 {
1209   if (!theSubShape.get() || !theBaseShape.get()) {
1210     return false;
1211   }
1212
1213   const TopoDS_Shape& aSubShape = theSubShape->impl<TopoDS_Shape>();
1214   const TopoDS_Shape& aBaseShape = theBaseShape->impl<TopoDS_Shape>();
1215
1216   if (aSubShape.ShapeType() == TopAbs_VERTEX) {
1217     // If sub-shape is a vertex check distance to shape. If it is <= Precision::Confusion() then OK.
1218     BRepExtrema_DistShapeShape aDist(aBaseShape, aSubShape);
1219     aDist.Perform();
1220     if (!aDist.IsDone() || aDist.Value() > Precision::Confusion()) {
1221       return false;
1222     }
1223   } else if (aSubShape.ShapeType() == TopAbs_EDGE) {
1224     if (aBaseShape.ShapeType() == TopAbs_FACE) {
1225       // Check that edge is on face surface.
1226       TopoDS_Face aFace = TopoDS::Face(aBaseShape);
1227       TopoDS_Edge anEdge = TopoDS::Edge(aSubShape);
1228       BRepLib_CheckCurveOnSurface aCheck(anEdge, aFace);
1229       aCheck.Perform();
1230       if (!aCheck.IsDone() || aCheck.MaxDistance() > Precision::Confusion()) {
1231         return false;
1232       }
1233
1234       // Check intersections.
1235       TopoDS_Vertex aV1, aV2;
1236       ShapeAnalysis::FindBounds(anEdge, aV1, aV2);
1237       gp_Pnt aPnt1 = BRep_Tool::Pnt(aV1);
1238       gp_Pnt aPnt2 = BRep_Tool::Pnt(aV2);
1239       for (TopExp_Explorer anExp(aBaseShape, TopAbs_EDGE); anExp.More(); anExp.Next()) {
1240         const TopoDS_Shape& anEdgeOnFace = anExp.Current();
1241         BRepExtrema_DistShapeShape aDist(anEdgeOnFace, anEdge);
1242         aDist.Perform();
1243         if (aDist.IsDone() && aDist.Value() <= Precision::Confusion()) {
1244           // Edge intersect face bound. Check that it is not on edge begin or end.
1245           for (Standard_Integer anIndex = 1; anIndex <= aDist.NbSolution(); ++anIndex) {
1246             gp_Pnt aPntOnSubShape = aDist.PointOnShape2(anIndex);
1247             if (aPntOnSubShape.Distance(aPnt1) > Precision::Confusion()
1248                 && aPntOnSubShape.Distance(aPnt2) > Precision::Confusion()) {
1249               return false;
1250             }
1251           }
1252         }
1253       }
1254
1255       // No intersections found. Edge is inside or outside face. Check it.
1256       BRepAdaptor_Curve aCurveAdaptor(anEdge);
1257       gp_Pnt aPointToCheck =
1258         aCurveAdaptor.Value((aCurveAdaptor.FirstParameter() +
1259                               aCurveAdaptor.LastParameter()) / 2.0);
1260       Handle(Geom_Surface) aSurface = BRep_Tool::Surface(aFace);
1261       ShapeAnalysis_Surface aSAS(aSurface);
1262       gp_Pnt2d aPointOnFace = aSAS.ValueOfUV(aPointToCheck, Precision::Confusion());
1263       BRepTopAdaptor_FClass2d aFClass2d(aFace, Precision::Confusion());
1264       if (aFClass2d.Perform(aPointOnFace) == TopAbs_OUT) {
1265         return false;
1266       }
1267
1268     } else {
1269       return false;
1270     }
1271   } else {
1272     return false;
1273   }
1274
1275   return true;
1276 }
1277
1278 //==================================================================================================
1279 bool GeomAlgoAPI_ShapeTools::isShapeValid(const std::shared_ptr<GeomAPI_Shape> theShape)
1280 {
1281   if (!theShape.get()) {
1282     return false;
1283   }
1284
1285   BRepCheck_Analyzer aChecker(theShape->impl<TopoDS_Shape>());
1286   return (aChecker.IsValid() == Standard_True);
1287 }
1288
1289 //==================================================================================================
1290 std::shared_ptr<GeomAPI_Shape>
1291   GeomAlgoAPI_ShapeTools::getFaceOuterWire(const std::shared_ptr<GeomAPI_Shape> theFace)
1292 {
1293   GeomShapePtr anOuterWire;
1294
1295   if (!theFace.get() || !theFace->isFace()) {
1296     return anOuterWire;
1297   }
1298
1299   TopoDS_Face aFace = TopoDS::Face(theFace->impl<TopoDS_Shape>());
1300   TopoDS_Wire aWire = BRepTools::OuterWire(aFace);
1301
1302   anOuterWire.reset(new GeomAPI_Shape());
1303   anOuterWire->setImpl(new TopoDS_Shape(aWire));
1304
1305   return anOuterWire;
1306 }
1307
1308 //==================================================================================================
1309 static bool boundaryOfEdge(const std::shared_ptr<GeomAPI_Edge> theEdge,
1310                           const std::shared_ptr<GeomAPI_Vertex> theVertex,
1311                           double& theParam)
1312 {
1313   GeomPointPtr aPoint = theVertex->point();
1314   GeomPointPtr aFirstPnt = theEdge->firstPoint();
1315   double aFirstPntTol = theEdge->firstPointTolerance();
1316   GeomPointPtr aLastPnt = theEdge->lastPoint();
1317   double aLastPntTol = theEdge->lastPointTolerance();
1318
1319   double aFirst, aLast;
1320   theEdge->getRange(aFirst, aLast);
1321
1322   bool isFirst = aPoint->distance(aFirstPnt) <= aFirstPntTol;
1323   bool isLast = aPoint->distance(aLastPnt) <= aLastPntTol;
1324   if (isFirst)
1325     theParam = aFirst;
1326   else if (isLast)
1327     theParam = aLast;
1328
1329   return isFirst != isLast;
1330 }
1331
1332 bool GeomAlgoAPI_ShapeTools::isTangent(const std::shared_ptr<GeomAPI_Edge> theEdge1,
1333                                        const std::shared_ptr<GeomAPI_Edge> theEdge2,
1334                                        const std::shared_ptr<GeomAPI_Vertex> theTgPoint)
1335 {
1336   double aParE1 = 0, aParE2 = 0;
1337   if (!boundaryOfEdge(theEdge1, theTgPoint, aParE1) ||
1338       !boundaryOfEdge(theEdge2, theTgPoint, aParE2))
1339     return false;
1340
1341   BRepAdaptor_Curve aC1(theEdge1->impl<TopoDS_Edge>());
1342   BRepAdaptor_Curve aC2(theEdge2->impl<TopoDS_Edge>());
1343   return BRepLProp::Continuity(aC1, aC2, aParE1, aParE2) >= GeomAbs_G1;
1344 }
1345
1346 //==================================================================================================
1347 bool GeomAlgoAPI_ShapeTools::isParallel(const std::shared_ptr<GeomAPI_Edge> theEdge,
1348                                         const std::shared_ptr<GeomAPI_Face> theFace)
1349 {
1350   if (!theEdge.get() || !theFace.get()) {
1351     return false;
1352   }
1353
1354   TopoDS_Edge anEdge = TopoDS::Edge(theEdge->impl<TopoDS_Shape>());
1355   TopoDS_Face aFace  = TopoDS::Face(theFace->impl<TopoDS_Shape>());
1356
1357   BRepExtrema_ExtCF anExt(anEdge, aFace);
1358   return anExt.IsParallel() == Standard_True;
1359 }
1360
1361 //==================================================================================================
1362 std::list<std::shared_ptr<GeomAPI_Vertex> > GeomAlgoAPI_ShapeTools::intersect(
1363   const std::shared_ptr<GeomAPI_Edge> theEdge, const std::shared_ptr<GeomAPI_Face> theFace)
1364 {
1365   std::list<std::shared_ptr<GeomAPI_Vertex> > aResult;
1366   if (!theEdge.get() || !theFace.get()) {
1367     return aResult;
1368   }
1369
1370   TopoDS_Edge anEdge = TopoDS::Edge(theEdge->impl<TopoDS_Shape>());
1371   double aFirstOnCurve, aLastOnCurve;
1372   Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirstOnCurve, aLastOnCurve);
1373
1374   TopoDS_Face aFace  = TopoDS::Face(theFace->impl<TopoDS_Shape>());
1375   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace);
1376
1377   GeomAPI_IntCS anIntAlgo(aCurve, aSurf);
1378   if (!anIntAlgo.IsDone())
1379     return aResult;
1380   // searching for points-intersection
1381   for (int anIntNum = 1; anIntNum <= anIntAlgo.NbPoints() + anIntAlgo.NbSegments(); anIntNum++) {
1382     gp_Pnt anInt;
1383     if (anIntNum <= anIntAlgo.NbPoints()) {
1384       anInt = anIntAlgo.Point(anIntNum);
1385     } else { // take the middle point on the segment of the intersection
1386       Handle(Geom_Curve) anIntCurve = anIntAlgo.Segment(anIntNum - anIntAlgo.NbPoints());
1387       anIntCurve->D0((anIntCurve->FirstParameter() + anIntCurve->LastParameter()) / 2., anInt);
1388     }
1389     aResult.push_back(std::shared_ptr<GeomAPI_Vertex>(
1390       new GeomAPI_Vertex(anInt.X(), anInt.Y(), anInt.Z())));
1391   }
1392   return aResult;
1393 }
1394
1395 //==================================================================================================
1396 void GeomAlgoAPI_ShapeTools::splitShape(const std::shared_ptr<GeomAPI_Shape>& theBaseShape,
1397                                       const GeomAlgoAPI_ShapeTools::PointToRefsMap& thePointsInfo,
1398                                       std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
1399 {
1400   // to split shape at least one point should be presented in the points container
1401   if (thePointsInfo.empty())
1402     return;
1403
1404     // General Fuse to split edge by vertices
1405   BOPAlgo_Builder aBOP;
1406   TopoDS_Edge aBaseEdge = theBaseShape->impl<TopoDS_Edge>();
1407   // Rebuild closed edge to place vertex to one of split points.
1408   // This will prevent edge to be split on same vertex.
1409   if (BRep_Tool::IsClosed(aBaseEdge))
1410   {
1411     Standard_Real aFirst, aLast;
1412     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aBaseEdge, aFirst, aLast);
1413
1414     PointToRefsMap::const_iterator aPIt = thePointsInfo.begin();
1415     std::shared_ptr<GeomAPI_Pnt> aPnt = aPIt->first;
1416     gp_Pnt aPoint(aPnt->x(), aPnt->y(), aPnt->z());
1417
1418     TopAbs_Orientation anOrientation = aBaseEdge.Orientation();
1419     aBaseEdge = BRepBuilderAPI_MakeEdge(aCurve, aPoint, aPoint).Edge();
1420     aBaseEdge.Orientation(anOrientation);
1421   }
1422   aBOP.AddArgument(aBaseEdge);
1423
1424   PointToRefsMap::const_iterator aPIt = thePointsInfo.begin();
1425   for (; aPIt != thePointsInfo.end(); ++aPIt) {
1426     std::shared_ptr<GeomAPI_Pnt> aPnt = aPIt->first;
1427     TopoDS_Vertex aV = BRepBuilderAPI_MakeVertex(gp_Pnt(aPnt->x(), aPnt->y(), aPnt->z()));
1428     aBOP.AddArgument(aV);
1429   }
1430
1431   aBOP.Perform();
1432   if (aBOP.HasErrors())
1433     return;
1434
1435   // Collect splits
1436   const TopTools_ListOfShape& aSplits = aBOP.Modified(aBaseEdge);
1437   TopTools_ListIteratorOfListOfShape anIt(aSplits);
1438   for (; anIt.More(); anIt.Next()) {
1439     std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
1440     anEdge->setImpl(new TopoDS_Shape(anIt.Value()));
1441     theShapes.insert(anEdge);
1442   }
1443 }
1444
1445 //==================================================================================================
1446 void GeomAlgoAPI_ShapeTools::splitShape_p(const std::shared_ptr<GeomAPI_Shape>& theBaseShape,
1447                                           const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
1448                                           std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
1449 {
1450   // General Fuse to split edge by vertices
1451   BOPAlgo_Builder aBOP;
1452   TopoDS_Edge aBaseEdge = theBaseShape->impl<TopoDS_Edge>();
1453   // Rebuild closed edge to place vertex to one of split points.
1454   // This will prevent edge to be split on seam vertex.
1455   if (BRep_Tool::IsClosed(aBaseEdge))
1456   {
1457     Standard_Real aFirst, aLast;
1458     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aBaseEdge, aFirst, aLast);
1459
1460     std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPIt = thePoints.begin();
1461     gp_Pnt aPoint((*aPIt)->x(), (*aPIt)->y(), (*aPIt)->z());
1462
1463     TopAbs_Orientation anOrientation = aBaseEdge.Orientation();
1464     aBaseEdge = BRepBuilderAPI_MakeEdge(aCurve, aPoint, aPoint).Edge();
1465     aBaseEdge.Orientation(anOrientation);
1466   }
1467   aBOP.AddArgument(aBaseEdge);
1468
1469   std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPtIt = thePoints.begin();
1470   for (; aPtIt != thePoints.end(); ++aPtIt) {
1471     std::shared_ptr<GeomAPI_Pnt> aPnt = *aPtIt;
1472     TopoDS_Vertex aV = BRepBuilderAPI_MakeVertex(gp_Pnt(aPnt->x(), aPnt->y(), aPnt->z()));
1473     aBOP.AddArgument(aV);
1474   }
1475
1476   aBOP.Perform();
1477   if (aBOP.HasErrors())
1478     return;
1479
1480   // Collect splits
1481   const TopTools_ListOfShape& aSplits = aBOP.Modified(aBaseEdge);
1482   TopTools_ListIteratorOfListOfShape anIt(aSplits);
1483   for (; anIt.More(); anIt.Next()) {
1484     std::shared_ptr<GeomAPI_Shape> anEdge(new GeomAPI_Shape);
1485     anEdge->setImpl(new TopoDS_Shape(anIt.Value()));
1486     theShapes.insert(anEdge);
1487   }
1488 }
1489
1490 //==================================================================================================
1491 std::shared_ptr<GeomAPI_Shape> GeomAlgoAPI_ShapeTools::findShape(
1492                                   const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
1493                                   const std::set<std::shared_ptr<GeomAPI_Shape> >& theShapes)
1494 {
1495   std::shared_ptr<GeomAPI_Shape> aResultShape;
1496
1497   if (thePoints.size() == 2) {
1498     std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator aPntIt = thePoints.begin();
1499     std::shared_ptr<GeomAPI_Pnt> aFirstPoint = *aPntIt;
1500     aPntIt++;
1501     std::shared_ptr<GeomAPI_Pnt> aLastPoint = *aPntIt;
1502
1503     std::set<std::shared_ptr<GeomAPI_Shape> >::const_iterator anIt = theShapes.begin(),
1504                                                               aLast = theShapes.end();
1505     for (; anIt != aLast; anIt++) {
1506       GeomShapePtr aShape = *anIt;
1507       std::shared_ptr<GeomAPI_Edge> anEdge(new GeomAPI_Edge(aShape));
1508       if (anEdge.get()) {
1509         std::shared_ptr<GeomAPI_Pnt> anEdgeFirstPoint = anEdge->firstPoint();
1510         std::shared_ptr<GeomAPI_Pnt> anEdgeLastPoint = anEdge->lastPoint();
1511         if (anEdgeFirstPoint->isEqual(aFirstPoint) &&
1512             anEdgeLastPoint->isEqual(aLastPoint))
1513             aResultShape = aShape;
1514       }
1515     }
1516   }
1517
1518   return aResultShape;
1519 }
1520
1521 //==================================================================================================
1522 #ifdef FEATURE_MULTIROTATION_TWO_DIRECTIONS
1523 std::shared_ptr<GeomAPI_Dir> GeomAlgoAPI_ShapeTools::buildDirFromAxisAndShape(
1524                                     const std::shared_ptr<GeomAPI_Shape> theBaseShape,
1525                                     const std::shared_ptr<GeomAPI_Ax1> theAxis)
1526 {
1527   gp_Pnt aCentreOfMassPoint =
1528     GeomAlgoAPI_ShapeTools::centreOfMass(theBaseShape)->impl<gp_Pnt>();
1529   Handle(Geom_Line) aLine = new Geom_Line(theAxis->impl<gp_Ax1>());
1530   GeomAPI_ProjectPointOnCurve aPrjTool(aCentreOfMassPoint, aLine);
1531   gp_Pnt aPoint = aPrjTool.NearestPoint();
1532
1533   std::shared_ptr<GeomAPI_Dir> aDir(new GeomAPI_Dir(aCentreOfMassPoint.X()-aPoint.X(),
1534                                                     aCentreOfMassPoint.Y()-aPoint.Y(),
1535                                                     aCentreOfMassPoint.Z()-aPoint.Z()));
1536   return aDir;
1537 }
1538 #endif
1539
1540 //==================================================================================================
1541 static TopoDS_Wire fixParametricGaps(const TopoDS_Wire& theWire)
1542 {
1543   TopoDS_Wire aFixedWire;
1544   Handle(Geom_Curve) aPrevCurve;
1545   double aPrevLastParam = -Precision::Infinite();
1546
1547   BRep_Builder aBuilder;
1548   aBuilder.MakeWire(aFixedWire);
1549
1550   BRepTools_WireExplorer aWExp(theWire);
1551   for (; aWExp.More(); aWExp.Next()) {
1552     TopoDS_Edge anEdge = aWExp.Current();
1553     double aFirst, aLast;
1554     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aFirst, aLast);
1555     if (aCurve == aPrevCurve && Abs(aFirst - aPrevLastParam) > Precision::Confusion()) {
1556       // if parametric gap occurs, create new edge based on the copied curve
1557       aCurve = Handle(Geom_Curve)::DownCast(aCurve->Copy());
1558       TopoDS_Vertex aV1, aV2;
1559       TopExp::Vertices(anEdge, aV1, aV2);
1560       anEdge = TopoDS::Edge(anEdge.EmptyCopied());
1561       aBuilder.UpdateEdge(anEdge, aCurve, BRep_Tool::Tolerance(anEdge));
1562       aBuilder.Add(anEdge, aV1);
1563       aBuilder.Add(anEdge, aV2);
1564     }
1565
1566     aBuilder.Add(aFixedWire, anEdge);
1567
1568     aPrevCurve = aCurve;
1569     aPrevLastParam = aLast;
1570   }
1571
1572   return aFixedWire;
1573 }
1574
1575 //==================================================================================================
1576 std::shared_ptr<GeomAPI_Edge> GeomAlgoAPI_ShapeTools::wireToEdge(
1577       const std::shared_ptr<GeomAPI_Wire>& theWire)
1578 {
1579   GeomEdgePtr anEdge;
1580   if (theWire) {
1581     TopoDS_Wire aWire = theWire->impl<TopoDS_Wire>();
1582     BRepTools_WireExplorer aWExp(aWire);
1583     TopoDS_Edge aNewEdge = aWExp.Current();
1584     aWExp.Next();
1585     if (aWExp.More()) {
1586       // Workaround for the closed wire to avoid jumping of its start point:
1587       // split this wire for two parts, convert them to edges, then compose together
1588       if (BRep_Tool::IsClosed(aWire)) {
1589         aWire = TopoDS::Wire(BRepBuilderAPI_Copy(aWire).Shape());
1590         aWExp.Init(aWire);
1591         aNewEdge = aWExp.Current();
1592
1593         BRep_Builder().Remove(aWire, aNewEdge);
1594         GeomWirePtr aSplitWire(new GeomAPI_Wire);
1595         aSplitWire->setImpl(new TopoDS_Wire(aWire));
1596         GeomEdgePtr aMergedEdge = wireToEdge(aSplitWire);
1597
1598         aWire = BRepBuilderAPI_MakeWire(aNewEdge, aMergedEdge->impl<TopoDS_Edge>());
1599       }
1600
1601       // Workaround: when concatenate a wire consisting of two edges based on the same B-spline
1602       // curve (non-periodic, but having equal start and end points), first of which is placed
1603       // at the end on the curve and second is placed at the start, this workaround copies
1604       // second curve to avoid treating these edges as a single curve by setting trim parameters.
1605       aWire = fixParametricGaps(aWire);
1606       aWire = BRepAlgo::ConcatenateWire(aWire, GeomAbs_G1); // join smooth parts of wire
1607       aNewEdge = BRepAlgo::ConcatenateWireC0(aWire); // join C0 parts of wire
1608
1609       // Reapproximate the result edge to have the parameter equal to curvilinear abscissa.
1610       static const int THE_MAX_DEGREE = 14;
1611       static const int THE_MAX_INTERVALS = 32;
1612       double aFirst, aLast;
1613       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(aNewEdge, aFirst, aLast);
1614 #if OCC_VERSION_LARGE < 0x07070000
1615       Handle(GeomAdaptor_HCurve) aHCurve = new GeomAdaptor_HCurve(aCurve);
1616 #else
1617       Handle(GeomAdaptor_Curve) aHCurve = new GeomAdaptor_Curve(aCurve);
1618 #endif
1619       Approx_CurvilinearParameter anApprox(aHCurve, Precision::Confusion(), aCurve->Continuity(),
1620                                            THE_MAX_DEGREE, THE_MAX_INTERVALS);
1621       if (anApprox.HasResult()) {
1622         Handle(Geom_BSplineCurve) aNewCurve = anApprox.Curve3d();
1623         TColStd_Array1OfReal aKnots = aNewCurve->Knots();
1624         BSplCLib::Reparametrize(aFirst, aLast, aKnots);
1625         aNewCurve->SetKnots(aKnots);
1626         BRep_Builder().UpdateEdge(aNewEdge, aNewCurve, BRep_Tool::Tolerance(aNewEdge));
1627       }
1628     }
1629     anEdge = GeomEdgePtr(new GeomAPI_Edge);
1630     anEdge->setImpl(new TopoDS_Edge(aNewEdge));
1631   }
1632   return anEdge;
1633 }
1634
1635 //==================================================================================================
1636 ListOfShape GeomAlgoAPI_ShapeTools::getLowLevelSubShapes(const GeomShapePtr& theShape)
1637 {
1638   ListOfShape aSubShapes;
1639
1640   if (!theShape->isCompound() && !theShape->isCompSolid() &&
1641       !theShape->isShell() && !theShape->isWire()) {
1642     return aSubShapes;
1643   }
1644
1645   for (GeomAPI_ShapeIterator anIt(theShape); anIt.more(); anIt.next()) {
1646     GeomShapePtr aSubShape = anIt.current();
1647     if (aSubShape->isVertex() || aSubShape->isEdge() ||
1648         aSubShape->isFace() || aSubShape->isSolid()) {
1649       aSubShapes.push_back(aSubShape);
1650     } else {
1651       aSubShapes.splice(aSubShapes.end(), getLowLevelSubShapes(aSubShape));
1652     }
1653   }
1654
1655   return aSubShapes;
1656 }
1657
1658 //==================================================================================================
1659 static void getMinMaxPointsOnLine(const std::list<std::shared_ptr<GeomAPI_Pnt> >& thePoints,
1660                                   const gp_Dir theDir,
1661                                   double& theMin, double& theMax)
1662 {
1663   theMin = RealLast();
1664   theMax = RealFirst();
1665   // Project bounding points on theDir
1666   for (std::list<std::shared_ptr<GeomAPI_Pnt> >::const_iterator
1667          aPointsIt = thePoints.begin(); aPointsIt != thePoints.end(); aPointsIt++) {
1668     const gp_Pnt& aPnt = (*aPointsIt)->impl<gp_Pnt>();
1669     gp_Dir aPntDir (aPnt.XYZ());
1670     Standard_Real proj = (theDir*aPntDir) * aPnt.XYZ().Modulus();
1671     if (proj < theMin) theMin = proj;
1672     if (proj > theMax) theMax = proj;
1673   }
1674 }
1675
1676 //==================================================================================================
1677 void GeomAlgoAPI_ShapeTools::computeThroughAll(const ListOfShape& theObjects,
1678                                                const ListOfShape& theBaseShapes,
1679                                                const std::shared_ptr<GeomAPI_Dir> theDir,
1680                                                double& theToSize, double& theFromSize)
1681 {
1682   // Bounding box of objects
1683   std::list<std::shared_ptr<GeomAPI_Pnt> > aBndObjs =
1684       GeomAlgoAPI_ShapeTools::getBoundingBox(theObjects);
1685   if (aBndObjs.size() != 8) {
1686     return;
1687   }
1688
1689   // the value to enlarge the bounding box of each object to make the extruded shape
1690   // a little bit larger than overall objects to get the correct result of Boolean CUT operation
1691   double anEnlargement = 0.1 * aBndObjs.front()->distance(aBndObjs.back());
1692
1693   // Prism direction
1694   if (theDir.get()) {
1695     // One direction for all prisms
1696     gp_Dir aDir = theDir->impl<gp_Dir>();
1697
1698     // Bounding box of the base
1699     std::list<std::shared_ptr<GeomAPI_Pnt> > aBndBases =
1700         GeomAlgoAPI_ShapeTools::getBoundingBox(theBaseShapes);
1701     if (aBndBases.size() != 8) {
1702       return;
1703     }
1704
1705     // Objects bounds
1706     Standard_Real lowBnd, upperBnd;
1707     getMinMaxPointsOnLine(aBndObjs, aDir, lowBnd, upperBnd);
1708
1709     // Base bounds
1710     Standard_Real lowBase, upperBase;
1711     getMinMaxPointsOnLine(aBndBases, aDir, lowBase, upperBase);
1712
1713     // ----------.-----.---------.--------------.-----------> theDir
1714     //       lowBnd   lowBase   upperBase    upperBnd
1715
1716     theToSize = upperBnd - lowBase;
1717     theFromSize = upperBase - lowBnd;
1718   } else {
1719     // Direction is a normal to each base shape (different normals to bases)
1720     // So we calculate own sizes for each base shape
1721     theToSize = 0.0;
1722     theFromSize = 0.0;
1723
1724     for (ListOfShape::const_iterator anIt = theBaseShapes.begin();
1725          anIt != theBaseShapes.end(); ++anIt) {
1726       const GeomShapePtr& aBaseShape_i = (*anIt);
1727       ListOfShape aBaseShapes_i;
1728       aBaseShapes_i.push_back(aBaseShape_i);
1729
1730       // Bounding box of the base
1731       std::list<std::shared_ptr<GeomAPI_Pnt> > aBndBases =
1732           GeomAlgoAPI_ShapeTools::getBoundingBox(aBaseShapes_i, anEnlargement);
1733       if (aBndBases.size() != 8) {
1734         return;
1735       }
1736
1737       // Direction (normal to aBaseShapes_i)
1738       // Code like in GeomAlgoAPI_Prism
1739       gp_Dir aDir;
1740       const TopoDS_Shape& aBaseShape = aBaseShape_i->impl<TopoDS_Shape>();
1741       BRepBuilderAPI_FindPlane aFindPlane(aBaseShape);
1742       if (aFindPlane.Found() == Standard_True) {
1743         Handle(Geom_Plane) aPlane;
1744         if (aBaseShape.ShapeType() == TopAbs_FACE || aBaseShape.ShapeType() == TopAbs_SHELL) {
1745           TopExp_Explorer anExp(aBaseShape, TopAbs_FACE);
1746           const TopoDS_Shape& aFace = anExp.Current();
1747           Handle(Geom_Surface) aSurface = BRep_Tool::Surface(TopoDS::Face(aFace));
1748           if (aSurface->DynamicType() == STANDARD_TYPE(Geom_RectangularTrimmedSurface)) {
1749             Handle(Geom_RectangularTrimmedSurface) aTrimSurface =
1750               Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurface);
1751             aSurface = aTrimSurface->BasisSurface();
1752           }
1753           if (aSurface->DynamicType() != STANDARD_TYPE(Geom_Plane)) {
1754             return;
1755           }
1756           aPlane = Handle(Geom_Plane)::DownCast(aSurface);
1757         } else {
1758           aPlane = aFindPlane.Plane();
1759         }
1760         aDir = aPlane->Axis().Direction();
1761       } else {
1762         return;
1763       }
1764
1765       // Objects bounds
1766       Standard_Real lowBnd, upperBnd;
1767       getMinMaxPointsOnLine(aBndObjs, aDir, lowBnd, upperBnd);
1768
1769       // Base bounds
1770       Standard_Real lowBase, upperBase;
1771       getMinMaxPointsOnLine(aBndBases, aDir, lowBase, upperBase);
1772
1773       // ----------.-----.---------.--------------.-----------> theDir
1774       //       lowBnd   lowBase   upperBase    upperBnd
1775
1776       double aToSize_i = upperBnd - lowBase;
1777       double aFromSize_i = upperBase - lowBnd;
1778
1779       if (aToSize_i > theToSize) theToSize = aToSize_i;
1780       if (aFromSize_i > theFromSize) theFromSize = aFromSize_i;
1781     }
1782   }
1783 }
1784
1785 ListOfShape GeomAlgoAPI_ShapeTools::getSharedFaces(const GeomShapePtr& theShape)
1786 {
1787   ListOfShape aSharedFaces;
1788   TopTools_IndexedDataMapOfShapeListOfShape aMapFS;
1789   TopExp::MapShapesAndUniqueAncestors(theShape->impl<TopoDS_Shape>(),
1790                                       TopAbs_FACE, TopAbs_SOLID, aMapFS);
1791   for (Standard_Integer i = 1; i <= aMapFS.Extent(); i++) {
1792     const TopTools_ListOfShape& ancestors = aMapFS.FindFromIndex(i);
1793     if (ancestors.Size() > 1) {
1794       GeomShapePtr aFace(new GeomAPI_Shape);
1795       aFace->setImpl<TopoDS_Shape>(new TopoDS_Shape(aMapFS.FindKey(i)));
1796       aSharedFaces.push_back(aFace);
1797     }
1798   }
1799   return aSharedFaces;
1800 }