Salome HOME
15ed9da9b6fa84f04c9ae06f33a1b601119d8c92
[modules/geom.git] / src / BlockFix / BlockFix_UnionFaces.cxx
1 // Copyright (C) 2007-2022  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 #include <BRepAdaptor_Surface.hxx>
88 #include <BRepAdaptor_HSurface.hxx>
89 #include <LocalAnalysis_SurfaceContinuity.hxx>
90 #include <GeomConvert_ApproxSurface.hxx>
91 #include <Bnd_Box.hxx>
92 #include <BRepBndLib.hxx>
93
94 #include <Geom_Curve.hxx>
95 #include <Geom_Line.hxx>
96 #include <Geom_Circle.hxx>
97
98 #include <Geom2d_Line.hxx>
99
100 #include <gp_XY.hxx>
101 #include <gp_Pnt2d.hxx>
102
103 #include <Standard_Failure.hxx>
104 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
105
106 //=======================================================================
107 //function : BlockFix_UnionFaces
108 //purpose  :
109 //=======================================================================
110 BlockFix_UnionFaces::BlockFix_UnionFaces()
111   : myTolerance(Precision::Confusion()),
112     myOptimumNbFaces(6)
113 {
114 }
115
116 //=======================================================================
117 //function : GetTolerance
118 //purpose  :
119 //=======================================================================
120 Standard_Real& BlockFix_UnionFaces::GetTolerance()
121 {
122   return myTolerance;
123 }
124
125 //=======================================================================
126 //function : GetOptimumNbFaces
127 //purpose  :
128 //=======================================================================
129 Standard_Integer& BlockFix_UnionFaces::GetOptimumNbFaces()
130 {
131   return myOptimumNbFaces;
132 }
133
134 //=======================================================================
135 //function : AddOrdinaryEdges
136 //purpose  : auxiliary
137 //           adds edges from the shape to the sequence
138 //           seams and equal edges are dropped
139 //           Returns true if one of original edges dropped
140 //=======================================================================
141 static Standard_Boolean AddOrdinaryEdges(TopTools_SequenceOfShape& edges,
142                                          const TopoDS_Shape aShape,
143                                          Standard_Integer& anIndex)
144 {
145   //map of edges
146   TopTools_MapOfShape aNewEdges;
147   TopExp_Explorer exp(aShape,TopAbs_EDGE);
148   //add edges without seams
149   for(; exp.More(); exp.Next()) {
150     TopoDS_Shape edge = exp.Current();
151     if(aNewEdges.Contains(edge))
152       aNewEdges.Remove(edge);
153     else
154       aNewEdges.Add(edge);
155   }
156
157   Standard_Boolean isDropped = Standard_False;
158   //merge edges and drop seams
159   for(Standard_Integer i = 1; i <= edges.Length(); i++) {
160     TopoDS_Shape current = edges(i);
161     if(aNewEdges.Contains(current)) {
162
163       aNewEdges.Remove(current);
164       edges.Remove(i);
165       i--;
166
167       if(!isDropped) {
168         isDropped = Standard_True;
169         anIndex = i;
170       }
171     }
172   }
173
174   //add edges to the sequence
175   for(exp.ReInit(); exp.More(); exp.Next()) {
176     const TopoDS_Shape &anEdge = exp.Current();
177
178     if (aNewEdges.Contains(anEdge)) {
179       edges.Append(anEdge);
180     }
181   }
182
183   return isDropped;
184 }
185
186 //=======================================================================
187 //function : ClearRts
188 //purpose  : auxiliary
189 //=======================================================================
190 static Handle(Geom_Surface) ClearRts(const Handle(Geom_Surface)& aSurface)
191 {
192   if(aSurface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) {
193     Handle(Geom_RectangularTrimmedSurface) rts =
194       Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurface);
195     return rts->BasisSurface();
196   }
197   return aSurface;
198 }
199
200 //=======================================================================
201 //function : IsFacesOfSameSolids
202 //purpose  : auxiliary
203 //=======================================================================
204 static Standard_Boolean IsFacesOfSameSolids
205        (const TopoDS_Face                               &theFace1,
206         const TopoDS_Face                               &theFace2,
207         const TopTools_IndexedDataMapOfShapeListOfShape &theMapFaceSolids)
208 {
209   Standard_Boolean isSame = Standard_False;
210
211   if (theMapFaceSolids.Contains(theFace1) &&
212       theMapFaceSolids.Contains(theFace2)) {
213     const TopTools_ListOfShape& aList1 = theMapFaceSolids.FindFromKey(theFace1);
214     const TopTools_ListOfShape& aList2 = theMapFaceSolids.FindFromKey(theFace2);
215
216     if (aList1.Extent() == aList2.Extent()) {
217       TopTools_ListIteratorOfListOfShape anIter1(aList1);
218
219       isSame = Standard_True;
220
221       for (; anIter1.More(); anIter1.Next()) {
222         const TopoDS_Shape                 &aSolid1 = anIter1.Value();
223         TopTools_ListIteratorOfListOfShape  anIter2(aList2);
224
225         for (; anIter2.More(); anIter2.Next()) {
226           if (aSolid1.IsSame(anIter2.Value())) {
227             // Same solid is detected. Break the loop
228             break;
229           }
230         }
231
232         if (!anIter2.More()) {
233           // No same solid is detected. Break the loop.
234           isSame = Standard_False;
235           break;
236         }
237       }
238     }
239   }
240
241   return isSame;
242 }
243
244 //=======================================================================
245 //function : DefineMaxTolerance
246 //purpose  : calculates maximum possible tolerance on edges of shape
247 //=======================================================================
248 static Standard_Real DefineMaxTolerance(const TopoDS_Shape& theShape)
249 {
250   Standard_Real aTol = Precision::Confusion();
251
252   Standard_Real MinSize = RealLast();
253   TopExp_Explorer Explo(theShape, TopAbs_EDGE);
254   for (; Explo.More(); Explo.Next())
255   {
256     const TopoDS_Edge& anEdge = TopoDS::Edge(Explo.Current());
257     Bnd_Box aBox;
258     BRepBndLib::Add(anEdge, aBox);
259     Standard_Real Xmin, Ymin, Zmin, Xmax, Ymax, Zmax;
260     aBox.Get(Xmin, Ymin, Zmin, Xmax, Ymax, Zmax);
261     Standard_Real MaxSize = Max(Xmax - Xmin, Max(Ymax - Ymin, Zmax - Zmin));
262     if (MaxSize < MinSize)
263       MinSize = MaxSize;
264   }
265
266   if (!Precision::IsInfinite(MinSize))
267     aTol = 0.1 * MinSize;
268
269   return aTol;
270 }
271
272 //=======================================================================
273 //function : IsTangentFaces
274 //purpose  : decides: is edge on closed surface tangent or not
275 //=======================================================================
276 static Standard_Boolean IsTangentFaces(const TopoDS_Edge& theEdge,
277                                        const TopoDS_Face& theFace)
278 {
279   Standard_Real TolC0 = Max(0.001, 1.5*BRep_Tool::Tolerance(theEdge));
280
281   Standard_Real aFirst;
282   Standard_Real aLast;
283     
284 // Obtaining of pcurves of edge on two faces.
285   const Handle(Geom2d_Curve) aC2d1 = BRep_Tool::CurveOnSurface
286                                                 (theEdge, theFace, aFirst, aLast);
287   TopoDS_Edge ReversedEdge = theEdge;
288   ReversedEdge.Reverse();
289   const Handle(Geom2d_Curve) aC2d2 = BRep_Tool::CurveOnSurface
290                                                 (ReversedEdge, theFace, aFirst, aLast);
291   if (aC2d1.IsNull() || aC2d2.IsNull())
292     return Standard_False;
293
294 // Obtaining of two surfaces from adjacent faces.
295   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(theFace);
296
297   if (aSurf.IsNull())
298     return Standard_False;
299
300 // Computation of the number of samples on the edge.
301   BRepAdaptor_Surface              aBAS(theFace);
302   Handle(BRepAdaptor_HSurface)     aBAHS      = new BRepAdaptor_HSurface(aBAS);
303   Handle(BRepTopAdaptor_TopolTool) aTool      = new BRepTopAdaptor_TopolTool(aBAHS);
304   Standard_Integer                 aNbSamples =     aTool->NbSamples();
305   const Standard_Integer           aNbSamplesMax =   23;
306   aNbSamples = Min(aNbSamplesMax, aNbSamples);
307   const Standard_Real              aTolAngle   =     M_PI/18;
308
309
310 // Computation of the continuity.
311   Standard_Real    aPar;
312   Standard_Real    aDelta = (aLast - aFirst)/(aNbSamples - 1);
313   Standard_Integer i, nbNotDone = 0;
314
315   for (i = 1, aPar = aFirst; i <= aNbSamples; i++, aPar += aDelta) {
316     if (i == aNbSamples) aPar = aLast;
317
318     LocalAnalysis_SurfaceContinuity aCont(aC2d1,  aC2d2,  aPar,
319                                           aSurf, aSurf, GeomAbs_G1,
320                                           0.001, TolC0, aTolAngle, 0.1, 0.1);
321     if (!aCont.IsDone()) 
322     {
323       nbNotDone++;
324       continue;
325     }
326
327     if (!aCont.IsG1())
328       return Standard_False;
329   }
330   
331   if (nbNotDone == aNbSamples)
332     return Standard_False;
333
334   return Standard_True;
335 }
336
337 //=======================================================================
338 //function : HasSeamEdge
339 //purpose  : Detects if a face contains a seam edge
340 //=======================================================================
341 static Standard_Boolean HasSeamEdge(const TopoDS_Face& theFace)
342 {
343   TopExp_Explorer Explo(theFace, TopAbs_EDGE);
344   for (; Explo.More(); Explo.Next())
345   {
346     const TopoDS_Edge& anEdge = TopoDS::Edge(Explo.Current());
347     if (BRepTools::IsReallyClosed(anEdge, theFace))
348       return Standard_True;
349   }
350
351   return Standard_False;
352 }
353
354
355 //=======================================================================
356 //function : IsEdgeValidToMerge
357 //purpose  : Edge is valid if it is not seam or if it is a seam and the face
358 //           has another seam edge.
359 //=======================================================================
360 static Standard_Boolean IsEdgeValidToMerge(const TopoDS_Edge& theEdge,
361                                            const TopoDS_Face& theFace,
362                                            const Handle(Geom_Surface)& theSurface,
363                                            Standard_Boolean& theIsEdgeOnSeam,
364                                            Standard_Boolean& theToMakeUPeriodic,
365                                            Standard_Boolean& theToMakeVPeriodic)
366 {
367   Standard_Boolean isValid = Standard_True;
368
369   theIsEdgeOnSeam |= BRep_Tool::IsClosed(theEdge, theFace);
370   
371   if (BRepTools::IsReallyClosed(theEdge, theFace)) {
372     // Mantis issue 0023451, now code corresponds to the comment to this method
373     isValid = Standard_False;
374
375     // This is a seam edge. Check if there are another seam edges on the face.
376     TopExp_Explorer anExp(theFace, TopAbs_EDGE);
377
378     for (; anExp.More(); anExp.Next()) {
379       const TopoDS_Shape &aShEdge = anExp.Current();
380
381       // Skip same edge.
382       if (theEdge.IsSame(aShEdge)) {
383         continue;
384       }
385
386       // Check if this edge is a seam.
387       TopoDS_Edge anEdge = TopoDS::Edge(aShEdge);
388
389       if (BRep_Tool::IsClosed(anEdge, theFace)) {
390         // Mantis issue 0023451, now code corresponds to the comment to this method
391         //isValid = Standard_False;
392         isValid = Standard_True;
393         break;
394       }
395     }
396   }
397   else if (theIsEdgeOnSeam)
398   {
399     Standard_Real fpar, lpar;
400     Handle(Geom2d_Curve) aPCurve = BRep_Tool::CurveOnSurface(theEdge, theFace, fpar, lpar);
401     gp_Pnt2d P2d1 = aPCurve->Value(fpar);
402     gp_Pnt2d P2d2 = aPCurve->Value(lpar);
403     if (!theSurface->IsUPeriodic() &&
404         theSurface->IsUClosed() &&
405         Abs(P2d1.X() - P2d2.X()) < Abs(P2d1.Y() - P2d2.Y()))
406     {
407       if (IsTangentFaces(theEdge, theFace))
408         theToMakeUPeriodic = Standard_True;
409       else
410         isValid = Standard_False;
411     }
412     if (!theSurface->IsVPeriodic() &&
413         theSurface->IsVClosed() &&
414         Abs(P2d1.Y() - P2d2.Y()) < Abs(P2d1.X() - P2d2.X()))
415     {
416       if (IsTangentFaces(theEdge, theFace))
417         theToMakeVPeriodic = Standard_True;
418       else
419         isValid = Standard_False;
420     }
421   }
422
423   return isValid;
424 }
425
426 //=======================================================================
427 //function : Perform
428 //purpose  :
429 //=======================================================================
430 TopoDS_Shape BlockFix_UnionFaces::Perform(const TopoDS_Shape& Shape)
431 {
432   // Fill Map of faces as keys and list of solids or shells as items.
433   TopTools_IndexedDataMapOfShapeListOfShape aMapFaceSoOrSh;
434
435   TopAbs_ShapeEnum aType = Shape.ShapeType();
436
437   if (aType != TopAbs_SHELL) {
438     aType = TopAbs_SOLID;
439   }
440
441   TopExp::MapShapesAndAncestors
442     (Shape, TopAbs_FACE, aType, aMapFaceSoOrSh);
443
444   // processing each solid
445   Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
446   TopTools_MapOfShape aProcessed;
447   TopExp_Explorer exps;
448   for (exps.Init(Shape, aType); exps.More(); exps.Next()) {
449     TopoDS_Shape aSoOrSh = exps.Current();
450
451     // creating map of edge faces
452     TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
453     TopExp::MapShapesAndAncestors(aSoOrSh, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
454
455     Standard_Integer NbModif = 0;
456     Standard_Boolean hasFailed = Standard_False;
457     Standard_Real tol = Min(Max(Precision::Confusion(), myTolerance/10.), 0.1);
458
459     // count faces
460     int nbf = 0;
461     TopExp_Explorer exp;
462     TopTools_MapOfShape mapF;
463     for (exp.Init(aSoOrSh, TopAbs_FACE); exp.More(); exp.Next()) {
464       if (mapF.Add(exp.Current()))
465         nbf++;
466     }
467
468     bool doUnion = ((myOptimumNbFaces == 0) ||
469                     ((myOptimumNbFaces > 0) && (nbf > myOptimumNbFaces)));
470
471     // processing each face
472     mapF.Clear();
473     for (exp.Init(aSoOrSh, TopAbs_FACE); exp.More() && doUnion; exp.Next()) {
474       TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
475
476       if (aProcessed.Contains(aFace)) {
477         continue;
478       }
479
480       Standard_Integer dummy;
481       TopTools_SequenceOfShape edges;
482       AddOrdinaryEdges(edges,aFace,dummy);
483
484       TopTools_SequenceOfShape faces;
485       faces.Append(aFace);
486
487       //surface and location to construct result
488       TopLoc_Location aBaseLocation;
489       Handle(Geom_Surface) aBaseSurface = BRep_Tool::Surface(aFace,aBaseLocation);
490       aBaseSurface = ClearRts(aBaseSurface);
491       aBaseSurface = Handle(Geom_Surface)::DownCast(aBaseSurface->Copy());
492       Standard_Boolean ToMakeUPeriodic = Standard_False, ToMakeVPeriodic = Standard_False;
493
494       // find adjacent faces to union
495       Standard_Integer i;
496       for (i = 1; i <= edges.Length(); i++) {
497         TopoDS_Edge edge = TopoDS::Edge(edges(i));
498         Standard_Boolean IsEdgeOnSeam = Standard_False;
499         if (BRep_Tool::Degenerated(edge) ||
500             !IsEdgeValidToMerge(edge, aFace, aBaseSurface,
501                                 IsEdgeOnSeam, ToMakeUPeriodic, ToMakeVPeriodic))
502           continue;
503
504         const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
505         TopTools_ListIteratorOfListOfShape anIter(aList);
506         for (; anIter.More(); anIter.Next()) {
507           TopoDS_Face anCheckedFace = TopoDS::Face(anIter.Value().Oriented(TopAbs_FORWARD));
508           if (anCheckedFace.IsSame(aFace))
509             continue;
510
511           if (aProcessed.Contains(anCheckedFace))
512             continue;
513
514           if (!IsEdgeValidToMerge(edge, anCheckedFace, aBaseSurface,
515                                   IsEdgeOnSeam, ToMakeUPeriodic, ToMakeVPeriodic)) {
516             // Skip seam edge.
517             continue;
518           }
519
520           // Check if faces belong to same solids.
521           if (!IsFacesOfSameSolids(aFace, anCheckedFace, aMapFaceSoOrSh)) {
522             continue;
523           }
524
525           if (IsSameDomain(aFace,anCheckedFace)) {
526
527             if (aList.Extent() != 2) {
528               // non mainfold case is not processed
529               continue;
530             }
531
532             //Prevent creating a face with parametric range more than period
533             if (IsEdgeOnSeam &&
534                 (HasSeamEdge(aFace) || HasSeamEdge(anCheckedFace)))
535               continue;
536
537             // replacing pcurves
538             TopoDS_Face aMockUpFace;
539             BRep_Builder B;
540             B.MakeFace(aMockUpFace,aBaseSurface,aBaseLocation,0.);
541             MovePCurves(aMockUpFace,anCheckedFace);
542
543             if (AddOrdinaryEdges(edges,aMockUpFace,dummy)) {
544               // sequence edges is modified
545               i = dummy;
546             }
547
548             faces.Append(anCheckedFace);
549             aProcessed.Add(anCheckedFace);
550             break;
551           }
552         }
553       }
554
555       // all faces collected in the sequence. Perform union of faces
556       if (faces.Length() > 1) {
557         NbModif++;
558         TopoDS_Face aResult;
559         BRep_Builder B;
560         if (ToMakeUPeriodic || ToMakeVPeriodic)
561         {
562           Handle(Geom_BSplineSurface) aBSplineSurface = Handle(Geom_BSplineSurface)::DownCast(aBaseSurface);
563           if (aBSplineSurface.IsNull())
564           {
565             Standard_Real aTol = 1.e-4;
566             GeomAbs_Shape aUCont = GeomAbs_C1, aVCont = GeomAbs_C1;
567             Standard_Integer degU = 14, degV = 14;
568             Standard_Integer nmax = 16;
569             Standard_Integer aPrec = 1;  
570             GeomConvert_ApproxSurface Approximator(aBaseSurface,aTol,aUCont,aVCont,degU,degV,nmax,aPrec);
571             aBSplineSurface = Approximator.Surface();
572           }
573           
574           if (ToMakeUPeriodic)
575             aBSplineSurface->SetUPeriodic();
576           if (ToMakeVPeriodic)
577             aBSplineSurface->SetVPeriodic();
578           
579           aBaseSurface = aBSplineSurface;
580         }
581         B.MakeFace(aResult,aBaseSurface,aBaseLocation,0);
582         Standard_Integer nbWires = 0;
583
584         // connecting wires
585         while (edges.Length()>0) {
586
587           Standard_Boolean isEdge3d = Standard_False;
588           nbWires++;
589           TopTools_MapOfShape aVertices;
590           TopoDS_Wire aWire;
591           B.MakeWire(aWire);
592
593           TopoDS_Edge anEdge = TopoDS::Edge(edges(1));
594           edges.Remove(1);
595
596           isEdge3d |= !BRep_Tool::Degenerated(anEdge);
597           B.Add(aWire,anEdge);
598           TopoDS_Vertex V1,V2;
599           TopExp::Vertices(anEdge,V1,V2);
600           aVertices.Add(V1);
601           aVertices.Add(V2);
602
603           Standard_Boolean isNewFound = Standard_False;
604           do {
605             isNewFound = Standard_False;
606             for(Standard_Integer j = 1; j <= edges.Length(); j++) {
607               anEdge = TopoDS::Edge(edges(j));
608               TopExp::Vertices(anEdge,V1,V2);
609               if(aVertices.Contains(V1) || aVertices.Contains(V2)) {
610                 isEdge3d |= !BRep_Tool::Degenerated(anEdge);
611                 aVertices.Add(V1);
612                 aVertices.Add(V2);
613                 B.Add(aWire,anEdge);
614                 edges.Remove(j);
615                 j--;
616                 isNewFound = Standard_True;
617               }
618             }
619           } while (isNewFound);
620
621           // sorting any type of edges
622           aWire = TopoDS::Wire(aContext->Apply(aWire));
623
624           Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(aWire,aResult,Precision::Confusion());
625           sfw->FixReorder();
626           Standard_Boolean isDegRemoved = Standard_False;
627           if(!sfw->StatusReorder ( ShapeExtend_FAIL )) {
628             // clear degenerated edges if at least one with 3d curve exist
629             if(isEdge3d) {
630               Handle(ShapeExtend_WireData) sewd = sfw->WireData();
631               for(Standard_Integer j = 1; j<=sewd->NbEdges();j++) {
632                 TopoDS_Edge E = sewd->Edge(j);
633                 if(BRep_Tool::Degenerated(E)) {
634                   sewd->Remove(j);
635                   isDegRemoved = Standard_True;
636                   j--;
637                 }
638               }
639             }
640             sfw->FixShifted();
641             if(isDegRemoved)
642               sfw->FixDegenerated();
643           }
644           TopoDS_Wire aWireFixed = sfw->Wire();
645           aContext->Replace(aWire,aWireFixed);
646           // add resulting wire
647           if (isEdge3d) {
648             B.Add(aResult,aWireFixed);
649           }
650           else  {
651             // sorting edges
652             Handle(ShapeExtend_WireData) sbwd = sfw->WireData();
653             Standard_Integer nbEdges = sbwd->NbEdges();
654             // sort degenerated edges and create one edge instead of several ones
655             ShapeAnalysis_WireOrder sawo(Standard_False, 0);
656             ShapeAnalysis_Edge sae;
657             Standard_Integer aLastEdge = nbEdges;
658             for (Standard_Integer j = 1; j <= nbEdges; j++) {
659               Standard_Real f,l;
660               //smh protection on NULL pcurve
661               Handle(Geom2d_Curve) c2d;
662               if (!sae.PCurve(sbwd->Edge(j),aResult,c2d,f,l)) {
663                 aLastEdge--;
664                 continue;
665               }
666               sawo.Add(c2d->Value(f).XY(),c2d->Value(l).XY());
667             }
668             if (aLastEdge > 0) {
669               sawo.Perform();
670
671               // constructing one degenerative edge
672               gp_XY aStart, anEnd, tmp;
673               Standard_Integer nbFirst = sawo.Ordered(1);
674               TopoDS_Edge anOrigE = TopoDS::Edge(sbwd->Edge(nbFirst).Oriented(TopAbs_FORWARD));
675               ShapeBuild_Edge sbe;
676               TopoDS_Vertex aDummyV;
677               TopoDS_Edge E = sbe.CopyReplaceVertices(anOrigE,aDummyV,aDummyV);
678               sawo.XY(nbFirst,aStart,tmp);
679               sawo.XY(sawo.Ordered(aLastEdge),tmp,anEnd);
680
681               gp_XY aVec = anEnd-aStart;
682               Handle(Geom2d_Line) aLine = new Geom2d_Line(aStart,gp_Dir2d(anEnd-aStart));
683
684               B.UpdateEdge(E,aLine,aResult,0.);
685               B.Range(E,aResult,0.,aVec.Modulus());
686               Handle(Geom_Curve) C3d;
687               B.UpdateEdge(E,C3d,0.);
688               B.Degenerated(E,Standard_True);
689               TopoDS_Wire aW;
690               B.MakeWire(aW);
691               B.Add(aW,E);
692               B.Add(aResult,aW);
693             }
694           }
695         }
696
697         // perform substitution of face
698         aContext->Replace(aContext->Apply(aFace),aResult);
699
700         ShapeFix_Face sff (aResult);
701         //Initializing by tolerances
702         sff.SetPrecision(myTolerance);
703         sff.SetMinTolerance(tol);
704         Standard_Real MaxTol = DefineMaxTolerance(aResult);
705         sff.SetMaxTolerance(MaxTol);
706         //Setting modes
707         sff.FixOrientationMode() = 0;
708         //sff.FixWireMode() = 0;
709         sff.SetContext(aContext);
710         // Applying the fixes
711         sff.Perform();
712         if(sff.Status(ShapeExtend_FAIL))
713         hasFailed = Standard_True;
714
715         // breaking down to several faces
716         TopoDS_Shape theResult = aContext->Apply(aResult);
717         for (TopExp_Explorer aFaceExp (theResult,TopAbs_FACE); aFaceExp.More(); aFaceExp.Next()) {
718           TopoDS_Face aCurrent = TopoDS::Face(aFaceExp.Current().Oriented(TopAbs_FORWARD));
719           Handle(TColGeom_HArray2OfSurface) grid = new TColGeom_HArray2OfSurface ( 1, 1, 1, 1 );
720           grid->SetValue ( 1, 1, aBaseSurface );
721           Handle(ShapeExtend_CompositeSurface) G = new ShapeExtend_CompositeSurface ( grid );
722           ShapeFix_ComposeShell CompShell;
723           CompShell.Init ( G, aBaseLocation, aCurrent, ::Precision::Confusion() );//myPrecision
724           CompShell.SetContext( aContext );
725
726           TopTools_SequenceOfShape parts;
727           ShapeFix_SequenceOfWireSegment wires;
728           for(TopExp_Explorer W_Exp(aCurrent,TopAbs_WIRE);W_Exp.More();W_Exp.Next()) {
729             Handle(ShapeExtend_WireData) sbwd =
730               new ShapeExtend_WireData ( TopoDS::Wire(W_Exp.Current() ));
731             ShapeFix_WireSegment seg ( sbwd, TopAbs_REVERSED );
732             wires.Append(seg);
733           }
734
735           CompShell.DispatchWires ( parts,wires );
736           for (Standard_Integer j=1; j <= parts.Length(); j++ ) {
737             ShapeFix_Face aFixOrient(TopoDS::Face(parts(j)));
738             aFixOrient.SetContext(aContext);
739             aFixOrient.FixOrientation();
740           }
741
742           TopoDS_Shape CompRes;
743           if ( faces.Length() !=1 ) {
744             TopoDS_Shell S;
745             B.MakeShell ( S );
746             for ( i=1; i <= parts.Length(); i++ )
747               B.Add ( S, parts(i) );
748             CompRes = S;
749           }
750           else CompRes = parts(1);
751
752           aContext->Replace(aCurrent,CompRes);
753         }
754
755         // remove the remaining faces
756         for(i = 2; i <= faces.Length(); i++)
757           aContext->Remove(faces(i));
758       }
759     } // end processing each face
760
761     //TopoDS_Shape aResult = Shape;
762     if (NbModif > 0 && !hasFailed) {
763       TopoDS_Shape aResult = aContext->Apply(aSoOrSh);
764
765       ShapeFix_Edge sfe;
766       for (exp.Init(aResult,TopAbs_EDGE); exp.More(); exp.Next()) {
767         TopoDS_Edge E = TopoDS::Edge(exp.Current());
768         sfe.FixVertexTolerance (E);
769         // ptv add fix same parameter
770         sfe.FixSameParameter(E, myTolerance);
771       }
772     }
773
774     for (exp.Init(aSoOrSh, TopAbs_FACE); exp.More(); exp.Next()) {
775       TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
776       Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire;
777       sfw->SetContext(aContext);
778       sfw->SetPrecision(myTolerance);
779       sfw->SetMinTolerance(myTolerance);
780       sfw->SetMaxTolerance(Max(1.,myTolerance*1000.));
781       sfw->SetFace(aFace);
782       for (TopoDS_Iterator iter (aFace,Standard_False); iter.More(); iter.Next()) {
783         TopoDS_Shape aFaceCont = iter.Value();
784         if (!aFaceCont.IsNull() && aFaceCont.ShapeType() == TopAbs_WIRE) {
785           TopoDS_Wire wire = TopoDS::Wire(iter.Value());
786           sfw->Load(wire);
787           sfw->FixReorder();
788           sfw->FixShifted();
789         }
790       }
791     }
792   } // end processing each solid
793
794   const TopoDS_Shape aResShape = aContext->Apply(Shape);
795
796   return aResShape;
797 }
798
799 //=======================================================================
800 //function : IsSameDomain
801 //purpose  :
802 //=======================================================================
803 bool getCylinder (Handle(Geom_Surface)& theInSurface, gp_Cylinder& theOutCylinder)
804 {
805   bool isCylinder = false;
806
807   if (theInSurface->IsKind(STANDARD_TYPE(Geom_CylindricalSurface))) {
808     Handle(Geom_CylindricalSurface) aGC = Handle(Geom_CylindricalSurface)::DownCast(theInSurface);
809
810     theOutCylinder = aGC->Cylinder();
811     isCylinder = true;
812   }
813   else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfRevolution))) {
814     Handle(Geom_SurfaceOfRevolution) aRS =
815       Handle(Geom_SurfaceOfRevolution)::DownCast(theInSurface);
816     Handle(Geom_Curve) aBasis = aRS->BasisCurve();
817     if (aBasis->IsKind(STANDARD_TYPE(Geom_Line))) {
818       Handle(Geom_Line) aBasisLine = Handle(Geom_Line)::DownCast(aBasis);
819       gp_Dir aDir = aRS->Direction();
820       gp_Dir aBasisDir = aBasisLine->Position().Direction();
821       if (aBasisDir.IsParallel(aDir, Precision::Confusion())) {
822         // basis line is parallel to the revolution axis: it is a cylinder
823         gp_Pnt aLoc = aRS->Location();
824         Standard_Real aR = aBasisLine->Lin().Distance(aLoc);
825         gp_Ax3 aCylAx (aLoc, aDir);
826
827         theOutCylinder = gp_Cylinder(aCylAx, aR);
828         isCylinder = true;
829       }
830     }
831   }
832   else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfLinearExtrusion))) {
833     Handle(Geom_SurfaceOfLinearExtrusion) aLES =
834       Handle(Geom_SurfaceOfLinearExtrusion)::DownCast(theInSurface);
835     Handle(Geom_Curve) aBasis = aLES->BasisCurve();
836     if (aBasis->IsKind(STANDARD_TYPE(Geom_Circle))) {
837       Handle(Geom_Circle) aBasisCircle = Handle(Geom_Circle)::DownCast(aBasis);
838       gp_Dir aDir = aLES->Direction();
839       gp_Dir aBasisDir = aBasisCircle->Position().Direction();
840       if (aBasisDir.IsParallel(aDir, Precision::Confusion())) {
841         // basis circle is normal to the extrusion axis: it is a cylinder
842         gp_Pnt aLoc = aBasisCircle->Location();
843         Standard_Real aR = aBasisCircle->Radius();
844         gp_Ax3 aCylAx (aLoc, aDir);
845
846         theOutCylinder = gp_Cylinder(aCylAx, aR);
847         isCylinder = true;
848       }
849     }
850   }
851   else {
852   }
853
854   return isCylinder;
855 }
856
857 Standard_Boolean BlockFix_UnionFaces::IsSameDomain(const TopoDS_Face& aFace,
858                                                    const TopoDS_Face& aCheckedFace) const
859 {
860   //checking the same handles
861   TopLoc_Location L1, L2;
862   Handle(Geom_Surface) S1, S2;
863
864   S1 = BRep_Tool::Surface(aFace,L1);
865   S2 = BRep_Tool::Surface(aCheckedFace,L2);
866
867   if (S1 == S2 && L1 == L2)
868     return true;
869
870   // planar and cylindrical cases (IMP 20052)
871   Standard_Real aPrec = Precision::Confusion();
872
873   S1 = BRep_Tool::Surface(aFace);
874   S2 = BRep_Tool::Surface(aCheckedFace);
875
876   S1 = ClearRts(S1);
877   S2 = ClearRts(S2);
878
879   //Handle(Geom_OffsetSurface) aGOFS1, aGOFS2;
880   //aGOFS1 = Handle(Geom_OffsetSurface)::DownCast(S1);
881   //aGOFS2 = Handle(Geom_OffsetSurface)::DownCast(S2);
882   //if (!aGOFS1.IsNull()) S1 = aGOFS1->BasisSurface();
883   //if (!aGOFS2.IsNull()) S2 = aGOFS2->BasisSurface();
884
885   // case of two elementary surfaces: use OCCT tool
886   // elementary surfaces: ConicalSurface, CylindricalSurface,
887   //                      Plane, SphericalSurface and ToroidalSurface
888   if (S1->IsKind(STANDARD_TYPE(Geom_ElementarySurface)) &&
889       S2->IsKind(STANDARD_TYPE(Geom_ElementarySurface)))
890   {
891     Handle(GeomAdaptor_HSurface) aGA1 = new GeomAdaptor_HSurface(S1);
892     Handle(GeomAdaptor_HSurface) aGA2 = new GeomAdaptor_HSurface(S2);
893
894     Handle(BRepTopAdaptor_TopolTool) aTT1 = new BRepTopAdaptor_TopolTool();
895     Handle(BRepTopAdaptor_TopolTool) aTT2 = new BRepTopAdaptor_TopolTool();
896
897     try {
898       OCC_CATCH_SIGNALS;
899
900       IntPatch_ImpImpIntersection anIIInt (aGA1, aTT1, aGA2, aTT2, aPrec, aPrec);
901
902       if (!anIIInt.IsDone() || anIIInt.IsEmpty())
903         return false;
904
905       return anIIInt.TangentFaces();
906     }
907     catch (Standard_Failure&) {
908       return false;
909     }
910   }
911
912   // case of two planar surfaces:
913   // all kinds of surfaces checked, including b-spline and bezier
914   GeomLib_IsPlanarSurface aPlanarityChecker1 (S1, aPrec);
915   if (aPlanarityChecker1.IsPlanar()) {
916     GeomLib_IsPlanarSurface aPlanarityChecker2 (S2, aPrec);
917     if (aPlanarityChecker2.IsPlanar()) {
918       gp_Pln aPln1 = aPlanarityChecker1.Plan();
919       gp_Pln aPln2 = aPlanarityChecker2.Plan();
920
921       if (aPln1.Position().Direction().IsParallel(aPln2.Position().Direction(), aPrec) &&
922           aPln1.Distance(aPln2) < aPrec) {
923         return true;
924       }
925     }
926   }
927
928   // case of two cylindrical surfaces, at least one of which is a swept surface
929   // swept surfaces: SurfaceOfLinearExtrusion, SurfaceOfRevolution
930   if ((S1->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
931        S1->IsKind(STANDARD_TYPE(Geom_SweptSurface))) &&
932       (S2->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
933        S2->IsKind(STANDARD_TYPE(Geom_SweptSurface))))
934   {
935     gp_Cylinder aCyl1, aCyl2;
936     if (getCylinder(S1, aCyl1) && getCylinder(S2, aCyl2)) {
937       if (fabs(aCyl1.Radius() - aCyl2.Radius()) < aPrec) {
938         gp_Dir aDir1 = aCyl1.Position().Direction();
939         gp_Dir aDir2 = aCyl2.Position().Direction();
940         if (aDir1.IsParallel(aDir2, aPrec)) {
941           gp_Pnt aLoc1 = aCyl1.Location();
942           gp_Pnt aLoc2 = aCyl2.Location();
943           gp_Vec aVec12 (aLoc1, aLoc2);
944           if (aVec12.SquareMagnitude() < aPrec*aPrec ||
945               aVec12.IsParallel(aDir1, aPrec)) {
946             return true;
947           }
948         }
949       }
950     }
951   }
952
953   return false;
954 }
955
956 //=======================================================================
957 //function : MovePCurves
958 //purpose  :
959 //=======================================================================
960 void BlockFix_UnionFaces::MovePCurves(TopoDS_Face& aTarget,
961                                       const TopoDS_Face& aSource) const
962 {
963   BRep_Builder B;
964   for(TopExp_Explorer wexp(aSource,TopAbs_WIRE);wexp.More();wexp.Next()) {
965     Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(TopoDS::Wire(wexp.Current()),
966                                                   aTarget, Precision::Confusion());
967     sfw->FixReorder();
968     Standard_Boolean isReoredFailed = sfw->StatusReorder ( ShapeExtend_FAIL );
969     sfw->FixEdgeCurves();
970     if(isReoredFailed)
971       continue;
972
973     sfw->FixShifted();
974     sfw->FixDegenerated();
975
976     // remove degenerated edges from not degenerated points
977     ShapeAnalysis_Edge sae;
978     Handle(ShapeExtend_WireData) sewd = sfw->WireData();
979     for(Standard_Integer i = 1; i<=sewd->NbEdges();i++) {
980       TopoDS_Edge E = sewd->Edge(i);
981       if(BRep_Tool::Degenerated(E)&&!sae.HasPCurve(E,aTarget)) {
982         sewd->Remove(i);
983         i--;
984       }
985     }
986
987     TopoDS_Wire ResWire = sfw->Wire();
988     B.Add(aTarget,ResWire);
989   }
990 }