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