Salome HOME
34f0e2fafe7ad27bbc14f301abe23ea149ef6fa1
[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 : IsEdgeValidToMerge
238 //purpose  : Edge is valid if it is not seam or if it is a seam and the face
239 //           has another seam edge.
240 //=======================================================================
241 static Standard_Boolean IsEdgeValidToMerge(const TopoDS_Edge &theEdge,
242                                            const TopoDS_Face &theFace)
243 {
244   Standard_Boolean isValid = Standard_True;
245
246   if (BRep_Tool::IsClosed(theEdge, theFace)) {
247     // This is a seam edge. Check if there are another seam edges on the face.
248     TopExp_Explorer anExp(theFace, TopAbs_EDGE);
249
250     for (; anExp.More(); anExp.Next()) {
251       const TopoDS_Shape &aShEdge = anExp.Current();
252
253       // Skip same edge.
254       if (theEdge.IsSame(aShEdge)) {
255         continue;
256       }
257
258       // Check if this edge is a seam.
259       TopoDS_Edge anEdge = TopoDS::Edge(aShEdge);
260
261       if (BRep_Tool::IsClosed(anEdge, theFace)) {
262         isValid = Standard_False;
263         break;
264       }
265     }
266   }
267
268   return isValid;
269 }
270
271 //=======================================================================
272 //function : Perform
273 //purpose  :
274 //=======================================================================
275 TopoDS_Shape BlockFix_UnionFaces::Perform(const TopoDS_Shape& Shape)
276 {
277   Handle(ShapeBuild_ReShape) myContext = new ShapeBuild_ReShape;
278   TopoDS_Shape aResShape = myContext->Apply(Shape);
279
280   // Fill Map of faces as keys and list of solids as items.
281   TopTools_IndexedDataMapOfShapeListOfShape aMapFaceSolids;
282
283   TopExp::MapShapesAndAncestors
284     (Shape, TopAbs_FACE, TopAbs_SOLID, aMapFaceSolids);
285
286   // processing each solid
287   TopExp_Explorer exps;
288   for (exps.Init(Shape, TopAbs_SOLID); exps.More(); exps.Next()) {
289     TopoDS_Solid aSolid = TopoDS::Solid(exps.Current());
290
291     // creating map of edge faces
292     TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
293     TopExp::MapShapesAndAncestors(aSolid, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
294
295     // map of processed shapes
296     TopTools_MapOfShape aProcessed;
297
298     Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
299
300     Standard_Integer NbModif = 0;
301     Standard_Boolean hasFailed = Standard_False;
302     Standard_Real tol = Min(Max(Precision::Confusion(), myTolerance/10.), 0.1);
303
304     // count faces
305     int nbf = 0;
306     TopExp_Explorer exp;
307     TopTools_MapOfShape mapF;
308     for (exp.Init(aSolid, TopAbs_FACE); exp.More(); exp.Next()) {
309       if (mapF.Add(exp.Current()))
310         nbf++;
311     }
312
313     bool doUnion = ((myOptimumNbFaces == 0) ||
314                     ((myOptimumNbFaces > 0) && (nbf > myOptimumNbFaces)));
315
316     // processing each face
317     mapF.Clear();
318     for (exp.Init(aSolid, TopAbs_FACE); exp.More() && doUnion; exp.Next()) {
319       TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
320
321       if (aProcessed.Contains(aFace))
322         continue;
323
324       Standard_Integer dummy;
325       TopTools_SequenceOfShape edges;
326       AddOrdinaryEdges(edges,aFace,dummy);
327
328       TopTools_SequenceOfShape faces;
329       faces.Append(aFace);
330
331       //surface and location to construct result
332       TopLoc_Location aBaseLocation;
333       Handle(Geom_Surface) aBaseSurface = BRep_Tool::Surface(aFace,aBaseLocation);
334       aBaseSurface = ClearRts(aBaseSurface);
335
336       // find adjacent faces to union
337       Standard_Integer i;
338       for (i = 1; i <= edges.Length(); i++) {
339         TopoDS_Edge edge = TopoDS::Edge(edges(i));
340         if (BRep_Tool::Degenerated(edge) || !IsEdgeValidToMerge(edge, aFace))
341           continue;
342
343         const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
344         TopTools_ListIteratorOfListOfShape anIter(aList);
345         for (; anIter.More(); anIter.Next()) {
346           TopoDS_Face anCheckedFace = TopoDS::Face(anIter.Value().Oriented(TopAbs_FORWARD));
347           if (anCheckedFace.IsSame(aFace))
348             continue;
349
350           if (aProcessed.Contains(anCheckedFace))
351             continue;
352
353           if (!IsEdgeValidToMerge(edge, anCheckedFace)) {
354             // Skip seam edge.
355             continue;
356           }
357
358           // Check if faces belong to same solids.
359           if (!IsFacesOfSameSolids(aFace, anCheckedFace, aMapFaceSolids)) {
360             continue;
361           }
362
363           if (IsSameDomain(aFace,anCheckedFace)) {
364
365             if (aList.Extent() != 2) {
366               // non mainfold case is not processed
367               continue;
368             }
369
370             // replacing pcurves
371             TopoDS_Face aMockUpFace;
372             BRep_Builder B;
373             B.MakeFace(aMockUpFace,aBaseSurface,aBaseLocation,0.);
374             MovePCurves(aMockUpFace,anCheckedFace);
375
376             if (AddOrdinaryEdges(edges,aMockUpFace,dummy)) {
377               // sequence edges is modified
378               i = dummy;
379             }
380
381             faces.Append(anCheckedFace);
382             aProcessed.Add(anCheckedFace);
383             break;
384           }
385         }
386       }
387
388       // all faces collected in the sequence. Perform union of faces
389       if (faces.Length() > 1) {
390         NbModif++;
391         TopoDS_Face aResult;
392         BRep_Builder B;
393         B.MakeFace(aResult,aBaseSurface,aBaseLocation,0);
394         Standard_Integer nbWires = 0;
395
396         // connecting wires
397         while (edges.Length()>0) {
398
399           Standard_Boolean isEdge3d = Standard_False;
400           nbWires++;
401           TopTools_MapOfShape aVertices;
402           TopoDS_Wire aWire;
403           B.MakeWire(aWire);
404
405           TopoDS_Edge anEdge = TopoDS::Edge(edges(1));
406           edges.Remove(1);
407
408           isEdge3d |= !BRep_Tool::Degenerated(anEdge);
409           B.Add(aWire,anEdge);
410           TopoDS_Vertex V1,V2;
411           TopExp::Vertices(anEdge,V1,V2);
412           aVertices.Add(V1);
413           aVertices.Add(V2);
414
415           Standard_Boolean isNewFound = Standard_False;
416           do {
417             isNewFound = Standard_False;
418             for(Standard_Integer j = 1; j <= edges.Length(); j++) {
419               anEdge = TopoDS::Edge(edges(j));
420               TopExp::Vertices(anEdge,V1,V2);
421               if(aVertices.Contains(V1) || aVertices.Contains(V2)) {
422                 isEdge3d |= !BRep_Tool::Degenerated(anEdge);
423                 aVertices.Add(V1);
424                 aVertices.Add(V2);
425                 B.Add(aWire,anEdge);
426                 edges.Remove(j);
427                 j--;
428                 isNewFound = Standard_True;
429               }
430             }
431           } while (isNewFound);
432
433           // sorting any type of edges
434           aWire = TopoDS::Wire(aContext->Apply(aWire));
435
436           TopoDS_Face tmpF = TopoDS::Face(aContext->Apply(faces(1).Oriented(TopAbs_FORWARD)));
437           Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(aWire,tmpF,Precision::Confusion());
438           sfw->FixReorder();
439           Standard_Boolean isDegRemoved = Standard_False;
440           if(!sfw->StatusReorder ( ShapeExtend_FAIL )) {
441             // clear degenerated edges if at least one with 3d curve exist
442             if(isEdge3d) {
443               Handle(ShapeExtend_WireData) sewd = sfw->WireData();
444               for(Standard_Integer j = 1; j<=sewd->NbEdges();j++) {
445                 TopoDS_Edge E = sewd->Edge(j);
446                 if(BRep_Tool::Degenerated(E)) {
447                   sewd->Remove(j);
448                   isDegRemoved = Standard_True;
449                   j--;
450                 }
451               }
452             }
453             sfw->FixShifted();
454             if(isDegRemoved)
455               sfw->FixDegenerated();
456           }
457           TopoDS_Wire aWireFixed = sfw->Wire();
458           aContext->Replace(aWire,aWireFixed);
459           // add resulting wire
460           if(isEdge3d) {
461             B.Add(aResult,aWireFixed);
462           }
463           else  {
464             // sorting edges
465             Handle(ShapeExtend_WireData) sbwd = sfw->WireData();
466             Standard_Integer nbEdges = sbwd->NbEdges();
467             // sort degenerated edges and create one edge instead of several ones
468             ShapeAnalysis_WireOrder sawo(Standard_False, 0);
469             ShapeAnalysis_Edge sae;
470             Standard_Integer aLastEdge = nbEdges;
471             for(Standard_Integer j = 1; j <= nbEdges; j++) {
472               Standard_Real f,l;
473               //smh protection on NULL pcurve
474               Handle(Geom2d_Curve) c2d;
475               if(!sae.PCurve(sbwd->Edge(j),tmpF,c2d,f,l)) {
476                 aLastEdge--;
477                 continue;
478               }
479               sawo.Add(c2d->Value(f).XY(),c2d->Value(l).XY());
480             }
481             sawo.Perform();
482
483             // constructind one degenerative edge
484             gp_XY aStart, anEnd, tmp;
485             Standard_Integer nbFirst = sawo.Ordered(1);
486             TopoDS_Edge anOrigE = TopoDS::Edge(sbwd->Edge(nbFirst).Oriented(TopAbs_FORWARD));
487             ShapeBuild_Edge sbe;
488             TopoDS_Vertex aDummyV;
489             TopoDS_Edge E = sbe.CopyReplaceVertices(anOrigE,aDummyV,aDummyV);
490             sawo.XY(nbFirst,aStart,tmp);
491             sawo.XY(sawo.Ordered(aLastEdge),tmp,anEnd);
492
493             gp_XY aVec = anEnd-aStart;
494             Handle(Geom2d_Line) aLine = new Geom2d_Line(aStart,gp_Dir2d(anEnd-aStart));
495
496             B.UpdateEdge(E,aLine,tmpF,0.);
497             B.Range(E,tmpF,0.,aVec.Modulus());
498             Handle(Geom_Curve) C3d;
499             B.UpdateEdge(E,C3d,0.);
500             B.Degenerated(E,Standard_True);
501             TopoDS_Wire aW;
502             B.MakeWire(aW);
503             B.Add(aW,E);
504             B.Add(aResult,aW);
505           }
506         }
507
508         // perform substitution of face
509         aContext->Replace(aContext->Apply(aFace),aResult);
510
511         ShapeFix_Face sff (aResult);
512         //Intializing by tolerances
513         sff.SetPrecision(myTolerance);
514         sff.SetMinTolerance(tol);
515         sff.SetMaxTolerance(Max(1.,myTolerance*1000.));
516         //Setting modes
517         sff.FixOrientationMode() = 0;
518         //sff.FixWireMode() = 0;
519         sff.SetContext(aContext);
520         // Applying the fixes
521         sff.Perform();
522         if(sff.Status(ShapeExtend_FAIL))
523         hasFailed = Standard_True;
524
525         // breaking down to several faces
526         TopoDS_Shape theResult = aContext->Apply(aResult);
527         for (TopExp_Explorer aFaceExp (theResult,TopAbs_FACE); aFaceExp.More(); aFaceExp.Next()) {
528           TopoDS_Face aCurrent = TopoDS::Face(aFaceExp.Current().Oriented(TopAbs_FORWARD));
529           Handle(TColGeom_HArray2OfSurface) grid = new TColGeom_HArray2OfSurface ( 1, 1, 1, 1 );
530           grid->SetValue ( 1, 1, aBaseSurface );
531           Handle(ShapeExtend_CompositeSurface) G = new ShapeExtend_CompositeSurface ( grid );
532           ShapeFix_ComposeShell CompShell;
533           CompShell.Init ( G, aBaseLocation, aCurrent, ::Precision::Confusion() );//myPrecision
534           CompShell.SetContext( aContext );
535
536           TopTools_SequenceOfShape parts;
537           ShapeFix_SequenceOfWireSegment wires;
538           for(TopExp_Explorer W_Exp(aCurrent,TopAbs_WIRE);W_Exp.More();W_Exp.Next()) {
539             Handle(ShapeExtend_WireData) sbwd =
540               new ShapeExtend_WireData ( TopoDS::Wire(W_Exp.Current() ));
541             ShapeFix_WireSegment seg ( sbwd, TopAbs_REVERSED );
542             wires.Append(seg);
543           }
544
545           CompShell.DispatchWires ( parts,wires );
546           for (Standard_Integer j=1; j <= parts.Length(); j++ ) {
547             ShapeFix_Face aFixOrient(TopoDS::Face(parts(j)));
548             aFixOrient.SetContext(aContext);
549             aFixOrient.FixOrientation();
550           }
551
552           TopoDS_Shape CompRes;
553           if ( faces.Length() !=1 ) {
554             TopoDS_Shell S;
555             B.MakeShell ( S );
556             for ( i=1; i <= parts.Length(); i++ )
557               B.Add ( S, parts(i) );
558             CompRes = S;
559           }
560           else CompRes = parts(1);
561
562           aContext->Replace(aCurrent,CompRes);
563         }
564
565         // remove the remaining faces
566         for(i = 2; i <= faces.Length(); i++)
567           aContext->Remove(faces(i));
568       }
569     } // end processing each face
570
571     //TopoDS_Shape aResult = Shape;
572     if (NbModif > 0 && !hasFailed) {
573       TopoDS_Shape aResult = aContext->Apply(aSolid);
574
575       ShapeFix_Edge sfe;
576       for (exp.Init(aResult,TopAbs_EDGE); exp.More(); exp.Next()) {
577         TopoDS_Edge E = TopoDS::Edge(exp.Current());
578         sfe.FixVertexTolerance (E);
579         // ptv add fix same parameter
580         sfe.FixSameParameter(E, myTolerance);
581       }
582
583       myContext->Replace(aSolid, aResult);
584     }
585     //else
586     {
587       for (exp.Init(aSolid, 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(myContext);
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     }
603   } // end processing each solid
604
605   aResShape = myContext->Apply(Shape);
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 #if OCC_VERSION_LARGE > 0x06010000
709       OCC_CATCH_SIGNALS;
710 #endif
711
712 #if OCC_VERSION_LARGE > 0x06040000 // Porting to OCCT6.5.1
713       IntPatch_ImpImpIntersection anIIInt (aGA1, aTT1, aGA2, aTT2, aPrec, aPrec);
714 #else
715       IntPatch_TheIIIntOfIntersection anIIInt (aGA1, aTT1, aGA2, aTT2, aPrec, aPrec);
716 #endif
717       if (!anIIInt.IsDone() || anIIInt.IsEmpty())
718         return false;
719
720       return anIIInt.TangentFaces();
721     }
722     catch (Standard_Failure) {
723       return false;
724     }
725   }
726
727   // case of two planar surfaces:
728   // all kinds of surfaces checked, including b-spline and bezier
729   GeomLib_IsPlanarSurface aPlanarityChecker1 (S1, aPrec);
730   if (aPlanarityChecker1.IsPlanar()) {
731     GeomLib_IsPlanarSurface aPlanarityChecker2 (S2, aPrec);
732     if (aPlanarityChecker2.IsPlanar()) {
733       gp_Pln aPln1 = aPlanarityChecker1.Plan();
734       gp_Pln aPln2 = aPlanarityChecker2.Plan();
735
736       if (aPln1.Position().Direction().IsParallel(aPln2.Position().Direction(), aPrec) &&
737           aPln1.Distance(aPln2) < aPrec) {
738         return true;
739       }
740     }
741   }
742
743   // case of two cylindrical surfaces, at least one of which is a swept surface
744   // swept surfaces: SurfaceOfLinearExtrusion, SurfaceOfRevolution
745   if ((S1->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
746        S1->IsKind(STANDARD_TYPE(Geom_SweptSurface))) &&
747       (S2->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
748        S2->IsKind(STANDARD_TYPE(Geom_SweptSurface))))
749   {
750     gp_Cylinder aCyl1, aCyl2;
751     if (getCylinder(S1, aCyl1) && getCylinder(S2, aCyl2)) {
752       if (fabs(aCyl1.Radius() - aCyl2.Radius()) < aPrec) {
753         gp_Dir aDir1 = aCyl1.Position().Direction();
754         gp_Dir aDir2 = aCyl2.Position().Direction();
755         if (aDir1.IsParallel(aDir2, aPrec)) {
756           gp_Pnt aLoc1 = aCyl1.Location();
757           gp_Pnt aLoc2 = aCyl2.Location();
758           gp_Vec aVec12 (aLoc1, aLoc2);
759           if (aVec12.SquareMagnitude() < aPrec*aPrec ||
760               aVec12.IsParallel(aDir1, aPrec)) {
761             return true;
762           }
763         }
764       }
765     }
766   }
767
768   return false;
769 }
770
771 //=======================================================================
772 //function : MovePCurves
773 //purpose  :
774 //=======================================================================
775 void BlockFix_UnionFaces::MovePCurves(TopoDS_Face& aTarget,
776                                       const TopoDS_Face& aSource) const
777 {
778   BRep_Builder B;
779   for(TopExp_Explorer wexp(aSource,TopAbs_WIRE);wexp.More();wexp.Next()) {
780     Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(TopoDS::Wire(wexp.Current()),
781                                                   aTarget, Precision::Confusion());
782     sfw->FixReorder();
783     Standard_Boolean isReoredFailed = sfw->StatusReorder ( ShapeExtend_FAIL );
784     sfw->FixEdgeCurves();
785     if(isReoredFailed)
786       continue;
787
788     sfw->FixShifted();
789     sfw->FixDegenerated();
790
791     // remove degenerated edges from not degenerated points
792     ShapeAnalysis_Edge sae;
793     Handle(ShapeExtend_WireData) sewd = sfw->WireData();
794     for(Standard_Integer i = 1; i<=sewd->NbEdges();i++) {
795       TopoDS_Edge E = sewd->Edge(i);
796       if(BRep_Tool::Degenerated(E)&&!sae.HasPCurve(E,aTarget)) {
797         sewd->Remove(i);
798         i--;
799       }
800     }
801
802     TopoDS_Wire ResWire = sfw->Wire();
803     B.Add(aTarget,ResWire);
804   }
805 }