0026656: ShapeFix_Face introduces extremely high vertex tolerance in the input shape
[occt.git] / src / ShapeFix / ShapeFix_Wire.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 //:j6 abv 7 Dec 98: ProSTEP TR10 r0601_id.stp #57676 & #58586: 
15 //    in FixIntersectingEdges, do not cut edges because of influence on adjacent faces
16 // pdn 17.12.98: shifting whole wire in FixShifted
17 //:k3 abv 24 Dec 98: BUC50070 #26682 and #30087: removing self-int loops on pcurves
18 // pdn 30.12.98: PRO10366 #210: shifting pcurve between two singularities
19 // pdn 05.01.98: renaming method FixLittle to FixSmall
20 //:l0 abv 10.01.99: remove unused code
21 //:n2 abv 22.01.99: ma-test5.igs: IGES read (pref3d): remove degen edge with no pcurve
22 //:o4 abv 17.02.99: r0301_db.stp #53082: using parameter isClosed in CheckOrder
23 //:p4 abv 23.02.99: PRO9234 #15720: update UV points of edges after shifting pcurves
24 //#67 rln 01.03.99 S4135: ims010.igs treatment of Geom_SphericalSurface together with V-closed surfaces
25 //:p7 abv 10.03.99 PRO18206: using method IsDegenerated() to detect singularity in FixLacking
26 //:r0 abv 19.03.99 PRO7226.stp #489490: remove degenerated edges if several
27 //#78 rln 12.03.99 S4135: checking spatial closure with Precision
28 //#79 rln 15.03.99 S4135: bmarkmdl.igs: check for gap before shifting on singularities
29 //    pdn 17.03.99 S4135: implemented fixing not adjacent intersection
30 //#86 rln 22.03.99 S4135: repeat of fix self-intersection if it was fixed just before
31 //%15 pdn 06.04.99 CTS18546-2: fix of self-intersection is repeated while fixed
32 //#3  smh 01.04.99 S4163: Overflow   
33 //#4  szv          S4163: optimization
34 //:r7 abv 12.04.99 S4136: FixLk: extend cases of adding degenerated edge
35 //:r8 abv 12.04.99 PRO10107.stp #2241: try increasing tolerance of edge for fix IE
36 //:s2 abv 21.04.99 S4136, PRO7978.igs: FixLacking extended to be able to bend pcurves
37 //szv#9:S4244:19Aug99 Methods FixGaps3d and FixGaps2d were introduced
38 //#15 smh 03.04.2000 PRO19800. Checking degenerated point on a surface of revolution.
39 // sln 25.09.2001  checking order of 3d and 2d representation curves  
40 // van 19.10.2001  fix of non-adjacent self-intersection corrected to agree with BRepCheck
41 // skl 07.03.2002 fix for bug OCC180
42 // skl 15.05.2002 for OCC208 (if few edges have reference to 
43 //                one pcurve we make replace pcurve)
44 // PTV 26.06.2002  Remove regressions after fix OCC450
45
46 #include <Adaptor3d_CurveOnSurface.hxx>
47 #include <Bnd_Array1OfBox2d.hxx>
48 #include <Bnd_Box2d.hxx>
49 #include <BndLib_Add2dCurve.hxx>
50 #include <BRep_Builder.hxx>
51 #include <BRep_GCurve.hxx>
52 #include <BRep_ListIteratorOfListOfCurveRepresentation.hxx>
53 #include <BRep_TEdge.hxx>
54 #include <BRep_Tool.hxx>
55 #include <BRepBuilderAPI_MakeEdge.hxx>
56 #include <BRepBuilderAPI_MakeVertex.hxx>
57 #include <BRepTools.hxx>
58 #include <Geom2d_BSplineCurve.hxx>
59 #include <Geom2d_Curve.hxx>
60 #include <Geom2d_Line.hxx>
61 #include <Geom2d_TrimmedCurve.hxx>
62 #include <Geom2dAdaptor_Curve.hxx>
63 #include <Geom2dAdaptor_HCurve.hxx>
64 #include <Geom2dConvert.hxx>
65 #include <Geom_BSplineCurve.hxx>
66 #include <Geom_Curve.hxx>
67 #include <Geom_OffsetCurve.hxx>
68 #include <Geom_Plane.hxx>
69 #include <Geom_SphericalSurface.hxx>
70 #include <Geom_Surface.hxx>
71 #include <Geom_SurfaceOfRevolution.hxx>
72 #include <Geom_TrimmedCurve.hxx>
73 #include <GeomAdaptor_Curve.hxx>
74 #include <GeomAdaptor_HSurface.hxx>
75 #include <GeomAdaptor_Surface.hxx>
76 #include <GeomAPI.hxx>
77 #include <GeomAPI_ProjectPointOnCurve.hxx>
78 #include <GeomConvert_CompCurveToBSplineCurve.hxx>
79 #include <gp_Pln.hxx>
80 #include <IntRes2d_IntersectionPoint.hxx>
81 #include <IntRes2d_SequenceOfIntersectionPoint.hxx>
82 #include <Message_Msg.hxx>
83 #include <Precision.hxx>
84 #include <ShapeAnalysis.hxx>
85 #include <ShapeAnalysis_Curve.hxx>
86 #include <ShapeAnalysis_Edge.hxx>
87 #include <ShapeAnalysis_Surface.hxx>
88 #include <ShapeAnalysis_TransferParameters.hxx>
89 #include <ShapeAnalysis_TransferParametersProj.hxx>
90 #include <ShapeAnalysis_Wire.hxx>
91 #include <ShapeAnalysis_WireOrder.hxx>
92 #include <ShapeBuild_Edge.hxx>
93 #include <ShapeBuild_ReShape.hxx>
94 #include <ShapeBuild_Vertex.hxx>
95 #include <ShapeConstruct_ProjectCurveOnSurface.hxx>
96 #include <ShapeExtend.hxx>
97 #include <ShapeExtend_WireData.hxx>
98 #include <ShapeFix.hxx>
99 #include <ShapeFix_Edge.hxx>
100 #include <ShapeFix_IntersectionTool.hxx>
101 #include <ShapeFix_SplitTool.hxx>
102 #include <ShapeFix_Wire.hxx>
103 #include <Standard_ErrorHandler.hxx>
104 #include <Standard_Failure.hxx>
105 #include <Standard_Type.hxx>
106 #include <TColgp_Array1OfPnt.hxx>
107 #include <TColgp_SequenceOfPnt.hxx>
108 #include <TColStd_Array1OfInteger.hxx>
109 #include <TColStd_Array1OfReal.hxx>
110 #include <TColStd_HSequenceOfReal.hxx>
111 #include <TopExp_Explorer.hxx>
112 #include <TopLoc_Location.hxx>
113 #include <TopoDS.hxx>
114 #include <TopoDS_Edge.hxx>
115 #include <TopoDS_Face.hxx>
116 #include <TopoDS_Vertex.hxx>
117 #include <TopoDS_Wire.hxx>
118 #include <TopTools_Array1OfShape.hxx>
119 #include <TopTools_HSequenceOfShape.hxx>
120
121 //S4135
122 //#######################################################################
123 //  Constructors, initializations, modes, querying
124 //#######################################################################
125 //=======================================================================
126 //function : ShapeFix_Wire
127 //purpose  : 
128 //=======================================================================
129 ShapeFix_Wire::ShapeFix_Wire() : myMaxTailAngleSine(0), myMaxTailWidth(-1)
130 {
131   myFixEdge = new ShapeFix_Edge;
132   myAnalyzer = new ShapeAnalysis_Wire;
133   ClearModes();
134   ClearStatuses();
135   myStatusRemovedSegment = Standard_False;
136 }
137
138 //=======================================================================
139 //function : ShapeFix_Wire
140 //purpose  : 
141 //=======================================================================
142
143 ShapeFix_Wire::ShapeFix_Wire (
144   const TopoDS_Wire& wire,
145   const TopoDS_Face &face,
146   const Standard_Real prec) : myMaxTailAngleSine(0), myMaxTailWidth(-1)
147 {
148   myFixEdge = new ShapeFix_Edge;
149   myAnalyzer = new ShapeAnalysis_Wire;
150   ClearModes();
151   SetMaxTolerance ( prec );
152   myStatusRemovedSegment = Standard_False;
153   Init ( wire, face, prec );
154 }
155
156 //=======================================================================
157 //function : SetPrecision
158 //purpose  : 
159 //=======================================================================
160
161 void ShapeFix_Wire::SetPrecision (const Standard_Real prec) 
162 {
163   ShapeFix_Root::SetPrecision ( prec );
164   myAnalyzer->SetPrecision ( prec );
165 }
166  
167 //=======================================================================
168 //function : SetMaxTailAngle
169 //purpose  :
170 //=======================================================================
171 void ShapeFix_Wire::SetMaxTailAngle(const Standard_Real theMaxTailAngle)
172 {
173   myMaxTailAngleSine = Sin(theMaxTailAngle);
174   myMaxTailAngleSine = (myMaxTailAngleSine >= 0) ? myMaxTailAngleSine : 0;
175 }
176
177 //=======================================================================
178 //function : SetMaxTailWidth
179 //purpose  :
180 //=======================================================================
181 void ShapeFix_Wire::SetMaxTailWidth(const Standard_Real theMaxTailWidth)
182 {
183   myMaxTailWidth = theMaxTailWidth;
184 }
185
186 //=======================================================================
187 //function : ClearModes
188 //purpose  : 
189 //=======================================================================
190
191 void ShapeFix_Wire::ClearModes()
192 {
193   myTopoMode = Standard_False;
194   myGeomMode = Standard_True;
195   myClosedMode = Standard_True;
196   myPreference2d = Standard_True;
197   myFixGapsByRanges = Standard_False;
198
199   myRemoveLoopMode = -1;
200
201   myFixReversed2dMode = -1;
202   myFixRemovePCurveMode = -1;
203   myFixRemoveCurve3dMode = -1;
204   myFixAddPCurveMode = -1;
205   myFixAddCurve3dMode = -1;
206   myFixSeamMode = -1;
207   myFixShiftedMode = -1;
208   myFixSameParameterMode = -1;
209   myFixVertexToleranceMode = -1;
210
211   myFixNotchedEdgesMode = -1;
212   myFixSelfIntersectingEdgeMode = -1;
213   myFixIntersectingEdgesMode = -1;
214   myFixNonAdjacentIntersectingEdgesMode = -1;
215   myFixTailMode = 0;
216
217   myFixReorderMode = -1;
218   myFixSmallMode = -1;
219   myFixConnectedMode = -1;
220   myFixEdgeCurvesMode = -1;
221   myFixDegeneratedMode = -1;
222   myFixSelfIntersectionMode = -1;
223   myFixLackingMode = -1;
224   myFixGaps3dMode = -1;
225   myFixGaps2dMode = -1;
226 }
227
228 //=======================================================================
229 //function : ClearStatuses
230 //purpose  : 
231 //=======================================================================
232
233 void ShapeFix_Wire::ClearStatuses()
234 {
235   Standard_Integer emptyStatus = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
236
237   myLastFixStatus          = emptyStatus;
238
239   myStatusReorder          = emptyStatus;
240   myStatusSmall            = emptyStatus;
241   myStatusConnected        = emptyStatus;
242   myStatusEdgeCurves       = emptyStatus;
243   myStatusDegenerated      = emptyStatus;
244   myStatusSelfIntersection = emptyStatus;
245   myStatusLacking          = emptyStatus;
246   myStatusGaps3d           = emptyStatus; //szv#9:S4244:19Aug99 new method introduced
247   myStatusGaps2d           = emptyStatus; //szv#9:S4244:19Aug99 new method introduced
248   myStatusClosed           = emptyStatus;
249   myStatusNotches = emptyStatus;
250   myStatusFixTails = emptyStatus;
251 }
252
253 //=======================================================================
254 //function : Init
255 //purpose  : 
256 //=======================================================================
257
258 void ShapeFix_Wire::Init (const TopoDS_Wire& wire, 
259                           const TopoDS_Face &face, const Standard_Real prec) 
260 {
261   Load ( wire );
262   SetFace ( face );
263   SetPrecision ( prec );
264 }
265
266 //=======================================================================
267 //function : Init
268 //purpose  : 
269 //=======================================================================
270
271 void ShapeFix_Wire::Init (const Handle(ShapeAnalysis_Wire)& saw) 
272 {
273   ClearStatuses();
274   myAnalyzer = saw;
275   myShape.Nullify();
276 //  SetPrecision ( saw.Precision() );
277 }
278
279 //=======================================================================
280 //function : Load
281 //purpose  : 
282 //=======================================================================
283
284 void ShapeFix_Wire::Load (const TopoDS_Wire& wire) 
285 {
286   ClearStatuses();
287
288   TopoDS_Wire W = wire;
289   if ( ! Context().IsNull() ) {
290     TopoDS_Shape S = Context()->Apply ( wire );
291     W = TopoDS::Wire ( S );
292   }
293
294   myAnalyzer->Load ( W );
295   myShape = wire;
296 }
297
298 //=======================================================================
299 //function : Load
300 //purpose  : 
301 //=======================================================================
302
303 void ShapeFix_Wire::Load (const Handle(ShapeExtend_WireData)& sbwd) 
304 {
305   ClearStatuses();
306   myAnalyzer->Load ( sbwd );
307   if ( ! Context().IsNull() ) UpdateWire();
308   myShape.Nullify();
309 }
310
311 //=======================================================================
312 //function : NbEdges
313 //purpose  : 
314 //=======================================================================
315
316 Standard_Integer ShapeFix_Wire::NbEdges() const
317 {
318   Handle(ShapeExtend_WireData) sbwd = myAnalyzer->WireData();
319   return sbwd.IsNull() ? 0 : sbwd->NbEdges();
320 }
321
322 //#######################################################################
323 //  Fixing methods of API level
324 //#######################################################################
325   
326 //=======================================================================
327 //function : Perform
328 //purpose  : This method performs all the available fixes.
329 //           If some fix is turned on or off explicitly by the flag,
330 //           it is called or not depending on that flag
331 //           Else (i.e. if flag is default) fix is called depending on the 
332 //           situation: default is True, but some fixes are not called or
333 //           are limited if order of edges in the wire is not OK
334 //=======================================================================
335
336 Standard_Boolean ShapeFix_Wire::Perform() 
337 {
338   ClearStatuses();
339   if ( ! IsLoaded() ) return Standard_False;
340
341   if ( !Context().IsNull() )
342     myFixEdge->SetContext( Context() );
343
344   Standard_Integer Fixed = Standard_False;
345   
346   // FixReorder is first, because as a rule wire is required to be ordered
347   // We shall analyze the order of edges in the wire and set appropriate 
348   // status even if FixReorder should not be called (if it is forbidden)
349
350   ShapeAnalysis_WireOrder sawo;
351   Standard_Boolean ReorderOK = ( myAnalyzer->CheckOrder ( sawo, myClosedMode ) ==0 );
352   if ( NeedFix ( myFixReorderMode, ! ReorderOK ) ) { 
353     if(FixReorder()) Fixed = Standard_True; 
354     ReorderOK = ! StatusReorder ( ShapeExtend_FAIL );
355   }
356
357   // FixSmall is allowed to change topology only if mode is set and FixReorder 
358   // did not failed
359   if ( NeedFix ( myFixSmallMode, myTopoMode ) ) {
360     if ( FixSmall ( ! myTopoMode || ! ReorderOK, MinTolerance() ) ) {
361       Fixed = Standard_True;
362       // retry reorder if necessary (after FixSmall it can work better)
363       if ( NeedFix ( myFixReorderMode, ! ReorderOK ) ) { 
364         FixReorder();
365         ReorderOK = ! StatusReorder ( ShapeExtend_FAIL );
366       }
367     }
368   }
369
370   if ( NeedFix ( myFixConnectedMode, ReorderOK ) ) {
371     if ( FixConnected() ) Fixed = Standard_True;
372   }
373
374   if ( NeedFix ( myFixEdgeCurvesMode ) ) {
375     Standard_Integer savFixShiftedMode = myFixShiftedMode;
376     // turn out FixShifted if reorder not done
377     if ( myFixShiftedMode == -1 && ! ReorderOK ) myFixShiftedMode = 0; 
378     if ( FixEdgeCurves() ) Fixed = Standard_True;
379     myFixShiftedMode = savFixShiftedMode;
380   }
381   
382   if ( NeedFix ( myFixDegeneratedMode ) ) {
383     if ( FixDegenerated() ) Fixed = Standard_True; // ?? if ! ReorderOK ??
384   }
385   
386   //pdn - temporary to test
387   if (myFixTailMode <= 0 && NeedFix(myFixNotchedEdgesMode, ReorderOK))
388   {
389     Fixed |= FixNotchedEdges();
390     if(Fixed) FixShifted(); //skl 07.03.2002 for OCC180
391   }
392     
393   if (myFixTailMode != 0)
394   {
395     Fixed |= FixTails();
396     if (Fixed)
397     {
398       FixShifted();
399     }
400   }
401
402   if ( NeedFix ( myFixSelfIntersectionMode, myClosedMode ) ) {
403     Standard_Integer savFixIntersectingEdgesMode = myFixIntersectingEdgesMode;
404     // switch off FixIntEdges if reorder not done
405     if ( myFixIntersectingEdgesMode == -1 && ! ReorderOK ) 
406          myFixIntersectingEdgesMode = 0; 
407     if ( FixSelfIntersection() ) Fixed = Standard_True;
408     FixReorder();
409     myFixIntersectingEdgesMode = savFixIntersectingEdgesMode;
410   }
411
412   if ( NeedFix ( myFixLackingMode, ReorderOK ) ) {
413     if ( FixLacking() ) Fixed = Standard_True;
414   }
415
416   // TEMPORARILY without special mode !!!
417   Handle(ShapeExtend_WireData) sbwd = WireData();
418   for (Standard_Integer iedge = 1; iedge <= sbwd->NbEdges(); iedge++)
419     if ( myFixEdge->FixVertexTolerance (sbwd->Edge (iedge)) ) 
420     {
421       Fixed = Standard_True;
422     }
423
424   if (  !Context().IsNull() )
425     UpdateWire();
426
427   return Fixed;
428 }
429
430 //=======================================================================
431 //function : FixReorder
432 //purpose  : 
433 //=======================================================================
434
435 Standard_Boolean ShapeFix_Wire::FixReorder() 
436 {
437   myStatusReorder = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
438   if ( ! IsLoaded() ) return Standard_False;
439
440   // fix in 3d
441   ShapeAnalysis_WireOrder sawo;
442   myAnalyzer->CheckOrder ( sawo, myClosedMode, Standard_True );
443   
444   //:abv revolCuts.sat -23: in case of bi-periodic surface check case
445   // of reversed wire specifically. This is necessary because degenerated
446   // cases are possible when direct evaluation will give bad result.
447   Standard_Boolean isReorder = Standard_False;
448   if ( sawo.Status() != 0 &&
449        ! myAnalyzer->Surface().IsNull() &&
450        myAnalyzer->Surface()->Surface()->IsUPeriodic() &&
451        myAnalyzer->Surface()->Surface()->IsVPeriodic() ) {
452     Handle(ShapeExtend_WireData) sbwd2 = new ShapeExtend_WireData;
453     for ( Standard_Integer i=WireData()->NbEdges(); i >=1; i-- )
454       sbwd2->Add ( WireData()->Edge(i) );
455     ShapeAnalysis_WireOrder sawo2;
456     ShapeAnalysis_Wire analyzer2 ( sbwd2, myAnalyzer->Face(), Precision() );
457     analyzer2.CheckOrder ( sawo2, myClosedMode, Standard_True );
458     if ( ( sawo2.Status() >=0 && sawo2.Status() < sawo.Status() ) || 
459          ( sawo.Status()   <0 && sawo2.Status() > sawo.Status() ) ) {
460       WireData()->Init ( sbwd2 );
461       sawo = sawo2;
462       isReorder = Standard_True;
463     }
464   }
465   
466   FixReorder ( sawo );
467   
468   if ( LastFixStatus ( ShapeExtend_FAIL ) )
469     myStatusReorder |= ShapeExtend::EncodeStatus ( LastFixStatus ( ShapeExtend_FAIL1 ) ? 
470                                                  ShapeExtend_FAIL1 : ShapeExtend_FAIL2 );
471   if ( ! LastFixStatus ( ShapeExtend_DONE )&& !isReorder ) return Standard_False;
472   
473   myStatusReorder |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
474   if ( sawo.Status() ==2 || sawo.Status() ==-2 ) 
475     myStatusReorder |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE2 );
476   if ( sawo.Status() <0 ) 
477     myStatusReorder |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE3 );
478   if ( sawo.Status() == 3)
479     myStatusReorder |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE5 );//only shifted
480   return Standard_True;
481 }
482
483 //=======================================================================
484 //function : FixSmall
485 //purpose  : 
486 //=======================================================================
487
488 Standard_Integer ShapeFix_Wire::FixSmall (const Standard_Boolean lockvtx,
489                                              const Standard_Real precsmall) 
490 {
491   myStatusSmall = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
492   if ( ! IsLoaded() ) return Standard_False;
493   
494   for ( Standard_Integer i = NbEdges(); i >0; i-- ) {
495     FixSmall ( i, lockvtx, precsmall );
496     myStatusSmall |= myLastFixStatus;
497   }
498
499   return StatusSmall ( ShapeExtend_DONE );
500
501 }
502
503 //=======================================================================
504 //function : FixConnected
505 //purpose  : 
506 //=======================================================================
507
508 Standard_Boolean ShapeFix_Wire::FixConnected (const Standard_Real prec) 
509 {
510   myStatusConnected = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
511   if ( ! IsLoaded() ) return Standard_False;
512   
513   Standard_Integer stop = ( myClosedMode ? 0 : 1 );
514   for ( Standard_Integer i = NbEdges(); i > stop; i-- ) {
515     FixConnected ( i, prec );
516     myStatusConnected |= myLastFixStatus;
517   }
518
519   return StatusConnected ( ShapeExtend_DONE );
520 }
521
522 //=======================================================================
523 //function : FixEdgeCurves
524 //purpose  : 
525 //=======================================================================
526
527 Standard_Boolean ShapeFix_Wire::FixEdgeCurves() 
528 {
529   myStatusEdgeCurves = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
530   if ( ! IsLoaded() ) return Standard_False;
531   Standard_Boolean isReady = IsReady();
532
533   Handle(ShapeExtend_WireData) sbwd = WireData();
534   Standard_Integer i, nb = sbwd->NbEdges();
535   TopoDS_Face face = Face();
536   Handle(ShapeFix_Edge) theAdvFixEdge = Handle(ShapeFix_Edge)::DownCast(myFixEdge);
537   if (theAdvFixEdge.IsNull()) myFixReversed2dMode = Standard_False;
538
539   // fix revesred 2d / 3d curves
540   if ( isReady && NeedFix ( myFixReversed2dMode ) ) {
541     for ( i=1; i <= nb; i++ ) {
542       theAdvFixEdge->FixReversed2d ( sbwd->Edge(i), face ); 
543       if ( theAdvFixEdge->Status ( ShapeExtend_DONE ) ) 
544         myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
545       if ( theAdvFixEdge->Status ( ShapeExtend_FAIL ) ) 
546         myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL1 );
547     }
548   }
549   
550   // add / remove pcurve
551   if ( isReady && NeedFix ( myFixRemovePCurveMode, Standard_False ) ) {
552     for ( i=1; i <= nb; i++ ) {
553       myFixEdge->FixRemovePCurve ( sbwd->Edge(i), face );
554       if ( myFixEdge->Status ( ShapeExtend_DONE ) ) 
555         myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE2 );
556       if ( myFixEdge->Status ( ShapeExtend_FAIL ) ) 
557         myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL2 );
558     }
559   }
560
561   if ( isReady && NeedFix ( myFixAddPCurveMode ) ) {
562     Standard_Integer overdegen = 0; //:c0
563     for ( i=1; i <= nb; i++ ) {
564       myFixEdge->FixAddPCurve ( sbwd->Edge(i), face, sbwd->IsSeam(i), 
565                          myAnalyzer->Surface(), Precision() );
566       if ( myFixEdge->Status ( ShapeExtend_DONE ) ) 
567         myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE3 );
568       if ( myFixEdge->Status ( ShapeExtend_FAIL ) ) 
569         myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL3 );
570
571       //if ( !sbwd->IsSeam(i) && myFixEdge->Status ( ShapeExtend_DONE2 )
572       //     && BRep_Tool::SameParameter(sbwd->Edge(i)) ) {
573       if ( !sbwd->IsSeam(i) && myFixEdge->Status ( ShapeExtend_DONE2 ) ) {
574         // abv 24 Feb 00: trj3_s1-ac-214.stp #1631 etc.: try to split the edge in singularity
575         if ( ! Context().IsNull() ) { 
576           ShapeBuild_Edge sbe;
577           TopoDS_Edge E = sbwd->Edge ( i );
578           ShapeAnalysis_Curve SAC;
579           Standard_Real a, b;
580           Handle(Geom_Curve) C = BRep_Tool::Curve ( E, a, b );
581           Handle(ShapeAnalysis_Surface) S = myAnalyzer->Surface();
582           Standard_Integer nbs = S->NbSingularities(MinTolerance());
583           GeomAdaptor_Curve GAC ( C, a, b );
584           TColStd_SequenceOfReal seq;
585           for (Standard_Integer j=1; j <= nbs; j++) {
586             Standard_Real Preci;
587             gp_Pnt2d pd1, pd2;
588             gp_Pnt P3d, pr;
589             Standard_Real par1, par2, split;
590             Standard_Boolean tmpUIsoDeg;
591             S->Singularity (j, Preci, P3d, pd1, pd2, par1, par2, tmpUIsoDeg);
592             if ( SAC.Project ( GAC, P3d, MinTolerance(), pr, split, Standard_True ) < Max(Preci,MinTolerance()) ) {
593               if ( split - a > ::Precision::PConfusion() &&
594                    b - split > ::Precision::PConfusion() ) {
595                 Standard_Integer k;
596                 for ( k=1; k <= seq.Length(); k++ ) {
597                   if ( split < seq(k)-::Precision::PConfusion() ) {
598                     seq.InsertBefore ( k, split );
599                     break;
600                   }
601                   else if ( split < seq(k)+::Precision::PConfusion() ) break;
602                 }
603                 if ( k > seq.Length() ) seq.Append ( split );
604               }
605             }
606           }
607           if ( seq.Length() >0 ) { // supposed that edge is SP
608 #ifdef OCCT_DEBUG
609             cout << "Edge going over singularity detected; splitted" << endl;
610 #endif
611       Standard_Boolean isFwd = ( E.Orientation() == TopAbs_FORWARD );
612       E.Orientation ( TopAbs_FORWARD );
613
614       //if( BRep_Tool::SameParameter(sbwd->Edge(i)) )
615       //  sbe.RemovePCurve ( E, face );
616
617       //10.04.2003 skl for using trimmed lines as pcurves
618       ShapeAnalysis_Edge sae;
619       if( BRep_Tool::SameParameter(sbwd->Edge(i)) )
620         sbe.RemovePCurve ( E, face );
621       else {
622         if(sae.HasPCurve(E,face)) {
623           Handle(Geom2d_Curve) C2d;
624           Standard_Real fp2d,lp2d;
625           if(sae.PCurve(E,face,C2d,fp2d,lp2d)) {
626             if( !C2d->IsKind(STANDARD_TYPE(Geom2d_TrimmedCurve)) )
627               sbe.RemovePCurve(E,face);
628           }
629         }
630       }
631
632 //    myFixEdge->FixSameParameter ( E ); // to ensure SameRange & SP
633       BRep_Builder B;
634       TopoDS_Vertex V1, V2, V;
635       //ShapeAnalysis_Edge sae;
636       V1 = sae.FirstVertex ( E );
637       V2 = sae.LastVertex ( E );
638         
639       Handle(ShapeExtend_WireData) sw = new ShapeExtend_WireData;
640       for ( Standard_Integer k=0; k <= seq.Length(); k++ )
641       {
642         Standard_Real split = ( k < seq.Length() ? seq(k+1) : b );
643         if ( k < seq.Length() )
644         {
645           B.MakeVertex ( V, C->Value(split), BRep_Tool::Tolerance(E) );
646           //try increase tolerance before splitting
647           Standard_Real aDist = BRep_Tool::Pnt(V1).Distance(BRep_Tool::Pnt(V));
648           if (aDist < BRep_Tool::Tolerance(V1) * 1.01) {
649             B.UpdateVertex(V1, Max(aDist, BRep_Tool::Tolerance(V1)));
650             a = split;
651             V1 = V;
652             continue;
653           }
654           else
655           {
656             aDist = BRep_Tool::Pnt(V2).Distance(BRep_Tool::Pnt(V));
657             if (aDist < BRep_Tool::Tolerance(V2) * 1.01) {
658               B.UpdateVertex(V, Max(aDist, BRep_Tool::Tolerance(V2)));
659               b = split;
660               V2 = V;
661               continue;
662             }
663           }
664         }
665         else
666         {
667           V = V2;
668         }
669
670         TopoDS_Edge edge = sbe.CopyReplaceVertices ( E, V1, V );
671         if( BRep_Tool::SameParameter(sbwd->Edge(i)) ) {
672           //TopoDS_Edge edge = sbe.CopyReplaceVertices ( E, V1, V );
673           B.Range ( edge, a, split );
674           sw->Add ( edge );
675         }
676         else {
677           //TopoDS_Edge edge = sbe.CopyReplaceVertices(sbwd->Edge(i),V1,V);
678           Handle(ShapeAnalysis_TransferParameters) sftp =
679             new ShapeAnalysis_TransferParameters(E,face);
680           sftp->TransferRange(edge, a, split, Standard_False);
681           sw->Add(edge);
682         }
683         //sw->Add(edge);
684         a = split;
685         V1 = V;
686       }
687       if ( ! isFwd ) {
688         sw->Reverse();
689         E.Orientation ( TopAbs_REVERSED );
690       }
691       Context()->Replace ( E, sw->Wire() );
692       UpdateWire();
693       nb = sbwd->NbEdges();
694       i--;
695       continue;
696     }
697         }
698         
699         overdegen = i;
700       }
701     }
702
703     //:c0 abv 20 Feb 98: treat case of curve going over degenerated pole and seam
704     if ( overdegen && myAnalyzer->Surface()->IsUClosed(Precision()) ) {
705       ShapeBuild_Edge sbe;
706       Standard_Real URange, SUF, SUL, SVF, SVL;
707       myAnalyzer->Surface()->Bounds(SUF, SUL, SVF, SVL);
708       URange = (Abs(SUL - SUF));
709       gp_XY vec(0,0);
710       ShapeAnalysis_Edge sae;
711       Standard_Integer k;
712       for ( k = 1; k <= nb; k++) {
713         Standard_Real cf, cl;
714         Handle(Geom2d_Curve) c2d;
715         if ( ! sae.PCurve ( sbwd->Edge(k), face, c2d, cf, cl, Standard_True ) ) break;
716         vec += c2d->Value(cl).XY() - c2d->Value(cf).XY();
717       }
718       if ( k > nb && Abs ( Abs ( vec.X() ) - URange ) < 0.1 * URange ) {
719         sbe.RemovePCurve (sbwd->Edge ( overdegen ), face);
720         myFixEdge->Projector()->AdjustOverDegenMode() = Standard_False;
721         myFixEdge->FixAddPCurve ( sbwd->Edge(overdegen), face, sbwd->IsSeam(overdegen), myAnalyzer->Surface(), Precision());
722       }
723 #ifdef OCCT_DEBUG
724       cout << "Edge going over singularity detected; pcurve adjusted" << endl;
725 #endif
726     }
727   }
728
729   // add / remove pcurve
730   if ( isReady && NeedFix ( myFixRemoveCurve3dMode, Standard_False ) ) {
731     for ( i=1; i <= nb; i++ ) {
732       myFixEdge->FixRemoveCurve3d ( sbwd->Edge(i) );
733       if ( myFixEdge->Status ( ShapeExtend_DONE ) ) 
734         myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE4 );
735       if ( myFixEdge->Status ( ShapeExtend_FAIL ) ) 
736         myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL4 );
737     }
738   }
739   if ( NeedFix ( myFixAddCurve3dMode ) ) {
740     for ( i=1; i <= nb; i++ ) {
741       myFixEdge->FixAddCurve3d ( sbwd->Edge(i) );
742       if ( myFixEdge->Status ( ShapeExtend_DONE ) ) 
743         myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE5 );
744       if ( myFixEdge->Status ( ShapeExtend_FAIL ) ) {
745         //:abv 29.08.01: Spatial_firex_lofting.sat: if 3d curve cannot
746         // be built because edge has no pcurves either, remove that edge
747         Handle(Geom2d_Curve) C;
748         Handle(Geom_Surface) S;
749         TopLoc_Location L;
750         Standard_Real first = 0., last = 0.;
751         BRep_Tool::CurveOnSurface ( sbwd->Edge(i), C, S, L, first, last );
752         if ( C.IsNull() || Abs (last - first) < Precision::PConfusion())
753         {
754           SendWarning ( sbwd->Edge ( i ), Message_Msg ( "FixWire.FixCurve3d.Removed" ) );// Incomplete edge (with no pcurves or 3d curve) removed
755           sbwd->Remove ( i-- );
756           nb--;
757           myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE5 );
758           FixConnected (i + 1, Precision());
759         }
760         myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL5 );
761       }
762     }
763   }
764   
765   // fix seam
766   if ( isReady && NeedFix ( myFixSeamMode, Standard_False ) ) {
767     for ( i=1; i <= nb; i++ ) {
768       FixSeam ( i );
769       if ( LastFixStatus ( ShapeExtend_DONE ) ) 
770         myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE6 );
771       if ( LastFixStatus ( ShapeExtend_FAIL ) ) 
772         myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL6 );
773     }
774   }
775
776   // fix shifted
777   if ( isReady && NeedFix ( myFixShiftedMode ) ) {
778     FixShifted();
779     if ( LastFixStatus ( ShapeExtend_DONE ) ) 
780       myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE7 );
781     if ( LastFixStatus ( ShapeExtend_FAIL ) ) 
782       myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL7 );
783   }
784
785   // fix same parameter
786   if ( isReady && NeedFix ( myFixSameParameterMode ) ){
787     for ( i=1; i <= nb; i++ ) {
788       // skl 28.10.2004 for OCC6366 - check SameRange
789       ShapeAnalysis_Edge sae;
790       Standard_Real First, Last;
791       Handle(Geom_Curve) tmpc3d = BRep_Tool::Curve(sbwd->Edge(i), First, Last);
792       if(sae.HasPCurve(sbwd->Edge(i),face)) {
793         Handle(Geom2d_Curve) C2d;
794         Standard_Real fp2d,lp2d;
795         if(sae.PCurve(sbwd->Edge(i),face,C2d,fp2d,lp2d)) {
796           if( fabs(First-fp2d)>Precision::PConfusion() ||
797               fabs(Last-lp2d)>Precision::PConfusion() ) {
798             BRep_Builder B;
799             B.SameRange(sbwd->Edge(i),Standard_False);
800           }
801         }
802       }
803       myFixEdge->FixSameParameter ( sbwd->Edge(i) );
804       if ( myFixEdge->Status ( ShapeExtend_DONE ) ) 
805         myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE8 );
806       if ( myFixEdge->Status ( ShapeExtend_FAIL ) ) 
807         myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL8 );
808     }
809   }
810
811   //:abv 10.06.02: porting C40 -> dev (CC670-12608.stp): moved from Perform()
812   // Update with face is needed for plane surfaces (w/o stored pcurves)
813   if ( NeedFix ( myFixVertexToleranceMode ) )
814   {
815     for ( i=1; i <= nb; i++)
816     {
817       myFixEdge->FixVertexTolerance (sbwd->Edge (i), face);
818       if ( myFixEdge->Status ( ShapeExtend_DONE ) ) 
819         myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE8 );
820       if ( myFixEdge->Status ( ShapeExtend_FAIL ) ) 
821         myStatusEdgeCurves |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL8 );
822     }
823     if (!Context().IsNull() )
824       UpdateWire();
825   }
826   
827
828   return StatusEdgeCurves ( ShapeExtend_DONE );
829 }
830
831 //=======================================================================
832 //function : FixDegenerated
833 //purpose  : 
834 //=======================================================================
835
836 Standard_Boolean ShapeFix_Wire::FixDegenerated() 
837 {
838   myStatusDegenerated = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
839   if ( ! IsReady() ) return Standard_False;
840   
841 //  if ( ! myAnalyzer->Surface()->HasSingularities ( Precision() ) ) return;
842
843   Standard_Integer lastcoded = -1, prevcoded = 0;
844   Standard_Integer stop = ( myClosedMode ? 0 : 1 );
845   for ( Standard_Integer i = NbEdges(); i > stop; i-- ) {
846     FixDegenerated ( i );
847     myStatusDegenerated |= myLastFixStatus;
848     //:r0 abv 19 Mar 99: PRO7226.stp #489490: remove duplicated degenerated edges
849     Standard_Integer coded = ( LastFixStatus ( ShapeExtend_DONE2 ) ? 1 : 0 );
850     if ( lastcoded ==-1 ) lastcoded = coded;
851     if ( coded && ( prevcoded || ( i ==1 && lastcoded ) ) && NbEdges() >1 ) {
852       Handle(ShapeExtend_WireData) sbwd = WireData();
853       BRep_Builder B;
854       sbwd->Remove ( i );
855       if ( ! prevcoded ) i = NbEdges();
856       B.Degenerated ( sbwd->Edge ( i++ ), Standard_False );
857       prevcoded = 0;
858     }
859     else prevcoded = coded; 
860   }
861
862   return StatusDegenerated ( ShapeExtend_DONE );
863 }
864
865
866 //=======================================================================
867 //function : FixSelfIntersection
868 //purpose  : Applies FixSelfIntersectingEdge and FixIntersectingEdges
869 //           and removes wrong edges
870 //=======================================================================
871
872 Standard_Boolean ShapeFix_Wire::FixSelfIntersection() 
873 {
874   myStatusSelfIntersection = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
875   if ( ! IsReady() ) return Standard_False;
876
877   Handle(ShapeExtend_WireData) sbwd = WireData();
878   Standard_Integer nb = sbwd->NbEdges();
879   
880   if ( NeedFix ( myFixSelfIntersectingEdgeMode ) ) {
881     if (myRemoveLoopMode<1)
882       for ( Standard_Integer num=1; num <=nb; num++ ) 
883       {
884         FixSelfIntersectingEdge ( num );
885         myStatusSelfIntersection |= myLastFixStatus;
886       }
887     else if (myRemoveLoopMode==1)
888     {
889       for ( Standard_Integer num=1; num <=nb; num++ )
890       {
891         FixSelfIntersectingEdge ( num );
892         myStatusSelfIntersection |= myLastFixStatus;
893         if(nb<sbwd->NbEdges()) num--;
894         nb = sbwd->NbEdges();
895       }
896       FixClosed(Precision());
897     }
898   }
899   
900   if ( NeedFix ( myFixIntersectingEdgesMode ) ) {
901     Standard_Integer num = ( myClosedMode ? 1 : 2 );
902     for ( ; nb >1 && num <= nb; num++ ) {
903       FixIntersectingEdges ( num );
904       if ( LastFixStatus ( ShapeExtend_FAIL1 ) ) 
905         myStatusSelfIntersection |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL1 );
906       if ( LastFixStatus ( ShapeExtend_FAIL2 ) ) 
907         myStatusSelfIntersection |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL2 );
908       if ( ! LastFixStatus ( ShapeExtend_DONE ) ) continue;
909
910       if ( LastFixStatus ( ShapeExtend_DONE1 ) ) 
911         myStatusSelfIntersection |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
912       if ( LastFixStatus ( ShapeExtend_DONE2 ) ) 
913         myStatusSelfIntersection |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE2 );
914       if(LastFixStatus (ShapeExtend_DONE6))
915   myStatusSelfIntersection |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE6 );
916
917       if ( /*! myTopoMode ||*/ nb < 3 ) {
918         //#86 rln 22.03.99 sim2.igs, entity 4292: After fixing of self-intersecting
919         //BRepCheck finds one more self-intersection not found by ShapeAnalysis
920         //%15 pdn 06.04.99 repeat until fixed CTS18546-2 entity 777
921         
922         // if the tolerance was modified we should recheck the result, if it was enough
923         if ( LastFixStatus ( ShapeExtend_DONE7 ) ) //num--;
924           FixIntersectingEdges ( num );
925         continue;
926       }
927
928       if ( LastFixStatus ( ShapeExtend_DONE4 ) ) sbwd->Remove ( num );
929       if ( LastFixStatus ( ShapeExtend_DONE3 ) ) sbwd->Remove ( num >1 ? num-1 : nb+num-1 );
930       if ( LastFixStatus ( ShapeExtend_DONE4 ) ||
931            LastFixStatus ( ShapeExtend_DONE3 ) ) {
932         myStatusSelfIntersection |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE3 );
933         num = ( myClosedMode ? 1 : 2 );
934         nb = sbwd->NbEdges();
935 #ifdef OCCT_DEBUG
936         cout << "Warning: ShapeFix_Wire::FixSelfIntersection: Edge removed" << endl;
937 #endif
938       }
939       else {
940         //#86 rln 22.03.99
941         //%15 pdn 06.04.99 repeat until fixed CTS18546-2 entity 777
942         FixIntersectingEdges ( num );
943         /*if ( LastFixStatus ( ShapeExtend_DONE7 ) )*/
944         // Always revisit the fixed edge
945         //num--;
946       }
947     }
948   }
949
950   //pdn 17.03.99 S4135 to avoid regression fixing not adjacent intersection
951   if ( NeedFix ( myFixNonAdjacentIntersectingEdgesMode ) ) {
952
953     ShapeFix_IntersectionTool ITool(Context(),Precision());
954     Standard_Integer NbSplit=0, NbCut=0,NbRemoved=0;
955     if(ITool.FixSelfIntersectWire(sbwd,myAnalyzer->Face(),NbSplit,NbCut,NbRemoved)) {
956       myStatusSelfIntersection |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE5 );//gka 06.09.04
957     }
958     if( NbSplit>0 || NbRemoved>0 ) {
959       if(NbRemoved>0) myStatusRemovedSegment = Standard_True;
960       //Load(sbwd); commented by skl 29.12.2004 for OCC7624, instead this
961       //            string inserted following three strings:
962       myAnalyzer->Load ( sbwd );
963       if ( ! Context().IsNull() ) UpdateWire();
964       myShape.Nullify();
965     }
966 #ifdef OCCT_DEBUG
967     if (StatusSelfIntersection (ShapeExtend_DONE5))
968       cout<<"Warning: ShapeFix_Wire::FixIntersection: Non-adjacent intersection fixed (split-"
969         <<NbSplit<<", cut-"<<NbCut<<", removed-"<<NbRemoved<<")"<<endl;
970 #endif    
971
972 /*
973     Bnd_Array1OfBox2d boxes(1,nb);
974     TopLoc_Location L;
975     const Handle(Geom_Surface)& S = BRep_Tool::Surface(Face(), L);
976     Handle(Geom2d_Curve) c2d;
977     Standard_Real cf,cl;
978     ShapeAnalysis_Edge sae;
979     for(Standard_Integer i = 1; i <= nb; i++){
980       TopoDS_Edge E = sbwd->Edge (i);
981       if(sae.PCurve (E,S,L,c2d,cf,cl,Standard_False)) {
982         Bnd_Box2d box;
983         Geom2dAdaptor_Curve gac;
984         Standard_Real aFirst = c2d->FirstParameter();
985         Standard_Real aLast = c2d->LastParameter();
986         if(c2d->IsKind(STANDARD_TYPE(Geom2d_BSplineCurve)) 
987            && (cf < aFirst || cl > aLast)) {
988           //pdn avoiding problems with segment in Bnd_Box
989           gac.Load(c2d);
990         }
991         else
992           gac.Load(c2d,cf,cl);
993         BndLib_Add2dCurve::Add(gac,::Precision::Confusion(),box);
994         boxes(i) = box;
995       }
996     }
997     
998     Standard_Boolean isFail = Standard_False, isDone = Standard_False;
999     for(Standard_Integer num1 = 1; num1 < nb-1; num1++) {
1000       Standard_Integer fin = (num1 == 1 ? nb-1 : nb);
1001       for(Standard_Integer num2 = num1+2; num2 <= fin; num2++) 
1002         if(!boxes(num1).IsOut(boxes(num2))){
1003           FixIntersectingEdges (num1, num2);
1004           isFail |= LastFixStatus ( ShapeExtend_FAIL1 );
1005           isDone |= LastFixStatus ( ShapeExtend_DONE1 );
1006         }
1007     }
1008     
1009     if(isFail)
1010       myStatusSelfIntersection |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL3 );
1011     if(isDone)
1012       myStatusSelfIntersection |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE5 );
1013 #ifdef OCCT_DEBUG
1014     if (StatusSelfIntersection (ShapeExtend_DONE5))
1015       cout << "Warning: ShapeFix_Wire::FixSelfIntersection: Non ajacent intersection fixed" << endl;
1016 #endif    
1017 */
1018   }
1019
1020   return StatusSelfIntersection ( ShapeExtend_DONE );
1021 }
1022
1023
1024 //=======================================================================
1025 //function : FixLacking
1026 //purpose  : 
1027 //=======================================================================
1028
1029 Standard_Boolean ShapeFix_Wire::FixLacking ( const Standard_Boolean force ) 
1030 {
1031   myStatusLacking = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
1032   if ( ! IsReady() ) return Standard_False;
1033   
1034   Standard_Integer start = ( myClosedMode ? 1 : 2 );
1035   for ( Standard_Integer i = start; i <= NbEdges(); i++ ) {
1036     FixLacking ( i, force );
1037     myStatusLacking |= myLastFixStatus;
1038   }
1039   
1040   return StatusLacking ( ShapeExtend_DONE );
1041 }
1042
1043
1044 //=======================================================================
1045 //function : FixClosed
1046 //purpose  : 
1047 //=======================================================================
1048
1049 Standard_Boolean ShapeFix_Wire::FixClosed (const Standard_Real prec) 
1050 {
1051   myStatusClosed = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
1052   if ( ! IsLoaded() || NbEdges() <1 ) return Standard_False;
1053   
1054   FixConnected ( 1, prec );
1055   if ( LastFixStatus ( ShapeExtend_DONE ) ) 
1056     myStatusClosed |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
1057   if ( LastFixStatus ( ShapeExtend_FAIL ) ) 
1058     myStatusClosed |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL1 );
1059
1060   FixDegenerated ( 1 );
1061   if ( LastFixStatus ( ShapeExtend_DONE ) ) 
1062     myStatusClosed |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE2 );
1063   if ( LastFixStatus ( ShapeExtend_FAIL ) ) 
1064     myStatusClosed |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL2 );
1065
1066   FixLacking ( 1 );
1067   if ( LastFixStatus ( ShapeExtend_DONE ) ) 
1068     myStatusClosed |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE3 );
1069   if ( LastFixStatus ( ShapeExtend_FAIL ) ) 
1070     myStatusClosed |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL3 );
1071   
1072   return StatusClosed ( ShapeExtend_DONE );
1073 }
1074
1075
1076 //#######################################################################
1077 //  Fixing methods of advanced level
1078 //#######################################################################
1079   
1080 //=======================================================================
1081 //function : FixReorder
1082 //purpose  : 
1083 //=======================================================================
1084
1085 Standard_Boolean ShapeFix_Wire::FixReorder (const ShapeAnalysis_WireOrder& wi) 
1086 {
1087   myLastFixStatus = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
1088   if ( ! IsLoaded() ) return Standard_False;
1089   
1090   Standard_Integer status = wi.Status();
1091   if ( status ==0 ) return Standard_False;
1092   if ( status <=-10 ) {
1093     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL1 );
1094     return Standard_False;
1095   }
1096
1097   Handle(ShapeExtend_WireData) sbwd = WireData();
1098   Standard_Integer i, nb = sbwd->NbEdges();
1099   if ( nb != wi.NbEdges() ) {  
1100     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL2 );
1101     return Standard_False;  
1102   }
1103   // D abord on protege
1104   for (i = 1; i <= nb; i ++) {
1105     if ( wi.Ordered(i) == 0 ) {  
1106       myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL3 );
1107       return Standard_False;  
1108     }
1109   }
1110
1111   Handle(TopTools_HSequenceOfShape) newedges = new TopTools_HSequenceOfShape();
1112   for ( i=1; i <= nb; i++ )
1113     newedges->Append ( sbwd->Edge ( wi.Ordered(i) ) );
1114   for ( i=1; i <= nb; i++ ) 
1115     sbwd->Set ( TopoDS::Edge ( newedges->Value(i) ), i );
1116   
1117   myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
1118   return Standard_True;
1119 }
1120
1121
1122 //=======================================================================
1123 //function : FixSmall
1124 //purpose  : 
1125 //=======================================================================
1126
1127 Standard_Boolean ShapeFix_Wire::FixSmall (const Standard_Integer num,
1128                                           const Standard_Boolean lockvtx,
1129                                           const Standard_Real precsmall) 
1130 {
1131   myLastFixStatus = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
1132   if ( ! IsLoaded() || NbEdges() <=1 ) return Standard_False;
1133
1134   // analysis:
1135   Handle(ShapeAnalysis_Wire) theAdvAnalyzer = Handle(ShapeAnalysis_Wire)::DownCast(myAnalyzer);
1136   if (theAdvAnalyzer.IsNull()) return Standard_False;
1137   Standard_Integer n = ( num >0 ? num : NbEdges() );
1138   theAdvAnalyzer->CheckSmall ( n, precsmall );
1139   if ( theAdvAnalyzer->LastCheckStatus ( ShapeExtend_FAIL ) ) {
1140     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL1 );
1141 //:n2    return Standard_False;
1142   }
1143
1144   if ( ! theAdvAnalyzer->LastCheckStatus ( ShapeExtend_DONE ) ) return Standard_False;
1145
1146   // OUI cette edge est NULLE
1147
1148   if ( theAdvAnalyzer->LastCheckStatus ( ShapeExtend_DONE2 ) ) {
1149     // edge is small, but vertices are not the same..
1150     if ( lockvtx || ! myTopoMode ) {
1151       myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL2 );
1152       return Standard_False;
1153     }
1154     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE2 );
1155   }
1156   else myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
1157
1158   // action: remove edge
1159   if ( ! Context().IsNull() ) 
1160     Context()->Remove(WireData()->Edge(n));
1161   SendWarning ( WireData()->Edge ( n ), Message_Msg ( "FixAdvWire.FixSmall.MSG0" ) ); //Small edge(s) removed
1162   WireData()->Remove ( n );
1163   
1164   // call FixConnected in the case if vertices of the small edge were not the same
1165   if ( LastFixStatus ( ShapeExtend_DONE2 ) ) {
1166     Standard_Integer savLastFixStatus = myLastFixStatus;
1167     //#43 rln 20.11.98 S4054 CTS18544 entity 21734 removing last edge
1168     FixConnected ( n <= NbEdges() ? n : 1, precsmall );
1169     if ( LastFixStatus ( ShapeExtend_FAIL ) )
1170       savLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL3 );
1171     myLastFixStatus = savLastFixStatus;
1172   }
1173
1174   return Standard_True;
1175 }
1176
1177
1178 //=======================================================================
1179 //function : FixConnected
1180 //purpose  : 
1181 //=======================================================================
1182
1183 Standard_Boolean ShapeFix_Wire::FixConnected (const Standard_Integer num,
1184                                               const Standard_Real prec) 
1185 {
1186   myLastFixStatus = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
1187   if ( ! IsLoaded() || NbEdges() <=0 ) return Standard_False;
1188
1189   // analysis
1190   
1191   myAnalyzer->CheckConnected ( num, prec < 0 ? MaxTolerance() : prec );
1192   if ( myAnalyzer->LastCheckStatus ( ShapeExtend_FAIL ) ) {
1193     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL1 );
1194   }
1195   if ( ! myAnalyzer->LastCheckStatus ( ShapeExtend_DONE ) ) return Standard_False;
1196
1197   // action: replacing vertex
1198   
1199   Handle(ShapeExtend_WireData) sbwd = WireData();
1200   Standard_Integer n2 = ( num >0 ? num  : sbwd->NbEdges() );
1201   Standard_Integer n1 = ( n2  >1 ? n2-1 : sbwd->NbEdges() );
1202   TopoDS_Edge E1 = sbwd->Edge(n1);
1203   TopoDS_Edge E2 = sbwd->Edge(n2);
1204   
1205   ShapeAnalysis_Edge sae;
1206   TopoDS_Vertex V1 = sae.LastVertex (E1);
1207   TopoDS_Vertex V2 = sae.FirstVertex (E2);
1208   TopoDS_Vertex V;
1209   
1210   if ( myAnalyzer->LastCheckStatus ( ShapeExtend_DONE1 ) ) { // absolutely confused
1211     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
1212     //#40 rln 18.11.98 S4054 BUC60035 entity 2393 (2-nd sub-curve is edge with the same vertex)
1213     if ( V2.IsSame ( sae.LastVertex (E2) ) ) {
1214       V = V2;
1215       if ( ! Context().IsNull() ) 
1216         Context()->Replace ( V1, V.Oriented(V1.Orientation()) );
1217     }
1218     else {
1219       V = V1;
1220       if ( ! Context().IsNull() ) 
1221         Context()->Replace ( V2, V.Oriented(V2.Orientation()) );
1222     }
1223   } 
1224   else {    // on moyenne ...
1225     if ( myAnalyzer->LastCheckStatus ( ShapeExtend_DONE2 ) )
1226       myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE2 );
1227     else myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE3 );
1228     ShapeBuild_Vertex sbv; 
1229     V = sbv.CombineVertex ( V1, V2, 1.0001 );
1230     if ( ! Context().IsNull() ) {
1231       Context()->Replace ( V1, V.Oriented(V1.Orientation()) );
1232       Context()->Replace ( V2, V.Oriented(V2.Orientation()) );
1233     }
1234   }
1235
1236   // replace vertices to a new one
1237   ShapeBuild_Edge sbe;
1238   if ( sbwd->NbEdges() <2 ) {
1239     if(E2.Free() && myTopoMode) {
1240       BRep_Builder B;
1241       B.Remove(E2,sae.FirstVertex(E2));
1242       B.Remove(E2,sae.LastVertex(E2));
1243       B.Add(E2,V.Oriented(TopAbs_FORWARD));
1244       B.Add(E2,V.Oriented(TopAbs_REVERSED));
1245     }
1246     else {
1247       TopoDS_Edge tmpE = sbe.CopyReplaceVertices ( E2, V, V );
1248       sbwd->Set ( tmpE, n2 );
1249       if ( ! Context().IsNull() ) Context()->Replace(E2,tmpE);
1250     }
1251   }
1252   else {
1253     if(E2.Free() &&E1.Free() && myTopoMode) {
1254       BRep_Builder B;
1255       B.Remove(E2,sae.FirstVertex(E2));
1256       B.Add(E2,V.Oriented(TopAbs_FORWARD));
1257       if ( ! myAnalyzer->LastCheckStatus ( ShapeExtend_DONE1 ) ||
1258           sae.FirstVertex (E2).IsSame (sae.LastVertex (E2)) ) {
1259         B.Remove(E1,sae.LastVertex(E1));
1260         B.Add(E1,V.Oriented(TopAbs_REVERSED));
1261       }
1262     }
1263     else {
1264       TopoDS_Edge tmpE2 = sbe.CopyReplaceVertices ( E2, V, TopoDS_Vertex() );
1265       sbwd->Set ( tmpE2, n2 );
1266       if ( ! Context().IsNull() ) Context()->Replace(E2,tmpE2);
1267       if ( ! myAnalyzer->LastCheckStatus ( ShapeExtend_DONE1 ) ||
1268           sae.FirstVertex (E2).IsSame (sae.LastVertex (E2)) ) {
1269         TopoDS_Edge tmpE1 = sbe.CopyReplaceVertices ( E1, TopoDS_Vertex(), V );
1270         sbwd->Set (tmpE1, n1 );
1271         if ( ! Context().IsNull() ) Context()->Replace(E1,tmpE1);
1272       }
1273     }
1274   }
1275   if ( ! Context().IsNull() ) UpdateWire();
1276   
1277   return Standard_True;
1278 }
1279
1280
1281 //=======================================================================
1282 //function : FixSeam
1283 //purpose  : 
1284 //=======================================================================
1285
1286 Standard_Boolean ShapeFix_Wire::FixSeam (const Standard_Integer num) 
1287 {
1288   myLastFixStatus = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
1289   if ( ! IsReady() ) return Standard_False;
1290
1291   Handle(Geom2d_Curve) C1, C2;
1292   Standard_Real cf, cl;
1293   if ( ! myAnalyzer->CheckSeam (num, C1, C2, cf, cl) ) return Standard_False;
1294
1295   BRep_Builder B;
1296   TopoDS_Edge E = WireData()->Edge ( num >0 ? num : NbEdges() );
1297   B.UpdateEdge (E, C2,C1, Face(), 0.); //:S4136: BRep_Tool::Tolerance(E)
1298   B.Range (E, Face(),cf,cl);
1299   myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
1300   
1301   return Standard_True;
1302 }
1303
1304 //=======================================================================
1305 //function : FixShifted
1306 //purpose  : fix parametric curves which may be shifted
1307 // to whole parametric range of closed surface as result of recomputing
1308 // from 3d representation.
1309 // This can be a curve on a seam or near it.
1310 // This function is to be called before FixDegenerated.
1311 // LIMITATION: this function cannot fix cases when, e.g., closed wire is 
1312 // composed of two meridians of the sphere and one of them is seam.
1313 // NOTE: wire is supposed to be closed and sorted !
1314 //=======================================================================
1315
1316 //:p4 abv 23.02.99: PRO9234 #15720: update UV points of edge 
1317 static void UpdateEdgeUVPoints (TopoDS_Edge &E, const TopoDS_Face &F)
1318 {
1319   Standard_Real first, last;
1320   BRep_Tool::Range ( E, F, first, last );
1321   BRep_Builder().Range ( E, F, first, last );
1322 }
1323
1324
1325 //=======================================================================
1326 //function : FixShifted
1327 //purpose  : 
1328 //=======================================================================
1329
1330 Standard_Boolean ShapeFix_Wire::FixShifted() 
1331 {
1332   myLastFixStatus = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
1333   if ( ! IsReady() ) return Standard_False;
1334
1335   Handle(ShapeAnalysis_Surface) surf = myAnalyzer->Surface();
1336   //#78 rln 12.03.99 S4135: checking spatial closure with Precision
1337   Standard_Boolean uclosed = surf->IsUClosed(Precision());
1338   Standard_Boolean vclosed = surf->IsVClosed(Precision()) || surf->Surface()->IsKind (STANDARD_TYPE(Geom_SphericalSurface));
1339   //#67 rln 01.03.99 S4135: ims010.igs entity D11900 (2D contour is 2*PI higher than V range [-pi/2,p/2])
1340   
1341   // PTV 26.06.2002 begin
1342   // CTS18546-2.igs entity 2222: base curve is periodic and 2dcurve is shifted
1343   Standard_Boolean IsVCrvClosed = Standard_False;
1344   Standard_Real VRange = 1.;
1345   if (surf->Surface()->IsKind (STANDARD_TYPE(Geom_SurfaceOfRevolution))) {
1346     Handle(Geom_SurfaceOfRevolution) aSurOfRev = Handle(Geom_SurfaceOfRevolution)::DownCast(surf->Surface());
1347     Handle(Geom_Curve) aBaseCrv = aSurOfRev->BasisCurve();
1348     while ( (aBaseCrv->IsKind(STANDARD_TYPE(Geom_OffsetCurve))) ||
1349            (aBaseCrv->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) ) {
1350       if (aBaseCrv->IsKind(STANDARD_TYPE(Geom_OffsetCurve)))
1351         aBaseCrv = Handle(Geom_OffsetCurve)::DownCast(aBaseCrv)->BasisCurve();
1352       if (aBaseCrv->IsKind(STANDARD_TYPE(Geom_TrimmedCurve)))
1353         aBaseCrv = Handle(Geom_TrimmedCurve)::DownCast(aBaseCrv)->BasisCurve();
1354     }
1355     if (aBaseCrv->IsPeriodic()) {
1356       vclosed = Standard_True;
1357       VRange = aBaseCrv->Period();
1358       IsVCrvClosed = Standard_True;
1359 #ifdef OCCT_DEBUG
1360       cout << "Warning: ShapeFix_Wire::FixShifted set vclosed True for Surface of Revolution" << endl;
1361 #endif
1362     }
1363   }
1364   // PTV 26.06.2002 end
1365   if ( ! uclosed && ! vclosed ) return Standard_False; 
1366   
1367   Standard_Real URange, /*VRange,*/ SUF, SUL, SVF, SVL;
1368   surf->Surface()->Bounds ( SUF, SUL, SVF, SVL );
1369   Standard_Real SUMid, SVMid;
1370   SUMid = 0.5*(SUF+SUL);
1371   SVMid = 0.5*(SVF+SVL);
1372   if (uclosed) URange = Abs ( SUL - SUF );
1373   else         URange = RealLast();
1374   if (!IsVCrvClosed) {
1375     if (vclosed) VRange = Abs ( SVL - SVF );
1376     else         VRange = RealLast();
1377   }
1378   Standard_Real UTol = 0.2 * URange, VTol = 0.2 * VRange;
1379
1380   Handle(ShapeExtend_WireData) sbwdOring = WireData();
1381   ShapeAnalysis_Edge sae;
1382   Handle(ShapeExtend_WireData) sbwd = new ShapeExtend_WireData;
1383   for ( Standard_Integer i=1; i <= sbwdOring->NbEdges(); i++ ) {
1384     TopoDS_Edge E1 = sbwdOring->Edge ( i );
1385     if ( BRep_Tool::Degenerated(E1) && !sae.HasPCurve(E1,Face()))
1386       continue;
1387     
1388     sbwd->Add(E1);
1389   }
1390   
1391   ShapeBuild_Edge sbe;
1392   Standard_Integer nb = sbwd->NbEdges();
1393   Standard_Boolean end = (nb == 0), degstop = Standard_False;;
1394   Standard_Integer stop = nb;
1395   Standard_Integer degn2 = 0;
1396   gp_Pnt pdeg;
1397   //pdn 17.12.98 r0901_ec 38237 to shift wire at 0
1398  
1399   //GeomAdaptor_Surface& GAS = myAnalyzer->Surface()->Adaptor3d()->ChangeSurface(); //SK
1400   Bnd_Box2d box;
1401   for ( Standard_Integer n2=1, n1=nb; ! end; n1 = n2++ ) {
1402     if ( n2 > nb ) n2 = 1;
1403     if ( n2 == stop ) end = Standard_True;
1404
1405     TopoDS_Edge E1 = sbwd->Edge ( n1 );
1406     TopoDS_Edge E2 = sbwd->Edge ( n2 );
1407
1408     if ( BRep_Tool::Degenerated(E1) || BRep_Tool::Degenerated(E2) )
1409     {
1410       if ( ! degstop )
1411       {
1412         stop = n2;
1413         degstop = Standard_True;
1414       }
1415       continue;
1416     }
1417
1418     TopoDS_Vertex V = sae.FirstVertex ( E2 );
1419     if (V.IsNull())
1420       continue;
1421
1422     gp_Pnt p = BRep_Tool::Pnt ( V );
1423   
1424     Standard_Real a1 = 0., b1 = 0., a2 = 0., b2 = 0.;
1425     Handle(Geom2d_Curve) c2d1, c2d2;
1426
1427     //:abv 29.08.01: torCuts.sat: distinguish degeneration by U and by V;
1428     // only corresponding move is prohibited
1429 //    Standard_Boolean isDeg = surf->IsDegenerated ( p, Max ( Precision(), BRep_Tool::Tolerance(V) ) );
1430     Standard_Integer isDeg = 0;
1431     gp_Pnt2d degP1, degP2;
1432     Standard_Real degT1, degT2;
1433     if ( surf->DegeneratedValues ( p, Max ( Precision(), BRep_Tool::Tolerance(V) ),
1434                                    degP1, degP2, degT1, degT2 ) )
1435       isDeg = ( Abs ( degP1.X() - degP2.X() ) > Abs ( degP1.Y() - degP2.Y() ) ? 1 : 2 );
1436
1437     // abv 23 Feb 00: UKI60107-6 210: additional check for near-degenerated case
1438     //smh#15 PRO19800. Check if the surface is surface of revolution.
1439     if (surf->Surface()->IsKind (STANDARD_TYPE(Geom_SurfaceOfRevolution))) {
1440       if ( ! isDeg && ! vclosed ) {
1441         if ( c2d1.IsNull() && ! sae.PCurve ( E1, Face(), c2d1, a1, b1, Standard_True ) ) continue;
1442         gp_Pnt2d p1 ( SUF, c2d1->Value(b1).Y() );
1443         gp_Pnt2d p2 ( SUL, c2d1->Value(b1).Y() );
1444         if ( surf->IsDegenerated ( p1, p2, MaxTolerance(), 10 ) &&
1445              ! surf->IsDegenerated ( c2d1->Value(a1), c2d1->Value(b1), MaxTolerance(), 10 ) ) // abv 31.07.00: trj4_pm1-ec-214.stp #31274: still allow work if edge already exists 
1446           isDeg = 1;
1447       }
1448       if ( ! isDeg && ! uclosed ) {
1449         if ( c2d1.IsNull() && ! sae.PCurve ( E1, Face(), c2d1, a1, b1, Standard_True ) ) continue;
1450         gp_Pnt2d p1 ( c2d1->Value(b1).X(), SVF );
1451         gp_Pnt2d p2 ( c2d1->Value(b1).X(), SVL );
1452         if ( surf->IsDegenerated ( p1, p2, MaxTolerance(), 10 ) &&
1453              ! surf->IsDegenerated ( c2d1->Value(a1), c2d1->Value(b1), MaxTolerance(), 10 ) ) // abv 31.07.00: trj4_pm1-ec-214.stp #31274: still allow work if edge already exists 
1454           isDeg = 2;
1455       }
1456     }
1457
1458     if ( isDeg )
1459     {
1460       if ( ! degstop )
1461       {
1462         stop = n2;
1463         degstop = Standard_True;
1464       }
1465
1466       if ( ! degn2 )
1467       {
1468         degn2 = n2;
1469         pdeg = p;
1470       }
1471       else
1472       {
1473         if ( pdeg.SquareDistance(p) < Precision() * Precision() )
1474         {
1475           degn2 = n2;
1476           //if ( stop < n2 ) { stop = n2; degstop = Standard_True; }
1477         }
1478         else
1479         {
1480           Standard_Real ax1 = 0., bx1 = 0., ax2 = 0., bx2 = 0.;
1481           Handle(Geom2d_Curve) cx1, cx2;
1482           if (  ( c2d1.IsNull() && ! sae.PCurve ( E1, Face(), c2d1, a1, b1, Standard_True ) ) ||
1483                 ( c2d2.IsNull() && ! sae.PCurve ( E2, Face(), c2d2, a2, b2, Standard_True ) ) ||
1484                 ! sae.PCurve ( sbwd->Edge ( degn2 >1 ? degn2-1 : nb ), Face(), cx1, ax1, bx1, Standard_True ) ||
1485                 ! sae.PCurve ( sbwd->Edge ( degn2 ), Face(), cx2, ax2, bx2, Standard_True ) )
1486           {
1487             myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL1 );
1488             continue;
1489           }
1490           gp_Pnt2d pd1 = cx1->Value ( bx1 );
1491           gp_Pnt2d pd2 = cx2->Value ( ax2 );
1492           gp_Pnt2d pn1 = c2d1->Value ( b1 );
1493           gp_Pnt2d pn2 = c2d2->Value ( a2 );
1494           gp_Vec2d x(0.,0.); // shift vector
1495           Standard_Real period;
1496           if ( uclosed ) { x.SetX ( 1. ); period = URange; }
1497           else { x.SetY ( 1. ); period = VRange; }
1498           Standard_Real rot1 = ( pn1.XY() - pd2.XY() ) ^ x.XY();
1499           Standard_Real rot2 = ( pd1.XY() - pn2.XY() ) ^ x.XY();
1500           Standard_Real scld = ( pd2.XY() - pd1.XY() ) * x.XY();
1501           Standard_Real scln = ( pn2.XY() - pn1.XY() ) * x.XY();
1502           if (  rot1 * rot2 < -::Precision::PConfusion() && 
1503                 scld * scln < -::Precision::PConfusion() && 
1504                 Abs ( scln ) > 0.1 * period && Abs ( scld ) > 0.1 * period && 
1505                 rot1 * scld > ::Precision::PConfusion() && 
1506                 rot2 * scln > ::Precision::PConfusion() )
1507           {
1508             // abv 02 Mar 00: trying more sophisticated analysis (ie_exhaust-A.stp #37520)
1509             Standard_Real sign = ( rot2 >0 ? 1. : -1. );
1510             Standard_Real deep1 = Min ( sign * ( pn2.XY() * x.XY() ),
1511                                   Min ( sign * ( pd1.XY() * x.XY() ),
1512                                   Min ( sign * ( c2d2->Value(b2 ).XY() * x.XY() ),
1513                                   Min ( sign * (  cx1->Value(ax1).XY() * x.XY() ),
1514                                   Min ( sign * ( c2d2->Value(0.5*(a2 +b2 )).XY() * x.XY() ),
1515                                         sign * (  cx1->Value(0.5*(ax1+bx1)).XY() * x.XY() ) ) ) ) ) );
1516             Standard_Real deep2 = Max ( sign * ( pn1.XY() * x.XY() ),
1517                                   Max ( sign * ( pd2.XY() * x.XY() ),
1518                                   Max ( sign * ( c2d1->Value(a1 ).XY() * x.XY() ),
1519                                   Max ( sign * (  cx2->Value(bx2).XY() * x.XY() ),
1520                                   Max ( sign * ( c2d1->Value(0.5*(a1 +b1 )).XY() * x.XY() ),
1521                                         sign * (  cx2->Value(0.5*(ax2+bx2)).XY() * x.XY() ) ) ) ) ) );
1522             Standard_Real deep = deep2 - deep1; // estimated current size of wire by x
1523             // pdn 30 Oct 00: trying correct period [0,period] (trj5_k1-tc-203.stp #4698)
1524             Standard_Real dx = ShapeAnalysis::AdjustToPeriod ( deep, ::Precision::PConfusion(), period+::Precision::PConfusion()); 
1525             x *= ( scld >0 ? -dx : dx );
1526             //x *= ( Abs(scld-scln) > 1.5 * period ? 2. : 1. ) *
1527             //     ( scld >0 ? -period : period );
1528             gp_Trsf2d Shift;
1529             Shift.SetTranslation ( x );
1530             for ( Standard_Integer k=degn2; ; k++ )
1531             {
1532               if ( k > nb ) k = 1;
1533               if ( k == n2 ) break;
1534               TopoDS_Edge edge = sbwd->Edge ( k );
1535               if ( ! sae.PCurve ( edge, Face(), cx1, ax1, bx1, Standard_True ) ) continue;
1536               //cx1->Transform ( Shift );
1537               // skl 15.05.2002 for OCC208 (if few edges have reference to one pcurve)
1538               Handle(Geom2d_Curve) cx1new = Handle(Geom2d_Curve)::DownCast(cx1->Transformed(Shift));
1539               sbe.ReplacePCurve(edge,cx1new,Face());
1540               UpdateEdgeUVPoints ( edge, Face() );
1541             }
1542             myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
1543 #ifdef OCCT_DEBUG
1544             cout << "Info: ShapeFix_Wire::FixShifted(): bi - meridian case fixed" << endl;
1545 #endif
1546             continue;
1547           }
1548           //degn2 = n2; pdeg = p; // ie_exhaust-A.stp #37520
1549         }
1550       }
1551 /*
1552       // pdn to fix half sphere
1553       TopoDS_Vertex VE = sae.LastVertex ( E2 );
1554       gp_Pnt pe = BRep_Tool::Pnt ( VE );
1555       //pdn is second vertex on singular point ?
1556       if ( surf->IsDegenerated ( pe, Max ( Precision(), BRep_Tool::Tolerance(V) ) ) ) {
1557         if ( ( c2d1.IsNull() && ! sae.PCurve ( E1, Face(), c2d1, a1, b1, Standard_True ) ) ||
1558              ( c2d2.IsNull() && ! sae.PCurve ( E2, Face(), c2d2, a2, b2, Standard_True ) ) ) {
1559           myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL1 );
1560           continue;
1561         }
1562         gp_Pnt2d p2d1 = c2d1->Value ( b1 ), p2f = c2d2->Value ( a2 ), p2l = c2d2->Value ( b2 );
1563         Standard_Real pres2 = ::Precision::PConfusion();
1564         Standard_Real du = 0.,dv = 0.;
1565         //#79 rln 15.03.99 S4135: bmarkmdl.igs entity 633 (incorrectly oriented contour) check for gap
1566         if(uclosed&&(Abs(p2f.X()-p2l.X())<pres2)&&Abs(p2d1.X()-p2f.X())>GAS.UResolution(Precision())) {
1567           if((Abs(p2f.X()-SUF)<pres2)&&(p2f.Y()<p2l.Y()))
1568             du = URange;
1569           if((Abs(p2f.X()-SUL)<pres2)&&(p2f.Y()>p2l.Y()))
1570             du = -URange;
1571         } 
1572         if(vclosed&&(Abs(p2f.Y()-p2l.Y())<pres2)&&Abs(p2d1.Y()-p2f.Y())>GAS.VResolution(Precision())) {
1573           if((Abs(p2f.Y()-SVF)<pres2)&&(p2f.X()>p2l.X()))
1574             dv = VRange;
1575           if((Abs(p2f.Y()-SVL)<pres2)&&(p2f.X()<p2l.X()))
1576             dv = -VRange;
1577         } 
1578         if ( du ==0. && dv == 0. ) continue;
1579         myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
1580         gp_Trsf2d Shift;
1581         Shift.SetTranslation ( gp_Vec2d ( du, dv ) );
1582         c2d2->Transform ( Shift );
1583         UpdateEdgeUVPoints ( E2, Face() );//rln 15.03.99 syntax correction :E1
1584       }
1585 */
1586 //:abv 29.08.01: torCuts.sat:      continue;
1587     }
1588
1589     if ( ( c2d1.IsNull() && ! sae.PCurve ( E1, Face(), c2d1, a1, b1, Standard_True ) ) ||
1590          ( c2d2.IsNull() && ! sae.PCurve ( E2, Face(), c2d2, a2, b2, Standard_True ) ) ) {
1591       myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL1 );
1592       continue;
1593     }
1594     gp_Pnt2d p2d1 = c2d1->Value ( b1 );
1595     gp_Pnt2d p2d2 = c2d2->Value ( a2 );
1596     box.Add ( p2d1 );
1597
1598     Standard_Real du=0., dv=0.;
1599     if ( uclosed && isDeg != 1 ) {
1600       Standard_Real dx = Abs ( p2d2.X() - p2d1.X() );
1601       if ( dx > URange - UTol ) 
1602         du = ShapeAnalysis::AdjustByPeriod ( p2d2.X(), p2d1.X(), URange );
1603       else if ( dx > UTol && stop == nb ) stop = n2; //:abv 29.08.01: torCuts2.stp
1604     }
1605     if ( vclosed && isDeg != 2 ) {
1606       Standard_Real dy = Abs ( p2d2.Y() - p2d1.Y() );
1607       if ( dy > VRange - VTol ) 
1608         dv = ShapeAnalysis::AdjustByPeriod ( p2d2.Y(), p2d1.Y(), VRange );
1609       else if ( dy > VTol && stop == nb ) stop = n2;
1610     }
1611     if ( du ==0. && dv == 0. ) continue;
1612
1613     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
1614     gp_Trsf2d Shift;
1615     Shift.SetTranslation ( gp_Vec2d ( du, dv ) );
1616     //c2d2->Transform ( Shift );
1617     // skl 15.05.2002 for OCC208 (if few edges have reference to one pcurve)
1618     Handle(Geom2d_Curve) c2d2new = Handle(Geom2d_Curve)::DownCast(c2d2->Transformed(Shift));
1619     sbe.ReplacePCurve(E2,c2d2new,Face());
1620     UpdateEdgeUVPoints ( E2, Face() );
1621   }
1622   if ( box.IsVoid() ) return Standard_False; //#3 smh 01.04.99. S4163: Overflow, when box is void.
1623
1624   Standard_Real umin, vmin, umax, vmax;
1625   box.Get ( umin, vmin, umax, vmax );
1626   if ( Abs ( umin + umax - SUF - SUL ) < URange &&
1627        Abs ( vmin + vmax - SVF - SVL ) < VRange &&
1628        ! LastFixStatus ( ShapeExtend_DONE ) ) return Standard_False;
1629
1630   box.SetVoid();
1631   Standard_Integer n; // svv Jan11 2000 : porting on DEC
1632   for ( n=1; n <= nb; n++ ) {
1633     Standard_Real a, b;
1634     Handle(Geom2d_Curve) c2d;
1635     if ( ! sae.PCurve ( sbwd->Edge(n), Face(), c2d, a, b, Standard_True ) ) continue;
1636     box.Add ( c2d->Value ( a ) );
1637     box.Add ( c2d->Value ( 0.5 * ( a + b ) ) );
1638   }
1639   box.Get ( umin, vmin, umax, vmax );
1640
1641   Standard_Real du=0., dv=0.;
1642
1643   if ( uclosed ) {
1644     Standard_Real umid = 0.5 * ( umin + umax );
1645 //     du = ShapeAnalysis::AdjustToPeriod(umid, SUF, SUL);
1646     // PTV 26.06.2002 xloop torus-apple iges face mode
1647     du = ShapeAnalysis::AdjustByPeriod(umid, SUMid, URange);
1648   }
1649   if ( vclosed ) {
1650     Standard_Real vmid = 0.5 * ( vmin + vmax );
1651 //     dv = ShapeAnalysis::AdjustToPeriod(vmid, SVF, SVL);
1652     // PTV 26.06.2002 xloop torus-apple iges face mode
1653     dv = ShapeAnalysis::AdjustByPeriod(vmid, SVMid, VRange);
1654   }
1655
1656   if ( du ==0. && dv == 0. ) return Standard_True;
1657
1658   myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE2 );
1659   
1660   gp_Trsf2d Shift;
1661   Shift.SetTranslation ( gp_Vec2d ( du, dv ) );
1662
1663   for ( n=1; n <= sbwdOring->NbEdges(); n++ ) {
1664     Standard_Real a, b;
1665     Handle(Geom2d_Curve) c2d;
1666     TopoDS_Edge ed = sbwdOring->Edge(n);
1667     if ( ! sae.PCurve ( ed, Face(), c2d, a, b, Standard_True ) ) continue;
1668     // skl 15.05.2002 for OCC208 (if few edges have reference to one pcurve)
1669     Handle(Geom2d_Curve) c2d2 = Handle(Geom2d_Curve)::DownCast(c2d->Transformed(Shift));
1670     sbe.ReplacePCurve(ed,c2d2,Face());
1671     UpdateEdgeUVPoints ( ed, Face() );
1672   }
1673   return Standard_True;
1674 }
1675
1676 //=======================================================================
1677 //function : FixDegenerated
1678 //purpose  : 
1679 //=======================================================================
1680
1681 Standard_Boolean ShapeFix_Wire::FixDegenerated (const Standard_Integer num) 
1682 {
1683   myLastFixStatus = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
1684   if ( ! IsReady() ) return Standard_False;
1685
1686   // analysis
1687   gp_Pnt2d p2d1, p2d2;
1688   myAnalyzer->CheckDegenerated ( num, p2d1, p2d2 );
1689   if ( myAnalyzer->LastCheckStatus ( ShapeExtend_FAIL1 ) ) {
1690     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL1 );
1691   }
1692   //: abv 29.08.01: torHalf2.sat: if edge was encoded as degenerated but 
1693   //  has no pcurve and no singularity is found at that point, remove it
1694   if ( myAnalyzer->LastCheckStatus ( ShapeExtend_FAIL2 ) ) {
1695     WireData()->Remove ( num );
1696     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE3 );
1697     return Standard_True;
1698   }
1699   if ( ! myAnalyzer->LastCheckStatus ( ShapeExtend_DONE ) ) return Standard_False;
1700   
1701   // action: create degenerated edge and insert it (or replace)
1702
1703   gp_Vec2d vect2d ( p2d1, p2d2 );
1704   gp_Dir2d dir2d ( vect2d );
1705   Handle(Geom2d_Line) line2d = new Geom2d_Line ( p2d1, dir2d );
1706
1707   TopoDS_Edge degEdge;
1708   BRep_Builder B;
1709   B.MakeEdge ( degEdge );
1710   B.Degenerated ( degEdge, Standard_True );
1711   B.UpdateEdge ( degEdge, line2d, Face(), ::Precision::Confusion() );
1712   B.Range ( degEdge, Face(), 0., vect2d.Magnitude() );
1713
1714   Handle(ShapeExtend_WireData) sbwd = WireData();
1715   Standard_Integer n2 = ( num >0 ? num  : sbwd->NbEdges() );
1716   Standard_Integer n1 = ( n2  >1 ? n2-1 : sbwd->NbEdges() );
1717   
1718   Standard_Boolean lack = myAnalyzer->LastCheckStatus ( ShapeExtend_DONE1 );
1719   Standard_Integer n3 = ( lack ? n2 : ( n2 < sbwd->NbEdges() ? n2+1 : 1 ) );
1720   
1721   ShapeAnalysis_Edge sae;
1722   TopoDS_Vertex V1 = sae.LastVertex ( sbwd->Edge ( n1 ) );
1723   TopoDS_Vertex V2 = sae.FirstVertex ( sbwd->Edge ( n3 ) );
1724   
1725   V1.Orientation(TopAbs_FORWARD);
1726   V2.Orientation(TopAbs_REVERSED);
1727   B.Add(degEdge,V1);
1728   B.Add(degEdge,V2);
1729   degEdge.Orientation(TopAbs_FORWARD);
1730
1731   if ( lack ) {
1732     sbwd->Add ( degEdge, n2 );
1733     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
1734   }
1735   else {
1736     sbwd->Set ( degEdge, n2 );
1737     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE2 );
1738   }
1739
1740 //  commented to avoid extra messages
1741 //  SendWarning ( degEdge, Message_Msg ( "FixWire.FixDegenerated.MSG0" ) );// Degenerated edge(s) detected
1742
1743   return Standard_True;
1744 }
1745
1746 //=======================================================================
1747 //function : FixSelfIntersectingEdge
1748 //purpose  : Tests edge for self-intersection and updates tolerance of vertex
1749 //           if intersection is found
1750 //           Returns True if tolerance was increased
1751 //=======================================================================
1752
1753 // Create edge on basis of E with new pcurve and call FixSP
1754 // Return resulting tolerance and modified pcurve
1755 static Standard_Boolean TryNewPCurve (const TopoDS_Edge &E, const TopoDS_Face &face,
1756                                       Handle(Geom2d_Curve) &c2d,
1757                                       Standard_Real &first,
1758                                       Standard_Real &last,
1759                                       Standard_Real &tol)
1760 {
1761   Standard_Real f, l;
1762   Handle(Geom_Curve) crv = BRep_Tool::Curve ( E, f, l );
1763   if ( crv.IsNull() ) return Standard_False;
1764
1765   // make temp edge and compute tolerance
1766   BRepBuilderAPI_MakeEdge mkedge ( crv, f, l );
1767
1768   ShapeBuild_Edge SBE;        //skl 17.07.2001
1769   SBE.SetRange3d(mkedge,f,l); //skl 17.07.2001
1770
1771   if ( ! mkedge.IsDone() ) return Standard_False;
1772
1773   TopoDS_Edge edge = mkedge;
1774   BRep_Builder B;
1775   B.UpdateEdge ( edge, c2d, face, 0. );
1776   B.Range ( edge, face, first, last );
1777   B.SameRange ( edge, Standard_False );
1778 // no call to BRepLib:  B.SameParameter ( edge, Standard_False );
1779
1780   Handle(ShapeFix_Edge) sfe = new ShapeFix_Edge;
1781   sfe->FixSameParameter ( edge ); 
1782   c2d = BRep_Tool::CurveOnSurface ( edge, face, first, last );
1783   tol = BRep_Tool::Tolerance ( edge );
1784   return Standard_True;
1785 }
1786   
1787 //:k3 abv 24 Dec 98: BUC50070 #26682 and #30087: 
1788 // Try to cut out the loop on the pcurve and make new pcurve by concatenating
1789 // the parts.
1790 // If result is not SameParameter with prec, does nothing and returns False
1791 // Warning: resulting pcurve will be C0
1792
1793 //=======================================================================
1794 //function : howMuchPCurves
1795 //purpose  : OCC901
1796 //=======================================================================
1797 static Standard_Integer howMuchPCurves (const TopoDS_Edge &E)
1798 {
1799   Standard_Integer count = 0;
1800   BRep_ListIteratorOfListOfCurveRepresentation itcr
1801     ((*((Handle(BRep_TEdge)*)&E.TShape()))->ChangeCurves());
1802
1803   while (itcr.More()) {
1804     const Handle(BRep_CurveRepresentation)& cr = itcr.Value();
1805     if ( cr->IsCurveOnSurface() )
1806       count++;
1807     itcr.Next();
1808   }
1809     
1810   return count;
1811 }
1812
1813
1814 //=======================================================================
1815 //function : RemoveLoop
1816 //purpose  : 
1817 //=======================================================================
1818 static Standard_Boolean RemoveLoop (TopoDS_Edge &E, const TopoDS_Face &face,
1819                                     const IntRes2d_IntersectionPoint &IP,
1820                                     const Standard_Real tolfact,
1821                                     const Standard_Real prec,
1822                                     const Standard_Boolean RemoveLoop3d)
1823 {
1824   Standard_Boolean loopRemoved3d;
1825   if ( BRep_Tool::IsClosed ( E, face ) ) return Standard_False;
1826   
1827   Standard_Real f, l;
1828   Handle(Geom_Curve) crv = BRep_Tool::Curve ( E, f, l );
1829
1830   Standard_Real t1 = IP.ParamOnFirst();
1831   Standard_Real t2 = IP.ParamOnSecond();
1832   if ( t1 > t2 ) { Standard_Real t = t1; t1 = t2; t2 = t; }
1833
1834   ShapeAnalysis_Edge sae;
1835   Standard_Real a, b;
1836   Handle(Geom2d_Curve) c2d;
1837   if ( ! sae.PCurve ( E, face, c2d, a, b, Standard_False ) ) 
1838     return Standard_False;
1839
1840 #ifdef OCCT_DEBUG
1841   cout << "Cut Loop: params (" << t1 << ", " << t2;
1842 #endif
1843   GeomAdaptor_Curve GAC ( crv, f, l );
1844   Standard_Real dt = tolfact * GAC.Resolution(prec);
1845   t1 -= dt; //1e-3;//::Precision::PConfusion();
1846   t2 += dt; //1e-3;//::Precision::PConfusion();
1847 #ifdef OCCT_DEBUG
1848   cout << ") -> (" << t1 << ", " << t2 << ")" << endl;
1849 #endif
1850       
1851   if ( t1 <= a || t2 >= b ) { // should not be so, but to be sure ..
1852     return Standard_False;
1853   }
1854
1855   // direct construction causes error on osf system.
1856   gp_Pnt p(0,0,0);
1857   gp_Dir d(0,0,1);
1858   gp_Ax3 ax(p, d);
1859   gp_Pln Pln (ax);
1860   
1861   // PTV OCC884
1862   Handle(Geom_Plane) aPlaneSurf = Handle(Geom_Plane)::DownCast( BRep_Tool::Surface(face) );
1863   Handle(Geom_Curve) pcurve3d = crv;
1864   if ( !aPlaneSurf.IsNull() ) {
1865     Pln =  aPlaneSurf->Pln();
1866   }
1867   else
1868     pcurve3d = GeomAPI::To3d ( c2d, Pln );
1869
1870   // first segment
1871   //Handle(Geom_Curve) pcurve3d = GeomAPI::To3d ( c2d, Pln );
1872   Handle(Geom_TrimmedCurve) trim = new Geom_TrimmedCurve (pcurve3d, a, t1);
1873   GeomConvert_CompCurveToBSplineCurve connect ( trim );
1874   
1875   // null-length segment patch instead of loop
1876   TColgp_Array1OfPnt Poles(1,2);
1877   TColStd_Array1OfReal Knots(1,2);
1878   TColStd_Array1OfInteger Mults(1,2);
1879
1880   Poles.SetValue(1,trim->Value(t1));
1881   Knots.SetValue(1,t1);
1882   Mults.SetValue(1,2);
1883
1884   trim = new Geom_TrimmedCurve (pcurve3d, t2, b);
1885   Poles.SetValue(2,trim->Value(t2));
1886   Knots.SetValue(2,t2);
1887   Mults.SetValue(2,2);
1888
1889   Handle(Geom_BSplineCurve) patch = new Geom_BSplineCurve ( Poles, Knots, Mults, 1 );
1890   if ( ! connect.Add (patch, ::Precision::PConfusion(), Standard_True, Standard_False) )
1891     return Standard_False;
1892   
1893   // last segment
1894   if ( ! connect.Add (trim, ::Precision::PConfusion(), Standard_True, Standard_False) )
1895     return Standard_False;
1896   // PTV OCC884
1897   // keep created 3d curve
1898   Handle(Geom_Curve) aNew3dCrv = connect.BSplineCurve();
1899   
1900   
1901   Handle(Geom2d_Curve) bs = GeomAPI::To2d ( aNew3dCrv, Pln );
1902   if ( bs.IsNull() ) return Standard_False;
1903   
1904   // make temp edge and compute tolerance
1905   BRep_Builder B;
1906
1907   if(!RemoveLoop3d) { // old variant (not remove loop 3d)
1908     Standard_Real newtol=0;
1909     // OCC901
1910     Standard_Integer nbC2d = howMuchPCurves( E );
1911     if ( nbC2d <= 1  && !aPlaneSurf.IsNull() )
1912       B.UpdateEdge ( E, bs, face, 0 );
1913     else
1914       if ( ! TryNewPCurve ( E, face, bs, a, b, newtol ) ) return Standard_False;
1915   
1916     Standard_Real tol = BRep_Tool::Tolerance ( E );
1917 #ifdef OCCT_DEBUG
1918     cout << "Cut Loop: tol orig " << tol << ", prec " << prec << ", new tol " << newtol << endl;
1919 #endif
1920     if ( newtol > Max ( prec, tol ) ) return Standard_False;
1921     //:s2  bs = BRep_Tool::CurveOnSurface ( edge, face, a, b );
1922     if ( Abs ( a - f ) > ::Precision::PConfusion() || // smth strange, cancel
1923          Abs ( b - l ) > ::Precision::PConfusion() ) return Standard_False;
1924     // PTV OCC884
1925     if ( !aPlaneSurf.IsNull() ) {
1926       B.UpdateEdge ( E, aNew3dCrv, Max (newtol, tol) );
1927       // OCC901
1928       if ( ! TryNewPCurve ( E, face, bs, a, b, newtol ) ) return Standard_False;
1929     }
1930     B.UpdateEdge ( E, bs, face, newtol );
1931     B.UpdateVertex ( sae.FirstVertex ( E ), newtol );
1932     B.UpdateVertex ( sae.LastVertex  ( E ), newtol );
1933     return Standard_True;
1934   }
1935
1936   //:q1
1937   TopLoc_Location L;
1938   Handle(Geom_Surface) S = BRep_Tool::Surface(face, L);
1939   Handle(Geom2dAdaptor_HCurve) AC = new Geom2dAdaptor_HCurve(c2d);
1940   Handle(GeomAdaptor_HSurface) AS = new GeomAdaptor_HSurface(S);
1941   
1942   Adaptor3d_CurveOnSurface ACS(AC,AS);
1943   gp_Pnt P1(ACS.Value(t1));
1944   gp_Pnt P2(ACS.Value(t2));
1945   gp_Pnt pcurPnt((P1.X()+P2.X())/2,(P1.Y()+P2.Y())/2,(P1.Z()+P2.Z())/2);
1946   
1947   ShapeAnalysis_TransferParametersProj SFTP(E,face);
1948   Handle(TColStd_HSequenceOfReal) Seq2d = new TColStd_HSequenceOfReal;
1949   Seq2d->Append(t1);
1950   Seq2d->Append(t2);
1951   Seq2d->Append((t1+t2)/2);
1952   Handle(TColStd_HSequenceOfReal) Seq3d = SFTP.Perform(Seq2d,Standard_False);
1953   
1954   Standard_Real dist1 = pcurPnt.Distance(crv->Value(Seq3d->Value(1)));// correting Seq3d already project 
1955   Standard_Real dist2 = pcurPnt.Distance(crv->Value(Seq3d->Value(2)));
1956   Standard_Real dist3 = pcurPnt.Distance(crv->Value(Seq3d->Value(3)));
1957   Standard_Real ftrim,ltrim;
1958   if(dist3>Max(dist1,dist2)) {
1959     loopRemoved3d = Standard_False;
1960   }
1961   else {
1962     loopRemoved3d = Standard_True;
1963   }
1964   
1965   Handle(Geom_Curve) bs1;
1966   
1967   if (!loopRemoved3d) {
1968     // create new 3d curve
1969     ftrim = Seq3d->Value(1);
1970     ltrim = Seq3d->Value(2);
1971     ftrim-=dt;
1972     ltrim+=dt;
1973     Handle(Geom_TrimmedCurve) trim1 = new Geom_TrimmedCurve (crv, f, ftrim);
1974     GeomConvert_CompCurveToBSplineCurve connect1 ( trim1 );
1975     TColgp_Array1OfPnt      Poles1(1,2);
1976     TColStd_Array1OfReal    Knots1(1,2);
1977     TColStd_Array1OfInteger Mults1(1,2);
1978     
1979     Poles1.SetValue(1,trim1->Value(ftrim));
1980     Knots1.SetValue(1,ftrim);
1981     Mults1.SetValue(1,2);
1982     
1983     trim1 = new Geom_TrimmedCurve (crv, ltrim, l);
1984     Poles1.SetValue(2,trim1->Value(ltrim));
1985     Knots1.SetValue(2,ltrim);
1986     Mults1.SetValue(2,2);
1987   
1988     // create b-spline curve
1989     Handle(Geom_BSplineCurve) patch1 = new Geom_BSplineCurve ( Poles1, Knots1, Mults1, 1 );
1990   
1991     if ( ! connect1.Add (patch1, ::Precision::PConfusion(), Standard_True, Standard_False) )
1992       return Standard_False;
1993     
1994     // last segment
1995     if ( ! connect1.Add (trim1, ::Precision::PConfusion(), Standard_True, Standard_False) )
1996       return Standard_False;
1997     
1998     bs1 = connect1.BSplineCurve();
1999     
2000     if ( bs1.IsNull() )
2001       return Standard_False;
2002   }
2003 //  Standard_Real oldtol = BRep_Tool::Tolerance ( E );
2004
2005   if (!loopRemoved3d)
2006     B.UpdateEdge ( E, bs1, L, 0. );
2007   B.UpdateEdge ( E, bs, face, 0. );
2008   B.Range ( E, face, f, l );
2009   B.SameRange ( E, Standard_False );
2010
2011   Handle(ShapeFix_Edge) sfe = new ShapeFix_Edge;
2012   sfe->FixSameParameter ( E ); 
2013
2014   return Standard_True;
2015 }
2016
2017 //=======================================================================
2018 //function : RemoveLoop
2019 //purpose  : 
2020 //=======================================================================
2021 static Standard_Boolean RemoveLoop (TopoDS_Edge &E, const TopoDS_Face &face,
2022                                     const IntRes2d_IntersectionPoint &IP2d,
2023                                     TopoDS_Edge &E1,
2024                                     TopoDS_Edge &E2)
2025 {
2026 #ifdef OCCT_DEBUG
2027   cout<<"Info: ShapeFix_Wire::FixSelfIntersection : Try insert vertex"<<endl;
2028 #endif
2029
2030   if ( BRep_Tool::IsClosed ( E, face ) ) return Standard_False;
2031   
2032   Standard_Real f, l;
2033   Handle(Geom_Curve) crv = BRep_Tool::Curve ( E, f, l );
2034
2035   Standard_Real t1 = IP2d.ParamOnFirst();
2036   Standard_Real t2 = IP2d.ParamOnSecond();
2037   
2038   if ( t1 > t2 ) 
2039   { 
2040     Standard_Real t = t1; t1 = t2; t2 = t; 
2041   }
2042
2043   ShapeAnalysis_Edge sae;
2044   
2045   // define vertexes Vfirst , Vlast, Vmid
2046   TopoDS_Vertex Vfirst,Vlast,Vmid;
2047   // initialize Vfirst and Vlast
2048   Vfirst = sae.FirstVertex(E);
2049   Vlast  = sae.LastVertex(E); 
2050   
2051   // find a 2d curve and parameters from edge E
2052   Standard_Real a, b;
2053   Handle (Geom2d_Curve) c2d;
2054   if ( ! sae.PCurve ( E, face, c2d, a, b, Standard_False ) ) 
2055     return Standard_False;
2056
2057   // first segment for 2d curve
2058   Handle(Geom2d_TrimmedCurve) trim1;
2059   if( (t1-a)>Precision::PConfusion() )
2060     trim1 = new Geom2d_TrimmedCurve (c2d, a, t1);
2061   // second segment for 2d curve
2062   Handle(Geom2d_TrimmedCurve) trim2 = new Geom2d_TrimmedCurve (c2d, t2, b);
2063
2064 //  if ( trim1.IsNull() || trim2.IsNull()  ) 
2065   if(trim2.IsNull()) 
2066     return Standard_False;
2067
2068   TopLoc_Location L;
2069   Handle (Geom_Surface) S = BRep_Tool::Surface(face, L);
2070   Handle (Geom2dAdaptor_HCurve) AC = new Geom2dAdaptor_HCurve(c2d);
2071   Handle (GeomAdaptor_HSurface) AS = new GeomAdaptor_HSurface(S); 
2072   
2073   Adaptor3d_CurveOnSurface ACS(AC,AS);
2074   gp_Pnt P1(ACS.Value(t1));
2075   gp_Pnt P2(ACS.Value(t2));
2076   gp_Pnt pcurPnt((P1.X()+P2.X())/2,(P1.Y()+P2.Y())/2,(P1.Z()+P2.Z())/2);
2077   
2078   // transfer parameters from pcurve to 3d curve
2079   ShapeAnalysis_TransferParametersProj SFTP(E,face);
2080   Handle (TColStd_HSequenceOfReal) Seq2d = new TColStd_HSequenceOfReal;
2081   Seq2d->Append(t1);
2082   Seq2d->Append(t2);
2083   Seq2d->Append((t1+t2)/2);
2084   Handle (TColStd_HSequenceOfReal) Seq3d = SFTP.Perform(Seq2d,Standard_False);
2085   
2086   Standard_Real dist1 = pcurPnt.Distance(crv->Value(Seq3d->Value(1)));// correting Seq3d already project 
2087   Standard_Real dist2 = pcurPnt.Distance(crv->Value(Seq3d->Value(2)));
2088   Standard_Real dist3 = pcurPnt.Distance(crv->Value(Seq3d->Value(3)));
2089   Standard_Real ftrim,ltrim;
2090   if ( dist3 > Max(dist1, dist2)) { // is loop in 3d
2091     ftrim = Seq3d->Value(1);
2092     ltrim = Seq3d->Value(2);
2093   }
2094   else { // not loop in 3d
2095     ftrim = Seq3d->Value(3);
2096     ltrim = Seq3d->Value(3);
2097   }
2098   
2099 //  ftrim = Seq3d->Value(1);
2100 //  ltrim = Seq3d->Value(2);
2101   
2102   // trim for 3d curve 'crv' with parameters from 'f' to 'l' 
2103   Handle(Geom_TrimmedCurve) trim3;
2104   if(!trim1.IsNull())
2105     trim3 = new Geom_TrimmedCurve (crv, f, ftrim);
2106   // second segment for 3d curve
2107   Handle(Geom_TrimmedCurve) trim4 = new Geom_TrimmedCurve (crv, ltrim, l);
2108
2109 //  if ( trim3.IsNull() || trim4.IsNull()  ) 
2110   if(trim4.IsNull()) 
2111     return Standard_False;
2112   
2113   // create a point for middle vertex
2114   gp_Pnt pnt1 = crv->Value(ftrim);
2115   gp_Pnt pnt2 = crv->Value(ltrim);
2116   gp_Pnt Pmid((pnt1.X()+pnt2.X())/2,(pnt1.Y()+pnt2.Y())/2,(pnt1.Z()+pnt2.Z())/2);
2117     
2118   BRep_Builder B;
2119   
2120   // create new copies for E1 and E2
2121   if(!trim1.IsNull())
2122     E1=TopoDS::Edge(E.EmptyCopied());
2123   E2=TopoDS::Edge(E.EmptyCopied());
2124   
2125   // initialize middle vertex Vmid
2126   if(trim1.IsNull()) 
2127     B.MakeVertex(Vmid, pnt2, 0.);
2128   else
2129     B.MakeVertex(Vmid, Pmid, 0.);
2130   
2131   ShapeBuild_Edge sbe;
2132   
2133   // replace verteces for new edges E1 and E2
2134   if (E.Orientation()== TopAbs_FORWARD)
2135   {
2136     if(!E1.IsNull())
2137       E1=sbe.CopyReplaceVertices(E1,Vfirst,Vmid);
2138     E2=sbe.CopyReplaceVertices(E2,Vmid, Vlast);
2139   }
2140   else 
2141   {
2142     if(!E1.IsNull())
2143       E1=sbe.CopyReplaceVertices(E1,Vmid, Vlast);
2144     E2=sbe.CopyReplaceVertices(E2,Vfirst, Vmid);
2145   }
2146   
2147   // Update edges by 2d and 3d curves
2148   Handle(ShapeFix_Edge) mySfe = new ShapeFix_Edge;
2149   if(!E1.IsNull()) {
2150     B.UpdateEdge(E1, trim1, face, 0.);
2151     B.UpdateEdge(E1, trim3, 0.);
2152     B.Range(E1, f, ftrim);
2153     B.SameRange(E1,Standard_False);
2154 //    B.SameParameter(E1,Standard_False);
2155     mySfe->FixSameParameter(E1);
2156     mySfe->FixVertexTolerance(E1);
2157   }
2158   B.UpdateEdge(E2, trim2, face, 0.);
2159   B.UpdateEdge(E2, trim4, 0.);
2160   B.Range ( E2,ltrim,l     );
2161   B.SameRange(E2, Standard_False );
2162 //  B.SameParameter(E2, Standard_False);
2163   mySfe->FixSameParameter(E2);
2164   mySfe->FixVertexTolerance(E2);
2165
2166   return Standard_True;
2167 }
2168
2169
2170 //=======================================================================
2171 //function : FixSelfIntersectingEdge
2172 //purpose  : 
2173 //=======================================================================
2174
2175 Standard_Boolean ShapeFix_Wire::FixSelfIntersectingEdge (const Standard_Integer num) 
2176 {
2177   myLastFixStatus = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
2178   if ( ! IsReady() ) return Standard_False;
2179
2180   // analysis
2181   IntRes2d_SequenceOfIntersectionPoint points2d;
2182   TColgp_SequenceOfPnt points3d;
2183   Handle(ShapeAnalysis_Wire) theAdvAnalyzer =  Handle(ShapeAnalysis_Wire)::DownCast(myAnalyzer);
2184   if (theAdvAnalyzer.IsNull()) return Standard_False;
2185   theAdvAnalyzer->CheckSelfIntersectingEdge ( num, points2d, points3d ); 
2186   if ( theAdvAnalyzer->LastCheckStatus ( ShapeExtend_FAIL ) ) {
2187     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL1 );
2188   }
2189   if ( ! theAdvAnalyzer->LastCheckStatus ( ShapeExtend_DONE ) ) return Standard_False;
2190   
2191   // action: increase tolerance of vertex
2192   
2193   TopoDS_Edge E = WireData()->Edge ( num >0 ? num : NbEdges() );
2194   
2195   ShapeAnalysis_Edge sae;
2196   TopoDS_Vertex V1 = sae.FirstVertex ( E );
2197   TopoDS_Vertex V2 = sae.LastVertex ( E );
2198   Standard_Real tol1 = BRep_Tool::Tolerance ( V1 );
2199   Standard_Real tol2 = BRep_Tool::Tolerance ( V2 );
2200   gp_Pnt pnt1 = BRep_Tool::Pnt ( V1 );
2201   gp_Pnt pnt2 = BRep_Tool::Pnt ( V2 );
2202
2203   // cycle is to verify fix in case of RemoveLoop
2204   Standard_Real tolfact = 0.1; // factor for shifting by parameter in RemoveLoop
2205   Standard_Real f2d = 0., l2d = 0.;
2206   Handle(Geom2d_Curve) c2d;
2207   Standard_Real newtol=0.; // = Precision();
2208
2209   if (myRemoveLoopMode<1) {
2210     for ( Standard_Integer iter=0; iter < 30; iter++ ) { 
2211       Standard_Boolean loopRemoved = Standard_False;;
2212       Standard_Real prevFirst = 0 , prevLast = 0; 
2213       for ( Standard_Integer i=1; i<=points2d.Length(); i++ ) {
2214         gp_Pnt pint = points3d.Value(i);
2215         Standard_Real dist21 = pnt1.SquareDistance ( pint );
2216         Standard_Real dist22 = pnt2.SquareDistance ( pint );
2217         if ( dist21 < tol1 * tol1 || dist22 < tol2 * tol2 ) continue;
2218         newtol = 1.001 * Sqrt ( Min ( dist21, dist22 ) ); //:f8
2219
2220         //:k3 abv 24 Dec 98: BUC50070 #26682 and #30087: try to remove loop
2221         if ( myGeomMode ) {
2222           if ( c2d.IsNull() )
2223             sae.PCurve ( E, Face(), c2d, f2d, l2d, Standard_False );
2224           Standard_Real firstpar = points2d.Value(i).ParamOnFirst(); 
2225           Standard_Real lastpar = points2d.Value(i).ParamOnSecond();
2226           if(firstpar > prevFirst && lastpar < prevLast) continue;
2227           if ( RemoveLoop (E, Face(), points2d.Value(i), tolfact, 
2228                            Min( MaxTolerance(), Max(newtol,Precision()) ),
2229                            myRemoveLoopMode==0 ) ) {
2230             myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE4 );
2231             loopRemoved = Standard_True;
2232             prevFirst = firstpar;
2233             prevLast = lastpar;
2234             continue; // repeat of fix on that edge required (to be done by caller)
2235           }
2236         }
2237         if ( newtol < MaxTolerance() ) {
2238           myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
2239           BRep_Builder B;
2240           if ( dist21 < dist22 ) B.UpdateVertex ( V1, tol1 = newtol );
2241           else                   B.UpdateVertex ( V2, tol2 = newtol );
2242         }
2243         else myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL2 );
2244       }
2245
2246       // after RemoveLoop, check that self-intersection disappeared
2247       if ( loopRemoved ) {
2248         IntRes2d_SequenceOfIntersectionPoint pnts2d;
2249         TColgp_SequenceOfPnt pnts3d;
2250         theAdvAnalyzer->CheckSelfIntersectingEdge ( num, pnts2d, pnts3d );
2251         if ( ! theAdvAnalyzer->LastCheckStatus ( ShapeExtend_DONE ) ) break;
2252         //points3d.Append(pnts3d);
2253         //points2d.Append(pnts2d);
2254         points3d = pnts3d;
2255         points2d = pnts2d;
2256         BRep_Builder B;
2257         B.UpdateEdge ( E, c2d, Face(), 0. );
2258         B.Range ( E, Face(), f2d, l2d );
2259         //newtol+=Precision();
2260       }
2261       else {
2262         break;
2263       }
2264     }
2265   }
2266   
2267   //===============================================
2268   // RemoveLoopMode = 1 , insert vertex 
2269   //===============================================
2270   if (myRemoveLoopMode == 1) {
2271     // after fixing will be nb+1 edges
2272     Standard_Boolean loopRemoved; 
2273     // create a sequence of resulting edges
2274     Handle (TopTools_HSequenceOfShape) TTSS = new TopTools_HSequenceOfShape;
2275     TopoDS_Edge E2;
2276     
2277     loopRemoved = Standard_False;
2278     //:k3 abv 24 Dec 98: BUC50070 #26682 and #30087: try to remove loop
2279     if ( myGeomMode ) {
2280       if ( c2d.IsNull() )
2281         sae.PCurve ( E, Face(), c2d, f2d, l2d, Standard_False );
2282       TopoDS_Edge E1;
2283       if ( RemoveLoop (E, Face(), points2d.Value(1),E1,E2) ) {
2284         myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE4 );
2285         loopRemoved = Standard_True;
2286         if(!E1.IsNull()) {
2287           TTSS->Append(E1);
2288           newtol = Max(BRep_Tool::Tolerance(E1),BRep_Tool::Tolerance(E2));
2289         }
2290         else
2291           newtol = BRep_Tool::Tolerance(E2);
2292       }
2293     }
2294
2295     TTSS->Append(E2);
2296     
2297     if ( newtol > MaxTolerance() ) 
2298       myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL2 );
2299     
2300     ShapeExtend_WireData sewd;
2301     for (Standard_Integer i=1 ; i <= TTSS->Length(); i++) {
2302       sewd.Add(TopoDS::Edge(TTSS->Value(i)));
2303     }
2304     if (! Context().IsNull()) {
2305       Context()->Replace ( E, sewd.Wire() );
2306       UpdateWire();
2307     }
2308     else {
2309       WireData()->Remove(num >0 ? num : NbEdges());
2310       WireData()->Add(sewd.Wire(), num >0 ? num : NbEdges());
2311     }
2312     if (loopRemoved)
2313       myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE8 );
2314     
2315   }
2316
2317   if ( LastFixStatus ( ShapeExtend_DONE ) && ! myShape.IsNull() ) {
2318     SendWarning ( E, Message_Msg ( "FixAdvWire.FixIntersection.MSG5" ) );// Edge was self-intersecting, corrected
2319   }
2320
2321   return LastFixStatus ( ShapeExtend_DONE );
2322 }
2323
2324
2325 //=======================================================================
2326 //function : ComputeLocalDeviation
2327 //purpose  : auxilary
2328 //=======================================================================
2329 static Standard_Real ComputeLocalDeviation (const TopoDS_Edge &edge, 
2330                                             const gp_Pnt &pint,const gp_Pnt &pnt,
2331                                             Standard_Real f, Standard_Real l,
2332                                             const TopoDS_Face &face )
2333 {
2334   ShapeAnalysis_Edge sae;
2335   Handle(Geom_Curve) c3d;
2336   Standard_Real a, b;
2337   if ( ! sae.Curve3d ( edge, c3d, a, b, Standard_False ) ) return RealLast();
2338   
2339   gp_Lin line ( pint, gp_Vec ( pint, pnt ) );
2340   
2341   Handle(Geom2d_Curve) Crv;
2342   Standard_Real fp,lp;
2343   if ( sae.PCurve(edge,face,Crv,fp,lp,Standard_False) ) {
2344     if(Crv->IsKind(STANDARD_TYPE(Geom2d_TrimmedCurve))) {
2345       Handle(Geom2d_TrimmedCurve) tc = Handle(Geom2d_TrimmedCurve)::DownCast(Crv);
2346       if(tc->BasisCurve()->IsKind(STANDARD_TYPE(Geom2d_Line))) {
2347         f = a + (f-fp)*(b-a)/(lp-fp);
2348         l = a + (l-fp)*(b-a)/(lp-fp);
2349       }
2350     }
2351   }
2352
2353   const Standard_Integer NSEG = 10;
2354   Standard_Real step = ( l - f ) / NSEG;
2355   Standard_Real dev = 0.;
2356   for ( Standard_Integer i=1; i < NSEG; i++ ) {
2357     gp_Pnt p = c3d->Value ( f + i * step );
2358     Standard_Real d = line.Distance ( p );
2359     if ( dev < d ) dev = d;
2360   }
2361   return dev;
2362 }
2363
2364 //=======================================================================
2365 //function : FixIntersectingEdges
2366 //purpose  : 
2367 //=======================================================================
2368
2369 Standard_Boolean ShapeFix_Wire::FixIntersectingEdges (const Standard_Integer num) 
2370 {
2371   myLastFixStatus = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
2372   if ( ! IsReady() || NbEdges() <2 ) return Standard_False;
2373
2374   // analysis
2375   IntRes2d_SequenceOfIntersectionPoint points2d;
2376   TColgp_SequenceOfPnt points3d;
2377   TColStd_SequenceOfReal errors;
2378   Handle(ShapeAnalysis_Wire) theAdvAnalyzer = Handle(ShapeAnalysis_Wire)::DownCast(myAnalyzer);
2379   if (theAdvAnalyzer.IsNull()) return Standard_False;
2380   theAdvAnalyzer->CheckIntersectingEdges ( num, points2d, points3d, errors );
2381   if ( theAdvAnalyzer->LastCheckStatus ( ShapeExtend_FAIL ) ) {
2382     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL1 );
2383   }
2384   if ( ! theAdvAnalyzer->LastCheckStatus ( ShapeExtend_DONE ) ) return Standard_False;
2385   
2386   //rln 03/02/98: CSR#BUC50004 entity 56 (to avoid later inserting lacking edge)
2387   //:l0  Standard_Boolean isLacking = myAnalyzer->CheckLacking ( num );
2388
2389   // action: increase tolerance of vertex
2390   
2391   Handle(ShapeExtend_WireData) sbwd = WireData();
2392   Standard_Integer n2 = ( num >0 ? num  : sbwd->NbEdges() );
2393   Standard_Integer n1 = ( n2  >1 ? n2-1 : sbwd->NbEdges() );
2394   TopoDS_Edge E1 = sbwd->Edge(n1);
2395   TopoDS_Edge E2 = sbwd->Edge(n2);
2396   Standard_Boolean isForward1 = ( E1.Orientation() == TopAbs_FORWARD );
2397   Standard_Boolean isForward2 = ( E2.Orientation() == TopAbs_FORWARD );
2398   Standard_Real a1, b1, a2, b2;
2399   BRep_Tool::Range ( E1, Face(), a1, b1 );
2400   BRep_Tool::Range ( E2, Face(), a2, b2 );
2401
2402   ShapeAnalysis_Edge sae;
2403   TopoDS_Vertex Vp = sae.FirstVertex ( E1 );
2404   TopoDS_Vertex V1 = sae.LastVertex  ( E1 );
2405   TopoDS_Vertex V2 = sae.FirstVertex ( E2 );
2406   TopoDS_Vertex Vn = sae.LastVertex  ( E2 );
2407
2408   Standard_Real tol = BRep_Tool::Tolerance ( V1 );
2409   gp_Pnt pnt = BRep_Tool::Pnt ( V1 );
2410   
2411   Standard_Real prevRange1 = RealLast(), prevRange2 = RealLast();
2412   Standard_Boolean cutEdge1 = Standard_False, cutEdge2 = Standard_False;
2413   Standard_Boolean IsCutLine = Standard_False;
2414
2415   BRep_Builder B;
2416
2417   Standard_Integer nb = points3d.Length();
2418   for ( Standard_Integer i=1; i <= nb; i++ ) {
2419     const IntRes2d_IntersectionPoint &IP = points2d.Value(i);
2420     Standard_Real param1 = ( num ==1 ? IP.ParamOnSecond() : IP.ParamOnFirst() );
2421     Standard_Real param2 = ( num ==1 ? IP.ParamOnFirst()  : IP.ParamOnSecond() );
2422     
2423     Standard_Real newRange1 = Abs ( ( isForward1 ? a1 : b1 ) - param1 );
2424     Standard_Real newRange2 = Abs ( ( isForward2 ? b2 : a2 ) - param2 );
2425     if ( newRange1 > prevRange1 && newRange2 > prevRange2 ) continue;
2426     
2427     gp_Pnt pint = points3d.Value(i);
2428     Standard_Real rad = errors.Value(i);
2429     Standard_Real newtol = 1.0001 * ( pnt.Distance ( pint ) + rad );
2430
2431     //GeomAdaptor_Surface& Ads = myAnalyzer->Surface()->Adaptor3d()->ChangeSurface();
2432
2433     //:r8 abv 12 Apr 99: try increasing tolerance of edge
2434
2435     Standard_Boolean locMayEdit = myTopoMode;
2436     // Always try to modify the tolerance firstly as a better solution
2437     if ( /*! myTopoMode &&*/ newtol > tol )
2438     {
2439       Standard_Real te1 = rad + ComputeLocalDeviation (E1, pint, pnt,
2440         param1, ( isForward1 ? b1 : a1 ), Face() );
2441       Standard_Real te2 = rad + ComputeLocalDeviation (E2, pint, pnt, 
2442         ( isForward2 ? a2 : b2 ), param2, Face() );
2443       Standard_Real maxte = Max ( te1, te2 );
2444       if ( maxte < MaxTolerance() && maxte < newtol )
2445       {
2446         if ( BRep_Tool::Tolerance(E1) < te1 || BRep_Tool::Tolerance(E2) < te2 )
2447         {
2448 #ifdef OCCT_DEBUG
2449           cout << "Warning: ShapeFix_Wire::FixIE: edges tolerance increased: (" <<
2450             te1 << ", " << te2 << ") / " << newtol << endl;
2451 #endif
2452
2453           // Make copy of edges.
2454           if (!Context().IsNull())
2455           {
2456             // Intersection point of two base edges.
2457             ShapeBuild_Edge aSBE;
2458             TopoDS_Vertex VV1 = Context()->CopyVertex(V1);
2459
2460             TopoDS_Vertex VVp = Vp;
2461             TopoDS_Vertex VVn = Vn;
2462             if (Vp.IsSame(Vn))
2463             {
2464               // Should modify only one vertex.
2465               VVp = Context()->CopyVertex(Vp);
2466               VVn = VVp;
2467             }
2468             else
2469             {
2470               VVp = Context()->CopyVertex(Vp);
2471               VVn = Context()->CopyVertex(Vn);
2472             }
2473
2474             TopoDS_Edge EE1 = aSBE.CopyReplaceVertices(E1, VVp, VV1);
2475             TopoDS_Edge EE2 = aSBE.CopyReplaceVertices(E2, VV1, VVn);
2476
2477             Context()->Replace(E1, EE1);
2478             Context()->Replace(E2, EE2);
2479
2480             UpdateWire();
2481             E1 = sbwd->Edge(n1);
2482             E2 = sbwd->Edge(n2);
2483             Vp = sae.FirstVertex ( E1 );
2484             V1 = sae.LastVertex  ( E1 );
2485             V2 = sae.FirstVertex ( E2 );
2486             Vn = sae.LastVertex  ( E2 );
2487           }
2488
2489           B.UpdateEdge ( E1, 1.000001 * te1 );
2490           B.UpdateVertex ( sae.FirstVertex ( E1 ), 1.000001 * te1 );
2491           B.UpdateVertex ( sae.LastVertex  ( E1 ), 1.000001 * te1 );
2492           B.UpdateEdge ( E2, 1.000001 * te2 );
2493           B.UpdateVertex ( sae.FirstVertex ( E2 ), 1.000001 * te2 );
2494           B.UpdateVertex ( sae.LastVertex  ( E2 ), 1.000001 * te2 );
2495
2496           myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE6 );
2497           locMayEdit = Standard_False;
2498         }
2499         newtol = 1.000001 * maxte;
2500       }
2501     }
2502     
2503     if ( locMayEdit || newtol <= MaxTolerance() )
2504     {
2505       prevRange1 = newRange1; 
2506       prevRange2 = newRange2;
2507       if ( locMayEdit )
2508       {
2509         newtol = 1.0001 * ( pnt.Distance ( pint ) + rad );
2510         //:j6 abv 7 Dec 98: ProSTEP TR10 r0601_id.stp #57676 & #58586: do not cut edges because of influence on adjacent faces
2511         ShapeFix_SplitTool aTool;
2512         
2513         if ( ! aTool.CutEdge ( E1, ( isForward1 ? a1 : b1 ), param1, Face(), IsCutLine ) ) {
2514           if ( V1.IsSame ( Vp ) )
2515             myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE3 );
2516           else locMayEdit = Standard_False;
2517         }
2518         else cutEdge1 = Standard_True; //:h4
2519         
2520         if ( ! aTool.CutEdge ( E2, ( isForward2 ? b2 : a2 ), param2, Face(), IsCutLine ) ) {
2521           if ( V2.IsSame ( Vn ) ) 
2522             myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE4 );
2523           else locMayEdit = Standard_False;
2524         }
2525         else cutEdge2 = Standard_True; //:h4
2526       }
2527
2528       if (  locMayEdit &&
2529             newRange1 <= prevRange1 && newRange2 <= prevRange2 && //rln 09/01/98
2530             BRep_Tool::SameParameter ( E1 ) &&
2531             BRep_Tool::SameParameter ( E2 ) )
2532       {
2533         myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE2 );
2534         pnt = pint;
2535         if ( tol <= rad ) {
2536           myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
2537           tol = 1.001 * rad;
2538         }
2539       }
2540       else
2541       {
2542         if(IsCutLine)
2543         {
2544           myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE2 );
2545           pnt = pint;
2546           if ( tol <= rad ) {
2547             myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
2548             tol = 1.001 * rad;
2549           }
2550         }
2551         else
2552         { // else increase tolerance
2553           if (tol < newtol)
2554           { //rln 07.04.99 CCI60005-brep.igs
2555             myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
2556             tol = newtol;
2557           }
2558         }
2559       }
2560     }
2561     else
2562     {
2563       myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL2 );
2564     }
2565   }
2566
2567   if ( ! LastFixStatus ( ShapeExtend_DONE ) ) return Standard_False;
2568
2569   B.UpdateVertex ( V1, pnt, tol );
2570   B.UpdateVertex ( V2, pnt, tol );
2571
2572   //:h4: make edges SP (after all cuts: t4mug.stp #3730+#6460)
2573   if ( cutEdge1 ) myFixEdge->FixSameParameter ( E1 );
2574   if ( cutEdge2 && !IsCutLine ) myFixEdge->FixSameParameter ( E2 );
2575   if ( cutEdge1 || cutEdge2 ) {
2576     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE7 );
2577   }
2578   if ( ! myShape.IsNull() ) {
2579     SendWarning ( Message_Msg ( "FixAdvWire.FixIntersection.MSG10" ) );// Edges were intersecting, corrected
2580   }
2581   return Standard_True;
2582 }
2583
2584 //=======================================================================
2585 //function : FixIntersectingEdges
2586 //purpose  : 
2587 //=======================================================================
2588 //pdn 17.03.99 fixing non ajacent intersection by increasing tolerance of vertex
2589
2590 Standard_Boolean ShapeFix_Wire::FixIntersectingEdges (const Standard_Integer num1,
2591                                                       const Standard_Integer num2)
2592 {
2593   myLastFixStatus = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
2594   if ( !IsReady() ) return Standard_False;
2595   IntRes2d_SequenceOfIntersectionPoint points2d;
2596   TColgp_SequenceOfPnt points3d;
2597   TColStd_SequenceOfReal errors;
2598   Handle(ShapeAnalysis_Wire) theAdvAnalyzer = Handle(ShapeAnalysis_Wire)::DownCast(myAnalyzer);
2599   if (theAdvAnalyzer.IsNull()) return Standard_False;
2600   theAdvAnalyzer->CheckIntersectingEdges ( num1, num2, points2d, points3d, errors);
2601   if ( theAdvAnalyzer->LastCheckStatus ( ShapeExtend_FAIL ) ) {
2602     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL1 );
2603   }
2604   if ( ! theAdvAnalyzer->LastCheckStatus ( ShapeExtend_DONE ) ) return Standard_False;
2605   TColgp_Array1OfPnt vertexPoints(1,4);
2606   TColStd_Array1OfReal vertexTolers(1,4);
2607   TColStd_Array1OfReal newTolers(1,4);
2608   TopTools_Array1OfShape vertices(1,4);
2609   newTolers.Init(0);
2610   
2611   Handle(ShapeExtend_WireData) sbwd = WireData();
2612   Standard_Integer n2 = ( num1 >0 ? num1  : sbwd->NbEdges() );
2613   Standard_Integer n1 = ( num2  >1 ? num2 : sbwd->NbEdges() );
2614   if(n1==n2) return Standard_False;
2615   
2616   TopoDS_Edge edge1 = sbwd->Edge(n1);
2617   TopoDS_Edge edge2 = sbwd->Edge(n2);
2618   
2619   ShapeAnalysis_Edge sae;
2620   vertices(1) = sae.FirstVertex(edge1);
2621   vertices(2) = sae.LastVertex(edge1);
2622   vertices(3) = sae.FirstVertex(edge2);
2623   vertices(4) = sae.LastVertex(edge2);
2624   
2625   Standard_Integer i; // svv Jan11 2000 : porting on DEC
2626   for (i = 1; i <=4; i++) {
2627     vertexPoints(i) = BRep_Tool::Pnt(TopoDS::Vertex(vertices(i)));
2628     vertexTolers(i) = BRep_Tool::Tolerance(TopoDS::Vertex(vertices(i)));
2629   }
2630    
2631   Standard_Real aNewTolEdge1 = 0.0, aNewTolEdge2 = 0.0;
2632   Standard_Integer nb = points3d.Length();
2633   for ( i=1; i <= nb; i++ ) {
2634     gp_Pnt pint = points3d.Value(i);
2635
2636     // searching for the nearest vertexies to the intersection point
2637     Standard_Real aVtx1Param=0., aVtx2Param=0.;
2638     Standard_Integer aVC1, aVC2;
2639     Standard_Real aMinDist = RealLast();
2640     gp_Pnt aNearestVertex;
2641     Standard_Real aNecessaryVtxTole = 0.0;
2642     for(aVC1 = 1; aVC1 <= 2; aVC1++) {
2643       for(aVC2 = 3; aVC2 <= 4; aVC2++) {
2644       
2645         Standard_Real aVtxIPDist = pint.Distance(vertexPoints(aVC1));
2646         Standard_Real aVtxVtxDist = vertexPoints(aVC1).Distance(vertexPoints(aVC2));
2647         if(aMinDist > aVtxIPDist && aVtxIPDist > aVtxVtxDist) {
2648           aNecessaryVtxTole = aVtxVtxDist;
2649           aNearestVertex = vertexPoints(aVC1);
2650           aMinDist = aVtxIPDist;
2651           aVtx1Param = BRep_Tool::Parameter(TopoDS::Vertex(vertices(aVC1)),edge1);
2652           aVtx2Param = BRep_Tool::Parameter(TopoDS::Vertex(vertices(aVC2)),edge2);
2653         }
2654       }
2655     }
2656     
2657     // calculation of necessary tolerances of edges
2658     const IntRes2d_IntersectionPoint &IP = points2d.Value(i);
2659     Standard_Real param1 = IP.ParamOnFirst(); 
2660     Standard_Real param2 = IP.ParamOnSecond();  
2661     Handle(Geom_Curve) aCurve1, aCurve2;
2662     Standard_Real f,l;
2663     TopLoc_Location L1, L2;
2664     aCurve1 = BRep_Tool::Curve(edge1, L1, f, l);
2665     aCurve2 = BRep_Tool::Curve(edge2, L2, f, l);
2666     
2667     // if aMinDist lower than resolution than the intersection point lyes inside the vertex
2668     if(aMinDist < gp::Resolution())
2669       continue;
2670     
2671     Standard_Real aMaxEdgeTol1 = 0.0, aMaxEdgeTol2 = 0.0;
2672     if(aMinDist < RealLast() && !aCurve1.IsNull() && !aCurve2.IsNull())
2673     {
2674       gp_Lin aLig(aNearestVertex, gp_Vec(aNearestVertex, pint));
2675       Standard_Integer aPointsC;
2676       Standard_Real du1 = 0.05*(param1 - aVtx1Param);
2677       Standard_Real du2 = 0.05*(param2 - aVtx2Param);
2678       Standard_Real tole1=BRep_Tool::Tolerance(edge1);
2679       Standard_Real tole2=BRep_Tool::Tolerance(edge2);
2680       for(aPointsC = 2; aPointsC < 19; aPointsC++)
2681       {
2682         Standard_Real u = aVtx1Param + aPointsC * du1;
2683         gp_Pnt P1 = aCurve1->Value(u);
2684         P1.Transform(L1.Transformation());
2685         Standard_Real d1 = aLig.Distance(P1) * 2.0000001;
2686         if(d1 > tole1 && d1 > aMaxEdgeTol1)
2687           aMaxEdgeTol1 = d1;
2688
2689         u = aVtx2Param + aPointsC * du2;
2690         gp_Pnt P2 = aCurve2->Value(u);
2691         P2.Transform(L2.Transformation());
2692         Standard_Real d2 = aLig.Distance(P2) * 2.0000001;
2693         if(d2 > tole2 && d2 > aMaxEdgeTol2)
2694           aMaxEdgeTol2 = d2;
2695       }
2696       if(aMaxEdgeTol1 == 0.0 && aMaxEdgeTol2 == 0.0) continue;
2697       // if the vertexies are far than tolerances so 
2698       // we do not need to increase edge tolerance
2699       if(aNecessaryVtxTole > Max(aMaxEdgeTol1, tole1) ||
2700          aNecessaryVtxTole > Max(aMaxEdgeTol2, tole2))
2701       {
2702         aMaxEdgeTol1 = 0.0;
2703         aMaxEdgeTol2 = 0.0;
2704       }
2705     }
2706     
2707     Standard_Real rad = errors.Value(i);
2708     Standard_Real finTol = RealLast();
2709     Standard_Integer rank=1;
2710     for(Standard_Integer j=1; j<=4; j++) {
2711       Standard_Real newtol = 1.0001 * ( pint.Distance (vertexPoints(j)) + rad );
2712       if(newtol<finTol) {
2713         rank = j;
2714         finTol = newtol;
2715       }
2716     }
2717     if(finTol <= MaxTolerance()) {
2718       myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1);
2719       if(newTolers(rank) < finTol)
2720       {
2721         if(Max(aMaxEdgeTol1, aMaxEdgeTol2) < finTol && (aMaxEdgeTol1 > 0 || aMaxEdgeTol2 > 0))
2722         {
2723           aNewTolEdge1 = Max(aNewTolEdge1, aMaxEdgeTol1);
2724           aNewTolEdge2 = Max(aNewTolEdge2, aMaxEdgeTol2);
2725         }
2726         else
2727         {
2728           newTolers(rank) = finTol;
2729         }
2730       }
2731     } else {
2732       myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL2 );
2733     }
2734   }
2735   
2736   BRep_Builder B;
2737   // update of tolerances of edges 
2738   if(aNewTolEdge1 > 0)
2739   {
2740     for(i = 1; i <= 2; i++)
2741       if(aNewTolEdge1 > Max(vertexTolers(i), newTolers(i)))
2742         newTolers(i) = aNewTolEdge1;
2743     B.UpdateEdge(edge1, aNewTolEdge1);
2744   }
2745   if(aNewTolEdge2 > 0)
2746   {
2747     for(i = 3; i <= 4; i++)
2748       if(aNewTolEdge2 > Max(vertexTolers(i), newTolers(i)))
2749         newTolers(i) = aNewTolEdge2;
2750     B.UpdateEdge(edge2, aNewTolEdge2);
2751   }
2752     
2753   // update of tolerances of vertexies 
2754   for(i = 1; i <=4; i++)
2755     if(newTolers(i)>0) B.UpdateVertex(TopoDS::Vertex(vertices(i)),newTolers(i));
2756   
2757   if ( ! myShape.IsNull() ) {
2758     SendWarning ( Message_Msg ( "FixAdvWire.FixIntersection.MSG10" ) );// Edges were intersecting, corrected
2759   }
2760   return Standard_True;
2761 }
2762
2763 //=======================================================================
2764 //function : FixLacking
2765 //purpose  : Test if two adjucent edges are disconnected in 2d (while connected 
2766 //           in 3d), and in that case either increase tolerance of the vertex or
2767 //           add a new edge (straight in 2d space), in order to close wire in 2d.
2768 //           Returns True if edge was added or tolerance was increased.
2769 //NOTE     : Is to be run after FixDegenerated
2770 //Algorithm: 1. Compute the 2d gap between edges and calculate a tolerance
2771 //              which should have vertex in order to comprise the gap
2772 //              (using GeomAdaptor_Surface); computed value is inctol
2773 //           2. If inctol < tol of vertex, return False (everything is OK)
2774 //           3. If inctol < Precision, just increase tolerance of vertex to inctol
2775 //           4. Else (if both edges are not degenerated) try to add new edge 
2776 //              with straight pcurve (in order to close the gap):
2777 //              a) if flag MayEdit is False
2778 //                 1. if inctol < MaxTolerance, increase tolerance of vertex to inctol
2779 //                 2. else try to add degenerated edge (check that middle point of 
2780 //                    that pcurveis inside the vertex)
2781 //              b) if MayEdit is True
2782 //                 1. try to replace big vertex with two new small vertices 
2783 //                    connected by new edge. This is made if there is a 3d space
2784 //                    between ends of adjacent edges.
2785 //                 2. if inctol < MaxTolerance, increase tolerance of vertex to inctol
2786 //                 3. else add either degenerated or closed edge (if middle point
2787 //                    of a pcurve of a new edge is inside the vertex, then
2788 //                    degenerated edge is added, else new edge is closed).
2789 //           5. If new edge cannot be added, but inctol < MaxTolerance,
2790 //              when increase tolerance of vertex to a value of inctol
2791 //Short list of some internal variables:
2792 // tol    - tolerance of vertex
2793 // tol2d  - tolerance in parametric space of the surface corresponding to 2*tol
2794 // dist2d - distance between ends of pcurves of edges (2d)
2795 // inctol - tolerance required for vertex to close 2d gap (=tol*dist2d/tol2d)
2796 // tol1, tol2 - tolerances of edges, tol0 = tol1 + tol2
2797 // p3d1, p3d2 - ends of 3d curves of edges
2798 //=======================================================================
2799 //:h2 abv 28 May 98: merged modifications by abv 22 Apr 98, gka 27 May 98 
2800 // and pdn 25 May 98 concerning lacking closed or degenerated edges
2801 // Example files: r0501_pe #107813, UKI60107-6 250, UKI60107-3 1577.
2802
2803 //:s2 abv 21 Apr 99: add functionality for bending pcurve
2804 static Standard_Boolean TryBendingPCurve (const TopoDS_Edge &E, const TopoDS_Face &face,
2805                                           const gp_Pnt2d p2d, const Standard_Boolean end,
2806                                           Handle(Geom2d_Curve) &c2d,
2807                                           Standard_Real &first, Standard_Real &last,
2808                                           Standard_Real &tol)
2809 {
2810   ShapeAnalysis_Edge sae;
2811   if ( ! sae.PCurve ( E, face, c2d, first, last, Standard_False ) ) return Standard_False;
2812   
2813   {
2814   try {
2815     OCC_CATCH_SIGNALS
2816     Handle(Geom2d_BSplineCurve) bs;
2817     if ( c2d->IsKind(STANDARD_TYPE(Geom2d_BSplineCurve)) ) 
2818       bs = Handle(Geom2d_BSplineCurve)::DownCast(c2d->Copy());
2819     else // if ( c2d->IsKind(STANDARD_TYPE(Geom2d_Line)) ) 
2820     {
2821       Handle(Geom2d_TrimmedCurve) trim = new Geom2d_TrimmedCurve ( c2d, first, last );
2822       bs = Geom2dConvert::CurveToBSplineCurve ( trim );
2823     }
2824     if ( bs.IsNull() ) return Standard_False;
2825   
2826     Standard_Real par = ( end ? last : first );
2827     if ( fabs ( bs->FirstParameter() - par ) < ::Precision::PConfusion() &&
2828         bs->Multiplicity(1) > bs->Degree() ) bs->SetPole ( 1, p2d );
2829     else if ( fabs ( bs->LastParameter() - par ) < ::Precision::PConfusion() &&
2830              bs->Multiplicity(bs->NbKnots()) > bs->Degree() ) bs->SetPole ( bs->NbPoles(), p2d );
2831     else {
2832       bs->Segment ( first, last );
2833       if (fabs ( bs->FirstParameter() - par ) < ::Precision::PConfusion() &&
2834           bs->Multiplicity(1) > bs->Degree()) bs->SetPole ( 1, p2d );
2835       else if (fabs ( bs->LastParameter() - par ) < ::Precision::PConfusion() &&
2836                bs->Multiplicity(bs->NbKnots()) > bs->Degree()) bs->SetPole ( bs->NbPoles(), p2d );
2837       else return Standard_False;
2838     }
2839     c2d = bs;
2840
2841     if ( ! TryNewPCurve ( E, face, c2d, first, last, tol ) ) return Standard_False;
2842   }
2843   catch ( Standard_Failure ) {
2844 #ifdef OCCT_DEBUG
2845     cout << "Warning: ShapeFix_Wire::FixLacking: Exception in Geom2d_BSplineCurve::Segment()" << endl;
2846 #endif
2847     return Standard_False;
2848   }
2849   }
2850
2851   return Standard_True;
2852 }
2853
2854
2855 //=======================================================================
2856 //function : FixLacking
2857 //purpose  : 
2858 //=======================================================================
2859
2860 Standard_Boolean ShapeFix_Wire::FixLacking (const Standard_Integer num,
2861                                             const Standard_Boolean force) 
2862 {
2863     myLastFixStatus = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
2864   if ( ! IsReady() ) return Standard_False;
2865
2866   //=============
2867   // First phase: analysis whether the problem (gap) exists
2868   gp_Pnt2d p2d1, p2d2;
2869   Handle(ShapeAnalysis_Wire)::DownCast(myAnalyzer)->CheckLacking ( num, ( force ? Precision() : 0. ), p2d1, p2d2 );
2870   if ( myAnalyzer->LastCheckStatus ( ShapeExtend_FAIL ) ) {
2871     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL1 );
2872   }
2873   if ( ! myAnalyzer->LastCheckStatus ( ShapeExtend_DONE ) ) return Standard_False;
2874   
2875   //=============
2876   // Second phase: collection of data necessary for further analysis
2877   
2878   Handle(ShapeExtend_WireData) sbwd = WireData();
2879   Standard_Integer n2 = ( num >0 ? num  : sbwd->NbEdges() );
2880   Standard_Integer n1 = ( n2  >1 ? n2-1 : sbwd->NbEdges() );
2881   TopoDS_Edge E1 = sbwd->Edge(n1);
2882   TopoDS_Edge E2 = sbwd->Edge(n2);
2883   
2884   ShapeAnalysis_Edge sae;
2885   TopoDS_Vertex V1 = sae.LastVertex  ( E1 );
2886   TopoDS_Vertex V2 = sae.FirstVertex ( E2 );
2887   Standard_Real tol = Max ( BRep_Tool::Tolerance ( V1 ), BRep_Tool::Tolerance ( V2 ) );
2888   
2889   Standard_Real Prec = Precision();
2890   Standard_Real dist2d = myAnalyzer->MaxDistance2d();
2891   Standard_Real inctol = myAnalyzer->MaxDistance3d();
2892   
2893   TopoDS_Face face = myAnalyzer->Face();
2894   Handle(ShapeAnalysis_Surface) surf = myAnalyzer->Surface();
2895
2896   gp_Pnt p3d1, p3d2;
2897   Standard_Real tol1=::Precision::Confusion(), tol2=::Precision::Confusion(); //SK
2898
2899   //=============
2900   //:s2 abv 21 Apr 99: Speculation: try bending pcurves
2901   Standard_Real bendtol1 = 0., bendtol2 = 0.;
2902   Handle(Geom2d_Curve) bendc1, bendc2;
2903   Standard_Real bendf1 = 0., bendl1 = 0., bendf2 = 0., bendl2 = 0.;
2904   if ( myGeomMode && ! BRep_Tool::IsClosed(E1,face) && ! BRep_Tool::IsClosed(E2,face) ) {
2905     gp_Pnt2d p2d = 0.5 * ( p2d1.XY() + p2d2.XY() );
2906     Standard_Boolean ok1 = TryBendingPCurve (E1, face, p2d, E1.Orientation() == TopAbs_FORWARD, 
2907                                              bendc1, bendf1, bendl1, bendtol1);
2908     Standard_Boolean ok2 = TryBendingPCurve (E2, face, p2d, E2.Orientation() == TopAbs_REVERSED, 
2909                                              bendc2, bendf2, bendl2, bendtol2);
2910     if ( ok1 && ! ok2 ) {
2911       bendtol2 = BRep_Tool::Tolerance(E2);
2912       ok1 = TryBendingPCurve (E1, face, p2d2, E1.Orientation() == TopAbs_FORWARD, 
2913                               bendc1, bendf1, bendl1, bendtol1);
2914     }
2915     else if ( ! ok1 && ok2 ) {
2916       bendtol1 = BRep_Tool::Tolerance(E1);
2917       ok2 = TryBendingPCurve (E2, face, p2d1, E2.Orientation() == TopAbs_FORWARD, 
2918                               bendc2, bendf2, bendl2, bendtol2);
2919     }
2920     if ( ! ok1 && ! ok2 ) bendc1.Nullify();
2921   }
2922   
2923   //=============
2924   // Third phase: analyse how to fix the problem
2925   
2926   // selector of solutions
2927   Standard_Boolean doIncrease  = Standard_False; // increase tolerance
2928   Standard_Boolean doAddLong   = Standard_False; // add long 3d edge in replacement of a vertex
2929   Standard_Boolean doAddClosed = Standard_False; // add closed 3d edge
2930   Standard_Boolean doAddDegen  = Standard_False; // add degenerated edge
2931   Standard_Boolean doBend      = Standard_False; //:s2 bend pcurves
2932
2933   // if bending is OK with existing tolerances of edges, take it
2934   if ( ! bendc1.IsNull() && ! bendc2.IsNull() &&
2935        ( ( bendtol1 < BRep_Tool::Tolerance(E1) &&
2936            bendtol2 < BRep_Tool::Tolerance(E2) ) ||
2937          ( inctol < Prec && bendtol1 < inctol && bendtol2 < inctol ) ) ) 
2938        doBend = Standard_True;
2939   
2940   // is it OK just to increase tolerance (to a value less than preci)?
2941   else if ( inctol < Prec ) doIncrease = Standard_True;
2942
2943   // If increase is not OK or force, try to find other solutions (adding edge)
2944   else if ( ! BRep_Tool::Degenerated ( E2 ) && ! BRep_Tool::Degenerated ( E1 ) ) {
2945     
2946     // analyze the 3d space btw edges: is it enough to add long 3d edge?
2947     if ( myTopoMode ) {
2948       Handle(Geom_Curve) c3d;
2949       Standard_Real a, b;
2950       if ( ! sae.Curve3d ( E1, c3d, a, b, Standard_True ) ) { // cannot work
2951         myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL1 );
2952         return Standard_False; 
2953       }
2954       p3d1 = c3d->Value ( b );
2955       Standard_Real dist2d3d1 = p3d1.Distance ( surf->Value ( p2d1 ) );
2956       if ( ! sae.Curve3d ( E2, c3d, a, b, Standard_True ) ) { // cannot work
2957         myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL1 );
2958         return Standard_False; 
2959       }
2960       p3d2 = c3d->Value ( a );
2961       Standard_Real dist2d3d2 = p3d2.Distance ( surf->Value ( p2d2 ) );
2962
2963       tol1 = Max ( BRep_Tool::Tolerance ( E1 ), dist2d3d1 );
2964       tol2 = Max ( BRep_Tool::Tolerance ( E2 ), dist2d3d2 );
2965       //:c5  Standard_Real tol0 = Max ( tol1 + tol2, thepreci );
2966       Standard_Real tol0 = tol1 + tol2; //:c5 abv 26 Feb 98: CTS17806 #44418
2967       Standard_Real dist3d2 = p3d1.SquareDistance ( p3d2 );
2968
2969       // is it OK to add a long 3d edge?
2970       if ( ! myAnalyzer->LastCheckStatus ( ShapeExtend_DONE2 ) && //:81 abv 20 Jan 98: don`t add back-going edges (zigzags)
2971            dist3d2 > 1.25 * tol0 * tol0 &&
2972            ( force || dist3d2 > Prec * Prec || inctol > MaxTolerance() ) ) {
2973         doAddLong = Standard_True;
2974       }
2975     }
2976     
2977     //:h6 abv 25 Jun 98: BUC40132 6361: try to increase tol up to MaxTol if not add
2978     if ( ! doAddLong && inctol < MaxTolerance() && 
2979          ! myAnalyzer->Surface()->IsDegenerated ( p2d1, p2d2, 2.*tol, 10. ) ) { //:p7
2980       if ( ! bendc1.IsNull() && ! bendc2.IsNull() &&
2981            bendtol1 < inctol && bendtol2 < inctol ) doBend = Standard_True;
2982       else doIncrease = Standard_True;
2983     }
2984     else 
2985       
2986     // else try to add either degenerated or closed edge
2987     if ( ! doAddLong ) {
2988       gp_Pnt pV = 0.5 * ( BRep_Tool::Pnt(V1).XYZ() + BRep_Tool::Pnt(V2).XYZ() );
2989       gp_Pnt pm = myAnalyzer->Surface()->Value ( 0.5 * ( p2d1.XY() + p2d2.XY() ) );
2990
2991       Standard_Real dist = pV.Distance ( pm );
2992       if ( dist <= tol ) doAddDegen = Standard_True;
2993       else if ( myTopoMode ) doAddClosed = Standard_True;
2994       else if ( dist <= MaxTolerance() ) { //:r7 abv 12 Apr 99: t3d_opt.stp #14245 after S4136
2995         doAddDegen = Standard_True;
2996         doIncrease = Standard_True;
2997         inctol = dist; 
2998       }
2999     }
3000   }
3001
3002   else if ( !BRep_Tool::Degenerated(E2) && BRep_Tool::Degenerated(E1) ) {
3003     // create new degenerated edge and replace E1 to new edge
3004   }
3005   else if ( BRep_Tool::Degenerated(E2) && !BRep_Tool::Degenerated(E1) ) {
3006     // create new degenerated edge and replace E2 to new edge
3007   }
3008   
3009   //=============
3010   // Third phase - do the fixes
3011   BRep_Builder B;
3012
3013   // add edge
3014   if ( doAddLong || doAddDegen || doAddClosed ) {
3015
3016     // construct new vertices
3017     TopoDS_Vertex newV1, newV2;
3018     if ( doAddLong ) {
3019       newV1 = BRepBuilderAPI_MakeVertex ( p3d1 );
3020       newV1.Reverse();
3021       newV2 = BRepBuilderAPI_MakeVertex ( p3d2 );
3022       B.UpdateVertex ( newV1, 1.001 * tol1 );
3023       B.UpdateVertex ( newV2, 1.001 * tol2 );
3024     }
3025     else {
3026       newV1 = V1;
3027       newV2 = V2;
3028     }
3029
3030     // prepare new edge
3031     TopoDS_Edge edge;
3032     B.MakeEdge ( edge );
3033     if ( doAddDegen ) B.Degenerated ( edge, Standard_True ); // sln: do it before adding curve
3034     gp_Vec2d v12 ( p2d1, p2d2 );
3035     Handle(Geom2d_Line) theLine2d = new Geom2d_Line ( p2d1, gp_Dir2d ( v12 ) );
3036     B.UpdateEdge ( edge, theLine2d, face, ::Precision::Confusion() );
3037     B.Range ( edge, face, 0, dist2d );
3038     B.Add ( edge, newV1.Oriented ( TopAbs_FORWARD ) );
3039     B.Add ( edge, newV2.Oriented ( TopAbs_REVERSED ) );
3040     ShapeBuild_Edge sbe;
3041     if ( ! doAddDegen && ! sbe.BuildCurve3d ( edge ) ) {
3042       myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL3 );
3043       return Standard_False; 
3044     }
3045
3046     // if long edge is added, replace vertices of adjacent edges
3047     if ( doAddLong ) {
3048       
3049       // replace 1st edge (n1==n2 - special case: wire consists of one edge)
3050       TopoDS_Edge edge1 = sbe.CopyReplaceVertices ( E1, 
3051                           ( n1 == n2 ? newV2 : TopoDS_Vertex() ), newV1 );
3052       sbwd->Set ( edge1, n1 );
3053       if ( ! Context().IsNull() ) {
3054         Context()->Replace ( E1, edge1 );
3055         // actually, this will occur only in context of single face
3056         // hence, recording to ReShape is rather for tracking modifications
3057         // than for keeping sharing
3058         Context()->Replace ( V1, newV1.Oriented ( V1.Orientation() ) );
3059         if ( ! V1.IsSame ( V2 ) ) { 
3060           Context()->Replace ( V2, newV2.Oriented ( V2.Orientation() ) );
3061         }
3062       }
3063       // replace 2nd edge
3064       if ( n1 != n2 ) {
3065         TopoDS_Edge edge2 = sbe.CopyReplaceVertices ( E2, newV2, TopoDS_Vertex() );
3066         sbwd->Set ( edge2, n2 );
3067         if ( ! Context().IsNull() ) Context()->Replace ( E2, edge2 );
3068       }
3069       if ( ! Context().IsNull() ) UpdateWire();
3070     }
3071
3072     // insert new edge
3073     if ( doAddDegen ) {
3074       myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE3 );
3075 #ifdef OCCT_DEBUG
3076       cout << "Warning: ShapeFix_Wire::FixLacking: degenerated edge added" << endl;
3077 #endif
3078     }
3079     else if ( ! doAddLong ) {
3080       myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE4 );
3081     }
3082     sbwd->Add ( edge, n2 );
3083     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE2 );
3084   }
3085   
3086   // else try to increase tol up to MaxTol
3087   else if ( inctol > tol && inctol < MaxTolerance() ) {
3088     if ( ! bendc1.IsNull() && ! bendc2.IsNull() &&
3089          bendtol1 < inctol && bendtol2 < inctol ) doBend = Standard_True;
3090     else doIncrease = Standard_True;
3091   }
3092   
3093   // bend pcurves
3094   if ( doBend ) { //:s2 abv 21 Apr 99
3095     B.UpdateEdge ( E1, bendc1, face, bendtol1 );
3096     B.Range ( E1, face, bendf1, bendl1 );
3097     B.UpdateEdge ( E2, bendc2, face, bendtol2 );
3098     B.Range ( E2, face, bendf2, bendl2 );
3099     B.UpdateVertex ( sae.FirstVertex(E1), bendtol1 );
3100     B.UpdateVertex ( sae.LastVertex(E1), bendtol1 );
3101     B.UpdateVertex ( sae.FirstVertex(E2), bendtol2 );
3102     B.UpdateVertex ( sae.LastVertex(E2), bendtol2 );
3103     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE5 );
3104     //:s3 abv 22 Apr 99: PRO7187 #11534: self-intersection not detected unitil curve is bent (!)
3105     FixSelfIntersectingEdge ( n1 );
3106     FixSelfIntersectingEdge ( n2 );
3107     FixIntersectingEdges ( n2 ); //skl 24.04.2003 for OCC58
3108 #ifdef OCCT_DEBUG
3109     cout << "Info: ShapeFix_Wire::FixLacking: Bending pcurves" << endl;
3110 #endif
3111     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE5 );
3112   }
3113   
3114   // increase vertex tolerance
3115   if ( doIncrease ) {
3116     B.UpdateVertex ( V1, 1.001 * inctol );
3117     B.UpdateVertex ( V2, 1.001 * inctol );
3118     myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
3119   }
3120
3121   if ( LastFixStatus ( ShapeExtend_DONE ) ) return Standard_True;
3122
3123   myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_FAIL2 );
3124   return Standard_False;
3125 }
3126
3127 //=======================================================================
3128 //function : FixNotchedEdges
3129 //purpose  : 
3130 //=======================================================================
3131
3132 Standard_Boolean ShapeFix_Wire::FixNotchedEdges()
3133 {
3134   myLastFixStatus = ShapeExtend::EncodeStatus ( ShapeExtend_OK );
3135   if ( ! IsReady() ) return Standard_False;
3136   
3137   Handle(ShapeAnalysis_Wire) theAdvAnalyzer = Handle(ShapeAnalysis_Wire)::DownCast(myAnalyzer);
3138   TopoDS_Face face = Face();
3139   if ( ! Context().IsNull() ) UpdateWire();
3140   Handle(ShapeExtend_WireData) sewd = WireData();
3141   
3142   for (Standard_Integer i = 1; i <= NbEdges() && NbEdges() > 2; i++) {
3143     Standard_Real param;
3144     Standard_Integer toRemove;
3145     if(theAdvAnalyzer->CheckNotchedEdges(i,toRemove,param,MinTolerance())){
3146       Standard_Integer n2 = (i > 0)  ? i : NbEdges();
3147       Standard_Integer n1 = (n2 > 1) ? n2-1 : NbEdges();
3148       Standard_Boolean isRemoveFirst = (n1==toRemove);
3149       Standard_Integer toSplit = (n2==toRemove ? n1 : n2);
3150       TopoDS_Edge splitE =  sewd->Edge ( toSplit );
3151       ShapeAnalysis_Edge sae;
3152       Handle(Geom2d_Curve) c2d;
3153       Standard_Real a, b;
3154       sae.PCurve ( splitE, face, c2d, a, b, Standard_True );
3155       Standard_Real ppar = (isRemoveFirst ? b : a);
3156       ShapeBuild_Edge sbe;
3157       TopAbs_Orientation orient = splitE.Orientation();
3158       if ( Abs(param - ppar) > ::Precision::PConfusion() ) {
3159         //pdn perform splitting of the edge and adding to wire
3160         
3161         //pdn check if it is necessary
3162         if( Abs((isRemoveFirst ? a : b)-param) < ::Precision::PConfusion() ) {
3163           continue;
3164         }
3165           
3166         Handle(ShapeAnalysis_TransferParametersProj) transferParameters =
3167           new ShapeAnalysis_TransferParametersProj;
3168         transferParameters->SetMaxTolerance(MaxTolerance());
3169         transferParameters->Init(splitE,face);
3170         Standard_Real first, last;
3171         if (a < b ) {
3172           first = a; 
3173           last = b;
3174         }
3175         else {
3176           first = b; 
3177           last = a;
3178         }
3179         TopoDS_Vertex Vnew;
3180         BRep_Builder B;
3181         B.MakeVertex(Vnew,Analyzer()->Surface()->Value(c2d->Value(param)),::Precision::Confusion());
3182         TopoDS_Edge wE = splitE;
3183         wE.Orientation ( TopAbs_FORWARD );
3184         TopoDS_Shape aTmpShape = Vnew.Oriented(TopAbs_REVERSED); //for porting
3185         TopoDS_Edge newE1 = sbe.CopyReplaceVertices ( wE, sae.FirstVertex(wE), TopoDS::Vertex(aTmpShape) );
3186         sbe.CopyPCurves ( newE1, wE  );
3187         transferParameters->TransferRange(newE1,first,param,Standard_True);
3188         B.SameRange(newE1,Standard_False);
3189         B.SameParameter(newE1,Standard_False);
3190         aTmpShape = Vnew.Oriented(TopAbs_FORWARD);
3191         TopoDS_Edge newE2 = sbe.CopyReplaceVertices ( wE, TopoDS::Vertex(aTmpShape),sae.LastVertex(wE) );
3192         sbe.CopyPCurves ( newE2, wE  );
3193         transferParameters->TransferRange(newE2,param,last,Standard_True);
3194         B.SameRange(newE2,Standard_False);
3195         B.SameParameter(newE2,Standard_False);
3196         
3197         if ( !Context().IsNull() ) {
3198           TopoDS_Wire wire;
3199           B.MakeWire(wire);
3200           B.Add(wire,newE1);
3201           B.Add(wire,newE2);
3202           Context()->Replace ( wE, wire );
3203         }
3204         
3205         newE1.Orientation(orient);
3206         newE2.Orientation(orient);
3207         if (orient==TopAbs_REVERSED){ TopoDS_Edge tmp = newE2; newE2 = newE1; newE1=tmp;}
3208         
3209         Standard_Boolean isRemoveLast = ((n1==NbEdges())&&(n2==1));
3210         sewd->Set ( newE1, toSplit);
3211         sewd->Add ( newE2, (toSplit==NbEdges()  ? 0 : toSplit+1));
3212         
3213         FixDummySeam(isRemoveLast ? NbEdges() : toRemove);
3214         myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE2 );
3215       }
3216       else 
3217       {
3218         FixDummySeam(n1);
3219         // The seam edge is removed from the list. So, need to step back to avoid missing of edge processing
3220         i--;
3221       }
3222   
3223       i--;
3224       if(!Context().IsNull()) //skl 07.03.2002 for OCC180
3225         UpdateWire();
3226       myLastFixStatus |= ShapeExtend::EncodeStatus ( ShapeExtend_DONE1 );
3227     }
3228   }
3229   myStatusNotches = myLastFixStatus;
3230   return LastFixStatus ( ShapeExtend_DONE );
3231 }
3232
3233 //=======================================================================
3234 //function : FixDummySeam
3235 //purpose  : 
3236 //=======================================================================
3237
3238 static void CopyReversePcurves(const TopoDS_Edge& toedge, 
3239                                const TopoDS_Edge& fromedge,
3240                                const Standard_Boolean reverse)
3241 {
3242   TopLoc_Location fromLoc = fromedge.Location();
3243   TopLoc_Location toLoc = toedge.Location();
3244   for (BRep_ListIteratorOfListOfCurveRepresentation fromitcr
3245        ((*((Handle(BRep_TEdge)*)&fromedge.TShape()))->ChangeCurves()); fromitcr.More(); fromitcr.Next()) {
3246     Handle(BRep_GCurve) fromGC = Handle(BRep_GCurve)::DownCast(fromitcr.Value());
3247     if ( fromGC.IsNull() ) continue;
3248     if ( fromGC->IsCurveOnSurface() ) {
3249       Handle(Geom_Surface) surface = fromGC->Surface();
3250       TopLoc_Location L = fromGC->Location();
3251       Standard_Boolean found = Standard_False;
3252       BRep_ListOfCurveRepresentation& tolist = (*((Handle(BRep_TEdge)*)&toedge.TShape()))->ChangeCurves();
3253       Handle(BRep_GCurve) toGC;
3254       for (BRep_ListIteratorOfListOfCurveRepresentation toitcr (tolist); toitcr.More() && !found; toitcr.Next()) {
3255         toGC = Handle(BRep_GCurve)::DownCast(toitcr.Value());
3256         if ( toGC.IsNull() || !toGC->IsCurveOnSurface() || 
3257             surface != toGC->Surface() || L != toGC->Location() ) continue;
3258         found = Standard_True;
3259         break;
3260       }
3261       if (!found) {
3262         Standard_Real fp = fromGC->First();
3263         Standard_Real lp = fromGC->Last();
3264         toGC = Handle(BRep_GCurve)::DownCast(fromGC->Copy());
3265         tolist.Append (toGC);
3266         Handle(Geom2d_Curve) pcurve = Handle(Geom2d_Curve)::DownCast( fromGC->PCurve()->Copy() );
3267         if (reverse) {
3268           fp = pcurve->ReversedParameter(fp);
3269           lp = pcurve->ReversedParameter(lp);
3270           pcurve->Reverse();
3271           Standard_Real tmp = fp;
3272           fp = lp;
3273           lp = tmp;
3274         }
3275         //bug OCC209 invalid location of pcurve in the edge after copying
3276         TopLoc_Location newLoc = (fromLoc*L).Predivided(toLoc);
3277         toGC->SetRange(fp,lp);  
3278         toGC->PCurve(pcurve);
3279         toGC->Location(newLoc);
3280         if ( fromGC->IsCurveOnClosedSurface() ) {
3281           pcurve = fromGC->PCurve2();
3282           toGC->PCurve2(Handle(Geom2d_Curve)::DownCast(pcurve->Copy()));
3283         }
3284       }
3285     }
3286   }
3287 }
3288
3289 //=======================================================================
3290 //function : HasNewPCurves
3291 //purpose  : 
3292 //=======================================================================
3293 //  Note:    This function temporarily not used, because adress to it in
3294 //           function FixDummySeam() (see below line 2472) not used too
3295 //
3296 //static Standard_Boolean HasNewPCurves(const TopoDS_Edge& toedge, 
3297 //                                    const TopoDS_Edge& fromedge)
3298 //     
3299 //{
3300 //  for (BRep_ListIteratorOfListOfCurveRepresentation fromitcr
3301 //       ((*((Handle(BRep_TEdge)*)&fromedge.TShape()))->ChangeCurves()); fromitcr.More(); fromitcr.Next()) {
3302 //    Handle(BRep_GCurve) fromGC = Handle(BRep_GCurve)::DownCast(fromitcr.Value());
3303 //    if ( fromGC.IsNull() ) continue;
3304 //    if ( fromGC->IsCurveOnSurface() ) {
3305 //      Handle(Geom_Surface) surface = fromGC->Surface();
3306 //      TopLoc_Location L = fromGC->Location();
3307 //      Standard_Boolean found = Standard_False;
3308 //      BRep_ListOfCurveRepresentation& tolist = (*((Handle(BRep_TEdge)*)&toedge.TShape()))->ChangeCurves();
3309 //      Handle(BRep_GCurve) toGC;
3310 //      for (BRep_ListIteratorOfListOfCurveRepresentation toitcr (tolist); toitcr.More() && !found; toitcr.Next()) {
3311 //      toGC = Handle(BRep_GCurve)::DownCast(toitcr.Value());
3312 //      if ( toGC.IsNull() || !toGC->IsCurveOnSurface() || 
3313 //          surface != toGC->Surface() || L != toGC->Location() )  continue;
3314 //      found = Standard_True;
3315 //      break;
3316 //      }
3317 //      if (!found) 
3318 //      return Standard_True;
3319 //    }
3320 //  }
3321 //  return Standard_False;
3322 //}
3323
3324 //=======================================================================
3325 //function : FixDummySeam
3326 //purpose  : 
3327 //=======================================================================
3328
3329 void ShapeFix_Wire::FixDummySeam(const Standard_Integer num)
3330 {
3331   ShapeAnalysis_Edge sae;
3332   ShapeBuild_Edge sbe;
3333   ShapeBuild_Vertex sbv;
3334   Standard_Integer num1 = (num == NbEdges()) ? 1 : num+1;
3335   Handle(ShapeExtend_WireData) sewd = WireData();
3336   TopoDS_Edge E1 = sewd->Edge(num), E2 = sewd->Edge(num1);
3337   TopoDS_Vertex V1 = sae.FirstVertex(E1), V2 = sae.LastVertex(E2);
3338   TopoDS_Vertex Vm = sbv.CombineVertex ( V1, V2, 1.0001 );
3339   
3340   //pnd defining if new pcurves exists
3341   //pdn Temporary not removed
3342 //  Standard_Boolean toRemove = !(HasNewPCurves(E1,E2)||HasNewPCurves(E2,E1));
3343   Standard_Boolean toRemove = Standard_False;
3344   
3345   //creating new edge with pcurves and new vertex
3346   TopoDS_Vertex Vs = sae.FirstVertex(E2);
3347   if ( Vs.IsSame ( V1 ) || Vs.IsSame ( V2 ) ) Vs = Vm;
3348   TopoDS_Edge newEdge = sbe.CopyReplaceVertices ( E2, Vs, Vm );
3349   CopyReversePcurves(newEdge,E1,E1.Orientation()==E2.Orientation());
3350   BRep_Builder B;
3351   B.SameRange(newEdge,Standard_False);
3352   B.SameParameter(newEdge,Standard_False);
3353
3354   if ( !Context().IsNull() ) {
3355     if (toRemove) {
3356       Context()->Remove ( E2 );
3357       Context()->Remove ( E1 );
3358     }
3359     else {
3360       Context()->Replace ( E2, newEdge );
3361       Context()->Replace ( E1, newEdge.Reversed());
3362     }
3363     Context()->Replace ( V1, Vm.Oriented(V1.Orientation()) );
3364     Context()->Replace ( V2, Vm.Oriented(V2.Orientation()) );
3365   }
3366  
3367   Standard_Integer next = ( num1 == NbEdges()) ? 1 : num1+1;
3368   Standard_Integer prev = ( num > 1) ? num-1 : NbEdges();
3369   TopoDS_Edge prevE = sewd->Edge(prev), nextE = sewd->Edge(next);
3370   
3371   TopoDS_Edge tmpE1=sbe.CopyReplaceVertices( prevE, TopoDS_Vertex(), Vm);
3372   sewd->Set ( tmpE1,prev );
3373   if ( !Context().IsNull() ) Context()->Replace ( prevE, tmpE1);
3374   
3375   tmpE1  =  sbe.CopyReplaceVertices ( nextE, Vm, TopoDS_Vertex());
3376   sewd->Set ( tmpE1,next );
3377   if ( !Context().IsNull() ) Context()->Replace ( nextE, tmpE1);
3378   
3379   //removing edges from wire
3380   Standard_Integer n1, n2;
3381   if ( num < num1 ) {
3382     n1 = num; n2 = num1;
3383   } else {
3384     n1 = num1; n2 = num;
3385   }
3386   sewd->Remove(n2);
3387   sewd->Remove(n1);
3388 }
3389
3390 //=======================================================================
3391 //function : UpdateWire
3392 //purpose  : 
3393 //=======================================================================
3394
3395 void ShapeFix_Wire::UpdateWire () 
3396 {
3397   Handle(ShapeExtend_WireData) sbwd = WireData();
3398   for ( Standard_Integer i=1; i <= sbwd->NbEdges(); i++ ) {
3399     TopoDS_Edge E = sbwd->Edge(i);
3400     TopoDS_Shape S = Context()->Apply ( E );
3401     if ( S == E ) continue;
3402     for ( TopExp_Explorer exp(S,TopAbs_EDGE); exp.More(); exp.Next() )
3403       sbwd->Add ( exp.Current(), i++ );
3404     sbwd->Remove ( i-- );
3405   }
3406 }
3407
3408 //=======================================================================
3409 //function : FixTails
3410 //purpose  :
3411 //=======================================================================
3412 Standard_Boolean ShapeFix_Wire::FixTails()
3413 {
3414   if (myMaxTailWidth < 0 || !IsReady())
3415   {
3416     return Standard_False;
3417   }
3418
3419   myLastFixStatus = ShapeExtend::EncodeStatus(ShapeExtend_OK);
3420   if (!Context().IsNull())
3421   {
3422     UpdateWire();
3423   }
3424   Handle(ShapeExtend_WireData) aSEWD = WireData();
3425   Standard_Integer aECount = NbEdges(), aENs[] = {aECount, 1};
3426   Standard_Boolean aCheckAngle = Standard_True;
3427   while (aECount >= 2 && aENs[1] <= aECount)
3428   {
3429     const TopoDS_Edge aEs[] = {aSEWD->Edge(aENs[0]), aSEWD->Edge(aENs[1])};
3430     TopoDS_Edge aEParts[2][2];
3431     if (!myAnalyzer->CheckTail(aEs[0], aEs[1],
3432       aCheckAngle ? myMaxTailAngleSine : -1, myMaxTailWidth, MaxTolerance(),
3433       aEParts[0][0], aEParts[0][1], aEParts[1][0], aEParts[1][1]))
3434     {
3435       aENs[0] = aENs[1]++;
3436       aCheckAngle = Standard_True;
3437       continue;
3438     }
3439
3440     // Provide not less than 1 edge in the result wire.
3441     Standard_Integer aSplitCounts[] =
3442       {aEParts[0][1].IsNull() ? 0 : 1, aEParts[1][1].IsNull() ? 0 : 1};
3443     const Standard_Integer aRemoveCount =
3444       (aEParts[0][0].IsNull() ? 0 : 1) + (aEParts[1][0].IsNull() ? 0 : 1);
3445     if (aECount + aSplitCounts[0] + aSplitCounts[1] < 1 + aRemoveCount)
3446     {
3447       aENs[0] = aENs[1]++;
3448       aCheckAngle = Standard_True;
3449       continue;
3450     }
3451
3452     // Split the edges.
3453     for (Standard_Integer aEI = 0; aEI < 2; ++aEI)
3454     {
3455       if (aSplitCounts[aEI] == 0)
3456       {
3457         continue;
3458       }
3459
3460       // Replace the edge by the wire of its parts in the shape.
3461       const TopoDS_Edge aE = aEs[aEI];
3462       if (!Context().IsNull())
3463       {
3464         TopoDS_Wire aEWire;
3465         BRep_Builder().MakeWire(aEWire);
3466         BRep_Builder().Add(aEWire, aEParts[aEI][0]);
3467         BRep_Builder().Add(aEWire, aEParts[aEI][1]);
3468         TopoDS_Edge aFE = TopoDS::Edge(aE.Oriented(TopAbs_FORWARD));
3469         Context()->Replace(aFE, aEWire);
3470       }
3471
3472       // Replace the edge by its parts in the edge wire.
3473       const TopAbs_Orientation aOrient = aE.Orientation();
3474       aEParts[aEI][0].Orientation(aOrient);
3475       aEParts[aEI][1].Orientation(aOrient);
3476       const Standard_Integer aFirstPI = (aOrient != TopAbs_REVERSED) ? 0 : 1;
3477       const Standard_Integer aAdd =
3478         (aEI == 0 || aENs[1] < aENs[0]) ? 0 : aSplitCounts[0];
3479       aSEWD->Set(aEParts[aEI][aFirstPI], aENs[aEI] + aAdd);
3480       aSEWD->Add(aEParts[aEI][1 - aFirstPI], aENs[aEI] + 1 + aAdd);
3481     }
3482
3483     // Remove the tail.
3484     if (aRemoveCount == 2)
3485     {
3486       aCheckAngle = Standard_True;
3487       FixDummySeam(aENs[0] + aSplitCounts[0] +
3488         ((aENs[0] < aENs[1]) ? 0 : aSplitCounts[1]));
3489       if (!Context().IsNull())
3490       {
3491         UpdateWire();
3492       }
3493       myLastFixStatus |= ShapeExtend::EncodeStatus(ShapeExtend_DONE);
3494
3495       if (aSplitCounts[0] + aSplitCounts[1] == 2)
3496       {
3497         aENs[0] = aENs[1]++;
3498         continue;
3499       }
3500
3501       if (aSplitCounts[0] == aSplitCounts[1])
3502       {
3503         aECount -= 2;
3504         if (aENs[1] >= 3)
3505         {
3506           --aENs[0];
3507           --aENs[1];
3508         }
3509         else
3510         {
3511           aENs[0] = aECount;
3512           aENs[1] = 1;
3513         }
3514         aCheckAngle = Standard_False;
3515       }
3516       else
3517       {
3518         --aECount;
3519         if (aSplitCounts[0] != 0)
3520         {
3521           aENs[0] = (aENs[0] <= aECount) ? aENs[0] : aECount;
3522         }
3523         else
3524         {
3525           if (aENs[1] >= 3)
3526           {
3527             --aENs[0];
3528             --aENs[1];
3529           }
3530           else
3531           {
3532             aENs[0] = aECount;
3533             aENs[1] = 1;
3534           }
3535         }
3536       }
3537     }
3538     else
3539     {
3540       aCheckAngle = Standard_False;
3541       --aECount;
3542       const Standard_Integer aRI = aEParts[0][0].IsNull() ? 1 : 0;
3543       if (aSplitCounts[aRI] != 0)
3544       {
3545         if (aRI == 0)
3546         {
3547           if (aENs[1] >= 3)
3548           {
3549             --aENs[0];
3550             --aENs[1];
3551           }
3552           else
3553           {
3554             aENs[0] = aECount;
3555             aENs[1] = 1;
3556           }
3557         }
3558         else
3559         {
3560           aENs[0] = (aENs[1] > 1) ? aENs[0] : aECount;
3561         }
3562       }
3563       aSEWD->Remove(aENs[aRI] + ((aRI != 0 || aSplitCounts[0] == 0) ? 0 : 1));
3564       if (!Context().IsNull())
3565       {
3566         Context()->Remove(aEs[aRI].Oriented(TopAbs_FORWARD));
3567         UpdateWire();
3568       }
3569       myLastFixStatus |= ShapeExtend::EncodeStatus(ShapeExtend_DONE);
3570     }
3571   }
3572   myStatusNotches = myLastFixStatus;
3573   return ShapeExtend::DecodeStatus(myLastFixStatus, ShapeExtend_DONE);
3574 }