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