0024983: For the incorrect seam edge in STEP file no fix is provided
[occt.git] / src / ShapeFix / ShapeFix_Face.cxx
1 // Copyright (c) 1999-2014 OPEN CASCADE SAS
2 //
3 // This file is part of Open CASCADE Technology software library.
4 //
5 // This library is free software; you can redistribute it and/or modify it under
6 // the terms of the GNU Lesser General Public License version 2.1 as published
7 // by the Free Software Foundation, with special exception defined in the file
8 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
9 // distribution for complete text of the license and disclaimer of any warranty.
10 //
11 // Alternatively, this file may be used under the terms of Open CASCADE
12 // commercial license or contractual agreement.
13
14 // pdn 10.12.98: tr9_r0501-ug
15 // pdn 28.12.98: PRO10366 shifting pcurve between two singularities
16 //:k7 abv 5.01.99: USA60022.igs ent 243: FixMissingSeam() improved
17 //:l2 abv 10.01.99: USA60022 7289: corrections for reversed face
18 //gka 11.01.99 file PRO7755.stp #2018: work-around error in BRepLib_MakeFace
19 //:p4 abv, pdn 23.02.99: PRO9234 #15720: call BRepTools::Update() for faces
20 //    rln 03.03.99 S4135: transmission of parameter precision to SA_Surface::NbSingularities
21 //:q5 abv 19.03.99 code improvement
22 //%14 pdn 15.03.99 adding function for fixing null area wires
23 //%15 pdn 20.03.99 code improvement
24 //    abv 09.04.99 S4136: improve tolerance management; remove unused flag Closed
25 //#4  szv          S4163: optimization
26 //    smh 31.01.01 BUC60810 : Case of small wire on face in solid
27 // sln 25.09.2001  checking order of 3d and 2d representation curves
28 // abv 19.10.2001  FixAddNaturalBound improved and extracted as separate fix
29 // skl,pdn 14.05.2002  OCC55 (correction precision for small faces)
30
31 #include <ShapeFix_Face.ixx>
32
33 #include <Standard_Failure.hxx>
34 #include <Standard_ErrorHandler.hxx>
35
36 #include <Precision.hxx>
37
38 #include <Geom2d_Curve.hxx>
39 #include <Geom2d_Line.hxx>
40 #include <Geom2dAdaptor_Curve.hxx>
41 #include <Geom_Curve.hxx>
42 #include <Geom_BSplineSurface.hxx>
43 #include <GeomAdaptor_HSurface.hxx>
44
45 #include <TopoDS.hxx>
46 #include <TopoDS_Edge.hxx>
47 #include <TopoDS_Vertex.hxx>
48 #include <TopoDS_Shell.hxx>
49 #include <TopoDS_Compound.hxx>
50 #include <TopoDS_Iterator.hxx>
51 #include <TopExp_Explorer.hxx>
52 #include <TopTools_SequenceOfShape.hxx>
53
54 #include <BRep_Tool.hxx>
55 #include <BRep_Builder.hxx>
56 #include <BRepTopAdaptor_FClass2d.hxx>
57 #include <BRepTools.hxx>
58 #include <BRepBuilderAPI_MakeFace.hxx>
59 #include <BRepBuilderAPI_MakeVertex.hxx>
60 #include <BRepBuilderAPI_MakeWire.hxx>
61
62 #include <Message_Msg.hxx>  
63 #include <ShapeBuild_ReShape.hxx>
64 #include <ShapeExtend_WireData.hxx>
65 #include <ShapeAnalysis.hxx>
66 #include <ShapeFix_Wire.hxx>
67 #include <ShapeFix_Edge.hxx>
68 #include <ShapeAnalysis_Edge.hxx>
69 #include <Bnd_Box2d.hxx>
70 #include <Geom_Circle.hxx>
71 #include <Geom_SphericalSurface.hxx>
72 #include <Geom_RectangularTrimmedSurface.hxx>
73 #include <Geom_ConicalSurface.hxx>
74 #include <ShapeAnalysis_Wire.hxx>
75 #include <ShapeAnalysis_Surface.hxx>
76
77 #include <ShapeExtend_CompositeSurface.hxx>
78 #include <ShapeFix_ComposeShell.hxx>
79 #include <TColGeom_HArray2OfSurface.hxx>
80 #include <ShapeBuild_Edge.hxx>
81 #include <TColgp_SequenceOfPnt2d.hxx>
82 #include <Bnd_Box.hxx>
83 #include <TopTools_IndexedMapOfShape.hxx>
84 #include <TopTools_DataMapOfShapeListOfShape.hxx>
85 #include <TopTools_ListIteratorOfListOfShape.hxx>
86 #include <TopTools_MapOfShape.hxx>
87 #include <TopoDS.hxx>
88 #include <TopExp.hxx>
89
90 #include <ShapeFix.hxx>
91 #include <ShapeFix_DataMapOfShapeBox2d.hxx>
92 #include <BndLib_Add2dCurve.hxx>
93 #include <Geom2dAdaptor_Curve.hxx>
94 #include <IntRes2d_Domain.hxx>
95 #include <Geom2dInt_GInter.hxx>
96 #include <IntRes2d_IntersectionPoint.hxx>
97 #include <IntRes2d_Transition.hxx>
98 #include <TopTools_SequenceOfShape.hxx>
99 #include <IntRes2d_IntersectionSegment.hxx>
100 #include <TopTools_DataMapOfShapeInteger.hxx>
101
102 #include <ShapeFix_IntersectionTool.hxx>
103 #include <ShapeFix_SplitTool.hxx>
104 #include <TColStd_MapOfInteger.hxx>
105 #include <TopTools_DataMapOfShapeShape.hxx>
106 #include <NCollection_Array1.hxx>
107
108 #ifdef DEB
109 #define DEBUG
110 #endif
111
112 static Standard_Boolean IsSurfaceUVInfinite(const Handle(Geom_Surface)& theSurf)
113 {
114   Standard_Real UMin,UMax,VMin,VMax;
115   theSurf->Bounds(UMin,UMax,VMin,VMax);
116
117   return (Precision::IsInfinite(UMin) ||
118           Precision::IsInfinite(UMax) ||
119           Precision::IsInfinite(VMin) ||
120           Precision::IsInfinite(VMax)   );
121 }
122
123 static Standard_Boolean IsSurfaceUVPeriodic(const Handle(Geom_Surface)& theSurf)
124 {
125   return theSurf->IsUPeriodic() && theSurf->IsVPeriodic();
126 }
127
128 //=======================================================================
129 //function : ShapeFix_Face
130 //purpose  : 
131 //=======================================================================
132
133 ShapeFix_Face::ShapeFix_Face()
134 {
135   myFwd = Standard_True;
136   myStatus = 0;
137   myFixWire = new ShapeFix_Wire;
138   ClearModes();
139 }
140
141 //=======================================================================
142 //function : ShapeFix_Face
143 //purpose  : 
144 //=======================================================================
145
146 ShapeFix_Face::ShapeFix_Face(const TopoDS_Face &face)
147 {
148   myFwd = Standard_True;
149   myStatus = 0;
150   myFixWire = new ShapeFix_Wire;
151   ClearModes();
152   Init( face );
153 }
154
155 //=======================================================================
156 //function : ClearModes
157 //purpose  : 
158 //=======================================================================
159
160 void ShapeFix_Face::ClearModes()
161 {
162   myFixWireMode              = -1;
163   myFixOrientationMode       = -1;
164   myFixAddNaturalBoundMode   = -1;
165   myFixMissingSeamMode       = -1;
166   myFixSmallAreaWireMode     = -1;
167   myFixIntersectingWiresMode = -1;
168   myFixLoopWiresMode         = -1;
169   myFixSplitFaceMode         = -1;
170   myAutoCorrectPrecisionMode =  1;
171   myFixPeriodicDegenerated   = -1;
172 }
173
174 //=======================================================================
175 //function : SetMsgRegistrator
176 //purpose  : 
177 //=======================================================================
178
179 void ShapeFix_Face::SetMsgRegistrator(const Handle(ShapeExtend_BasicMsgRegistrator)& msgreg)
180 {
181   ShapeFix_Root::SetMsgRegistrator ( msgreg );
182   myFixWire->SetMsgRegistrator ( msgreg );
183 }
184
185 //=======================================================================
186 //function : SetPrecision
187 //purpose  : 
188 //=======================================================================
189
190 void ShapeFix_Face::SetPrecision (const Standard_Real preci) 
191 {
192   ShapeFix_Root::SetPrecision ( preci );
193   myFixWire->SetPrecision ( preci );
194 }
195
196 //=======================================================================
197 //function : SetMinTolerance
198 //purpose  : 
199 //=======================================================================
200
201 void ShapeFix_Face::SetMinTolerance (const Standard_Real mintol) 
202 {
203   ShapeFix_Root::SetMinTolerance ( mintol );
204   myFixWire->SetMinTolerance ( mintol );
205 }
206
207 //=======================================================================
208 //function : SetMaxTolerance
209 //purpose  : 
210 //=======================================================================
211
212 void ShapeFix_Face::SetMaxTolerance (const Standard_Real maxtol) 
213 {
214   ShapeFix_Root::SetMaxTolerance ( maxtol );
215   myFixWire->SetMaxTolerance ( maxtol );
216 }
217
218 //=======================================================================
219 //function : Init
220 //purpose  : 
221 //=======================================================================
222
223 void ShapeFix_Face::Init (const Handle(Geom_Surface)& surf,
224                           const Standard_Real preci, const Standard_Boolean fwd) 
225 {
226   myStatus = 0;
227   Handle(ShapeAnalysis_Surface) sas = new ShapeAnalysis_Surface ( surf );
228   Init ( sas, preci, fwd );
229 }
230
231 //=======================================================================
232 //function : Init
233 //purpose  : 
234 //=======================================================================
235
236 void ShapeFix_Face::Init (const Handle(ShapeAnalysis_Surface)& surf,
237                           const Standard_Real preci, const Standard_Boolean fwd) 
238 {
239   myStatus = 0;
240   mySurf = surf;
241   SetPrecision ( preci );
242   BRep_Builder B;
243   B.MakeFace ( myFace, mySurf->Surface(), ::Precision::Confusion() );
244   myShape = myFace;
245   myFwd = fwd;
246   if ( !fwd ) myFace.Orientation(TopAbs_REVERSED);
247 }
248
249 //=======================================================================
250 //function : Init
251 //purpose  : 
252 //=======================================================================
253
254 void ShapeFix_Face::Init (const TopoDS_Face& face) 
255 {
256   myStatus = 0;
257   mySurf = new ShapeAnalysis_Surface ( BRep_Tool::Surface (face) );
258   myFwd = ( face.Orientation() != TopAbs_REVERSED );
259   myFace = face;
260   myShape = myFace;
261 //  myFace = TopoDS::Face(face.EmptyCopied());
262 //  for (TopoDS_Iterator ws (face,Standard_False); ws.More(); ws.Next())
263 //    Add (TopoDS::Wire (ws.Value()) );
264 }
265
266 //=======================================================================
267 //function : Add
268 //purpose  : 
269 //=======================================================================
270
271 void ShapeFix_Face::Add (const TopoDS_Wire& wire) 
272 {
273   if ( wire.IsNull() ) return;
274   BRep_Builder B;
275   //szv#4:S4163:12Mar99 SGI warns
276   TopoDS_Shape fc = myFace.Oriented(TopAbs_FORWARD); //:l2 abv 10 Jan 99: Oriented()
277   B.Add ( fc, wire );
278 }
279
280
281 //=======================================================================
282 //function : SplitWire
283 //purpose  : auxilary - try to split wire (it is needed if some segments
284 //           were removed in ShapeFix_Wire::FixSelfIntersection()
285 //=======================================================================
286 static Standard_Boolean SplitWire(const TopoDS_Face &face, const TopoDS_Wire& wire,
287                                   TopTools_SequenceOfShape& aResWires)
288 {
289   TColStd_MapOfInteger UsedEdges;
290   Handle(ShapeExtend_WireData) sewd = new ShapeExtend_WireData(wire);
291   Standard_Integer i,j,k;
292   ShapeAnalysis_Edge sae;
293   for(i=1; i<=sewd->NbEdges(); i++) {
294     if(UsedEdges.Contains(i)) continue;
295     TopoDS_Edge E1 = sewd->Edge(i);
296     UsedEdges.Add(i);
297     TopoDS_Vertex V0,V1,V2;
298     V0 = sae.FirstVertex(E1);
299     V1 = sae.LastVertex(E1);
300     Handle(ShapeExtend_WireData) sewd1 = new ShapeExtend_WireData;
301     sewd1->Add(E1);
302     Standard_Boolean IsConnectedEdge = Standard_True;
303     for(j=2; j<=sewd->NbEdges() && IsConnectedEdge; j++) {
304       TopoDS_Edge E2;
305       for(k=2; k<=sewd->NbEdges(); k++) {
306         if(UsedEdges.Contains(k)) continue;
307         E2 = sewd->Edge(k);
308         TopoDS_Vertex V21 = sae.FirstVertex(E2);
309         TopoDS_Vertex V22 = sae.LastVertex(E2);
310         if( sae.FirstVertex(E2).IsSame(V1) ) {
311           sewd1->Add(E2);
312           UsedEdges.Add(k);
313           V1 = sae.LastVertex(E2);
314           break;
315         }
316       }
317       if(k>sewd->NbEdges()) {
318         IsConnectedEdge = Standard_False;
319         break;
320       }
321       if(V1.IsSame(V0)) {
322         //check that V0 and V1 are same in 2d too
323         Standard_Real a1,b1,a2,b2;
324         Handle (Geom2d_Curve) curve1 = BRep_Tool::CurveOnSurface(E1,face,a1,b1);
325         Handle (Geom2d_Curve) curve2 = BRep_Tool::CurveOnSurface(E2,face,a2,b2);
326         gp_Pnt2d v0,v1;
327         if (E1.Orientation() == TopAbs_REVERSED)
328           a1 = b1;
329         if (E2.Orientation() == TopAbs_REVERSED)
330           b2 = a2;
331         curve1->D0(a1,v0);
332         curve2->D0(b2,v1);
333         GeomAdaptor_Surface anAdaptor(BRep_Tool::Surface(face));
334         Standard_Real tol = Max(BRep_Tool::Tolerance(V0),BRep_Tool::Tolerance(V1));
335         Standard_Real maxResolution = 2 * Max ( anAdaptor.UResolution(tol), anAdaptor.VResolution(tol) );
336         if (v0.SquareDistance(v1) < maxResolution) {
337           // new wire is closed, put it into sequence
338           aResWires.Append(sewd1->Wire());
339           break;
340         }
341       }
342     }
343     if(!IsConnectedEdge) {
344       // create new notclosed wire
345       aResWires.Append(sewd1->Wire());
346     }
347     if(UsedEdges.Extent()==sewd->NbEdges()) break;
348   }
349
350   if(aResWires.Length()>1) {
351 #ifdef DEBUG
352     cout<<"Wire was splitted on "<<aResWires.Length()<<" wires"<< endl;
353 #endif
354   }
355
356   return Standard_True; 
357 }
358
359
360 //=======================================================================
361 //function : Perform
362 //purpose  : 
363 //=======================================================================
364
365 Standard_Boolean ShapeFix_Face::Perform() 
366 {
367   myStatus = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
368   myFixWire->SetContext ( Context() );
369   Handle(ShapeFix_Wire) theAdvFixWire = Handle(ShapeFix_Wire)::DownCast(myFixWire);
370   if (theAdvFixWire.IsNull()) return Standard_False;
371
372   BRep_Builder B;
373   TopoDS_Shape aInitFace = myFace;
374   // perform first part of fixes on wires
375   Standard_Boolean isfixReorder = Standard_False;
376   Standard_Boolean isReplaced = Standard_False;
377
378   //gka fix in order to avoid lost messages (following OCC21771)
379   TopTools_DataMapOfShapeShape aMapReorderedWires;
380
381   Standard_Real aSavPreci =  Precision();
382   if ( NeedFix ( myFixWireMode ) ) {
383     theAdvFixWire->SetFace ( myFace );
384     
385     Standard_Integer usFixLackingMode = theAdvFixWire->FixLackingMode();
386     //Standard_Integer usFixNotchedEdgesMode = theAdvFixWire->FixNotchedEdgesMode(); // CR0024983
387     Standard_Integer usFixSelfIntersectionMode = theAdvFixWire->FixSelfIntersectionMode();
388     theAdvFixWire->FixLackingMode() = Standard_False;
389     //theAdvFixWire->FixNotchedEdgesMode() = Standard_False; // CR0024983
390     theAdvFixWire->FixSelfIntersectionMode() = Standard_False;
391     
392     Standard_Boolean fixed = Standard_False; 
393     TopoDS_Shape S = myFace;
394     if ( ! Context().IsNull() ) 
395       S = Context()->Apply ( myFace );
396     TopoDS_Shape emptyCopied = S.EmptyCopied(); 
397     TopoDS_Face tmpFace = TopoDS::Face(emptyCopied);
398     tmpFace.Orientation ( TopAbs_FORWARD );
399
400     /*
401     // skl 14.05.2002 OCC55 + corrected 03.03.2004
402     Standard_Real dPreci = aSavPreci*aSavPreci;
403     dPreci*=4;
404     Standard_Real newpreci=dPreci;
405     for(TopExp_Explorer exp(S,TopAbs_EDGE); exp.More(); exp.Next()) { 
406       TopoDS_Edge edge = TopoDS::Edge ( exp.Current() );
407       Standard_Real first,last;
408       Handle(Geom_Curve) c3d = BRep_Tool::Curve(edge, first, last);
409       if(!c3d.IsNull()) {
410         Bnd_Box bb;
411         bb.Add(c3d->Value(first));
412         bb.Add(c3d->Value(last));
413         bb.Add(c3d->Value((last+first)/2.));
414         Standard_Real x1,x2,y1,y2,z1,z2,size;
415         bb.Get(x1,y1,z1,x2,y2,z2);
416         size = (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) + (z2-z1)*(z2-z1);
417         if(size<newpreci) newpreci=size;
418       }
419     }
420     newpreci=sqrt(newpreci)/2.*1.00001;
421     if( aSavPreci > newpreci && newpreci > Precision::Confusion()) {
422       SetPrecision(newpreci);
423       theAdvFixWire->SetPrecision(newpreci);    
424     }
425     // end skl 14.05.2002
426     */
427
428     // skl 29.03.2010 (OCC21623)
429     if( myAutoCorrectPrecisionMode ) {
430       Standard_Real size = ShapeFix::LeastEdgeSize(S);
431       Standard_Real newpreci = Min(aSavPreci,size/2.);
432       newpreci = newpreci*1.00001;
433       if( aSavPreci > newpreci && newpreci > Precision::Confusion()) {
434         SetPrecision(newpreci);
435         theAdvFixWire->SetPrecision(newpreci);    
436       }
437     }
438
439     isfixReorder = Standard_False;
440     for ( TopoDS_Iterator iter(S,Standard_False); iter.More(); iter.Next()) { 
441       if(iter.Value().ShapeType() != TopAbs_WIRE) {
442         B.Add ( tmpFace, iter.Value() );
443         continue;
444       }
445       TopoDS_Wire wire = TopoDS::Wire ( iter.Value() );
446       theAdvFixWire->Load ( wire );
447       if(theAdvFixWire->NbEdges() == 0) {
448         if(theAdvFixWire->WireData()->NbNonManifoldEdges())
449           B.Add ( tmpFace, wire );
450         else {
451           fixed = Standard_True;
452           myStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE5 );
453         }
454         continue;
455       }
456       if ( theAdvFixWire->Perform() ) {
457         //fixed = Standard_True; 
458         isfixReorder =  (theAdvFixWire->StatusReorder(ShapeExtend_DONE) || isfixReorder);
459         fixed = (theAdvFixWire->StatusSmall(ShapeExtend_DONE) || 
460                theAdvFixWire->StatusConnected(ShapeExtend_DONE) ||
461                theAdvFixWire->StatusEdgeCurves(ShapeExtend_DONE) ||
462                theAdvFixWire->StatusNotches(ShapeExtend_DONE) ||  // CR0024983
463                theAdvFixWire->StatusDegenerated(ShapeExtend_DONE) ||
464                theAdvFixWire->StatusClosed(ShapeExtend_DONE));
465         TopoDS_Wire w = theAdvFixWire->Wire();
466         if(fixed) {
467           if ( ! Context().IsNull() ) Context()->Replace ( wire, w );
468           if(theAdvFixWire->NbEdges() == 0) {
469             myStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE5 );
470             continue;
471           }
472         }
473         else if(!wire.IsSame(w))
474           aMapReorderedWires.Bind(wire,w);
475         
476         wire = w;
477       }
478       B.Add ( tmpFace, wire );
479       //      if ( theAdvFixWire->Status ( ShapeExtend_FAIL ) )
480       //        myStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL1 );
481     }
482     
483     theAdvFixWire->FixLackingMode() = usFixLackingMode;
484     //theAdvFixWire->FixNotchedEdgesMode() = usFixNotchedEdgesMode;  // CR0024983
485     theAdvFixWire->FixSelfIntersectionMode() = usFixSelfIntersectionMode;
486     if ( ! myFwd ) tmpFace.Orientation ( TopAbs_REVERSED );
487     
488     if ( fixed ) {
489       //if ( ! myFwd ) tmpFace.Orientation ( TopAbs_REVERSED );
490       if ( ! Context().IsNull() ) Context()->Replace ( S, tmpFace );
491       //myFace = tmpFace;
492       isReplaced = Standard_True;
493     }
494     if(fixed || isfixReorder) {
495       myFace = tmpFace;
496       if (!theAdvFixWire->StatusReorder(ShapeExtend_DONE5)) {
497         myStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
498       }
499     }
500   }
501   
502   myResult = myFace;
503   TopoDS_Shape savShape = myFace; //gka BUG 6555
504
505   // Specific case for conic surfaces
506   if ( NeedFix(myFixPeriodicDegenerated) )
507     this->FixPeriodicDegenerated();
508
509   // fix missing seam
510   if ( NeedFix ( myFixMissingSeamMode ) ) {
511     if ( FixMissingSeam() ) {
512       myStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE3 );
513     }
514   }
515
516   // cycle by all possible faces coming from FixMissingSeam
517   // each face is processed as if it was single
518   TopExp_Explorer exp(myResult,TopAbs_FACE);
519   for ( ; exp.More(); exp.Next() ) {
520     myFace = TopoDS::Face ( exp.Current() );
521     Standard_Boolean NeedCheckSplitWire = Standard_False;
522
523     // perform second part of fixes on wires
524     if ( NeedFix ( myFixWireMode ) ) {
525       theAdvFixWire->SetFace ( myFace );
526       
527       Standard_Integer usFixSmallMode = theAdvFixWire->FixSmallMode();
528       Standard_Integer usFixConnectedMode = theAdvFixWire->FixConnectedMode();
529       Standard_Integer usFixEdgeCurvesMode =theAdvFixWire->FixEdgeCurvesMode(); 
530       Standard_Integer usFixDegeneratedMode  = theAdvFixWire->FixDegeneratedMode();
531       theAdvFixWire->FixSmallMode() = Standard_False;
532       theAdvFixWire->FixConnectedMode() = Standard_False;
533       theAdvFixWire->FixEdgeCurvesMode() = Standard_False; 
534       theAdvFixWire->FixDegeneratedMode() = Standard_False;
535       
536       Standard_Boolean fixed = Standard_False; 
537       TopoDS_Shape S = myFace;
538       if ( ! Context().IsNull() ) 
539         S = Context()->Apply ( myFace );
540       TopoDS_Shape emptyCopied = S.EmptyCopied();
541       TopoDS_Face tmpFace = TopoDS::Face(emptyCopied);
542       tmpFace.Orientation ( TopAbs_FORWARD );
543       for ( TopoDS_Iterator iter(S,Standard_False); iter.More(); iter.Next()) { 
544         if(iter.Value().ShapeType() != TopAbs_WIRE) {
545           B.Add ( tmpFace,iter.Value());
546           continue;
547         }
548         
549         TopoDS_Wire wire = TopoDS::Wire ( iter.Value() );
550         theAdvFixWire->Load ( wire );
551         if(theAdvFixWire->NbEdges() == 0) {
552           if(theAdvFixWire->WireData()->NbNonManifoldEdges())
553             B.Add ( tmpFace, wire );
554           else {
555             fixed = Standard_True;
556             myStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE5 );
557           }
558           continue;
559         }
560         if ( theAdvFixWire->Perform() ) {
561           isfixReorder =  theAdvFixWire->StatusReorder(ShapeExtend_DONE);
562           fixed = (theAdvFixWire->StatusLacking(ShapeExtend_DONE) ||
563                    theAdvFixWire->StatusSelfIntersection(ShapeExtend_DONE) ||
564                    theAdvFixWire->StatusNotches(ShapeExtend_DONE));  //Standard_True; 
565           TopoDS_Wire w = theAdvFixWire->Wire();
566           if(fixed) {
567             if ( ! Context().IsNull() ) Context()->Replace ( wire, w );
568             
569           }
570           else if(!wire.IsSame(w))
571             aMapReorderedWires.Bind(wire,w);
572
573           wire = w;
574         }
575         if(theAdvFixWire->StatusRemovedSegment())
576           NeedCheckSplitWire = Standard_True;
577   
578         //fix for loop of wire
579         TopTools_SequenceOfShape aLoopWires;
580         if(NeedFix ( myFixLoopWiresMode) && FixLoopWire(aLoopWires)) {
581           if (aLoopWires.Length() > 1)
582             SendWarning ( wire, Message_Msg ( "FixAdvFace.FixLoopWire.MSG0" ) );// Wire was splitted on several wires
583           myStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE7 );
584           fixed = Standard_True;
585           Standard_Integer k=1;
586           for( ; k <= aLoopWires.Length(); k++)
587             B.Add (tmpFace,aLoopWires.Value(k));
588         }
589         else
590           B.Add ( tmpFace, wire );
591       }
592     
593       theAdvFixWire->FixSmallMode() = usFixSmallMode;
594       theAdvFixWire->FixConnectedMode() = usFixConnectedMode;
595       theAdvFixWire->FixEdgeCurvesMode() = usFixEdgeCurvesMode; 
596       theAdvFixWire->FixDegeneratedMode() = usFixDegeneratedMode;
597
598       if ( fixed ) {
599         if ( ! myFwd ) tmpFace.Orientation ( TopAbs_REVERSED );
600         if(!isReplaced && !aInitFace.IsSame(myResult) && ! Context().IsNull()) //gka 06.09.04 BUG 6555
601           Context()->Replace(aInitFace,savShape);
602         if ( ! Context().IsNull() ) Context()->Replace ( S, tmpFace );
603         myFace = tmpFace;
604         myStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
605       }
606     }
607     
608     if(NeedCheckSplitWire) {
609       // try to split wire - it is needed if some segments were removed
610       // in ShapeFix_Wire::FixSelfIntersection()
611       TopoDS_Shape S = myFace;
612       if ( ! Context().IsNull() ) 
613         S = Context()->Apply ( myFace );
614       TopoDS_Shape emptyCopied = S.EmptyCopied();
615       TopoDS_Face tmpFace = TopoDS::Face(emptyCopied);
616       tmpFace.Orientation ( TopAbs_FORWARD );
617       TopTools_SequenceOfShape aWires;
618       Standard_Integer nbw=0;
619       for ( TopoDS_Iterator iter(S,Standard_False); iter.More(); iter.Next()) { 
620         if(iter.Value().ShapeType() != TopAbs_WIRE) {
621           B.Add (tmpFace,iter.Value());
622           continue;
623         }
624         if(iter.Value().Orientation() != TopAbs_FORWARD && 
625            iter.Value().Orientation() != TopAbs_REVERSED) {
626           B.Add (tmpFace,TopoDS::Wire(iter.Value()));
627           continue;
628         }
629         nbw++;
630         TopoDS_Wire wire = TopoDS::Wire ( iter.Value() );
631         SplitWire(tmpFace,wire,aWires);
632       }
633       if(nbw<aWires.Length()) {
634         for(Standard_Integer iw=1; iw<=aWires.Length(); iw++)
635           B.Add (tmpFace,aWires.Value(iw));
636         if ( ! Context().IsNull() ) Context()->Replace ( S, tmpFace );
637         myStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE8 );
638         myFace = tmpFace;
639       }
640     }
641
642     // fix intersecting wires
643     if(FixWiresTwoCoincEdges())
644       myStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE7 );
645     if ( NeedFix ( myFixIntersectingWiresMode ) ) {
646       if ( FixIntersectingWires() ) {
647         myStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE6 );
648       }
649     }
650
651     // fix orientation
652     TopTools_DataMapOfShapeListOfShape MapWires;
653     MapWires.Clear();
654     if ( NeedFix ( myFixOrientationMode ) ) {
655       if ( FixOrientation(MapWires) )
656         myStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE2 );
657     }
658
659     BRepTools::Update(myFace);
660
661     // fix natural bounds
662     Standard_Boolean NeedSplit = Standard_True;
663     if ( NeedFix ( myFixAddNaturalBoundMode ) ) {
664       if ( FixAddNaturalBound() ) {
665         NeedSplit = Standard_False;
666         myStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE5 );
667       }
668     }
669
670     // split face
671     if ( NeedFix ( myFixSplitFaceMode ) && NeedSplit && MapWires.Extent()>1 ) {
672       if ( FixSplitFace(MapWires) )
673         myStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE8 );
674     }
675
676   }
677   
678   //return the original preci
679   SetPrecision(aSavPreci);
680   theAdvFixWire->SetPrecision(aSavPreci);
681   
682   // cycle by all possible faces coming from FixAddNaturalBound
683   // each face is processed as if it was single 
684   for ( exp.Init(myResult,TopAbs_FACE); exp.More(); exp.Next() ) {
685     myFace = TopoDS::Face ( exp.Current() );
686
687     // fix small-area wires
688     if ( NeedFix ( myFixSmallAreaWireMode, Standard_False ) ) {
689       if ( FixSmallAreaWire() )
690         myStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE4 );
691     }
692   }
693   
694     
695   if ( ! Context().IsNull() ) {
696     if(Status ( ShapeExtend_DONE ) && !isReplaced && !aInitFace.IsSame(savShape))
697     {
698       //gka fix in order to avoid lost messages (following OCC21771)
699       if(aMapReorderedWires.Extent())
700       {
701         TopoDS_Iterator aItW(aInitFace,Standard_False);
702         for( ; aItW.More() ; aItW.Next())
703         {
704           TopoDS_Shape aCurW = aItW.Value();
705           while(aMapReorderedWires.IsBound(aCurW))
706           {
707             TopoDS_Shape aFixW = aMapReorderedWires.Find(aCurW);
708             Context()->Replace(aCurW, aFixW);
709             aCurW = aFixW;
710           }
711         }
712
713       }
714       Context()->Replace(aInitFace, savShape);
715     }
716     myResult = Context()->Apply ( aInitFace ); //gka 06.09.04
717   }
718   else if(!Status ( ShapeExtend_DONE ))
719     myResult = aInitFace;
720     
721   return Status ( ShapeExtend_DONE );
722 }
723
724 //=======================================================================
725 //function : Auxiliary functions
726 //purpose  : 
727 //=======================================================================
728
729 // Shift all pcurves of edges in the given wire on the given face 
730 // to vector <vec>
731 static void Shift2dWire(const TopoDS_Wire w, const TopoDS_Face f,
732                         const gp_Vec2d vec, 
733                         const Handle(ShapeAnalysis_Surface)& mySurf,
734                         Standard_Boolean recompute3d = Standard_False)
735 {
736   gp_Trsf2d tr2d;
737   tr2d.SetTranslation(vec.XY());
738   ShapeAnalysis_Edge sae;
739   ShapeBuild_Edge sbe;
740   BRep_Builder B;
741   for (TopoDS_Iterator ei (w,Standard_False); ei.More(); ei.Next()){
742     TopoDS_Edge edge = TopoDS::Edge(ei.Value());
743     Handle (Geom2d_Curve) C2d;
744     Standard_Real cf, cl;
745     if ( ! sae.PCurve(edge, f, C2d, cf, cl, Standard_True) ) continue; 
746     C2d->Transform(tr2d);
747     if ( recompute3d ) {
748       // recompute 3d curve and vertex
749       sbe.RemoveCurve3d ( edge );
750       sbe.BuildCurve3d ( edge );
751       B.UpdateVertex ( sae.FirstVertex(edge), mySurf->Value(C2d->Value(cf)), 0. );
752     }
753   }
754 }  
755
756 // Cut interval from the sequence of intervals
757 static Standard_Boolean CutInterval (TColgp_SequenceOfPnt2d &intervals, 
758                                      const gp_Pnt2d &toAddI,
759                                      const Standard_Real period)
760 {
761   if ( intervals.Length() <=0 ) return Standard_False;
762   for ( Standard_Integer j=0; j <2; j++ ) { // try twice, align to bottom and to top
763     for ( Standard_Integer i=1; i <= intervals.Length(); i++ ) {
764       gp_Pnt2d interval = intervals(i);
765       // ACIS907, OCC921 a054a.sat (face 124)
766       Standard_Real shift = ShapeAnalysis::AdjustByPeriod ( ( j ? toAddI.X() : toAddI.Y() ),
767                                                             0.5*( interval.X() + interval.Y() ),period);
768       gp_Pnt2d toAdd ( toAddI.X() + shift, toAddI.Y() + shift );
769       if ( toAdd.Y() <= interval.X() || toAdd.X() >= interval.Y() ) continue;
770       if ( toAdd.X() > interval.X() ) {
771         if ( toAdd.Y() < interval.Y() ) {
772           intervals.InsertBefore ( i, interval );
773           intervals.ChangeValue(i+1).SetX ( toAdd.Y() ); // i++...
774         }
775         intervals.ChangeValue(i).SetY ( toAdd.X() );
776       }
777       else if ( toAdd.Y() < interval.Y() ) {
778         intervals.ChangeValue(i).SetX ( toAdd.Y() );
779       }
780       else intervals.Remove ( i-- );
781     }
782   }
783   return Standard_True;
784 }
785
786 // Find middle of the biggest interval
787 static Standard_Real FindBestInterval (TColgp_SequenceOfPnt2d &intervals)
788 {
789   Standard_Real shift = 0., max = -1.;
790   for ( Standard_Integer i=1; i <= intervals.Length(); i++ ) {
791     gp_Pnt2d interval = intervals(i);
792     if ( interval.Y() - interval.X() <= max ) continue;
793     max = interval.Y() - interval.X();
794     shift = interval.X() + 0.5 * max;
795   }
796   return shift;
797 }
798
799 //=======================================================================
800 //function : FixAddNaturalBound
801 //purpose  : 
802 //=======================================================================
803 // Detect missing natural bounary on spherical surfaces and add it if 
804 // necessary
805 //pdn 981202: add natural bounds if missing (on sphere only)
806 //:abv 28.08.01: rewritten and extended for toruses
807
808 Standard_Boolean ShapeFix_Face::FixAddNaturalBound()
809 {
810   if ( ! Context().IsNull() ) {
811     TopoDS_Shape S = Context()->Apply ( myFace );
812     myFace = TopoDS::Face ( S );
813   }
814   
815   // collect wires in sequence
816   TopTools_SequenceOfShape ws;
817   TopTools_SequenceOfShape vs;
818   TopoDS_Iterator wi (myFace,Standard_False);
819   for ( ; wi.More(); wi.Next()) {
820     if(wi.Value().ShapeType() == TopAbs_WIRE &&
821        (wi.Value().Orientation() == TopAbs_FORWARD || wi.Value().Orientation() == TopAbs_REVERSED))
822       ws.Append (wi.Value());
823     else
824       vs.Append(wi.Value());
825   }
826
827   // deal with the case of an empty face: just create a new face by a standard tool
828   if (ws.IsEmpty() && !IsSurfaceUVInfinite (mySurf->Surface()))
829   {
830     BRepBuilderAPI_MakeFace aFaceBuilder (mySurf->Surface(), Precision::Confusion());
831
832     TopoDS_Face aNewFace = aFaceBuilder.Face();
833     aNewFace.Orientation (myFace.Orientation());
834
835     if ( ! Context().IsNull() )
836       Context()->Replace (myFace, aNewFace);
837
838     // taking into account orientation
839     myFace = aNewFace;
840
841     //gka 11.01.99 file PRO7755.stp entity #2018 surface #1895: error BRepLib_MakeFace func IsDegenerated
842     Handle(ShapeFix_Edge) sfe = myFixWire->FixEdgeTool();
843     for (TopExp_Explorer Eed (myFace, TopAbs_EDGE); Eed.More(); Eed.Next()) {
844       TopoDS_Edge edg = TopoDS::Edge (Eed.Current());
845       sfe->FixVertexTolerance(edg);
846     }
847
848 //    B.UpdateFace (myFace,myPrecision);
849     SendWarning ( myFace, Message_Msg ( "FixAdvFace.FixOrientation.MSG0" ) );// Face created with natural bounds
850     BRepTools::Update(myFace);
851     myResult = myFace;
852     return Standard_True;
853   }
854
855   // check if surface is double-closed and fix is needed
856   if ( !IsSurfaceUVPeriodic (mySurf->Surface()) || ShapeAnalysis::IsOuterBound (myFace) ) 
857     return Standard_False;
858
859   // Collect informations on free intervals in U and V
860   TColgp_SequenceOfPnt2d intU, intV, centers;
861   Standard_Real SUF, SUL, SVF, SVL;
862   mySurf->Bounds(SUF, SUL, SVF, SVL);
863   intU.Append ( gp_Pnt2d(SUF, SUL) );
864   intV.Append ( gp_Pnt2d(SVF, SVL) );
865   Standard_Integer nb = ws.Length();
866   Standard_Integer i;
867   for ( i=1; i <= nb; i ++) {
868     Standard_Real Umin, Vmin, Umax, Vmax;
869 //     Bnd_Box2d B;
870     TopoDS_Wire aw = TopoDS::Wire (ws.Value(i));
871     // PTV 01.11.2002 ACIS907, OCC921 begin
872 //     BRepTools::AddUVBounds(myFace,aw,B);
873 //     B.Get(Umin, Vmin, Umax, Vmax);
874     TopoDS_Face aWireFace = TopoDS::Face( myFace.EmptyCopied() );
875     BRep_Builder aB;
876     aB.Add( aWireFace, aw );
877     ShapeAnalysis::GetFaceUVBounds(aWireFace, Umin, Umax, Vmin, Vmax);
878     // PTV 01.11.2002 ACIS907, OCC921 end
879     if ( mySurf->IsUClosed() ) CutInterval ( intU, gp_Pnt2d(Umin,Umax), SUL-SUF );
880     if ( mySurf->IsVClosed() ) CutInterval ( intV, gp_Pnt2d(Vmin,Vmax), SVL-SVF );
881     centers.Append ( gp_Pnt2d ( 0.5*(Umin+Umax), 0.5*(Vmin+Vmax) ) );
882   }
883
884   // find best interval and thus compute shift
885   gp_Pnt2d shift(0.,0.);
886   if ( mySurf->IsUClosed() ) shift.SetX ( FindBestInterval ( intU ) );
887   if ( mySurf->IsVClosed() ) shift.SetY ( FindBestInterval ( intV ) );
888
889   // Adjust all other wires to be inside outer one
890   gp_Pnt2d center ( shift.X() + 0.5*(SUL-SUF), shift.Y() + 0.5*(SVL-SVF) );
891   for ( i=1; i <= nb; i++ ) {
892     TopoDS_Wire wire = TopoDS::Wire (ws.Value(i));
893     gp_Pnt2d sh(0.,0.);
894     if ( mySurf->IsUClosed() ) 
895       sh.SetX ( ShapeAnalysis::AdjustByPeriod ( centers(i).X(), center.X(), SUL-SUF ) );
896     if ( mySurf->IsVClosed() ) 
897       sh.SetY ( ShapeAnalysis::AdjustByPeriod ( centers(i).Y(), center.Y(), SVL-SVF ) );
898     Shift2dWire ( wire, myFace, sh.XY(), mySurf );
899   }
900   
901   // Create naturally bounded surface and add that wire to sequence
902 /* variant 1
903   // Create fictive grid and call ComposeShell 
904   Handle(Geom_RectangularTrimmedSurface) RTS = 
905     new Geom_RectangularTrimmedSurface ( mySurf->Surface(), SUF+shift.X(), SUL+shift.X(), 
906                                          SVF+shift.Y(), SVL+shift.Y() );
907   Handle(TColGeom_HArray2OfSurface) grid = new TColGeom_HArray2OfSurface ( 1, 1, 1, 1 );
908   grid->SetValue ( 1, 1, RTS );
909   Handle(ShapeExtend_CompositeSurface) G = new ShapeExtend_CompositeSurface ( grid );
910   TopLoc_Location L;
911     
912   ShapeFix_ComposeShell CompShell;
913   CompShell.Init ( G, L, myFace, ::Precision::Confusion() );
914   CompShell.ClosedMode() = Standard_True;
915   CompShell.NaturalBoundMode() = Standard_True;
916   CompShell.SetContext( Context() );
917   CompShell.SetMaxTolerance(MaxTolerance());
918   CompShell.Perform();
919   TopoDS_Shape res = CompShell.Result();
920   
921   Context()->Replace ( myFace, res );
922   for (TopExp_Explorer exp ( res, TopAbs_FACE ); exp.More(); exp.Next() ) {
923     myFace = TopoDS::Face ( exp.Current() );
924     BRepTools::Update(myFace); //:p4
925   }
926   myResult = Context()->Apply ( myResult );
927 */
928 /* variant 2 */
929   TopLoc_Location L;
930   Handle(Geom_Surface) surf = BRep_Tool::Surface ( myFace, L );
931   BRepBuilderAPI_MakeFace mf (surf, Precision::Confusion());
932   TopoDS_Face ftmp = mf.Face();
933   ftmp.Location ( L );
934   for (wi.Initialize (ftmp,Standard_False); wi.More(); wi.Next()) {
935     if(wi.Value().ShapeType() != TopAbs_WIRE)
936       continue;
937     TopoDS_Wire wire = TopoDS::Wire ( wi.Value() );
938     ws.Append ( wire );
939     if ( shift.XY().Modulus() < ::Precision::PConfusion() ) continue;
940     Shift2dWire ( wire, myFace, shift.XY(), mySurf, Standard_True );
941   }
942
943   // Fix possible case on sphere when gap contains degenerated edge 
944   // and thus has a common part with natural boundary
945   // Such hole should be merged with boundary
946   if ( mySurf->Adaptor3d()->GetType() == GeomAbs_Sphere &&
947        ws.Length() == nb+1 ) {
948     Handle(ShapeExtend_WireData) bnd = 
949       new ShapeExtend_WireData ( TopoDS::Wire ( ws.Last() ) );
950     // code to become separate method FixTouchingWires()
951     for ( i=1; i <= nb; i++ ) {
952       Handle(ShapeExtend_WireData) sbwd = 
953         new ShapeExtend_WireData ( TopoDS::Wire ( ws.Value(i) ) );
954       for (Standard_Integer j=1; j <= sbwd->NbEdges(); j++ ) {
955         if ( ! BRep_Tool::Degenerated ( sbwd->Edge(j) ) ) continue;
956         // find corresponding place in boundary 
957         ShapeAnalysis_Edge sae;
958         TopoDS_Vertex V = sae.FirstVertex ( sbwd->Edge(j) );
959         Standard_Integer k;
960         for ( k=1; k <= bnd->NbEdges(); k++ ) {
961           if ( ! BRep_Tool::Degenerated ( bnd->Edge(k) ) ) continue;
962           if ( BRepTools::Compare ( V, sae.FirstVertex ( bnd->Edge(k) ) ) ) break;
963         }
964         if ( k > bnd->NbEdges() ) continue;
965         // and insert hole to that place
966         BRep_Builder B;
967         B.Degenerated ( sbwd->Edge(j), Standard_False );
968         B.Degenerated ( bnd->Edge(k), Standard_False );
969         sbwd->SetLast ( j );
970         bnd->Add ( sbwd, k+1 );
971         ws.Remove ( i-- );
972         nb--;
973         myFixWire->SetFace ( myFace );
974         myFixWire->Load ( bnd );
975         myFixWire->FixConnected();
976         myFixWire->FixDegenerated();
977         ws.SetValue ( ws.Length(), bnd->Wire() );
978         break;
979       }
980     }
981   }
982   
983   // Create resulting face
984   BRep_Builder B;
985   TopoDS_Shape S = myFace.EmptyCopied();
986   S.Orientation ( TopAbs_FORWARD );
987   for ( i = 1; i <= ws.Length(); i++ ) B.Add ( S, ws.Value(i) );
988   for ( i = 1; i <= vs.Length(); i++ ) B.Add ( S, vs.Value(i) );
989   if ( ! myFwd ) S.Orientation (TopAbs_REVERSED);
990   if ( ! Context().IsNull() ) Context()->Replace ( myFace, S );
991   myFace = TopoDS::Face ( S );
992   BRepTools::Update(myFace);
993   
994 /**/
995 #ifdef DEBUG
996   cout<<"Natural bound on sphere or torus with holes added"<<endl; // mise au point !
997 #endif
998   SendWarning ( myFace, Message_Msg ( "FixAdvFace.FixOrientation.MSG0" ) );// Face created with natural bounds
999   return Standard_True;
1000 }
1001
1002
1003 //=======================================================================
1004 //function : FixOrientation
1005 //purpose  : 
1006 //=======================================================================
1007
1008 Standard_Boolean ShapeFix_Face::FixOrientation() 
1009 {
1010   TopTools_DataMapOfShapeListOfShape MapWires;
1011   MapWires.Clear();
1012   return FixOrientation(MapWires);
1013 }
1014
1015
1016 //=======================================================================
1017 //function : FixOrientation
1018 //purpose  : 
1019 //=======================================================================
1020
1021 Standard_Boolean ShapeFix_Face::FixOrientation(TopTools_DataMapOfShapeListOfShape &MapWires) 
1022 {
1023   Standard_Boolean done = Standard_False;
1024   
1025   if ( ! Context().IsNull() ) {
1026     TopoDS_Shape S = Context()->Apply ( myFace );
1027     myFace = TopoDS::Face ( S );
1028   }
1029   TopTools_SequenceOfShape ws;
1030   TopTools_SequenceOfShape allSubShapes;
1031   // smh: BUC60810 : protection against very small wires (one-edge, null-length)
1032   TopTools_SequenceOfShape VerySmallWires; 
1033   for ( TopoDS_Iterator wi (myFace,Standard_False); wi.More(); wi.Next()) {
1034     if(wi.Value().ShapeType() == TopAbs_VERTEX || 
1035        (wi.Value().Orientation() != TopAbs_FORWARD && 
1036          wi.Value().Orientation() != TopAbs_REVERSED)) {
1037       allSubShapes.Append (wi.Value());
1038       //ws.Append (wi.Value());
1039       continue;
1040     }
1041     
1042     TopoDS_Iterator ei (wi.Value(),Standard_False);
1043     TopoDS_Edge anEdge;
1044     Standard_Real length = RealLast();
1045     if ( ei.More() ) {
1046       anEdge = TopoDS::Edge(ei.Value()); 
1047       ei.Next();
1048       if ( ! ei.More() ) {
1049         length = 0;
1050         Standard_Real First, Last;
1051         Handle(Geom_Curve) c3d;
1052         ShapeAnalysis_Edge sae;
1053         if ( sae.Curve3d(anEdge,c3d,First,Last) ) {
1054           gp_Pnt pntIni = c3d->Value(First);
1055           gp_XYZ prev;
1056           prev = pntIni.XYZ();
1057           Standard_Integer NbControl = 10;
1058           for ( Standard_Integer j = 1; j < NbControl; j++) {
1059             Standard_Real prm = ((NbControl-1-j)*First + j*Last)/(NbControl-1);
1060             gp_Pnt pntCurr = c3d->Value(prm);
1061             gp_XYZ curr = pntCurr.XYZ();
1062             gp_XYZ delta = curr - prev;
1063             length += delta.Modulus();
1064             prev = curr;
1065           }
1066         }
1067       }
1068     }
1069     else length = 0;
1070     if (length > ::Precision::Confusion()) {
1071       ws.Append (wi.Value());
1072       allSubShapes.Append (wi.Value());
1073     }
1074     else VerySmallWires.Append (wi.Value());
1075   }
1076   if ( VerySmallWires.Length() >0 ) done = Standard_True;
1077   
1078   Standard_Integer nb = ws.Length();
1079   Standard_Integer nbAll = allSubShapes.Length();
1080   BRep_Builder B;
1081
1082   // if no wires, just do nothing
1083   if ( nb <= 0) return Standard_False;
1084   Standard_Integer nbInternal=0;
1085   Standard_Boolean isAddNaturalBounds = (NeedFix (myFixAddNaturalBoundMode) && 
1086                                          IsSurfaceUVPeriodic (mySurf->Surface()));
1087   TColStd_SequenceOfInteger aSeqReversed;
1088   // if wire is only one, check its orientation
1089   if ( nb == 1 ) {
1090     // skl 12.04.2002 for cases with nbwires>1 (VerySmallWires>1)
1091     // make face with only one wire (ws.Value(1))
1092     TopoDS_Shape dummy = myFace.EmptyCopied();
1093     TopoDS_Face af = TopoDS::Face ( dummy );
1094     af.Orientation ( TopAbs_FORWARD );
1095     B.Add (af,ws.Value(1));
1096     if ((myFixAddNaturalBoundMode != Standard_True || //: abv 29.08.01: Spatial_firex_lofting.sat
1097          !IsSurfaceUVPeriodic (mySurf->Surface())    ) &&
1098         !ShapeAnalysis::IsOuterBound (af)                )
1099     {
1100       Handle(ShapeExtend_WireData) sbdw = 
1101         new ShapeExtend_WireData (TopoDS::Wire(ws.Value(1)));
1102       sbdw->Reverse ( myFace );
1103       ws.SetValue ( 1, sbdw->Wire() );
1104       SendWarning ( sbdw->Wire(), Message_Msg ( "FixAdvFace.FixOrientation.MSG5" ) );// Wire on face was reversed
1105       done = Standard_True;
1106 #ifdef DEBUG
1107       cout<<"Wire reversed"<<endl; // mise au point !
1108 #endif
1109     }
1110   }
1111   // in case of several wires, perform complex analysis
1112 //  ATTENTION ESSAI
1113 //  Plusieurs wires : orientations relatives
1114 //  Chaque wire doit "contenir" tous les autres
1115 //  Evidemment, en cas de peau de leopard, il peut y avoir probleme
1116   else {
1117 //    On prend chaque wire (NB: pcurves presentes !)
1118 //    En principe on devrait rejeter les wires non fermes (cf couture manque ?)
1119 //    On le classe par rapport aux autres, qui doivent tous etre, soit IN soit
1120 //    OUT. Sinon il y a imbrication -> SDB. Si IN, OK, si OUT on inverse
1121 //      (nb : ici pas myClos donc pas de pb de couture)
1122 //    Si au moins une inversion, il faut refaire la face (cf myRebil)
1123
1124     //:94 abv 30 Jan 98: calculate parametric precision
1125     
1126 //    GeomAdaptor_Surface& Ads = mySurf->Adaptor3d()->ChangeSurface();
1127 //    Standard_Real toluv = Min ( Ads.UResolution(Precision()), Ads.VResolution(Precision()) );
1128     Standard_Boolean uclosed = mySurf->IsUClosed();
1129     Standard_Boolean vclosed = mySurf->IsVClosed();
1130     Standard_Real SUF, SUL, SVF, SVL;
1131     mySurf->Bounds(SUF, SUL, SVF, SVL);
1132     Standard_Real uRange = SUL - SUF;
1133     Standard_Real vRange = SVL - SVF;
1134     
1135     TopTools_DataMapOfShapeListOfShape MW;
1136     TopTools_DataMapOfShapeInteger SI;
1137     TopTools_MapOfShape MapIntWires;
1138     MW.Clear();
1139     SI.Clear();
1140     MapIntWires.Clear();
1141     Standard_Integer NbOuts=0;
1142     Standard_Integer i;
1143
1144     NCollection_Array1<Bnd_Box2d> aWireBoxes(1, nb);
1145     Standard_Real uMiddle = 0, vMiddle = 0;
1146     Standard_Boolean isFirst = Standard_True;
1147     //create Bounding boxes for each wire
1148     for ( i = 1; i <= nb; i ++) {
1149       TopoDS_Shape aShape = ws.Value(i);
1150       TopoDS_Wire aWire = TopoDS::Wire (aShape);
1151       Bnd_Box2d aBox;
1152       Standard_Real cf,cl;
1153       TopoDS_Iterator ew (aWire);
1154       for(;ew.More(); ew.Next()) {
1155         TopoDS_Edge ed = TopoDS::Edge (ew.Value());
1156         Handle(Geom2d_Curve) cw = BRep_Tool::CurveOnSurface (ed,myFace,cf,cl);
1157         Geom2dAdaptor_Curve gac;
1158         Standard_Real aFirst = cw->FirstParameter();
1159         Standard_Real aLast = cw->LastParameter();
1160         if(cw->IsKind(STANDARD_TYPE(Geom2d_BSplineCurve)) && (cf < aFirst || cl > aLast)) {
1161           //avoiding problems with segment in Bnd_Box
1162           gac.Load(cw);
1163         }
1164        else
1165          gac.Load(cw,cf,cl);
1166        BndLib_Add2dCurve::Add(gac,::Precision::Confusion(),aBox);
1167       }
1168
1169       Standard_Real aXMin, aXMax, aYMin, aYMax;
1170       aBox.Get(aXMin, aYMin, aXMax, aYMax);
1171       if (isFirst) {
1172         isFirst = Standard_False;
1173         uMiddle = (aXMin + aXMax) * 0.5;
1174         vMiddle = (aYMin + aYMax) * 0.5;
1175       }
1176       else {
1177         Standard_Real xShift = 0, yShift = 0;
1178         if ( mySurf->IsUClosed() ) 
1179           xShift = ShapeAnalysis::AdjustByPeriod ( 0.5*(aXMin + aXMax), uMiddle, uRange );
1180         if ( mySurf->IsVClosed() ) 
1181           yShift = ShapeAnalysis::AdjustByPeriod ( 0.5*(aYMin + aYMax), vMiddle, vRange ) ;
1182         aBox.Update(aXMin + xShift, aYMin + yShift, aXMax + xShift, aYMax + yShift);
1183       }
1184       aWireBoxes.ChangeValue(i) = aBox;
1185     }
1186     
1187     for ( i = 1; i <= nb; i ++) {
1188       TopoDS_Shape asw = ws.Value(i);
1189       TopoDS_Wire aw = TopoDS::Wire (asw);
1190       Bnd_Box2d aBox1 = aWireBoxes.Value(i);
1191       TopoDS_Shape dummy = myFace.EmptyCopied();
1192       TopoDS_Face af = TopoDS::Face ( dummy );
1193 //      B.MakeFace (af,mySurf->Surface(),::Precision::Confusion());
1194       af.Orientation ( TopAbs_FORWARD );
1195       B.Add (af,aw);
1196       // PTV OCC945 06.11.2002 files ie_exhaust-A.stp (entities 3782,  3787)
1197       // tolerance is too big. It is seems that to identify placement of 2d point
1198       // it is enough Precision::PConfusion(), cause wea re know that 2d point in TopAbs_ON
1199       // BRepTopAdaptor_FClass2d clas (af,toluv);
1200       Standard_Boolean CheckShift = Standard_True;
1201       BRepTopAdaptor_FClass2d clas (af,::Precision::PConfusion());
1202       TopAbs_State sta = TopAbs_OUT;
1203       TopAbs_State staout = clas.PerformInfinitePoint();
1204       TopTools_ListOfShape IntWires;
1205       Standard_Integer aWireIt = 0;
1206       for ( Standard_Integer j = 1; j <= nbAll; j ++) {
1207         aWireIt++;
1208         //if(i==j) continue;
1209         TopoDS_Shape aSh2 = allSubShapes.Value(j);
1210         if(aw == aSh2)
1211           continue;
1212         TopAbs_State stb = TopAbs_UNKNOWN;
1213         if(aSh2.ShapeType() == TopAbs_VERTEX) {
1214           aWireIt--;
1215           gp_Pnt aP = BRep_Tool::Pnt(TopoDS::Vertex(aSh2));
1216           gp_Pnt2d p2d = mySurf->ValueOfUV(aP,Precision::Confusion());
1217           stb = clas.Perform (p2d,Standard_False);
1218           if(stb == staout && (uclosed || vclosed)) {
1219             gp_Pnt2d p2d1;
1220             if(uclosed) {
1221               p2d1.SetCoord(p2d.X()+uRange, p2d.Y());
1222               stb = clas.Perform (p2d1,Standard_False);
1223               
1224             }
1225             if(stb == staout && vclosed) {
1226               p2d1.SetCoord(p2d.X(), p2d.Y()+ vRange);
1227               stb = clas.Perform (p2d1,Standard_False);
1228             }
1229           }
1230         }
1231         else if (aSh2.ShapeType() == TopAbs_WIRE) {
1232           CheckShift = Standard_True;
1233           TopoDS_Wire bw = TopoDS::Wire (aSh2);
1234           //Standard_Integer numin =0;
1235           Bnd_Box2d aBox2 = aWireBoxes.Value(aWireIt);
1236           if (aBox2.IsOut(aBox1))
1237             continue;
1238
1239           TopoDS_Iterator ew (bw);
1240           for(;ew.More(); ew.Next()) {
1241             TopoDS_Edge ed = TopoDS::Edge (ew.Value());
1242             Standard_Real cf,cl;
1243             Handle(Geom2d_Curve) cw = BRep_Tool::CurveOnSurface (ed,myFace,cf,cl);
1244             if (cw.IsNull()) continue;
1245             gp_Pnt2d unp = cw->Value ((cf+cl)/2.);
1246             TopAbs_State ste = clas.Perform (unp,Standard_False);
1247             if( ste==TopAbs_OUT || ste==TopAbs_IN ) {
1248               if(stb==TopAbs_UNKNOWN) {
1249                 stb = ste;
1250               }
1251               else {
1252                 if(!(stb==ste)) {
1253                   sta = TopAbs_UNKNOWN;
1254                   SI.Bind(aw,0);
1255                   j=nb;
1256                   break;
1257                 }
1258               }
1259             }
1260           
1261             Standard_Boolean found = Standard_False;
1262             gp_Pnt2d unp1;
1263             if( stb == staout && CheckShift ) {
1264               CheckShift = Standard_False;
1265               if(uclosed) {
1266                 unp1.SetCoord(unp.X()+uRange, unp.Y());
1267                 found = (staout != clas.Perform (unp1,Standard_False));
1268                 if(!found) {
1269                   unp1.SetX(unp.X()-uRange);
1270                   found = (staout != clas.Perform (unp1,Standard_False));
1271                 }
1272               }
1273               if(vclosed&&!found) {
1274                 unp1.SetCoord(unp.X(), unp.Y()+vRange);
1275                 found = (staout != clas.Perform (unp1,Standard_False));
1276                 if(!found) {
1277                   unp1.SetY(unp.Y()-vRange);
1278                   found = (staout != clas.Perform (unp1,Standard_False));
1279                 }
1280               }
1281             }
1282             if(found) {
1283               if(stb==TopAbs_IN) stb = TopAbs_OUT;
1284               else stb = TopAbs_IN;
1285               Shift2dWire(bw,myFace,unp1.XY()-unp.XY(), mySurf);
1286             }
1287           }
1288         }
1289         if(stb==staout) {
1290           sta = TopAbs_IN;
1291         }
1292         else {
1293           IntWires.Append(aSh2);
1294           MapIntWires.Add(aSh2);
1295         }
1296       }
1297
1298       if (sta == TopAbs_UNKNOWN) {    // ERREUR
1299         SendWarning ( aw, Message_Msg ( "FixAdvFace.FixOrientation.MSG11" ) );// Cannot orient wire
1300       } 
1301       else {
1302         MW.Bind(aw,IntWires);
1303         if(sta==TopAbs_OUT) {
1304           NbOuts++;
1305           if(staout==TopAbs_IN) {
1306             // wire is OUT but InfinitePoint is IN => need to reverse
1307             ShapeExtend_WireData sewd (aw);
1308             sewd.Reverse(myFace);
1309             ws.SetValue (i,sewd.Wire());
1310             SendWarning ( sewd.Wire(), Message_Msg ( "FixAdvFace.FixOrientation.MSG5" ) );// Wire on face was reversed
1311             aSeqReversed.Append(i);
1312             done = Standard_True;
1313             SI.Bind(ws.Value(i),1);
1314             MapWires.Bind(ws.Value(i),IntWires);
1315           }
1316           else {
1317             SI.Bind(aw,1);
1318             MapWires.Bind(aw,IntWires);
1319           }
1320         }
1321         else {
1322           if(staout==TopAbs_OUT) SI.Bind(aw,2);
1323           else SI.Bind(aw,3);
1324         }
1325       }        
1326
1327     }
1328
1329     for(i=1; i<=nb; i++) {
1330       TopoDS_Wire aw = TopoDS::Wire (ws.Value(i));
1331       Standard_Integer tmpi = SI.Find(aw);
1332       if(tmpi>1) {
1333         if(!MapIntWires.Contains(aw)) {
1334           NbOuts++;
1335           const TopTools_ListOfShape& IW = MW.Find(aw);
1336           if(tmpi==3) {
1337             // wire is OUT but InfinitePoint is IN => need to reverse
1338             ShapeExtend_WireData sewd (aw);
1339             sewd.Reverse(myFace);
1340             ws.SetValue (i,sewd.Wire());
1341             SendWarning ( sewd.Wire(), Message_Msg ( "FixAdvFace.FixOrientation.MSG5" ) );// Wire on face was reversed
1342             aSeqReversed.Append(i);
1343             done = Standard_True;
1344             MapWires.Bind(ws.Value(i),IW);
1345           }
1346           else MapWires.Bind(aw,IW);
1347         }
1348         else {
1349           if(tmpi==2) {
1350             // wire is IN but InfinitePoint is OUT => need to reverse
1351             ShapeExtend_WireData sewd (aw);
1352             sewd.Reverse(myFace);
1353             ws.SetValue (i,sewd.Wire());
1354             SendWarning ( sewd.Wire(), Message_Msg ( "FixAdvFace.FixOrientation.MSG5" ) );// Wire on face was reversed
1355             aSeqReversed.Append(i);
1356             done = Standard_True;
1357           }
1358         }
1359       }
1360     }
1361
1362   }
1363
1364   //done = (done && (nb ==1 || (isAddNaturalBounds || (!isAddNaturalBounds && nbInternal <nb))));
1365   if(isAddNaturalBounds && nb == aSeqReversed.Length())
1366     done = Standard_False;
1367   else
1368     done = (done && (nb ==1 || (isAddNaturalBounds || (!isAddNaturalBounds && nbInternal <nb))));
1369   //    Faut-il reconstruire ? si myRebil est mis
1370   if ( done ) {
1371     TopoDS_Shape S = myFace.EmptyCopied();
1372     S.Orientation ( TopAbs_FORWARD );
1373     Standard_Integer i = 1;
1374     for ( ; i <= nb; i++ )
1375       B.Add ( S, ws.Value(i) );
1376     
1377     if(nb < nbAll) {
1378       for( i =1; i <= nbAll;i++) {
1379         TopoDS_Shape aS2 = allSubShapes.Value(i);
1380         if(aS2.ShapeType() != TopAbs_WIRE || 
1381            (aS2.Orientation() != TopAbs_FORWARD && aS2.Orientation() != TopAbs_REVERSED))
1382           B.Add ( S,aS2);
1383       }
1384     }
1385     
1386     if ( ! myFwd ) S.Orientation (TopAbs_REVERSED);
1387     if ( ! Context().IsNull() ) Context()->Replace ( myFace, S );
1388     myFace = TopoDS::Face ( S );
1389     BRepTools::Update(myFace);
1390     Standard_Integer k =1;
1391     for( ; k <= aSeqReversed.Length(); k++ )
1392     {
1393 #ifdef DEBUG
1394       cout<<"Wire no "<<aSeqReversed.Value(k)<<" of "<<nb<<" reversed"<<endl; // mise au point !
1395 #endif
1396     }
1397       
1398   }
1399   return done;
1400 }
1401
1402
1403 //=======================================================================
1404 //function : CheckWire
1405 //purpose  : auxilary for FixMissingSeam
1406 //=======================================================================
1407 //:i7 abv 18 Sep 98: ProSTEP TR9 r0501-ug.stp: algorithm of fixing missing seam changed
1408 // test whether the wire is opened on period of periodical surface
1409 static Standard_Boolean CheckWire (const TopoDS_Wire &wire, 
1410                                    const TopoDS_Face &face,
1411                                    const Standard_Real dU,
1412                                    const Standard_Real dV,
1413                                    Standard_Integer &isuopen,
1414                                    Standard_Integer &isvopen,
1415                                    Standard_Boolean &isDeg)
1416 {
1417   gp_XY vec;
1418   vec.SetX(0);
1419   vec.SetY(0);
1420   ShapeAnalysis_Edge sae;
1421
1422   isuopen = isvopen = 0;
1423   isDeg = Standard_True;
1424   for ( TopoDS_Iterator ed(wire); ed.More(); ed.Next() ) {
1425     TopoDS_Edge edge = TopoDS::Edge ( ed.Value() );
1426     if ( ! BRep_Tool::Degenerated ( edge ) ) isDeg = Standard_False;
1427     Handle(Geom2d_Curve) c2d;
1428     Standard_Real f, l;
1429     if ( ! sae.PCurve ( edge, face, c2d, f, l, Standard_True ) ) 
1430       return Standard_False;
1431     vec += c2d->Value(l).XY() - c2d->Value(f).XY();
1432   }
1433
1434   Standard_Real aDelta = Abs(vec.X())-dU;
1435   if(Abs(aDelta) < 0.1*dU)
1436   {
1437     if(vec.X() > 0.0)
1438     {
1439       isuopen = 1;
1440     }
1441     else
1442     {
1443       isuopen = -1;
1444     }
1445   }
1446   else
1447   {
1448     isuopen = 0;
1449   }
1450
1451   aDelta = Abs(vec.Y())-dV;
1452   if(Abs(aDelta) < 0.1*dV)
1453   {
1454     if(vec.Y() > 0.0)
1455     {
1456       isvopen = 1;
1457     }
1458     else
1459     {
1460       isvopen = -1;
1461     }
1462   }
1463   else
1464   {
1465     isvopen = 0;
1466   }
1467
1468   return isuopen || isvopen;
1469 }
1470
1471 //=======================================================================
1472 //function : FixMissingSeam
1473 //purpose  : 
1474 //=======================================================================
1475 Standard_Boolean ShapeFix_Face::FixMissingSeam() 
1476 {
1477   Standard_Boolean uclosed = mySurf->IsUClosed();
1478   Standard_Boolean vclosed = mySurf->IsVClosed();
1479   
1480   if ( ! uclosed && ! vclosed ) return Standard_False; 
1481   
1482   if ( ! Context().IsNull() ) {
1483     TopoDS_Shape S = Context()->Apply ( myFace );
1484     myFace = TopoDS::Face ( S );
1485   }
1486   
1487   //%pdn: surface should be made periodic before (see ShapeCustom_Surface)!
1488   if (mySurf->Surface()->IsKind(STANDARD_TYPE (Geom_BSplineSurface))) { 
1489     Handle (Geom_BSplineSurface) BSpl = Handle (Geom_BSplineSurface)::DownCast (mySurf->Surface());
1490     if (!BSpl->IsUPeriodic() && !BSpl->IsVPeriodic())
1491       return Standard_False;
1492   }
1493   
1494   Standard_Real URange, VRange, SUF, SUL, SVF, SVL;
1495   mySurf->Bounds ( SUF, SUL, SVF, SVL );
1496   Standard_Real fU1,fU2,fV1,fV2;
1497   BRepTools::UVBounds(myFace,fU1,fU2,fV1,fV2);
1498   
1499   //pdn OCC55 fix to faces without the wires to avoid identical first and last parameters
1500   if ( ::Precision::IsInfinite ( SUF ) || ::Precision::IsInfinite ( SUL ) ) {
1501     if ( ::Precision::IsInfinite ( SUF ) ) SUF = fU1;
1502     if ( ::Precision::IsInfinite ( SUL ) ) SUL = fU2;
1503     if(Abs(SUL-SUF) < ::Precision::PConfusion()) {
1504       if ( ::Precision::IsInfinite ( SUF ) ) SUF-=1000.;
1505       else SUL+=1000.;
1506     }
1507   }
1508   if ( ::Precision::IsInfinite ( SVF ) || ::Precision::IsInfinite ( SVL ) ) {
1509     if ( ::Precision::IsInfinite ( SVF ) ) SVF = fV1;
1510     if ( ::Precision::IsInfinite ( SVL ) ) SVL = fV2;
1511     if(Abs(SVL-SVF) < ::Precision::PConfusion()) {
1512       if ( ::Precision::IsInfinite ( SVF ) ) SVF-=1000.;
1513       else SVL+=1000.;
1514     }
1515   }
1516     
1517   URange = Min(Abs (SUL - SUF), Precision::Infinite());
1518   VRange = Min(Abs(SVL - SVF), Precision::Infinite());
1519 //  Standard_Real UTol = 0.2 * URange, VTol = 0.2 * VRange;
1520   Standard_Integer ismodeu = 0, ismodev = 0; //szv#4:S4163:12Mar99 was Boolean
1521   Standard_Integer isdeg1=0, isdeg2=0;
1522
1523   TopTools_SequenceOfShape ws;
1524   TopTools_SequenceOfShape aSeqNonManif;
1525   for ( TopoDS_Iterator wi(myFace,Standard_False); wi.More(); wi.Next() ) {
1526     if(wi.Value().ShapeType() != TopAbs_WIRE || 
1527        (wi.Value().Orientation() != TopAbs_FORWARD && wi.Value().Orientation() != TopAbs_REVERSED)) {
1528       aSeqNonManif.Append(wi.Value());
1529       continue;
1530     }
1531     ws.Append ( wi.Value() );
1532   }
1533     
1534   TopoDS_Wire w1, w2;
1535   Standard_Integer i;
1536   for ( i=1; i <= ws.Length(); i++ ) {
1537     TopoDS_Wire wire = TopoDS::Wire ( ws.Value(i) );
1538     Standard_Integer isuopen, isvopen;
1539     Standard_Boolean isdeg;
1540     if ( ! CheckWire ( wire, myFace, URange, VRange, isuopen, isvopen, isdeg ) ) 
1541       continue;
1542     if ( w1.IsNull() ) { w1 = wire; ismodeu = isuopen; ismodev = isvopen; isdeg1 = isdeg ? i : 0; }
1543     else if ( w2.IsNull() ) {
1544       if ( ismodeu == -isuopen && ismodev == -isvopen ) { w2 = wire; isdeg2 = isdeg ? i : 0; }
1545       else if ( ismodeu == isuopen && ismodev == isvopen ) {
1546         w2 = wire;
1547         isdeg2 = isdeg;
1548         //:abv 29.08.01: If wires are contraversal, reverse one of them
1549         // If first one is single degenerated edge, reverse it; else second
1550         if ( isdeg1 ) {
1551           w1.Reverse();
1552           ismodeu = -ismodeu;
1553           ismodev = -ismodev;
1554         }
1555         else {
1556           w2.Reverse();
1557 #ifdef DEB
1558           if ( ! isdeg2 ) cout << "Warning: ShapeFix_Face::FixMissingSeam(): wire reversed" << endl;
1559 #endif
1560         }
1561       }
1562 #ifdef DEB
1563       else cout << "Warning: ShapeFix_Face::FixMissingSeam(): incompatible open wires" << endl;
1564 #endif
1565     }
1566 //    else return Standard_False; //  abort
1567     else {
1568 #ifdef DEB
1569       cout << "Warning: ShapeFix_Face::FixMissingSeam(): more than two open wires detected!" << endl;
1570 #endif
1571       //:abv 30.08.09: if more than one open wires and more than two of them are
1572       // completely degenerated, remove any of them
1573       if ( isdeg || isdeg1 || isdeg2 ) {
1574         ws.Remove ( isdeg ? i : isdeg2 ? isdeg2 : isdeg1 );
1575         w1.Nullify();
1576         w2.Nullify();
1577         i = 0;
1578 #ifdef DEB
1579         cout << "Warning: ShapeFix_Face::FixMissingSeam(): open degenerated wire removed" << endl;
1580 #endif
1581         continue;
1582       }
1583     }
1584   }
1585
1586   BRep_Builder B;
1587   if ( w1.IsNull() ) return Standard_False;
1588   else if ( w2.IsNull()) {
1589     // For spheres and BSpline cone-like surfaces(bug 24055):
1590     // If only one of wires limiting face on surface is open in 2d,
1591     // this may means that degenerated edge should be added, and
1592     // then usual procedure applied
1593     gp_Pnt2d p;
1594     gp_Dir2d d;
1595     Standard_Real aRange;
1596
1597     if ( ismodeu && mySurf->Surface()->IsKind(STANDARD_TYPE(Geom_SphericalSurface)) ) {
1598       p.SetCoord ( ( ismodeu < 0 ? 0. : 2.*M_PI ), ismodeu * 0.5 * M_PI );
1599       Standard_Real aXCoord = -ismodeu;
1600       d.SetCoord ( aXCoord, 0.);
1601       aRange = 2.*M_PI;
1602     }
1603     else if ( ismodev && mySurf->Surface()->IsKind(STANDARD_TYPE(Geom_BSplineSurface))) {
1604       Standard_Real uCoord;
1605       if (mySurf->Value(SUF, SVF).Distance(mySurf->Value(SUF, (SVF + SVL) / 2)) < ::Precision::Confusion())
1606         uCoord = SUF;
1607       else if (mySurf->Value(SUL, SVF).Distance(mySurf->Value(SUL, (SVF + SVL) / 2)) < ::Precision::Confusion())
1608         uCoord = SUL;
1609       else return Standard_False;
1610
1611       p.SetCoord ( uCoord, ( ismodev < 0 ? 0. : VRange ) );
1612       d.SetCoord ( 0., -ismodev);
1613       aRange = VRange;
1614     }
1615     else if ( ismodeu && mySurf->Surface()->IsKind(STANDARD_TYPE(Geom_BSplineSurface))) {
1616       Standard_Real vCoord;
1617       if (mySurf->Value(SUF, SVF).Distance(mySurf->Value((SUF + SUL) / 2, SVF)) < ::Precision::Confusion())
1618         vCoord = SVF;
1619       else if (mySurf->Value(SUL, SVL).Distance(mySurf->Value((SUF + SUL) / 2, SVL)) < ::Precision::Confusion())
1620         vCoord = SVL;
1621       else return Standard_False;
1622
1623       p.SetCoord ( ( ismodeu < 0 ? 0. : URange ), vCoord );
1624       Standard_Real aXCoord = -ismodeu;
1625       d.SetCoord ( aXCoord, 0.);
1626       aRange = URange;
1627     }
1628     else return Standard_False;
1629
1630     Handle(Geom2d_Line) line = new Geom2d_Line ( p, d );
1631     TopoDS_Edge edge;
1632     B.MakeEdge ( edge );
1633     B.Degenerated ( edge, Standard_True );
1634     B.UpdateEdge ( edge, line, myFace, ::Precision::Confusion() );
1635     B.Range ( edge, myFace, 0., aRange );
1636     TopoDS_Vertex V;
1637     B.MakeVertex ( V, mySurf->Value ( p.X(), p.Y() ), ::Precision::Confusion() );
1638     V.Orientation(TopAbs_FORWARD);
1639     B.Add(edge,V);
1640     V.Orientation(TopAbs_REVERSED);
1641     B.Add(edge,V);
1642     B.MakeWire ( w2 );
1643     B.Add ( w2, edge );
1644     ws.Append ( w2 );
1645   }
1646   
1647   // sort original wires
1648   Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire;
1649   sfw->SetFace ( myFace );
1650   sfw->SetPrecision ( Precision() );
1651
1652   Handle(ShapeExtend_WireData) wd1 = new ShapeExtend_WireData ( w1 );
1653   Handle(ShapeExtend_WireData) wd2 = new ShapeExtend_WireData ( w2 );
1654
1655   // sorting
1656 //  Standard_Boolean degenerated = ( secondDeg != firstDeg );
1657 //  if ( ! degenerated ) {
1658     sfw->Load ( wd1 );
1659     sfw->FixReorder();
1660 //  }
1661   sfw->Load ( wd2 );
1662   sfw->FixReorder();
1663
1664   //:abv 29.08.01: reconstruct face taking into account reversing
1665   TopoDS_Shape dummy = myFace.EmptyCopied();
1666   TopoDS_Face tmpF = TopoDS::Face ( dummy );
1667   tmpF.Orientation ( TopAbs_FORWARD );
1668   for ( i=1; i <= ws.Length(); i++ ) {
1669     TopoDS_Wire wire = TopoDS::Wire ( ws.Value(i) );
1670     if ( wire.IsSame ( w1 ) ) wire = w1;
1671     else if ( wire.IsSame ( w2 ) ) wire = w2;
1672     B.Add ( tmpF, wire );
1673   }
1674   tmpF.Orientation ( myFace.Orientation() );
1675   
1676   Standard_Real uf=SUF, vf=SVF;
1677   
1678   // A special kind of FixShifted is necessary for torus-like
1679   // surfaces to adjust wires by period ALONG the missing SEAM direction
1680   // tr9_r0501-ug.stp #187640
1681   if ( uclosed && vclosed ) {
1682     Standard_Integer coord = ( ismodeu ? 1 : 0 );
1683     Standard_Integer isneg = ( ismodeu ? ismodeu : -ismodev );
1684     Standard_Real period = ( ismodeu ? URange : VRange );
1685     TopoDS_Shape S;
1686     Standard_Real m1[2][2], m2[2][2];
1687     S = tmpF.EmptyCopied();
1688     B.Add ( S, w1 );
1689     ShapeAnalysis::GetFaceUVBounds (TopoDS::Face(S), m1[0][0], m1[0][1], m1[1][0], m1[1][1]);
1690     S = tmpF.EmptyCopied();
1691     B.Add ( S, w2 );
1692     ShapeAnalysis::GetFaceUVBounds (TopoDS::Face(S), m2[0][0], m2[0][1], m2[1][0], m2[1][1]);
1693     Standard_Real shiftw2 = 
1694       ShapeAnalysis::AdjustByPeriod ( 0.5 * ( m2[coord][0] + m2[coord][1] ),
1695                                       0.5 * ( m1[coord][0] + m1[coord][1]  +
1696                                               isneg * ( period + ::Precision::PConfusion() ) ), 
1697                                       period );
1698     m1[coord][0] = Min ( m1[coord][0], m2[coord][0] + shiftw2 );
1699     m1[coord][1] = Max ( m1[coord][1], m2[coord][1] + shiftw2 );
1700     for ( TopoDS_Iterator it(tmpF,Standard_False); it.More(); it.Next() ) {
1701       if(it.Value().ShapeType() != TopAbs_WIRE)
1702         continue;
1703       TopoDS_Wire w = TopoDS::Wire ( it.Value() );
1704       if ( w == w1 ) continue;
1705       Standard_Real shift;
1706       if ( w == w2 ) shift = shiftw2;
1707       else {
1708         S = tmpF.EmptyCopied();
1709         B.Add ( S, w );
1710         ShapeAnalysis::GetFaceUVBounds (TopoDS::Face(S), m2[0][0], m2[0][1], m2[1][0], m2[1][1]);
1711         shift = ShapeAnalysis::AdjustByPeriod ( 0.5 * ( m2[coord][0] + m2[coord][1] ),
1712                                                 0.5 * ( m1[coord][0] + m1[coord][1] ), period );
1713       }
1714       if ( shift != 0. ) {
1715         gp_Vec2d V(0.,0.);
1716         V.SetCoord ( coord+1, shift );
1717         ShapeAnalysis_Edge sae;
1718         for ( TopoDS_Iterator iw(w); iw.More(); iw.Next() ) {
1719           TopoDS_Edge E = TopoDS::Edge ( iw.Value() );
1720           Handle(Geom2d_Curve) C;
1721           Standard_Real a, b;
1722           if ( ! sae.PCurve ( E, tmpF, C, a, b ) ) continue;
1723           C->Translate ( V );
1724         }
1725       }
1726     }
1727     // abv 05 Feb 02: OCC34
1728     // by the way, select proper split place by V to avoid extra intersections
1729     if ( m1[coord][1] - m1[coord][0] <= period ) {
1730       Standard_Real other = 0.5 * ( m1[coord][0] + m1[coord][1] - period );
1731       if ( ismodeu ) vf = other;
1732       else uf = other;
1733     }
1734   }
1735   
1736   // find the best place by u and v to insert a seam
1737   // (so as to minimize splitting edges as possible)
1738   ShapeAnalysis_Edge sae;
1739   Standard_Integer foundU=0, foundV=0;
1740   Standard_Integer nb1 = wd1->NbEdges();
1741   Standard_Integer nb2 = wd2->NbEdges();
1742   for ( Standard_Integer i1 = 1; i1 <= nb1 + nb2; i1++ ) {
1743     TopoDS_Edge edge1 = ( i1 <= nb1 ? wd1->Edge ( i1 ) : wd2->Edge ( i1-nb1 ) );
1744     Handle(Geom2d_Curve) c2d;
1745     Standard_Real f, l;
1746     if ( ! sae.PCurve ( edge1, tmpF, c2d, f, l, Standard_True ) ) return Standard_False;
1747     gp_Pnt2d pos1 = c2d->Value(l).XY();
1748     // the best place is end of edge which is nearest to 0 
1749     Standard_Boolean skipU = ! uclosed;
1750     if ( uclosed && ismodeu ) {
1751       pos1.SetX ( pos1.X() + ShapeAnalysis::AdjustByPeriod ( pos1.X(), SUF, URange ) );
1752       if ( foundU ==2 && Abs ( pos1.X() ) > Abs(uf) ) skipU = Standard_True;
1753       else if ( ! foundU || ( foundU ==1 && Abs ( pos1.X() ) < Abs(uf) ) ) {
1754         foundU = 1;
1755         uf = pos1.X();
1756       }
1757     }
1758     Standard_Boolean skipV = ! vclosed;
1759     if ( vclosed && ! ismodeu ) {
1760       pos1.SetY ( pos1.Y() + ShapeAnalysis::AdjustByPeriod ( pos1.Y(), SVF, VRange ) );
1761       if ( foundV ==2 && Abs ( pos1.Y() ) > Abs(vf) ) skipV = Standard_True;
1762       else if ( ! foundV || ( foundV ==1 && Abs ( pos1.Y() ) < Abs(vf) ) ) {
1763         foundV = 1;
1764         vf = pos1.Y();
1765       }
1766     }
1767     if ( skipU && skipV ) {
1768       if ( i1 <= nb1 ) continue;
1769       else break;
1770     }
1771     // or yet better - if it is end of some edges on both wires
1772     for ( Standard_Integer i2 = 1; i1 <= nb1 && i2 <= nb2; i2++ ) {
1773       TopoDS_Edge edge2 = wd2->Edge ( i2 );
1774       if ( ! sae.PCurve ( edge2, tmpF, c2d, f, l, Standard_True ) ) return Standard_False;
1775       gp_Pnt2d pos2 = c2d->Value(f).XY();
1776       if ( uclosed && ismodeu ) {
1777         pos2.SetX ( pos2.X() + ShapeAnalysis::AdjustByPeriod ( pos2.X(), pos1.X(), URange ) );
1778         if ( Abs ( pos2.X() - pos1.X() ) < ::Precision::PConfusion() &&
1779              ( foundU != 2 || Abs ( pos1.X() ) < Abs ( uf ) ) ) {
1780           foundU = 2;
1781           uf = pos1.X();
1782         }
1783       }
1784       if ( vclosed && ! ismodeu ) {
1785         pos2.SetY ( pos2.Y() + ShapeAnalysis::AdjustByPeriod ( pos2.Y(), pos1.Y(), VRange ) );
1786         if ( Abs ( pos2.Y() - pos1.Y() ) < ::Precision::PConfusion() &&
1787              ( foundV != 2 || Abs ( pos1.Y() ) < Abs ( vf ) ) ) {
1788           foundV = 2;
1789           vf = pos1.Y();
1790         }
1791       }
1792     }
1793   }
1794
1795   //pdn fixing RTS on offsets
1796   if ( uf < SUF || uf > SUL ) 
1797     uf+=ShapeAnalysis::AdjustToPeriod(uf,SUF,SUF+URange);
1798   if ( vf < SVF || vf > SVL )
1799     vf+=ShapeAnalysis::AdjustToPeriod(vf,SVF,SVF+VRange);
1800   
1801   // Create fictive grid and call ComposeShell to insert a seam
1802   Handle(Geom_RectangularTrimmedSurface) RTS = 
1803     new Geom_RectangularTrimmedSurface ( mySurf->Surface(), uf, uf+URange, vf, vf+VRange );
1804   Handle(TColGeom_HArray2OfSurface) grid = new TColGeom_HArray2OfSurface ( 1, 1, 1, 1 );
1805   grid->SetValue ( 1, 1, RTS ); //mySurf->Surface() );
1806   Handle(ShapeExtend_CompositeSurface) G = new ShapeExtend_CompositeSurface ( grid );
1807   TopLoc_Location L;
1808   
1809   //addition non-manifold topology
1810   Standard_Integer j=1;
1811   for( ; j <= aSeqNonManif.Length(); j++) 
1812     B.Add(tmpF,aSeqNonManif.Value(j));
1813   
1814   ShapeFix_ComposeShell CompShell;
1815 //  TopoDS_Face tmpF = myFace;
1816 //  tmpF.Orientation(TopAbs_FORWARD);
1817   CompShell.Init ( G, L, tmpF, ::Precision::Confusion() );//myPrecision 
1818   if ( Context().IsNull() ) SetContext ( new ShapeBuild_ReShape );
1819   CompShell.ClosedMode() = Standard_True;
1820   CompShell.SetContext( Context() );
1821   CompShell.SetMaxTolerance(MaxTolerance());
1822   CompShell.Perform();
1823   
1824   // abv 03.07.00: CAX-IF TRJ4: trj4_k1_goe-tu-214.stp: #785: reset mySurf
1825   mySurf = new ShapeAnalysis_Surface ( RTS );
1826
1827   myResult = CompShell.Result();
1828 //  if ( myFace.Orientation() == TopAbs_REVERSED ) res.Reverse();
1829   Context()->Replace ( myFace, myResult );
1830   for (TopExp_Explorer exp ( myResult, TopAbs_FACE ); exp.More(); exp.Next() ) {
1831     myFace = TopoDS::Face ( exp.Current() );
1832     BRepTools::Update(myFace); //:p4
1833   }
1834
1835   SendWarning ( Message_Msg ( "FixAdvFace.FixMissingSeam.MSG0" ) );// Missing seam-edge added
1836   return Standard_True;
1837 }
1838
1839 //=======================================================================
1840 //function : FixSmallAreaWire
1841 //purpose  : 
1842 //=======================================================================
1843
1844 //%14 pdn 24.02.99 PRO10109, USA60293 fix wire on face with small area.
1845 Standard_Boolean ShapeFix_Face::FixSmallAreaWire() 
1846 {
1847   if ( ! Context().IsNull() ) {
1848     TopoDS_Shape S = Context()->Apply ( myFace );
1849     myFace = TopoDS::Face ( S );
1850   }
1851   
1852   //smh#8
1853   TopoDS_Shape emptyCopied = myFace.EmptyCopied();
1854   TopoDS_Face face = TopoDS::Face (emptyCopied);
1855   Standard_Integer nbRemoved = 0, nbWires = 0;
1856   BRep_Builder B;
1857   Standard_Real prec = ::Precision::PConfusion()*100;
1858   for (TopoDS_Iterator wi (myFace, Standard_False); wi.More(); wi.Next()) {
1859     if(wi.Value().ShapeType() != TopAbs_WIRE && 
1860        (wi.Value().Orientation() != TopAbs_FORWARD && wi.Value().Orientation() != TopAbs_REVERSED))
1861         continue;
1862     TopoDS_Wire wire = TopoDS::Wire ( wi.Value() );
1863     Handle(ShapeAnalysis_Wire) saw = new ShapeAnalysis_Wire(wire,myFace,prec);
1864     if ( saw->CheckSmallArea(prec) )
1865     {
1866       SendWarning ( wire, Message_Msg ("FixAdvFace.FixSmallAreaWire.MSG0") );// Null area wire detected, wire skipped
1867       nbRemoved++;
1868     }
1869     else
1870     {
1871       B.Add(face,wire);
1872       nbWires++;
1873     }
1874   }
1875   if ( nbRemoved <=0 ) return Standard_False;
1876   
1877   if ( nbWires <=0 ) {
1878 #ifdef DEB
1879     cout << "Warning: ShapeFix_Face: All wires on a face have small area; left untouched" << endl;
1880 #endif
1881     return Standard_False;
1882   }
1883 #ifdef DEB
1884   cout << "Warning: ShapeFix_Face: " << nbRemoved << " small area wire(s) removed" << endl;
1885 #endif
1886   if ( ! Context().IsNull() ) Context()->Replace ( myFace, face );
1887   myFace = face;
1888   return Standard_True;
1889 }
1890 //=======================================================================
1891 //function : FixLoopWire
1892 //purpose  : 
1893 //=======================================================================
1894 static void FindNext(const TopoDS_Shape& aVert,
1895                      const TopoDS_Shape& ainitEdge,
1896                      TopTools_IndexedMapOfShape& aMapVertices,
1897                      TopTools_DataMapOfShapeListOfShape& aMapVertexEdges,
1898                      const TopTools_MapOfShape& aMapSmallEdges,
1899                      const TopTools_MapOfShape& aMapSeemEdges,
1900                      TopTools_MapOfShape& aMapEdges,
1901                      Handle(ShapeExtend_WireData)& aWireData)
1902 {
1903   TopoDS_Iterator aItV(ainitEdge);
1904   TopoDS_Shape anextVert = aVert;
1905   Standard_Boolean isFind = Standard_False;
1906   for( ; aItV.More() && !isFind; aItV.Next())
1907   {
1908     if(!aItV.Value().IsSame(aVert) ) {
1909       isFind = Standard_True;
1910       anextVert = aItV.Value();
1911       
1912     }
1913   }
1914
1915   if(!isFind && !aMapSmallEdges.Contains(ainitEdge)) 
1916     return;
1917   if(isFind && aMapVertices.Contains(anextVert))
1918     return;
1919
1920   const TopTools_ListOfShape& aledges = aMapVertexEdges.Find(anextVert);
1921   TopTools_ListIteratorOfListOfShape liter(aledges);
1922   isFind = Standard_False;
1923   TopoDS_Shape anextEdge;
1924   for( ; liter.More() && !isFind; liter.Next())
1925   {
1926     if(!aMapEdges.Contains(liter.Value()) && !liter.Value().IsSame(ainitEdge)) {
1927       anextEdge = liter.Value();
1928       aWireData->Add(anextEdge);
1929       if(aMapSeemEdges.Contains(anextEdge))
1930         aWireData->Add(anextEdge.Reversed());
1931       isFind = Standard_True;
1932       aMapEdges.Add(anextEdge);
1933       FindNext(anextVert,anextEdge,aMapVertices,aMapVertexEdges,aMapSmallEdges,aMapSeemEdges,aMapEdges,aWireData);
1934     }
1935   }
1936   return;
1937 }
1938
1939 static Standard_Boolean isClosed2D(const TopoDS_Face& aFace,const TopoDS_Wire& aWire)
1940 {
1941   Standard_Boolean isClosed = Standard_True;
1942   Handle(ShapeAnalysis_Wire) asaw = new ShapeAnalysis_Wire(aWire,aFace,Precision::Confusion());
1943   for (Standard_Integer i = 1; i <= asaw->NbEdges() && isClosed; i++) {
1944     TopoDS_Edge edge1 = asaw->WireData()->Edge(i);
1945     //checking that wire is closed in 2D space with tolerance of vertex.
1946     ShapeAnalysis_Edge sae;
1947     TopoDS_Vertex v1 = sae.FirstVertex(edge1);
1948     asaw->SetPrecision(BRep_Tool::Tolerance(v1));
1949     asaw->CheckGap2d(i);
1950     isClosed = (asaw->LastCheckStatus(ShapeExtend_OK));
1951     
1952   }
1953   return isClosed;
1954 }
1955
1956 //=======================================================================
1957 //function : FixLoopWire
1958 //purpose  : 
1959 //=======================================================================
1960
1961 Standard_Boolean ShapeFix_Face::FixLoopWire(TopTools_SequenceOfShape& aResWires)
1962 {
1963   TopTools_IndexedMapOfShape aMapVertices;
1964   TopTools_DataMapOfShapeListOfShape aMapVertexEdges;
1965   TopTools_MapOfShape aMapSmallEdges;
1966   TopTools_MapOfShape aMapSeemEdges;
1967   if(!FixWireTool()->Analyzer()->CheckLoop(aMapVertices, aMapVertexEdges,aMapSmallEdges,aMapSeemEdges))
1968     return Standard_False;
1969
1970   
1971   TopTools_MapOfShape aMapEdges;
1972   TopTools_SequenceOfShape aSeqWires;
1973
1974   //collecting wires from common vertex belonging more than 2 edges
1975   Standard_Integer i =1;
1976   for( ; i <= aMapVertices.Extent(); i++) {
1977     TopoDS_Shape aVert = aMapVertices.FindKey(i);
1978     const TopTools_ListOfShape& aledges = aMapVertexEdges.Find(aVert);
1979     TopTools_ListIteratorOfListOfShape liter(aledges);
1980     for( ; liter.More(); liter.Next())
1981     {
1982       TopoDS_Edge Edge = TopoDS::Edge(liter.Value());
1983       if(aMapEdges.Contains(Edge))
1984         continue;
1985       
1986       Handle(ShapeExtend_WireData) aWireData = new ShapeExtend_WireData;
1987       aWireData->Add(Edge);
1988        if(aMapSeemEdges.Contains(Edge))
1989         aWireData->Add(Edge.Reversed());
1990       aMapEdges.Add(Edge);
1991       FindNext(aVert,Edge,aMapVertices,aMapVertexEdges,aMapSmallEdges,aMapSeemEdges,aMapEdges,aWireData);
1992       if(aWireData->NbEdges() ==1 && aMapSmallEdges.Contains(aWireData->Edge(1)))
1993         continue;
1994       TopoDS_Vertex aV1,aV2;
1995       TopoDS_Wire aWire = aWireData->Wire();
1996       TopExp::Vertices(aWire,aV1,aV2);
1997       
1998       if(aV1.IsSame(aV2)) {
1999         Handle(ShapeExtend_WireData) asewd = new ShapeExtend_WireData(aWire);
2000         Handle(ShapeFix_Wire) asfw = new ShapeFix_Wire;
2001         asfw->Load(asewd);
2002         asfw->FixReorder();
2003         TopoDS_Wire awire2 = asfw->Wire();
2004         aResWires.Append(awire2);
2005         
2006       }
2007       else aSeqWires.Append(aWireData->Wire()); 
2008     }
2009   }
2010
2011
2012   if(aSeqWires.Length() ==1) {
2013     aResWires.Append(aSeqWires.Value(1));
2014   }
2015   else {
2016     //collecting whole wire from two not closed wires having two common vertices.
2017     for( i =1; i <= aSeqWires.Length(); i++) {
2018       TopoDS_Vertex aV1,aV2;
2019       TopoDS_Wire aWire = TopoDS::Wire(aSeqWires.Value(i));
2020       TopExp::Vertices(aWire,aV1,aV2);
2021       Standard_Integer j = i+1;
2022       for( ; j <= aSeqWires.Length(); j++)
2023       {
2024         TopoDS_Vertex aV21,aV22;
2025         TopoDS_Wire aWire2 = TopoDS::Wire(aSeqWires.Value(j));
2026         TopExp::Vertices(aWire2,aV21,aV22);
2027         if((aV1.IsSame(aV21) || aV1.IsSame(aV22)) && (aV2.IsSame(aV21) || aV2.IsSame(aV22)))
2028         {
2029           Handle(ShapeExtend_WireData) asewd = new ShapeExtend_WireData(aWire);
2030           asewd->Add(aWire2);
2031           Handle(ShapeFix_Wire) asfw = new ShapeFix_Wire;
2032           asfw->Load(asewd);
2033           asfw->FixReorder();
2034           aResWires.Append(asfw->Wire());
2035           aSeqWires.Remove(j--);
2036           myStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE7 );
2037           break;
2038         }
2039         
2040       }
2041       if(j <= aSeqWires.Length())
2042         aSeqWires.Remove(i--);
2043       
2044     }
2045     if(aSeqWires.Length()<3) {
2046       for( i =1; i <= aSeqWires.Length(); i++) 
2047         aResWires.Append(aSeqWires.Value(i));
2048       
2049     }
2050     else {
2051       //collecting wires having one common vertex
2052       for( i =1; i <= aSeqWires.Length(); i++) {
2053         TopoDS_Vertex aV1,aV2;
2054         TopoDS_Wire aWire = TopoDS::Wire(aSeqWires.Value(i));
2055         TopExp::Vertices(aWire,aV1,aV2);
2056         Standard_Integer j =i+1;
2057         for( ; j <= aSeqWires.Length(); j++)
2058         {
2059           TopoDS_Vertex aV21,aV22;
2060           TopoDS_Wire aWire2 = TopoDS::Wire(aSeqWires.Value(j));
2061           TopExp::Vertices(aWire2,aV21,aV22);
2062           if((aV1.IsSame(aV21) || aV1.IsSame(aV22)) || (aV2.IsSame(aV21) || aV2.IsSame(aV22)))
2063           {
2064             Handle(ShapeExtend_WireData) asewd = new ShapeExtend_WireData(aWire);
2065             asewd->Add(aWire2);
2066             Handle(ShapeFix_Wire) asfw = new ShapeFix_Wire;
2067             asfw->Load(asewd);
2068             asfw->FixReorder();
2069             aWire =  asfw->Wire();
2070             TopExp::Vertices(aWire,aV1,aV2);
2071             aSeqWires.Remove(j--);
2072             myStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE7 );
2073           }
2074         }
2075         aResWires.Append(aWire);
2076         
2077       }
2078     }
2079   }
2080   Standard_Boolean isClosed = Standard_True;
2081
2082   //checking that obtained wires is closed in 2D space
2083   if (mySurf->Adaptor3d()->GetType() != GeomAbs_Plane) {
2084     
2085     TopoDS_Shape emptyCopied = myFace.EmptyCopied(); 
2086     TopoDS_Face tmpFace = TopoDS::Face(emptyCopied);
2087     tmpFace.Orientation ( TopAbs_FORWARD );
2088     
2089     for(i =1; i <= aResWires.Length() && isClosed; i++) {
2090       TopoDS_Wire awire = TopoDS::Wire(aResWires.Value(i));
2091       isClosed = isClosed2D(tmpFace,awire);
2092     }
2093   }
2094   
2095   Standard_Boolean isDone =(aResWires.Length() && isClosed);
2096   if(isDone && aResWires.Length() >1)
2097   {
2098 #ifdef DEBUG
2099     cout<<"Wire was splitted on "<<aResWires.Length()<<" wires"<< endl;
2100 #endif
2101   }
2102
2103   return isDone; 
2104 }
2105
2106 //=======================================================================
2107 //function : SplitEdge
2108 //purpose  : 
2109 //=======================================================================
2110
2111 Standard_Boolean ShapeFix_Face::SplitEdge(const Handle(ShapeExtend_WireData)& sewd,
2112                                           const Standard_Integer num,
2113                                           const Standard_Real param,
2114                                           const TopoDS_Vertex& vert,
2115                                           const Standard_Real preci,
2116                                           ShapeFix_DataMapOfShapeBox2d& boxes) 
2117 {
2118   TopoDS_Edge edge = sewd->Edge(num);
2119   TopoDS_Edge newE1, newE2;
2120   ShapeFix_SplitTool aTool;
2121   if(aTool.SplitEdge(edge,param,vert,myFace,newE1,newE2,preci,0.01*preci)) {
2122     // change context
2123     Handle(ShapeExtend_WireData) wd = new ShapeExtend_WireData;
2124     wd->Add(newE1);
2125     wd->Add(newE2);
2126     if(!Context().IsNull()) Context()->Replace( edge, wd->Wire() );
2127     for (TopExp_Explorer exp ( wd->Wire(), TopAbs_EDGE ); exp.More(); exp.Next() ) {
2128       TopoDS_Edge E = TopoDS::Edge ( exp.Current() );
2129       BRepTools::Update(E);
2130     }
2131
2132 //    for ( Standard_Integer i=1; i <= sewd->NbEdges(); i++ ) {
2133 //      TopoDS_Edge E = sewd->Edge(i);
2134 //      TopoDS_Shape S = Context()->Apply ( E );
2135 //      if ( S == E ) continue;
2136 //      for ( TopExp_Explorer exp(S,TopAbs_EDGE); exp.More(); exp.Next() )
2137 //        sewd->Add ( exp.Current(), i++ );
2138 //      sewd->Remove ( i-- );
2139 //    }
2140
2141     // change sewd and boxes
2142     sewd->Set(newE1,num);
2143     if(num==sewd->NbEdges())
2144       sewd->Add(newE2);
2145     else
2146       sewd->Add(newE2,num+1);
2147
2148     boxes.UnBind(edge);
2149     TopLoc_Location L;
2150     const Handle(Geom_Surface)& S = BRep_Tool::Surface(myFace,L);
2151     Handle(Geom2d_Curve) c2d;
2152     Standard_Real cf,cl;
2153     ShapeAnalysis_Edge sae;
2154     if(sae.PCurve(newE1,S,L,c2d,cf,cl,Standard_False)) {
2155       Bnd_Box2d box;
2156       Geom2dAdaptor_Curve gac;
2157       Standard_Real aFirst = c2d->FirstParameter();
2158       Standard_Real aLast = c2d->LastParameter();
2159       if(c2d->IsKind(STANDARD_TYPE(Geom2d_BSplineCurve)) 
2160          && (cf < aFirst || cl > aLast)) {
2161         //pdn avoiding problems with segment in Bnd_Box
2162         gac.Load(c2d);
2163       }
2164       else
2165         gac.Load(c2d,cf,cl);
2166       BndLib_Add2dCurve::Add(gac,::Precision::Confusion(),box);
2167       boxes.Bind(newE1,box);
2168     }
2169     if(sae.PCurve(newE2,S,L,c2d,cf,cl,Standard_False)) {
2170       Bnd_Box2d box;
2171       Geom2dAdaptor_Curve gac;
2172       Standard_Real aFirst = c2d->FirstParameter();
2173       Standard_Real aLast = c2d->LastParameter();
2174       if(c2d->IsKind(STANDARD_TYPE(Geom2d_BSplineCurve)) 
2175          && (cf < aFirst || cl > aLast)) {
2176         //pdn avoiding problems with segment in Bnd_Box
2177         gac.Load(c2d);
2178       }
2179       else
2180         gac.Load(c2d,cf,cl);
2181       BndLib_Add2dCurve::Add(gac,::Precision::Confusion(),box);
2182       boxes.Bind(newE2,box);
2183     }
2184     return Standard_True;
2185   }
2186   return Standard_False;
2187 }
2188
2189
2190 //=======================================================================
2191 //function : SplitEdge
2192 //purpose  : 
2193 //=======================================================================
2194
2195 Standard_Boolean ShapeFix_Face::SplitEdge(const Handle(ShapeExtend_WireData)& sewd,
2196                                           const Standard_Integer num,
2197                                           const Standard_Real param1,
2198                                           const Standard_Real param2,
2199                                           const TopoDS_Vertex& vert,
2200                                           const Standard_Real preci,
2201                                           ShapeFix_DataMapOfShapeBox2d& boxes) 
2202 {
2203   TopoDS_Edge edge = sewd->Edge(num);
2204   TopoDS_Edge newE1, newE2;
2205   ShapeFix_SplitTool aTool;
2206   if(aTool.SplitEdge(edge,param1,param2,vert,myFace,newE1,newE2,preci,0.01*preci)) {
2207     // change context
2208     Handle(ShapeExtend_WireData) wd = new ShapeExtend_WireData;
2209     wd->Add(newE1);
2210     wd->Add(newE2);
2211     if(!Context().IsNull()) Context()->Replace( edge, wd->Wire() );
2212     for (TopExp_Explorer exp ( wd->Wire(), TopAbs_EDGE ); exp.More(); exp.Next() ) {
2213       TopoDS_Edge E = TopoDS::Edge ( exp.Current() );
2214       BRepTools::Update(E);
2215     }
2216
2217     // change sewd and boxes
2218     sewd->Set(newE1,num);
2219     if(num==sewd->NbEdges())
2220       sewd->Add(newE2);
2221     else
2222       sewd->Add(newE2,num+1);
2223
2224     boxes.UnBind(edge);
2225     TopLoc_Location L;
2226     const Handle(Geom_Surface)& S = BRep_Tool::Surface(myFace,L);
2227     Handle(Geom2d_Curve) c2d;
2228     Standard_Real cf,cl;
2229     ShapeAnalysis_Edge sae;
2230     if(sae.PCurve(newE1,S,L,c2d,cf,cl,Standard_False)) {
2231       Bnd_Box2d box;
2232       Geom2dAdaptor_Curve gac;
2233       Standard_Real aFirst = c2d->FirstParameter();
2234       Standard_Real aLast = c2d->LastParameter();
2235       if(c2d->IsKind(STANDARD_TYPE(Geom2d_BSplineCurve)) 
2236          && (cf < aFirst || cl > aLast)) {
2237         //pdn avoiding problems with segment in Bnd_Box
2238         gac.Load(c2d);
2239       }
2240       else
2241         gac.Load(c2d,cf,cl);
2242       BndLib_Add2dCurve::Add(gac,::Precision::Confusion(),box);
2243       boxes.Bind(newE1,box);
2244     }
2245     if(sae.PCurve(newE2,S,L,c2d,cf,cl,Standard_False)) {
2246       Bnd_Box2d box;
2247       Geom2dAdaptor_Curve gac;
2248       Standard_Real aFirst = c2d->FirstParameter();
2249       Standard_Real aLast = c2d->LastParameter();
2250       if(c2d->IsKind(STANDARD_TYPE(Geom2d_BSplineCurve)) 
2251          && (cf < aFirst || cl > aLast)) {
2252         //pdn avoiding problems with segment in Bnd_Box
2253         gac.Load(c2d);
2254       }
2255       else
2256         gac.Load(c2d,cf,cl);
2257       BndLib_Add2dCurve::Add(gac,::Precision::Confusion(),box);
2258       boxes.Bind(newE2,box);
2259     }
2260     return Standard_True;
2261   }
2262   return Standard_False;
2263 }
2264
2265
2266 //=======================================================================
2267 //function : FixIntersectingWires
2268 //purpose  : 
2269 //=======================================================================
2270
2271 Standard_Boolean ShapeFix_Face::FixIntersectingWires() 
2272 {
2273   ShapeFix_IntersectionTool ITool(Context(),Precision(),MaxTolerance());
2274   return ITool.FixIntersectingWires(myFace);
2275 }
2276
2277
2278 //=======================================================================
2279 //function : FixWiresTwoCoincEdges
2280 //purpose  : 
2281 //=======================================================================
2282
2283 Standard_Boolean ShapeFix_Face::FixWiresTwoCoincEdges() 
2284 {
2285   if ( ! Context().IsNull() ) {
2286     TopoDS_Shape S = Context()->Apply ( myFace );
2287     myFace = TopoDS::Face ( S );
2288   }
2289   
2290   TopAbs_Orientation ori = myFace.Orientation();
2291   TopoDS_Shape emptyCopied = myFace.EmptyCopied();
2292   TopoDS_Face face = TopoDS::Face (emptyCopied);
2293   face.Orientation(TopAbs_FORWARD);
2294   Standard_Integer nbWires = 0;
2295   BRep_Builder B;
2296   
2297   for (TopoDS_Iterator it (myFace, Standard_False); it.More(); it.Next()) {
2298     if(it.Value().ShapeType() != TopAbs_WIRE || 
2299        (it.Value().Orientation() != TopAbs_FORWARD && it.Value().Orientation() != TopAbs_REVERSED)) {
2300         continue;
2301     }
2302     nbWires++;
2303   }
2304   if(nbWires<2) return Standard_False;
2305   Standard_Boolean isFixed = Standard_False;
2306   for (TopoDS_Iterator wi (myFace, Standard_False); wi.More(); wi.Next()) {
2307     if(wi.Value().ShapeType() != TopAbs_WIRE ||
2308        (wi.Value().Orientation() != TopAbs_FORWARD && wi.Value().Orientation() != TopAbs_REVERSED)) {
2309       B.Add(face,wi.Value());
2310       continue;
2311     }
2312     TopoDS_Wire wire = TopoDS::Wire ( wi.Value() );
2313     Handle(ShapeExtend_WireData) sewd = new ShapeExtend_WireData(wire);
2314     if(sewd->NbEdges()==2) {
2315       TopoDS_Edge E1 = sewd->Edge(1);
2316       TopoDS_Edge E2 = sewd->Edge(2);
2317       E1.Orientation(TopAbs_FORWARD);
2318       E2.Orientation(TopAbs_FORWARD);
2319       if( !(E1==E2) ) {
2320         B.Add(face,wire);
2321       }
2322       else isFixed = Standard_True;
2323     }
2324     else {
2325       B.Add(face,wire);
2326     }
2327   }
2328   if(isFixed) {
2329     face.Orientation(ori);
2330     if ( ! Context().IsNull() ) Context()->Replace ( myFace, face );
2331     myFace = face;
2332   }
2333
2334   return isFixed;
2335 }
2336
2337
2338 //=======================================================================
2339 //function : FixSplitFace
2340 //purpose  : 
2341 //=======================================================================
2342
2343 Standard_Boolean ShapeFix_Face::FixSplitFace(const TopTools_DataMapOfShapeListOfShape &MapWires) 
2344 {
2345   BRep_Builder B;
2346   TopTools_SequenceOfShape faces;
2347   TopoDS_Shape S = myFace;
2348   if ( ! Context().IsNull() ) 
2349     S = Context()->Apply ( myFace );
2350   Standard_Integer NbWires=0, NbWiresNew=0, NbEdges;
2351   for(TopoDS_Iterator iter(S,Standard_False); iter.More(); iter.Next()) {
2352     const TopoDS_Shape& aShape = iter.Value();
2353     if(aShape.ShapeType() != TopAbs_WIRE || 
2354        (aShape.Orientation() != TopAbs_FORWARD && aShape.Orientation() != TopAbs_REVERSED))
2355         continue;
2356     TopoDS_Wire wire = TopoDS::Wire ( aShape );
2357     NbWires++;
2358     if(MapWires.IsBound(wire)) {
2359       // if wire not closed --> stop split and return false
2360       Handle(ShapeExtend_WireData) sewd = new ShapeExtend_WireData(wire);
2361       NbEdges = sewd->NbEdges();
2362       if (NbEdges == 0) {
2363         continue;
2364       }
2365       //
2366       TopoDS_Edge E1 = sewd->Edge(1);
2367       TopoDS_Edge E2 = sewd->Edge(NbEdges);
2368       TopoDS_Vertex V1,V2;
2369       ShapeAnalysis_Edge sae;
2370       V1=sae.FirstVertex(E1);
2371       V2=sae.LastVertex(E2);
2372       if(!V1.IsSame(V2)) {
2373         cout<<"wire not closed --> stop split"<<endl;
2374         return Standard_False;
2375       }
2376       // create face
2377       TopoDS_Shape emptyCopied = S.EmptyCopied();
2378       TopoDS_Face tmpFace = TopoDS::Face(emptyCopied);
2379       tmpFace.Orientation ( TopAbs_FORWARD );
2380       B.Add(tmpFace,wire);
2381       NbWiresNew++;
2382       const TopTools_ListOfShape& IntWires = MapWires.Find(wire);
2383       TopTools_ListIteratorOfListOfShape liter(IntWires);
2384       for( ; liter.More(); liter.Next()) {
2385         TopoDS_Shape aShape = tmpFace.EmptyCopied();
2386         TopoDS_Face aFace = TopoDS::Face ( aShape );
2387         aFace.Orientation ( TopAbs_FORWARD );
2388         B.Add (aFace,liter.Value());
2389         BRepTopAdaptor_FClass2d clas (aFace,::Precision::PConfusion());
2390         TopAbs_State staout = clas.PerformInfinitePoint();
2391         if (staout == TopAbs_IN) 
2392           B.Add(tmpFace,liter.Value());
2393         else
2394           B.Add(tmpFace,liter.Value().Reversed());                
2395         NbWiresNew++;
2396       }
2397       if(!myFwd) tmpFace.Orientation(TopAbs_REVERSED);
2398       faces.Append(tmpFace);
2399     }
2400   }
2401
2402   if(NbWires!=NbWiresNew) return Standard_False;
2403   
2404   if(faces.Length()>1) {
2405     TopoDS_Compound Comp;
2406     B.MakeCompound(Comp);
2407     for(Standard_Integer i=1; i<=faces.Length(); i++ ) 
2408       B.Add(Comp,faces(i));
2409     myResult = Comp;
2410     Context()->Replace ( myFace, myResult );
2411     for (TopExp_Explorer exp ( myResult, TopAbs_FACE ); exp.More(); exp.Next() ) {
2412       myFace = TopoDS::Face ( exp.Current() );
2413       BRepTools::Update(myFace);
2414     }
2415     return Standard_True;
2416   }
2417
2418   return Standard_False;
2419 }
2420
2421 //=======================================================================
2422 //function : IsPeriodicConicalLoop
2423 //purpose  : Checks whether the passed wire makes up a periodic loop on
2424 //           passed conical surface
2425 //=======================================================================
2426
2427 static Standard_Boolean IsPeriodicConicalLoop(const Handle(Geom_ConicalSurface)& theSurf,
2428                                               const TopoDS_Wire& theWire,
2429                                               const Standard_Real theTolerance,
2430                                               Standard_Real& theMinU,
2431                                               Standard_Real& theMaxU,
2432                                               Standard_Real& theMinV,
2433                                               Standard_Real& theMaxV,
2434                                               Standard_Boolean& isUDecrease)
2435 {
2436   if ( theSurf.IsNull() )
2437     return Standard_False;
2438
2439   ShapeAnalysis_Edge aSAE;
2440   TopLoc_Location aLoc;
2441
2442   Standard_Real aCumulDeltaU = 0.0, aCumulDeltaUAbs = 0.0;
2443   Standard_Real aMinU = RealLast();
2444   Standard_Real aMinV = aMinU;
2445   Standard_Real aMaxU = -aMinU;
2446   Standard_Real aMaxV = aMaxU;
2447
2448   // Iterate over the edges to check whether the wire is periodic on conical surface
2449   TopoDS_Iterator aWireIter(theWire, Standard_False);
2450   for ( ; aWireIter.More(); aWireIter.Next() )
2451   {
2452     const TopoDS_Edge& aCurrentEdge = TopoDS::Edge(aWireIter.Value());
2453     Handle(Geom2d_Curve) aC2d;
2454     Standard_Real aPFirst, aPLast;
2455
2456     aSAE.PCurve(aCurrentEdge, theSurf, aLoc, aC2d, aPFirst, aPLast, Standard_True);
2457
2458     if ( aC2d.IsNull() )
2459       return Standard_False;
2460
2461     gp_Pnt2d aUVFirst = aC2d->Value(aPFirst),
2462              aUVLast = aC2d->Value(aPLast);
2463
2464     Standard_Real aUFirst = aUVFirst.X(), aULast = aUVLast.X();
2465     Standard_Real aVFirst = aUVFirst.Y(), aVLast = aUVLast.Y();
2466
2467     Standard_Real aCurMaxU = Max(aUFirst, aULast),
2468                   aCurMinU = Min(aUFirst, aULast);
2469     Standard_Real aCurMaxV = Max(aVFirst, aVLast),
2470                   aCurMinV = Min(aVFirst, aVLast);
2471     
2472     if ( aCurMinU < aMinU )
2473       aMinU = aCurMinU;
2474     if ( aCurMaxU > aMaxU )
2475       aMaxU = aCurMaxU;
2476     if ( aCurMinV < aMinV )
2477       aMinV = aCurMinV;
2478     if ( aCurMaxV > aMaxV )
2479       aMaxV = aCurMaxV;
2480
2481     Standard_Real aDeltaU = aULast - aUFirst;
2482
2483     aCumulDeltaU += aDeltaU;
2484     aCumulDeltaUAbs += Abs(aDeltaU);
2485   }
2486
2487   theMinU = aMinU;
2488   theMaxU = aMaxU;
2489   theMinV = aMinV;
2490   theMaxV = aMaxV;
2491   isUDecrease = (aCumulDeltaU < 0 ? Standard_True : Standard_False);
2492
2493   Standard_Boolean is2PIDelta = Abs(aCumulDeltaUAbs - 2*M_PI) <= theTolerance;
2494   Standard_Boolean isAroundApex = Abs(theMaxU - theMinU) > 2*M_PI - theTolerance;
2495
2496   return is2PIDelta && isAroundApex;
2497 }
2498
2499 //=======================================================================
2500 //function : FixPeriodicDegenerated
2501 //purpose  : 
2502 //=======================================================================
2503
2504 Standard_Boolean ShapeFix_Face::FixPeriodicDegenerated() 
2505 {
2506   /* =====================
2507    *  Prepare fix routine
2508    * ===================== */
2509
2510   if ( !Context().IsNull() )
2511   {
2512     TopoDS_Shape aSh = Context()->Apply(myFace);
2513     myFace = TopoDS::Face(aSh);
2514   }
2515
2516   /* ================================================
2517    *  Check if fix can be applied on the passed face
2518    * ================================================ */
2519
2520   // Collect all wires owned by the face
2521   TopTools_SequenceOfShape aWireSeq;
2522   for ( TopoDS_Iterator aWireIt(myFace, Standard_False); aWireIt.More(); aWireIt.Next() )
2523   {
2524     const TopoDS_Shape& aSubSh = aWireIt.Value();
2525     if (  aSubSh.ShapeType() != TopAbs_WIRE || ( aSubSh.Orientation() != TopAbs_FORWARD &&
2526                                                  aSubSh.Orientation() != TopAbs_REVERSED ) ) 
2527       continue;
2528
2529     aWireSeq.Append( aWireIt.Value() );
2530   }
2531
2532   // Get number of wires and surface
2533   Standard_Integer aNbWires = aWireSeq.Length();
2534   Handle(Geom_Surface) aSurface = BRep_Tool::Surface(myFace);
2535
2536   // Only single wires on conical surfaces are checked
2537   if ( aNbWires != 1 || aSurface.IsNull() || 
2538        aSurface->DynamicType() != STANDARD_TYPE(Geom_ConicalSurface) )
2539     return Standard_False;
2540
2541   // Get the single wire
2542   TopoDS_Wire aSoleWire = TopoDS::Wire( aWireSeq.Value(1) );
2543
2544   // Check whether this wire is belting the conical surface by period
2545   Handle(Geom_ConicalSurface) aConeSurf = Handle(Geom_ConicalSurface)::DownCast(aSurface);
2546   Standard_Real aMinLoopU = 0.0, aMaxLoopU = 0.0, aMinLoopV = 0.0, aMaxLoopV = 0.0;
2547   Standard_Boolean isUDecrease = Standard_False;
2548
2549   Standard_Boolean isConicLoop = IsPeriodicConicalLoop(aConeSurf, aSoleWire, Precision(),
2550                                                        aMinLoopU, aMaxLoopU,
2551                                                        aMinLoopV, aMaxLoopV,
2552                                                        isUDecrease);
2553
2554   if ( !isConicLoop )
2555     return Standard_False;
2556
2557   /* ===============
2558    *  Retrieve apex
2559    * =============== */
2560
2561   // Get base circle of the conical surface (the circle it was built from)
2562   Handle(Geom_Curve) aConeBaseCrv = aConeSurf->VIso(0.0);
2563   Handle(Geom_Circle) aConeBaseCirc = Handle(Geom_Circle)::DownCast(aConeBaseCrv);
2564
2565   // Retrieve conical props
2566   Standard_Real aConeBaseR = aConeBaseCirc->Radius();
2567   Standard_Real aSemiAngle = aConeSurf->SemiAngle();
2568
2569   if ( fabs(aSemiAngle) <= Precision::Confusion() )
2570     return Standard_False; // Bad surface
2571
2572   // Find the V parameter of the apex
2573   Standard_Real aConeBaseH = aConeBaseR / Sin(aSemiAngle);
2574   Standard_Real anApexV = -aConeBaseH;
2575
2576   // Get apex vertex
2577   TopoDS_Vertex anApex = BRepBuilderAPI_MakeVertex( aConeSurf->Apex() );
2578
2579   // ====================================
2580   //  Build degenerated edge in the apex
2581   // ====================================
2582         
2583   TopoDS_Edge anApexEdge;
2584   BRep_Builder aBuilder;
2585   aBuilder.MakeEdge(anApexEdge);
2586
2587   // Check if positional relationship between the initial wire and apex
2588   // line in 2D is going to be consistent
2589   if ( fabs(anApexV - aMinLoopV) <= Precision() ||
2590        fabs(anApexV - aMaxLoopV) <= Precision() ||
2591       ( anApexV < aMaxLoopV && anApexV > aMinLoopV ) )
2592     return Standard_False;
2593
2594   Handle(Geom2d_Line) anApexCurve2d;
2595
2596   // Apex curve below the wire
2597   if ( anApexV < aMinLoopV )
2598   {
2599     anApexCurve2d = new Geom2d_Line( gp_Pnt2d(aMinLoopU, anApexV), gp_Dir2d(1, 0) );
2600     if ( !isUDecrease )
2601       aSoleWire.Reverse();
2602   }
2603
2604   // Apex curve above the wire
2605   if ( anApexV > aMaxLoopV )
2606   {
2607     anApexCurve2d = new Geom2d_Line( gp_Pnt2d(aMaxLoopU, anApexV), gp_Dir2d(-1, 0) );
2608     if ( isUDecrease )
2609       aSoleWire.Reverse();
2610   }
2611
2612   // Create degenerated edge & wire for apex
2613   aBuilder.UpdateEdge( anApexEdge, anApexCurve2d, myFace, Precision() );
2614   aBuilder.Add( anApexEdge, anApex );
2615   aBuilder.Add( anApexEdge, anApex.Reversed() );
2616   aBuilder.Degenerated(anApexEdge, Standard_True);
2617   aBuilder.Range( anApexEdge, 0, fabs(aMaxLoopU - aMinLoopU) );
2618   TopoDS_Wire anApexWire = BRepBuilderAPI_MakeWire(anApexEdge);
2619
2620   // ===============================================================
2621   //  Finalize the fix building new face and setting up the results
2622   // ===============================================================
2623
2624   // Collect the resulting set of wires
2625   TopTools_SequenceOfShape aNewWireSeq;
2626   aNewWireSeq.Append(aSoleWire);
2627   aNewWireSeq.Append(anApexWire);
2628
2629   // Assemble new face
2630   TopoDS_Face aNewFace = TopoDS::Face( myFace.EmptyCopied() );
2631   aNewFace.Orientation(TopAbs_FORWARD);
2632   BRep_Builder aFaceBuilder;
2633   for ( Standard_Integer i = 1; i <= aNewWireSeq.Length(); i++ )
2634   {
2635     TopoDS_Wire aNewWire = TopoDS::Wire( aNewWireSeq.Value(i) );
2636     aFaceBuilder.Add(aNewFace, aNewWire);
2637   }
2638   aNewFace.Orientation( myFace.Orientation() );
2639  
2640   // Adjust the resulting state of the healing tool
2641   myResult = aNewFace;
2642   Context()->Replace(myFace, myResult);
2643
2644   return Standard_True;
2645 }