Salome HOME
Update mail address
[modules/geom.git] / src / GEOMAlgo / BlockFix_UnionFaces.cxx
1 // Copyright (C) 2005  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
3 // 
4 // This library is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU Lesser General Public
6 // License as published by the Free Software Foundation; either 
7 // version 2.1 of the License.
8 // 
9 // This library is distributed in the hope that it will be useful 
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
12 // Lesser General Public License for more details.
13 //
14 // You should have received a copy of the GNU Lesser General Public  
15 // License along with this library; if not, write to the Free Software 
16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 //
18 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 //
20 // File:        BlockFix_UnionFaces.cxx
21 // Created:     Tue Dec  7 17:15:42 2004
22 // Author:      Pavel DURANDIN
23 //              Open CASCADE SA 2004
24
25 #include <BlockFix_UnionFaces.ixx>
26 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
27 #include <TopExp.hxx>
28 #include <TopTools_MapOfShape.hxx>
29 #include <ShapeBuild_ReShape.hxx>
30 #include <TopoDS.hxx>
31 #include <TopoDS_Edge.hxx>
32 #include <TopoDS_Wire.hxx>
33 #include <TopoDS_Face.hxx>  
34 #include <TopoDS_Solid.hxx>
35 #include <TopExp_Explorer.hxx>
36 #include <TopTools_SequenceOfShape.hxx>
37 #include <Geom_Surface.hxx>
38 #include <BRep_Tool.hxx>
39 #include <TopTools_ListOfShape.hxx>
40 #include <TopTools_ListIteratorOfListOfShape.hxx>
41 #include <BRep_Builder.hxx>
42 #include <TopTools_MapIteratorOfMapOfShape.hxx>
43 #include <TopoDS_Vertex.hxx>
44 #include <ShapeFix_Face.hxx>
45 #include <BRep_Tool.hxx>
46 #include <ShapeExtend_WireData.hxx>
47 #include <ShapeAnalysis_WireOrder.hxx>
48 #include <ShapeAnalysis_Edge.hxx>
49 #include <Geom2d_Line.hxx>
50 #include <gp_XY.hxx>
51 #include <gp_Pnt2d.hxx>
52 #include <ShapeBuild_Edge.hxx>
53 #include <Geom_Curve.hxx>
54 #include <TopoDS_Vertex.hxx>
55
56 #include <ShapeFix_Wire.hxx>
57 #include <ShapeFix_Edge.hxx>
58
59 #include <Geom_RectangularTrimmedSurface.hxx>
60 #include <BRepTools.hxx>
61
62 #include <TColGeom_HArray2OfSurface.hxx>
63 #include <ShapeExtend_CompositeSurface.hxx>
64 #include <ShapeFix_ComposeShell.hxx>
65 #include <TopTools_SequenceOfShape.hxx>
66 #include <ShapeFix_SequenceOfWireSegment.hxx>
67 #include <ShapeFix_WireSegment.hxx>
68 #include <TopoDS_Shell.hxx>
69 #include <TopoDS_Iterator.hxx>
70
71 #include <Geom_CylindricalSurface.hxx>
72 #include <Geom_SphericalSurface.hxx>
73
74   
75 //=======================================================================
76 //function : BlockFix_UnionFaces
77 //purpose  : 
78 //=======================================================================
79
80 BlockFix_UnionFaces::BlockFix_UnionFaces()
81      : myTolerance(Precision::Confusion())
82 {
83 }
84
85
86 //=======================================================================
87 //function : GetTolearnce
88 //purpose  : 
89 //=======================================================================
90
91 Standard_Real& BlockFix_UnionFaces::GetTolerance()
92 {
93   return myTolerance;
94 }
95
96
97 //=======================================================================
98 //function : AddOrdinaryEdges
99 //purpose  : auxilary
100 //=======================================================================
101 // adds edges from the shape to the sequence
102 // seams and equal edges are dropped
103 // Returns true if one of original edges dropped
104 static Standard_Boolean AddOrdinaryEdges(TopTools_SequenceOfShape& edges,
105                                          const TopoDS_Shape aShape,
106                                          Standard_Integer& anIndex)
107 {
108   //map of edges
109   TopTools_MapOfShape aNewEdges;
110   //add edges without seams
111   for(TopExp_Explorer exp(aShape,TopAbs_EDGE); exp.More(); exp.Next()) {
112     TopoDS_Shape edge = exp.Current();
113     if(aNewEdges.Contains(edge))
114       aNewEdges.Remove(edge);
115     else
116       aNewEdges.Add(edge);
117   }
118
119   Standard_Boolean isDropped = Standard_False;
120   //merge edges and drop seams
121   for(Standard_Integer i = 1; i <= edges.Length(); i++) {
122     TopoDS_Shape current = edges(i);
123     if(aNewEdges.Contains(current)) {
124                
125       aNewEdges.Remove(current);
126       edges.Remove(i);
127       i--;
128       
129       if(!isDropped) {
130         isDropped = Standard_True;
131         anIndex = i;
132       }
133     }
134   }
135           
136   //add edges to the sequemce
137   for(TopTools_MapIteratorOfMapOfShape anIter(aNewEdges); anIter.More(); anIter.Next())
138     edges.Append(anIter.Key());
139   
140   return isDropped;
141 }
142
143
144 //=======================================================================
145 //function : ClearRts
146 //purpose  : auxilary
147 //=======================================================================
148 static Handle(Geom_Surface) ClearRts(const Handle(Geom_Surface)& aSurface)
149 {
150   if(aSurface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) {
151     Handle(Geom_RectangularTrimmedSurface) rts = 
152       Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurface);
153     return rts->BasisSurface();
154   }
155   return aSurface;
156 }
157
158
159 //=======================================================================
160 //function : Perform
161 //purpose  : 
162 //=======================================================================
163
164 TopoDS_Shape BlockFix_UnionFaces::Perform(const TopoDS_Shape& Shape)
165 {
166   Handle(ShapeBuild_ReShape) myContext = new ShapeBuild_ReShape;
167   TopoDS_Shape aResShape = myContext->Apply(Shape);
168
169   // processing each solid
170   TopExp_Explorer exps;
171   for(exps.Init(Shape, TopAbs_SOLID); exps.More(); exps.Next()) {
172     TopoDS_Solid aSolid = TopoDS::Solid(exps.Current());
173
174     // creating map of edge faces
175     TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
176     TopExp::MapShapesAndAncestors(aSolid, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
177
178     // map of processed shapes
179     TopTools_MapOfShape aProcessed;
180   
181     Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
182
183     Standard_Integer NbModif=0;
184     Standard_Boolean hasFailed = Standard_False;
185     Standard_Real tol = Min(Max(Precision::Confusion(), myTolerance/10.),0.1);
186     // processing each face
187     TopExp_Explorer exp;
188     //for( exp.Init(Shape, TopAbs_FACE); exp.More(); exp.Next()) {
189     for( exp.Init(aSolid, TopAbs_FACE); exp.More(); exp.Next()) {
190       TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
191       
192       if(aProcessed.Contains(aFace))
193         continue;
194     
195       Standard_Integer dummy;
196       TopTools_SequenceOfShape edges;
197       AddOrdinaryEdges(edges,aFace,dummy);
198     
199       TopTools_SequenceOfShape faces;
200       faces.Append(aFace);
201     
202       //surface and location to construct result
203       TopLoc_Location aBaseLocation;
204       Handle(Geom_Surface) aBaseSurface = BRep_Tool::Surface(aFace,aBaseLocation);
205       aBaseSurface = ClearRts(aBaseSurface);
206
207       // find adjacent faces to union
208       Standard_Integer i;
209       for( i = 1; i <= edges.Length(); i++) {
210         TopoDS_Edge edge = TopoDS::Edge(edges(i));
211         if(BRep_Tool::Degenerated(edge))
212           continue;
213       
214         const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
215         TopTools_ListIteratorOfListOfShape anIter(aList);
216         for( ; anIter.More(); anIter.Next()) {
217           TopoDS_Face anCheckedFace = TopoDS::Face(anIter.Value().Oriented(TopAbs_FORWARD));
218           if(anCheckedFace.IsSame(aFace))
219             continue;
220         
221           if(aProcessed.Contains(anCheckedFace))
222             continue;
223         
224           if(IsSameDomain(aFace,anCheckedFace)) {
225           
226             if(aList.Extent() != 2) {
227               // non mainfold case is not processed
228               continue;
229             }
230           
231             // replacing pcurves
232             TopoDS_Face aMockUpFace;
233             BRep_Builder B;
234             B.MakeFace(aMockUpFace,aBaseSurface,aBaseLocation,0.);
235             MovePCurves(aMockUpFace,anCheckedFace);
236             
237             if(AddOrdinaryEdges(edges,aMockUpFace,dummy)) {
238               // sequence edges is modified
239               i = dummy;
240             }
241             
242             faces.Append(anCheckedFace);
243             aProcessed.Add(anCheckedFace);
244             break;
245           }
246         }
247       }
248     
249       // all faces collected in the sequence. Perform union of faces
250       if(faces.Length() > 1) {
251         NbModif++;
252         TopoDS_Face aResult;
253         BRep_Builder B;
254         B.MakeFace(aResult,aBaseSurface,aBaseLocation,0);
255         Standard_Integer nbWires = 0;
256       
257         // connecting wires
258         while(edges.Length()>0) {
259         
260           Standard_Boolean isEdge3d = Standard_False;
261           nbWires++;
262           TopTools_MapOfShape aVertices;
263           TopoDS_Wire aWire;
264           B.MakeWire(aWire);
265         
266           TopoDS_Edge anEdge = TopoDS::Edge(edges(1));
267           edges.Remove(1);
268         
269           isEdge3d |= !BRep_Tool::Degenerated(anEdge);
270           B.Add(aWire,anEdge);
271           TopoDS_Vertex V1,V2;
272           TopExp::Vertices(anEdge,V1,V2);
273           aVertices.Add(V1);
274           aVertices.Add(V2);
275         
276           Standard_Boolean isNewFound = Standard_False;
277           do {
278             isNewFound = Standard_False;
279             for(Standard_Integer j = 1; j <= edges.Length(); j++) {
280               anEdge = TopoDS::Edge(edges(j));
281               TopExp::Vertices(anEdge,V1,V2);
282               if(aVertices.Contains(V1) || aVertices.Contains(V2)) {
283                 isEdge3d |= !BRep_Tool::Degenerated(anEdge);
284                 aVertices.Add(V1);
285                 aVertices.Add(V2);
286                 B.Add(aWire,anEdge);
287                 edges.Remove(j);
288                 j--;
289                 isNewFound = Standard_True;
290               }
291             }
292           } while (isNewFound);
293         
294           // sorting eny type of edges
295           aWire = TopoDS::Wire(aContext->Apply(aWire));
296                 
297           TopoDS_Face tmpF = TopoDS::Face(aContext->Apply(faces(1).Oriented(TopAbs_FORWARD)));
298           Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(aWire,tmpF,Precision::Confusion());
299           sfw->FixReorder();
300           Standard_Boolean isDegRemoved = Standard_False;
301           if(!sfw->StatusReorder ( ShapeExtend_FAIL )) {
302             // clear degenerated edges if at least one with 3d curve exist
303             if(isEdge3d) {
304               Handle(ShapeExtend_WireData) sewd = sfw->WireData();
305               for(Standard_Integer j = 1; j<=sewd->NbEdges();j++) {
306                 TopoDS_Edge E = sewd->Edge(j);
307                 if(BRep_Tool::Degenerated(E)) {
308                   sewd->Remove(j);
309                   isDegRemoved = Standard_True;
310                   j--;
311                 }
312               }
313             }
314             sfw->FixShifted();
315             if(isDegRemoved)
316               sfw->FixDegenerated();
317           }
318           TopoDS_Wire aWireFixed = sfw->Wire();
319           aContext->Replace(aWire,aWireFixed);
320           // add resulting wire
321           if(isEdge3d) {
322             B.Add(aResult,aWireFixed);
323           }
324           else  {
325             // sorting edges
326             Handle(ShapeExtend_WireData) sbwd = sfw->WireData();
327             Standard_Integer nbEdges = sbwd->NbEdges();
328             // sort degenerated edges and create one edge instead of several ones
329             ShapeAnalysis_WireOrder sawo(Standard_False, 0);
330             ShapeAnalysis_Edge sae;
331             Standard_Integer aLastEdge = nbEdges;
332             for(Standard_Integer j = 1; j <= nbEdges; j++) {
333               Standard_Real f,l;
334               //smh protection on NULL pcurve
335               Handle(Geom2d_Curve) c2d;
336               if(!sae.PCurve(sbwd->Edge(j),tmpF,c2d,f,l)) {
337                 aLastEdge--;
338                 continue;
339               }
340               sawo.Add(c2d->Value(f).XY(),c2d->Value(l).XY());
341             }
342             sawo.Perform();
343             
344             // constructind one degenerative edge
345             gp_XY aStart, anEnd, tmp;
346             Standard_Integer nbFirst = sawo.Ordered(1);
347             TopoDS_Edge anOrigE = TopoDS::Edge(sbwd->Edge(nbFirst).Oriented(TopAbs_FORWARD));
348             ShapeBuild_Edge sbe;
349             TopoDS_Vertex aDummyV;
350             TopoDS_Edge E = sbe.CopyReplaceVertices(anOrigE,aDummyV,aDummyV);
351             sawo.XY(nbFirst,aStart,tmp);
352             sawo.XY(sawo.Ordered(aLastEdge),tmp,anEnd);
353           
354             gp_XY aVec = anEnd-aStart;
355             Handle(Geom2d_Line) aLine = new Geom2d_Line(aStart,gp_Dir2d(anEnd-aStart));
356
357             B.UpdateEdge(E,aLine,tmpF,0.);
358             B.Range(E,tmpF,0.,aVec.Modulus());
359             Handle(Geom_Curve) C3d;
360             B.UpdateEdge(E,C3d,0.);
361             B.Degenerated(E,Standard_True);
362             TopoDS_Wire aW;
363             B.MakeWire(aW);
364             B.Add(aW,E);
365             B.Add(aResult,aW);
366           }
367         
368         }
369       
370         // perform substitution of face
371         aContext->Replace(aContext->Apply(aFace),aResult);
372       
373       
374         ShapeFix_Face sff (aResult);
375         //Intializing by tolerances
376         sff.SetPrecision(myTolerance);
377         sff.SetMinTolerance(tol);
378         sff.SetMaxTolerance(Max(1.,myTolerance*1000.));
379         //Setting modes
380         sff.FixOrientationMode() = 0;
381         //sff.FixWireMode() = 0;
382         sff.SetContext(aContext);
383         // Applying the fixes
384         sff.Perform();
385         if(sff.Status(ShapeExtend_FAIL)) 
386         hasFailed = Standard_True;
387       
388         // breaking down to several faces
389         TopoDS_Shape theResult = aContext->Apply(aResult);
390         for(TopExp_Explorer aFaceExp(theResult,TopAbs_FACE);aFaceExp.More();aFaceExp.Next()) {
391           TopoDS_Face aCurrent = TopoDS::Face(aFaceExp.Current().Oriented(TopAbs_FORWARD));
392           Handle(TColGeom_HArray2OfSurface) grid = new TColGeom_HArray2OfSurface ( 1, 1, 1, 1 );
393           grid->SetValue ( 1, 1, aBaseSurface );
394           Handle(ShapeExtend_CompositeSurface) G = new ShapeExtend_CompositeSurface ( grid );
395           ShapeFix_ComposeShell CompShell;
396           CompShell.Init ( G, aBaseLocation, aCurrent, ::Precision::Confusion() );//myPrecision 
397           CompShell.SetContext( aContext );
398           
399           TopTools_SequenceOfShape parts;
400           ShapeFix_SequenceOfWireSegment wires;
401           for(TopExp_Explorer W_Exp(aCurrent,TopAbs_WIRE);W_Exp.More();W_Exp.Next()) {
402             Handle(ShapeExtend_WireData) sbwd = 
403               new ShapeExtend_WireData ( TopoDS::Wire(W_Exp.Current() ));
404             ShapeFix_WireSegment seg ( sbwd, TopAbs_REVERSED );
405             wires.Append(seg);
406           }
407                 
408           CompShell.DispatchWires ( parts,wires );
409           for (Standard_Integer j=1; j <= parts.Length(); j++ ) {
410             ShapeFix_Face aFixOrient(TopoDS::Face(parts(j)));
411             aFixOrient.SetContext(aContext);
412             aFixOrient.FixOrientation();
413           }
414         
415           TopoDS_Shape CompRes;
416           if ( faces.Length() !=1 ) {
417             TopoDS_Shell S;
418             B.MakeShell ( S );
419             for ( i=1; i <= parts.Length(); i++ ) 
420               B.Add ( S, parts(i) );
421             CompRes = S;
422           }
423           else CompRes = parts(1);
424           
425           aContext->Replace(aCurrent,CompRes);
426         }
427       
428         // remove the remaining faces
429         for(i = 2; i <= faces.Length(); i++)
430           aContext->Remove(faces(i));
431       }
432     }
433   
434     //TopoDS_Shape aResult = Shape;
435     if(NbModif>0) {
436       TopoDS_Shape aResult = aSolid;
437       if(!hasFailed) {
438         aResult = aContext->Apply(aSolid);
439     
440         ShapeFix_Edge sfe;
441         for(exp.Init(aResult,TopAbs_EDGE); exp.More(); exp.Next()) {
442           TopoDS_Edge E = TopoDS::Edge(exp.Current());
443           sfe.FixVertexTolerance (E);
444           // ptv add fix same parameter
445           sfe.FixSameParameter(E, myTolerance);
446         }
447         
448         myContext->Replace(aSolid,aResult);
449       }
450     }
451 //    else {
452       for( exp.Init(aSolid, TopAbs_FACE); exp.More(); exp.Next()) {
453         TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
454         Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire;
455         sfw->SetContext(myContext);
456         sfw->SetPrecision(myTolerance);
457         sfw->SetMinTolerance(myTolerance);
458         sfw->SetMaxTolerance(Max(1.,myTolerance*1000.));
459         sfw->SetFace(aFace);
460         for ( TopoDS_Iterator iter(aFace,Standard_False); iter.More(); iter.Next()) { 
461           TopoDS_Wire wire = TopoDS::Wire ( iter.Value() );
462           sfw->Load(wire);
463           sfw->FixReorder();
464           sfw->FixShifted();
465         }
466       }
467 //    }
468
469   } // end processing each solid
470
471   aResShape = myContext->Apply(Shape);
472   return aResShape;
473 }
474
475
476 //=======================================================================
477 //function : IsSameDomain
478 //purpose  : 
479 //=======================================================================
480
481 Standard_Boolean BlockFix_UnionFaces::IsSameDomain(const TopoDS_Face& aFace,
482                                                    const TopoDS_Face& aCheckedFace) const
483 {
484   //checking the same handless
485   TopLoc_Location L1, L2;
486   Handle(Geom_Surface) S1, S2;
487   
488   S1 = BRep_Tool::Surface(aFace,L1);
489   S2 = BRep_Tool::Surface(aCheckedFace,L2);
490   
491   return (S1 == S2 && L1 == L2);
492 }
493
494
495 //=======================================================================
496 //function : MovePCurves
497 //purpose  : 
498 //=======================================================================
499
500 void BlockFix_UnionFaces::MovePCurves(TopoDS_Face& aTarget,
501                                       const TopoDS_Face& aSource) const
502 {
503   BRep_Builder B;
504   for(TopExp_Explorer wexp(aSource,TopAbs_WIRE);wexp.More();wexp.Next()) {
505     Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(TopoDS::Wire(wexp.Current()), 
506                                                   aTarget, Precision::Confusion());
507     sfw->FixReorder();
508     Standard_Boolean isReoredFailed = sfw->StatusReorder ( ShapeExtend_FAIL );
509     sfw->FixEdgeCurves();
510     if(isReoredFailed)
511       continue;
512     
513     sfw->FixShifted();
514     sfw->FixDegenerated();
515     
516     // remove degenerated edges from not degenerated points
517     ShapeAnalysis_Edge sae;
518     Handle(ShapeExtend_WireData) sewd = sfw->WireData();
519     for(Standard_Integer i = 1; i<=sewd->NbEdges();i++) {
520       TopoDS_Edge E = sewd->Edge(i);
521       if(BRep_Tool::Degenerated(E)&&!sae.HasPCurve(E,aTarget)) {
522         sewd->Remove(i);
523         i--;
524       }
525     }
526     
527     TopoDS_Wire ResWire = sfw->Wire();
528     B.Add(aTarget,ResWire);
529   }
530 }
531