Salome HOME
7054e59d0d9798be343044f845762cf451d4b679
[modules/geom.git] / src / BlockFix / BlockFix_SphereSpaceModifier.cxx
1 // Copyright (C) 2007-2023  CEA, EDF, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 // File:        BlockFix.cxx
24 // Created:     Tue Dec  7 11:59:05 2004
25 // Author:      Pavel DURANDIN
26
27 #include <BlockFix_SphereSpaceModifier.hxx>
28
29 #include <ShapeFix_Edge.hxx>
30
31 #include <TopExp.hxx>
32
33 #include <TopLoc_Location.hxx>
34
35 #include <TopoDS.hxx>
36 #include <TopoDS_Edge.hxx>
37 #include <TopoDS_Face.hxx>
38 #include <TopoDS_Vertex.hxx>
39 #include <TopoDS_Iterator.hxx>
40
41 #include <BRepGProp.hxx>
42 #include <GProp_GProps.hxx>
43
44 #include <BRep_Tool.hxx>
45 #include <BRep_Builder.hxx>
46 #include <BRepTools.hxx>
47 #include <BRepAdaptor_Curve2d.hxx>
48 #include <BRepTopAdaptor_FClass2d.hxx>
49 #include <BRepClass_FaceClassifier.hxx>
50
51 #include <ElSLib.hxx>
52 #include <Geom_Circle.hxx>
53 #include <Geom_TrimmedCurve.hxx>
54 #include <Geom_SphericalSurface.hxx>
55 #include <Geom_RectangularTrimmedSurface.hxx>
56 #include <Geom_Curve.hxx>
57 #include <Geom_Surface.hxx>
58
59 #include <Geom2d_Curve.hxx>
60
61 #include <gp_Pnt.hxx>
62 #include <gp_Sphere.hxx>
63
64 IMPLEMENT_STANDARD_RTTIEXT(BlockFix_SphereSpaceModifier, BRepTools_Modification)
65
66 //=======================================================================
67 //function : BlockFix_SphereSpaceModifier
68 //purpose  :
69 //=======================================================================
70 BlockFix_SphereSpaceModifier::BlockFix_SphereSpaceModifier()
71 : myTolerance(Precision::Confusion()),
72   mySmallRotation(Standard_True)
73 {
74   myMapOfFaces.Clear();
75   myMapOfSpheres.Clear();
76 }
77
78 //=======================================================================
79 //function : ~BlockFix_SphereSpaceModifier
80 //purpose  :
81 //=======================================================================
82 BlockFix_SphereSpaceModifier::~BlockFix_SphereSpaceModifier() {}
83
84 //=======================================================================
85 //function : SetTolerance
86 //purpose  :
87 //=======================================================================
88 void BlockFix_SphereSpaceModifier::SetTolerance(const Standard_Real Tol)
89 {
90   myTolerance = Tol;
91 }
92
93 //=======================================================================
94 //function : SetTrySmallRotation
95 //purpose  :
96 //=======================================================================
97 void BlockFix_SphereSpaceModifier::SetTrySmallRotation(const Standard_Boolean isSmallRotation)
98 {
99   mySmallRotation = isSmallRotation;
100 }
101
102 //=======================================================================
103 //function : NewSurface
104 //purpose  :
105 //=======================================================================
106 static Standard_Boolean ModifySurface(const TopoDS_Face&          theFace,
107                                       const Handle(Geom_Surface)& theSurface,
108                                       Handle(Geom_Surface)&       theNewSurface,
109                                       const Standard_Boolean      theTrySmallRotation)
110 {
111   Handle(Geom_Surface) aSurf = theSurface;
112   if (aSurf->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) {
113     Handle(Geom_RectangularTrimmedSurface) RTS =
114       Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurf);
115     aSurf = RTS->BasisSurface();
116   }
117
118   if (!aSurf->IsKind(STANDARD_TYPE(Geom_SphericalSurface)))
119     return Standard_False;
120
121   Standard_Real PI2 = M_PI/2.;
122   Handle(Geom_SphericalSurface) aSphere = Handle(Geom_SphericalSurface)::DownCast(aSurf);
123   gp_Sphere sp = aSphere->Sphere();
124   Standard_Real Radius = sp.Radius();
125   Standard_Real Umin, Umax, Vmin, Vmax;
126
127   // try with small rotation (old implementation, giving better result in some cases
128   if (theTrySmallRotation) {
129     BRepTools::UVBounds(theFace, Umin, Umax, Vmin, Vmax);
130     if (Vmax > PI2 - Precision::PConfusion() || Vmin < -PI2 + Precision::PConfusion()) {
131       //modified by jgv, 12.11.2012 for issue 21777//
132       Standard_Real HalfArea = 2.*M_PI*Radius*Radius;
133       GProp_GProps Properties;
134       BRepGProp::SurfaceProperties(theFace, Properties);
135       Standard_Real anArea = Properties.Mass();
136       Standard_Real AreaTol = Radius*Radius*1.e-6;
137       if (anArea < HalfArea - AreaTol) { // a chance to avoid singularity
138         gp_Ax3 ax3 = sp.Position();
139         if (Abs(Vmax-Vmin) < PI2) {
140           gp_Ax3 axnew3 (ax3.Axis().Location(), ax3.Direction()^ax3.XDirection(), ax3.XDirection());
141           sp.SetPosition(axnew3);
142           Handle(Geom_SphericalSurface) aNewSphere = new Geom_SphericalSurface(sp);
143           theNewSurface = aNewSphere;
144           return Standard_True;
145         }
146         else {
147           gp_Pnt PC = ax3.Location();
148           Standard_Real Vpar;
149           if (fabs(PI2-Vmax) > fabs(-PI2-Vmin))
150             Vpar = (PI2+Vmax)/2.;
151           else
152             Vpar = (-PI2+Vmin)/2.;
153           Standard_Real Upar = (Umin+Umax)/2.;
154           gp_Pnt PN,PX;
155           aSurf->D0(Upar,Vpar,PN);
156           aSurf->D0(Upar+PI2,0.,PX);
157           gp_Dir newNorm(gp_Vec(PC,PN));
158           gp_Dir newDirX(gp_Vec(PC,PX));
159           gp_Ax3 axnew3(ax3.Axis().Location(), newNorm, newDirX);
160           sp.SetPosition(axnew3);
161
162           // check if both new poles are outside theFace
163           gp_Pnt LP; // lowest pole (opposite to PN)
164           aSurf->D0(Upar + M_PI, -Vpar, LP);
165           BRepClass_FaceClassifier aClsf (theFace, LP, Precision::PConfusion());
166           if (aClsf.State() != TopAbs_IN && aClsf.State() != TopAbs_ON) {
167             Handle(Geom_SphericalSurface) aNewSphere = new Geom_SphericalSurface(sp);
168             theNewSurface = aNewSphere;
169             return Standard_True;
170           }
171         }
172       }
173     }
174     else {
175       // no rotation needed
176       return Standard_False;
177     }
178   }
179
180   // try with big rotation (new implementation)
181   TopoDS_Face aFace = theFace;
182   aFace.Orientation (TopAbs_FORWARD);
183   BRepTools::UVBounds(aFace, Umin, Umax, Vmin, Vmax);
184
185   gp_Pnt aCentre = sp.Location();
186
187   TopoDS_Wire aWire = BRepTools::OuterWire (aFace);
188   BRepTopAdaptor_FClass2d aClassifier (aFace, Precision::PConfusion());
189   TopTools_MapOfShape aEmap;
190   const Standard_Real anOffsetValue = 0.01*M_PI;
191   for (Standard_Integer ii = 1; ii <= 2; ii++) {
192     TopoDS_Iterator itw (aWire);
193     for (; itw.More(); itw.Next()) {
194       const TopoDS_Edge& anEdge = TopoDS::Edge (itw.Value());
195       if (aEmap.Contains (anEdge) ||
196           anEdge.Orientation() == TopAbs_INTERNAL ||
197           anEdge.Orientation() == TopAbs_EXTERNAL ||
198           BRep_Tool::Degenerated (anEdge) ||
199           BRepTools::IsReallyClosed (anEdge, aFace))
200         continue;
201
202       BRepAdaptor_Curve2d aBAcurve2d (anEdge, aFace);
203       GeomAbs_CurveType aType = aBAcurve2d.GetType();
204       if (ii == 1 && aType == GeomAbs_Line) //first pass: consider only curvilinear edges
205         continue;
206
207       Standard_Real aMidPar = (aBAcurve2d.FirstParameter() + aBAcurve2d.LastParameter())/2;
208       gp_Pnt2d aMidP2d;
209       gp_Vec2d aTangent;
210       aBAcurve2d.D1 (aMidPar, aMidP2d, aTangent);
211       if (anEdge.Orientation() == TopAbs_REVERSED)
212         aTangent.Reverse();
213
214       aTangent.Normalize();
215       gp_Vec2d aNormal (aTangent.Y(), -aTangent.X());
216       aNormal *= anOffsetValue;
217       gp_Pnt2d anUpperPole = aMidP2d.Translated (aNormal);
218       if (anUpperPole.Y() < -PI2 || anUpperPole.Y() > PI2) {
219         aEmap.Add(anEdge);
220         continue;
221       }
222       if (anUpperPole.X() < 0.)
223         anUpperPole.SetX (anUpperPole.X() + 2.*M_PI);
224       else if (anUpperPole.X() > 2.*M_PI)
225         anUpperPole.SetX (anUpperPole.X() - 2.*M_PI);
226
227       TopAbs_State aStatus = aClassifier.Perform (anUpperPole);
228       if (aStatus != TopAbs_OUT) {
229         aEmap.Add(anEdge);
230         continue;
231       }
232
233       gp_Pnt anUpperPole3d = aSphere->Value (anUpperPole.X(), anUpperPole.Y());
234       gp_Vec aVec (aCentre, anUpperPole3d);
235       aVec.Reverse();
236       gp_Pnt aLowerPole3d = aCentre.Translated (aVec);
237       Standard_Real aU, aV;
238       ElSLib::Parameters (sp, aLowerPole3d, aU, aV);
239       gp_Pnt2d aLowerPole (aU, aV);
240       aStatus = aClassifier.Perform (aLowerPole);
241       if (aStatus != TopAbs_OUT) {
242         aEmap.Add(anEdge);
243         continue;
244       }
245
246       //Build a meridian
247       gp_Vec anUp (aCentre, anUpperPole3d);
248       anUp.Normalize();
249       gp_Pnt aMidPnt = aSphere->Value (aMidP2d.X(), aMidP2d.Y());
250       gp_Vec aMidOnEdge (aCentre, aMidPnt);
251       aMidOnEdge.Normalize();
252       gp_Vec AxisOfCircle = anUp ^ aMidOnEdge;
253       gp_Vec XDirOfCircle = anUp ^ AxisOfCircle;
254       gp_Ax2 anAxis (aCentre, AxisOfCircle, XDirOfCircle);
255       Handle(Geom_Circle) aCircle = new Geom_Circle (anAxis, Radius);
256       Handle(Geom_TrimmedCurve) aMeridian = new Geom_TrimmedCurve (aCircle, -PI2, PI2);
257
258       //Check the meridian
259       Standard_Boolean IsInnerPointFound = Standard_False;
260       Standard_Integer NbSamples = 10;
261       Standard_Real aDelta = M_PI / NbSamples;
262       for (Standard_Integer jj = 1; jj < NbSamples; jj++) {
263         Standard_Real aParam = -PI2 + jj*aDelta;
264         gp_Pnt aPnt = aMeridian->Value (aParam);
265         ElSLib::Parameters (sp, aPnt, aU, aV);
266         gp_Pnt2d aP2d (aU, aV);
267         aStatus = aClassifier.Perform (aP2d);
268         if (aStatus != TopAbs_OUT) {
269           IsInnerPointFound = Standard_True;
270           break;
271         }
272       }
273       if (IsInnerPointFound) {
274         aEmap.Add(anEdge);
275         continue;
276       }
277
278       gp_Ax3 anAxisOfNewSphere (aCentre, anUp, XDirOfCircle);
279       theNewSurface = new Geom_SphericalSurface (anAxisOfNewSphere, Radius);
280       break;
281     } //for (; itw.More(); itw.Next()) (iteration on outer wire)
282     if (!theNewSurface.IsNull())
283       break;
284   } //for (Standard_Integer ii = 1; ii <= 2; ii++) (two passes)
285
286   return (!theNewSurface.IsNull());
287 }
288
289 Standard_Boolean BlockFix_SphereSpaceModifier::NewSurface(const TopoDS_Face& F,
290                                                           Handle(Geom_Surface)& S,
291                                                           TopLoc_Location& L,
292                                                           Standard_Real& Tol,
293                                                           Standard_Boolean& RevWires,
294                                                           Standard_Boolean& RevFace)
295 {
296   TopLoc_Location LS;
297   Handle(Geom_Surface) SIni = BRep_Tool::Surface(F, LS);
298
299   //check if pole of the sphere in the parametric space
300   if (ModifySurface(F, SIni, S, mySmallRotation)) {
301
302     RevWires = Standard_False;
303     RevFace = Standard_False;
304
305     L = LS;
306     Tol = BRep_Tool::Tolerance(F);
307
308     Standard_Integer anIndex = myMapOfSpheres.Add(S);
309     myMapOfFaces.Bind(F,anIndex);
310     return Standard_True;
311   }
312
313   return Standard_False;
314 }
315
316 //=======================================================================
317 //function : NewCurve
318 //purpose  :
319 //=======================================================================
320 Standard_Boolean BlockFix_SphereSpaceModifier::NewCurve(const TopoDS_Edge& /*E*/,Handle(Geom_Curve)& /*C*/,
321                                                         TopLoc_Location& /*L*/,Standard_Real& /*Tol*/)
322 {
323   return Standard_False;
324 }
325
326 //=======================================================================
327 //function : NewPoint
328 //purpose  :
329 //=======================================================================
330 Standard_Boolean BlockFix_SphereSpaceModifier::NewPoint(const TopoDS_Vertex& /*V*/,
331                                                       gp_Pnt& /*P*/,
332                                                       Standard_Real& /*Tol*/)
333 {
334   return Standard_False;
335 }
336
337 //=======================================================================
338 //function : NewCurve2d
339 //purpose  :
340 //=======================================================================
341 Standard_Boolean BlockFix_SphereSpaceModifier::NewCurve2d(const TopoDS_Edge& E,const TopoDS_Face& F,
342                                                         const TopoDS_Edge& /*NewE*/,const TopoDS_Face& /*NewF*/,
343                                                         Handle(Geom2d_Curve)& C,Standard_Real& Tol)
344 {
345   //check if undelying surface of the face was modified
346   if(myMapOfFaces.IsBound(F)) {
347     Standard_Integer anIndex = myMapOfFaces.Find(F);
348
349     Handle(Geom_Surface) aNewSphere = Handle(Geom_Surface)::DownCast(myMapOfSpheres.FindKey(anIndex));
350
351     Standard_Real f,l;
352     TopLoc_Location LC, LS;
353     Handle(Geom_Curve) C3d = BRep_Tool::Curve ( E, LC, f, l );
354     Handle(Geom_Surface) S = BRep_Tool::Surface(F, LS);
355
356     //taking into account the orientation of the seam
357     C = BRep_Tool::CurveOnSurface(E,F,f,l);
358     Tol = BRep_Tool::Tolerance(E);
359
360     BRep_Builder B;
361     TopoDS_Edge TempE;
362     B.MakeEdge(TempE);
363     B.Add(TempE, TopExp::FirstVertex(E));
364     B.Add(TempE, TopExp::LastVertex(E));
365
366     if(!C3d.IsNull())
367       B.UpdateEdge(TempE, Handle(Geom_Curve)::DownCast(C3d->Transformed(LC.Transformation())), Precision::Confusion());
368     B.Range(TempE, f, l);
369
370     Handle(ShapeFix_Edge) sfe = new ShapeFix_Edge;
371     Handle(Geom_Surface) STemp = Handle(Geom_Surface)::DownCast(aNewSphere->Transformed(LS.Transformation()));
372     TopLoc_Location LTemp;
373     LTemp.Identity();
374
375     Standard_Boolean isClosed = BRep_Tool::IsClosed (E, F);
376     Standard_Real aWorkTol = 2*myTolerance+Tol;
377     sfe->FixAddPCurve(TempE, STemp, LTemp, isClosed, Max(Precision::Confusion(), aWorkTol));
378     sfe->FixSameParameter(TempE);
379
380     //keep the orientation of original edge
381     TempE.Orientation(E.Orientation());
382     C = BRep_Tool::CurveOnSurface(TempE, STemp, LTemp, f, l);
383
384     // shifting seam of sphere
385     if(isClosed  && !C.IsNull()) {
386       Standard_Real f2,l2;
387       Handle(Geom2d_Curve) c22 =
388         BRep_Tool::CurveOnSurface(TopoDS::Edge(TempE.Reversed()),STemp, LTemp,f2,l2);
389       Standard_Real dPreci = Precision::PConfusion()*Precision::PConfusion();
390       if((C->Value(f).SquareDistance(c22->Value(f2)) < dPreci)
391          ||(C->Value(l).SquareDistance(c22->Value(l2)) < dPreci)) {
392         gp_Vec2d shift(S->UPeriod(),0.);
393         C->Translate(shift);
394       }
395     }
396     //sphere was modified
397     return Standard_True;
398   }
399
400   return Standard_False;
401 }
402
403 //=======================================================================
404 //function : NewParameter
405 //purpose  :
406 //=======================================================================
407 Standard_Boolean BlockFix_SphereSpaceModifier::NewParameter(const TopoDS_Vertex& /*V*/,const TopoDS_Edge& /*E*/,
408                                                             Standard_Real& /*P*/,Standard_Real& /*Tol*/)
409 {
410   return Standard_False;
411 }
412
413 //=======================================================================
414 //function : Continuity
415 //purpose  :
416 //=======================================================================
417 GeomAbs_Shape BlockFix_SphereSpaceModifier::Continuity(const TopoDS_Edge& E,const TopoDS_Face& F1,
418                                                      const TopoDS_Face& F2,const TopoDS_Edge& /*NewE*/,
419                                                      const TopoDS_Face& /*NewF1*/,const TopoDS_Face& /*NewF2*/)
420 {
421   return BRep_Tool::Continuity(E,F1,F2);
422 }