Salome HOME
0022388: [CEA 977] Invalide shape after UnionFaces
[modules/geom.git] / src / BlockFix / BlockFix_UnionFaces.cxx
1 // Copyright (C) 2007-2013  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
23 //  File:    BlockFix_UnionFaces.cxx
24 //  Created: Tue Dec  7 17:15:42 2004
25 //  Author:  Pavel DURANDIN
26
27 #include <BlockFix_UnionFaces.hxx>
28
29 #include <Basics_OCCTVersion.hxx>
30
31 #include <ShapeAnalysis_WireOrder.hxx>
32 #include <ShapeAnalysis_Edge.hxx>
33
34 #include <ShapeBuild_Edge.hxx>
35 #include <ShapeBuild_ReShape.hxx>
36
37 #include <ShapeExtend_WireData.hxx>
38 #include <ShapeExtend_CompositeSurface.hxx>
39
40 #include <ShapeFix_Face.hxx>
41 #include <ShapeFix_ComposeShell.hxx>
42 #include <ShapeFix_SequenceOfWireSegment.hxx>
43 #include <ShapeFix_WireSegment.hxx>
44 #include <ShapeFix_Wire.hxx>
45 #include <ShapeFix_Edge.hxx>
46
47 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
48 #include <IntPatch_ImpImpIntersection.hxx>
49 #else
50 #include <IntPatch_TheIIIntOfIntersection.hxx>
51 #endif
52
53 #include <BRep_Tool.hxx>
54 #include <BRep_Builder.hxx>
55 #include <BRepTools.hxx>
56 #include <BRepTopAdaptor_TopolTool.hxx>
57
58 #include <TopExp.hxx>
59 #include <TopExp_Explorer.hxx>
60
61 #include <TopTools_SequenceOfShape.hxx>
62 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
63 #include <TopTools_ListOfShape.hxx>
64 #include <TopTools_ListIteratorOfListOfShape.hxx>
65 #include <TopTools_MapOfShape.hxx>
66 #include <TopTools_MapIteratorOfMapOfShape.hxx>
67
68 #include <TopoDS.hxx>
69 #include <TopoDS_Edge.hxx>
70 #include <TopoDS_Wire.hxx>
71 #include <TopoDS_Face.hxx>
72 #include <TopoDS_Solid.hxx>
73 #include <TopoDS_Vertex.hxx>
74 #include <TopoDS_Shell.hxx>
75 #include <TopoDS_Iterator.hxx>
76 #include <TopoDS_Shape.hxx>
77
78 #include <TColGeom_HArray2OfSurface.hxx>
79
80 #include <GeomAdaptor_HSurface.hxx>
81 #include <GeomLib_IsPlanarSurface.hxx>
82
83 #include <Geom_Surface.hxx>
84 #include <Geom_Plane.hxx>
85 #include <Geom_OffsetSurface.hxx>
86 #include <Geom_SphericalSurface.hxx>
87 #include <Geom_CylindricalSurface.hxx>
88 #include <Geom_SurfaceOfRevolution.hxx>
89 #include <Geom_SurfaceOfLinearExtrusion.hxx>
90 #include <Geom_RectangularTrimmedSurface.hxx>
91
92 #include <Geom_Curve.hxx>
93 #include <Geom_Line.hxx>
94 #include <Geom_Circle.hxx>
95
96 #include <Geom2d_Line.hxx>
97
98 #include <gp_XY.hxx>
99 #include <gp_Pnt2d.hxx>
100
101 #include <Standard_Failure.hxx>
102 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
103
104 //=======================================================================
105 //function : BlockFix_UnionFaces
106 //purpose  :
107 //=======================================================================
108 BlockFix_UnionFaces::BlockFix_UnionFaces()
109   : myTolerance(Precision::Confusion()),
110     myOptimumNbFaces(6)
111 {
112 }
113
114 //=======================================================================
115 //function : GetTolerance
116 //purpose  :
117 //=======================================================================
118 Standard_Real& BlockFix_UnionFaces::GetTolerance()
119 {
120   return myTolerance;
121 }
122
123 //=======================================================================
124 //function : GetOptimumNbFaces
125 //purpose  :
126 //=======================================================================
127 Standard_Integer& BlockFix_UnionFaces::GetOptimumNbFaces()
128 {
129   return myOptimumNbFaces;
130 }
131
132 //=======================================================================
133 //function : AddOrdinaryEdges
134 //purpose  : auxilary
135 //           adds edges from the shape to the sequence
136 //           seams and equal edges are dropped
137 //           Returns true if one of original edges dropped
138 //=======================================================================
139 static Standard_Boolean AddOrdinaryEdges(TopTools_SequenceOfShape& edges,
140                                          const TopoDS_Shape aShape,
141                                          Standard_Integer& anIndex)
142 {
143   //map of edges
144   TopTools_MapOfShape aNewEdges;
145   //add edges without seams
146   for(TopExp_Explorer exp(aShape,TopAbs_EDGE); exp.More(); exp.Next()) {
147     TopoDS_Shape edge = exp.Current();
148     if(aNewEdges.Contains(edge))
149       aNewEdges.Remove(edge);
150     else
151       aNewEdges.Add(edge);
152   }
153
154   Standard_Boolean isDropped = Standard_False;
155   //merge edges and drop seams
156   for(Standard_Integer i = 1; i <= edges.Length(); i++) {
157     TopoDS_Shape current = edges(i);
158     if(aNewEdges.Contains(current)) {
159
160       aNewEdges.Remove(current);
161       edges.Remove(i);
162       i--;
163
164       if(!isDropped) {
165         isDropped = Standard_True;
166         anIndex = i;
167       }
168     }
169   }
170
171   //add edges to the sequemce
172   for(TopTools_MapIteratorOfMapOfShape anIter(aNewEdges); anIter.More(); anIter.Next())
173     edges.Append(anIter.Key());
174
175   return isDropped;
176 }
177
178 //=======================================================================
179 //function : ClearRts
180 //purpose  : auxilary
181 //=======================================================================
182 static Handle(Geom_Surface) ClearRts(const Handle(Geom_Surface)& aSurface)
183 {
184   if(aSurface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) {
185     Handle(Geom_RectangularTrimmedSurface) rts =
186       Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurface);
187     return rts->BasisSurface();
188   }
189   return aSurface;
190 }
191
192 //=======================================================================
193 //function : IsFacesOfSameSolids
194 //purpose  : auxilary
195 //=======================================================================
196 static Standard_Boolean IsFacesOfSameSolids
197        (const TopoDS_Face                               &theFace1,
198         const TopoDS_Face                               &theFace2,
199         const TopTools_IndexedDataMapOfShapeListOfShape &theMapFaceSolids)
200 {
201   Standard_Boolean isSame = Standard_False;
202
203   if (theMapFaceSolids.Contains(theFace1) &&
204       theMapFaceSolids.Contains(theFace2)) {
205     const TopTools_ListOfShape& aList1 = theMapFaceSolids.FindFromKey(theFace1);
206     const TopTools_ListOfShape& aList2 = theMapFaceSolids.FindFromKey(theFace2);
207
208     if (aList1.Extent() == aList2.Extent()) {
209       TopTools_ListIteratorOfListOfShape anIter1(aList1);
210
211       isSame = Standard_True;
212
213       for (; anIter1.More(); anIter1.Next()) {
214         const TopoDS_Shape                 &aSolid1 = anIter1.Value();
215         TopTools_ListIteratorOfListOfShape  anIter2(aList2);
216
217         for (; anIter2.More(); anIter2.Next()) {
218           if (aSolid1.IsSame(anIter2.Value())) {
219             // Same solid is detected. Break the loop
220             break;
221           }
222         }
223
224         if (!anIter2.More()) {
225           // No same solid is detected. Break the loop.
226           isSame = Standard_False;
227           break;
228         }
229       }
230     }
231   }
232
233   return isSame;
234 }
235
236 //=======================================================================
237 //function : Perform
238 //purpose  :
239 //=======================================================================
240 TopoDS_Shape BlockFix_UnionFaces::Perform(const TopoDS_Shape& Shape)
241 {
242   Handle(ShapeBuild_ReShape) myContext = new ShapeBuild_ReShape;
243   TopoDS_Shape aResShape = myContext->Apply(Shape);
244
245   // Fill Map of faces as keys and list of solids as items.
246   TopTools_IndexedDataMapOfShapeListOfShape aMapFaceSolids;
247
248   TopExp::MapShapesAndAncestors
249     (Shape, TopAbs_FACE, TopAbs_SOLID, aMapFaceSolids);
250
251   // processing each solid
252   TopExp_Explorer exps;
253   for (exps.Init(Shape, TopAbs_SOLID); exps.More(); exps.Next()) {
254     TopoDS_Solid aSolid = TopoDS::Solid(exps.Current());
255
256     // creating map of edge faces
257     TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
258     TopExp::MapShapesAndAncestors(aSolid, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
259
260     // map of processed shapes
261     TopTools_MapOfShape aProcessed;
262
263     Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
264
265     Standard_Integer NbModif = 0;
266     Standard_Boolean hasFailed = Standard_False;
267     Standard_Real tol = Min(Max(Precision::Confusion(), myTolerance/10.), 0.1);
268
269     // count faces
270     int nbf = 0;
271     TopExp_Explorer exp;
272     TopTools_MapOfShape mapF;
273     for (exp.Init(aSolid, TopAbs_FACE); exp.More(); exp.Next()) {
274       if (mapF.Add(exp.Current()))
275         nbf++;
276     }
277
278     bool doUnion = ((myOptimumNbFaces == 0) ||
279                     ((myOptimumNbFaces > 0) && (nbf > myOptimumNbFaces)));
280
281     // processing each face
282     mapF.Clear();
283     for (exp.Init(aSolid, TopAbs_FACE); exp.More() && doUnion; exp.Next()) {
284       TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
285
286       if (aProcessed.Contains(aFace))
287         continue;
288
289       Standard_Integer dummy;
290       TopTools_SequenceOfShape edges;
291       AddOrdinaryEdges(edges,aFace,dummy);
292
293       TopTools_SequenceOfShape faces;
294       faces.Append(aFace);
295
296       //surface and location to construct result
297       TopLoc_Location aBaseLocation;
298       Handle(Geom_Surface) aBaseSurface = BRep_Tool::Surface(aFace,aBaseLocation);
299       aBaseSurface = ClearRts(aBaseSurface);
300
301       // find adjacent faces to union
302       Standard_Integer i;
303       for (i = 1; i <= edges.Length(); i++) {
304         TopoDS_Edge edge = TopoDS::Edge(edges(i));
305         if (BRep_Tool::Degenerated(edge) || BRep_Tool::IsClosed(edge, aFace))
306           continue;
307
308         const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
309         TopTools_ListIteratorOfListOfShape anIter(aList);
310         for (; anIter.More(); anIter.Next()) {
311           TopoDS_Face anCheckedFace = TopoDS::Face(anIter.Value().Oriented(TopAbs_FORWARD));
312           if (anCheckedFace.IsSame(aFace))
313             continue;
314
315           if (aProcessed.Contains(anCheckedFace))
316             continue;
317
318           if (BRep_Tool::IsClosed(edge, anCheckedFace)) {
319             // Skip seam edge.
320             continue;
321           }
322
323           // Check if faces belong to same solids.
324           if (!IsFacesOfSameSolids(aFace, anCheckedFace, aMapFaceSolids)) {
325             continue;
326           }
327
328           if (IsSameDomain(aFace,anCheckedFace)) {
329
330             if (aList.Extent() != 2) {
331               // non mainfold case is not processed
332               continue;
333             }
334
335             // replacing pcurves
336             TopoDS_Face aMockUpFace;
337             BRep_Builder B;
338             B.MakeFace(aMockUpFace,aBaseSurface,aBaseLocation,0.);
339             MovePCurves(aMockUpFace,anCheckedFace);
340
341             if (AddOrdinaryEdges(edges,aMockUpFace,dummy)) {
342               // sequence edges is modified
343               i = dummy;
344             }
345
346             faces.Append(anCheckedFace);
347             aProcessed.Add(anCheckedFace);
348             break;
349           }
350         }
351       }
352
353       // all faces collected in the sequence. Perform union of faces
354       if (faces.Length() > 1) {
355         NbModif++;
356         TopoDS_Face aResult;
357         BRep_Builder B;
358         B.MakeFace(aResult,aBaseSurface,aBaseLocation,0);
359         Standard_Integer nbWires = 0;
360
361         // connecting wires
362         while (edges.Length()>0) {
363
364           Standard_Boolean isEdge3d = Standard_False;
365           nbWires++;
366           TopTools_MapOfShape aVertices;
367           TopoDS_Wire aWire;
368           B.MakeWire(aWire);
369
370           TopoDS_Edge anEdge = TopoDS::Edge(edges(1));
371           edges.Remove(1);
372
373           isEdge3d |= !BRep_Tool::Degenerated(anEdge);
374           B.Add(aWire,anEdge);
375           TopoDS_Vertex V1,V2;
376           TopExp::Vertices(anEdge,V1,V2);
377           aVertices.Add(V1);
378           aVertices.Add(V2);
379
380           Standard_Boolean isNewFound = Standard_False;
381           do {
382             isNewFound = Standard_False;
383             for(Standard_Integer j = 1; j <= edges.Length(); j++) {
384               anEdge = TopoDS::Edge(edges(j));
385               TopExp::Vertices(anEdge,V1,V2);
386               if(aVertices.Contains(V1) || aVertices.Contains(V2)) {
387                 isEdge3d |= !BRep_Tool::Degenerated(anEdge);
388                 aVertices.Add(V1);
389                 aVertices.Add(V2);
390                 B.Add(aWire,anEdge);
391                 edges.Remove(j);
392                 j--;
393                 isNewFound = Standard_True;
394               }
395             }
396           } while (isNewFound);
397
398           // sorting any type of edges
399           aWire = TopoDS::Wire(aContext->Apply(aWire));
400
401           TopoDS_Face tmpF = TopoDS::Face(aContext->Apply(faces(1).Oriented(TopAbs_FORWARD)));
402           Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(aWire,tmpF,Precision::Confusion());
403           sfw->FixReorder();
404           Standard_Boolean isDegRemoved = Standard_False;
405           if(!sfw->StatusReorder ( ShapeExtend_FAIL )) {
406             // clear degenerated edges if at least one with 3d curve exist
407             if(isEdge3d) {
408               Handle(ShapeExtend_WireData) sewd = sfw->WireData();
409               for(Standard_Integer j = 1; j<=sewd->NbEdges();j++) {
410                 TopoDS_Edge E = sewd->Edge(j);
411                 if(BRep_Tool::Degenerated(E)) {
412                   sewd->Remove(j);
413                   isDegRemoved = Standard_True;
414                   j--;
415                 }
416               }
417             }
418             sfw->FixShifted();
419             if(isDegRemoved)
420               sfw->FixDegenerated();
421           }
422           TopoDS_Wire aWireFixed = sfw->Wire();
423           aContext->Replace(aWire,aWireFixed);
424           // add resulting wire
425           if(isEdge3d) {
426             B.Add(aResult,aWireFixed);
427           }
428           else  {
429             // sorting edges
430             Handle(ShapeExtend_WireData) sbwd = sfw->WireData();
431             Standard_Integer nbEdges = sbwd->NbEdges();
432             // sort degenerated edges and create one edge instead of several ones
433             ShapeAnalysis_WireOrder sawo(Standard_False, 0);
434             ShapeAnalysis_Edge sae;
435             Standard_Integer aLastEdge = nbEdges;
436             for(Standard_Integer j = 1; j <= nbEdges; j++) {
437               Standard_Real f,l;
438               //smh protection on NULL pcurve
439               Handle(Geom2d_Curve) c2d;
440               if(!sae.PCurve(sbwd->Edge(j),tmpF,c2d,f,l)) {
441                 aLastEdge--;
442                 continue;
443               }
444               sawo.Add(c2d->Value(f).XY(),c2d->Value(l).XY());
445             }
446             sawo.Perform();
447
448             // constructind one degenerative edge
449             gp_XY aStart, anEnd, tmp;
450             Standard_Integer nbFirst = sawo.Ordered(1);
451             TopoDS_Edge anOrigE = TopoDS::Edge(sbwd->Edge(nbFirst).Oriented(TopAbs_FORWARD));
452             ShapeBuild_Edge sbe;
453             TopoDS_Vertex aDummyV;
454             TopoDS_Edge E = sbe.CopyReplaceVertices(anOrigE,aDummyV,aDummyV);
455             sawo.XY(nbFirst,aStart,tmp);
456             sawo.XY(sawo.Ordered(aLastEdge),tmp,anEnd);
457
458             gp_XY aVec = anEnd-aStart;
459             Handle(Geom2d_Line) aLine = new Geom2d_Line(aStart,gp_Dir2d(anEnd-aStart));
460
461             B.UpdateEdge(E,aLine,tmpF,0.);
462             B.Range(E,tmpF,0.,aVec.Modulus());
463             Handle(Geom_Curve) C3d;
464             B.UpdateEdge(E,C3d,0.);
465             B.Degenerated(E,Standard_True);
466             TopoDS_Wire aW;
467             B.MakeWire(aW);
468             B.Add(aW,E);
469             B.Add(aResult,aW);
470           }
471         }
472
473         // perform substitution of face
474         aContext->Replace(aContext->Apply(aFace),aResult);
475
476         ShapeFix_Face sff (aResult);
477         //Intializing by tolerances
478         sff.SetPrecision(myTolerance);
479         sff.SetMinTolerance(tol);
480         sff.SetMaxTolerance(Max(1.,myTolerance*1000.));
481         //Setting modes
482         sff.FixOrientationMode() = 0;
483         //sff.FixWireMode() = 0;
484         sff.SetContext(aContext);
485         // Applying the fixes
486         sff.Perform();
487         if(sff.Status(ShapeExtend_FAIL))
488         hasFailed = Standard_True;
489
490         // breaking down to several faces
491         TopoDS_Shape theResult = aContext->Apply(aResult);
492         for (TopExp_Explorer aFaceExp (theResult,TopAbs_FACE); aFaceExp.More(); aFaceExp.Next()) {
493           TopoDS_Face aCurrent = TopoDS::Face(aFaceExp.Current().Oriented(TopAbs_FORWARD));
494           Handle(TColGeom_HArray2OfSurface) grid = new TColGeom_HArray2OfSurface ( 1, 1, 1, 1 );
495           grid->SetValue ( 1, 1, aBaseSurface );
496           Handle(ShapeExtend_CompositeSurface) G = new ShapeExtend_CompositeSurface ( grid );
497           ShapeFix_ComposeShell CompShell;
498           CompShell.Init ( G, aBaseLocation, aCurrent, ::Precision::Confusion() );//myPrecision
499           CompShell.SetContext( aContext );
500
501           TopTools_SequenceOfShape parts;
502           ShapeFix_SequenceOfWireSegment wires;
503           for(TopExp_Explorer W_Exp(aCurrent,TopAbs_WIRE);W_Exp.More();W_Exp.Next()) {
504             Handle(ShapeExtend_WireData) sbwd =
505               new ShapeExtend_WireData ( TopoDS::Wire(W_Exp.Current() ));
506             ShapeFix_WireSegment seg ( sbwd, TopAbs_REVERSED );
507             wires.Append(seg);
508           }
509
510           CompShell.DispatchWires ( parts,wires );
511           for (Standard_Integer j=1; j <= parts.Length(); j++ ) {
512             ShapeFix_Face aFixOrient(TopoDS::Face(parts(j)));
513             aFixOrient.SetContext(aContext);
514             aFixOrient.FixOrientation();
515           }
516
517           TopoDS_Shape CompRes;
518           if ( faces.Length() !=1 ) {
519             TopoDS_Shell S;
520             B.MakeShell ( S );
521             for ( i=1; i <= parts.Length(); i++ )
522               B.Add ( S, parts(i) );
523             CompRes = S;
524           }
525           else CompRes = parts(1);
526
527           aContext->Replace(aCurrent,CompRes);
528         }
529
530         // remove the remaining faces
531         for(i = 2; i <= faces.Length(); i++)
532           aContext->Remove(faces(i));
533       }
534     } // end processing each face
535
536     //TopoDS_Shape aResult = Shape;
537     if (NbModif > 0 && !hasFailed) {
538       TopoDS_Shape aResult = aContext->Apply(aSolid);
539
540       ShapeFix_Edge sfe;
541       for (exp.Init(aResult,TopAbs_EDGE); exp.More(); exp.Next()) {
542         TopoDS_Edge E = TopoDS::Edge(exp.Current());
543         sfe.FixVertexTolerance (E);
544         // ptv add fix same parameter
545         sfe.FixSameParameter(E, myTolerance);
546       }
547
548       myContext->Replace(aSolid, aResult);
549     }
550     //else
551     {
552       for (exp.Init(aSolid, TopAbs_FACE); exp.More(); exp.Next()) {
553         TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
554         Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire;
555         sfw->SetContext(myContext);
556         sfw->SetPrecision(myTolerance);
557         sfw->SetMinTolerance(myTolerance);
558         sfw->SetMaxTolerance(Max(1.,myTolerance*1000.));
559         sfw->SetFace(aFace);
560         for (TopoDS_Iterator iter (aFace,Standard_False); iter.More(); iter.Next()) {
561           TopoDS_Wire wire = TopoDS::Wire(iter.Value());
562           sfw->Load(wire);
563           sfw->FixReorder();
564           sfw->FixShifted();
565         }
566       }
567     }
568   } // end processing each solid
569
570   aResShape = myContext->Apply(Shape);
571   return aResShape;
572 }
573
574 //=======================================================================
575 //function : IsSameDomain
576 //purpose  :
577 //=======================================================================
578 bool getCylinder (Handle(Geom_Surface)& theInSurface, gp_Cylinder& theOutCylinder)
579 {
580   bool isCylinder = false;
581
582   if (theInSurface->IsKind(STANDARD_TYPE(Geom_CylindricalSurface))) {
583     Handle(Geom_CylindricalSurface) aGC = Handle(Geom_CylindricalSurface)::DownCast(theInSurface);
584
585     theOutCylinder = aGC->Cylinder();
586     isCylinder = true;
587   }
588   else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfRevolution))) {
589     Handle(Geom_SurfaceOfRevolution) aRS =
590       Handle(Geom_SurfaceOfRevolution)::DownCast(theInSurface);
591     Handle(Geom_Curve) aBasis = aRS->BasisCurve();
592     if (aBasis->IsKind(STANDARD_TYPE(Geom_Line))) {
593       Handle(Geom_Line) aBasisLine = Handle(Geom_Line)::DownCast(aBasis);
594       gp_Dir aDir = aRS->Direction();
595       gp_Dir aBasisDir = aBasisLine->Position().Direction();
596       if (aBasisDir.IsParallel(aDir, Precision::Confusion())) {
597         // basis line is parallel to the revolution axis: it is a cylinder
598         gp_Pnt aLoc = aRS->Location();
599         Standard_Real aR = aBasisLine->Lin().Distance(aLoc);
600         gp_Ax3 aCylAx (aLoc, aDir);
601
602         theOutCylinder = gp_Cylinder(aCylAx, aR);
603         isCylinder = true;
604       }
605     }
606   }
607   else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfLinearExtrusion))) {
608     Handle(Geom_SurfaceOfLinearExtrusion) aLES =
609       Handle(Geom_SurfaceOfLinearExtrusion)::DownCast(theInSurface);
610     Handle(Geom_Curve) aBasis = aLES->BasisCurve();
611     if (aBasis->IsKind(STANDARD_TYPE(Geom_Circle))) {
612       Handle(Geom_Circle) aBasisCircle = Handle(Geom_Circle)::DownCast(aBasis);
613       gp_Dir aDir = aLES->Direction();
614       gp_Dir aBasisDir = aBasisCircle->Position().Direction();
615       if (aBasisDir.IsParallel(aDir, Precision::Confusion())) {
616         // basis circle is normal to the extrusion axis: it is a cylinder
617         gp_Pnt aLoc = aBasisCircle->Location();
618         Standard_Real aR = aBasisCircle->Radius();
619         gp_Ax3 aCylAx (aLoc, aDir);
620
621         theOutCylinder = gp_Cylinder(aCylAx, aR);
622         isCylinder = true;
623       }
624     }
625   }
626   else {
627   }
628
629   return isCylinder;
630 }
631
632 Standard_Boolean BlockFix_UnionFaces::IsSameDomain(const TopoDS_Face& aFace,
633                                                    const TopoDS_Face& aCheckedFace) const
634 {
635   //checking the same handles
636   TopLoc_Location L1, L2;
637   Handle(Geom_Surface) S1, S2;
638
639   S1 = BRep_Tool::Surface(aFace,L1);
640   S2 = BRep_Tool::Surface(aCheckedFace,L2);
641
642   if (S1 == S2 && L1 == L2)
643     return true;
644
645   // planar and cylindrical cases (IMP 20052)
646   Standard_Real aPrec = Precision::Confusion();
647
648   S1 = BRep_Tool::Surface(aFace);
649   S2 = BRep_Tool::Surface(aCheckedFace);
650
651   S1 = ClearRts(S1);
652   S2 = ClearRts(S2);
653
654   //Handle(Geom_OffsetSurface) aGOFS1, aGOFS2;
655   //aGOFS1 = Handle(Geom_OffsetSurface)::DownCast(S1);
656   //aGOFS2 = Handle(Geom_OffsetSurface)::DownCast(S2);
657   //if (!aGOFS1.IsNull()) S1 = aGOFS1->BasisSurface();
658   //if (!aGOFS2.IsNull()) S2 = aGOFS2->BasisSurface();
659
660   // case of two elementary surfaces: use OCCT tool
661   // elementary surfaces: ConicalSurface, CylindricalSurface,
662   //                      Plane, SphericalSurface and ToroidalSurface
663   if (S1->IsKind(STANDARD_TYPE(Geom_ElementarySurface)) &&
664       S2->IsKind(STANDARD_TYPE(Geom_ElementarySurface)))
665   {
666     Handle(GeomAdaptor_HSurface) aGA1 = new GeomAdaptor_HSurface(S1);
667     Handle(GeomAdaptor_HSurface) aGA2 = new GeomAdaptor_HSurface(S2);
668
669     Handle(BRepTopAdaptor_TopolTool) aTT1 = new BRepTopAdaptor_TopolTool();
670     Handle(BRepTopAdaptor_TopolTool) aTT2 = new BRepTopAdaptor_TopolTool();
671
672     try {
673 #if OCC_VERSION_LARGE > 0x06010000
674       OCC_CATCH_SIGNALS;
675 #endif
676
677 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
678       IntPatch_ImpImpIntersection anIIInt (aGA1, aTT1, aGA2, aTT2, aPrec, aPrec);
679 #else
680       IntPatch_TheIIIntOfIntersection anIIInt (aGA1, aTT1, aGA2, aTT2, aPrec, aPrec);
681 #endif
682       if (!anIIInt.IsDone() || anIIInt.IsEmpty())
683         return false;
684
685       return anIIInt.TangentFaces();
686     }
687     catch (Standard_Failure) {
688       return false;
689     }
690   }
691
692   // case of two planar surfaces:
693   // all kinds of surfaces checked, including b-spline and bezier
694   GeomLib_IsPlanarSurface aPlanarityChecker1 (S1, aPrec);
695   if (aPlanarityChecker1.IsPlanar()) {
696     GeomLib_IsPlanarSurface aPlanarityChecker2 (S2, aPrec);
697     if (aPlanarityChecker2.IsPlanar()) {
698       gp_Pln aPln1 = aPlanarityChecker1.Plan();
699       gp_Pln aPln2 = aPlanarityChecker2.Plan();
700
701       if (aPln1.Position().Direction().IsParallel(aPln2.Position().Direction(), aPrec) &&
702           aPln1.Distance(aPln2) < aPrec) {
703         return true;
704       }
705     }
706   }
707
708   // case of two cylindrical surfaces, at least one of which is a swept surface
709   // swept surfaces: SurfaceOfLinearExtrusion, SurfaceOfRevolution
710   if ((S1->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
711        S1->IsKind(STANDARD_TYPE(Geom_SweptSurface))) &&
712       (S2->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
713        S2->IsKind(STANDARD_TYPE(Geom_SweptSurface))))
714   {
715     gp_Cylinder aCyl1, aCyl2;
716     if (getCylinder(S1, aCyl1) && getCylinder(S2, aCyl2)) {
717       if (fabs(aCyl1.Radius() - aCyl2.Radius()) < aPrec) {
718         gp_Dir aDir1 = aCyl1.Position().Direction();
719         gp_Dir aDir2 = aCyl2.Position().Direction();
720         if (aDir1.IsParallel(aDir2, aPrec)) {
721           gp_Pnt aLoc1 = aCyl1.Location();
722           gp_Pnt aLoc2 = aCyl2.Location();
723           gp_Vec aVec12 (aLoc1, aLoc2);
724           if (aVec12.SquareMagnitude() < aPrec*aPrec ||
725               aVec12.IsParallel(aDir1, aPrec)) {
726             return true;
727           }
728         }
729       }
730     }
731   }
732
733   return false;
734 }
735
736 //=======================================================================
737 //function : MovePCurves
738 //purpose  :
739 //=======================================================================
740 void BlockFix_UnionFaces::MovePCurves(TopoDS_Face& aTarget,
741                                       const TopoDS_Face& aSource) const
742 {
743   BRep_Builder B;
744   for(TopExp_Explorer wexp(aSource,TopAbs_WIRE);wexp.More();wexp.Next()) {
745     Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(TopoDS::Wire(wexp.Current()),
746                                                   aTarget, Precision::Confusion());
747     sfw->FixReorder();
748     Standard_Boolean isReoredFailed = sfw->StatusReorder ( ShapeExtend_FAIL );
749     sfw->FixEdgeCurves();
750     if(isReoredFailed)
751       continue;
752
753     sfw->FixShifted();
754     sfw->FixDegenerated();
755
756     // remove degenerated edges from not degenerated points
757     ShapeAnalysis_Edge sae;
758     Handle(ShapeExtend_WireData) sewd = sfw->WireData();
759     for(Standard_Integer i = 1; i<=sewd->NbEdges();i++) {
760       TopoDS_Edge E = sewd->Edge(i);
761       if(BRep_Tool::Degenerated(E)&&!sae.HasPCurve(E,aTarget)) {
762         sewd->Remove(i);
763         i--;
764       }
765     }
766
767     TopoDS_Wire ResWire = sfw->Wire();
768     B.Add(aTarget,ResWire);
769   }
770 }