Salome HOME
Changes for bug 20589 from Mantis.
[modules/geom.git] / src / GEOMAlgo / BlockFix_UnionEdges.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, 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.
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 // File:      BlockFix_UnionEdges.cxx
23 // Created:   07.12.04 15:27:30
24 // Author:    Sergey KUUL
25
26 #include <BlockFix_UnionEdges.ixx>
27
28 #include <Approx_Curve3d.hxx>
29 #include <BRepAdaptor_HCompCurve.hxx>
30 #include <BRep_Builder.hxx>
31 #include <BRep_Tool.hxx>
32 #include <GC_MakeCircle.hxx>
33 #include <Geom_BSplineCurve.hxx>
34 #include <Geom_Circle.hxx>
35 #include <Geom_Curve.hxx>
36 #include <Geom_Line.hxx>
37 #include <Geom_TrimmedCurve.hxx>
38 #include <ShapeAnalysis_Edge.hxx>
39 #include <ShapeFix_Edge.hxx>
40 #include <ShapeFix_Face.hxx>
41 #include <ShapeFix_Shell.hxx>
42 #include <TColgp_SequenceOfPnt.hxx>
43 #include <TColStd_MapOfInteger.hxx>
44 #include <TopExp.hxx>
45 #include <TopExp_Explorer.hxx>
46 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
47 #include <TopTools_IndexedMapOfShape.hxx>
48 #include <TopTools_ListOfShape.hxx>
49 #include <TopTools_MapOfShape.hxx>
50 #include <TopTools_ListIteratorOfListOfShape.hxx>
51 #include <TopTools_SequenceOfShape.hxx>
52 #include <TopoDS.hxx>
53 #include <TopoDS_Edge.hxx>
54 #include <TopoDS_Face.hxx>
55 #include <TopoDS_Shell.hxx>
56 #include <TopoDS_Solid.hxx>
57 #include <TopoDS_Vertex.hxx>
58 #include <TopoDS_Iterator.hxx>
59
60 #include "utilities.h"
61
62 //=======================================================================
63 //function : BlockFix_UnionEdges()
64 //purpose  : Constructor
65 //=======================================================================
66
67 BlockFix_UnionEdges::BlockFix_UnionEdges (  )
68 {
69 }
70
71
72 //=======================================================================
73 //function : MergeEdges
74 //purpose  : auxilary
75 //=======================================================================
76 static Standard_Boolean MergeEdges(const TopTools_SequenceOfShape& SeqEdges,
77                                    const TopoDS_Face& aFace,
78                                    const Standard_Real Tol,
79                                    TopoDS_Edge& anEdge)
80 {
81   // make chain for union
82   BRep_Builder B;
83   ShapeAnalysis_Edge sae;
84   TopoDS_Edge FirstE = TopoDS::Edge(SeqEdges.Value(1));
85   TopoDS_Edge LastE = FirstE;
86   TopoDS_Vertex VF = sae.FirstVertex(FirstE);
87   TopoDS_Vertex VL = sae.LastVertex(LastE);
88   TopTools_SequenceOfShape aChain;
89   aChain.Append(FirstE);
90   TColStd_MapOfInteger IndUsedEdges;
91   IndUsedEdges.Add(1);
92   Standard_Integer j;
93   for(j=2; j<=SeqEdges.Length(); j++) {
94     for(Standard_Integer k=2; k<=SeqEdges.Length(); k++) {
95       if(IndUsedEdges.Contains(k)) continue;
96       TopoDS_Edge edge = TopoDS::Edge(SeqEdges.Value(k));
97       TopoDS_Vertex VF2 = sae.FirstVertex(edge);
98       TopoDS_Vertex VL2 = sae.LastVertex(edge);
99       if(sae.FirstVertex(edge).IsSame(VL)) {
100         aChain.Append(edge);
101         LastE = edge;
102         VL = sae.LastVertex(LastE);
103         IndUsedEdges.Add(k);
104       }
105       else if(sae.LastVertex(edge).IsSame(VF)) {
106         aChain.Prepend(edge);
107         FirstE = edge;
108         VF = sae.FirstVertex(FirstE);
109         IndUsedEdges.Add(k);
110       }
111     }
112   }
113   if(aChain.Length()<SeqEdges.Length()) {
114     MESSAGE ("can not create correct chain...");
115     return Standard_False;
116   }
117   // union edges in chain
118   // first step: union lines and circles
119   TopLoc_Location Loc;
120   Standard_Real fp1,lp1,fp2,lp2;
121   for(j=1; j<aChain.Length(); j++) {
122     TopoDS_Edge edge1 = TopoDS::Edge(aChain.Value(j));
123     Handle(Geom_Curve) c3d1 = BRep_Tool::Curve(edge1,Loc,fp1,lp1);
124     if(c3d1.IsNull()) break;
125     while(c3d1->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
126       Handle(Geom_TrimmedCurve) tc =
127         Handle(Geom_TrimmedCurve)::DownCast(c3d1);
128       c3d1 = tc->BasisCurve();
129     }
130     TopoDS_Edge edge2 = TopoDS::Edge(aChain.Value(j+1));
131     Handle(Geom_Curve) c3d2 = BRep_Tool::Curve(edge2,Loc,fp2,lp2);
132     if(c3d2.IsNull()) break;
133     while(c3d2->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
134       Handle(Geom_TrimmedCurve) tc =
135         Handle(Geom_TrimmedCurve)::DownCast(c3d2);
136       c3d2 = tc->BasisCurve();
137     }
138     if( c3d1->IsKind(STANDARD_TYPE(Geom_Line)) && c3d2->IsKind(STANDARD_TYPE(Geom_Line)) ) {
139       // union lines
140       Handle(Geom_Line) L1 = Handle(Geom_Line)::DownCast(c3d1);
141       Handle(Geom_Line) L2 = Handle(Geom_Line)::DownCast(c3d2);
142       gp_Dir Dir1 = L1->Position().Direction();
143       gp_Dir Dir2 = L2->Position().Direction();
144       //if(!Dir1.IsEqual(Dir2,Precision::Angular())) { 
145       //if(!Dir1.IsParallel(Dir2,Precision::Angular())) { 
146       if(!Dir1.IsParallel(Dir2,Tol)) { 
147         continue;
148       }
149       // can union lines => create new edge
150       TopoDS_Vertex V1 = sae.FirstVertex(edge1);
151       gp_Pnt PV1 = BRep_Tool::Pnt(V1);
152       TopoDS_Vertex V2 = sae.LastVertex(edge2);
153       gp_Pnt PV2 = BRep_Tool::Pnt(V2);
154       gp_Vec Vec(PV1,PV2);
155       Handle(Geom_Line) L = new Geom_Line(gp_Ax1(PV1,Vec));
156       Standard_Real dist = PV1.Distance(PV2);
157       Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(L,0.0,dist);
158       TopoDS_Edge E;
159       B.MakeEdge (E,tc,Precision::Confusion());
160       B.Add (E,V1);  B.Add (E,V2);
161       B.UpdateVertex(V1, 0., E, 0.);
162       B.UpdateVertex(V2, dist, E, 0.);
163       //ShapeFix_Edge sfe;
164       //sfe.FixAddPCurve(E,aFace,Standard_False);
165       //sfe.FixSameParameter(E);
166       aChain.Remove(j);
167       aChain.SetValue(j,E);
168       j--;
169     }
170     if( c3d1->IsKind(STANDARD_TYPE(Geom_Circle)) && c3d2->IsKind(STANDARD_TYPE(Geom_Circle)) ) {
171       // union circles
172       Handle(Geom_Circle) C1 = Handle(Geom_Circle)::DownCast(c3d1);
173       Handle(Geom_Circle) C2 = Handle(Geom_Circle)::DownCast(c3d2);
174       gp_Pnt P01 = C1->Location();
175       gp_Pnt P02 = C2->Location();
176       if (P01.Distance(P02) > Precision::Confusion()) continue;
177       // can union circles => create new edge
178       TopoDS_Vertex V1 = sae.FirstVertex(edge1);
179       gp_Pnt PV1 = BRep_Tool::Pnt(V1);
180       TopoDS_Vertex V2 = sae.LastVertex(edge2);
181       gp_Pnt PV2 = BRep_Tool::Pnt(V2);
182       TopoDS_Vertex VM = sae.LastVertex(edge1);
183       gp_Pnt PVM = BRep_Tool::Pnt(VM);
184       GC_MakeCircle MC (PV1,PVM,PV2);
185       Handle(Geom_Circle) C = MC.Value();
186       TopoDS_Edge E;
187       if (!MC.IsDone() || C.IsNull()) {
188         // jfa for Mantis issue 0020228
189         if (PV1.Distance(PV2) > Precision::Confusion()) continue;
190         // closed chain
191         C = C1;
192         B.MakeEdge (E,C,Precision::Confusion());
193         B.Add(E,V1);
194         B.Add(E,V2);
195       }
196       else {
197         gp_Pnt P0 = C->Location();
198         gp_Dir D1(gp_Vec(P0,PV1));
199         gp_Dir D2(gp_Vec(P0,PV2));
200         Standard_Real fpar = C->XAxis().Direction().Angle(D1);
201         if(fabs(fpar)>Precision::Confusion()) {
202           // check orientation
203           gp_Dir ND =  C->XAxis().Direction().Crossed(D1);
204           if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
205             fpar = -fpar;
206           }
207         }
208         Standard_Real lpar = C->XAxis().Direction().Angle(D2);
209         if(fabs(lpar)>Precision::Confusion()) {
210           // check orientation
211           gp_Dir ND =  C->XAxis().Direction().Crossed(D2);
212           if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
213             lpar = -lpar;
214           }
215         }
216         if(lpar<fpar) lpar += 2*PI;
217         Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(C,fpar,lpar);
218         B.MakeEdge (E,tc,Precision::Confusion());
219         B.Add(E,V1);
220         B.Add(E,V2);
221         B.UpdateVertex(V1, fpar, E, 0.);
222         B.UpdateVertex(V2, lpar, E, 0.);
223       }
224       ShapeFix_Edge sfe;
225       sfe.FixAddPCurve(E,aFace,Standard_False);
226       sfe.FixSameParameter(E);
227       aChain.Remove(j);
228       aChain.SetValue(j,E);
229       j--;
230     }
231   }
232   if (j < aChain.Length()) {
233     MESSAGE ("null curve3d in edge...");
234     return Standard_False;
235   }
236   if (aChain.Length() > 1) {
237     // second step: union edges with various curves
238     // skl for bug 0020052 from Mantis: perform such unions
239     // only if curves are bspline or bezier
240     bool NeedUnion = true;
241     for(j=1; j<=aChain.Length(); j++) {
242       TopoDS_Edge edge = TopoDS::Edge(aChain.Value(j));
243       Handle(Geom_Curve) c3d = BRep_Tool::Curve(edge,Loc,fp1,lp1);
244       if(c3d.IsNull()) continue;
245       while(c3d->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
246         Handle(Geom_TrimmedCurve) tc =
247           Handle(Geom_TrimmedCurve)::DownCast(c3d);
248         c3d = tc->BasisCurve();
249       }
250       if( ( c3d->IsKind(STANDARD_TYPE(Geom_BSplineCurve)) ||
251             c3d->IsKind(STANDARD_TYPE(Geom_BezierCurve)) ) ) continue;
252       NeedUnion = false;
253       break;
254     }
255     if(NeedUnion) {
256       MESSAGE ("can not make analitical union => make approximation");
257       TopoDS_Wire W;
258       B.MakeWire(W);
259       for(j=1; j<=aChain.Length(); j++) {
260         TopoDS_Edge edge = TopoDS::Edge(aChain.Value(j));
261         B.Add(W,edge);
262       }
263       Handle(BRepAdaptor_HCompCurve) Adapt = new BRepAdaptor_HCompCurve(W);
264       Approx_Curve3d Conv(Adapt,Tol,GeomAbs_C1,9,1000);
265       Handle(Geom_BSplineCurve) bc = Conv.Curve();
266       TopoDS_Edge E;
267       B.MakeEdge (E,bc,Precision::Confusion());
268       B.Add (E,VF);
269       B.Add (E,VL);
270       aChain.SetValue(1,E);
271     }
272     else {
273       MESSAGE ("can not make approximation for such types of curves");
274       return Standard_False;
275     }
276   }
277
278   anEdge = TopoDS::Edge(aChain.Value(1));
279   return Standard_True;
280 }
281
282
283 //=======================================================================
284 //function : Perform
285 //purpose  :
286 //=======================================================================
287
288 TopoDS_Shape BlockFix_UnionEdges::Perform(const TopoDS_Shape& Shape,
289                                           const Standard_Real Tol)
290 {
291   myContext = new ShapeBuild_ReShape;
292   myTolerance = Tol;
293   TopoDS_Shape aResult = myContext->Apply(Shape);
294
295   // processing each solid
296   TopExp_Explorer exps;
297   for(exps.Init(Shape, TopAbs_SOLID); exps.More(); exps.Next()) {
298     TopoDS_Solid aSolid = TopoDS::Solid(exps.Current());
299
300     TopTools_IndexedMapOfShape ChangedFaces;
301
302     // creating map of edge faces
303     TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
304     TopExp::MapShapesAndAncestors(aSolid, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
305
306     Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
307     TopoDS_Shape aRes = aSolid;
308     aRes = aContext->Apply(aSolid);
309
310     // processing each face
311     TopExp_Explorer exp;
312     for(exp.Init(aRes, TopAbs_FACE); exp.More(); exp.Next()) {
313       TopoDS_Face aFace =
314         TopoDS::Face(aContext->Apply(exp.Current().Oriented(TopAbs_FORWARD)));
315       TopTools_IndexedDataMapOfShapeListOfShape aMapFacesEdges;
316
317       for(TopExp_Explorer expe(aFace,TopAbs_EDGE); expe.More(); expe.Next()) {
318         TopoDS_Edge edge = TopoDS::Edge(expe.Current());
319         if(!aMapEdgeFaces.Contains(edge)) continue;
320         const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
321         TopTools_ListIteratorOfListOfShape anIter(aList);
322         for( ; anIter.More(); anIter.Next()) {
323           TopoDS_Face face = TopoDS::Face(anIter.Value());
324           TopoDS_Face face1 = TopoDS::Face(aContext->Apply(anIter.Value()));
325           if(face1.IsSame(aFace)) continue;
326           if(aMapFacesEdges.Contains(face)) {
327             aMapFacesEdges.ChangeFromKey(face).Append(edge);
328           }
329           else {
330             TopTools_ListOfShape ListEdges;
331             ListEdges.Append(edge);
332             aMapFacesEdges.Add(face,ListEdges);
333           }
334         }
335       }
336
337       for(Standard_Integer i=1; i<=aMapFacesEdges.Extent(); i++) {
338         const TopTools_ListOfShape& ListEdges = aMapFacesEdges.FindFromIndex(i);
339         TopTools_SequenceOfShape SeqEdges;
340         TopTools_ListIteratorOfListOfShape anIter(ListEdges);
341         for( ; anIter.More(); anIter.Next()) {
342           SeqEdges.Append(anIter.Value());
343         }
344         if(SeqEdges.Length()==1) continue;
345         TopoDS_Edge E;
346         if( MergeEdges(SeqEdges,aFace,Tol,E) ) {
347           // now we have only one edge - aChain.Value(1)
348           // we have to replace old ListEdges with this new edge
349           aContext->Replace(SeqEdges(1),E);
350           for(Standard_Integer j=2; j<=SeqEdges.Length(); j++) {
351             aContext->Remove(SeqEdges(j));
352           }
353           TopoDS_Face tmpF = TopoDS::Face(exp.Current());
354           if( !ChangedFaces.Contains(tmpF) )
355             ChangedFaces.Add(tmpF);
356           tmpF = TopoDS::Face(aMapFacesEdges.FindKey(i));
357           if( !ChangedFaces.Contains(tmpF) )
358             ChangedFaces.Add(tmpF);
359         }
360       }
361
362     } // end processing each face
363
364     // fix changed faces and replace them in the local context
365     for(Standard_Integer i=1; i<=ChangedFaces.Extent(); i++) {
366       TopoDS_Face aFace = TopoDS::Face(aContext->Apply(ChangedFaces.FindKey(i)));
367       Handle(ShapeFix_Face) sff = new ShapeFix_Face(aFace);
368       sff->SetContext(myContext);
369       sff->SetPrecision(myTolerance);
370       sff->SetMinTolerance(myTolerance);
371       sff->SetMaxTolerance(Max(1.,myTolerance*1000.));
372       sff->Perform();
373       aContext->Replace(aFace,sff->Face());
374     }
375
376     if(ChangedFaces.Extent()>0) {
377       // fix changed shell and replace it in the local context
378       TopoDS_Shape aRes1 = aContext->Apply(aRes);
379       TopExp_Explorer expsh;
380       for(expsh.Init(aRes1, TopAbs_SHELL); expsh.More(); expsh.Next()) {
381         TopoDS_Shell aShell = TopoDS::Shell(expsh.Current());
382         Handle(ShapeFix_Shell) sfsh = new ShapeFix_Shell;
383         sfsh->FixFaceOrientation(aShell);
384         aContext->Replace(aShell,sfsh->Shell());
385       }
386       TopoDS_Shape aRes2 = aContext->Apply(aRes1);
387       // put new solid into global context
388       myContext->Replace(aSolid,aRes2);
389     }
390
391   } // end processing each solid
392
393   aResult = myContext->Apply(Shape);
394   return aResult;
395 }