0024981: IntTools_FaceFace enters to infinite loop on the attached case
[occt.git] / src / IntTools / IntTools_FaceFace.cxx
1 // Created on: 2000-11-23
2 // Created by: Michael KLOKOV
3 // Copyright (c) 2000-2014 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16 #include <IntTools_FaceFace.ixx>
17
18 #include <Precision.hxx>
19
20 #include <TColStd_HArray1OfReal.hxx>
21 #include <TColStd_Array1OfReal.hxx>
22 #include <TColStd_Array1OfInteger.hxx>
23 #include <TColStd_SequenceOfReal.hxx>
24 #include <TColStd_ListOfInteger.hxx>
25 #include <TColStd_ListIteratorOfListOfInteger.hxx>
26 #include <TColStd_Array1OfListOfInteger.hxx>
27
28 #include <gp_Lin2d.hxx>
29 #include <gp_Ax22d.hxx>
30 #include <gp_Circ2d.hxx>
31 #include <gp_Torus.hxx>
32 #include <gp_Cylinder.hxx>
33
34 #include <Bnd_Box.hxx>
35
36 #include <TColgp_HArray1OfPnt2d.hxx>
37 #include <TColgp_SequenceOfPnt2d.hxx>
38 #include <TColgp_Array1OfPnt.hxx>
39 #include <TColgp_Array1OfPnt2d.hxx>
40
41 #include <IntAna_QuadQuadGeo.hxx>
42
43 #include <IntSurf_PntOn2S.hxx>
44 #include <IntSurf_LineOn2S.hxx>
45 #include <IntSurf_PntOn2S.hxx>
46 #include <IntSurf_ListOfPntOn2S.hxx>
47 #include <IntRes2d_Domain.hxx>
48 #include <ProjLib_Plane.hxx>
49
50 #include <IntPatch_GLine.hxx>
51 #include <IntPatch_RLine.hxx>
52 #include <IntPatch_WLine.hxx>
53 #include <IntPatch_ALine.hxx>
54 #include <IntPatch_ALineToWLine.hxx>
55
56 #include <ElSLib.hxx>
57 #include <ElCLib.hxx>
58
59 #include <Extrema_ExtCC.hxx>
60 #include <Extrema_POnCurv.hxx>
61 #include <BndLib_AddSurface.hxx>
62
63 #include <Adaptor3d_SurfacePtr.hxx>
64 #include <Adaptor2d_HLine2d.hxx>
65
66 #include <GeomAbs_SurfaceType.hxx>
67 #include <GeomAbs_CurveType.hxx>
68
69 #include <Geom_Surface.hxx>
70 #include <Geom_Line.hxx>
71 #include <Geom_Circle.hxx>
72 #include <Geom_Ellipse.hxx>
73 #include <Geom_Parabola.hxx>
74 #include <Geom_Hyperbola.hxx>
75 #include <Geom_TrimmedCurve.hxx>
76 #include <Geom_BSplineCurve.hxx>
77 #include <Geom_RectangularTrimmedSurface.hxx>
78 #include <Geom_OffsetSurface.hxx>
79 #include <Geom_Curve.hxx>
80 #include <Geom_Conic.hxx>
81
82 #include <Geom2d_TrimmedCurve.hxx>
83 #include <Geom2d_BSplineCurve.hxx>
84 #include <Geom2d_Line.hxx>
85 #include <Geom2d_Curve.hxx>
86 #include <Geom2d_Circle.hxx>
87
88 #include <Geom2dAPI_InterCurveCurve.hxx>
89 #include <Geom2dInt_GInter.hxx>
90 #include <GeomAdaptor_Curve.hxx>
91 #include <GeomAdaptor_HSurface.hxx>
92 #include <GeomAdaptor_Surface.hxx>
93 #include <GeomLib_CheckBSplineCurve.hxx>
94 #include <GeomLib_Check2dBSplineCurve.hxx>
95
96 #include <GeomInt_WLApprox.hxx>
97 #include <GeomProjLib.hxx>
98 #include <GeomAPI_ProjectPointOnSurf.hxx>
99 #include <Geom2dAdaptor_Curve.hxx>
100 #include <TopoDS.hxx>
101 #include <TopoDS_Edge.hxx>
102 #include <TopExp_Explorer.hxx>
103
104 #include <BRep_Tool.hxx>
105 #include <BRepTools.hxx>
106 #include <BRepAdaptor_Surface.hxx>
107
108 #include <IntTools_Curve.hxx>
109 #include <IntTools_Tools.hxx>
110 #include <IntTools_Tools.hxx>
111 #include <IntTools_TopolTool.hxx>
112 #include <IntTools_PntOnFace.hxx>
113 #include <IntTools_PntOn2Faces.hxx>
114 #include <IntTools_Context.hxx>
115 #include <IntSurf_ListIteratorOfListOfPntOn2S.hxx>
116
117 static
118   void RefineVector(gp_Vec2d& aV2D);
119 #ifdef DEB_DUMPWLINE
120 static
121   void DumpWLine(const Handle(IntPatch_WLine)& aWLine);
122 #endif
123 //
124 static
125   void TolR3d(const TopoDS_Face& ,
126               const TopoDS_Face& ,
127               Standard_Real& );
128 static 
129   Handle(Geom_Curve) MakeBSpline (const Handle(IntPatch_WLine)&,
130                                   const Standard_Integer,
131                                   const Standard_Integer);
132
133 static 
134   void Parameters(const Handle(GeomAdaptor_HSurface)&,
135                   const Handle(GeomAdaptor_HSurface)&,
136                   const gp_Pnt&,
137                   Standard_Real&,
138                   Standard_Real&,
139                   Standard_Real&,
140                   Standard_Real&);
141
142 static 
143   void BuildPCurves (Standard_Real f,Standard_Real l,Standard_Real& Tol,
144                      const Handle (Geom_Surface)& S,
145                      const Handle (Geom_Curve)&   C,
146                      Handle (Geom2d_Curve)& C2d);
147
148 static 
149   void CorrectSurfaceBoundaries(const TopoDS_Face&  theFace,
150                                 const Standard_Real theTolerance,
151                                 Standard_Real&      theumin,
152                                 Standard_Real&      theumax, 
153                                 Standard_Real&      thevmin, 
154                                 Standard_Real&      thevmax);
155 static
156   Standard_Boolean NotUseSurfacesForApprox
157           (const TopoDS_Face& aF1,
158            const TopoDS_Face& aF2,
159            const Handle(IntPatch_WLine)& WL,
160            const Standard_Integer ifprm,
161            const Standard_Integer ilprm);
162
163 static 
164   Handle(IntPatch_WLine) ComputePurgedWLine(const Handle(IntPatch_WLine)& theWLine);
165
166 static 
167   Handle(Geom2d_BSplineCurve) MakeBSpline2d(const Handle(IntPatch_WLine)& theWLine,
168                                             const Standard_Integer                         ideb,
169                                             const Standard_Integer                         ifin,
170                                             const Standard_Boolean                         onFirst);
171
172 static 
173   Standard_Boolean DecompositionOfWLine(const Handle(IntPatch_WLine)& theWLine,
174                                         const Handle(GeomAdaptor_HSurface)&            theSurface1, 
175                                         const Handle(GeomAdaptor_HSurface)&            theSurface2,
176                                         const TopoDS_Face&                             theFace1,
177                                         const TopoDS_Face&                             theFace2,
178                                         const IntTools_LineConstructor&                theLConstructor,
179                                         const Standard_Boolean                         theAvoidLConstructor,
180                                         IntPatch_SequenceOfLine&                       theNewLines,
181                                         Standard_Real&                                 theReachedTol3d,
182                                         const Handle(IntTools_Context)& );
183
184 static 
185   Standard_Boolean ParameterOutOfBoundary(const Standard_Real       theParameter, 
186                                           const Handle(Geom_Curve)& theCurve, 
187                                           const TopoDS_Face&        theFace1, 
188                                           const TopoDS_Face&        theFace2,
189                                           const Standard_Real       theOtherParameter,
190                                           const Standard_Boolean    bIncreasePar,
191                                           Standard_Real&            theNewParameter,
192                                           const Handle(IntTools_Context)& );
193
194 static 
195   Standard_Boolean IsCurveValid(Handle(Geom2d_Curve)& thePCurve);
196
197 static 
198   Standard_Boolean IsPointOnBoundary(const Standard_Real theParameter,
199                                      const Standard_Real theFirstBoundary,
200                                      const Standard_Real theSecondBoundary,
201                                      const Standard_Real theResolution,
202                                      Standard_Boolean&   IsOnFirstBoundary);
203 static
204   Standard_Boolean FindPoint(const gp_Pnt2d&     theFirstPoint,
205                              const gp_Pnt2d&     theLastPoint,
206                              const Standard_Real theUmin, 
207                              const Standard_Real theUmax,
208                              const Standard_Real theVmin,
209                              const Standard_Real theVmax,
210                              gp_Pnt2d&           theNewPoint);
211
212
213 static 
214   Standard_Integer ComputeTangentZones( const Handle(GeomAdaptor_HSurface)& theSurface1,
215                                        const Handle(GeomAdaptor_HSurface)&  theSurface2,
216                                        const TopoDS_Face&                   theFace1,
217                                        const TopoDS_Face&                   theFace2,
218                                        Handle(TColgp_HArray1OfPnt2d)&       theResultOnS1,
219                                        Handle(TColgp_HArray1OfPnt2d)&       theResultOnS2,
220                                        Handle(TColStd_HArray1OfReal)&       theResultRadius,
221                                        const Handle(IntTools_Context)& );
222
223 static
224   Standard_Boolean FindPoint(const gp_Pnt2d&     theFirstPoint,
225                              const gp_Pnt2d&     theLastPoint,
226                              const Standard_Real theUmin, 
227                              const Standard_Real theUmax,
228                              const Standard_Real theVmin,
229                              const Standard_Real theVmax,
230                              const gp_Pnt2d&     theTanZoneCenter,
231                              const Standard_Real theZoneRadius,
232                              Handle(GeomAdaptor_HSurface) theGASurface,
233                              gp_Pnt2d&           theNewPoint);
234
235 static
236   Standard_Boolean IsInsideTanZone(const gp_Pnt2d&     thePoint,
237                                    const gp_Pnt2d&     theTanZoneCenter,
238                                    const Standard_Real theZoneRadius,
239                                    Handle(GeomAdaptor_HSurface) theGASurface);
240
241 static
242   gp_Pnt2d AdjustByNeighbour(const gp_Pnt2d&     theaNeighbourPoint,
243                              const gp_Pnt2d&     theOriginalPoint,
244                              Handle(GeomAdaptor_HSurface) theGASurface);
245 static
246   Standard_Boolean  ApproxWithPCurves(const gp_Cylinder& theCyl, 
247                                       const gp_Sphere& theSph);
248
249 static void  PerformPlanes(const Handle(GeomAdaptor_HSurface)& theS1, 
250                            const Handle(GeomAdaptor_HSurface)& theS2, 
251                            const Standard_Real TolAng, 
252                            const Standard_Real TolTang, 
253                            const Standard_Boolean theApprox1,
254                            const Standard_Boolean theApprox2,
255                            IntTools_SequenceOfCurves& theSeqOfCurve, 
256                            Standard_Boolean& theTangentFaces);
257
258 static Standard_Boolean ClassifyLin2d(const Handle(GeomAdaptor_HSurface)& theS, 
259                                       const gp_Lin2d& theLin2d, 
260                                       const Standard_Real theTol,
261                                       Standard_Real& theP1, 
262                                       Standard_Real& theP2);
263 //
264 static
265   void ApproxParameters(const Handle(GeomAdaptor_HSurface)& aHS1,
266                         const Handle(GeomAdaptor_HSurface)& aHS2,
267                         Standard_Integer& iDegMin,
268                         Standard_Integer& iNbIter,
269                         Standard_Integer& iDegMax);
270
271 static
272   void Tolerances(const Handle(GeomAdaptor_HSurface)& aHS1,
273                   const Handle(GeomAdaptor_HSurface)& aHS2,
274                   Standard_Real& aTolTang);
275
276 static
277   Standard_Boolean SortTypes(const GeomAbs_SurfaceType aType1,
278                              const GeomAbs_SurfaceType aType2);
279 static
280   Standard_Integer IndexType(const GeomAbs_SurfaceType aType);
281
282 //
283 static
284   Standard_Real MaxSquareDistance (const Standard_Real aT,
285                                    const Handle(Geom_Curve)& aC3D,
286                                    const Handle(Geom2d_Curve)& aC2D1,
287                                    const Handle(Geom2d_Curve)& aC2D2,
288                                    const Handle(GeomAdaptor_HSurface) myHS1,
289                                    const Handle(GeomAdaptor_HSurface) myHS2,
290                                    const TopoDS_Face& aF1,
291                                    const TopoDS_Face& aF2,
292                                    const Handle(IntTools_Context)& aCtx);
293
294 static
295   Standard_Boolean CheckPCurve(const Handle(Geom2d_Curve)& aPC, 
296                                const TopoDS_Face& aFace);
297
298 //
299 static
300   Standard_Real FindMaxSquareDistance (const Standard_Real aA,
301                                        const Standard_Real aB,
302                                        const Standard_Real aEps,
303                                        const Handle(Geom_Curve)& aC3D,
304                                        const Handle(Geom2d_Curve)& aC2D1,
305                                        const Handle(Geom2d_Curve)& aC2D2,
306                                        const Handle(GeomAdaptor_HSurface)& myHS1,
307                                        const Handle(GeomAdaptor_HSurface)& myHS2,
308                                        const TopoDS_Face& aF1,
309                                        const TopoDS_Face& aF2,
310                                        const Handle(IntTools_Context)& aCtx);
311
312 //=======================================================================
313 //function : 
314 //purpose  : 
315 //=======================================================================
316 IntTools_FaceFace::IntTools_FaceFace()
317 {
318   myIsDone=Standard_False;
319   myTangentFaces=Standard_False;
320   //
321   myHS1 = new GeomAdaptor_HSurface ();
322   myHS2 = new GeomAdaptor_HSurface ();
323   myTolReached2d=0.; 
324   myTolReached3d=0.;
325   SetParameters(Standard_True, Standard_True, Standard_True, 1.e-07);
326   
327 }
328 //=======================================================================
329 //function : SetContext
330 //purpose  : 
331 //======================================================================= 
332 void IntTools_FaceFace::SetContext(const Handle(IntTools_Context)& aContext)
333 {
334   myContext=aContext;
335 }
336 //=======================================================================
337 //function : Context
338 //purpose  : 
339 //======================================================================= 
340 const Handle(IntTools_Context)& IntTools_FaceFace::Context()const
341 {
342   return myContext;
343 }
344 //=======================================================================
345 //function : Face1
346 //purpose  : 
347 //======================================================================= 
348 const TopoDS_Face& IntTools_FaceFace::Face1() const
349 {
350   return myFace1;
351 }
352 //=======================================================================
353 //function : Face2
354 //purpose  : 
355 //======================================================================= 
356 const TopoDS_Face& IntTools_FaceFace::Face2() const
357 {
358   return myFace2;
359 }
360 //=======================================================================
361 //function : TangentFaces
362 //purpose  : 
363 //======================================================================= 
364 Standard_Boolean IntTools_FaceFace::TangentFaces() const
365 {
366   return myTangentFaces;
367 }
368 //=======================================================================
369 //function : Points
370 //purpose  : 
371 //======================================================================= 
372 const IntTools_SequenceOfPntOn2Faces& IntTools_FaceFace::Points() const
373 {
374   return myPnts;
375 }
376 //=======================================================================
377 //function : IsDone
378 //purpose  : 
379 //======================================================================= 
380 Standard_Boolean IntTools_FaceFace::IsDone() const
381 {
382   return myIsDone;
383 }
384 //=======================================================================
385 //function : TolReached3d
386 //purpose  : 
387 //=======================================================================
388 Standard_Real IntTools_FaceFace::TolReached3d() const
389 {
390   return myTolReached3d;
391 }
392 //=======================================================================
393 //function : Lines
394 //purpose  : return lines of intersection
395 //=======================================================================
396 const IntTools_SequenceOfCurves& IntTools_FaceFace::Lines() const
397 {
398   StdFail_NotDone_Raise_if
399     (!myIsDone,
400      "IntTools_FaceFace::Lines() => myIntersector NOT DONE");
401   return mySeqOfCurve;
402 }
403 //=======================================================================
404 //function : TolReached2d
405 //purpose  : 
406 //=======================================================================
407 Standard_Real IntTools_FaceFace::TolReached2d() const
408 {
409   return myTolReached2d;
410 }
411 // =======================================================================
412 // function: SetParameters
413 //
414 // =======================================================================
415 void IntTools_FaceFace::SetParameters(const Standard_Boolean ToApproxC3d,
416                                       const Standard_Boolean ToApproxC2dOnS1,
417                                       const Standard_Boolean ToApproxC2dOnS2,
418                                       const Standard_Real ApproximationTolerance) 
419 {
420   myApprox = ToApproxC3d;
421   myApprox1 = ToApproxC2dOnS1;
422   myApprox2 = ToApproxC2dOnS2;
423   myTolApprox = ApproximationTolerance;
424 }
425 //=======================================================================
426 //function : SetList
427 //purpose  : 
428 //=======================================================================
429 void IntTools_FaceFace::SetList(IntSurf_ListOfPntOn2S& aListOfPnts)
430 {
431   myListOfPnts = aListOfPnts;  
432 }
433
434
435 static Standard_Boolean isTreatAnalityc(const TopoDS_Face& theF1,
436                                         const TopoDS_Face& theF2)
437 {
438   const Standard_Real Tolang = 1.e-8;
439   const Standard_Real aTolF1=BRep_Tool::Tolerance(theF1);
440   const Standard_Real aTolF2=BRep_Tool::Tolerance(theF2);
441   const Standard_Real aTolSum = aTolF1 + aTolF2;
442   Standard_Real aHigh = 0.0;
443
444   const BRepAdaptor_Surface aBAS1(theF1), aBAS2(theF2);
445   const GeomAbs_SurfaceType aType1=aBAS1.GetType();
446   const GeomAbs_SurfaceType aType2=aBAS2.GetType();
447   
448   gp_Pln aS1;
449   gp_Cylinder aS2;
450   if(aType1 == GeomAbs_Plane)
451   {
452     aS1=aBAS1.Plane();
453   }
454   else if(aType2 == GeomAbs_Plane)
455   {
456     aS1=aBAS2.Plane();
457   }
458   else
459   {
460     return Standard_True;
461   }
462
463   if(aType1 == GeomAbs_Cylinder)
464   {
465     aS2=aBAS1.Cylinder();
466     const Standard_Real VMin = aBAS1.FirstVParameter();
467     const Standard_Real VMax = aBAS1.LastVParameter();
468
469     if( Precision::IsNegativeInfinite(VMin) ||
470         Precision::IsPositiveInfinite(VMax))
471           return Standard_True;
472     else
473       aHigh = VMax - VMin;
474   }
475   else if(aType2 == GeomAbs_Cylinder)
476   {
477     aS2=aBAS2.Cylinder();
478
479     const Standard_Real VMin = aBAS2.FirstVParameter();
480     const Standard_Real VMax = aBAS2.LastVParameter();
481
482     if( Precision::IsNegativeInfinite(VMin) ||
483         Precision::IsPositiveInfinite(VMax))
484           return Standard_True;
485     else
486       aHigh = VMax - VMin;
487   }
488   else
489   {
490     return Standard_True;
491   }
492
493   IntAna_QuadQuadGeo inter;
494   inter.Perform(aS1,aS2,Tolang,aTolSum, aHigh);
495   if(inter.TypeInter() == IntAna_Ellipse)
496   {
497     const gp_Elips anEl = inter.Ellipse(1);
498     const Standard_Real aMajorR = anEl.MajorRadius();
499     const Standard_Real aMinorR = anEl.MinorRadius();
500     
501     return (aMajorR < 100000.0 * aMinorR);
502   }
503   else
504   {
505     return inter.IsDone();
506   }
507 }
508 //=======================================================================
509 //function : Perform
510 //purpose  : intersect surfaces of the faces
511 //=======================================================================
512   void IntTools_FaceFace::Perform(const TopoDS_Face& aF1,
513                                 const TopoDS_Face& aF2)
514 {
515   Standard_Boolean RestrictLine = Standard_False, hasCone = Standard_False;
516   
517   if (myContext.IsNull()) {
518     myContext=new IntTools_Context;
519   }
520
521   mySeqOfCurve.Clear();
522   myTolReached2d=0.;
523   myTolReached3d=0.;
524   myIsDone = Standard_False;
525   myNbrestr=0;//?
526
527   myFace1=aF1;
528   myFace2=aF2;
529
530   const BRepAdaptor_Surface aBAS1(myFace1, Standard_False);
531   const BRepAdaptor_Surface aBAS2(myFace2, Standard_False);
532   GeomAbs_SurfaceType aType1=aBAS1.GetType();
533   GeomAbs_SurfaceType aType2=aBAS2.GetType();
534
535   const Standard_Boolean bReverse=SortTypes(aType1, aType2);
536   if (bReverse)
537   {
538     myFace1=aF2;
539     myFace2=aF1;
540     aType1=aBAS2.GetType();
541     aType2=aBAS1.GetType();
542
543     if (myListOfPnts.Extent())
544     {
545       Standard_Real aU1,aV1,aU2,aV2;
546       IntSurf_ListIteratorOfListOfPntOn2S aItP2S;
547       //
548       aItP2S.Initialize(myListOfPnts);
549       for (; aItP2S.More(); aItP2S.Next())
550       {
551         IntSurf_PntOn2S& aP2S=aItP2S.Value();
552         aP2S.Parameters(aU1,aV1,aU2,aV2);
553         aP2S.SetValue(aU2,aV2,aU1,aV1);
554       }
555     }
556   }
557
558
559   const Handle(Geom_Surface) S1=BRep_Tool::Surface(myFace1);
560   const Handle(Geom_Surface) S2=BRep_Tool::Surface(myFace2);
561
562   const Standard_Real aTolF1=BRep_Tool::Tolerance(myFace1);
563   const Standard_Real aTolF2=BRep_Tool::Tolerance(myFace2);
564
565   Standard_Real TolArc = aTolF1 + aTolF2;
566   Standard_Real TolTang = TolArc;
567
568   const Standard_Boolean isFace1Quad = (aType1 == GeomAbs_Cylinder ||
569                                         aType1 == GeomAbs_Cone ||
570                                         aType1 == GeomAbs_Torus);
571
572   const Standard_Boolean isFace2Quad = (aType2 == GeomAbs_Cylinder ||
573                                         aType2 == GeomAbs_Cone ||
574                                         aType2 == GeomAbs_Torus);
575
576   if(aType1==GeomAbs_Plane && aType2==GeomAbs_Plane)  {
577     Standard_Real umin, umax, vmin, vmax;
578     Standard_Real dU, dV;
579     //
580     BRepTools::UVBounds(myFace1, umin, umax, vmin, vmax);
581     dU=0.1*(umax-umin);
582     dV=0.1*(vmax-vmin);
583     umin=umin-dU;
584     umax=umax+dU;
585     vmin=vmin-dV;
586     vmax=vmax+dV;
587     myHS1->ChangeSurface().Load(S1, umin, umax, vmin, vmax);
588     //
589     BRepTools::UVBounds(myFace2, umin, umax, vmin, vmax);
590     dU=0.1*(umax-umin);
591     dV=0.1*(vmax-vmin);
592     umin=umin-dU;
593     umax=umax+dU;
594     vmin=vmin-dV;
595     vmax=vmax+dV;
596     myHS2->ChangeSurface().Load(S2, umin, umax, vmin, vmax);
597     //
598     Standard_Real TolAng = 1.e-8;
599     //
600     PerformPlanes(myHS1, myHS2, TolAng, TolTang, myApprox1, myApprox2, 
601                   mySeqOfCurve, myTangentFaces);
602     //
603     myIsDone = Standard_True;
604     
605     if(!myTangentFaces) {
606       const Standard_Integer NbLinPP = mySeqOfCurve.Length();
607       if(NbLinPP) {
608         Standard_Real aTolFMax;
609         myTolReached3d = 1.e-7;
610         aTolFMax=Max(aTolF1, aTolF2);
611         if (aTolFMax>myTolReached3d) {
612           myTolReached3d=aTolFMax;
613         }
614         //
615         myTolReached2d = myTolReached3d;
616
617         if (bReverse) {
618           Handle(Geom2d_Curve) aC2D1, aC2D2;
619           const Standard_Integer aNbLin = mySeqOfCurve.Length();
620           for (Standard_Integer i = 1; i <= aNbLin; ++i) {
621             IntTools_Curve& aIC=mySeqOfCurve(i);
622             aC2D1=aIC.FirstCurve2d();
623             aC2D2=aIC.SecondCurve2d();
624             aIC.SetFirstCurve2d(aC2D2);
625             aIC.SetSecondCurve2d(aC2D1);
626           }
627         }
628       }
629     }
630     return;
631   }//if(aType1==GeomAbs_Plane && aType2==GeomAbs_Plane){
632
633   if ((aType1==GeomAbs_Plane) && isFace2Quad)
634   {
635     Standard_Real dU, dV;
636
637     // F1
638     Standard_Real umin, umax, vmin, vmax;
639     BRepTools::UVBounds(myFace1, umin, umax, vmin, vmax);
640
641     dU=0.1*(umax-umin);
642     dV=0.1*(vmax-vmin);
643     umin=umin-dU;
644     umax=umax+dU;
645     vmin=vmin-dV;
646     vmax=vmax+dV;
647     myHS1->ChangeSurface().Load(S1, umin, umax, vmin, vmax);
648     // F2
649     BRepTools::UVBounds(myFace2, umin, umax, vmin, vmax);
650     CorrectSurfaceBoundaries(myFace2, (aTolF1 + aTolF2) * 2., umin, umax, vmin, vmax);
651     myHS2->ChangeSurface().Load(S2, umin, umax, vmin, vmax);
652     //
653     if( aType2==GeomAbs_Cone ) { 
654       TolArc = 0.0001; 
655       hasCone = Standard_True; 
656     }
657   }
658   else if ((aType2==GeomAbs_Plane) && isFace1Quad)
659   {
660     Standard_Real dU, dV;
661
662     //F1
663     Standard_Real umin, umax, vmin, vmax;
664     BRepTools::UVBounds(myFace1, umin, umax, vmin, vmax);
665     CorrectSurfaceBoundaries(myFace1, (aTolF1 + aTolF2) * 2., umin, umax, vmin, vmax);
666     myHS1->ChangeSurface().Load(S1, umin, umax, vmin, vmax);
667     // F2
668     BRepTools::UVBounds(myFace2, umin, umax, vmin, vmax);
669     dU=0.1*(umax-umin);
670     dV=0.1*(vmax-vmin);
671     umin=umin-dU;
672     umax=umax+dU;
673     vmin=vmin-dV;
674     vmax=vmax+dV;
675     myHS2->ChangeSurface().Load(S2, umin, umax, vmin, vmax);
676     //
677     if( aType1==GeomAbs_Cone ) {
678       TolArc = 0.0001; 
679       hasCone = Standard_True; 
680     }
681   }
682   else
683   {
684     Standard_Real umin, umax, vmin, vmax;
685     BRepTools::UVBounds(myFace1, umin, umax, vmin, vmax);
686     CorrectSurfaceBoundaries(myFace1, (aTolF1 + aTolF2) * 2., umin, umax, vmin, vmax);
687     myHS1->ChangeSurface().Load(S1, umin, umax, vmin, vmax);
688     BRepTools::UVBounds(myFace2, umin, umax, vmin, vmax);
689     CorrectSurfaceBoundaries(myFace2, (aTolF1 + aTolF2) * 2., umin, umax, vmin, vmax);
690     myHS2->ChangeSurface().Load(S2, umin, umax, vmin, vmax);
691   }
692
693   const Handle(IntTools_TopolTool) dom1 = new IntTools_TopolTool(myHS1);
694   const Handle(IntTools_TopolTool) dom2 = new IntTools_TopolTool(myHS2);
695
696   myLConstruct.Load(dom1, dom2, myHS1, myHS2);
697   
698
699   Tolerances(myHS1, myHS2, TolTang);
700
701   {
702     const Standard_Real UVMaxStep = 0.001;
703     const Standard_Real Deflection = (hasCone) ? 0.085 : 0.1;
704   myIntersector.SetTolerances(TolArc, TolTang, UVMaxStep, Deflection); 
705   }
706   
707   if((myHS1->IsUClosed() && !myHS1->IsUPeriodic()) || 
708      (myHS1->IsVClosed() && !myHS1->IsVPeriodic()) ||
709      (myHS2->IsUClosed() && !myHS2->IsUPeriodic()) || 
710      (myHS2->IsVClosed() && !myHS2->IsVPeriodic()))
711   {
712     RestrictLine = Standard_True;
713   }
714   //
715   if((aType1 != GeomAbs_BSplineSurface) &&
716       (aType1 != GeomAbs_BezierSurface)  &&
717      (aType1 != GeomAbs_OtherSurface)  &&
718      (aType2 != GeomAbs_BSplineSurface) &&
719       (aType2 != GeomAbs_BezierSurface)  &&
720      (aType2 != GeomAbs_OtherSurface))
721   {
722     RestrictLine = Standard_True;
723
724     if ((aType1 == GeomAbs_Torus) ||
725         (aType2 == GeomAbs_Torus))
726     {
727       myListOfPnts.Clear();
728     }
729   }
730
731   //
732   if(!RestrictLine)
733   {
734     TopExp_Explorer aExp;
735     for(Standard_Integer i = 0; (!RestrictLine) && (i < 2); i++)
736     {
737       const TopoDS_Face& aF=(!i) ? myFace1 : myFace2;
738       aExp.Init(aF, TopAbs_EDGE);
739       for(; aExp.More(); aExp.Next())
740       {
741         const TopoDS_Edge& aE=TopoDS::Edge(aExp.Current());
742
743         if(BRep_Tool::Degenerated(aE))
744         {
745           RestrictLine = Standard_True;
746           break;
747         }
748       }
749     }
750   }
751
752   const Standard_Boolean isGeomInt = isTreatAnalityc(aF1, aF2);
753   myIntersector.Perform(myHS1, dom1, myHS2, dom2, TolArc, TolTang, 
754                                   myListOfPnts, RestrictLine, isGeomInt);
755
756   myIsDone = myIntersector.IsDone();
757
758   if (myIsDone)
759   {
760     myTangentFaces=myIntersector.TangentFaces();
761     if (myTangentFaces) {
762       return;
763     }
764     //
765     if(RestrictLine) {
766       myListOfPnts.Clear(); // to use LineConstructor
767     }
768     //
769     const Standard_Integer aNbLin = myIntersector.NbLines();
770     for (Standard_Integer i=1; i <= aNbLin; ++i) {
771       MakeCurve(i, dom1, dom2);
772     }
773     //
774     ComputeTolReached3d();
775     //
776     if (bReverse) {
777       Handle(Geom2d_Curve) aC2D1, aC2D2;
778       //
779       const Standard_Integer aNbLin=mySeqOfCurve.Length();
780       for (Standard_Integer i=1; i<=aNbLin; ++i)
781       {
782         IntTools_Curve& aIC=mySeqOfCurve(i);
783         aC2D1=aIC.FirstCurve2d();
784         aC2D2=aIC.SecondCurve2d();
785         aIC.SetFirstCurve2d(aC2D2);
786         aIC.SetSecondCurve2d(aC2D1);
787       }
788     }
789
790     // Points
791     Standard_Real U1,V1,U2,V2;
792     IntTools_PntOnFace aPntOnF1, aPntOnF2;
793     IntTools_PntOn2Faces aPntOn2Faces;
794     //
795     const Standard_Integer aNbPnts = myIntersector.NbPnts();
796     for (Standard_Integer i=1; i <= aNbPnts; ++i)
797     {
798       const IntSurf_PntOn2S& aISPnt=myIntersector.Point(i).PntOn2S();
799       const gp_Pnt& aPnt=aISPnt.Value();
800       aISPnt.Parameters(U1,V1,U2,V2);
801       aPntOnF1.Init(myFace1, aPnt, U1, V1);
802       aPntOnF2.Init(myFace2, aPnt, U2, V2);
803       //
804       if (!bReverse)
805       {
806         aPntOn2Faces.SetP1(aPntOnF1);
807         aPntOn2Faces.SetP2(aPntOnF2);
808       }
809       else
810       {
811         aPntOn2Faces.SetP2(aPntOnF1);
812         aPntOn2Faces.SetP1(aPntOnF2);
813       }
814
815       myPnts.Append(aPntOn2Faces);
816     }
817   }
818 }
819
820 //=======================================================================
821 //function :ComputeTolReached3d 
822 //purpose  : 
823 //=======================================================================
824   void IntTools_FaceFace::ComputeTolReached3d()
825 {
826   Standard_Boolean bCase1;
827   Standard_Integer aNbLin, i;
828   GeomAbs_SurfaceType aType1, aType2;
829   //
830   aNbLin=myIntersector.NbLines();
831   if (!aNbLin) {
832     return;
833   }
834   //
835   aType1=myHS1->Surface().GetType();
836   aType2=myHS2->Surface().GetType();
837   //
838   bCase1=((aType1==GeomAbs_Plane && aType2==GeomAbs_SurfaceOfExtrusion) ||
839           (aType2==GeomAbs_Plane && aType1==GeomAbs_SurfaceOfExtrusion));
840   //
841   if (aType1==GeomAbs_Cylinder && aType2==GeomAbs_Cylinder) {
842     if (aNbLin==2){ 
843       Handle(IntPatch_Line) aIL1, aIL2;
844       IntPatch_IType aTL1, aTL2;
845       //
846       aIL1=myIntersector.Line(1);
847       aIL2=myIntersector.Line(2);
848       aTL1=aIL1->ArcType();
849       aTL2=aIL2->ArcType();
850       if (aTL1==IntPatch_Lin && aTL2==IntPatch_Lin) {
851         Standard_Real aD, aDTresh, dTol;
852         gp_Lin aL1, aL2;
853         //
854         dTol=1.e-8;
855         aDTresh=1.5e-6;
856         //
857         aL1=Handle(IntPatch_GLine)::DownCast(aIL1)->Line();
858         aL2=Handle(IntPatch_GLine)::DownCast(aIL2)->Line();
859         aD=aL1.Distance(aL2);
860         aD=0.5*aD;
861         if (aD<aDTresh) {
862           myTolReached3d=aD+dTol;
863         }
864         return;
865       }
866     }
867     //ZZ
868     if (aNbLin) {// Check the distances
869       Standard_Integer  aNbP, j ;
870       Standard_Real aT1, aT2, dT, aD2, aD2Max, aEps, aT11, aT12;
871       //
872       aD2Max=0.;
873       aNbP=10;
874       aNbLin=mySeqOfCurve.Length();
875       //
876       for (i=1; i<=aNbLin; ++i) {
877         const IntTools_Curve& aIC=mySeqOfCurve(i);
878         const Handle(Geom_Curve)& aC3D=aIC.Curve();
879         const Handle(Geom2d_Curve)& aC2D1=aIC.FirstCurve2d();
880         const Handle(Geom2d_Curve)& aC2D2=aIC.SecondCurve2d();
881         //
882         if (aC3D.IsNull()) {
883           continue;
884         }
885         const Handle(Geom_BSplineCurve)& aBC=
886           Handle(Geom_BSplineCurve)::DownCast(aC3D);
887         if (aBC.IsNull()) {
888           continue;
889         }
890         //
891         aT1=aBC->FirstParameter();
892         aT2=aBC->LastParameter();
893         //
894         aEps=0.01*(aT2-aT1);
895         dT=(aT2-aT1)/aNbP;
896         for (j=1; j<aNbP; ++j) {
897           aT11=aT1+j*dT;
898           aT12=aT11+dT;
899           aD2=FindMaxSquareDistance(aT11, aT12, aEps, aC3D, aC2D1, aC2D2,
900                                     myHS1, myHS2, myFace1, myFace2, myContext);
901           if (aD2>aD2Max) {
902             aD2Max=aD2;
903           }
904         }
905       }//for (i=1; i<=aNbLin; ++i) {
906       //
907       myTolReached3d=sqrt(aD2Max);
908     }// if (aNbLin) 
909   }// if (aType1==GeomAbs_Cylinder && aType2==GeomAbs_Cylinder) {
910   //
911   //904/G3 f
912   else if (aType1==GeomAbs_Plane && aType2==GeomAbs_Plane) {
913     Standard_Real aTolF1, aTolF2, aTolFMax, aTolTresh;
914     //
915     aTolTresh=1.e-7;
916     //
917     aTolF1 = BRep_Tool::Tolerance(myFace1);
918     aTolF2 = BRep_Tool::Tolerance(myFace2);
919     aTolFMax=Max(aTolF1, aTolF2);
920     //
921     if (aTolFMax>aTolTresh) {
922       myTolReached3d=aTolFMax;
923     }
924   }//if (aType1==GeomAbs_Plane && aType2==GeomAbs_Plane) {
925   //t
926   //IFV Bug OCC20297 
927   else if((aType1 == GeomAbs_Cylinder && aType2 == GeomAbs_Plane) ||
928           (aType2 == GeomAbs_Cylinder && aType1 == GeomAbs_Plane)) {
929     if(aNbLin == 1) {
930       const Handle(IntPatch_Line)& aIL1 = myIntersector.Line(1);
931       if(aIL1->ArcType() == IntPatch_Circle) {
932         gp_Circ aCir = Handle(IntPatch_GLine)::DownCast(aIL1)->Circle();
933         gp_XYZ aCirDir = aCir.Axis().Direction().XYZ();
934         gp_XYZ aPlDir;
935         gp_Pln aPln;
936         if(aType1 == GeomAbs_Plane) {
937           aPln = myHS1->Surface().Plane();
938         }
939         else {
940           aPln = myHS2->Surface().Plane();
941         }
942         aPlDir = aPln.Axis().Direction().XYZ();
943         Standard_Real cs = aCirDir*aPlDir;
944         if(cs < 0.) aPlDir.Reverse();
945         Standard_Real eps = 1.e-14;
946         if(!aPlDir.IsEqual(aCirDir, eps)) {
947           Standard_Integer aNbP = 11;
948           Standard_Real dt = 2.*M_PI / (aNbP - 1), t;
949           for(t = 0.; t < 2.*M_PI; t += dt) {
950             Standard_Real d = aPln.Distance(ElCLib::Value(t, aCir)); 
951             if(myTolReached3d < d) myTolReached3d = d;
952           }
953           myTolReached3d *= 1.1;
954         }
955       } //aIL1->ArcType() == IntPatch_Circle
956     } //aNbLin == 1
957   } // aType1 == GeomAbs_Cylinder && aType2 == GeomAbs_Plane) 
958   //End IFV Bug OCC20297
959   //
960   else if ((aType1==GeomAbs_Plane && aType2==GeomAbs_Torus) ||
961            (aType2==GeomAbs_Plane && aType1==GeomAbs_Torus)) {
962     aNbLin=mySeqOfCurve.Length();
963     if (aNbLin!=1) {
964       return;
965     }
966     //
967     Standard_Integer aNbP;
968     Standard_Real aT, aT1, aT2, dT, aUT, aVT, aUP, aVP;
969     Standard_Real aDP, aDT, aDmax;
970     gp_Pln aPln;
971     gp_Torus aTorus;
972     gp_Pnt aP, aPP, aPT;
973     //
974     const IntTools_Curve& aIC=mySeqOfCurve(1);
975     const Handle(Geom_Curve)& aC3D=aIC.Curve();
976     const Handle(Geom_BSplineCurve)& aBS=
977       Handle(Geom_BSplineCurve)::DownCast(aC3D);
978     if (aBS.IsNull()) {
979       return;
980     }
981     //
982     aT1=aBS->FirstParameter();
983     aT2=aBS->LastParameter();
984     //
985     aPln  =(aType1==GeomAbs_Plane) ? myHS1->Plane() : myHS2->Plane();
986     aTorus=(aType1==GeomAbs_Plane) ? myHS2->Torus() : myHS1->Torus();
987     //
988     aDmax=-1.;
989     aNbP=11;
990     dT=(aT2-aT1)/(aNbP-1);
991     for (i=0; i<aNbP; ++i) {
992       aT=aT1+i*dT;
993       if (i==aNbP-1) {
994         aT=aT2;
995       }
996       //
997       aC3D->D0(aT, aP);
998       //
999       ElSLib::Parameters(aPln, aP, aUP, aVP);
1000       aPP=ElSLib::Value(aUP, aVP, aPln);
1001       aDP=aP.SquareDistance(aPP);
1002       if (aDP>aDmax) {
1003         aDmax=aDP;
1004       }
1005       //
1006       ElSLib::Parameters(aTorus, aP, aUT, aVT);
1007       aPT=ElSLib::Value(aUT, aVT, aTorus);
1008       aDT=aP.SquareDistance(aPT);
1009       if (aDT>aDmax) {
1010         aDmax=aDT;
1011       }
1012     }
1013     //
1014     if (aDmax > myTolReached3d*myTolReached3d) {
1015       myTolReached3d=sqrt(aDmax);
1016       myTolReached3d=1.1*myTolReached3d;
1017     }
1018   }// if ((aType1==GeomAbs_Plane && aType2==GeomAbs_Torus) ||
1019   //
1020   else if ((aType1==GeomAbs_SurfaceOfRevolution && aType2==GeomAbs_Cylinder) ||
1021            (aType2==GeomAbs_SurfaceOfRevolution && aType1==GeomAbs_Cylinder)) {
1022     Standard_Integer j, aNbP;
1023     Standard_Real aT, aT1, aT2, dT, aD2max, aD2;
1024     //
1025     aNbLin=mySeqOfCurve.Length();
1026     aD2max=0.;
1027     aNbP=11;
1028     //
1029     for (i=1; i<=aNbLin; ++i) {
1030       const IntTools_Curve& aIC=mySeqOfCurve(i);
1031       const Handle(Geom_Curve)& aC3D=aIC.Curve();
1032       const Handle(Geom2d_Curve)& aC2D1=aIC.FirstCurve2d();
1033       const Handle(Geom2d_Curve)& aC2D2=aIC.SecondCurve2d();
1034       //
1035       if (aC3D.IsNull()) {
1036         continue;
1037       }
1038       const Handle(Geom_BSplineCurve)& aBC=
1039         Handle(Geom_BSplineCurve)::DownCast(aC3D);
1040       if (aBC.IsNull()) {
1041         return;
1042       }
1043       //
1044       aT1=aBC->FirstParameter();
1045       aT2=aBC->LastParameter();
1046       //
1047       dT=(aT2-aT1)/(aNbP-1);
1048       for (j=0; j<aNbP; ++j) {
1049         aT=aT1+j*dT;
1050         if (j==aNbP-1) {
1051           aT=aT2;
1052         }
1053         //
1054         aD2=MaxSquareDistance(aT, aC3D, aC2D1, aC2D2,
1055                               myHS1, myHS2, myFace1, myFace2, myContext);
1056         if (aD2>aD2max) {
1057           aD2max=aD2;
1058         }
1059       }//for (j=0; j<aNbP; ++j) {
1060      
1061     }//for (i=1; i<=aNbLin; ++i) {
1062     //
1063     aD2=myTolReached3d*myTolReached3d;
1064     if (aD2max > aD2) {
1065       myTolReached3d=sqrt(aD2max);
1066     }
1067   }//if((aType1==GeomAbs_SurfaceOfRevolution ...
1068   else if ((aType1==GeomAbs_Plane && aType2==GeomAbs_Sphere) ||
1069            (aType2==GeomAbs_Plane && aType1==GeomAbs_Sphere)) {
1070     Standard_Integer  j, aNbP;
1071     Standard_Real aT1, aT2, dT, aD2max, aD2, aEps, aT11, aT12;
1072     //
1073     aNbLin=mySeqOfCurve.Length();
1074     aD2max=0.;
1075     aNbP=10;
1076     //
1077     for (i=1; i<=aNbLin; ++i) {
1078       const IntTools_Curve& aIC=mySeqOfCurve(i);
1079       const Handle(Geom_Curve)& aC3D=aIC.Curve();
1080       const Handle(Geom2d_Curve)& aC2D1=aIC.FirstCurve2d();
1081       const Handle(Geom2d_Curve)& aC2D2=aIC.SecondCurve2d();
1082       //
1083       const Handle(Geom2d_BSplineCurve)& aBC2D1=
1084         Handle(Geom2d_BSplineCurve)::DownCast(aC2D1);
1085       const Handle(Geom2d_BSplineCurve)& aBC2D2=
1086         Handle(Geom2d_BSplineCurve)::DownCast(aC2D2);
1087       //
1088       if (aBC2D1.IsNull() && aBC2D2.IsNull()) {
1089         return;
1090       }
1091       //
1092       if (!aBC2D1.IsNull()) {
1093         aT1=aBC2D1->FirstParameter();
1094         aT2=aBC2D1->LastParameter();
1095       }
1096       else {
1097         aT1=aBC2D2->FirstParameter();
1098         aT2=aBC2D2->LastParameter();
1099       }
1100       //
1101       aEps=0.01*(aT2-aT1);
1102       dT=(aT2-aT1)/aNbP;
1103       for (j=0; j<aNbP; ++j) {
1104         aT11=aT1+j*dT;
1105         aT12=aT11+dT;
1106         if (j==aNbP-1) {
1107           aT12=aT2;
1108         }
1109         //
1110         aD2=FindMaxSquareDistance(aT11, aT12, aEps, aC3D, aC2D1, aC2D2,
1111                                   myHS1, myHS2, myFace1, myFace2, myContext);
1112         if (aD2>aD2max) {
1113           aD2max=aD2;
1114         }
1115       }//for (j=0; j<aNbP; ++j) {
1116      
1117     }//for (i=1; i<=aNbLin; ++i) {
1118     //
1119     aD2=myTolReached3d*myTolReached3d;
1120     if (aD2max > aD2) {
1121       myTolReached3d=sqrt(aD2max);
1122     }
1123   }//else if ((aType1==GeomAbs_Plane && aType2==GeomAbs_Sphere) ...
1124   else if (!myApprox || bCase1) {
1125   //else if (!myApprox) {
1126     Standard_Integer aNbP, j;
1127     Standard_Real aT1, aT2, dT, aD2, aD2Max, aEps, aT11, aT12;
1128     //
1129     aD2Max=0.;
1130     aNbLin=mySeqOfCurve.Length();
1131     //
1132     for (i=1; i<=aNbLin; ++i) {
1133       const IntTools_Curve& aIC=mySeqOfCurve(i);
1134       const Handle(Geom_Curve)& aC3D=aIC.Curve();
1135       const Handle(Geom2d_Curve)& aC2D1=aIC.FirstCurve2d();
1136       const Handle(Geom2d_Curve)& aC2D2=aIC.SecondCurve2d();
1137       //
1138       if (aC3D.IsNull()) {
1139         continue;
1140 }
1141       const Handle(Geom_BSplineCurve)& aBC=
1142         Handle(Geom_BSplineCurve)::DownCast(aC3D);
1143       if (aBC.IsNull()) {
1144         continue;
1145       }
1146       //
1147       aT1=aBC->FirstParameter();
1148       aT2=aBC->LastParameter();
1149       //
1150       aEps=0.0001*(aT2-aT1);
1151       aNbP=11;
1152       dT=(aT2-aT1)/aNbP;
1153       for (j=1; j<aNbP-1; ++j) {
1154         aT11=aT1+j*dT;
1155         aT12=aT11+dT;
1156         aD2=FindMaxSquareDistance(aT11, aT12, aEps, aC3D, aC2D1, aC2D2,
1157                                   myHS1, myHS2, myFace1, myFace2, myContext);
1158         if (aD2>aD2Max) {
1159           aD2Max=aD2;
1160         }
1161       }
1162     }//for (i=1; i<=aNbLin; ++i) {
1163     myTolReached3d=sqrt(aD2Max);
1164   }
1165 }
1166 //=======================================================================
1167 //function : MakeCurve
1168 //purpose  : 
1169 //=======================================================================
1170   void IntTools_FaceFace::MakeCurve(const Standard_Integer Index,
1171                                     const Handle(Adaptor3d_TopolTool)& dom1,
1172                                     const Handle(Adaptor3d_TopolTool)& dom2) 
1173 {
1174   Standard_Boolean bDone, rejectSurface, reApprox, bAvoidLineConstructor;
1175   Standard_Boolean ok, bPCurvesOk;
1176   Standard_Integer i, j, aNbParts;
1177   Standard_Real fprm, lprm;
1178   Standard_Real Tolpc;
1179   Handle(IntPatch_Line) L;
1180   IntPatch_IType typl;
1181   Handle(Geom_Curve) newc;
1182   //
1183   const Standard_Real TOLCHECK   =0.0000001;
1184   const Standard_Real TOLANGCHECK=0.1;
1185   //
1186   rejectSurface = Standard_False;
1187   reApprox = Standard_False;
1188   //
1189   bPCurvesOk = Standard_True;
1190  
1191  reapprox:;
1192   
1193   Tolpc = myTolApprox;
1194   bAvoidLineConstructor = Standard_False;
1195   L = myIntersector.Line(Index);
1196   typl = L->ArcType();
1197   //
1198   if(typl==IntPatch_Walking) {
1199     Handle(IntPatch_Line) anewL;
1200     //
1201     const Handle(IntPatch_WLine)& aWLine=
1202       Handle(IntPatch_WLine)::DownCast(L);
1203     //DumpWLine(aWLine);
1204
1205     anewL = ComputePurgedWLine(aWLine);
1206     if(anewL.IsNull()) {
1207       return;
1208     }
1209     L = anewL;
1210     
1211     //const Handle(IntPatch_WLine)& aWLineX = Handle(IntPatch_WLine)::DownCast(L);
1212     //DumpWLine(aWLineX);
1213
1214     //
1215     if(!myListOfPnts.IsEmpty()) {
1216       bAvoidLineConstructor = Standard_True;
1217     }
1218
1219     Standard_Integer nbp = aWLine->NbPnts();
1220     const IntSurf_PntOn2S& p1 = aWLine->Point(1);
1221     const IntSurf_PntOn2S& p2 = aWLine->Point(nbp);
1222
1223     const gp_Pnt& P1 = p1.Value();
1224     const gp_Pnt& P2 = p2.Value();
1225
1226     if(P1.SquareDistance(P2) < 1.e-14) {
1227       bAvoidLineConstructor = Standard_False;
1228     }
1229   }
1230   //
1231   // Line Constructor
1232   if(!bAvoidLineConstructor) {
1233     myLConstruct.Perform(L);
1234     //
1235     bDone=myLConstruct.IsDone();
1236     aNbParts=myLConstruct.NbParts();
1237     if (!bDone|| !aNbParts) {
1238       return;
1239     }
1240   }
1241   // Do the Curve
1242   
1243   
1244   typl=L->ArcType();
1245   switch (typl) {
1246   //########################################  
1247   // Line, Parabola, Hyperbola
1248   //########################################  
1249   case IntPatch_Lin:
1250   case IntPatch_Parabola: 
1251   case IntPatch_Hyperbola: {
1252     if (typl == IntPatch_Lin) {
1253       newc = 
1254         new Geom_Line (Handle(IntPatch_GLine)::DownCast(L)->Line());
1255     }
1256
1257     else if (typl == IntPatch_Parabola) {
1258       newc = 
1259         new Geom_Parabola(Handle(IntPatch_GLine)::DownCast(L)->Parabola());
1260     }
1261     
1262     else if (typl == IntPatch_Hyperbola) {
1263       newc = 
1264         new Geom_Hyperbola (Handle(IntPatch_GLine)::DownCast(L)->Hyperbola());
1265     }
1266     //
1267     // myTolReached3d
1268     if (typl == IntPatch_Lin) {
1269       TolR3d (myFace1, myFace2, myTolReached3d);
1270     }
1271     //
1272     aNbParts=myLConstruct.NbParts();
1273     for (i=1; i<=aNbParts; i++) {
1274       myLConstruct.Part(i, fprm, lprm);
1275       
1276       if (!Precision::IsNegativeInfinite(fprm) && 
1277           !Precision::IsPositiveInfinite(lprm)) {
1278         //
1279         IntTools_Curve aCurve;
1280         //
1281         Handle(Geom_TrimmedCurve) aCT3D=new Geom_TrimmedCurve(newc, fprm, lprm);
1282         aCurve.SetCurve(aCT3D);
1283         if (typl == IntPatch_Parabola) {
1284           Standard_Real aTolF1, aTolF2, aTolBase;
1285           
1286           aTolF1 = BRep_Tool::Tolerance(myFace1);
1287           aTolF2 = BRep_Tool::Tolerance(myFace2);
1288           aTolBase=aTolF1+aTolF2;
1289           myTolReached3d=IntTools_Tools::CurveTolerance(aCT3D, aTolBase);
1290         }
1291         //
1292         aCurve.SetCurve(new Geom_TrimmedCurve(newc, fprm, lprm));
1293         if(myApprox1) { 
1294           Handle (Geom2d_Curve) C2d;
1295           BuildPCurves(fprm, lprm, Tolpc, myHS1->ChangeSurface().Surface(), newc, C2d);
1296           if(Tolpc>myTolReached2d || myTolReached2d==0.) { 
1297             myTolReached2d=Tolpc;
1298           }
1299             //            
1300             aCurve.SetFirstCurve2d(new Geom2d_TrimmedCurve(C2d,fprm,lprm));
1301           }
1302           else { 
1303             Handle(Geom2d_BSplineCurve) H1;
1304             //
1305             aCurve.SetFirstCurve2d(H1);
1306           }
1307         
1308         if(myApprox2) { 
1309           Handle (Geom2d_Curve) C2d;
1310           BuildPCurves(fprm,lprm,Tolpc,myHS2->ChangeSurface().Surface(),newc,C2d);
1311           if(Tolpc>myTolReached2d || myTolReached2d==0.) { 
1312             myTolReached2d=Tolpc;
1313           }
1314           //
1315           aCurve.SetSecondCurve2d(new Geom2d_TrimmedCurve(C2d,fprm,lprm));
1316           }
1317         else { 
1318           Handle(Geom2d_BSplineCurve) H1;
1319           //
1320           aCurve.SetSecondCurve2d(H1);
1321         }
1322         mySeqOfCurve.Append(aCurve);
1323       } // end of if (!Precision::IsNegativeInfinite(fprm) &&  !Precision::IsPositiveInfinite(lprm))
1324       else {
1325         //  on regarde si on garde
1326         //
1327         Standard_Boolean bFNIt, bLPIt;
1328         Standard_Real aTestPrm, dT=100.;
1329
1330         bFNIt=Precision::IsNegativeInfinite(fprm);
1331         bLPIt=Precision::IsPositiveInfinite(lprm);
1332         
1333         aTestPrm=0.;
1334         
1335         if (bFNIt && !bLPIt) {
1336           aTestPrm=lprm-dT;
1337         }
1338         else if (!bFNIt && bLPIt) {
1339           aTestPrm=fprm+dT;
1340         }
1341         
1342         gp_Pnt ptref(newc->Value(aTestPrm));
1343         //
1344         GeomAbs_SurfaceType typS1 = myHS1->GetType();
1345         GeomAbs_SurfaceType typS2 = myHS2->GetType();
1346         if( typS1 == GeomAbs_SurfaceOfExtrusion ||
1347             typS1 == GeomAbs_OffsetSurface ||
1348             typS1 == GeomAbs_SurfaceOfRevolution ||
1349             typS2 == GeomAbs_SurfaceOfExtrusion ||
1350             typS2 == GeomAbs_OffsetSurface ||
1351             typS2 == GeomAbs_SurfaceOfRevolution) 
1352         {
1353           Handle(Geom2d_BSplineCurve) H1;
1354           mySeqOfCurve.Append(IntTools_Curve(newc, H1, H1));
1355           continue;
1356         }
1357
1358         Standard_Real u1, v1, u2, v2, Tol;
1359         
1360         Tol = Precision::Confusion();
1361         Parameters(myHS1, myHS2, ptref,  u1, v1, u2, v2);
1362         ok = (dom1->Classify(gp_Pnt2d(u1, v1), Tol) != TopAbs_OUT);
1363         if(ok) { 
1364           ok = (dom2->Classify(gp_Pnt2d(u2,v2),Tol) != TopAbs_OUT); 
1365         }
1366         if (ok) {
1367           Handle(Geom2d_BSplineCurve) H1;
1368           mySeqOfCurve.Append(IntTools_Curve(newc, H1, H1));
1369         }
1370       }
1371     }// end of for (i=1; i<=myLConstruct.NbParts(); i++)
1372   }// case IntPatch_Lin:  case IntPatch_Parabola:  case IntPatch_Hyperbola:
1373     break;
1374
1375   //########################################  
1376   // Circle and Ellipse
1377   //########################################  
1378   case IntPatch_Circle: 
1379   case IntPatch_Ellipse: {
1380
1381     if (typl == IntPatch_Circle) {
1382       newc = new Geom_Circle
1383         (Handle(IntPatch_GLine)::DownCast(L)->Circle());
1384     }
1385     else { //IntPatch_Ellipse
1386       newc = new Geom_Ellipse
1387         (Handle(IntPatch_GLine)::DownCast(L)->Ellipse());
1388     }
1389     //
1390     // myTolReached3d
1391     TolR3d (myFace1, myFace2, myTolReached3d);
1392     //
1393     aNbParts=myLConstruct.NbParts();
1394     //
1395     Standard_Real aPeriod, aNul;
1396     TColStd_SequenceOfReal aSeqFprm,  aSeqLprm;
1397     
1398     aNul=0.;
1399     aPeriod=M_PI+M_PI;
1400
1401     for (i=1; i<=aNbParts; i++) {
1402       myLConstruct.Part(i, fprm, lprm);
1403
1404       if (fprm < aNul && lprm > aNul) {
1405         // interval that goes through 0. is divided on two intervals;
1406         while (fprm<aNul || fprm>aPeriod) fprm=fprm+aPeriod;
1407         while (lprm<aNul || lprm>aPeriod) lprm=lprm+aPeriod;
1408         //
1409         if((aPeriod - fprm) > Tolpc) {
1410           aSeqFprm.Append(fprm);
1411           aSeqLprm.Append(aPeriod);
1412         }
1413         else {
1414           gp_Pnt P1 = newc->Value(fprm);
1415           gp_Pnt P2 = newc->Value(aPeriod);
1416           Standard_Real aTolDist = BRep_Tool::Tolerance(myFace1) + BRep_Tool::Tolerance(myFace2);
1417           aTolDist = (myTolReached3d > aTolDist) ? myTolReached3d : aTolDist;
1418
1419           if(P1.Distance(P2) > aTolDist) {
1420             Standard_Real anewpar = fprm;
1421
1422             if(ParameterOutOfBoundary(fprm, newc, myFace1, myFace2, 
1423                                       lprm, Standard_False, anewpar, myContext)) {
1424               fprm = anewpar;
1425             }
1426             aSeqFprm.Append(fprm);
1427             aSeqLprm.Append(aPeriod);
1428           }
1429         }
1430
1431         //
1432         if((lprm - aNul) > Tolpc) {
1433           aSeqFprm.Append(aNul);
1434           aSeqLprm.Append(lprm);
1435         }
1436         else {
1437           gp_Pnt P1 = newc->Value(aNul);
1438           gp_Pnt P2 = newc->Value(lprm);
1439           Standard_Real aTolDist = BRep_Tool::Tolerance(myFace1) + BRep_Tool::Tolerance(myFace2);
1440           aTolDist = (myTolReached3d > aTolDist) ? myTolReached3d : aTolDist;
1441
1442           if(P1.Distance(P2) > aTolDist) {
1443             Standard_Real anewpar = lprm;
1444
1445             if(ParameterOutOfBoundary(lprm, newc, myFace1, myFace2, 
1446                                       fprm, Standard_True, anewpar, myContext)) {
1447               lprm = anewpar;
1448             }
1449             aSeqFprm.Append(aNul);
1450             aSeqLprm.Append(lprm);
1451           }
1452         }
1453       }
1454       else {
1455         // usual interval 
1456         aSeqFprm.Append(fprm);
1457         aSeqLprm.Append(lprm);
1458       }
1459     }
1460     
1461     //
1462     aNbParts=aSeqFprm.Length();
1463     for (i=1; i<=aNbParts; i++) {
1464       fprm=aSeqFprm(i);
1465       lprm=aSeqLprm(i);
1466       //
1467       Standard_Real aRealEpsilon=RealEpsilon();
1468       if (Abs(fprm) > aRealEpsilon || Abs(lprm-2.*M_PI) > aRealEpsilon) {
1469         //==============================================
1470         ////
1471         IntTools_Curve aCurve;
1472         Handle(Geom_TrimmedCurve) aTC3D=new Geom_TrimmedCurve(newc,fprm,lprm);
1473         aCurve.SetCurve(aTC3D);
1474         fprm=aTC3D->FirstParameter();
1475         lprm=aTC3D->LastParameter ();
1476         ////         
1477         if (typl == IntPatch_Circle || typl == IntPatch_Ellipse) {//// 
1478           if(myApprox1) { 
1479             Handle (Geom2d_Curve) C2d;
1480             BuildPCurves(fprm,lprm,Tolpc,myHS1->ChangeSurface().Surface(),newc,C2d);
1481             if(Tolpc>myTolReached2d || myTolReached2d==0) { 
1482               myTolReached2d=Tolpc;
1483             }
1484             //
1485             aCurve.SetFirstCurve2d(C2d);
1486           }
1487           else { //// 
1488             Handle(Geom2d_BSplineCurve) H1;
1489             aCurve.SetFirstCurve2d(H1);
1490           }
1491
1492
1493           if(myApprox2) { 
1494             Handle (Geom2d_Curve) C2d;
1495             BuildPCurves(fprm,lprm,Tolpc,myHS2->ChangeSurface().Surface(),newc,C2d);
1496             if(Tolpc>myTolReached2d || myTolReached2d==0) { 
1497               myTolReached2d=Tolpc;
1498             }
1499             //
1500             aCurve.SetSecondCurve2d(C2d);
1501           }
1502           else { 
1503             Handle(Geom2d_BSplineCurve) H1;
1504             aCurve.SetSecondCurve2d(H1);
1505           }
1506         }
1507         
1508         else { 
1509           Handle(Geom2d_BSplineCurve) H1;
1510           aCurve.SetFirstCurve2d(H1);
1511           aCurve.SetSecondCurve2d(H1);
1512         }
1513         mySeqOfCurve.Append(aCurve);
1514           //==============================================        
1515       } //if (Abs(fprm) > RealEpsilon() || Abs(lprm-2.*M_PI) > RealEpsilon())
1516
1517       else {
1518         //  on regarde si on garde
1519         //
1520         if (aNbParts==1) {
1521 //           if (Abs(fprm) < RealEpsilon() &&  Abs(lprm-2.*M_PI) < RealEpsilon()) {
1522           if (Abs(fprm) <= aRealEpsilon && Abs(lprm-2.*M_PI) <= aRealEpsilon) {
1523             IntTools_Curve aCurve;
1524             Handle(Geom_TrimmedCurve) aTC3D=new Geom_TrimmedCurve(newc,fprm,lprm);
1525             aCurve.SetCurve(aTC3D);
1526             fprm=aTC3D->FirstParameter();
1527             lprm=aTC3D->LastParameter ();
1528             
1529             if(myApprox1) { 
1530               Handle (Geom2d_Curve) C2d;
1531               BuildPCurves(fprm,lprm,Tolpc,myHS1->ChangeSurface().Surface(),newc,C2d);
1532               if(Tolpc>myTolReached2d || myTolReached2d==0) { 
1533                 myTolReached2d=Tolpc;
1534               }
1535               //
1536               aCurve.SetFirstCurve2d(C2d);
1537             }
1538             else { //// 
1539               Handle(Geom2d_BSplineCurve) H1;
1540               aCurve.SetFirstCurve2d(H1);
1541             }
1542
1543             if(myApprox2) { 
1544               Handle (Geom2d_Curve) C2d;
1545               BuildPCurves(fprm,lprm,Tolpc,myHS2->ChangeSurface().Surface(),newc,C2d);
1546               if(Tolpc>myTolReached2d || myTolReached2d==0) { 
1547                 myTolReached2d=Tolpc;
1548               }
1549               //
1550               aCurve.SetSecondCurve2d(C2d);
1551             }
1552             else { 
1553               Handle(Geom2d_BSplineCurve) H1;
1554               aCurve.SetSecondCurve2d(H1);
1555             }
1556             mySeqOfCurve.Append(aCurve);
1557             break;
1558           }
1559         }
1560         //
1561         Standard_Real aTwoPIdiv17, u1, v1, u2, v2, Tol;
1562
1563         aTwoPIdiv17=2.*M_PI/17.;
1564
1565         for (j=0; j<=17; j++) {
1566           gp_Pnt ptref (newc->Value (j*aTwoPIdiv17));
1567           Tol = Precision::Confusion();
1568
1569           Parameters(myHS1, myHS2, ptref, u1, v1, u2, v2);
1570           ok = (dom1->Classify(gp_Pnt2d(u1,v1),Tol) != TopAbs_OUT);
1571           if(ok) { 
1572             ok = (dom2->Classify(gp_Pnt2d(u2,v2),Tol) != TopAbs_OUT);
1573           }
1574           if (ok) {
1575             IntTools_Curve aCurve;
1576             aCurve.SetCurve(newc);
1577             //==============================================
1578             if (typl == IntPatch_Circle || typl == IntPatch_Ellipse) {
1579               
1580               if(myApprox1) { 
1581                 Handle (Geom2d_Curve) C2d;
1582                 BuildPCurves(fprm, lprm, Tolpc, myHS1->ChangeSurface().Surface(), newc, C2d);
1583                 if(Tolpc>myTolReached2d || myTolReached2d==0) { 
1584                   myTolReached2d=Tolpc;
1585                 }
1586                 // 
1587                 aCurve.SetFirstCurve2d(C2d);
1588               }
1589               else { 
1590                 Handle(Geom2d_BSplineCurve) H1;
1591                 aCurve.SetFirstCurve2d(H1);
1592               }
1593                 
1594               if(myApprox2) { 
1595                 Handle (Geom2d_Curve) C2d;
1596                 BuildPCurves(fprm, lprm, Tolpc,myHS2->ChangeSurface().Surface(), newc, C2d);
1597                 if(Tolpc>myTolReached2d || myTolReached2d==0) { 
1598                   myTolReached2d=Tolpc;
1599                 }
1600                 //                 
1601                 aCurve.SetSecondCurve2d(C2d);
1602               }
1603                 
1604               else { 
1605                 Handle(Geom2d_BSplineCurve) H1;
1606                 aCurve.SetSecondCurve2d(H1);
1607               }
1608             }//  end of if (typl == IntPatch_Circle || typl == IntPatch_Ellipse)
1609              
1610             else { 
1611               Handle(Geom2d_BSplineCurve) H1;
1612               //         
1613               aCurve.SetFirstCurve2d(H1);
1614               aCurve.SetSecondCurve2d(H1);
1615             }
1616             //==============================================        
1617             //
1618             mySeqOfCurve.Append(aCurve);
1619             break;
1620
1621             }//  end of if (ok) {
1622           }//  end of for (Standard_Integer j=0; j<=17; j++)
1623         }//  end of else { on regarde si on garde
1624       }// for (i=1; i<=myLConstruct.NbParts(); i++)
1625     }// IntPatch_Circle: IntPatch_Ellipse:
1626     break;
1627     
1628   case IntPatch_Analytic: {
1629     IntSurf_Quadric quad1,quad2;
1630     GeomAbs_SurfaceType typs = myHS1->Surface().GetType();
1631     
1632     switch (typs) {
1633       case GeomAbs_Plane:
1634         quad1.SetValue(myHS1->Surface().Plane());
1635         break;
1636       case GeomAbs_Cylinder:
1637         quad1.SetValue(myHS1->Surface().Cylinder());
1638         break;
1639       case GeomAbs_Cone:
1640         quad1.SetValue(myHS1->Surface().Cone());
1641         break;
1642       case GeomAbs_Sphere:
1643         quad1.SetValue(myHS1->Surface().Sphere());
1644         break;
1645     case GeomAbs_Torus:
1646       quad1.SetValue(myHS1->Surface().Torus());
1647       break;
1648       default:
1649         Standard_ConstructionError::Raise("GeomInt_IntSS::MakeCurve 1");
1650       }
1651       
1652     typs = myHS2->Surface().GetType();
1653     
1654     switch (typs) {
1655       case GeomAbs_Plane:
1656         quad2.SetValue(myHS2->Surface().Plane());
1657         break;
1658       case GeomAbs_Cylinder:
1659         quad2.SetValue(myHS2->Surface().Cylinder());
1660         break;
1661       case GeomAbs_Cone:
1662         quad2.SetValue(myHS2->Surface().Cone());
1663         break;
1664       case GeomAbs_Sphere:
1665         quad2.SetValue(myHS2->Surface().Sphere());
1666         break;
1667     case GeomAbs_Torus:
1668       quad2.SetValue(myHS2->Surface().Torus());
1669       break;
1670       default:
1671         Standard_ConstructionError::Raise("GeomInt_IntSS::MakeCurve 2");
1672       }
1673     //
1674     //=========
1675     IntPatch_ALineToWLine convert (quad1, quad2);
1676       
1677     if (!myApprox) {
1678       aNbParts=myLConstruct.NbParts();
1679       for (i=1; i<=aNbParts; i++) {
1680         myLConstruct.Part(i, fprm, lprm);
1681         Handle(IntPatch_WLine) WL = 
1682           convert.MakeWLine(Handle(IntPatch_ALine)::DownCast(L), fprm, lprm);
1683         //
1684         Handle(Geom2d_BSplineCurve) H1;
1685         Handle(Geom2d_BSplineCurve) H2;
1686
1687         if(myApprox1) {
1688           H1 = MakeBSpline2d(WL, 1, WL->NbPnts(), Standard_True);
1689         }
1690         
1691         if(myApprox2) {
1692           H2 = MakeBSpline2d(WL, 1, WL->NbPnts(), Standard_False);
1693         }
1694         //          
1695         mySeqOfCurve.Append(IntTools_Curve(MakeBSpline(WL,1,WL->NbPnts()), H1, H2));
1696       }
1697     } // if (!myApprox)
1698
1699     else { // myApprox=TRUE
1700       GeomInt_WLApprox theapp3d;
1701       // 
1702       Standard_Real tol2d = myTolApprox;
1703       //         
1704       theapp3d.SetParameters(myTolApprox, tol2d, 4, 8, 0, Standard_True);
1705       
1706       aNbParts=myLConstruct.NbParts();
1707       for (i=1; i<=aNbParts; i++) {
1708         myLConstruct.Part(i, fprm, lprm);
1709         Handle(IntPatch_WLine) WL = 
1710           convert.MakeWLine(Handle(IntPatch_ALine):: DownCast(L),fprm,lprm);
1711
1712         theapp3d.Perform(myHS1,myHS2,WL,Standard_True,myApprox1,myApprox2, 1, WL->NbPnts());
1713
1714         if (!theapp3d.IsDone()) {
1715           //
1716           Handle(Geom2d_BSplineCurve) H1;
1717           Handle(Geom2d_BSplineCurve) H2;
1718
1719           if(myApprox1) {
1720             H1 = MakeBSpline2d(WL, 1, WL->NbPnts(), Standard_True);
1721           }
1722           
1723           if(myApprox2) {
1724             H2 = MakeBSpline2d(WL, 1, WL->NbPnts(), Standard_False);
1725           }
1726           //          
1727           mySeqOfCurve.Append(IntTools_Curve(MakeBSpline(WL,1,WL->NbPnts()), H1, H2));
1728         }
1729
1730         else {
1731           if(myApprox1 || myApprox2) { 
1732             if( theapp3d.TolReached2d()>myTolReached2d || myTolReached2d==0) { 
1733               myTolReached2d = theapp3d.TolReached2d();
1734             }
1735           }
1736           
1737           if( theapp3d.TolReached3d()>myTolReached3d || myTolReached3d==0) { 
1738             myTolReached3d = theapp3d.TolReached3d();
1739           }
1740
1741           Standard_Integer aNbMultiCurves, nbpoles;
1742           aNbMultiCurves=theapp3d.NbMultiCurves();
1743           for (j=1; j<=aNbMultiCurves; j++) {
1744             const AppParCurves_MultiBSpCurve& mbspc = theapp3d.Value(j);
1745             nbpoles = mbspc.NbPoles();
1746             
1747             TColgp_Array1OfPnt tpoles(1, nbpoles);
1748             mbspc.Curve(1, tpoles);
1749             Handle(Geom_BSplineCurve) BS=new Geom_BSplineCurve(tpoles,
1750                                                                mbspc.Knots(),
1751                                                                mbspc.Multiplicities(),
1752                                                                mbspc.Degree());
1753             
1754             GeomLib_CheckBSplineCurve Check(BS,TOLCHECK,TOLANGCHECK);
1755             Check.FixTangent(Standard_True,Standard_True);
1756             // 
1757             IntTools_Curve aCurve;
1758             aCurve.SetCurve(BS);
1759             
1760             if(myApprox1) { 
1761               TColgp_Array1OfPnt2d tpoles2d(1,nbpoles);
1762               mbspc.Curve(2,tpoles2d);
1763               Handle(Geom2d_BSplineCurve) BS2=new Geom2d_BSplineCurve(tpoles2d,
1764                                                                       mbspc.Knots(),
1765                                                                       mbspc.Multiplicities(),
1766                                                                       mbspc.Degree());
1767
1768               GeomLib_Check2dBSplineCurve newCheck(BS2,TOLCHECK,TOLANGCHECK);
1769               newCheck.FixTangent(Standard_True,Standard_True);
1770               //                 
1771               aCurve.SetFirstCurve2d(BS2);
1772             }
1773             else {
1774               Handle(Geom2d_BSplineCurve) H1;
1775               aCurve.SetFirstCurve2d(H1);
1776             }
1777             
1778             if(myApprox2) { 
1779               TColgp_Array1OfPnt2d tpoles2d(1, nbpoles);
1780               Standard_Integer TwoOrThree;
1781               TwoOrThree=myApprox1 ? 3 : 2;
1782               mbspc.Curve(TwoOrThree, tpoles2d);
1783               Handle(Geom2d_BSplineCurve) BS2 =new Geom2d_BSplineCurve(tpoles2d,
1784                                                                        mbspc.Knots(),
1785                                                                        mbspc.Multiplicities(),
1786                                                                        mbspc.Degree());
1787                 
1788               GeomLib_Check2dBSplineCurve newCheck(BS2,TOLCHECK,TOLANGCHECK);
1789               newCheck.FixTangent(Standard_True,Standard_True);
1790               //         
1791               aCurve.SetSecondCurve2d(BS2);
1792             }
1793             else { 
1794               Handle(Geom2d_BSplineCurve) H2;
1795               aCurve.SetSecondCurve2d(H2);
1796             }
1797             // 
1798             mySeqOfCurve.Append(aCurve);
1799
1800           }// for (j=1; j<=aNbMultiCurves; j++) {
1801         }// else from if (!theapp3d.IsDone())
1802       }// for (i=1; i<=aNbParts; i++) {
1803     }// else { // myApprox=TRUE
1804   }// case IntPatch_Analytic:
1805     break;
1806
1807   case IntPatch_Walking:{
1808     Handle(IntPatch_WLine) WL = 
1809       Handle(IntPatch_WLine)::DownCast(L);
1810     //
1811     Standard_Integer ifprm, ilprm;
1812     //
1813     if (!myApprox) {
1814       aNbParts = 1;
1815       if(!bAvoidLineConstructor){
1816         aNbParts=myLConstruct.NbParts();
1817       }
1818       for (i=1; i<=aNbParts; ++i) {
1819         Handle(Geom2d_BSplineCurve) H1, H2;
1820         Handle(Geom_Curve) aBSp;
1821         //
1822         if(bAvoidLineConstructor) {
1823           ifprm = 1;
1824           ilprm = WL->NbPnts();
1825         }
1826         else {
1827           myLConstruct.Part(i, fprm, lprm);
1828           ifprm=(Standard_Integer)fprm;
1829           ilprm=(Standard_Integer)lprm;
1830         }
1831         //
1832         if(myApprox1) {
1833           H1 = MakeBSpline2d(WL, ifprm, ilprm, Standard_True);
1834         }
1835         //
1836         if(myApprox2) {
1837           H2 = MakeBSpline2d(WL, ifprm, ilprm, Standard_False);
1838         }
1839         //           
1840         aBSp=MakeBSpline(WL, ifprm, ilprm);
1841         IntTools_Curve aIC(aBSp, H1, H2);
1842         mySeqOfCurve.Append(aIC);
1843       }// for (i=1; i<=aNbParts; ++i) {
1844     }// if (!myApprox) {
1845     //
1846     else { // X
1847       Standard_Boolean bIsDecomposited;
1848       Standard_Integer nbiter, aNbSeqOfL;
1849       Standard_Real tol2d, aTolApproxImp;
1850       IntPatch_SequenceOfLine aSeqOfL;
1851       GeomInt_WLApprox theapp3d;
1852       Approx_ParametrizationType aParType = Approx_ChordLength;
1853       //
1854       Standard_Boolean anApprox1 = myApprox1;
1855       Standard_Boolean anApprox2 = myApprox2;
1856       //
1857       aTolApproxImp=1.e-5;
1858       tol2d = myTolApprox;
1859
1860       GeomAbs_SurfaceType typs1, typs2;
1861       typs1 = myHS1->Surface().GetType();
1862       typs2 = myHS2->Surface().GetType();
1863       Standard_Boolean anWithPC = Standard_True;
1864
1865       if(typs1 == GeomAbs_Cylinder && typs2 == GeomAbs_Sphere) {
1866         anWithPC = 
1867           ApproxWithPCurves(myHS1->Surface().Cylinder(), myHS2->Surface().Sphere());
1868       }
1869       else if (typs1 == GeomAbs_Sphere && typs2 == GeomAbs_Cylinder) {
1870         anWithPC = 
1871           ApproxWithPCurves(myHS2->Surface().Cylinder(), myHS1->Surface().Sphere());
1872       }
1873       //
1874       if(!anWithPC) {
1875         myTolApprox = aTolApproxImp;//1.e-5; 
1876         anApprox1 = Standard_False;
1877         anApprox2 = Standard_False;
1878         //         
1879         tol2d = myTolApprox;
1880       }
1881         
1882       if(myHS1 == myHS2) { 
1883         theapp3d.SetParameters(myTolApprox, tol2d, 4, 8, 0, Standard_False, aParType);
1884         rejectSurface = Standard_True;
1885       }
1886       else { 
1887         if(reApprox && !rejectSurface)
1888           theapp3d.SetParameters(myTolApprox, tol2d, 4, 8, 0, Standard_False, aParType);
1889         else {
1890           Standard_Integer iDegMax, iDegMin, iNbIter;
1891           //
1892           ApproxParameters(myHS1, myHS2, iDegMin, iDegMax, iNbIter);
1893           theapp3d.SetParameters(myTolApprox, tol2d, iDegMin, iDegMax, iNbIter, Standard_True, aParType);
1894         }
1895       }
1896       //
1897       Standard_Real aReachedTol = Precision::Confusion();
1898       bIsDecomposited=DecompositionOfWLine(WL,
1899                                            myHS1, 
1900                                            myHS2, 
1901                                            myFace1, 
1902                                            myFace2, 
1903                                            myLConstruct, 
1904                                            bAvoidLineConstructor, 
1905                                            aSeqOfL, 
1906                                            aReachedTol,
1907                                            myContext);
1908       if ( bIsDecomposited && ( myTolReached3d < aReachedTol ) ) {
1909         myTolReached3d = aReachedTol;
1910       }
1911       //
1912       aNbSeqOfL=aSeqOfL.Length();
1913       //
1914       if (bIsDecomposited) {
1915         nbiter=aNbSeqOfL;
1916       }
1917       else {
1918         nbiter=1;
1919         aNbParts=1;
1920         if (!bAvoidLineConstructor) {
1921           aNbParts=myLConstruct.NbParts();
1922           nbiter=aNbParts;
1923         }
1924       }
1925       //
1926       for(i = 1; i <= nbiter; ++i) {
1927         if(bIsDecomposited) {
1928           WL = Handle(IntPatch_WLine)::DownCast(aSeqOfL.Value(i));
1929           ifprm = 1;
1930           ilprm = WL->NbPnts();
1931         }
1932         else {
1933           if(bAvoidLineConstructor) {
1934             ifprm = 1;
1935             ilprm = WL->NbPnts();
1936           }
1937           else {
1938             myLConstruct.Part(i, fprm, lprm);
1939             ifprm = (Standard_Integer)fprm;
1940             ilprm = (Standard_Integer)lprm;
1941           }
1942         }
1943         //-- lbr : 
1944         //-- Si une des surfaces est un plan , on approxime en 2d
1945         //-- sur cette surface et on remonte les points 2d en 3d.
1946         if(typs1 == GeomAbs_Plane) { 
1947           theapp3d.Perform(myHS1, myHS2, WL, Standard_False,Standard_True, myApprox2,ifprm,ilprm);
1948         }          
1949         else if(typs2 == GeomAbs_Plane) { 
1950           theapp3d.Perform(myHS1,myHS2,WL,Standard_False,myApprox1,Standard_True,ifprm,ilprm);
1951         }
1952         else { 
1953           //
1954           if (myHS1 != myHS2){
1955             if ((typs1==GeomAbs_BezierSurface || typs1==GeomAbs_BSplineSurface) &&
1956                 (typs2==GeomAbs_BezierSurface || typs2==GeomAbs_BSplineSurface)) {
1957              
1958               theapp3d.SetParameters(myTolApprox, tol2d, 4, 8, 0, Standard_True, aParType);
1959               
1960               Standard_Boolean bUseSurfaces;
1961               bUseSurfaces=NotUseSurfacesForApprox(myFace1, myFace2, WL, ifprm,  ilprm);
1962               if (bUseSurfaces) {
1963                 // ######
1964                 rejectSurface = Standard_True;
1965                 // ######
1966                 theapp3d.SetParameters(myTolApprox, tol2d, 4, 8, 0, Standard_False, aParType);
1967               }
1968             }
1969           }
1970           //
1971           theapp3d.Perform(myHS1,myHS2,WL,Standard_True,anApprox1,anApprox2,ifprm,ilprm);
1972         }
1973           //           
1974         if (!theapp3d.IsDone()) {
1975           Handle(Geom2d_BSplineCurve) H1;
1976           Handle(Geom2d_BSplineCurve) H2;
1977           //           
1978           Handle(Geom_Curve) aBSp=MakeBSpline(WL,ifprm, ilprm);
1979           //
1980           if(myApprox1) {
1981             H1 = MakeBSpline2d(WL, ifprm, ilprm, Standard_True);
1982           }
1983           //
1984           if(myApprox2) {
1985             H2 = MakeBSpline2d(WL, ifprm, ilprm, Standard_False);
1986           }
1987           //           
1988           IntTools_Curve aIC(aBSp, H1, H2);
1989           mySeqOfCurve.Append(aIC);
1990         }
1991         
1992         else {
1993           if(myApprox1 || myApprox2 || (typs1==GeomAbs_Plane || typs2==GeomAbs_Plane)) { 
1994             if( theapp3d.TolReached2d()>myTolReached2d || myTolReached2d==0.) { 
1995               myTolReached2d = theapp3d.TolReached2d();
1996             }
1997           }
1998           if(typs1==GeomAbs_Plane || typs2==GeomAbs_Plane) { 
1999             myTolReached3d = myTolReached2d;
2000             //
2001             if (typs1==GeomAbs_Torus || typs2==GeomAbs_Torus) {
2002               if (myTolReached3d<1.e-6) {
2003                 myTolReached3d = theapp3d.TolReached3d();
2004                 myTolReached3d=1.e-6;
2005               }
2006             }
2007           }
2008           else  if( theapp3d.TolReached3d()>myTolReached3d || myTolReached3d==0.) { 
2009             myTolReached3d = theapp3d.TolReached3d();
2010           }
2011           
2012           Standard_Integer aNbMultiCurves, nbpoles;
2013           aNbMultiCurves=theapp3d.NbMultiCurves(); 
2014           for (j=1; j<=aNbMultiCurves; j++) {
2015             if(typs1 == GeomAbs_Plane) {
2016               const AppParCurves_MultiBSpCurve& mbspc = theapp3d.Value(j);
2017               nbpoles = mbspc.NbPoles();
2018               
2019               TColgp_Array1OfPnt2d tpoles2d(1,nbpoles);
2020               TColgp_Array1OfPnt   tpoles(1,nbpoles);
2021               
2022               mbspc.Curve(1,tpoles2d);
2023               const gp_Pln&  Pln = myHS1->Surface().Plane();
2024               //
2025               Standard_Integer ik; 
2026               for(ik = 1; ik<= nbpoles; ik++) { 
2027                 tpoles.SetValue(ik,
2028                                 ElSLib::Value(tpoles2d.Value(ik).X(),
2029                                               tpoles2d.Value(ik).Y(),
2030                                               Pln));
2031               }
2032               //
2033               Handle(Geom_BSplineCurve) BS = 
2034                 new Geom_BSplineCurve(tpoles,
2035                                       mbspc.Knots(),
2036                                       mbspc.Multiplicities(),
2037                                       mbspc.Degree());
2038               GeomLib_CheckBSplineCurve Check(BS,TOLCHECK,TOLANGCHECK);
2039               Check.FixTangent(Standard_True, Standard_True);
2040               //         
2041               IntTools_Curve aCurve;
2042               aCurve.SetCurve(BS);
2043
2044               if(myApprox1) { 
2045                 Handle(Geom2d_BSplineCurve) BS1 = 
2046                   new Geom2d_BSplineCurve(tpoles2d,
2047                                           mbspc.Knots(),
2048                                           mbspc.Multiplicities(),
2049                                           mbspc.Degree());
2050                 GeomLib_Check2dBSplineCurve Check1(BS1,TOLCHECK,TOLANGCHECK);
2051                 Check1.FixTangent(Standard_True,Standard_True);
2052                 //
2053                 // ############################################
2054                 if(!rejectSurface && !reApprox) {
2055                   Standard_Boolean isValid = IsCurveValid(BS1);
2056                   if(!isValid) {
2057                     reApprox = Standard_True;
2058                     goto reapprox;
2059                   }
2060                 }
2061                 // ############################################
2062                 aCurve.SetFirstCurve2d(BS1);
2063               }
2064               else {
2065                 Handle(Geom2d_BSplineCurve) H1;
2066                 aCurve.SetFirstCurve2d(H1);
2067               }
2068
2069               if(myApprox2) { 
2070                 mbspc.Curve(2, tpoles2d);
2071                 
2072                 Handle(Geom2d_BSplineCurve) BS2 = new Geom2d_BSplineCurve(tpoles2d,
2073                                                                           mbspc.Knots(),
2074                                                                           mbspc.Multiplicities(),
2075                                                                           mbspc.Degree());
2076                 GeomLib_Check2dBSplineCurve newCheck(BS2,TOLCHECK,TOLANGCHECK);
2077                 newCheck.FixTangent(Standard_True,Standard_True);
2078                 
2079                 // ###########################################
2080                 if(!rejectSurface && !reApprox) {
2081                   Standard_Boolean isValid = IsCurveValid(BS2);
2082                   if(!isValid) {
2083                     reApprox = Standard_True;
2084                     goto reapprox;
2085                   }
2086                 }
2087                 // ###########################################
2088                 // 
2089                 aCurve.SetSecondCurve2d(BS2);
2090               }
2091               else { 
2092                 Handle(Geom2d_BSplineCurve) H2;
2093                 //                 
2094                   aCurve.SetSecondCurve2d(H2);
2095               }
2096               //
2097               mySeqOfCurve.Append(aCurve);
2098             }//if(typs1 == GeomAbs_Plane) {
2099             
2100             else if(typs2 == GeomAbs_Plane) { 
2101               const AppParCurves_MultiBSpCurve& mbspc = theapp3d.Value(j);
2102               nbpoles = mbspc.NbPoles();
2103               
2104               TColgp_Array1OfPnt2d tpoles2d(1,nbpoles);
2105               TColgp_Array1OfPnt   tpoles(1,nbpoles);
2106               mbspc.Curve((myApprox1==Standard_True)? 2 : 1,tpoles2d);
2107               const gp_Pln&  Pln = myHS2->Surface().Plane();
2108               //
2109               Standard_Integer ik; 
2110               for(ik = 1; ik<= nbpoles; ik++) { 
2111                 tpoles.SetValue(ik,
2112                                 ElSLib::Value(tpoles2d.Value(ik).X(),
2113                                               tpoles2d.Value(ik).Y(),
2114                                               Pln));
2115                 
2116               }
2117               //
2118               Handle(Geom_BSplineCurve) BS=new Geom_BSplineCurve(tpoles,
2119                                                                  mbspc.Knots(),
2120                                                                  mbspc.Multiplicities(),
2121                                                                  mbspc.Degree());
2122               GeomLib_CheckBSplineCurve Check(BS,TOLCHECK,TOLANGCHECK);
2123               Check.FixTangent(Standard_True,Standard_True);
2124               //         
2125               IntTools_Curve aCurve;
2126               aCurve.SetCurve(BS);
2127
2128               if(myApprox2) {
2129                 Handle(Geom2d_BSplineCurve) BS1=new Geom2d_BSplineCurve(tpoles2d,
2130                                                                         mbspc.Knots(),
2131                                                                         mbspc.Multiplicities(),
2132                                                                         mbspc.Degree());
2133                 GeomLib_Check2dBSplineCurve Check1(BS1,TOLCHECK,TOLANGCHECK);
2134                 Check1.FixTangent(Standard_True,Standard_True);
2135                 //         
2136                 // ###########################################
2137                 if(!rejectSurface && !reApprox) {
2138                   Standard_Boolean isValid = IsCurveValid(BS1);
2139                   if(!isValid) {
2140                     reApprox = Standard_True;
2141                     goto reapprox;
2142                   }
2143                 }
2144                 // ###########################################
2145                 bPCurvesOk = CheckPCurve(BS1, myFace2);
2146                 aCurve.SetSecondCurve2d(BS1);
2147               }
2148               else {
2149                 Handle(Geom2d_BSplineCurve) H2;
2150                 aCurve.SetSecondCurve2d(H2);
2151               }
2152               
2153               if(myApprox1) { 
2154                 mbspc.Curve(1,tpoles2d);
2155                 Handle(Geom2d_BSplineCurve) BS2=new Geom2d_BSplineCurve(tpoles2d,
2156                                                                         mbspc.Knots(),
2157                                                                         mbspc.Multiplicities(),
2158                                                                         mbspc.Degree());
2159                 GeomLib_Check2dBSplineCurve Check2(BS2,TOLCHECK,TOLANGCHECK);
2160                 Check2.FixTangent(Standard_True,Standard_True);
2161                 //
2162                 // ###########################################
2163                 if(!rejectSurface && !reApprox) {
2164                   Standard_Boolean isValid = IsCurveValid(BS2);
2165                   if(!isValid) {
2166                     reApprox = Standard_True;
2167                     goto reapprox;
2168                   }
2169                 }
2170                 // ###########################################
2171                 bPCurvesOk = bPCurvesOk && CheckPCurve(BS2, myFace1);
2172                 aCurve.SetFirstCurve2d(BS2);
2173               }
2174               else { 
2175                 Handle(Geom2d_BSplineCurve) H1;
2176                 //                 
2177                 aCurve.SetFirstCurve2d(H1);
2178               }
2179               //
2180               //if points of the pcurves are out of the faces bounds
2181               //create 3d and 2d curves without approximation
2182               if (!bPCurvesOk) {
2183                 Handle(Geom2d_BSplineCurve) H1, H2;
2184                 bPCurvesOk = Standard_True;
2185                 //           
2186                 Handle(Geom_Curve) aBSp=MakeBSpline(WL,ifprm, ilprm);
2187                 
2188                 if(myApprox1) {
2189                   H1 = MakeBSpline2d(WL, ifprm, ilprm, Standard_True);
2190                   bPCurvesOk = CheckPCurve(H1, myFace1);
2191                 }
2192                 
2193                 if(myApprox2) {
2194                   H2 = MakeBSpline2d(WL, ifprm, ilprm, Standard_False);
2195                   bPCurvesOk = bPCurvesOk && CheckPCurve(H2, myFace2);
2196                 }
2197                 //
2198                 //if pcurves created without approximation are out of the 
2199                 //faces bounds, use approximated 3d and 2d curves
2200                 if (bPCurvesOk) {
2201                   IntTools_Curve aIC(aBSp, H1, H2);
2202                   mySeqOfCurve.Append(aIC);
2203                 } else {
2204                   mySeqOfCurve.Append(aCurve);
2205                 }
2206               } else {
2207                 mySeqOfCurve.Append(aCurve);
2208               }
2209             }// else if(typs2 == GeomAbs_Plane)
2210             //
2211             else { //typs2 != GeomAbs_Plane && typs1 != GeomAbs_Plane
2212               Standard_Boolean bIsValid1, bIsValid2;
2213               Handle(Geom_BSplineCurve) BS;
2214               Handle(Geom2d_BSplineCurve) aH2D;        
2215               IntTools_Curve aCurve; 
2216               //
2217               bIsValid1=Standard_True;
2218               bIsValid2=Standard_True;
2219               //
2220               const AppParCurves_MultiBSpCurve& mbspc = theapp3d.Value(j);
2221               nbpoles = mbspc.NbPoles();
2222               TColgp_Array1OfPnt tpoles(1,nbpoles);
2223               mbspc.Curve(1,tpoles);
2224               BS=new Geom_BSplineCurve(tpoles,
2225                                                                  mbspc.Knots(),
2226                                                                  mbspc.Multiplicities(),
2227                                                                  mbspc.Degree());
2228               GeomLib_CheckBSplineCurve Check(BS,TOLCHECK,TOLANGCHECK);
2229               Check.FixTangent(Standard_True,Standard_True);
2230               //                 
2231               aCurve.SetCurve(BS);
2232               aCurve.SetFirstCurve2d(aH2D);
2233               aCurve.SetSecondCurve2d(aH2D);
2234               //
2235               if(myApprox1) { 
2236                 if(anApprox1) {
2237                   Handle(Geom2d_BSplineCurve) BS1;
2238                   TColgp_Array1OfPnt2d tpoles2d(1,nbpoles);
2239                   mbspc.Curve(2,tpoles2d);
2240                   //
2241                   BS1=new Geom2d_BSplineCurve(tpoles2d,
2242                                                                         mbspc.Knots(),
2243                                                                         mbspc.Multiplicities(),
2244                                                                         mbspc.Degree());
2245                   GeomLib_Check2dBSplineCurve newCheck(BS1,TOLCHECK,TOLANGCHECK);
2246                   newCheck.FixTangent(Standard_True,Standard_True);
2247                   //         
2248                   if (!reApprox) {
2249                     bIsValid1=CheckPCurve(BS1, myFace1);
2250                   }
2251                   //
2252                   aCurve.SetFirstCurve2d(BS1);
2253                 }
2254                 else {
2255                   Handle(Geom2d_BSplineCurve) BS1;
2256                   fprm = BS->FirstParameter();
2257                   lprm = BS->LastParameter();
2258
2259                   Handle(Geom2d_Curve) C2d;
2260                   Standard_Real aTol = myTolApprox;
2261                   BuildPCurves(fprm, lprm, aTol, myHS1->ChangeSurface().Surface(), BS, C2d);
2262                   BS1 = Handle(Geom2d_BSplineCurve)::DownCast(C2d);
2263                   aCurve.SetFirstCurve2d(BS1);
2264                 }
2265               } // if(myApprox1) { 
2266                 //                 
2267               if(myApprox2) { 
2268                 if(anApprox2) {
2269                   Handle(Geom2d_BSplineCurve) BS2;
2270                   TColgp_Array1OfPnt2d tpoles2d(1,nbpoles);
2271                   mbspc.Curve((myApprox1==Standard_True)? 3 : 2,tpoles2d);
2272                   BS2=new Geom2d_BSplineCurve(tpoles2d,
2273                                                                         mbspc.Knots(),
2274                                                                         mbspc.Multiplicities(),
2275                                                                         mbspc.Degree());
2276                   GeomLib_Check2dBSplineCurve newCheck(BS2,TOLCHECK,TOLANGCHECK);
2277                   newCheck.FixTangent(Standard_True,Standard_True);
2278                 //                 
2279                   if (!reApprox) {
2280                     bIsValid2=CheckPCurve(BS2, myFace2);        
2281                   }
2282                   aCurve.SetSecondCurve2d(BS2);
2283                 }
2284                 else {
2285                   Handle(Geom2d_BSplineCurve) BS2;
2286                   fprm = BS->FirstParameter();
2287                   lprm = BS->LastParameter();
2288
2289                   Handle(Geom2d_Curve) C2d;
2290                   Standard_Real aTol = myTolApprox;
2291                   BuildPCurves(fprm, lprm, aTol, myHS2->ChangeSurface().Surface(), BS, C2d);
2292                   BS2 = Handle(Geom2d_BSplineCurve)::DownCast(C2d);
2293                   aCurve.SetSecondCurve2d(BS2);
2294                 }
2295               } //if(myApprox2) { 
2296               if (!bIsValid1 || !bIsValid2) {
2297                 myTolApprox=aTolApproxImp;//1.e-5;
2298                 tol2d = myTolApprox;
2299                 reApprox = Standard_True;
2300                 goto reapprox;
2301               }
2302                 //                 
2303               mySeqOfCurve.Append(aCurve);
2304             }
2305           }
2306         }
2307       }
2308     }// else { // X
2309   }// case IntPatch_Walking:{
2310     break;
2311     
2312   case IntPatch_Restriction: 
2313     break;
2314   default:
2315     break;
2316
2317   }
2318 }
2319
2320 //=======================================================================
2321 //function : BuildPCurves
2322 //purpose  : 
2323 //=======================================================================
2324 void BuildPCurves (Standard_Real f,
2325                    Standard_Real l,
2326                    Standard_Real& Tol,
2327                    const Handle (Geom_Surface)& S,
2328                    const Handle (Geom_Curve)&   C,
2329                    Handle (Geom2d_Curve)& C2d)
2330 {
2331   if (!C2d.IsNull()) {
2332     return;
2333   }
2334   //
2335   Standard_Real umin,umax,vmin,vmax;
2336   // 
2337   S->Bounds(umin, umax, vmin, vmax);
2338   // in class ProjLib_Function the range of parameters is shrank by 1.e-09
2339   if((l - f) > 2.e-09) {
2340     C2d = GeomProjLib::Curve2d(C,f,l,S,umin,umax,vmin,vmax,Tol);
2341     //
2342     if (C2d.IsNull()) {
2343       // proj. a circle that goes through the pole on a sphere to the sphere     
2344       Tol += Precision::Confusion();
2345       C2d = GeomProjLib::Curve2d(C,f,l,S,Tol);
2346     }
2347   }
2348   else {
2349     if((l - f) > Epsilon(Abs(f))) {
2350       GeomAPI_ProjectPointOnSurf aProjector1, aProjector2;
2351       gp_Pnt P1 = C->Value(f);
2352       gp_Pnt P2 = C->Value(l);
2353       aProjector1.Init(P1, S);
2354       aProjector2.Init(P2, S);
2355       
2356       if(aProjector1.IsDone() && aProjector2.IsDone()) {
2357         Standard_Real U=0., V=0.;
2358         aProjector1.LowerDistanceParameters(U, V);
2359         gp_Pnt2d p1(U, V);
2360         
2361         aProjector2.LowerDistanceParameters(U, V);
2362         gp_Pnt2d p2(U, V);
2363         
2364         if(p1.Distance(p2) > gp::Resolution()) {
2365           TColgp_Array1OfPnt2d poles(1,2);
2366           TColStd_Array1OfReal knots(1,2);
2367           TColStd_Array1OfInteger mults(1,2);
2368           poles(1) = p1;
2369           poles(2) = p2;
2370           knots(1) = f;
2371           knots(2) = l;
2372           mults(1) = mults(2) = 2;
2373           
2374           C2d = new Geom2d_BSplineCurve(poles,knots,mults,1);
2375           
2376           // compute reached tolerance.begin
2377           gp_Pnt PMid = C->Value((f + l) * 0.5);
2378           aProjector1.Perform(PMid);
2379           
2380           if(aProjector1.IsDone()) {
2381             aProjector1.LowerDistanceParameters(U, V);
2382             gp_Pnt2d pmidproj(U, V);
2383             gp_Pnt2d pmidcurve2d = C2d->Value((f + l) * 0.5);
2384             Standard_Real adist = pmidcurve2d.Distance(pmidproj);
2385             Tol = (adist > Tol) ? adist : Tol;
2386           }
2387           // compute reached tolerance.end
2388         }
2389       }
2390     }
2391   }
2392   //
2393   if (S->IsUPeriodic() && !C2d.IsNull()) {
2394     // Recadre dans le domaine UV de la face
2395     Standard_Real aTm, U0, aEps, period, du, U0x;
2396     Standard_Boolean bAdjust;
2397     //
2398     aEps = Precision::PConfusion();
2399     period = S->UPeriod();
2400     //
2401     aTm = .5*(f + l);
2402     gp_Pnt2d pm = C2d->Value(aTm);
2403     U0 = pm.X();
2404     //
2405     bAdjust = 
2406       IntTools_Tools::AdjustPeriodic(U0, umin, umax, period, U0x, du, aEps);
2407     if (bAdjust) {
2408       gp_Vec2d T1(du, 0.);
2409       C2d->Translate(T1);
2410     }
2411   }
2412 }
2413
2414 //=======================================================================
2415 //function : Parameters
2416 //purpose  : 
2417 //=======================================================================
2418  void Parameters(const Handle(GeomAdaptor_HSurface)& HS1,
2419                  const Handle(GeomAdaptor_HSurface)& HS2,
2420                  const gp_Pnt& Ptref,
2421                  Standard_Real& U1,
2422                  Standard_Real& V1,
2423                  Standard_Real& U2,
2424                  Standard_Real& V2)
2425 {
2426
2427   IntSurf_Quadric quad1,quad2;
2428   GeomAbs_SurfaceType typs = HS1->Surface().GetType();
2429
2430   switch (typs) {
2431   case GeomAbs_Plane:
2432     quad1.SetValue(HS1->Surface().Plane());
2433     break;
2434   case GeomAbs_Cylinder:
2435     quad1.SetValue(HS1->Surface().Cylinder());
2436     break;
2437   case GeomAbs_Cone:
2438     quad1.SetValue(HS1->Surface().Cone());
2439     break;
2440   case GeomAbs_Sphere:
2441     quad1.SetValue(HS1->Surface().Sphere());
2442     break;
2443   case GeomAbs_Torus:
2444     quad1.SetValue(HS1->Surface().Torus());
2445     break;
2446   default:
2447     Standard_ConstructionError::Raise("GeomInt_IntSS::MakeCurve");
2448   }
2449   
2450   typs = HS2->Surface().GetType();
2451   switch (typs) {
2452   case GeomAbs_Plane:
2453     quad2.SetValue(HS2->Surface().Plane());
2454     break;
2455   case GeomAbs_Cylinder:
2456     quad2.SetValue(HS2->Surface().Cylinder());
2457     break;
2458   case GeomAbs_Cone:
2459     quad2.SetValue(HS2->Surface().Cone());
2460     break;
2461   case GeomAbs_Sphere:
2462     quad2.SetValue(HS2->Surface().Sphere());
2463     break;
2464   case GeomAbs_Torus:
2465     quad2.SetValue(HS2->Surface().Torus());
2466     break;
2467   default:
2468     Standard_ConstructionError::Raise("GeomInt_IntSS::MakeCurve");
2469   }
2470
2471   quad1.Parameters(Ptref,U1,V1);
2472   quad2.Parameters(Ptref,U2,V2);
2473 }
2474
2475 //=======================================================================
2476 //function : MakeBSpline
2477 //purpose  : 
2478 //=======================================================================
2479 Handle(Geom_Curve) MakeBSpline  (const Handle(IntPatch_WLine)& WL,
2480                                  const Standard_Integer ideb,
2481                                  const Standard_Integer ifin)
2482 {
2483   Standard_Integer i,nbpnt = ifin-ideb+1;
2484   TColgp_Array1OfPnt poles(1,nbpnt);
2485   TColStd_Array1OfReal knots(1,nbpnt);
2486   TColStd_Array1OfInteger mults(1,nbpnt);
2487   Standard_Integer ipidebm1;
2488   for(i=1,ipidebm1=i+ideb-1; i<=nbpnt;ipidebm1++, i++) {
2489     poles(i) = WL->Point(ipidebm1).Value();
2490     mults(i) = 1;
2491     knots(i) = i-1;
2492   }
2493   mults(1) = mults(nbpnt) = 2;
2494   return
2495     new Geom_BSplineCurve(poles,knots,mults,1);
2496 }
2497 //
2498
2499 //=======================================================================
2500 //function : MakeBSpline2d
2501 //purpose  : 
2502 //=======================================================================
2503 Handle(Geom2d_BSplineCurve) MakeBSpline2d(const Handle(IntPatch_WLine)& theWLine,
2504                                           const Standard_Integer ideb,
2505                                           const Standard_Integer ifin,
2506                                           const Standard_Boolean onFirst)
2507 {
2508   Standard_Integer i, nbpnt = ifin-ideb+1;
2509   TColgp_Array1OfPnt2d poles(1,nbpnt);
2510   TColStd_Array1OfReal knots(1,nbpnt);
2511   TColStd_Array1OfInteger mults(1,nbpnt);
2512   Standard_Integer ipidebm1;
2513
2514   for(i = 1, ipidebm1 = i+ideb-1; i <= nbpnt; ipidebm1++, i++) {
2515       Standard_Real U, V;
2516       if(onFirst)
2517         theWLine->Point(ipidebm1).ParametersOnS1(U, V);
2518       else
2519         theWLine->Point(ipidebm1).ParametersOnS2(U, V);
2520       poles(i).SetCoord(U, V);
2521       mults(i) = 1;
2522       knots(i) = i-1;
2523     }
2524     mults(1) = mults(nbpnt) = 2;
2525
2526   return new Geom2d_BSplineCurve(poles,knots,mults,1);
2527 }
2528 //=======================================================================
2529 //function : PrepareLines3D
2530 //purpose  : 
2531 //=======================================================================
2532   void IntTools_FaceFace::PrepareLines3D(const Standard_Boolean bToSplit)
2533 {
2534   Standard_Integer i, aNbCurves;
2535   GeomAbs_SurfaceType aType1, aType2;
2536   IntTools_SequenceOfCurves aNewCvs;
2537   //
2538   // 1. Treatment closed  curves
2539   aNbCurves=mySeqOfCurve.Length();
2540   for (i=1; i<=aNbCurves; ++i) {
2541     const IntTools_Curve& aIC=mySeqOfCurve(i);
2542     //
2543     if (bToSplit) {
2544       Standard_Integer j, aNbC;
2545       IntTools_SequenceOfCurves aSeqCvs;
2546       //
2547       aNbC=IntTools_Tools::SplitCurve(aIC, aSeqCvs);
2548       if (aNbC) {
2549         for (j=1; j<=aNbC; ++j) {
2550           const IntTools_Curve& aICNew=aSeqCvs(j);
2551           aNewCvs.Append(aICNew);
2552         }
2553       }
2554       else {
2555         aNewCvs.Append(aIC);
2556       }
2557     }
2558     else {
2559       aNewCvs.Append(aIC);
2560     }
2561   }
2562   //
2563   // 2. Plane\Cone intersection when we had 4 curves
2564   aType1=myHS1->GetType();
2565   aType2=myHS2->GetType();
2566   aNbCurves=aNewCvs.Length();
2567   //
2568   if ((aType1==GeomAbs_Plane && aType2==GeomAbs_Cone) ||
2569       (aType2==GeomAbs_Plane && aType1==GeomAbs_Cone)) {
2570     if (aNbCurves==4) {
2571       GeomAbs_CurveType aCType1;
2572       //
2573       aCType1=aNewCvs(1).Type();
2574       if (aCType1==GeomAbs_Line) {
2575         IntTools_SequenceOfCurves aSeqIn, aSeqOut;
2576         //
2577         for (i=1; i<=aNbCurves; ++i) {
2578           const IntTools_Curve& aIC=aNewCvs(i);
2579           aSeqIn.Append(aIC);
2580         }
2581         //
2582         IntTools_Tools::RejectLines(aSeqIn, aSeqOut);
2583         //
2584         aNewCvs.Clear();
2585         aNbCurves=aSeqOut.Length(); 
2586         for (i=1; i<=aNbCurves; ++i) {
2587           const IntTools_Curve& aIC=aSeqOut(i);
2588           aNewCvs.Append(aIC);
2589         }
2590       }
2591     }
2592   }// if ((aType1==GeomAbs_Plane && aType2==GeomAbs_Cone)...
2593   //
2594   // 3. Fill  mySeqOfCurve
2595   mySeqOfCurve.Clear();
2596   aNbCurves=aNewCvs.Length();
2597   for (i=1; i<=aNbCurves; ++i) {
2598     const IntTools_Curve& aIC=aNewCvs(i);
2599     mySeqOfCurve.Append(aIC);
2600   }
2601 }
2602 //=======================================================================
2603 //function : CorrectSurfaceBoundaries
2604 //purpose  : 
2605 //=======================================================================
2606  void CorrectSurfaceBoundaries(const TopoDS_Face&  theFace,
2607                               const Standard_Real theTolerance,
2608                               Standard_Real&      theumin,
2609                               Standard_Real&      theumax, 
2610                               Standard_Real&      thevmin, 
2611                               Standard_Real&      thevmax) 
2612 {
2613   Standard_Boolean enlarge, isuperiodic, isvperiodic;
2614   Standard_Real uinf, usup, vinf, vsup, delta;
2615   GeomAbs_SurfaceType aType;
2616   Handle(Geom_Surface) aSurface;
2617   //
2618   aSurface = BRep_Tool::Surface(theFace);
2619   aSurface->Bounds(uinf, usup, vinf, vsup);
2620   delta = theTolerance;
2621   enlarge = Standard_False;
2622   //
2623   GeomAdaptor_Surface anAdaptorSurface(aSurface);
2624   //
2625   if(aSurface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) {
2626     Handle(Geom_Surface) aBasisSurface = 
2627       (Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurface))->BasisSurface();
2628     
2629     if(aBasisSurface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface)) ||
2630        aBasisSurface->IsKind(STANDARD_TYPE(Geom_OffsetSurface))) {
2631       return;
2632     }
2633   }
2634   //
2635   if(aSurface->IsKind(STANDARD_TYPE(Geom_OffsetSurface))) {
2636     Handle(Geom_Surface) aBasisSurface = 
2637       (Handle(Geom_OffsetSurface)::DownCast(aSurface))->BasisSurface();
2638     
2639     if(aBasisSurface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface)) ||
2640        aBasisSurface->IsKind(STANDARD_TYPE(Geom_OffsetSurface))) {
2641       return;
2642     }
2643   }
2644   //
2645   isuperiodic = anAdaptorSurface.IsUPeriodic();
2646   isvperiodic = anAdaptorSurface.IsVPeriodic();
2647   //
2648   aType=anAdaptorSurface.GetType();
2649   if((aType==GeomAbs_BezierSurface) ||
2650      (aType==GeomAbs_BSplineSurface) ||
2651      (aType==GeomAbs_SurfaceOfExtrusion) ||
2652      (aType==GeomAbs_SurfaceOfRevolution) ||
2653      (aType==GeomAbs_Cylinder)) {
2654     enlarge=Standard_True;
2655   }
2656   //
2657   if(!isuperiodic && enlarge) {
2658
2659     if((theumin - uinf) > delta )
2660       theumin -= delta;
2661     else {
2662       theumin = uinf;
2663     }
2664
2665     if((usup - theumax) > delta )
2666       theumax += delta;
2667     else
2668       theumax = usup;
2669   }
2670   //
2671   if(!isvperiodic && enlarge) {
2672     if((thevmin - vinf) > delta ) {
2673       thevmin -= delta;
2674     }
2675     else { 
2676       thevmin = vinf;
2677     }
2678     if((vsup - thevmax) > delta ) {
2679       thevmax += delta;
2680     }
2681     else {
2682       thevmax = vsup;
2683     }
2684   }
2685   //
2686   {
2687     Standard_Integer aNbP;
2688     Standard_Real aXP, dXfact, aXmid, aX1, aX2, aTolPA;
2689     //
2690     aTolPA=Precision::Angular();
2691     // U
2692     if (isuperiodic) {
2693       aXP=anAdaptorSurface.UPeriod();
2694       dXfact=theumax-theumin;
2695       if (dXfact-aTolPA>aXP) {
2696         aXmid=0.5*(theumax+theumin);
2697         aNbP=RealToInt(aXmid/aXP);
2698         if (aXmid<0.) {
2699           aNbP=aNbP-1;
2700         }
2701         aX1=aNbP*aXP;
2702         if (theumin>aTolPA) {
2703           aX1=theumin+aNbP*aXP;
2704         }
2705         aX2=aX1+aXP;
2706         if (theumin<aX1) {
2707           theumin=aX1;
2708         }
2709         if (theumax>aX2) {
2710           theumax=aX2;
2711         }
2712       }
2713     }
2714     // V
2715     if (isvperiodic) {
2716       aXP=anAdaptorSurface.VPeriod();
2717       dXfact=thevmax-thevmin;
2718       if (dXfact-aTolPA>aXP) {
2719         aXmid=0.5*(thevmax+thevmin);
2720         aNbP=RealToInt(aXmid/aXP);
2721         if (aXmid<0.) {
2722           aNbP=aNbP-1;
2723         }
2724         aX1=aNbP*aXP;
2725         if (thevmin>aTolPA) {
2726           aX1=thevmin+aNbP*aXP;
2727         }
2728         aX2=aX1+aXP;
2729         if (thevmin<aX1) {
2730           thevmin=aX1;
2731         }
2732         if (thevmax>aX2) {
2733           thevmax=aX2;
2734         }
2735       }
2736     }
2737   }
2738   //
2739   if(isuperiodic || isvperiodic) {
2740     Standard_Boolean correct = Standard_False;
2741     Standard_Boolean correctU = Standard_False;
2742     Standard_Boolean correctV = Standard_False;
2743     Bnd_Box2d aBox;
2744     TopExp_Explorer anExp;
2745
2746     for(anExp.Init(theFace, TopAbs_EDGE); anExp.More(); anExp.Next()) {
2747       if(BRep_Tool::IsClosed(TopoDS::Edge(anExp.Current()), theFace)) {
2748         correct = Standard_True;
2749         Standard_Real f, l;
2750         TopoDS_Edge anEdge = TopoDS::Edge(anExp.Current());
2751         
2752         for(Standard_Integer i = 0; i < 2; i++) {
2753           if(i==0) {
2754             anEdge.Orientation(TopAbs_FORWARD);
2755           }
2756           else {
2757             anEdge.Orientation(TopAbs_REVERSED);
2758           }
2759           Handle(Geom2d_Curve) aCurve = BRep_Tool::CurveOnSurface(anEdge, theFace, f, l);
2760           
2761           if(aCurve.IsNull()) {
2762             correct = Standard_False;
2763             break;
2764           }
2765           Handle(Geom2d_Line) aLine = Handle(Geom2d_Line)::DownCast(aCurve);
2766
2767           if(aLine.IsNull()) {
2768             correct = Standard_False;
2769             break;
2770           }
2771           gp_Dir2d anUDir(1., 0.);
2772           gp_Dir2d aVDir(0., 1.);
2773           Standard_Real anAngularTolerance = Precision::Angular();
2774
2775           correctU = correctU || aLine->Position().Direction().IsParallel(aVDir, anAngularTolerance);
2776           correctV = correctV || aLine->Position().Direction().IsParallel(anUDir, anAngularTolerance);
2777           
2778           gp_Pnt2d pp1 = aCurve->Value(f);
2779           aBox.Add(pp1);
2780           gp_Pnt2d pp2 = aCurve->Value(l);
2781           aBox.Add(pp2);
2782         }
2783         if(!correct)
2784           break;
2785       }
2786     }
2787
2788     if(correct) {
2789       Standard_Real umin, vmin, umax, vmax;
2790       aBox.Get(umin, vmin, umax, vmax);
2791
2792       if(isuperiodic && correctU) {
2793         
2794         if(theumin < umin)
2795           theumin = umin;
2796         
2797         if(theumax > umax) {
2798           theumax = umax;
2799         }
2800       }
2801       if(isvperiodic && correctV) {
2802         
2803         if(thevmin < vmin)
2804           thevmin = vmin;
2805         if(thevmax > vmax)
2806           thevmax = vmax;
2807       }
2808     }
2809   }
2810 }
2811 //
2812 //
2813 // The block is dedicated to determine whether WLine [ifprm, ilprm]
2814 // crosses the degenerated zone on each given surface or not.
2815 // If Yes -> We will not use info about surfaces during approximation
2816 // because inside degenerated zone of the surface the approx. algo.
2817 // uses wrong values of normal, etc., and resulting curve will have
2818 // oscillations that we would not like to have. 
2819  
2820
2821
2822 static
2823   Standard_Boolean IsDegeneratedZone(const gp_Pnt2d& aP2d,
2824                                      const Handle(Geom_Surface)& aS,
2825                                      const Standard_Integer iDir);
2826 static
2827   Standard_Boolean IsPointInDegeneratedZone(const IntSurf_PntOn2S& aP2S,
2828                                             const TopoDS_Face& aF1,
2829                                             const TopoDS_Face& aF2);
2830 //=======================================================================
2831 //function :  NotUseSurfacesForApprox
2832 //purpose  : 
2833 //=======================================================================
2834 Standard_Boolean NotUseSurfacesForApprox(const TopoDS_Face& aF1,
2835                                          const TopoDS_Face& aF2,
2836                                          const Handle(IntPatch_WLine)& WL,
2837                                          const Standard_Integer ifprm,
2838                                          const Standard_Integer ilprm)
2839 {
2840   Standard_Boolean bPInDZ;
2841
2842   Handle(IntSurf_LineOn2S) aLineOn2S=WL->Curve();
2843   
2844   const IntSurf_PntOn2S& aP2Sfprm=aLineOn2S->Value(ifprm);
2845   bPInDZ=IsPointInDegeneratedZone(aP2Sfprm, aF1, aF2);
2846   if (bPInDZ) {
2847     return bPInDZ;
2848   }
2849
2850   const IntSurf_PntOn2S& aP2Slprm=aLineOn2S->Value(ilprm);
2851   bPInDZ=IsPointInDegeneratedZone(aP2Slprm, aF1, aF2);
2852   
2853   return bPInDZ;
2854 }
2855 //=======================================================================
2856 //function : IsPointInDegeneratedZone
2857 //purpose  : 
2858 //=======================================================================
2859 Standard_Boolean IsPointInDegeneratedZone(const IntSurf_PntOn2S& aP2S,
2860                                           const TopoDS_Face& aF1,
2861                                           const TopoDS_Face& aF2)
2862                                           
2863 {
2864   Standard_Boolean bFlag=Standard_True;
2865   Standard_Real US11, US12, VS11, VS12, US21, US22, VS21, VS22;
2866   Standard_Real U1, V1, U2, V2, aDelta, aD;
2867   gp_Pnt2d aP2d;
2868
2869   Handle(Geom_Surface)aS1 = BRep_Tool::Surface(aF1);
2870   aS1->Bounds(US11, US12, VS11, VS12);
2871   GeomAdaptor_Surface aGAS1(aS1);
2872
2873   Handle(Geom_Surface)aS2 = BRep_Tool::Surface(aF2);
2874   aS1->Bounds(US21, US22, VS21, VS22);
2875   GeomAdaptor_Surface aGAS2(aS2);
2876   //
2877   //const gp_Pnt& aP=aP2S.Value();
2878   aP2S.Parameters(U1, V1, U2, V2);
2879   //
2880   aDelta=1.e-7;
2881   // Check on Surf 1
2882   aD=aGAS1.UResolution(aDelta);
2883   aP2d.SetCoord(U1, V1);
2884   if (fabs(U1-US11) < aD) {
2885     bFlag=IsDegeneratedZone(aP2d, aS1, 1);
2886     if (bFlag) {
2887       return bFlag;
2888     }
2889   }
2890   if (fabs(U1-US12) < aD) {
2891     bFlag=IsDegeneratedZone(aP2d, aS1, 1);
2892     if (bFlag) {
2893       return bFlag;
2894     }
2895   }
2896   aD=aGAS1.VResolution(aDelta);
2897   if (fabs(V1-VS11) < aDelta) {
2898     bFlag=IsDegeneratedZone(aP2d, aS1, 2);
2899     if (bFlag) {
2900       return bFlag;
2901     }
2902   }
2903   if (fabs(V1-VS12) < aDelta) {
2904     bFlag=IsDegeneratedZone(aP2d, aS1, 2);
2905     if (bFlag) {
2906       return bFlag;
2907     }
2908   }
2909   // Check on Surf 2
2910   aD=aGAS2.UResolution(aDelta);
2911   aP2d.SetCoord(U2, V2);
2912   if (fabs(U2-US21) < aDelta) {
2913     bFlag=IsDegeneratedZone(aP2d, aS2, 1);
2914     if (bFlag) {
2915       return bFlag;
2916     }
2917   }
2918   if (fabs(U2-US22) < aDelta) {
2919     bFlag=IsDegeneratedZone(aP2d, aS2, 1);
2920     if (bFlag) {
2921       return bFlag;
2922     }
2923   }
2924   aD=aGAS2.VResolution(aDelta);
2925   if (fabs(V2-VS21) < aDelta) {
2926     bFlag=IsDegeneratedZone(aP2d, aS2, 2);
2927     if (bFlag) {  
2928       return bFlag;
2929     }
2930   }
2931   if (fabs(V2-VS22) < aDelta) {
2932     bFlag=IsDegeneratedZone(aP2d, aS2, 2);
2933     if (bFlag) {
2934       return bFlag;
2935     }
2936   }
2937   return !bFlag;
2938 }
2939
2940 //=======================================================================
2941 //function : IsDegeneratedZone
2942 //purpose  : 
2943 //=======================================================================
2944 Standard_Boolean IsDegeneratedZone(const gp_Pnt2d& aP2d,
2945                                    const Handle(Geom_Surface)& aS,
2946                                    const Standard_Integer iDir)
2947 {
2948   Standard_Boolean bFlag=Standard_True;
2949   Standard_Real US1, US2, VS1, VS2, dY, dX, d1, d2, dD;
2950   Standard_Real aXm, aYm, aXb, aYb, aXe, aYe;
2951   aS->Bounds(US1, US2, VS1, VS2); 
2952
2953   gp_Pnt aPm, aPb, aPe;
2954   
2955   aXm=aP2d.X();
2956   aYm=aP2d.Y();
2957   
2958   aS->D0(aXm, aYm, aPm); 
2959   
2960   dX=1.e-5;
2961   dY=1.e-5;
2962   dD=1.e-12;
2963
2964   if (iDir==1) {
2965     aXb=aXm;
2966     aXe=aXm;
2967     aYb=aYm-dY;
2968     if (aYb < VS1) {
2969       aYb=VS1;
2970     }
2971     aYe=aYm+dY;
2972     if (aYe > VS2) {
2973       aYe=VS2;
2974     }
2975     aS->D0(aXb, aYb, aPb);
2976     aS->D0(aXe, aYe, aPe);
2977     
2978     d1=aPm.Distance(aPb);
2979     d2=aPm.Distance(aPe);
2980     if (d1 < dD && d2 < dD) {
2981       return bFlag;
2982     }
2983     return !bFlag;
2984   }
2985   //
2986   else if (iDir==2) {
2987     aYb=aYm;
2988     aYe=aYm;
2989     aXb=aXm-dX;
2990     if (aXb < US1) {
2991       aXb=US1;
2992     }
2993     aXe=aXm+dX;
2994     if (aXe > US2) {
2995       aXe=US2;
2996     }
2997     aS->D0(aXb, aYb, aPb);
2998     aS->D0(aXe, aYe, aPe);
2999     
3000     d1=aPm.Distance(aPb);
3001     d2=aPm.Distance(aPe);
3002     if (d1 < dD && d2 < dD) {
3003       return bFlag;
3004     }
3005     return !bFlag;
3006   }
3007   return !bFlag;
3008 }
3009
3010 //=========================================================================
3011 // static function : ComputePurgedWLine
3012 // purpose : Removes equal points (leave one of equal points) from theWLine
3013 //           and recompute vertex parameters.
3014 //           Returns new WLine or null WLine if the number
3015 //           of the points is less than 2.
3016 //=========================================================================
3017 Handle(IntPatch_WLine) ComputePurgedWLine(const Handle(IntPatch_WLine)& theWLine) {
3018  
3019   Standard_Integer i, k, v, nb, nbvtx;
3020   Handle(IntPatch_WLine) aResult;
3021   nbvtx = theWLine->NbVertex();
3022   nb = theWLine->NbPnts();
3023   if (nb==2) {
3024     const IntSurf_PntOn2S& p1 = theWLine->Point(1);
3025     const IntSurf_PntOn2S& p2 = theWLine->Point(2);
3026     if(p1.Value().IsEqual(p2.Value(), gp::Resolution())) {
3027       return aResult;
3028     }
3029   }
3030   //
3031   Handle(IntPatch_WLine) aLocalWLine;
3032   Handle(IntPatch_WLine) aTmpWLine = theWLine;
3033   Handle(IntSurf_LineOn2S) aLineOn2S = new IntSurf_LineOn2S();
3034   aLocalWLine = new IntPatch_WLine(aLineOn2S, Standard_False);
3035   for(i = 1; i <= nb; i++) {
3036     aLineOn2S->Add(theWLine->Point(i));
3037   }
3038
3039   for(v = 1; v <= nbvtx; v++) {
3040     aLocalWLine->AddVertex(theWLine->Vertex(v));
3041   }
3042   
3043   for(i = 1; i <= aLineOn2S->NbPoints(); i++) {
3044     Standard_Integer aStartIndex = i + 1;
3045     Standard_Integer anEndIndex = i + 5;
3046     nb = aLineOn2S->NbPoints();
3047     anEndIndex = (anEndIndex > nb) ? nb : anEndIndex;
3048
3049     if((aStartIndex > nb) || (anEndIndex <= 1)) {
3050       continue;
3051     }
3052     k = aStartIndex;
3053
3054     while(k <= anEndIndex) {
3055       
3056       if(i != k) {
3057         IntSurf_PntOn2S p1 = aLineOn2S->Value(i);
3058         IntSurf_PntOn2S p2 = aLineOn2S->Value(k);
3059         
3060         if(p1.Value().IsEqual(p2.Value(), gp::Resolution())) {
3061           aTmpWLine = aLocalWLine;
3062           aLocalWLine = new IntPatch_WLine(aLineOn2S, Standard_False);
3063
3064           for(v = 1; v <= aTmpWLine->NbVertex(); v++) {
3065             IntPatch_Point aVertex = aTmpWLine->Vertex(v);
3066             Standard_Integer avertexindex = (Standard_Integer)aVertex.ParameterOnLine();
3067
3068             if(avertexindex >= k) {
3069               aVertex.SetParameter(aVertex.ParameterOnLine() - 1.);
3070             }
3071             aLocalWLine->AddVertex(aVertex);
3072           }
3073           aLineOn2S->RemovePoint(k);
3074           anEndIndex--;
3075           continue;
3076         }
3077       }
3078       k++;
3079     }
3080   }
3081
3082   if(aLineOn2S->NbPoints() > 1) {
3083     aResult = aLocalWLine;
3084   }
3085   return aResult;
3086 }
3087
3088 //=======================================================================
3089 //function : TolR3d
3090 //purpose  : 
3091 //=======================================================================
3092 void TolR3d(const TopoDS_Face& aF1,
3093             const TopoDS_Face& aF2,
3094             Standard_Real& myTolReached3d)
3095 {
3096   Standard_Real aTolF1, aTolF2, aTolFMax, aTolTresh;
3097       
3098   aTolTresh=2.999999e-3;
3099   aTolF1 = BRep_Tool::Tolerance(aF1);
3100   aTolF2 = BRep_Tool::Tolerance(aF2);
3101   aTolFMax=Max(aTolF1, aTolF2);
3102   
3103   if (aTolFMax>aTolTresh) {
3104     myTolReached3d=aTolFMax;
3105   }
3106 }
3107 //=======================================================================
3108 //function : IsPointOnBoundary
3109 //purpose  : 
3110 //=======================================================================
3111 Standard_Boolean IsPointOnBoundary(const Standard_Real theParameter,
3112                                    const Standard_Real theFirstBoundary,
3113                                    const Standard_Real theSecondBoundary,
3114                                    const Standard_Real theResolution,
3115                                    Standard_Boolean&   IsOnFirstBoundary) 
3116 {
3117   Standard_Boolean bRet;
3118   Standard_Integer i;
3119   Standard_Real adist;
3120   //
3121   bRet=Standard_False;
3122   for(i = 0; i < 2; ++i) {
3123     IsOnFirstBoundary = (i == 0);
3124     if (IsOnFirstBoundary) {
3125       adist = fabs(theParameter - theFirstBoundary);
3126     }
3127     else {
3128       adist = fabs(theParameter - theSecondBoundary);
3129     }
3130     if(adist < theResolution) {
3131       return !bRet;
3132     }
3133   }
3134   return bRet;
3135 }
3136 // ------------------------------------------------------------------------------------------------
3137 // static function: FindPoint
3138 // purpose:
3139 // ------------------------------------------------------------------------------------------------
3140 Standard_Boolean FindPoint(const gp_Pnt2d&     theFirstPoint,
3141                            const gp_Pnt2d&     theLastPoint,
3142                            const Standard_Real theUmin, 
3143                            const Standard_Real theUmax,
3144                            const Standard_Real theVmin,
3145                            const Standard_Real theVmax,
3146                            gp_Pnt2d&           theNewPoint) {
3147   
3148   gp_Vec2d aVec(theFirstPoint, theLastPoint);
3149   Standard_Integer i = 0, j = 0;
3150
3151   for(i = 0; i < 4; i++) {
3152     gp_Vec2d anOtherVec;
3153     gp_Vec2d anOtherVecNormal;
3154     gp_Pnt2d aprojpoint = theLastPoint;    
3155
3156     if((i % 2) == 0) {
3157       anOtherVec.SetX(0.);
3158       anOtherVec.SetY(1.);
3159       anOtherVecNormal.SetX(1.);
3160       anOtherVecNormal.SetY(0.);
3161
3162       if(i < 2)
3163         aprojpoint.SetX(theUmin);
3164       else
3165         aprojpoint.SetX(theUmax);
3166     }
3167     else {
3168       anOtherVec.SetX(1.);
3169       anOtherVec.SetY(0.);
3170       anOtherVecNormal.SetX(0.);
3171       anOtherVecNormal.SetY(1.);
3172
3173       if(i < 2)
3174         aprojpoint.SetY(theVmin);
3175       else
3176         aprojpoint.SetY(theVmax);
3177     }
3178     gp_Vec2d anormvec = aVec;
3179     anormvec.Normalize();
3180     RefineVector(anormvec);
3181     Standard_Real adot1 = anormvec.Dot(anOtherVecNormal);
3182
3183     if(fabs(adot1) < Precision::Angular())
3184       continue;
3185     Standard_Real adist = 0.;
3186     Standard_Boolean bIsOut = Standard_False;
3187
3188     if((i % 2) == 0) {
3189       adist = (i < 2) ? fabs(theLastPoint.X() - theUmin) : fabs(theLastPoint.X() - theUmax);
3190       bIsOut = (i < 2) ? (theLastPoint.X() < theUmin) : (theLastPoint.X() > theUmax);
3191     }
3192     else {
3193       adist = (i < 2) ? fabs(theLastPoint.Y() - theVmin) : fabs(theLastPoint.Y() - theVmax);
3194       bIsOut = (i < 2) ? (theLastPoint.Y() < theVmin) : (theLastPoint.Y() > theVmax);
3195     }
3196     Standard_Real anoffset = adist * anOtherVec.Dot(anormvec) / adot1;
3197
3198     for(j = 0; j < 2; j++) {
3199       anoffset = (j == 0) ? anoffset : -anoffset;
3200       gp_Pnt2d acurpoint(aprojpoint.XY() + (anOtherVec.XY()*anoffset));
3201       gp_Vec2d acurvec(theLastPoint, acurpoint);
3202       if ( bIsOut )
3203         acurvec.Reverse();
3204
3205       Standard_Real aDotX, anAngleX;
3206       //
3207       aDotX = aVec.Dot(acurvec);
3208       anAngleX = aVec.Angle(acurvec);
3209       //
3210       if(aDotX > 0. && fabs(anAngleX) < Precision::PConfusion()) {
3211         if((i % 2) == 0) {
3212           if((acurpoint.Y() >= theVmin) &&
3213              (acurpoint.Y() <= theVmax)) {
3214             theNewPoint = acurpoint;
3215             return Standard_True;
3216           }
3217         }
3218         else {
3219           if((acurpoint.X() >= theUmin) &&
3220              (acurpoint.X() <= theUmax)) {
3221             theNewPoint = acurpoint;
3222             return Standard_True;
3223           }
3224         }
3225       }
3226     }
3227   }
3228   return Standard_False;
3229 }
3230
3231
3232 // ------------------------------------------------------------------------------------------------
3233 // static function: FindPoint
3234 // purpose: Find point on the boundary of radial tangent zone
3235 // ------------------------------------------------------------------------------------------------
3236 Standard_Boolean FindPoint(const gp_Pnt2d&     theFirstPoint,
3237                            const gp_Pnt2d&     theLastPoint,
3238                            const Standard_Real theUmin, 
3239                            const Standard_Real theUmax,
3240                            const Standard_Real theVmin,
3241                            const Standard_Real theVmax,
3242                            const gp_Pnt2d&     theTanZoneCenter,
3243                            const Standard_Real theZoneRadius,
3244                            Handle(GeomAdaptor_HSurface) theGASurface,
3245                            gp_Pnt2d&           theNewPoint) {
3246   theNewPoint = theLastPoint;
3247
3248   if ( !IsInsideTanZone( theLastPoint, theTanZoneCenter, theZoneRadius, theGASurface) )
3249     return Standard_False;
3250
3251   Standard_Real aUResolution = theGASurface->UResolution( theZoneRadius );
3252   Standard_Real aVResolution = theGASurface->VResolution( theZoneRadius );
3253
3254   Standard_Real aRadius = ( aUResolution < aVResolution ) ? aUResolution : aVResolution;
3255   gp_Ax22d anAxis( theTanZoneCenter, gp_Dir2d(1, 0), gp_Dir2d(0, 1) );
3256   gp_Circ2d aCircle( anAxis, aRadius );
3257   
3258   //
3259   gp_Vec2d aDir( theLastPoint.XY() - theFirstPoint.XY() );
3260   Standard_Real aLength = aDir.Magnitude();
3261   if ( aLength <= gp::Resolution() )
3262     return Standard_False;
3263   gp_Lin2d aLine( theFirstPoint, aDir );
3264
3265   //
3266   Handle(Geom2d_Line) aCLine = new Geom2d_Line( aLine );
3267   Handle(Geom2d_TrimmedCurve) aC1 = new Geom2d_TrimmedCurve( aCLine, 0, aLength );
3268   Handle(Geom2d_Circle) aC2 = new Geom2d_Circle( aCircle );
3269
3270   Standard_Real aTol = aRadius * 0.001;
3271   aTol = ( aTol < Precision::PConfusion() ) ? Precision::PConfusion() : aTol;
3272
3273   Geom2dAPI_InterCurveCurve anIntersector;
3274   anIntersector.Init( aC1, aC2, aTol );
3275
3276   if ( anIntersector.NbPoints() == 0 )
3277     return Standard_False;
3278
3279   Standard_Boolean aFound = Standard_False;
3280   Standard_Real aMinDist = aLength * aLength;
3281   Standard_Integer i = 0;
3282   for ( i = 1; i <= anIntersector.NbPoints(); i++ ) {
3283     gp_Pnt2d aPInt = anIntersector.Point( i );
3284     if ( aPInt.SquareDistance( theFirstPoint ) < aMinDist ) {
3285       if ( ( aPInt.X() >= theUmin ) && ( aPInt.X() <= theUmax ) &&
3286            ( aPInt.Y() >= theVmin ) && ( aPInt.Y() <= theVmax ) ) {
3287         theNewPoint = aPInt;
3288         aFound = Standard_True;
3289       }
3290     }
3291   }
3292
3293   return aFound;
3294 }
3295
3296 // ------------------------------------------------------------------------------------------------
3297 // static function: IsInsideTanZone
3298 // purpose: Check if point is inside a radial tangent zone
3299 // ------------------------------------------------------------------------------------------------
3300 Standard_Boolean IsInsideTanZone(const gp_Pnt2d&     thePoint,
3301                                  const gp_Pnt2d&     theTanZoneCenter,
3302                                  const Standard_Real theZoneRadius,
3303                                  Handle(GeomAdaptor_HSurface) theGASurface) {
3304
3305   Standard_Real aUResolution = theGASurface->UResolution( theZoneRadius );
3306   Standard_Real aVResolution = theGASurface->VResolution( theZoneRadius );
3307   Standard_Real aRadiusSQR = ( aUResolution < aVResolution ) ? aUResolution : aVResolution;
3308   aRadiusSQR *= aRadiusSQR;
3309   if ( thePoint.SquareDistance( theTanZoneCenter ) <= aRadiusSQR )
3310     return Standard_True;
3311   return Standard_False;
3312 }
3313
3314 // ------------------------------------------------------------------------------------------------
3315 // static function: CheckTangentZonesExist
3316 // purpose: Check if tangent zone exists
3317 // ------------------------------------------------------------------------------------------------
3318 Standard_Boolean CheckTangentZonesExist( const Handle(GeomAdaptor_HSurface)& theSurface1,
3319                                         const Handle(GeomAdaptor_HSurface)&  theSurface2 ) 
3320 {
3321   if ( ( theSurface1->GetType() != GeomAbs_Torus ) ||
3322       ( theSurface2->GetType() != GeomAbs_Torus ) )
3323     return Standard_False;
3324
3325   gp_Torus aTor1 = theSurface1->Torus();
3326   gp_Torus aTor2 = theSurface2->Torus();
3327
3328   if ( aTor1.Location().Distance( aTor2.Location() ) > Precision::Confusion() )
3329     return Standard_False;
3330
3331   if ( ( fabs( aTor1.MajorRadius() - aTor2.MajorRadius() ) > Precision::Confusion() ) ||
3332        ( fabs( aTor1.MinorRadius() - aTor2.MinorRadius() ) > Precision::Confusion() ) )
3333     return Standard_False;
3334
3335   if ( ( aTor1.MajorRadius() < aTor1.MinorRadius() ) ||
3336        ( aTor2.MajorRadius() < aTor2.MinorRadius() ) )
3337     return Standard_False;
3338   return Standard_True;
3339 }
3340
3341 // ------------------------------------------------------------------------------------------------
3342 // static function: ComputeTangentZones
3343 // purpose: 
3344 // ------------------------------------------------------------------------------------------------
3345 Standard_Integer ComputeTangentZones( const Handle(GeomAdaptor_HSurface)& theSurface1,
3346                                      const Handle(GeomAdaptor_HSurface)&  theSurface2,
3347                                      const TopoDS_Face&                   theFace1,
3348                                      const TopoDS_Face&                   theFace2,
3349                                      Handle(TColgp_HArray1OfPnt2d)&       theResultOnS1,
3350                                      Handle(TColgp_HArray1OfPnt2d)&       theResultOnS2,
3351                                      Handle(TColStd_HArray1OfReal)&       theResultRadius,
3352                                      const Handle(IntTools_Context)& aContext)
3353 {
3354   Standard_Integer aResult = 0;
3355   if ( !CheckTangentZonesExist( theSurface1, theSurface2 ) )
3356     return aResult;
3357
3358
3359   TColgp_SequenceOfPnt2d aSeqResultS1, aSeqResultS2;
3360   TColStd_SequenceOfReal aSeqResultRad;
3361
3362   gp_Torus aTor1 = theSurface1->Torus();
3363   gp_Torus aTor2 = theSurface2->Torus();
3364
3365   gp_Ax2 anax1( aTor1.Location(), aTor1.Axis().Direction() );
3366   gp_Ax2 anax2( aTor2.Location(), aTor2.Axis().Direction() );
3367   Standard_Integer j = 0;
3368
3369   for ( j = 0; j < 2; j++ ) {
3370     Standard_Real aCoef = ( j == 0 ) ? -1 : 1;
3371     Standard_Real aRadius1 = fabs(aTor1.MajorRadius() + aCoef * aTor1.MinorRadius());
3372     Standard_Real aRadius2 = fabs(aTor2.MajorRadius() + aCoef * aTor2.MinorRadius());
3373
3374     gp_Circ aCircle1( anax1, aRadius1 );
3375     gp_Circ aCircle2( anax2, aRadius2 );
3376
3377     // roughly compute radius of tangent zone for perpendicular case
3378     Standard_Real aCriteria = Precision::Confusion() * 0.5;
3379
3380     Standard_Real aT1 = aCriteria;
3381     Standard_Real aT2 = aCriteria;
3382     if ( j == 0 ) {
3383       // internal tangency
3384       Standard_Real aR = ( aRadius1 > aTor2.MinorRadius() ) ? aRadius1 : aTor2.MinorRadius();
3385       //aT1 = aCriteria * aCriteria + aR * aR - ( aR - aCriteria ) * ( aR - aCriteria );
3386       aT1 = 2. * aR * aCriteria;
3387       aT2 = aT1;
3388     }
3389     else {
3390       // external tangency
3391       Standard_Real aRb = ( aRadius1 > aTor2.MinorRadius() ) ? aRadius1 : aTor2.MinorRadius();
3392       Standard_Real aRm = ( aRadius1 < aTor2.MinorRadius() ) ? aRadius1 : aTor2.MinorRadius();
3393       Standard_Real aDelta = aRb - aCriteria;
3394       aDelta *= aDelta;
3395       aDelta -= aRm * aRm;
3396       aDelta /= 2. * (aRb - aRm);
3397       aDelta -= 0.5 * (aRb - aRm);
3398       
3399       aT1 = 2. * aRm * (aRm - aDelta);
3400       aT2 = aT1;
3401     }
3402     aCriteria = ( aT1 > aT2) ? aT1 : aT2;
3403     if ( aCriteria > 0 )
3404       aCriteria = sqrt( aCriteria );
3405
3406     if ( aCriteria > 0.5 * aTor1.MinorRadius() ) {
3407       // too big zone -> drop to minimum
3408       aCriteria = Precision::Confusion();
3409     }
3410
3411     GeomAdaptor_Curve aC1( new Geom_Circle(aCircle1) );
3412     GeomAdaptor_Curve aC2( new Geom_Circle(aCircle2) );
3413     Extrema_ExtCC anExtrema(aC1, aC2, 0, 2. * M_PI, 0, 2. * M_PI, 
3414                             Precision::PConfusion(), Precision::PConfusion());
3415             
3416     if ( anExtrema.IsDone() ) {
3417
3418       Standard_Integer i = 0;
3419       for ( i = 1; i <= anExtrema.NbExt(); i++ ) {
3420         if ( anExtrema.SquareDistance(i) > aCriteria * aCriteria )
3421           continue;
3422
3423         Extrema_POnCurv P1, P2;
3424         anExtrema.Points( i, P1, P2 );
3425
3426         Standard_Boolean bFoundResult = Standard_True;
3427         gp_Pnt2d pr1, pr2;
3428
3429         Standard_Integer surfit = 0;
3430         for ( surfit = 0; surfit < 2; surfit++ ) {
3431           GeomAPI_ProjectPointOnSurf& aProjector = 
3432             (surfit == 0) ? aContext->ProjPS(theFace1) : aContext->ProjPS(theFace2);
3433
3434           gp_Pnt aP3d = (surfit == 0) ? P1.Value() : P2.Value();
3435           aProjector.Perform(aP3d);
3436
3437           if(!aProjector.IsDone())
3438             bFoundResult = Standard_False;
3439           else {
3440             if(aProjector.LowerDistance() > aCriteria) {
3441               bFoundResult = Standard_False;
3442             }
3443             else {
3444               Standard_Real foundU = 0, foundV = 0;
3445               aProjector.LowerDistanceParameters(foundU, foundV);
3446               if ( surfit == 0 )
3447                 pr1 = gp_Pnt2d( foundU, foundV );
3448               else
3449                 pr2 = gp_Pnt2d( foundU, foundV );
3450             }
3451           }
3452         }
3453         if ( bFoundResult ) {
3454           aSeqResultS1.Append( pr1 );
3455           aSeqResultS2.Append( pr2 );
3456           aSeqResultRad.Append( aCriteria );
3457
3458           // torus is u and v periodic
3459           const Standard_Real twoPI = M_PI + M_PI;
3460           Standard_Real arr1tmp[2] = {pr1.X(), pr1.Y()};
3461           Standard_Real arr2tmp[2] = {pr2.X(), pr2.Y()};
3462
3463           // iteration on period bounds
3464           for ( Standard_Integer k1 = 0; k1 < 2; k1++ ) {
3465             Standard_Real aBound = ( k1 == 0 ) ? 0 : twoPI;
3466             Standard_Real aShift = ( k1 == 0 ) ? twoPI : -twoPI;
3467
3468             // iteration on surfaces
3469             for ( Standard_Integer k2 = 0; k2 < 2; k2++ ) {
3470               Standard_Real* arr1 = ( k2 == 0 ) ? arr1tmp : arr2tmp;
3471               Standard_Real* arr2 = ( k2 != 0 ) ? arr1tmp : arr2tmp;
3472               TColgp_SequenceOfPnt2d& aSeqS1 = ( k2 == 0 ) ? aSeqResultS1 : aSeqResultS2; 
3473               TColgp_SequenceOfPnt2d& aSeqS2 = ( k2 != 0 ) ? aSeqResultS1 : aSeqResultS2; 
3474
3475               if (fabs(arr1[0] - aBound) < Precision::PConfusion()) {
3476                 aSeqS1.Append( gp_Pnt2d( arr1[0] + aShift, arr1[1] ) );
3477                 aSeqS2.Append( gp_Pnt2d( arr2[0], arr2[1] ) );
3478                 aSeqResultRad.Append( aCriteria );
3479               }
3480               if (fabs(arr1[1] - aBound) < Precision::PConfusion()) {
3481                 aSeqS1.Append( gp_Pnt2d( arr1[0], arr1[1] + aShift) );
3482                 aSeqS2.Append( gp_Pnt2d( arr2[0], arr2[1] ) );
3483                 aSeqResultRad.Append( aCriteria );
3484               }
3485             }
3486           } //
3487         }
3488       }
3489     }
3490   }
3491   aResult = aSeqResultRad.Length();
3492
3493   if ( aResult > 0 ) {
3494     theResultOnS1 = new TColgp_HArray1OfPnt2d( 1, aResult );
3495     theResultOnS2 = new TColgp_HArray1OfPnt2d( 1, aResult );
3496     theResultRadius = new TColStd_HArray1OfReal( 1, aResult );
3497
3498     for ( Standard_Integer i = 1 ; i <= aResult; i++ ) {
3499       theResultOnS1->SetValue( i, aSeqResultS1.Value(i) );
3500       theResultOnS2->SetValue( i, aSeqResultS2.Value(i) );
3501       theResultRadius->SetValue( i, aSeqResultRad.Value(i) );
3502     }
3503   }
3504   return aResult;
3505 }
3506
3507 // ------------------------------------------------------------------------------------------------
3508 // static function: AdjustByNeighbour
3509 // purpose:
3510 // ------------------------------------------------------------------------------------------------
3511 gp_Pnt2d AdjustByNeighbour(const gp_Pnt2d&     theaNeighbourPoint,
3512                            const gp_Pnt2d&     theOriginalPoint,
3513                            Handle(GeomAdaptor_HSurface) theGASurface) {
3514   
3515   gp_Pnt2d ap1 = theaNeighbourPoint;
3516   gp_Pnt2d ap2 = theOriginalPoint;
3517
3518   if ( theGASurface->IsUPeriodic() ) {
3519     Standard_Real aPeriod     = theGASurface->UPeriod();
3520     gp_Pnt2d aPTest = ap2;
3521     Standard_Real aSqDistMin = 1.e+100;
3522
3523     for ( Standard_Integer pIt = -1; pIt <= 1; pIt++) {
3524       aPTest.SetX( theOriginalPoint.X() + aPeriod * pIt );
3525       Standard_Real dd = ap1.SquareDistance( aPTest );
3526
3527       if ( dd < aSqDistMin ) {
3528         ap2 = aPTest;
3529         aSqDistMin = dd;
3530       }
3531     }
3532   }
3533   if ( theGASurface->IsVPeriodic() ) {
3534     Standard_Real aPeriod     = theGASurface->VPeriod();
3535     gp_Pnt2d aPTest = ap2;
3536     Standard_Real aSqDistMin = 1.e+100;
3537
3538     for ( Standard_Integer pIt = -1; pIt <= 1; pIt++) {
3539       aPTest.SetY( theOriginalPoint.Y() + aPeriod * pIt );
3540       Standard_Real dd = ap1.SquareDistance( aPTest );
3541
3542       if ( dd < aSqDistMin ) {
3543         ap2 = aPTest;
3544         aSqDistMin = dd;
3545       }
3546     }
3547   }
3548   return ap2;
3549 }
3550
3551 // ------------------------------------------------------------------------------------------------
3552 //function: DecompositionOfWLine
3553 // purpose:
3554 // ------------------------------------------------------------------------------------------------
3555 Standard_Boolean DecompositionOfWLine(const Handle(IntPatch_WLine)& theWLine,
3556                                       const Handle(GeomAdaptor_HSurface)&            theSurface1, 
3557                                       const Handle(GeomAdaptor_HSurface)&            theSurface2,
3558                                       const TopoDS_Face&                             theFace1,
3559                                       const TopoDS_Face&                             theFace2,
3560                                       const IntTools_LineConstructor&                theLConstructor,
3561                                       const Standard_Boolean                         theAvoidLConstructor,
3562                                       IntPatch_SequenceOfLine&                       theNewLines,
3563                                       Standard_Real&                                 theReachedTol3d,
3564                                       const Handle(IntTools_Context)& aContext) 
3565 {
3566
3567   Standard_Boolean bRet, bAvoidLineConstructor;
3568   Standard_Integer aNbPnts, aNbParts;
3569   //
3570   bRet=Standard_False;
3571   aNbPnts=theWLine->NbPnts();
3572   bAvoidLineConstructor=theAvoidLConstructor;
3573   //
3574   if(!aNbPnts){
3575     return bRet;
3576   }
3577   if (!bAvoidLineConstructor) {
3578     aNbParts=theLConstructor.NbParts();
3579     if (!aNbParts) {
3580       return bRet;
3581     }
3582   }
3583   //
3584   Standard_Boolean bIsPrevPointOnBoundary, bIsPointOnBoundary, bIsCurrentPointOnBoundary;
3585   Standard_Integer nblines, pit, i, j;
3586   Standard_Real aTol;
3587   TColStd_Array1OfListOfInteger anArrayOfLines(1, aNbPnts); 
3588   TColStd_Array1OfInteger       anArrayOfLineType(1, aNbPnts);
3589   TColStd_ListOfInteger aListOfPointIndex;
3590   
3591   Handle(TColgp_HArray1OfPnt2d) aTanZoneS1;
3592   Handle(TColgp_HArray1OfPnt2d) aTanZoneS2;
3593   Handle(TColStd_HArray1OfReal) aTanZoneRadius;
3594   Standard_Integer aNbZone = ComputeTangentZones( theSurface1, theSurface2, theFace1, theFace2,
3595                                                  aTanZoneS1, aTanZoneS2, aTanZoneRadius, aContext);
3596   
3597   //
3598   nblines=0;
3599   aTol=Precision::Confusion();
3600   aTol=0.5*aTol;
3601   bIsPrevPointOnBoundary=Standard_False;
3602   bIsPointOnBoundary=Standard_False;
3603   //
3604   // 1. ...
3605   //
3606   // Points
3607   for(pit = 1; pit <= aNbPnts; ++pit) {
3608     Standard_Boolean bIsOnFirstBoundary, isperiodic;
3609     Standard_Real aResolution, aPeriod, alowerboundary, aupperboundary, U, V;
3610     Standard_Real aParameter, anoffset, anAdjustPar;
3611     Standard_Real umin, umax, vmin, vmax;
3612     //
3613     bIsCurrentPointOnBoundary = Standard_False;
3614     const IntSurf_PntOn2S& aPoint = theWLine->Point(pit);
3615     //
3616     // Surface
3617     for(i = 0; i < 2; ++i) {
3618       Handle(GeomAdaptor_HSurface) aGASurface = (!i) ? theSurface1 : theSurface2;
3619       aGASurface->ChangeSurface().Surface()->Bounds(umin, umax, vmin, vmax);
3620       if(!i) {
3621         aPoint.ParametersOnS1(U, V);
3622       }
3623       else {
3624         aPoint.ParametersOnS2(U, V);
3625       }
3626       // U, V
3627       for(j = 0; j < 2; j++) {
3628         isperiodic = (!j) ? aGASurface->IsUPeriodic() : aGASurface->IsVPeriodic();
3629         if(!isperiodic){
3630           continue;
3631         }
3632         //
3633         if (!j) {
3634           aResolution=aGASurface->UResolution(aTol);
3635           aPeriod=aGASurface->UPeriod();
3636           alowerboundary=umin;
3637           aupperboundary=umax;
3638           aParameter=U;
3639         }
3640         else {
3641           aResolution=aGASurface->VResolution(aTol);
3642           aPeriod=aGASurface->VPeriod();
3643           alowerboundary=vmin;
3644           aupperboundary=vmax;
3645           aParameter=V;
3646         }
3647         
3648         IntTools_Tools::AdjustPeriodic(aParameter, 
3649                                        alowerboundary, 
3650                                        aupperboundary, 
3651                                        aPeriod,
3652                                        anAdjustPar,
3653                                        anoffset);
3654         //
3655         bIsOnFirstBoundary = Standard_True;// ?
3656         bIsPointOnBoundary=
3657           IsPointOnBoundary(anAdjustPar, 
3658                             alowerboundary, 
3659                             aupperboundary,
3660                             aResolution, 
3661                             bIsOnFirstBoundary);
3662         //
3663         if(bIsPointOnBoundary) {
3664           bIsCurrentPointOnBoundary = Standard_True;
3665           break;
3666         }
3667         else {
3668           // check if a point belong to a tangent zone. Begin
3669           Standard_Integer zIt = 0;
3670           for ( zIt = 1; zIt <= aNbZone; zIt++ ) {
3671             gp_Pnt2d aPZone = (i == 0) ? aTanZoneS1->Value(zIt) : aTanZoneS2->Value(zIt);
3672             Standard_Real aZoneRadius = aTanZoneRadius->Value(zIt);
3673
3674             if ( IsInsideTanZone(gp_Pnt2d( U, V ), aPZone, aZoneRadius, aGASurface ) ) {
3675               // set boundary flag to split the curve by a tangent zone
3676               bIsPointOnBoundary = Standard_True;
3677               bIsCurrentPointOnBoundary = Standard_True;
3678               if ( theReachedTol3d < aZoneRadius ) {
3679                 theReachedTol3d = aZoneRadius;
3680               }
3681               break;
3682             }
3683           }
3684         }
3685       }//for(j = 0; j < 2; j++) {
3686
3687       if(bIsCurrentPointOnBoundary){
3688         break;
3689       }
3690     }//for(i = 0; i < 2; ++i) {
3691     //
3692     if((bIsCurrentPointOnBoundary != bIsPrevPointOnBoundary)) {
3693       if(!aListOfPointIndex.IsEmpty()) {
3694         nblines++;
3695         anArrayOfLines.SetValue(nblines, aListOfPointIndex);
3696         anArrayOfLineType.SetValue(nblines, bIsPrevPointOnBoundary);
3697         aListOfPointIndex.Clear();
3698       }
3699       bIsPrevPointOnBoundary = bIsCurrentPointOnBoundary;
3700     }
3701     aListOfPointIndex.Append(pit);
3702   } //for(pit = 1; pit <= aNbPnts; ++pit) {
3703   //
3704   if(!aListOfPointIndex.IsEmpty()) {
3705     nblines++;
3706     anArrayOfLines.SetValue(nblines, aListOfPointIndex);
3707     anArrayOfLineType.SetValue(nblines, bIsPrevPointOnBoundary);
3708     aListOfPointIndex.Clear();
3709   }
3710   //
3711   if(nblines<=1) {
3712     return bRet; //Standard_False;
3713   }
3714   //
3715   // 
3716   // 2. Correct wlines.begin
3717   TColStd_Array1OfListOfInteger anArrayOfLineEnds(1, nblines);
3718   Handle(IntSurf_LineOn2S) aSeqOfPntOn2S = new IntSurf_LineOn2S();
3719   //
3720   for(i = 1; i <= nblines; i++) {
3721     if(anArrayOfLineType.Value(i) != 0) {
3722       continue;
3723     }
3724     const TColStd_ListOfInteger& aListOfIndex = anArrayOfLines.Value(i);
3725     if(aListOfIndex.Extent() < 2) {
3726       continue;
3727     }
3728     TColStd_ListOfInteger aListOfFLIndex;
3729
3730     for(j = 0; j < 2; j++) {
3731       Standard_Integer aneighbourindex = (j == 0) ? (i - 1) : (i + 1);
3732
3733       if((aneighbourindex < 1) || (aneighbourindex > nblines))
3734         continue;
3735
3736       if(anArrayOfLineType.Value(aneighbourindex) == 0)
3737         continue;
3738       const TColStd_ListOfInteger& aNeighbour = anArrayOfLines.Value(aneighbourindex);
3739       Standard_Integer anIndex = (j == 0) ? aNeighbour.Last() : aNeighbour.First();
3740       const IntSurf_PntOn2S& aPoint = theWLine->Point(anIndex);
3741
3742       IntSurf_PntOn2S aNewP = aPoint;
3743       
3744       for(Standard_Integer surfit = 0; surfit < 2; surfit++) {
3745
3746         Handle(GeomAdaptor_HSurface) aGASurface = (surfit == 0) ? theSurface1 : theSurface2;
3747         Standard_Real umin=0., umax=0., vmin=0., vmax=0.;
3748         aGASurface->ChangeSurface().Surface()->Bounds(umin, umax, vmin, vmax);
3749         Standard_Real U=0., V=0.;
3750
3751         if(surfit == 0)
3752           aNewP.ParametersOnS1(U, V);
3753         else
3754           aNewP.ParametersOnS2(U, V);
3755         Standard_Integer nbboundaries = 0;
3756
3757         Standard_Boolean bIsNearBoundary = Standard_False;
3758         Standard_Integer aZoneIndex = 0;
3759         Standard_Integer bIsUBoundary = Standard_False; // use if nbboundaries == 1
3760         Standard_Integer bIsFirstBoundary = Standard_False; // use if nbboundaries == 1
3761         
3762
3763         for(Standard_Integer parit = 0; parit < 2; parit++) {
3764           Standard_Boolean isperiodic = (parit == 0) ? aGASurface->IsUPeriodic() : aGASurface->IsVPeriodic();
3765
3766           Standard_Real aResolution = (parit == 0) ? aGASurface->UResolution(aTol) : aGASurface->VResolution(aTol);
3767           Standard_Real alowerboundary = (parit == 0) ? umin : vmin;
3768           Standard_Real aupperboundary = (parit == 0) ? umax : vmax;
3769
3770           Standard_Real aParameter = (parit == 0) ? U : V;
3771           Standard_Boolean bIsOnFirstBoundary = Standard_True;
3772   
3773           if(!isperiodic) {
3774             bIsPointOnBoundary=
3775               IsPointOnBoundary(aParameter, alowerboundary, aupperboundary, aResolution, bIsOnFirstBoundary);
3776             if(bIsPointOnBoundary) {
3777               bIsUBoundary = (parit == 0);
3778               bIsFirstBoundary = bIsOnFirstBoundary;
3779               nbboundaries++;
3780             }
3781           }
3782           else {
3783             Standard_Real aPeriod     = (parit == 0) ? aGASurface->UPeriod() : aGASurface->VPeriod();
3784             Standard_Real anoffset, anAdjustPar;
3785             IntTools_Tools::AdjustPeriodic(aParameter, alowerboundary, aupperboundary,
3786                                            aPeriod, anAdjustPar, anoffset);
3787
3788             bIsPointOnBoundary=
3789               IsPointOnBoundary(anAdjustPar, alowerboundary, aupperboundary, aResolution, bIsOnFirstBoundary);
3790             if(bIsPointOnBoundary) {
3791               bIsUBoundary = (parit == 0);
3792               bIsFirstBoundary = bIsOnFirstBoundary;
3793               nbboundaries++;
3794             }
3795             else {
3796               //check neighbourhood of boundary
3797               Standard_Real anEpsilon = aResolution * 100.;
3798               Standard_Real aPart = ( aupperboundary - alowerboundary ) * 0.1;
3799               anEpsilon = ( anEpsilon > aPart ) ? aPart : anEpsilon;
3800                 
3801               bIsNearBoundary = IsPointOnBoundary(anAdjustPar, alowerboundary, aupperboundary, 
3802                                                   anEpsilon, bIsOnFirstBoundary);
3803
3804             }
3805           }
3806         }
3807
3808         // check if a point belong to a tangent zone. Begin
3809         for ( Standard_Integer zIt = 1; zIt <= aNbZone; zIt++ ) {
3810           gp_Pnt2d aPZone = (surfit == 0) ? aTanZoneS1->Value(zIt) : aTanZoneS2->Value(zIt);
3811           Standard_Real aZoneRadius = aTanZoneRadius->Value(zIt);
3812
3813           Standard_Integer aneighbourpointindex1 = (j == 0) ? aListOfIndex.First() : aListOfIndex.Last();
3814           const IntSurf_PntOn2S& aNeighbourPoint = theWLine->Point(aneighbourpointindex1);
3815           Standard_Real nU1, nV1;
3816             
3817           if(surfit == 0)
3818             aNeighbourPoint.ParametersOnS1(nU1, nV1);
3819           else
3820             aNeighbourPoint.ParametersOnS2(nU1, nV1);
3821           gp_Pnt2d ap1(nU1, nV1);
3822           gp_Pnt2d ap2 = AdjustByNeighbour( ap1, gp_Pnt2d( U, V ), aGASurface );
3823
3824
3825           if ( IsInsideTanZone( ap2, aPZone, aZoneRadius, aGASurface ) ) {
3826             aZoneIndex = zIt;
3827             bIsNearBoundary = Standard_True;
3828             if ( theReachedTol3d < aZoneRadius ) {
3829               theReachedTol3d = aZoneRadius;
3830             }
3831           }
3832         }
3833         // check if a point belong to a tangent zone. End
3834         Standard_Boolean bComputeLineEnd = Standard_False;
3835
3836         if(nbboundaries == 2) {
3837           //xf
3838           bComputeLineEnd = Standard_True;
3839           //xt
3840         }
3841         else if(nbboundaries == 1) {
3842           Standard_Boolean isperiodic = (bIsUBoundary) ? aGASurface->IsUPeriodic() : aGASurface->IsVPeriodic();
3843
3844           if(isperiodic) {
3845             Standard_Real alowerboundary = (bIsUBoundary) ? umin : vmin;
3846             Standard_Real aupperboundary = (bIsUBoundary) ? umax : vmax;
3847             Standard_Real aPeriod     = (bIsUBoundary) ? aGASurface->UPeriod() : aGASurface->VPeriod();
3848             Standard_Real aParameter = (bIsUBoundary) ? U : V;
3849             Standard_Real anoffset, anAdjustPar;
3850             IntTools_Tools::AdjustPeriodic(aParameter, alowerboundary, aupperboundary, 
3851                                            aPeriod, anAdjustPar, anoffset);
3852
3853             Standard_Real adist = (bIsFirstBoundary) ? fabs(anAdjustPar - alowerboundary) : fabs(anAdjustPar - aupperboundary);
3854             Standard_Real anotherPar = (bIsFirstBoundary) ? (aupperboundary - adist) : (alowerboundary + adist);
3855             anotherPar += anoffset;
3856             Standard_Integer aneighbourpointindex = (j == 0) ? aListOfIndex.First() : aListOfIndex.Last();
3857             const IntSurf_PntOn2S& aNeighbourPoint = theWLine->Point(aneighbourpointindex);
3858             Standard_Real nU1, nV1;
3859
3860             if(surfit == 0)
3861               aNeighbourPoint.ParametersOnS1(nU1, nV1);
3862             else
3863               aNeighbourPoint.ParametersOnS2(nU1, nV1);
3864             
3865             Standard_Real adist1 = (bIsUBoundary) ? fabs(nU1 - U) : fabs(nV1 - V);
3866             Standard_Real adist2 = (bIsUBoundary) ? fabs(nU1 - anotherPar) : fabs(nV1 - anotherPar);
3867             bComputeLineEnd = Standard_True;
3868             Standard_Boolean bCheckAngle1 = Standard_False;
3869             Standard_Boolean bCheckAngle2 = Standard_False;
3870             gp_Vec2d aNewVec;
3871             Standard_Real anewU = (bIsUBoundary) ? anotherPar : U;
3872             Standard_Real anewV = (bIsUBoundary) ? V : anotherPar;
3873
3874             if(((adist1 - adist2) > Precision::PConfusion()) && 
3875                (adist2 < (aPeriod / 4.))) {
3876               bCheckAngle1 = Standard_True;
3877               aNewVec = gp_Vec2d(gp_Pnt2d(nU1, nV1), gp_Pnt2d(anewU, anewV));
3878
3879               if(aNewVec.SquareMagnitude() < (gp::Resolution() * gp::Resolution())) {
3880                 aNewP.SetValue((surfit == 0), anewU, anewV);
3881                 bCheckAngle1 = Standard_False;
3882               }
3883             }
3884             else if(adist1 < (aPeriod / 4.)) {
3885               bCheckAngle2 = Standard_True;
3886               aNewVec = gp_Vec2d(gp_Pnt2d(nU1, nV1), gp_Pnt2d(U, V));
3887
3888               if(aNewVec.SquareMagnitude() < (gp::Resolution() * gp::Resolution())) {
3889                 bCheckAngle2 = Standard_False;
3890               }
3891             }
3892
3893             if(bCheckAngle1 || bCheckAngle2) {
3894               // assume there are at least two points in line (see "if" above)
3895               Standard_Integer anindexother = aneighbourpointindex;
3896
3897               while((anindexother <= aListOfIndex.Last()) && (anindexother >= aListOfIndex.First())) {
3898                 anindexother = (j == 0) ? (anindexother + 1) : (anindexother - 1);
3899                 const IntSurf_PntOn2S& aPrevNeighbourPoint = theWLine->Point(anindexother);
3900                 Standard_Real nU2, nV2;
3901                 
3902                 if(surfit == 0)
3903                   aPrevNeighbourPoint.ParametersOnS1(nU2, nV2);
3904                 else
3905                   aPrevNeighbourPoint.ParametersOnS2(nU2, nV2);
3906                 gp_Vec2d aVecOld(gp_Pnt2d(nU2, nV2), gp_Pnt2d(nU1, nV1));
3907
3908                 if(aVecOld.SquareMagnitude() <= (gp::Resolution() * gp::Resolution())) {
3909                   continue;
3910                 }
3911                 else {
3912                   Standard_Real anAngle = aNewVec.Angle(aVecOld);
3913
3914                   if((fabs(anAngle) < (M_PI * 0.25)) && (aNewVec.Dot(aVecOld) > 0.)) {
3915
3916                     if(bCheckAngle1) {
3917                       Standard_Real U1, U2, V1, V2;
3918                       IntSurf_PntOn2S atmppoint = aNewP;
3919                       atmppoint.SetValue((surfit == 0), anewU, anewV);
3920                       atmppoint.Parameters(U1, V1, U2, V2);
3921                       gp_Pnt P1 = theSurface1->Value(U1, V1);
3922                       gp_Pnt P2 = theSurface2->Value(U2, V2);
3923                       gp_Pnt P0 = aPoint.Value();
3924
3925                       if(P0.IsEqual(P1, aTol) &&
3926                          P0.IsEqual(P2, aTol) &&
3927                          P1.IsEqual(P2, aTol)) {
3928                         bComputeLineEnd = Standard_False;
3929                         aNewP.SetValue((surfit == 0), anewU, anewV);
3930                       }
3931                     }
3932
3933                     if(bCheckAngle2) {
3934                       bComputeLineEnd = Standard_False;
3935                     }
3936                   }
3937                   break;
3938                 }
3939               } // end while(anindexother...)
3940             }
3941           }
3942         }
3943         else if ( bIsNearBoundary ) {
3944           bComputeLineEnd = Standard_True;
3945         }
3946
3947         if(bComputeLineEnd) {
3948
3949           gp_Pnt2d anewpoint;
3950           Standard_Boolean found = Standard_False;
3951
3952           if ( bIsNearBoundary ) {
3953             // re-compute point near natural boundary or near tangent zone
3954             Standard_Real u1, v1, u2, v2;
3955             aNewP.Parameters( u1, v1, u2, v2 );
3956             if(surfit == 0)
3957               anewpoint = gp_Pnt2d( u1, v1 );
3958             else
3959               anewpoint = gp_Pnt2d( u2, v2 );
3960             
3961             Standard_Integer aneighbourpointindex1 = (j == 0) ? aListOfIndex.First() : aListOfIndex.Last();
3962             const IntSurf_PntOn2S& aNeighbourPoint = theWLine->Point(aneighbourpointindex1);
3963             Standard_Real nU1, nV1;
3964             
3965             if(surfit == 0)
3966               aNeighbourPoint.ParametersOnS1(nU1, nV1);
3967             else
3968               aNeighbourPoint.ParametersOnS2(nU1, nV1);
3969             gp_Pnt2d ap1(nU1, nV1);
3970             gp_Pnt2d ap2;
3971
3972
3973             if ( aZoneIndex ) {
3974               // exclude point from a tangent zone
3975               anewpoint = AdjustByNeighbour( ap1, anewpoint, aGASurface );
3976               gp_Pnt2d aPZone = (surfit == 0) ? aTanZoneS1->Value(aZoneIndex) : aTanZoneS2->Value(aZoneIndex);
3977               Standard_Real aZoneRadius = aTanZoneRadius->Value(aZoneIndex);
3978
3979               if ( FindPoint(ap1, anewpoint, umin, umax, vmin, vmax, 
3980                              aPZone, aZoneRadius, aGASurface, ap2) ) {
3981                 anewpoint = ap2;
3982                 found = Standard_True;
3983               }
3984             }
3985             else if ( aGASurface->IsUPeriodic() || aGASurface->IsVPeriodic() ) {
3986               // re-compute point near boundary if shifted on a period
3987               ap2 = AdjustByNeighbour( ap1, anewpoint, aGASurface );
3988
3989               if ( ( ap2.X() < umin ) || ( ap2.X() > umax ) ||
3990                   ( ap2.Y() < vmin ) || ( ap2.Y() > vmax ) ) {
3991                 found = FindPoint(ap1, ap2, umin, umax, vmin, vmax, anewpoint);
3992               }
3993               else {
3994                 anewpoint = ap2;
3995                 aNewP.SetValue( (surfit == 0), anewpoint.X(), anewpoint.Y() );
3996               }
3997             }
3998           }
3999           else {
4000
4001             Standard_Integer aneighbourpointindex1 = (j == 0) ? aListOfIndex.First() : aListOfIndex.Last();
4002             const IntSurf_PntOn2S& aNeighbourPoint = theWLine->Point(aneighbourpointindex1);
4003             Standard_Real nU1, nV1;
4004
4005             if(surfit == 0)
4006               aNeighbourPoint.ParametersOnS1(nU1, nV1);
4007             else
4008               aNeighbourPoint.ParametersOnS2(nU1, nV1);
4009             gp_Pnt2d ap1(nU1, nV1);
4010             gp_Pnt2d ap2(nU1, nV1);
4011             Standard_Integer aneighbourpointindex2 = aneighbourpointindex1;
4012
4013             while((aneighbourpointindex2 <= aListOfIndex.Last()) && (aneighbourpointindex2 >= aListOfIndex.First())) {
4014               aneighbourpointindex2 = (j == 0) ? (aneighbourpointindex2 + 1) : (aneighbourpointindex2 - 1);
4015               const IntSurf_PntOn2S& aPrevNeighbourPoint = theWLine->Point(aneighbourpointindex2);
4016               Standard_Real nU2, nV2;
4017
4018               if(surfit == 0)
4019                 aPrevNeighbourPoint.ParametersOnS1(nU2, nV2);
4020               else
4021                 aPrevNeighbourPoint.ParametersOnS2(nU2, nV2);
4022               ap2.SetX(nU2);
4023               ap2.SetY(nV2);
4024
4025               if(ap1.SquareDistance(ap2) > (gp::Resolution() * gp::Resolution())) {
4026                 break;
4027               }
4028             }  
4029             found = FindPoint(ap2, ap1, umin, umax, vmin, vmax, anewpoint);
4030           }
4031
4032           if(found) {
4033             // check point
4034             Standard_Real aCriteria = BRep_Tool::Tolerance(theFace1) + BRep_Tool::Tolerance(theFace2);
4035             GeomAPI_ProjectPointOnSurf& aProjector = 
4036               (surfit == 0) ? aContext->ProjPS(theFace2) : aContext->ProjPS(theFace1);
4037             Handle(GeomAdaptor_HSurface) aSurface = (surfit == 0) ? theSurface1 : theSurface2;
4038
4039             Handle(GeomAdaptor_HSurface) aSurfaceOther = (surfit == 0) ? theSurface2 : theSurface1;
4040
4041             gp_Pnt aP3d = aSurface->Value(anewpoint.X(), anewpoint.Y());
4042             aProjector.Perform(aP3d);
4043
4044             if(aProjector.IsDone()) {
4045               if(aProjector.LowerDistance() < aCriteria) {
4046                 Standard_Real foundU = U, foundV = V;
4047                 aProjector.LowerDistanceParameters(foundU, foundV);
4048
4049                 //Correction of projected coordinates. Begin
4050                 //Note, it may be shifted on a period
4051                 Standard_Integer aneindex1 = (j == 0) ? aListOfIndex.First() : aListOfIndex.Last();
4052                 const IntSurf_PntOn2S& aNeighbourPoint = theWLine->Point(aneindex1);
4053                 Standard_Real nUn, nVn;
4054                 
4055                 if(surfit == 0)
4056                   aNeighbourPoint.ParametersOnS2(nUn, nVn);
4057                 else
4058                   aNeighbourPoint.ParametersOnS1(nUn, nVn);
4059                 gp_Pnt2d aNeighbour2d(nUn, nVn);
4060                 gp_Pnt2d anAdjustedPoint = AdjustByNeighbour( aNeighbour2d, gp_Pnt2d(foundU, foundV), aSurfaceOther );
4061                 foundU = anAdjustedPoint.X();
4062                 foundV = anAdjustedPoint.Y();
4063
4064                 if ( ( anAdjustedPoint.X() < umin ) && ( anAdjustedPoint.X() > umax ) &&
4065                     ( anAdjustedPoint.Y() < vmin ) && ( anAdjustedPoint.Y() > vmax ) ) {
4066                   // attempt to roughly re-compute point
4067                   foundU = ( foundU < umin ) ? umin : foundU;
4068                   foundU = ( foundU > umax ) ? umax : foundU;
4069                   foundV = ( foundV < vmin ) ? vmin : foundV;
4070                   foundV = ( foundV > vmax ) ? vmax : foundV;
4071
4072                   GeomAPI_ProjectPointOnSurf& aProjector2 = 
4073                     (surfit == 0) ? aContext->ProjPS(theFace1) : aContext->ProjPS(theFace2);
4074
4075                   aP3d = aSurfaceOther->Value(foundU, foundV);
4076                   aProjector2.Perform(aP3d);
4077                   
4078                   if(aProjector2.IsDone()) {
4079                     if(aProjector2.LowerDistance() < aCriteria) {
4080                       Standard_Real foundU2 = anewpoint.X(), foundV2 = anewpoint.Y();
4081                       aProjector2.LowerDistanceParameters(foundU2, foundV2);
4082                       anewpoint.SetX(foundU2);
4083                       anewpoint.SetY(foundV2);
4084                     }
4085                   }
4086                 }
4087                 //Correction of projected coordinates. End
4088
4089                 if(surfit == 0)
4090                   aNewP.SetValue(aP3d, anewpoint.X(), anewpoint.Y(), foundU, foundV);
4091                 else
4092                   aNewP.SetValue(aP3d, foundU, foundV, anewpoint.X(), anewpoint.Y());
4093               }
4094             }
4095           }
4096         }
4097       }
4098       aSeqOfPntOn2S->Add(aNewP);
4099       aListOfFLIndex.Append(aSeqOfPntOn2S->NbPoints());
4100     }
4101     anArrayOfLineEnds.SetValue(i, aListOfFLIndex);
4102   }
4103   // Correct wlines.end
4104
4105   // Split wlines.begin
4106   Standard_Integer nbiter;
4107   //
4108   nbiter=1;
4109   if (!bAvoidLineConstructor) {
4110     nbiter=theLConstructor.NbParts();
4111   }
4112   //
4113   for(j = 1; j <= nbiter; ++j) {
4114     Standard_Real fprm, lprm;
4115     Standard_Integer ifprm, ilprm;
4116     //
4117     if(bAvoidLineConstructor) {
4118       ifprm = 1;
4119       ilprm = theWLine->NbPnts();
4120     }
4121     else {
4122       theLConstructor.Part(j, fprm, lprm);
4123       ifprm = (Standard_Integer)fprm;
4124       ilprm = (Standard_Integer)lprm;
4125     }
4126
4127     Handle(IntSurf_LineOn2S) aLineOn2S = new IntSurf_LineOn2S();
4128     //
4129     for(i = 1; i <= nblines; i++) {
4130       if(anArrayOfLineType.Value(i) != 0) {
4131         continue;
4132       }
4133       const TColStd_ListOfInteger& aListOfIndex = anArrayOfLines.Value(i);
4134
4135       if(aListOfIndex.Extent() < 2) {
4136         continue;
4137       }
4138       const TColStd_ListOfInteger& aListOfFLIndex = anArrayOfLineEnds.Value(i);
4139       Standard_Boolean bhasfirstpoint = (aListOfFLIndex.Extent() == 2);
4140       Standard_Boolean bhaslastpoint = (aListOfFLIndex.Extent() == 2);
4141
4142       if(!bhasfirstpoint && !aListOfFLIndex.IsEmpty()) {
4143         bhasfirstpoint = (i != 1);
4144       }
4145
4146       if(!bhaslastpoint && !aListOfFLIndex.IsEmpty()) {
4147         bhaslastpoint = (i != nblines);
4148       }
4149       Standard_Boolean bIsFirstInside = ((ifprm >= aListOfIndex.First()) && (ifprm <= aListOfIndex.Last()));
4150       Standard_Boolean bIsLastInside =  ((ilprm >= aListOfIndex.First()) && (ilprm <= aListOfIndex.Last()));
4151
4152       if(!bIsFirstInside && !bIsLastInside) {
4153         if((ifprm < aListOfIndex.First()) && (ilprm > aListOfIndex.Last())) {
4154           // append whole line, and boundaries if neccesary
4155           if(bhasfirstpoint) {
4156             const IntSurf_PntOn2S& aP = aSeqOfPntOn2S->Value(aListOfFLIndex.First());
4157             aLineOn2S->Add(aP);
4158           }
4159           TColStd_ListIteratorOfListOfInteger anIt(aListOfIndex);
4160
4161           for(; anIt.More(); anIt.Next()) {
4162             const IntSurf_PntOn2S& aP = theWLine->Point(anIt.Value());
4163             aLineOn2S->Add(aP);
4164           }
4165
4166           if(bhaslastpoint) {
4167             const IntSurf_PntOn2S& aP = aSeqOfPntOn2S->Value(aListOfFLIndex.Last());
4168             aLineOn2S->Add(aP);
4169           }
4170
4171           // check end of split line (end is almost always)
4172           Standard_Integer aneighbour = i + 1;
4173           Standard_Boolean bIsEndOfLine = Standard_True;
4174
4175           if(aneighbour <= nblines) {
4176             const TColStd_ListOfInteger& aListOfNeighbourIndex = anArrayOfLines.Value(aneighbour);
4177
4178             if((anArrayOfLineType.Value(aneighbour) != 0) &&
4179                (aListOfNeighbourIndex.IsEmpty())) {
4180               bIsEndOfLine = Standard_False;
4181             }
4182           }
4183
4184           if(bIsEndOfLine) {
4185             if(aLineOn2S->NbPoints() > 1) {
4186               Handle(IntPatch_WLine) aNewWLine = 
4187                 new IntPatch_WLine(aLineOn2S, Standard_False);
4188               theNewLines.Append(aNewWLine);
4189             }
4190             aLineOn2S = new IntSurf_LineOn2S();
4191           }
4192         }
4193         continue;
4194       }
4195       // end if(!bIsFirstInside && !bIsLastInside)
4196
4197       if(bIsFirstInside && bIsLastInside) {
4198         // append inside points between ifprm and ilprm
4199         TColStd_ListIteratorOfListOfInteger anIt(aListOfIndex);
4200
4201         for(; anIt.More(); anIt.Next()) {
4202           if((anIt.Value() < ifprm) || (anIt.Value() > ilprm))
4203             continue;
4204           const IntSurf_PntOn2S& aP = theWLine->Point(anIt.Value());
4205           aLineOn2S->Add(aP);
4206         }
4207       }
4208       else {
4209
4210         if(bIsFirstInside) {
4211           // append points from ifprm to last point + boundary point
4212           TColStd_ListIteratorOfListOfInteger anIt(aListOfIndex);
4213
4214           for(; anIt.More(); anIt.Next()) {
4215             if(anIt.Value() < ifprm)
4216               continue;
4217             const IntSurf_PntOn2S& aP = theWLine->Point(anIt.Value());
4218             aLineOn2S->Add(aP);
4219           }
4220
4221           if(bhaslastpoint) {
4222             const IntSurf_PntOn2S& aP = aSeqOfPntOn2S->Value(aListOfFLIndex.Last());
4223             aLineOn2S->Add(aP);
4224           }
4225           // check end of split line (end is almost always)
4226           Standard_Integer aneighbour = i + 1;
4227           Standard_Boolean bIsEndOfLine = Standard_True;
4228
4229           if(aneighbour <= nblines) {
4230             const TColStd_ListOfInteger& aListOfNeighbourIndex = anArrayOfLines.Value(aneighbour);
4231
4232             if((anArrayOfLineType.Value(aneighbour) != 0) &&
4233                (aListOfNeighbourIndex.IsEmpty())) {
4234               bIsEndOfLine = Standard_False;
4235             }
4236           }
4237
4238           if(bIsEndOfLine) {
4239             if(aLineOn2S->NbPoints() > 1) {
4240               Handle(IntPatch_WLine) aNewWLine = 
4241                 new IntPatch_WLine(aLineOn2S, Standard_False);
4242               theNewLines.Append(aNewWLine);
4243             }
4244             aLineOn2S = new IntSurf_LineOn2S();
4245           }
4246         }
4247         // end if(bIsFirstInside)
4248
4249         if(bIsLastInside) {
4250           // append points from first boundary point to ilprm
4251           if(bhasfirstpoint) {
4252             const IntSurf_PntOn2S& aP = aSeqOfPntOn2S->Value(aListOfFLIndex.First());
4253             aLineOn2S->Add(aP);
4254           }
4255           TColStd_ListIteratorOfListOfInteger anIt(aListOfIndex);
4256
4257           for(; anIt.More(); anIt.Next()) {
4258             if(anIt.Value() > ilprm)
4259               continue;
4260             const IntSurf_PntOn2S& aP = theWLine->Point(anIt.Value());
4261             aLineOn2S->Add(aP);
4262           }
4263         }
4264         //end if(bIsLastInside)
4265       }
4266     }
4267
4268     if(aLineOn2S->NbPoints() > 1) {
4269       Handle(IntPatch_WLine) aNewWLine = 
4270         new IntPatch_WLine(aLineOn2S, Standard_False);
4271       theNewLines.Append(aNewWLine);
4272     }
4273   }
4274   // Split wlines.end
4275
4276   return Standard_True;
4277 }
4278
4279 // ------------------------------------------------------------------------------------------------
4280 // static function: ParameterOutOfBoundary
4281 // purpose:         Computes a new parameter for given curve. The corresponding 2d points 
4282 //                  does not lay on any boundary of given faces
4283 // ------------------------------------------------------------------------------------------------
4284 Standard_Boolean ParameterOutOfBoundary(const Standard_Real       theParameter, 
4285                                         const Handle(Geom_Curve)& theCurve, 
4286                                         const TopoDS_Face&        theFace1, 
4287                                         const TopoDS_Face&        theFace2,
4288                                         const Standard_Real       theOtherParameter,
4289                                         const Standard_Boolean    bIncreasePar,
4290                                         Standard_Real&            theNewParameter,
4291                                         const Handle(IntTools_Context)& aContext)
4292 {
4293   Standard_Boolean bIsComputed = Standard_False;
4294   theNewParameter = theParameter;
4295
4296   Standard_Real acurpar = theParameter;
4297   TopAbs_State aState = TopAbs_ON;
4298   Standard_Integer iter = 0;
4299   Standard_Real asumtol = BRep_Tool::Tolerance(theFace1) + BRep_Tool::Tolerance(theFace2);
4300   Standard_Real adelta = asumtol * 0.1;
4301   adelta = (adelta < Precision::Confusion()) ? Precision::Confusion() : adelta;
4302   Handle(Geom_Surface) aSurf1 = BRep_Tool::Surface(theFace1);
4303   Handle(Geom_Surface) aSurf2 = BRep_Tool::Surface(theFace2);
4304
4305   Standard_Real u1, u2, v1, v2;
4306
4307   GeomAPI_ProjectPointOnSurf aPrj1;
4308   aSurf1->Bounds(u1, u2, v1, v2);
4309   aPrj1.Init(aSurf1, u1, u2, v1, v2);
4310
4311   GeomAPI_ProjectPointOnSurf aPrj2;
4312   aSurf2->Bounds(u1, u2, v1, v2);
4313   aPrj2.Init(aSurf2, u1, u2, v1, v2);
4314
4315   while(aState == TopAbs_ON) {
4316     if(bIncreasePar)
4317       acurpar += adelta;
4318     else
4319       acurpar -= adelta;
4320     gp_Pnt aPCurrent = theCurve->Value(acurpar);
4321     aPrj1.Perform(aPCurrent);
4322     Standard_Real U=0., V=0.;
4323
4324     if(aPrj1.IsDone()) {
4325       aPrj1.LowerDistanceParameters(U, V);
4326       aState = aContext->StatePointFace(theFace1, gp_Pnt2d(U, V));
4327     }
4328
4329     if(aState != TopAbs_ON) {
4330       aPrj2.Perform(aPCurrent);
4331                 
4332       if(aPrj2.IsDone()) {
4333         aPrj2.LowerDistanceParameters(U, V);
4334         aState = aContext->StatePointFace(theFace2, gp_Pnt2d(U, V));
4335       }
4336     }
4337
4338     if(iter > 11) {
4339       break;
4340     }
4341     iter++;
4342   }
4343
4344   if(iter <= 11) {
4345     theNewParameter = acurpar;
4346     bIsComputed = Standard_True;
4347
4348     if(bIncreasePar) {
4349       if(acurpar >= theOtherParameter)
4350         theNewParameter = theOtherParameter;
4351     }
4352     else {
4353       if(acurpar <= theOtherParameter)
4354         theNewParameter = theOtherParameter;
4355     }
4356   }
4357   return bIsComputed;
4358 }
4359
4360 //=======================================================================
4361 //function : IsCurveValid
4362 //purpose  : 
4363 //=======================================================================
4364 Standard_Boolean IsCurveValid(Handle(Geom2d_Curve)& thePCurve)
4365 {
4366   if(thePCurve.IsNull())
4367     return Standard_False;
4368
4369   Standard_Real tolint = 1.e-10;
4370   Geom2dAdaptor_Curve PCA;
4371   IntRes2d_Domain PCD;
4372   Geom2dInt_GInter PCI;
4373
4374   Standard_Real pf = 0., pl = 0.;
4375   gp_Pnt2d pntf, pntl;
4376
4377   if(!thePCurve->IsClosed() && !thePCurve->IsPeriodic()) {
4378     pf = thePCurve->FirstParameter();
4379     pl = thePCurve->LastParameter();
4380     pntf = thePCurve->Value(pf);
4381     pntl = thePCurve->Value(pl);
4382     PCA.Load(thePCurve);
4383     if(!PCA.IsPeriodic()) {
4384       if(PCA.FirstParameter() > pf) pf = PCA.FirstParameter();
4385       if(PCA.LastParameter()  < pl) pl = PCA.LastParameter();
4386     }
4387     PCD.SetValues(pntf,pf,tolint,pntl,pl,tolint);
4388     PCI.Perform(PCA,PCD,tolint,tolint);
4389     if(PCI.IsDone())
4390       if(PCI.NbPoints() > 0) {
4391         return Standard_False;
4392       }
4393   }
4394
4395   return Standard_True;
4396 }
4397
4398 //=======================================================================
4399 //static function : ApproxWithPCurves
4400 //purpose  : for bug 20964 only
4401 //=======================================================================
4402 Standard_Boolean ApproxWithPCurves(const gp_Cylinder& theCyl, 
4403                                    const gp_Sphere& theSph)
4404 {
4405   Standard_Boolean bRes = Standard_True;
4406   Standard_Real R1 = theCyl.Radius(), R2 = theSph.Radius();
4407   //
4408   {
4409     Standard_Real aD2, aRc2, aEps;
4410     gp_Pnt aApexSph;
4411     //
4412     aEps=1.E-7;
4413     aRc2=R1*R1;
4414     //
4415     const gp_Ax3& aAx3Sph=theSph.Position();
4416     const gp_Pnt& aLocSph=aAx3Sph.Location();
4417     const gp_Dir& aDirSph=aAx3Sph.Direction();
4418     //
4419     const gp_Ax1& aAx1Cyl=theCyl.Axis();
4420     gp_Lin aLinCyl(aAx1Cyl);
4421     //
4422     aApexSph.SetXYZ(aLocSph.XYZ()+R2*aDirSph.XYZ());
4423     aD2=aLinCyl.SquareDistance(aApexSph);
4424     if (fabs(aD2-aRc2)<aEps) {
4425       return !bRes;
4426     }
4427     //
4428     aApexSph.SetXYZ(aLocSph.XYZ()-R2*aDirSph.XYZ());
4429     aD2=aLinCyl.SquareDistance(aApexSph);
4430     if (fabs(aD2-aRc2)<aEps) {
4431       return !bRes;
4432     }
4433   }
4434   //
4435     
4436   if(R1 < 2.*R2) {
4437     return bRes;
4438   }
4439   gp_Lin anCylAx(theCyl.Axis());
4440
4441   Standard_Real aDist = anCylAx.Distance(theSph.Location());
4442   Standard_Real aDRel = Abs(aDist - R1)/R2;
4443
4444   if(aDRel > .2) return bRes;
4445
4446   Standard_Real par = ElCLib::Parameter(anCylAx, theSph.Location());
4447   gp_Pnt aP = ElCLib::Value(par, anCylAx);
4448   gp_Vec aV(aP, theSph.Location());
4449
4450   Standard_Real dd = aV.Dot(theSph.Position().XDirection());
4451
4452   if(aDist < R1 && dd > 0.) return Standard_False;
4453   if(aDist > R1 && dd < 0.) return Standard_False;
4454
4455   
4456   return bRes;
4457 }
4458 //=======================================================================
4459 //function : PerformPlanes
4460 //purpose  : 
4461 //=======================================================================
4462 void  PerformPlanes(const Handle(GeomAdaptor_HSurface)& theS1, 
4463                     const Handle(GeomAdaptor_HSurface)& theS2, 
4464                     const Standard_Real TolAng, 
4465                     const Standard_Real TolTang, 
4466                     const Standard_Boolean theApprox1,
4467                     const Standard_Boolean theApprox2,
4468                     IntTools_SequenceOfCurves& theSeqOfCurve, 
4469                     Standard_Boolean& theTangentFaces)
4470 {
4471
4472   gp_Pln aPln1 = theS1->Surface().Plane();
4473   gp_Pln aPln2 = theS2->Surface().Plane();
4474
4475   IntAna_QuadQuadGeo aPlnInter(aPln1, aPln2, TolAng, TolTang);
4476
4477   if(!aPlnInter.IsDone()) {
4478     theTangentFaces = Standard_False;
4479     return;
4480   }
4481
4482   IntAna_ResultType aResType = aPlnInter.TypeInter();
4483
4484   if(aResType == IntAna_Same) {
4485     theTangentFaces = Standard_True;
4486     return;
4487   }
4488
4489   theTangentFaces = Standard_False;
4490
4491   if(aResType == IntAna_Empty) {
4492     return;
4493   }
4494
4495   gp_Lin aLin = aPlnInter.Line(1);
4496
4497   ProjLib_Plane aProj;
4498
4499   aProj.Init(aPln1);
4500   aProj.Project(aLin);
4501   gp_Lin2d aLin2d1 = aProj.Line();
4502   //
4503   aProj.Init(aPln2);
4504   aProj.Project(aLin);
4505   gp_Lin2d aLin2d2 = aProj.Line();
4506   //
4507   //classify line2d1 relatively first plane
4508   Standard_Real P11, P12;
4509   Standard_Boolean IsCrossed = ClassifyLin2d(theS1, aLin2d1, TolTang, P11, P12);
4510   if(!IsCrossed) return;
4511   //classify line2d2 relatively second plane
4512   Standard_Real P21, P22;
4513   IsCrossed = ClassifyLin2d(theS2, aLin2d2, TolTang, P21, P22);
4514   if(!IsCrossed) return;
4515
4516   //Analysis of parametric intervals: must have common part
4517
4518   if(P21 >= P12) return;
4519   if(P22 <= P11) return;
4520
4521   Standard_Real pmin, pmax;
4522   pmin = Max(P11, P21);
4523   pmax = Min(P12, P22);
4524
4525   if(pmax - pmin <= TolTang) return;
4526
4527   Handle(Geom_Line) aGLin = new Geom_Line(aLin);
4528
4529   IntTools_Curve aCurve;
4530   Handle(Geom_TrimmedCurve) aGTLin = new Geom_TrimmedCurve(aGLin, pmin, pmax);
4531
4532   aCurve.SetCurve(aGTLin);
4533
4534   if(theApprox1) { 
4535     Handle(Geom2d_Line) C2d = new Geom2d_Line(aLin2d1);
4536     aCurve.SetFirstCurve2d(new Geom2d_TrimmedCurve(C2d, pmin, pmax));
4537   }
4538   else { 
4539     Handle(Geom2d_Curve) H1;
4540     aCurve.SetFirstCurve2d(H1);
4541   }
4542   if(theApprox2) { 
4543     Handle(Geom2d_Line) C2d = new Geom2d_Line(aLin2d2);
4544     aCurve.SetSecondCurve2d(new Geom2d_TrimmedCurve(C2d, pmin, pmax));
4545   }
4546   else { 
4547     Handle(Geom2d_Curve) H1;
4548     aCurve.SetFirstCurve2d(H1);
4549   }
4550
4551   theSeqOfCurve.Append(aCurve);
4552  
4553 }
4554
4555 //=======================================================================
4556 //function : ClassifyLin2d
4557 //purpose  : 
4558 //=======================================================================
4559 static inline Standard_Boolean INTER(const Standard_Real d1, 
4560                                      const Standard_Real d2, 
4561                                      const Standard_Real tol) 
4562 {
4563   return (d1 > tol && d2 < -tol) || 
4564          (d1 < -tol && d2 > tol) ||
4565          ((d1 <= tol && d1 >= -tol) && (d2 > tol || d2 < -tol)) || 
4566          ((d2 <= tol && d2 >= -tol) && (d1 > tol || d1 < -tol));
4567 }
4568 static inline Standard_Boolean COINC(const Standard_Real d1, 
4569                                      const Standard_Real d2, 
4570                                      const Standard_Real tol) 
4571 {
4572   return (d1 <= tol && d1 >= -tol) && (d2 <= tol && d2 >= -tol);
4573 }
4574 Standard_Boolean ClassifyLin2d(const Handle(GeomAdaptor_HSurface)& theS, 
4575                                const gp_Lin2d& theLin2d, 
4576                                const Standard_Real theTol,
4577                                Standard_Real& theP1, 
4578                                Standard_Real& theP2)
4579
4580 {
4581   Standard_Real xmin, xmax, ymin, ymax, d1, d2, A, B, C;
4582   Standard_Real par[2];
4583   Standard_Integer nbi = 0;
4584
4585   xmin = theS->Surface().FirstUParameter();
4586   xmax = theS->Surface().LastUParameter();
4587   ymin = theS->Surface().FirstVParameter();
4588   ymax = theS->Surface().LastVParameter();
4589
4590   theLin2d.Coefficients(A, B, C);
4591
4592   //xmin, ymin <-> xmin, ymax
4593   d1 = A*xmin + B*ymin + C;
4594   d2 = A*xmin + B*ymax + C;
4595
4596   if(INTER(d1, d2, theTol)) {
4597     //Intersection with boundary
4598     Standard_Real y = -(C + A*xmin)/B;
4599     par[nbi] = ElCLib::Parameter(theLin2d, gp_Pnt2d(xmin, y));
4600     nbi++;
4601   }
4602   else if (COINC(d1, d2, theTol)) {
4603     //Coincidence with boundary
4604     par[0] = ElCLib::Parameter(theLin2d, gp_Pnt2d(xmin, ymin));
4605     par[1] = ElCLib::Parameter(theLin2d, gp_Pnt2d(xmin, ymax));
4606     nbi = 2;
4607   }
4608
4609   if(nbi == 2) {
4610
4611     if(fabs(par[0]-par[1]) > theTol) {
4612       theP1 = Min(par[0], par[1]);
4613       theP2 = Max(par[0], par[1]);
4614       return Standard_True;
4615     }
4616     else return Standard_False;
4617
4618   }
4619
4620   //xmin, ymax <-> xmax, ymax
4621   d1 = d2;
4622   d2 = A*xmax + B*ymax + C;
4623
4624   if(d1 > theTol || d1 < -theTol) {//to avoid checking of
4625                                    //coincidence with the same point
4626     if(INTER(d1, d2, theTol)) {
4627       Standard_Real x = -(C + B*ymax)/A;
4628       par[nbi] = ElCLib::Parameter(theLin2d, gp_Pnt2d(x, ymax));
4629       nbi++;
4630     }
4631     else if (COINC(d1, d2, theTol)) {
4632       par[0] = ElCLib::Parameter(theLin2d, gp_Pnt2d(xmin, ymax));
4633       par[1] = ElCLib::Parameter(theLin2d, gp_Pnt2d(xmax, ymax));
4634       nbi = 2;
4635     }
4636   }
4637
4638   if(nbi == 2) {
4639
4640     if(fabs(par[0]-par[1]) > theTol) {
4641       theP1 = Min(par[0], par[1]);
4642       theP2 = Max(par[0], par[1]);
4643       return Standard_True;
4644     }
4645     else return Standard_False;
4646
4647   }
4648
4649   //xmax, ymax <-> xmax, ymin
4650   d1 = d2;
4651   d2 = A*xmax + B*ymin + C;
4652
4653   if(d1 > theTol || d1 < -theTol) {
4654     if(INTER(d1, d2, theTol)) {
4655       Standard_Real y = -(C + A*xmax)/B;
4656       par[nbi] = ElCLib::Parameter(theLin2d, gp_Pnt2d(xmax, y));
4657       nbi++;
4658     }
4659     else if (COINC(d1, d2, theTol)) {
4660       par[0] = ElCLib::Parameter(theLin2d, gp_Pnt2d(xmax, ymax));
4661       par[1] = ElCLib::Parameter(theLin2d, gp_Pnt2d(xmax, ymin));
4662       nbi = 2;
4663     }
4664   }
4665
4666   if(nbi == 2) {
4667     if(fabs(par[0]-par[1]) > theTol) {
4668       theP1 = Min(par[0], par[1]);
4669       theP2 = Max(par[0], par[1]);
4670       return Standard_True;
4671     }
4672     else return Standard_False;
4673   }
4674
4675   //xmax, ymin <-> xmin, ymin 
4676   d1 = d2;
4677   d2 = A*xmin + B*ymin + C;
4678
4679   if(d1 > theTol || d1 < -theTol) {
4680     if(INTER(d1, d2, theTol)) {
4681       Standard_Real x = -(C + B*ymin)/A;
4682       par[nbi] = ElCLib::Parameter(theLin2d, gp_Pnt2d(x, ymin));
4683       nbi++;
4684     }
4685     else if (COINC(d1, d2, theTol)) {
4686       par[0] = ElCLib::Parameter(theLin2d, gp_Pnt2d(xmax, ymin));
4687       par[1] = ElCLib::Parameter(theLin2d, gp_Pnt2d(xmin, ymin));
4688       nbi = 2;
4689     }
4690   }
4691
4692   if(nbi == 2) {
4693     if(fabs(par[0]-par[1]) > theTol) {
4694       theP1 = Min(par[0], par[1]);
4695       theP2 = Max(par[0], par[1]);
4696       return Standard_True;
4697     }
4698     else return Standard_False;
4699   }
4700
4701   return Standard_False;
4702
4703 }
4704 //
4705 //=======================================================================
4706 //function : ApproxParameters
4707 //purpose  : 
4708 //=======================================================================
4709 void ApproxParameters(const Handle(GeomAdaptor_HSurface)& aHS1,
4710                       const Handle(GeomAdaptor_HSurface)& aHS2,
4711                       Standard_Integer& iDegMin,
4712                       Standard_Integer& iDegMax,
4713                       Standard_Integer& iNbIter)
4714
4715 {
4716   GeomAbs_SurfaceType aTS1, aTS2;
4717   
4718   //
4719   iNbIter=0;
4720   iDegMin=4;
4721   iDegMax=8;
4722   //
4723   aTS1=aHS1->Surface().GetType();
4724   aTS2=aHS2->Surface().GetType();
4725   //
4726   // Cylinder/Torus
4727   if ((aTS1==GeomAbs_Cylinder && aTS2==GeomAbs_Torus) ||
4728       (aTS2==GeomAbs_Cylinder && aTS1==GeomAbs_Torus)) {
4729     Standard_Real aRC, aRT, dR, aPC;
4730     gp_Cylinder aCylinder;
4731     gp_Torus aTorus;
4732     //
4733     aPC=Precision::Confusion();
4734     //
4735     aCylinder=(aTS1==GeomAbs_Cylinder)? aHS1->Surface().Cylinder() : aHS2->Surface().Cylinder();
4736     aTorus=(aTS1==GeomAbs_Torus)? aHS1->Surface().Torus() : aHS2->Surface().Torus();
4737     //
4738     aRC=aCylinder.Radius();
4739     aRT=aTorus.MinorRadius();
4740     dR=aRC-aRT;
4741     if (dR<0.) {
4742       dR=-dR;
4743     }
4744     //
4745     if (dR<aPC) {
4746       iDegMax=6;
4747     }
4748   }
4749   if (aTS1==GeomAbs_Cylinder && aTS2==GeomAbs_Cylinder) {
4750     iNbIter=1; 
4751   }
4752 }
4753 //=======================================================================
4754 //function : Tolerances
4755 //purpose  : 
4756 //=======================================================================
4757 void Tolerances(const Handle(GeomAdaptor_HSurface)& aHS1,
4758                 const Handle(GeomAdaptor_HSurface)& aHS2,
4759                 Standard_Real& aTolTang)
4760 {
4761   GeomAbs_SurfaceType aTS1, aTS2;
4762   //
4763   aTS1=aHS1->Surface().GetType();
4764   aTS2=aHS2->Surface().GetType();
4765   //
4766   // Cylinder/Torus
4767   if ((aTS1==GeomAbs_Cylinder && aTS2==GeomAbs_Torus) ||
4768       (aTS2==GeomAbs_Cylinder && aTS1==GeomAbs_Torus)) {
4769     Standard_Real aRC, aRT, dR, aPC;
4770     gp_Cylinder aCylinder;
4771     gp_Torus aTorus;
4772     //
4773     aPC=Precision::Confusion();
4774     //
4775     aCylinder=(aTS1==GeomAbs_Cylinder)? aHS1->Surface().Cylinder() : aHS2->Surface().Cylinder();
4776     aTorus=(aTS1==GeomAbs_Torus)? aHS1->Surface().Torus() : aHS2->Surface().Torus();
4777     //
4778     aRC=aCylinder.Radius();
4779     aRT=aTorus.MinorRadius();
4780     dR=aRC-aRT;
4781     if (dR<0.) {
4782       dR=-dR;
4783     }
4784     //
4785     if (dR<aPC) {
4786       aTolTang=0.1*aTolTang;
4787     }
4788   }
4789 }
4790 //=======================================================================
4791 //function : SortTypes
4792 //purpose  : 
4793 //=======================================================================
4794 Standard_Boolean SortTypes(const GeomAbs_SurfaceType aType1,
4795                            const GeomAbs_SurfaceType aType2)
4796 {
4797   Standard_Boolean bRet;
4798   Standard_Integer aI1, aI2;
4799   //
4800   bRet=Standard_False;
4801   //
4802   aI1=IndexType(aType1);
4803   aI2=IndexType(aType2);
4804   if (aI1<aI2){
4805     bRet=!bRet;
4806   }
4807   return bRet;
4808 }
4809 //=======================================================================
4810 //function : IndexType
4811 //purpose  : 
4812 //=======================================================================
4813 Standard_Integer IndexType(const GeomAbs_SurfaceType aType)
4814 {
4815   Standard_Integer aIndex;
4816   //
4817   aIndex=11;
4818   //
4819   if (aType==GeomAbs_Plane) {
4820     aIndex=0;
4821   }
4822   else if (aType==GeomAbs_Cylinder) {
4823     aIndex=1;
4824   } 
4825   else if (aType==GeomAbs_Cone) {
4826     aIndex=2;
4827   } 
4828   else if (aType==GeomAbs_Sphere) {
4829     aIndex=3;
4830   } 
4831   else if (aType==GeomAbs_Torus) {
4832     aIndex=4;
4833   } 
4834   else if (aType==GeomAbs_BezierSurface) {
4835     aIndex=5;
4836   } 
4837   else if (aType==GeomAbs_BSplineSurface) {
4838     aIndex=6;
4839   } 
4840   else if (aType==GeomAbs_SurfaceOfRevolution) {
4841     aIndex=7;
4842   } 
4843   else if (aType==GeomAbs_SurfaceOfExtrusion) {
4844     aIndex=8;
4845   } 
4846   else if (aType==GeomAbs_OffsetSurface) {
4847     aIndex=9;
4848   } 
4849   else if (aType==GeomAbs_OtherSurface) {
4850     aIndex=10;
4851   } 
4852   return aIndex;
4853 }
4854 #ifdef DEB_DUMPWLINE
4855 //=======================================================================
4856 //function : DumpWLine
4857 //purpose  : 
4858 //=======================================================================
4859 void DumpWLine(const Handle(IntPatch_WLine)& aWLine)
4860 {
4861   Standard_Integer i, aNbPnts; 
4862   Standard_Real aX, aY, aZ, aU1, aV1, aU2, aV2;
4863   //
4864   printf(" *WLine\n");
4865   aNbPnts=aWLine->NbPnts();
4866   for (i=1; i<=aNbPnts; ++i) {
4867     const IntSurf_PntOn2S aPntOn2S=aWLine->Point(i);
4868     const gp_Pnt& aP3D=aPntOn2S.Value();
4869     aP3D.Coord(aX, aY, aZ);
4870     aPntOn2S.Parameters(aU1, aV1, aU2, aV2);
4871     //
4872     printf("point p_%d %lf %lf %lf\n", i, aX, aY, aZ);
4873     //printf("point p_%d %20.15lf %20.15lf %20.15lf %20.15lf %20.15lf %20.15lf %20.15lf\n",
4874         //   i, aX, aY, aZ, aU1, aV1, aU2, aV2);
4875   }
4876 }
4877 #endif
4878 //=======================================================================
4879 //function : RefineVector
4880 //purpose  : 
4881 //=======================================================================
4882 void RefineVector(gp_Vec2d& aV2D)
4883 {
4884   Standard_Integer k,m;
4885   Standard_Real aC[2], aEps, aR1, aR2, aNum;
4886   //
4887   aEps=RealEpsilon();
4888   aR1=1.-aEps;
4889   aR2=1.+aEps;
4890   //
4891   aV2D.Coord(aC[0], aC[1]);
4892   //
4893   for (k=0; k<2; ++k) {
4894     m=(k+1)%2;
4895     aNum=fabs(aC[k]);
4896     if (aNum>aR1 && aNum<aR2) {
4897       if (aC[k]<0.) {
4898         aC[k]=-1.;
4899       }          
4900       else {
4901         aC[k]=1.;
4902       }
4903       aC[m]=0.;
4904       break;
4905     }
4906   }
4907   aV2D.SetCoord(aC[0], aC[1]);
4908 }
4909 //=======================================================================
4910 //function : FindMaxSquareDistance
4911 //purpose  : 
4912 //=======================================================================
4913 Standard_Real FindMaxSquareDistance (const Standard_Real aT1,
4914                                      const Standard_Real aT2,
4915                                      const Standard_Real aEps,
4916                                      const Handle(Geom_Curve)& aC3D,
4917                                      const Handle(Geom2d_Curve)& aC2D1,
4918                                      const Handle(Geom2d_Curve)& aC2D2,
4919                                      const Handle(GeomAdaptor_HSurface)& myHS1,
4920                                      const Handle(GeomAdaptor_HSurface)& myHS2,
4921                                      const TopoDS_Face& myFace1,
4922                                      const TopoDS_Face& myFace2,
4923                                      const Handle(IntTools_Context)& myContext)
4924 {
4925   Standard_Real aA, aB, aCf, aX1, aX2, aF1, aF2, aX, aF;
4926   //
4927   aCf=1.6180339887498948482045868343656;// =0.5*(1.+sqrt(5.));
4928   aA=aT1;
4929   aB=aT2;
4930   aX1=aB-(aB-aA)/aCf;  
4931   aF1=MaxSquareDistance(aX1, 
4932                         aC3D, aC2D1, aC2D2, myHS1, myHS2, myFace1, myFace2, myContext);
4933   aX2=aA+(aB-aA)/aCf;
4934   aF2=MaxSquareDistance(aX2, 
4935                         aC3D, aC2D1, aC2D2, myHS1, myHS2, myFace1, myFace2, myContext);
4936   //
4937   for(;;) {
4938     //
4939     if (fabs(aA-aB)<aEps) {
4940       aX=0.5*(aA+aB);
4941       aF=MaxSquareDistance(aX, 
4942                         aC3D, aC2D1, aC2D2, myHS1, myHS2, myFace1, myFace2, myContext);
4943       break;
4944     }
4945     if (aF1<aF2){
4946       aA=aX1;
4947       aX1=aX2;
4948       aF1=aF2;
4949       aX2=aA+(aB-aA)/aCf;
4950       aF2=MaxSquareDistance(aX2, 
4951                             aC3D, aC2D1, aC2D2, myHS1, myHS2, myFace1, myFace2, myContext);
4952       
4953     }
4954     else {
4955       aB=aX2;
4956       aX2=aX1;
4957       aF2=aF1;
4958       aX1=aB-(aB-aA)/aCf; 
4959       aF1=MaxSquareDistance(aX1, 
4960                             aC3D, aC2D1, aC2D2, myHS1, myHS2, myFace1, myFace2, myContext);
4961     }
4962   }
4963   return aF;
4964 }
4965 //=======================================================================
4966 //function : MaxSquareDistance
4967 //purpose  : 
4968 //=======================================================================
4969 Standard_Real MaxSquareDistance (const Standard_Real aT,
4970                                  const Handle(Geom_Curve)& aC3D,
4971                                  const Handle(Geom2d_Curve)& aC2D1,
4972                                  const Handle(Geom2d_Curve)& aC2D2,
4973                                  const Handle(GeomAdaptor_HSurface) myHS1,
4974                                  const Handle(GeomAdaptor_HSurface) myHS2,
4975                                  const TopoDS_Face& aF1,
4976                                  const TopoDS_Face& aF2,
4977                                  const Handle(IntTools_Context)& aCtx)
4978 {
4979   Standard_Boolean bIsDone;
4980   Standard_Integer i;
4981   Standard_Real aU, aV, aD2Max, aD2;
4982   gp_Pnt2d aP2D;
4983   gp_Pnt aP, aPS;
4984   //
4985   aD2Max=0.;
4986   //
4987   aC3D->D0(aT, aP);
4988   if (aC3D.IsNull()) {
4989     return aD2Max;
4990   }
4991   //
4992   for (i=0; i<2; ++i) {
4993     const Handle(GeomAdaptor_HSurface)& aGHS=(!i) ? myHS1 : myHS2;
4994     const TopoDS_Face &aF=(!i) ? aF1 : aF2;
4995     const Handle(Geom2d_Curve)& aC2D=(!i) ? aC2D1 : aC2D2;
4996     //
4997     if (!aC2D.IsNull()) {
4998       aC2D->D0(aT, aP2D);
4999       aP2D.Coord(aU, aV);
5000       aGHS->D0(aU, aV, aPS);
5001       aD2=aP.SquareDistance(aPS);
5002       if (aD2>aD2Max) {
5003         aD2Max=aD2;
5004       }
5005     }
5006     //
5007     GeomAPI_ProjectPointOnSurf& aProjector=aCtx->ProjPS(aF);
5008     //
5009     aProjector.Perform(aP);
5010     bIsDone=aProjector.IsDone();
5011     if (bIsDone) {
5012       aProjector.LowerDistanceParameters(aU, aV);
5013       aGHS->D0(aU, aV, aPS);
5014       aD2=aP.SquareDistance(aPS);
5015       if (aD2>aD2Max) {
5016         aD2Max=aD2;
5017       }
5018     }
5019   }
5020   //
5021   return aD2Max;
5022 }
5023
5024 //=======================================================================
5025 //function : CheckPCurve
5026 //purpose  : Checks if points of the pcurve are out of the face bounds.
5027 //=======================================================================
5028   Standard_Boolean CheckPCurve(const Handle(Geom2d_Curve)& aPC, 
5029                                const TopoDS_Face& aFace) 
5030 {
5031   const Standard_Integer NPoints = 23;
5032   Standard_Integer i;
5033   Standard_Real umin,umax,vmin,vmax;
5034
5035   BRepTools::UVBounds(aFace, umin, umax, vmin, vmax);
5036   Standard_Real tolU = Max ((umax-umin)*0.01, Precision::Confusion());
5037   Standard_Real tolV = Max ((vmax-vmin)*0.01, Precision::Confusion());
5038   Standard_Real fp = aPC->FirstParameter();
5039   Standard_Real lp = aPC->LastParameter();
5040
5041
5042   // adjust domain for periodic surfaces
5043   TopLoc_Location aLoc;
5044   Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace, aLoc);
5045   if (aSurf->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) {
5046     aSurf = (Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurf))->BasisSurface();
5047   }
5048   gp_Pnt2d pnt = aPC->Value((fp+lp)/2);
5049   Standard_Real u,v;
5050   pnt.Coord(u,v);
5051   //
5052   if (aSurf->IsUPeriodic()) {
5053     Standard_Real aPer = aSurf->UPeriod();
5054     Standard_Integer nshift = (Standard_Integer) ((u-umin)/aPer);
5055     if (u < umin+aPer*nshift) nshift--;
5056     umin += aPer*nshift;
5057     umax += aPer*nshift;
5058   }
5059   if (aSurf->IsVPeriodic()) {
5060     Standard_Real aPer = aSurf->VPeriod();
5061     Standard_Integer nshift = (Standard_Integer) ((v-vmin)/aPer);
5062     if (v < vmin+aPer*nshift) nshift--;
5063     vmin += aPer*nshift;
5064     vmax += aPer*nshift;
5065   }
5066   //
5067   //--------------------------------------------------------
5068   Standard_Boolean bRet;
5069   Standard_Integer j, aNbIntervals;
5070   Standard_Real aT, dT;
5071   gp_Pnt2d aP2D; 
5072   //
5073   Geom2dAdaptor_Curve aGAC(aPC);
5074   aNbIntervals=aGAC.NbIntervals(GeomAbs_CN);
5075   //
5076   TColStd_Array1OfReal aTI(1, aNbIntervals+1);
5077   aGAC.Intervals(aTI,GeomAbs_CN);
5078   //
5079   bRet=Standard_False;
5080   //
5081   aT=aGAC.FirstParameter();
5082   for (j=1; j<=aNbIntervals; ++j) {
5083     dT=(aTI(j+1)-aTI(j))/NPoints;
5084     //
5085     for (i=1; i<NPoints; i++) {
5086       aT=aT+dT;
5087       aGAC.D0(aT, aP2D);
5088       aP2D.Coord(u,v);
5089     if (umin-u > tolU || u-umax > tolU ||
5090           vmin-v > tolV || v-vmax > tolV) {
5091         return bRet;
5092   }
5093 }
5094   }
5095   return !bRet;
5096 }