0024002: Overall code and build procedure refactoring -- automatic
[occt.git] / src / BRepLib / BRepLib.cxx
1 // Created on: 1993-12-15
2 // Created by: Remi LEQUETTE
3 // Copyright (c) 1993-1999 Matra Datavision
4 // Copyright (c) 1999-2014 OPEN CASCADE SAS
5 //
6 // This file is part of Open CASCADE Technology software library.
7 //
8 // This library is free software; you can redistribute it and/or modify it under
9 // the terms of the GNU Lesser General Public License version 2.1 as published
10 // by the Free Software Foundation, with special exception defined in the file
11 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
12 // distribution for complete text of the license and disclaimer of any warranty.
13 //
14 // Alternatively, this file may be used under the terms of Open CASCADE
15 // commercial license or contractual agreement.
16
17 //pmn 26/09/97 Add parameters of approximation in BuildCurve3d
18 //  Modified by skv - Thu Jun  3 12:39:19 2004 OCC5898
19
20 #include <Adaptor3d_CurveOnSurface.hxx>
21 #include <AdvApprox_ApproxAFunction.hxx>
22 #include <AppParCurves_MultiBSpCurve.hxx>
23 #include <AppParCurves_MultiCurve.hxx>
24 #include <Approx_CurvilinearParameter.hxx>
25 #include <Approx_SameParameter.hxx>
26 #include <Bnd_Box.hxx>
27 #include <BRep_Builder.hxx>
28 #include <BRep_CurveRepresentation.hxx>
29 #include <BRep_GCurve.hxx>
30 #include <BRep_ListIteratorOfListOfCurveRepresentation.hxx>
31 #include <BRep_ListOfCurveRepresentation.hxx>
32 #include <BRep_TEdge.hxx>
33 #include <BRep_TFace.hxx>
34 #include <BRep_Tool.hxx>
35 #include <BRep_TVertex.hxx>
36 #include <BRepAdaptor_HCurve2d.hxx>
37 #include <BRepAdaptor_HSurface.hxx>
38 #include <BRepAdaptor_Surface.hxx>
39 #include <BRepBndLib.hxx>
40 #include <BRepClass3d_SolidClassifier.hxx>
41 #include <BRepLib.hxx>
42 #include <BSplCLib.hxx>
43 #include <ElSLib.hxx>
44 #include <Extrema_LocateExtPC.hxx>
45 #include <GCPnts_QuasiUniformDeflection.hxx>
46 #include <Geom2d_BSplineCurve.hxx>
47 #include <Geom2d_Curve.hxx>
48 #include <Geom2d_TrimmedCurve.hxx>
49 #include <Geom2dAdaptor.hxx>
50 #include <Geom2dAdaptor_Curve.hxx>
51 #include <Geom2dAdaptor_HCurve.hxx>
52 #include <Geom2dConvert.hxx>
53 #include <Geom_BSplineCurve.hxx>
54 #include <Geom_BSplineSurface.hxx>
55 #include <Geom_Curve.hxx>
56 #include <Geom_Plane.hxx>
57 #include <Geom_RectangularTrimmedSurface.hxx>
58 #include <Geom_Surface.hxx>
59 #include <Geom_TrimmedCurve.hxx>
60 #include <GeomAdaptor_Curve.hxx>
61 #include <GeomAdaptor_HCurve.hxx>
62 #include <GeomAdaptor_HSurface.hxx>
63 #include <GeomAdaptor_Surface.hxx>
64 #include <GeomLib.hxx>
65 #include <GeomLProp_SLProps.hxx>
66 #include <gp.hxx>
67 #include <gp_Ax2.hxx>
68 #include <gp_Pln.hxx>
69 #include <Poly_PolygonOnTriangulation.hxx>
70 #include <Poly_Triangulation.hxx>
71 #include <Precision.hxx>
72 #include <ProjLib_ProjectedCurve.hxx>
73 #include <Standard_Real.hxx>
74 #include <TColgp_Array1OfPnt.hxx>
75 #include <TColgp_Array1OfPnt2d.hxx>
76 #include <TColStd_Array1OfReal.hxx>
77 #include <TColStd_MapOfTransient.hxx>
78 #include <TopExp.hxx>
79 #include <TopExp_Explorer.hxx>
80 #include <TopoDS.hxx>
81 #include <TopoDS_Edge.hxx>
82 #include <TopoDS_Face.hxx>
83 #include <TopoDS_Shape.hxx>
84 #include <TopoDS_Solid.hxx>
85 #include <TopoDS_Vertex.hxx>
86 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
87 #include <TopTools_ListIteratorOfListOfShape.hxx>
88 #include <TopTools_MapOfShape.hxx>
89 #include <TShort_HArray1OfShortReal.hxx>
90
91 // TODO - not thread-safe static variables
92 static Standard_Real thePrecision = Precision::Confusion();     
93 static Handle(Geom_Plane) thePlane;
94
95 //=======================================================================
96 //function : Precision
97 //purpose  : 
98 //=======================================================================
99
100 void BRepLib::Precision(const Standard_Real P)
101 {
102   thePrecision = P;
103 }
104
105 //=======================================================================
106 //function : Precision
107 //purpose  : 
108 //=======================================================================
109
110 Standard_Real  BRepLib::Precision()
111 {
112   return thePrecision;
113 }
114
115 //=======================================================================
116 //function : Plane
117 //purpose  : 
118 //=======================================================================
119
120 void  BRepLib::Plane(const Handle(Geom_Plane)& P)
121 {
122   thePlane = P;
123 }
124
125
126 //=======================================================================
127 //function : Plane
128 //purpose  : 
129 //=======================================================================
130
131 const Handle(Geom_Plane)&  BRepLib::Plane()
132 {
133   if (thePlane.IsNull()) thePlane = new Geom_Plane(gp::XOY());
134   return thePlane;
135 }
136 //=======================================================================
137 //function : CheckSameRange
138 //purpose  : 
139 //=======================================================================
140
141 Standard_Boolean  BRepLib::CheckSameRange(const TopoDS_Edge& AnEdge,
142   const Standard_Real Tolerance) 
143 {
144   Standard_Boolean  IsSameRange = Standard_True,
145     first_time_in = Standard_True ;
146
147   BRep_ListIteratorOfListOfCurveRepresentation an_Iterator
148     ((*((Handle(BRep_TEdge)*)&AnEdge.TShape()))->ChangeCurves());
149
150   Standard_Real first, last;
151   Standard_Real current_first =0., current_last =0. ;
152   Handle(BRep_GCurve) geometric_representation_ptr ;
153
154   while (IsSameRange && an_Iterator.More()) {
155     geometric_representation_ptr =
156       Handle(BRep_GCurve)::DownCast(an_Iterator.Value());
157     if (!geometric_representation_ptr.IsNull()) {
158
159       first = geometric_representation_ptr->First();
160       last =  geometric_representation_ptr->Last();
161       if (first_time_in ) {
162         current_first = first ;
163         current_last = last   ;
164         first_time_in = Standard_False ;
165       }
166       else {
167         IsSameRange = (Abs(current_first - first) <= Tolerance) 
168           && (Abs(current_last -last) <= Tolerance ) ;
169       }
170     }
171     an_Iterator.Next() ;
172   }
173   return IsSameRange ;
174 }
175
176 //=======================================================================
177 //function : SameRange
178 //purpose  : 
179 //=======================================================================
180
181 void BRepLib::SameRange(const TopoDS_Edge& AnEdge,
182   const Standard_Real Tolerance) 
183 {
184   BRep_ListIteratorOfListOfCurveRepresentation an_Iterator
185     ((*((Handle(BRep_TEdge)*)&AnEdge.TShape()))->ChangeCurves());
186
187   Handle(Geom2d_Curve) Curve2dPtr, Curve2dPtr2, NewCurve2dPtr, NewCurve2dPtr2;
188   TopLoc_Location LocalLoc ;
189
190   Standard_Boolean first_time_in = Standard_True,
191     has_curve,
192     has_closed_curve ;
193   Handle(BRep_GCurve) geometric_representation_ptr ;
194   Standard_Real first,
195     current_first,
196     last,
197     current_last ;
198
199   const Handle(Geom_Curve) C = BRep_Tool::Curve(AnEdge,
200     LocalLoc,
201     current_first,
202     current_last);
203   if (!C.IsNull()) {
204     first_time_in = Standard_False ;
205   }
206
207   while (an_Iterator.More()) {
208     geometric_representation_ptr =
209       Handle(BRep_GCurve)::DownCast(an_Iterator.Value());
210     if (! geometric_representation_ptr.IsNull()) {
211       has_closed_curve =
212         has_curve = Standard_False ;
213       first = geometric_representation_ptr->First();
214       last =  geometric_representation_ptr->Last();
215       if (geometric_representation_ptr->IsCurveOnSurface()) {
216         Curve2dPtr = geometric_representation_ptr->PCurve() ; 
217         has_curve = Standard_True ;
218       }
219       if (geometric_representation_ptr->IsCurveOnClosedSurface()) {
220         Curve2dPtr2 = geometric_representation_ptr->PCurve2() ;
221         has_closed_curve = Standard_True ;
222       }
223       if (has_curve || has_closed_curve) {
224         if (first_time_in) {
225           current_first = first ;
226           current_last = last ;
227           first_time_in = Standard_False ;
228         }
229
230         if (Abs(first - current_first) > Precision::Confusion() ||
231           Abs(last - current_last) > Precision::Confusion() )
232         {
233           if (has_curve)
234           {
235             GeomLib::SameRange(Tolerance,
236               Curve2dPtr,
237               geometric_representation_ptr->First(),
238               geometric_representation_ptr->Last(),
239               current_first,
240               current_last,
241               NewCurve2dPtr);
242             geometric_representation_ptr->PCurve(NewCurve2dPtr) ;
243           }
244           if (has_closed_curve)
245           {
246             GeomLib::SameRange(Tolerance,
247               Curve2dPtr2,
248               geometric_representation_ptr->First(),
249               geometric_representation_ptr->Last(),
250               current_first,
251               current_last,
252               NewCurve2dPtr2);
253             geometric_representation_ptr->PCurve2(NewCurve2dPtr2) ;
254           }
255         }
256       }
257     }
258     an_Iterator.Next() ;
259   }
260   BRep_Builder B;
261   B.Range(TopoDS::Edge(AnEdge),
262     current_first,
263     current_last) ;
264
265   B.SameRange(AnEdge,
266     Standard_True) ;
267 }
268
269 //=======================================================================
270 //function : EvaluateMaxSegment
271 //purpose  : return MaxSegment to pass in approximation, if MaxSegment==0 provided
272 //=======================================================================
273
274 static Standard_Integer evaluateMaxSegment(const Standard_Integer aMaxSegment,
275   const Adaptor3d_CurveOnSurface& aCurveOnSurface)
276 {
277   if (aMaxSegment != 0) return aMaxSegment;
278
279   Handle(Adaptor3d_HSurface) aSurf   = aCurveOnSurface.GetSurface();
280   Handle(Adaptor2d_HCurve2d) aCurv2d = aCurveOnSurface.GetCurve();
281
282   Standard_Real aNbSKnots = 0, aNbC2dKnots = 0;
283
284   if (aSurf->GetType() == GeomAbs_BSplineSurface) {
285     Handle(Geom_BSplineSurface) aBSpline = aSurf->BSpline();
286     aNbSKnots = Max(aBSpline->NbUKnots(), aBSpline->NbVKnots());
287   }
288   if (aCurv2d->GetType() == GeomAbs_BSplineCurve) {
289     aNbC2dKnots = aCurv2d->NbKnots();
290   }
291   Standard_Integer aReturn = (Standard_Integer) (  30 + Max(aNbSKnots, aNbC2dKnots) ) ;
292   return aReturn;
293 }
294
295 //=======================================================================
296 //function : BuildCurve3d
297 //purpose  : 
298 //=======================================================================
299
300 Standard_Boolean  BRepLib::BuildCurve3d(const TopoDS_Edge& AnEdge,
301   const Standard_Real Tolerance,
302   const GeomAbs_Shape Continuity,
303   const Standard_Integer MaxDegree,
304   const Standard_Integer MaxSegment)
305 {
306   Standard_Integer //ErrorCode,
307     //                   ReturnCode = 0,
308     ii,
309     //                   num_knots,
310     jj;
311
312   TopLoc_Location LocalLoc,L[2],LC;
313   Standard_Real f,l,fc,lc, first[2], last[2],
314     tolerance,
315     max_deviation,
316     average_deviation ;
317   Handle(Geom2d_Curve) Curve2dPtr, Curve2dArray[2]  ;
318   Handle(Geom_Surface) SurfacePtr, SurfaceArray[2]  ;
319
320   Standard_Integer not_done ;
321   // if the edge has a 3d curve returns true
322
323
324   const Handle(Geom_Curve) C = BRep_Tool::Curve(AnEdge,LocalLoc,f,l);
325   if (!C.IsNull()) 
326     return Standard_True;
327   //
328   // this should not exists but UpdateEdge makes funny things 
329   // if the edge is not same range 
330   //
331   if (! CheckSameRange(AnEdge,
332     Precision::Confusion())) {
333       SameRange(AnEdge,
334         Tolerance) ;
335   }
336
337
338
339   // search a curve on a plane
340   Handle(Geom_Surface) S;
341   Handle(Geom2d_Curve) PC;
342   Standard_Integer i = 0;
343   Handle(Geom_Plane) P;
344   not_done = 1 ;
345
346   while (not_done) {
347     i++;
348     BRep_Tool::CurveOnSurface(AnEdge,PC,S,LocalLoc,f,l,i);
349     Handle(Geom_RectangularTrimmedSurface) RT = 
350       Handle(Geom_RectangularTrimmedSurface)::DownCast(S);
351     if ( RT.IsNull()) {
352       P = Handle(Geom_Plane)::DownCast(S);
353     }
354     else {
355       P = Handle(Geom_Plane)::DownCast(RT->BasisSurface());
356     }
357     not_done = ! (S.IsNull() || !P.IsNull()) ;
358   }
359   if (! P.IsNull()) {
360     // compute the 3d curve
361     gp_Ax2 axes = P->Position().Ax2();
362     Handle(Geom_Curve) C3d = GeomLib::To3d(axes,PC);
363     if (C3d.IsNull())
364       return Standard_False;
365     // update the edge
366     Standard_Real First, Last;
367
368     BRep_Builder B;
369     B.UpdateEdge(AnEdge,C3d,LocalLoc,0.0e0);
370     BRep_Tool::Range(AnEdge, S, LC, First, Last);
371     B.Range(AnEdge, First, Last); //Do not forget 3D range.(PRO6412)
372   }
373   else {
374     //
375     // compute the 3d curve using existing surface
376     //
377     fc = f ;
378     lc = l ;
379     if (!BRep_Tool::Degenerated(AnEdge)) {
380       jj = 0 ;
381       for (ii = 0 ; ii < 3 ; ii++ ) {
382         BRep_Tool::CurveOnSurface(TopoDS::Edge(AnEdge),
383           Curve2dPtr,
384           SurfacePtr,
385           LocalLoc,
386           fc,
387           lc,
388           ii) ;
389
390         if (!Curve2dPtr.IsNull() && jj < 2){
391           Curve2dArray[jj] = Curve2dPtr ;
392           SurfaceArray[jj] = SurfacePtr ;
393           L[jj] = LocalLoc ;
394           first[jj] = fc ;
395           last[jj] = lc ;
396           jj += 1 ;
397         }
398       }
399       f = first[0] ;
400       l = last[0] ;
401       Curve2dPtr = Curve2dArray[0] ;
402       SurfacePtr = SurfaceArray[0] ;
403
404       Geom2dAdaptor_Curve     AnAdaptor3dCurve2d (Curve2dPtr, f, l) ;
405       GeomAdaptor_Surface     AnAdaptor3dSurface (SurfacePtr) ;
406       Handle(Geom2dAdaptor_HCurve) AnAdaptor3dCurve2dPtr =
407         new Geom2dAdaptor_HCurve(AnAdaptor3dCurve2d) ;
408       Handle(GeomAdaptor_HSurface) AnAdaptor3dSurfacePtr =
409         new GeomAdaptor_HSurface (AnAdaptor3dSurface) ;
410       Adaptor3d_CurveOnSurface  CurveOnSurface( AnAdaptor3dCurve2dPtr,
411         AnAdaptor3dSurfacePtr) ;
412
413       Handle(Geom_Curve) NewCurvePtr ;
414
415       GeomLib::BuildCurve3d(Tolerance,
416         CurveOnSurface,
417         f,
418         l,
419         NewCurvePtr,
420         max_deviation,
421         average_deviation,
422         Continuity,
423         MaxDegree,
424         evaluateMaxSegment(MaxSegment,CurveOnSurface)) ;
425       BRep_Builder B;   
426       tolerance = BRep_Tool::Tolerance(AnEdge) ;
427       //Patch
428       //max_deviation = Max(tolerance, max_deviation) ;
429       max_deviation = Max( tolerance, Tolerance );
430       if (NewCurvePtr.IsNull())
431         return Standard_False;
432       B.UpdateEdge(TopoDS::Edge(AnEdge),
433         NewCurvePtr,
434         L[0],
435         max_deviation) ;
436       if (jj == 1 ) {
437         //
438         // if there is only one curve on surface attached to the edge
439         // than it can be qualified sameparameter
440         //
441         B.SameParameter(TopoDS::Edge(AnEdge),
442           Standard_True) ;
443       }
444     }
445     else {
446       return Standard_False ;
447     }
448
449   }         
450   return Standard_True;
451 }
452 //=======================================================================
453 //function : BuildCurves3d
454 //purpose  : 
455 //=======================================================================
456
457 Standard_Boolean  BRepLib::BuildCurves3d(const TopoDS_Shape& S) 
458
459 {
460   return BRepLib::BuildCurves3d(S,
461     1.0e-5) ;
462 }
463
464 //=======================================================================
465 //function : BuildCurves3d
466 //purpose  : 
467 //=======================================================================
468
469 Standard_Boolean  BRepLib::BuildCurves3d(const TopoDS_Shape& S,
470   const Standard_Real Tolerance,
471   const GeomAbs_Shape Continuity,
472   const Standard_Integer MaxDegree,
473   const Standard_Integer MaxSegment)
474 {
475   Standard_Boolean boolean_value,
476     ok = Standard_True;
477   TopTools_MapOfShape a_counter ;
478   TopExp_Explorer ex(S,TopAbs_EDGE);
479
480   while (ex.More()) {
481     if (a_counter.Add(ex.Current())) {
482       boolean_value = 
483         BuildCurve3d(TopoDS::Edge(ex.Current()),
484         Tolerance, Continuity,
485         MaxDegree, MaxSegment);
486       ok = ok && boolean_value ;
487     }
488     ex.Next();
489   }
490   return ok;
491 }
492 //=======================================================================
493 //function : UpdateEdgeTolerance
494 //purpose  : 
495 //=======================================================================
496
497 Standard_Boolean  BRepLib::UpdateEdgeTol(const TopoDS_Edge& AnEdge,
498   const Standard_Real MinToleranceRequested,
499   const Standard_Real MaxToleranceToCheck)
500 {
501
502   Standard_Integer curve_on_surface_index,
503     curve_index,
504     not_done,
505     has_closed_curve,
506     has_curve,
507     jj,
508     ii,
509     geom_reference_curve_flag = 0,
510     max_sampling_points = 90,
511     min_sampling_points = 30 ;
512
513   Standard_Real factor = 100.0e0,
514     //     sampling_array[2],
515     safe_factor = 1.4e0,
516     current_last,
517     current_first,
518     max_distance,
519     coded_edge_tolerance,
520     edge_tolerance = 0.0e0 ;
521   Handle(TColStd_HArray1OfReal) parameters_ptr ;
522   Handle(BRep_GCurve) geometric_representation_ptr ;
523
524   if (BRep_Tool::Degenerated(AnEdge)) return Standard_False ;
525   coded_edge_tolerance = BRep_Tool::Tolerance(AnEdge) ;
526   if (coded_edge_tolerance > MaxToleranceToCheck) return Standard_False ;
527
528   const Handle(BRep_TEdge)& TE = *((Handle(BRep_TEdge)*)&AnEdge.TShape());
529   BRep_ListOfCurveRepresentation& list_curve_rep = TE->ChangeCurves() ;
530   BRep_ListIteratorOfListOfCurveRepresentation an_iterator(list_curve_rep),
531     second_iterator(list_curve_rep) ;
532   Handle(Geom2d_Curve) curve2d_ptr, new_curve2d_ptr;
533   Handle(Geom_Surface) surface_ptr ;
534   TopLoc_Location local_location ;
535   GCPnts_QuasiUniformDeflection  a_sampler ;
536   GeomAdaptor_Curve  geom_reference_curve ;
537   Adaptor3d_CurveOnSurface  curve_on_surface_reference ; 
538   Handle(Geom_Curve) C = BRep_Tool::Curve(AnEdge,
539     local_location,
540     current_first,
541     current_last);
542   curve_on_surface_index = -1 ;
543   if (!C.IsNull()) {
544     if (! local_location.IsIdentity()) {
545       C = Handle(Geom_Curve)::
546         DownCast(C-> Transformed(local_location.Transformation()) ) ;
547     }
548     geom_reference_curve.Load(C) ;
549     geom_reference_curve_flag = 1 ;
550     a_sampler.Initialize(geom_reference_curve,
551       MinToleranceRequested * factor,
552       current_first,
553       current_last) ;
554   }
555   else {
556     not_done = 1 ;
557     curve_on_surface_index = 0 ;  
558
559     while (not_done && an_iterator.More()) {
560       geometric_representation_ptr =
561         Handle(BRep_GCurve)::DownCast(second_iterator.Value());
562       if (!geometric_representation_ptr.IsNull() 
563         && geometric_representation_ptr->IsCurveOnSurface()) {
564           curve2d_ptr = geometric_representation_ptr->PCurve() ;
565           local_location = geometric_representation_ptr->Location() ;
566           current_first = geometric_representation_ptr->First();
567           //first = geometric_representation_ptr->First();
568           current_last =  geometric_representation_ptr->Last();
569           // must be inverted 
570           //
571           if (! local_location.IsIdentity() ) {
572             surface_ptr = Handle(Geom_Surface)::
573               DownCast( geometric_representation_ptr->Surface()->
574               Transformed(local_location.Transformation()) ) ;
575           }
576           else {
577             surface_ptr = 
578               geometric_representation_ptr->Surface() ;
579           }
580           not_done = 0 ;
581       }
582       curve_on_surface_index += 1 ;
583     }
584     Geom2dAdaptor_Curve     AnAdaptor3dCurve2d (curve2d_ptr) ;
585     GeomAdaptor_Surface     AnAdaptor3dSurface (surface_ptr) ;
586     Handle(Geom2dAdaptor_HCurve) AnAdaptor3dCurve2dPtr =
587       new Geom2dAdaptor_HCurve(AnAdaptor3dCurve2d) ;
588     Handle(GeomAdaptor_HSurface) AnAdaptor3dSurfacePtr =
589       new GeomAdaptor_HSurface (AnAdaptor3dSurface) ;
590     curve_on_surface_reference.Load (AnAdaptor3dCurve2dPtr, AnAdaptor3dSurfacePtr);
591     a_sampler.Initialize(curve_on_surface_reference,
592       MinToleranceRequested * factor,
593       current_first,
594       current_last) ;
595   }
596   TColStd_Array1OfReal   sampling_parameters(1,a_sampler.NbPoints()) ;
597   for (ii = 1 ; ii <= a_sampler.NbPoints() ; ii++) {
598     sampling_parameters(ii) = a_sampler.Parameter(ii) ;
599   }
600   if (a_sampler.NbPoints() < min_sampling_points) {
601     GeomLib::DensifyArray1OfReal(min_sampling_points,
602       sampling_parameters,
603       parameters_ptr) ;
604   }
605   else if (a_sampler.NbPoints() > max_sampling_points) {
606     GeomLib::RemovePointsFromArray(max_sampling_points,
607       sampling_parameters,
608       parameters_ptr) ; 
609   }
610   else {
611     jj = 1 ;
612     parameters_ptr =
613       new TColStd_HArray1OfReal(1,sampling_parameters.Length()) ;
614     for (ii = sampling_parameters.Lower() ; ii <= sampling_parameters.Upper() ; ii++) {
615       parameters_ptr->ChangeArray1()(jj) =
616         sampling_parameters(ii) ;
617       jj +=1 ;
618     }
619   }
620
621   curve_index = 0 ;
622
623   while (second_iterator.More()) {
624     geometric_representation_ptr =
625       Handle(BRep_GCurve)::DownCast(second_iterator.Value());
626     if (! geometric_representation_ptr.IsNull() && 
627       curve_index != curve_on_surface_index) {
628         has_closed_curve =
629           has_curve = Standard_False ;
630         //      first = geometric_representation_ptr->First();
631         //      last =  geometric_representation_ptr->Last();
632         local_location = geometric_representation_ptr->Location() ;
633         if (geometric_representation_ptr->IsCurveOnSurface()) {
634           curve2d_ptr = geometric_representation_ptr->PCurve() ; 
635           has_curve = Standard_True ;
636         }
637         if (geometric_representation_ptr->IsCurveOnClosedSurface()) {
638           curve2d_ptr = geometric_representation_ptr->PCurve2() ;
639           has_closed_curve = Standard_True ;
640         }
641
642         if (has_curve ||
643           has_closed_curve) {
644             if (! local_location.IsIdentity() ) {
645               surface_ptr = Handle(Geom_Surface)::
646                 DownCast( geometric_representation_ptr->Surface()->
647                 Transformed(local_location.Transformation()) ) ;
648             }
649             else {
650               surface_ptr = 
651                 geometric_representation_ptr->Surface() ;
652             }
653             Geom2dAdaptor_Curve     an_adaptor_curve2d (curve2d_ptr) ;
654             GeomAdaptor_Surface     an_adaptor_surface(surface_ptr) ;
655             Handle(Geom2dAdaptor_HCurve) an_adaptor_curve2d_ptr =
656               new Geom2dAdaptor_HCurve(an_adaptor_curve2d) ;
657             Handle(GeomAdaptor_HSurface) an_adaptor_surface_ptr =
658               new GeomAdaptor_HSurface (an_adaptor_surface) ;
659             Adaptor3d_CurveOnSurface a_curve_on_surface(an_adaptor_curve2d_ptr,
660               an_adaptor_surface_ptr) ;
661
662             if (BRep_Tool::SameParameter(AnEdge)) {
663
664               GeomLib::EvalMaxParametricDistance(a_curve_on_surface,
665                 geom_reference_curve,
666                 MinToleranceRequested,
667                 parameters_ptr->Array1(),
668                 max_distance) ;
669             }
670             else if (geom_reference_curve_flag) {
671               GeomLib::EvalMaxDistanceAlongParameter(a_curve_on_surface,
672                 geom_reference_curve,
673                 MinToleranceRequested,
674                 parameters_ptr->Array1(),
675                 max_distance) ;
676             }
677             else {
678
679               GeomLib::EvalMaxDistanceAlongParameter(a_curve_on_surface,
680                 curve_on_surface_reference,
681                 MinToleranceRequested,
682                 parameters_ptr->Array1(),
683                 max_distance) ;
684             }
685             max_distance *= safe_factor ;
686             edge_tolerance = Max(max_distance, edge_tolerance) ;
687         }
688
689
690     }
691     curve_index += 1 ;
692     second_iterator.Next() ; 
693   }
694
695   TE->Tolerance(edge_tolerance);
696   return Standard_True ;
697
698 }
699 //=======================================================================
700 //function : UpdateEdgeTolerance
701 //purpose  : 
702 //=======================================================================
703
704 Standard_Boolean BRepLib::UpdateEdgeTolerance(const TopoDS_Shape& S,
705   const Standard_Real MinToleranceRequested,
706   const Standard_Real MaxToleranceToCheck) 
707 {
708   TopExp_Explorer ex(S,TopAbs_EDGE);
709   TopTools_MapOfShape  a_counter ;
710
711   Standard_Boolean     return_status = Standard_False,
712     local_flag ;
713
714   while (ex.More()) {
715     if (a_counter.Add(ex.Current())) {
716       local_flag =
717         BRepLib::UpdateEdgeTol(TopoDS::Edge(ex.Current()),
718         MinToleranceRequested,
719         MaxToleranceToCheck) ;
720       if (local_flag && ! return_status) {
721         return_status = Standard_True ;
722       }
723     }
724     ex.Next();
725   }
726   return return_status ;
727 }
728
729 //=======================================================================
730 //function : SetEdgeTol
731 //purpose  : 
732 //=======================================================================
733
734 static void SetEdgeTol(const TopoDS_Edge& E,
735   const TopoDS_Face& F)
736 {
737   TopLoc_Location L;
738   const Handle(Geom_Surface)& S = BRep_Tool::Surface(F,L);
739   TopLoc_Location l = L.Predivided(E.Location());
740
741   const Handle(BRep_TEdge)& TE = *((Handle(BRep_TEdge)*)&E.TShape());
742   BRep_ListIteratorOfListOfCurveRepresentation itcr(TE->ChangeCurves());
743
744   while (itcr.More()) {
745     const Handle(BRep_CurveRepresentation)& cr = itcr.Value();
746     if(cr->IsCurveOnSurface(S,l)) return;
747     itcr.Next();
748   }
749
750   Handle(Geom_Plane) GP;
751   Handle(Geom_RectangularTrimmedSurface) GRTS;
752   GRTS = Handle(Geom_RectangularTrimmedSurface)::DownCast(S);
753   if(!GRTS.IsNull())
754     GP = Handle(Geom_Plane)::DownCast(GRTS->BasisSurface());
755   else
756     GP = Handle(Geom_Plane)::DownCast(S);
757
758   Handle(GeomAdaptor_HCurve) HC = new GeomAdaptor_HCurve();
759   Handle(GeomAdaptor_HSurface) HS = new GeomAdaptor_HSurface();
760
761   TopLoc_Location LC;
762   Standard_Real First, Last;
763   GeomAdaptor_Curve& GAC = HC->ChangeCurve();
764   GAC.Load(BRep_Tool::Curve(E,LC,First,Last));
765   LC = L.Predivided(LC);
766
767   if (!LC.IsIdentity()) {
768     GP = Handle(Geom_Plane)::DownCast(
769       GP->Transformed(LC.Transformation()));
770   }
771   GeomAdaptor_Surface& GAS = HS->ChangeSurface();
772   GAS.Load(GP);
773
774   ProjLib_ProjectedCurve Proj(HS,HC);
775   Handle(Geom2d_Curve) pc = Geom2dAdaptor::MakeCurve(Proj);
776
777   gp_Pln pln = GAS.Plane();
778   Standard_Real d2 = 0.;
779   Standard_Integer nn = 23;
780   Standard_Real unsurnn = 1./nn;
781   for(Standard_Integer i = 0; i <= nn; i++){
782     Standard_Real t = unsurnn*i;
783     Standard_Real u = First*(1.-t) + Last*t;
784     gp_Pnt Pc3d = HC->Value(u);
785     gp_Pnt2d p2d = pc->Value(u);
786     gp_Pnt Pcons = ElSLib::Value(p2d.X(),p2d.Y(),pln);
787     Standard_Real eps = Max(Pc3d.XYZ().SquareModulus(), Pcons.XYZ().SquareModulus());
788     eps = Epsilon(eps);
789     Standard_Real temp = Pc3d.SquareDistance(Pcons);
790     if(temp <= eps)
791     {
792       temp = 0.;
793     }
794     if(temp > d2) d2 = temp;
795   }
796   d2 = 1.5*sqrt(d2);
797   TE->UpdateTolerance(d2);
798 }
799
800 //=======================================================================
801 //function : SameParameter
802 //purpose  : 
803 //=======================================================================
804 void  BRepLib::SameParameter(const TopoDS_Shape& S,
805   const Standard_Real Tolerance,
806   const Standard_Boolean forced) 
807 {
808   TopExp_Explorer ex(S,TopAbs_EDGE);
809   TopTools_MapOfShape  Done;
810   BRep_Builder brB;
811
812   while (ex.More()) {
813     if (Done.Add(ex.Current())) {
814       if (forced) {
815         brB.SameRange(TopoDS::Edge(ex.Current()), Standard_False);
816         brB.SameParameter(TopoDS::Edge(ex.Current()), Standard_False);
817       }
818       BRepLib::SameParameter(TopoDS::Edge(ex.Current()),Tolerance);
819     }
820     ex.Next();
821   }
822
823   Done.Clear();
824   BRepAdaptor_Surface BS;
825   for(ex.Init(S,TopAbs_FACE); ex.More(); ex.Next()){
826     const TopoDS_Face& curface = TopoDS::Face(ex.Current());
827     if(!Done.Add(curface)) continue;
828     BS.Initialize(curface);
829     if(BS.GetType() != GeomAbs_Plane) continue;
830     TopExp_Explorer ex2;
831     for(ex2.Init(curface,TopAbs_EDGE); ex2.More(); ex2.Next()){
832       const TopoDS_Edge& E = TopoDS::Edge(ex2.Current());
833       SetEdgeTol(E,curface);
834     }
835   }
836   BRepLib::UpdateTolerances(S);
837 }
838
839 //================================================================
840 //function : SameParameter
841 //WARNING  : New spec DUB LBO 9/9/97.
842 //  Recode in the edge the best tolerance found, 
843 //  for vertex extremities it is required to find something else
844 //================================================================
845 static Standard_Boolean EvalTol(const Handle(Geom2d_Curve)& pc,
846   const Handle(Geom_Surface)& s,
847   const GeomAdaptor_Curve&    gac,
848   const Standard_Real         tol,
849   Standard_Real&              tolbail)
850 {
851   Standard_Integer ok = 0;
852   Standard_Real f = gac.FirstParameter();
853   Standard_Real l = gac.LastParameter();
854   Extrema_LocateExtPC Projector;
855   Projector.Initialize(gac,f,l,tol);
856   Standard_Real u,v;
857   gp_Pnt p;
858   tolbail = tol;
859   for(Standard_Integer i = 1; i <= 5; i++){
860     Standard_Real t = i/6.;
861     t = (1.-t) * f + t * l;
862     pc->Value(t).Coord(u,v);
863     p = s->Value(u,v);
864     Projector.Perform(p,t);
865     if (Projector.IsDone()) {
866       Standard_Real dist2 = Projector.SquareDistance();
867       if(dist2 > tolbail * tolbail) tolbail = sqrt (dist2);
868       ok++;
869     }
870   }
871   return (ok > 2);
872 }
873
874 static Standard_Real ComputeTol(const Handle(Adaptor3d_HCurve)& c3d,
875   const Handle(Adaptor2d_HCurve2d)& c2d,
876   const Handle(Adaptor3d_HSurface)& surf,
877   const Standard_Integer        nbp)
878
879 {
880
881   TColStd_Array1OfReal dist(1,nbp+10);
882   dist.Init(-1.);
883
884   Adaptor3d_CurveOnSurface  cons(c2d,surf);
885   Standard_Real d2 = 0.;
886   Standard_Real first = c3d->FirstParameter();
887   Standard_Real last  = c3d->LastParameter();
888   Standard_Integer i = 0;
889   for(i = 0; i <= nbp; i++){
890     const Standard_Real t = IntToReal(i)/IntToReal(nbp);
891     const Standard_Real u = first*(1.-t) + last*t;
892     gp_Pnt Pc3d = c3d->Value(u);
893     gp_Pnt Pcons = cons.Value(u);
894     if (Precision::IsInfinite(Pcons.X()) ||
895       Precision::IsInfinite(Pcons.Y()) ||
896       Precision::IsInfinite(Pcons.Z())) {
897         d2=Precision::Infinite();
898         break;
899     }
900     Standard_Real temp = Pc3d.SquareDistance(Pcons);
901
902
903     dist(i+1) = temp;
904
905
906     if(temp > d2) d2 = temp;
907   }
908
909
910   Standard_Boolean ana = Standard_False;
911   Standard_Real D2 = 0;
912   Standard_Integer N1 = 0;
913   Standard_Integer N2 = 0;
914   Standard_Integer N3 = 0;
915
916   for( i = 1; i<= nbp+10; i++)
917     if( dist(i) > 0 ) {
918       if( dist(i) < 1.0 ) N1++;
919       else N2++;
920     }
921
922     if( N1 > N2 && N2 != 0 ) N3 = 100*N2/(N1+N2);
923     if( N3 < 10 && N3 != 0 ) {
924       ana = Standard_True;
925       for( i = 1; i<= nbp+10; i++)
926         if( dist(i) > 0 && dist(i) < 1.0 )
927           if( dist(i) > D2 ) D2 = dist(i);
928     }
929
930     //d2 = 1.5*sqrt(d2);
931     d2 = (!ana) ? 1.5*sqrt(d2) : 1.5*sqrt(D2);
932     if(d2<1.e-7) d2 = 1.e-7;
933
934     return d2;
935 }
936
937 void BRepLib::SameParameter(const TopoDS_Edge&  AnEdge,
938   const Standard_Real Tolerance)
939 {
940   if (BRep_Tool::SameParameter(AnEdge)) return;
941
942   const Standard_Integer NCONTROL = 22;
943
944   Handle(GeomAdaptor_HCurve) HC = new GeomAdaptor_HCurve();
945   Handle(Geom2dAdaptor_HCurve) HC2d = new Geom2dAdaptor_HCurve();
946   Handle(GeomAdaptor_HSurface) HS = new GeomAdaptor_HSurface();
947   GeomAdaptor_Curve& GAC = HC->ChangeCurve();
948   Geom2dAdaptor_Curve& GAC2d = HC2d->ChangeCurve2d();
949   GeomAdaptor_Surface& GAS = HS->ChangeSurface();
950   Standard_Real f3d =0.,l3d =0.;
951   TopLoc_Location L3d;
952   Handle(Geom_Curve) C3d;
953
954   const Handle(BRep_TEdge)& TE = *((Handle(BRep_TEdge)*) &AnEdge.TShape());
955   BRep_ListOfCurveRepresentation& CList = TE->ChangeCurves();
956   BRep_ListIteratorOfListOfCurveRepresentation It(CList);
957
958   Standard_Boolean NotDone = Standard_True;
959
960   while (NotDone && It.More()) {
961     Handle(BRep_GCurve) GCurve = Handle(BRep_GCurve)::DownCast(It.Value());
962     if (!GCurve.IsNull() && GCurve->IsCurve3D()) {
963       C3d = GCurve->Curve3D() ;
964       f3d = GCurve->First();
965       l3d = GCurve->Last();
966       L3d = GCurve->Location() ;
967       NotDone = Standard_False;
968     } 
969     It.Next() ;
970   }
971
972   if(C3d.IsNull()) return;
973
974   // modified by NIZHNY-OCC486  Tue Aug 27 17:15:13 2002 :
975   Standard_Boolean m_TrimmedPeriodical = Standard_False;
976   Handle(Standard_Type) TheType = C3d->DynamicType();
977   if( TheType == STANDARD_TYPE(Geom_TrimmedCurve))
978   {
979     Handle(Geom_Curve) gtC (Handle(Geom_TrimmedCurve)::DownCast (C3d)->BasisCurve());
980     m_TrimmedPeriodical = gtC->IsPeriodic();
981   }
982   // modified by NIZHNY-OCC486  Tue Aug 27 17:15:17 2002 .
983
984   BRep_Builder B;
985   if(!C3d->IsPeriodic()) {
986     Standard_Real Udeb = C3d->FirstParameter();
987     Standard_Real Ufin = C3d->LastParameter();
988     // modified by NIZHNY-OCC486  Tue Aug 27 17:17:14 2002 :
989     //if (Udeb > f3d) f3d = Udeb;
990     //if (l3d > Ufin) l3d = Ufin;
991     if(!m_TrimmedPeriodical)
992     {
993       if (Udeb > f3d) f3d = Udeb;
994       if (l3d > Ufin) l3d = Ufin;
995     }
996     // modified by NIZHNY-OCC486  Tue Aug 27 17:17:55 2002 .
997   }
998   if(!L3d.IsIdentity()){
999     C3d = Handle(Geom_Curve)::DownCast(C3d->Transformed(L3d.Transformation()));
1000   }
1001   GAC.Load(C3d,f3d,l3d);
1002
1003   Standard_Boolean IsSameP = 1;
1004   Standard_Real maxdist = 0.;
1005
1006   //  Modified by skv - Thu Jun  3 12:39:19 2004 OCC5898 Begin
1007   Standard_Real anEdgeTol = BRep_Tool::Tolerance(AnEdge);
1008   //  Modified by skv - Thu Jun  3 12:39:20 2004 OCC5898 End
1009   Standard_Boolean SameRange = BRep_Tool::SameRange(AnEdge);
1010   Standard_Boolean YaPCu = Standard_False;
1011   It.Initialize(CList);
1012
1013   while (It.More()) {
1014     Standard_Boolean isANA = Standard_False;
1015     Standard_Boolean isBSP = Standard_False;
1016     Handle(BRep_GCurve) GCurve = Handle(BRep_GCurve)::DownCast(It.Value());
1017     Handle(Geom2d_Curve) PC[2];
1018     Handle(Geom_Surface) S;
1019     if (!GCurve.IsNull() && GCurve->IsCurveOnSurface()) {
1020       YaPCu = Standard_True;
1021       PC[0] = GCurve->PCurve();
1022       TopLoc_Location PCLoc = GCurve->Location();
1023       S = GCurve->Surface();
1024       if (!PCLoc.IsIdentity() ) {
1025         S = Handle(Geom_Surface)::DownCast(S->Transformed(PCLoc.Transformation()));
1026       }
1027
1028       GAS.Load(S);
1029       if (GCurve->IsCurveOnClosedSurface()) {
1030         PC[1] = GCurve->PCurve2();
1031       }
1032
1033       // Eval tol2d to compute SameRange
1034       Standard_Real UResol = Max(GAS.UResolution(Tolerance), Precision::PConfusion());
1035       Standard_Real VResol = Max(GAS.VResolution(Tolerance), Precision::PConfusion());
1036       Standard_Real Tol2d  = Min(UResol, VResol);
1037       for(Standard_Integer i = 0; i < 2; i++){
1038         Handle(Geom2d_Curve) curPC = PC[i];
1039         Standard_Boolean updatepc = 0;
1040         if(curPC.IsNull()) break;
1041         if(!SameRange){
1042           GeomLib::SameRange(Tol2d,
1043             PC[i],GCurve->First(),GCurve->Last(),
1044             f3d,l3d,curPC);
1045
1046           updatepc = (curPC != PC[i]);
1047
1048         }
1049         Standard_Boolean goodpc = 1;
1050         GAC2d.Load(curPC,f3d,l3d);
1051
1052         Standard_Real error = ComputeTol(HC, HC2d, HS, NCONTROL);
1053
1054         if(GAC2d.GetType() == GeomAbs_BSplineCurve && 
1055           GAC2d.Continuity() == GeomAbs_C0) {
1056             Handle(Geom2d_BSplineCurve) bs2d = GAC2d.BSpline();
1057             Handle(Geom2d_BSplineCurve) bs2dsov = bs2d;
1058             Standard_Real fC0 = bs2d->FirstParameter(), lC0 = bs2d->LastParameter();
1059             Standard_Boolean repar = Standard_True;
1060             gp_Pnt2d OriginPoint;
1061             bs2d->D0(fC0, OriginPoint);
1062             Geom2dConvert::C0BSplineToC1BSplineCurve(bs2d, Tol2d);
1063             isBSP = Standard_True; 
1064
1065             if(bs2d->IsPeriodic()) { // -------- IFV, Jan 2000
1066               gp_Pnt2d NewOriginPoint;
1067               bs2d->D0(bs2d->FirstParameter(), NewOriginPoint);
1068               if(Abs(OriginPoint.X() - NewOriginPoint.X()) > Precision::PConfusion() ||
1069                 Abs(OriginPoint.Y() - NewOriginPoint.Y()) > Precision::PConfusion()    ) {
1070
1071                   TColStd_Array1OfReal Knotbs2d (1, bs2d->NbKnots());
1072                   bs2d->Knots(Knotbs2d);
1073
1074                   for(Standard_Integer Index = 1; Index <= bs2d->NbKnots(); Index++) {
1075                     bs2d->D0(Knotbs2d(Index), NewOriginPoint);
1076                     if(Abs(OriginPoint.X() - NewOriginPoint.X()) > Precision::PConfusion() ||
1077                       Abs(OriginPoint.Y() - NewOriginPoint.Y()) > Precision::PConfusion()    ) continue;
1078
1079                     bs2d->SetOrigin(Index);
1080                     break;
1081                   }
1082               }
1083             }
1084
1085             if(bs2d->Continuity() == GeomAbs_C0) {
1086               Standard_Real tolbail;
1087               if(EvalTol(curPC,S,GAC,Tolerance,tolbail)){
1088                 bs2d = bs2dsov;
1089                 Standard_Real UResbail = GAS.UResolution(tolbail);
1090                 Standard_Real VResbail = GAS.VResolution(tolbail);
1091                 Standard_Real Tol2dbail  = Min(UResbail,VResbail);
1092                 bs2d->D0(bs2d->FirstParameter(), OriginPoint); 
1093
1094                 Standard_Integer nbp = bs2d->NbPoles();
1095                 TColgp_Array1OfPnt2d poles(1,nbp);
1096                 bs2d->Poles(poles);
1097                 gp_Pnt2d p = poles(1), p1;
1098                 Standard_Real d = Precision::Infinite();
1099                 for(Standard_Integer ip = 2; ip <= nbp; ip++) {
1100                   p1 = poles(ip);
1101                   d = Min(d,p.SquareDistance(p1));
1102                   p = p1;
1103                 }
1104                 d = sqrt(d)*.1;
1105
1106                 Tol2dbail = Max(Min(Tol2dbail,d),Tol2d);
1107
1108                 Geom2dConvert::C0BSplineToC1BSplineCurve(bs2d,Tol2dbail);
1109
1110                 if(bs2d->IsPeriodic()) { // -------- IFV, Jan 2000
1111                   gp_Pnt2d NewOriginPoint;
1112                   bs2d->D0(bs2d->FirstParameter(), NewOriginPoint);
1113                   if(Abs(OriginPoint.X() - NewOriginPoint.X()) > Precision::PConfusion() ||
1114                     Abs(OriginPoint.Y() - NewOriginPoint.Y()) > Precision::PConfusion()    ) {
1115
1116                       TColStd_Array1OfReal Knotbs2d (1, bs2d->NbKnots());
1117                       bs2d->Knots(Knotbs2d);
1118
1119                       for(Standard_Integer Index = 1; Index <= bs2d->NbKnots(); Index++) {
1120                         bs2d->D0(Knotbs2d(Index), NewOriginPoint);
1121                         if(Abs(OriginPoint.X() - NewOriginPoint.X()) > Precision::PConfusion() ||
1122                           Abs(OriginPoint.Y() - NewOriginPoint.Y()) > Precision::PConfusion()    ) continue;
1123
1124                         bs2d->SetOrigin(Index);
1125                         break;
1126                       }
1127                   }
1128                 }
1129
1130
1131                 if(bs2d->Continuity() == GeomAbs_C0) {
1132                   goodpc = 1;
1133                   bs2d = bs2dsov;
1134                   repar = Standard_False;
1135                 }
1136               }
1137               else goodpc = 0;
1138             }
1139
1140             if(goodpc){
1141               if(repar) {
1142                 Standard_Integer NbKnots = bs2d->NbKnots();
1143                 TColStd_Array1OfReal Knots(1,NbKnots);
1144                 bs2d->Knots(Knots);
1145                 //          BSplCLib::Reparametrize(f3d,l3d,Knots);
1146                 BSplCLib::Reparametrize(fC0,lC0,Knots);
1147                 bs2d->SetKnots(Knots);
1148                 GAC2d.Load(bs2d,f3d,l3d);
1149                 curPC = bs2d;
1150                 Standard_Boolean updatepcsov = updatepc;
1151                 updatepc = Standard_True;
1152
1153                 Standard_Real error1 = ComputeTol(HC, HC2d, HS, NCONTROL);
1154                 if(error1 > error) {
1155                   bs2d = bs2dsov;
1156                   GAC2d.Load(bs2d,f3d,l3d);
1157                   curPC = bs2d;
1158                   updatepc = updatepcsov;
1159                   isANA = Standard_True;
1160                 }
1161                 else {
1162                   error = error1;
1163                 }
1164               }
1165
1166               //check, if new BSpline "good" or not --------- IFV, Jan of 2000
1167               GeomAbs_Shape cont = bs2d->Continuity();
1168               Standard_Boolean IsBad = Standard_False;
1169
1170               if(cont > GeomAbs_C0 && error > Max(1.e-3,Tolerance)) {
1171                 Standard_Integer NbKnots = bs2d->NbKnots();
1172                 TColStd_Array1OfReal Knots(1,NbKnots);
1173                 bs2d->Knots(Knots);
1174                 Standard_Real critratio = 10.; 
1175                 Standard_Real dtprev = Knots(2) - Knots(1), dtratio = 1.;
1176                 Standard_Real dtmin = dtprev;
1177                 Standard_Real dtcur;
1178                 for(Standard_Integer j = 2; j < NbKnots; j++) {
1179                   dtcur = Knots(j+1) - Knots(j);
1180                   dtmin = Min(dtmin, dtcur);
1181
1182                   if(IsBad) continue;
1183
1184                   if(dtcur > dtprev) dtratio = dtcur/dtprev;
1185                   else dtratio = dtprev/dtcur;
1186                   if(dtratio > critratio) {IsBad = Standard_True;}
1187                   dtprev = dtcur;
1188
1189                 }
1190                 if(IsBad) {
1191                   // To avoid failures in Approx_CurvilinearParameter 
1192                   bs2d->Resolution(Max(1.e-3,Tolerance), dtcur);
1193                   if(dtmin < dtcur) IsBad = Standard_False;
1194                 }
1195               }
1196
1197
1198               if(IsBad ) { //if BSpline "bad", try to reparametrize it
1199                 // by its curve length
1200
1201                 //            GeomAbs_Shape cont = bs2d->Continuity();
1202                 if(cont > GeomAbs_C2) cont = GeomAbs_C2;
1203                 Standard_Integer maxdeg = bs2d->Degree();
1204                 if(maxdeg == 1) maxdeg = 14;
1205                 Approx_CurvilinearParameter AppCurPar(HC2d, HS, Max(1.e-3,Tolerance),
1206                   cont, maxdeg, 10);
1207                 if(AppCurPar.IsDone() || AppCurPar.HasResult()) {
1208                   bs2d = AppCurPar.Curve2d1();
1209                   GAC2d.Load(bs2d,f3d,l3d);
1210                   curPC = bs2d;
1211
1212                   if(Abs(bs2d->FirstParameter() - fC0) > Tol2d ||
1213                     Abs(bs2d->LastParameter() - lC0) > Tol2d    ) {
1214                       Standard_Integer NbKnots = bs2d->NbKnots();
1215                       TColStd_Array1OfReal Knots(1,NbKnots);
1216                       bs2d->Knots(Knots);
1217                       //                  BSplCLib::Reparametrize(f3d,l3d,Knots);
1218                       BSplCLib::Reparametrize(fC0,lC0,Knots);
1219                       bs2d->SetKnots(Knots);
1220                       GAC2d.Load(bs2d,f3d,l3d);
1221                       curPC = bs2d;
1222
1223                   }
1224                 }
1225               }
1226
1227
1228             }
1229         }
1230
1231
1232         if(goodpc){
1233           //      Approx_SameParameter SameP(HC,HC2d,HS,Tolerance);
1234           Standard_Real aTol = (isANA && isBSP) ? 1.e-7 : Tolerance;
1235           const Handle(Adaptor3d_HCurve)& aHCurv = HC; // to avoid ambiguity
1236           const Handle(Adaptor2d_HCurve2d)& aHCurv2d = HC2d; // to avoid ambiguity
1237           Approx_SameParameter SameP(aHCurv,aHCurv2d,HS,aTol);
1238
1239           if (SameP.IsSameParameter()) {
1240             maxdist = Max(maxdist,SameP.TolReached());
1241             if(updatepc){
1242               if (i == 0) GCurve->PCurve(curPC);
1243               else GCurve->PCurve2(curPC);
1244             }
1245           }
1246           else if (SameP.IsDone()) {
1247             Standard_Real tolreached = SameP.TolReached();
1248             if(tolreached < error) {
1249               curPC = SameP.Curve2d();
1250               updatepc = Standard_True;
1251               maxdist = Max(maxdist,tolreached);
1252             }
1253             else {
1254               maxdist = Max(maxdist, error);
1255             }
1256             if(updatepc){
1257               if (i == 0) GCurve->PCurve(curPC);
1258               else GCurve->PCurve2(curPC);
1259             }
1260           }
1261           else IsSameP = 0;
1262
1263         }
1264         else IsSameP = 0;
1265
1266         //  Modified by skv - Thu Jun  3 12:39:19 2004 OCC5898 Begin
1267         if (!IsSameP) {
1268           if (anEdgeTol > error) {
1269             maxdist = Max(maxdist, anEdgeTol);
1270             IsSameP = Standard_True;
1271           }
1272         }
1273         //  Modified by skv - Thu Jun  3 12:39:20 2004 OCC5898 End
1274       }
1275     }
1276     It.Next() ;
1277   }
1278   B.Range(AnEdge,f3d,l3d);
1279   B.SameRange(AnEdge,Standard_True);
1280   if ( IsSameP) {
1281     // Reduce eventually the tolerance of the edge, as
1282     // all its representations are processed (except for some associated
1283     // to planes and not stored in the edge !) 
1284     // The same cannot be done with vertices that cannot be enlarged 
1285     // or left as is.
1286     if (YaPCu) {
1287       // Avoid setting too small tolerances.
1288       maxdist = Max(maxdist,Precision::Confusion());
1289       TopoDS_Vertex V1,V2;
1290       TopExp::Vertices(AnEdge,V1,V2);
1291       if (!V1.IsNull())
1292         B.UpdateVertex(V1,maxdist);
1293       if (!V2.IsNull())
1294         B.UpdateVertex(V2,maxdist);
1295       TE->Modified(Standard_True);
1296       TE->Tolerance(maxdist);
1297     }
1298     B.SameParameter(AnEdge,Standard_True);
1299   }
1300 }
1301
1302 //=======================================================================
1303 //function : UpdateTolerances
1304 //purpose  : 
1305 //=======================================================================
1306 void  BRepLib::UpdateTolerances(const TopoDS_Shape& aShape,
1307   const Standard_Boolean verifyTolerance) 
1308 {
1309
1310   // Harmonize tolerances
1311   // with rule Tolerance(VERTEX)>=Tolerance(EDGE)>=Tolerance(FACE)
1312   BRep_Builder B;
1313   Standard_Real tol=0;
1314   if (verifyTolerance) {
1315     // Set tolerance to its minimum value
1316     Handle(Geom_Surface) S;
1317     TopLoc_Location l;
1318     TopExp_Explorer ex;
1319     Bnd_Box aB;
1320     Standard_Real aXmin, aYmin, aZmin, aXmax, aYmax, aZmax, dMax;
1321     for (ex.Init(aShape, TopAbs_FACE); ex.More(); ex.Next()) {
1322       const TopoDS_Face& curf=TopoDS::Face(ex.Current());
1323       S = BRep_Tool::Surface(curf, l);
1324       if (!S.IsNull()) {
1325         aB.SetVoid();
1326         BRepBndLib::Add(curf,aB);
1327         if (S->DynamicType() == STANDARD_TYPE(Geom_RectangularTrimmedSurface)) {
1328           S = Handle(Geom_RectangularTrimmedSurface)::DownCast (S)->BasisSurface();
1329         }
1330         GeomAdaptor_Surface AS(S);
1331         switch (AS.GetType()) {
1332         case GeomAbs_Plane: 
1333         case GeomAbs_Cylinder: 
1334         case GeomAbs_Cone: 
1335           {
1336             tol=Precision::Confusion();
1337             break;
1338           }
1339         case GeomAbs_Sphere: 
1340         case GeomAbs_Torus: 
1341           {
1342             tol=Precision::Confusion()*2;
1343             break;
1344           }
1345         default:
1346           tol=Precision::Confusion()*4;
1347         }
1348         if (!aB.IsWhole()) {
1349           aB.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
1350           dMax=1.;
1351           if (!aB.IsOpenXmin() && !aB.IsOpenXmax()) dMax=aXmax-aXmin;
1352           if (!aB.IsOpenYmin() && !aB.IsOpenYmax()) aYmin=aYmax-aYmin;
1353           if (!aB.IsOpenZmin() && !aB.IsOpenZmax()) aZmin=aZmax-aZmin;
1354           if (aYmin>dMax) dMax=aYmin;
1355           if (aZmin>dMax) dMax=aZmin;
1356           tol=tol*dMax;
1357           // Do not process tolerances > 1.
1358           if (tol>1.) tol=0.99;
1359         }
1360         const Handle(BRep_TFace)& Tf = *((Handle(BRep_TFace)*)&curf.TShape());
1361         Tf->Tolerance(tol);
1362       }
1363     }
1364   }
1365
1366   //Process edges
1367   TopTools_IndexedDataMapOfShapeListOfShape parents;
1368   TopExp::MapShapesAndAncestors(aShape, TopAbs_EDGE, TopAbs_FACE, parents);
1369   TopTools_ListIteratorOfListOfShape lConx;
1370   Standard_Integer iCur;
1371   for (iCur=1; iCur<=parents.Extent(); iCur++) {
1372     tol=0;
1373     for (lConx.Initialize(parents(iCur)); lConx.More(); lConx.Next()) {
1374       tol=Max(tol, BRep_Tool::Tolerance(TopoDS::Face(lConx.Value())));
1375     }
1376     // Update can only increase tolerance, so if the edge has a greater
1377     //  tolerance than its faces it is not concerned
1378     B.UpdateEdge(TopoDS::Edge(parents.FindKey(iCur)), tol);
1379   }
1380
1381   //Vertices are processed
1382   parents.Clear();
1383   TopExp::MapShapesAndAncestors(aShape, TopAbs_VERTEX, TopAbs_EDGE, parents);
1384   TColStd_MapOfTransient Initialized;
1385   TopTools_MapOfShape Done;
1386   Standard_Integer nbV = parents.Extent();
1387   for (iCur=1; iCur<=nbV; iCur++) {
1388     tol=0;
1389     Done.Clear();
1390     const TopoDS_Vertex& V = TopoDS::Vertex(parents.FindKey(iCur));
1391     Bnd_Box box;
1392     box.Add(BRep_Tool::Pnt(V));
1393     gp_Pnt p3d;
1394     for (lConx.Initialize(parents(iCur)); lConx.More(); lConx.Next()) {
1395       const TopoDS_Edge& E = TopoDS::Edge(lConx.Value());
1396       if(!Done.Add(E)) continue;
1397       tol=Max(tol, BRep_Tool::Tolerance(E));
1398       if(!BRep_Tool::SameRange(E)) continue;
1399       Standard_Real par = BRep_Tool::Parameter(V,E);
1400       Handle(BRep_TEdge)& TE = *((Handle(BRep_TEdge)*)&E.TShape());
1401       BRep_ListIteratorOfListOfCurveRepresentation itcr(TE->Curves());
1402       const TopLoc_Location& Eloc = E.Location();
1403       while (itcr.More()) {
1404         // For each CurveRepresentation, check the provided parameter
1405         const Handle(BRep_CurveRepresentation)& cr = itcr.Value();
1406         const TopLoc_Location& loc = cr->Location();
1407         TopLoc_Location L = (Eloc * loc);
1408         if (cr->IsCurve3D()) {
1409           const Handle(Geom_Curve)& C = cr->Curve3D();
1410           if (!C.IsNull()) { // edge non degenerated
1411             p3d = C->Value(par);
1412             p3d.Transform(L.Transformation());
1413             box.Add(p3d);
1414           }
1415         }
1416         else if (cr->IsCurveOnSurface()) {
1417           const Handle(Geom_Surface)& Su = cr->Surface();
1418           const Handle(Geom2d_Curve)& PC = cr->PCurve();
1419           Handle(Geom2d_Curve) PC2;
1420           if (cr->IsCurveOnClosedSurface()) {
1421             PC2 = cr->PCurve2();
1422           }
1423           gp_Pnt2d p2d = PC->Value(par);
1424           p3d = Su->Value(p2d.X(),p2d.Y());
1425           p3d.Transform(L.Transformation());
1426           box.Add(p3d);
1427           if (!PC2.IsNull()) {
1428             p2d = PC2->Value(par);
1429             p3d = Su->Value(p2d.X(),p2d.Y());
1430             p3d.Transform(L.Transformation());
1431             box.Add(p3d);
1432           }
1433         }
1434         itcr.Next();
1435       }
1436     }
1437     Standard_Real aXmin, aYmin, aZmin, aXmax, aYmax, aZmax;
1438     box.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
1439     aXmax -= aXmin; aYmax -= aYmin; aZmax -= aZmin;
1440     tol = Max(tol,sqrt(aXmax*aXmax+aYmax*aYmax+aZmax*aZmax));
1441     tol += 2.*Epsilon(tol);
1442     if (verifyTolerance) {
1443       // ASet minimum value of the tolerance 
1444       // Attention to sharing of the vertex by other shapes
1445       const Handle(BRep_TVertex)& TV = *((Handle(BRep_TVertex)*)&V.TShape());
1446       if (Initialized.Add(TV)) 
1447         TV->Tolerance(tol);
1448       else 
1449         B.UpdateVertex(V, tol);
1450     }
1451     else {
1452       // Update can only increase tolerance, so if the edge has a greater
1453       //  tolerance than its faces it is not concerned
1454       B.UpdateVertex(V, tol);
1455     }
1456   }
1457 }
1458
1459 //=======================================================================
1460 //function : OrientClosedSolid
1461 //purpose  : 
1462 //=======================================================================
1463 Standard_Boolean BRepLib::OrientClosedSolid(TopoDS_Solid& solid) 
1464 {
1465   // Set material inside the solid
1466   BRepClass3d_SolidClassifier where(solid);
1467   where.PerformInfinitePoint(Precision::Confusion());
1468   if (where.State()==TopAbs_IN) {
1469     solid.Reverse();
1470   }
1471   else if (where.State()==TopAbs_ON || where.State()==TopAbs_UNKNOWN) 
1472     return Standard_False;
1473
1474   return Standard_True;
1475 }
1476
1477 //=======================================================================
1478 //function : tgtfaces
1479 //purpose  : check the angle at the border between two squares.
1480 //           Two shares should have a shared front edge.
1481 //=======================================================================
1482
1483 static Standard_Boolean tgtfaces(const TopoDS_Edge& Ed,
1484   const TopoDS_Face& F1,
1485   const TopoDS_Face& F2,
1486   const Standard_Real ta,
1487   const Standard_Boolean couture)
1488 {
1489   // Check if pcurves exist on both faces of edge
1490   Standard_Real aFirst,aLast;
1491   Handle(Geom2d_Curve) aCurve;
1492   aCurve = BRep_Tool::CurveOnSurface(Ed,F1,aFirst,aLast);
1493   if(aCurve.IsNull())
1494     return Standard_False;
1495   aCurve = BRep_Tool::CurveOnSurface(Ed,F2,aFirst,aLast);
1496   if(aCurve.IsNull())
1497     return Standard_False;
1498
1499   Standard_Real u;
1500   TopoDS_Edge E = Ed;
1501   BRepAdaptor_Surface aBAS1(F1,Standard_False);
1502   BRepAdaptor_Surface aBAS2(F2,Standard_False);
1503   Handle(BRepAdaptor_HSurface) HS1 = new BRepAdaptor_HSurface(aBAS1);
1504   Handle(BRepAdaptor_HSurface) HS2;
1505   if(couture) HS2 = HS1;
1506   else HS2 = new BRepAdaptor_HSurface(aBAS2);
1507
1508   E.Orientation(TopAbs_FORWARD);
1509   Handle(BRepAdaptor_HCurve2d) HC2d1 = new BRepAdaptor_HCurve2d();
1510   HC2d1->ChangeCurve2d().Initialize(E,F1);
1511   if(couture) E.Orientation(TopAbs_REVERSED);
1512   Handle(BRepAdaptor_HCurve2d) HC2d2 = new BRepAdaptor_HCurve2d();
1513   HC2d2->ChangeCurve2d().Initialize(E,F2);
1514   Adaptor3d_CurveOnSurface C1(HC2d1,HS1);
1515   Adaptor3d_CurveOnSurface C2(HC2d2,HS2);
1516
1517   Standard_Boolean rev1 = (F1.Orientation() == TopAbs_REVERSED);
1518   Standard_Boolean rev2 = (F2.Orientation() == TopAbs_REVERSED);
1519   Standard_Real f,l,eps, angmax = -M_PI;
1520   Standard_Real ang =0.;
1521   BRep_Tool::Range(E,f,l);
1522   Extrema_LocateExtPC ext;
1523   Standard_Boolean IsInitialized = Standard_False;
1524
1525   eps = (l - f)/100.;
1526   f += eps; // to avoid calculations on  
1527   l -= eps; // points of pointed squares.
1528   gp_Pnt2d p;
1529   gp_Pnt pp1,pp2;//,PP;
1530   gp_Vec du,dv;
1531   gp_Vec d1,d2;
1532   Standard_Real uu, vv, norm;
1533
1534   Standard_Integer i;
1535   Standard_Boolean Nok;
1536   for(i = 0; (i<= 20) && (angmax<=ta) ; i++){
1537     // First suppose that this is sameParameter
1538     Nok = Standard_True;
1539     u = f + (l-f)*i/20;
1540     HC2d1->D0(u,p);
1541     HS1->D1(p.X(),p.Y(),pp1,du,dv);
1542     d1 = (du.Crossed(dv));
1543     norm = d1.Magnitude(); 
1544     if (norm > 1.e-12) d1 /= norm;
1545     else Nok=Standard_False;
1546     if(rev1) d1.Reverse();
1547
1548     HC2d2->D0(u,p);
1549     HS2->D1(p.X(), p.Y(), pp2, du, dv);
1550     d2 = (du.Crossed(dv));
1551     norm = d2.Magnitude();
1552     if (norm> 1.e-12) d2 /= norm;
1553     else Nok=Standard_False;
1554     if(rev2) d2.Reverse();
1555     if (Nok) ang = d1.Angle(d2);
1556
1557     if (Nok &&(ang > ta)) { // Refine by projection
1558       if (! IsInitialized ) {
1559         ext.Initialize(C2,f,l,Precision::PConfusion());
1560         IsInitialized = Standard_True;
1561       }      
1562       ext.Perform(pp1,u);
1563       if(ext.IsDone() && ext.IsMin()){
1564         Extrema_POnCurv poc = ext.Point();
1565         Standard_Real v = poc.Parameter();
1566
1567         HC2d2->D0(v,p);
1568         p.Coord(uu,vv);
1569         HS2->D1(p.X(), p.Y(), pp2, du, dv);
1570         d2 = (du.Crossed(dv));
1571         norm = d2.Magnitude();
1572         if (norm> 1.e-12) d2 /= norm;
1573         else Nok = Standard_False;
1574         if(rev2) d2.Reverse();
1575         if (Nok) ang = d1.Angle(d2);
1576       }
1577     }
1578     if(ang >= angmax) angmax = ang;
1579   }     
1580
1581   return (angmax<=ta);
1582
1583 }
1584
1585
1586 //=======================================================================
1587 // function : EncodeRegularity
1588 // purpose  : code the regularities on all edges of the shape, boundary of 
1589 //            two faces that do not have it.
1590 //=======================================================================
1591
1592 void BRepLib::EncodeRegularity(const TopoDS_Shape& S,
1593   const Standard_Real TolAng)
1594 {
1595   BRep_Builder B;
1596   TopTools_IndexedDataMapOfShapeListOfShape M;
1597   TopExp::MapShapesAndAncestors(S,TopAbs_EDGE,TopAbs_FACE,M);
1598   TopTools_ListIteratorOfListOfShape It;
1599   TopExp_Explorer Ex;
1600   TopoDS_Face F1,F2;
1601   Standard_Boolean found, couture;
1602   for(Standard_Integer i = 1; i <= M.Extent(); i++){
1603     TopoDS_Edge E = TopoDS::Edge(M.FindKey(i));
1604     found = Standard_False; couture = Standard_False;
1605     F1.Nullify();
1606     for(It.Initialize(M.FindFromIndex(i));It.More() && !found;It.Next()){
1607       if(F1.IsNull()) { F1 = TopoDS::Face(It.Value()); }
1608       else {
1609         if(!F1.IsSame(TopoDS::Face(It.Value()))){
1610           found = Standard_True;
1611           F2 = TopoDS::Face(It.Value());
1612         }
1613       }
1614     }
1615     if (!found && !F1.IsNull()){//is it a sewing edge?
1616       TopAbs_Orientation orE = E.Orientation();
1617       TopoDS_Edge curE;
1618       for(Ex.Init(F1,TopAbs_EDGE);Ex.More() && !found;Ex.Next()){
1619         curE= TopoDS::Edge(Ex.Current());
1620         if(E.IsSame(curE) && orE != curE.Orientation()) {
1621           found = Standard_True;
1622           couture = Standard_True;
1623           F2 = F1;
1624         }
1625       }
1626     }
1627     if(found){
1628       if(BRep_Tool::Continuity(E,F1,F2)<=GeomAbs_C0){
1629
1630         try {
1631           if(tgtfaces(E, F1, F2, TolAng, couture)){
1632             B.Continuity(E,F1,F2,GeomAbs_G1);
1633           }
1634         }
1635         catch(Standard_Failure)
1636         {
1637         }
1638       }
1639     }
1640   }
1641 }
1642
1643 //=======================================================================
1644 // function : EncodeRegularity
1645 // purpose  : code the regularity between 2 faces on an edge 
1646 //=======================================================================
1647
1648 void BRepLib::EncodeRegularity(TopoDS_Edge& E,
1649   const TopoDS_Face& F1,
1650   const TopoDS_Face& F2,
1651   const Standard_Real TolAng)
1652 {
1653   BRep_Builder B;
1654   if(BRep_Tool::Continuity(E,F1,F2)<=GeomAbs_C0){
1655     try {
1656       if( tgtfaces(E, F1, F2, TolAng, F1.IsEqual(F2))) {
1657         B.Continuity(E,F1,F2,GeomAbs_G1);
1658       }
1659     }
1660     catch(Standard_Failure)
1661     {
1662     }
1663   }
1664 }
1665
1666 //=======================================================================
1667 // function : EnsureNormalConsistency
1668 // purpose  : Corrects the normals in Poly_Triangulation of faces.
1669 //              Returns TRUE if any correction is done.
1670 //=======================================================================
1671 Standard_Boolean BRepLib::
1672             EnsureNormalConsistency(const TopoDS_Shape& theShape,
1673                                     const Standard_Real theAngTol,
1674                                     const Standard_Boolean theForceComputeNormals)
1675 {
1676   const Standard_Real aThresDot = cos(theAngTol);
1677
1678   Standard_Boolean aRetVal = Standard_False, isNormalsFound = Standard_False;
1679
1680   // compute normals if they are absent
1681   TopExp_Explorer anExpFace(theShape,TopAbs_FACE);
1682   for (; anExpFace.More(); anExpFace.Next())
1683   {
1684     const TopoDS_Face& aFace = TopoDS::Face(anExpFace.Current());
1685     const Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aFace);
1686     if(aSurf.IsNull())
1687       continue;
1688     TopLoc_Location aLoc;
1689     const Handle(Poly_Triangulation)& aPT = BRep_Tool::Triangulation(aFace, aLoc);
1690     if(aPT.IsNull())
1691       continue;
1692     if (!theForceComputeNormals && aPT->HasNormals())
1693     {
1694       isNormalsFound = Standard_True;
1695       continue;
1696     }
1697
1698     GeomLProp_SLProps aSLP(aSurf, 2, Precision::Confusion());
1699     const Standard_Integer anArrDim = 3*aPT->NbNodes();
1700     Handle(TShort_HArray1OfShortReal) aNormArr = new TShort_HArray1OfShortReal(1, anArrDim);
1701     Standard_Integer anNormInd = aNormArr->Lower();
1702     for(Standard_Integer i = aPT->UVNodes().Lower(); i <= aPT->UVNodes().Upper(); i++)
1703     {
1704       const gp_Pnt2d &aP2d = aPT->UVNodes().Value(i);
1705       aSLP.SetParameters(aP2d.X(), aP2d.Y());
1706
1707       gp_XYZ aNorm(0.,0.,0.);
1708       if(!aSLP.IsNormalDefined())
1709       {
1710 #ifdef OCCT_DEBUG
1711         cout << "BRepLib::EnsureNormalConsistency(): Cannot find normal!" << endl;
1712 #endif
1713       }
1714       else
1715       {
1716         aNorm = aSLP.Normal().XYZ();
1717         if (aFace.Orientation() == TopAbs_REVERSED)
1718           aNorm.Reverse();
1719       }
1720       aNormArr->ChangeValue(anNormInd++) = static_cast<Standard_ShortReal>(aNorm.X());
1721       aNormArr->ChangeValue(anNormInd++) = static_cast<Standard_ShortReal>(aNorm.Y());
1722       aNormArr->ChangeValue(anNormInd++) = static_cast<Standard_ShortReal>(aNorm.Z());
1723     }
1724
1725     aRetVal = Standard_True;
1726     isNormalsFound = Standard_True;
1727     aPT->SetNormals(aNormArr);
1728   }
1729
1730   if(!isNormalsFound)
1731   {
1732     return aRetVal;
1733   }
1734
1735   // loop by edges
1736   TopTools_IndexedDataMapOfShapeListOfShape aMapEF;
1737   TopExp::MapShapesAndAncestors(theShape,TopAbs_EDGE,TopAbs_FACE,aMapEF);
1738   for(Standard_Integer anInd = 1; anInd <= aMapEF.Extent(); anInd++)
1739   {
1740     const TopoDS_Edge& anEdg = TopoDS::Edge(aMapEF.FindKey(anInd));
1741     const TopTools_ListOfShape& anEdgList = aMapEF.FindFromIndex(anInd);
1742     if (anEdgList.Extent() != 2)
1743       continue;
1744     TopTools_ListIteratorOfListOfShape anItF(anEdgList);
1745     const TopoDS_Face aFace1 = TopoDS::Face(anItF.Value());
1746     anItF.Next();
1747     const TopoDS_Face aFace2 = TopoDS::Face(anItF.Value());
1748     TopLoc_Location aLoc1, aLoc2;
1749     const Handle(Poly_Triangulation)& aPT1 = BRep_Tool::Triangulation(aFace1, aLoc1);
1750     const Handle(Poly_Triangulation)& aPT2 = BRep_Tool::Triangulation(aFace2, aLoc2);
1751
1752     if(aPT1.IsNull() || aPT2.IsNull())
1753       continue;
1754
1755     if(!aPT1->HasNormals() || !aPT2->HasNormals())
1756       continue;
1757
1758     const Handle(Poly_PolygonOnTriangulation)& aPTEF1 = 
1759                                 BRep_Tool::PolygonOnTriangulation(anEdg, aPT1, aLoc1);
1760     const Handle(Poly_PolygonOnTriangulation)& aPTEF2 = 
1761                                 BRep_Tool::PolygonOnTriangulation(anEdg, aPT2, aLoc2);
1762
1763     TShort_Array1OfShortReal& aNormArr1 = aPT1->ChangeNormals();
1764     TShort_Array1OfShortReal& aNormArr2 = aPT2->ChangeNormals();
1765
1766     for(Standard_Integer anEdgNode = aPTEF1->Nodes().Lower();
1767                          anEdgNode <= aPTEF1->Nodes().Upper(); anEdgNode++)
1768     {
1769       //Number of node
1770       const Standard_Integer aFNodF1 = aPTEF1->Nodes().Value(anEdgNode);
1771       const Standard_Integer aFNodF2 = aPTEF2->Nodes().Value(anEdgNode);
1772
1773       const Standard_Integer aFNorm1FirstIndex = aNormArr1.Lower() + 3*
1774                                                     (aFNodF1 - aPT1->Nodes().Lower());
1775       const Standard_Integer aFNorm2FirstIndex = aNormArr2.Lower() + 3*
1776                                                     (aFNodF2 - aPT2->Nodes().Lower());
1777
1778       gp_XYZ aNorm1(aNormArr1.Value(aFNorm1FirstIndex),
1779                     aNormArr1.Value(aFNorm1FirstIndex+1),
1780                     aNormArr1.Value(aFNorm1FirstIndex+2));
1781       gp_XYZ aNorm2(aNormArr2.Value(aFNorm2FirstIndex),
1782                     aNormArr2.Value(aFNorm2FirstIndex+1),
1783                     aNormArr2.Value(aFNorm2FirstIndex+2));
1784       const Standard_Real aDot = aNorm1 * aNorm2;
1785
1786       if(aDot > aThresDot)
1787       {
1788         gp_XYZ aNewNorm = (aNorm1 + aNorm2).Normalized();
1789         aNormArr1.ChangeValue(aFNorm1FirstIndex) =
1790           aNormArr2.ChangeValue(aFNorm2FirstIndex) =
1791           static_cast<Standard_ShortReal>(aNewNorm.X());
1792         aNormArr1.ChangeValue(aFNorm1FirstIndex+1) =
1793           aNormArr2.ChangeValue(aFNorm2FirstIndex+1) =
1794           static_cast<Standard_ShortReal>(aNewNorm.Y());
1795         aNormArr1.ChangeValue(aFNorm1FirstIndex+2) =
1796           aNormArr2.ChangeValue(aFNorm2FirstIndex+2) =
1797           static_cast<Standard_ShortReal>(aNewNorm.Z());
1798         aRetVal = Standard_True;
1799       }
1800     }
1801   }
1802
1803   return aRetVal;
1804 }
1805
1806 //=======================================================================
1807 //function : SortFaces
1808 //purpose  : 
1809 //=======================================================================
1810
1811 void  BRepLib::SortFaces (const TopoDS_Shape& Sh,
1812   TopTools_ListOfShape& LF)
1813 {
1814   LF.Clear();
1815   TopTools_ListOfShape LTri,LPlan,LCyl,LCon,LSphere,LTor,LOther;
1816   TopExp_Explorer exp(Sh,TopAbs_FACE);
1817   TopLoc_Location l;
1818   Handle(Geom_Surface) S;
1819
1820   for (; exp.More(); exp.Next()) {
1821     const TopoDS_Face&   F = TopoDS::Face(exp.Current());
1822     S = BRep_Tool::Surface(F, l);
1823     if (!S.IsNull()) {
1824       if (S->DynamicType() == STANDARD_TYPE(Geom_RectangularTrimmedSurface)) {
1825         S = Handle(Geom_RectangularTrimmedSurface)::DownCast (S)->BasisSurface();
1826       }
1827       GeomAdaptor_Surface AS(S);
1828       switch (AS.GetType()) {
1829       case GeomAbs_Plane: 
1830         {
1831           LPlan.Append(F);
1832           break;
1833         }
1834       case GeomAbs_Cylinder: 
1835         {
1836           LCyl.Append(F);
1837           break;
1838         }
1839       case GeomAbs_Cone: 
1840         {
1841           LCon.Append(F);
1842           break;
1843         }
1844       case GeomAbs_Sphere: 
1845         {
1846           LSphere.Append(F);
1847           break;
1848         }
1849       case GeomAbs_Torus: 
1850         {
1851           LTor.Append(F);
1852           break;
1853         }
1854       default:
1855         LOther.Append(F);
1856       }
1857     }
1858     else LTri.Append(F);
1859   }
1860   LF.Append(LPlan); LF.Append(LCyl  ); LF.Append(LCon); LF.Append(LSphere);
1861   LF.Append(LTor ); LF.Append(LOther); LF.Append(LTri); 
1862 }
1863
1864 //=======================================================================
1865 //function : ReverseSortFaces
1866 //purpose  : 
1867 //=======================================================================
1868
1869 void  BRepLib::ReverseSortFaces (const TopoDS_Shape& Sh,
1870   TopTools_ListOfShape& LF)
1871 {
1872   LF.Clear();
1873   TopTools_ListOfShape LTri,LPlan,LCyl,LCon,LSphere,LTor,LOther;
1874   TopExp_Explorer exp(Sh,TopAbs_FACE);
1875   TopLoc_Location l;
1876   Handle(Geom_Surface) S;
1877
1878   for (; exp.More(); exp.Next()) {
1879     const TopoDS_Face&   F = TopoDS::Face(exp.Current());
1880     S = BRep_Tool::Surface(F, l);
1881     if (!S.IsNull()) {
1882       if (S->DynamicType() == STANDARD_TYPE(Geom_RectangularTrimmedSurface)) {
1883         S = Handle(Geom_RectangularTrimmedSurface)::DownCast (S)->BasisSurface();
1884       }
1885       GeomAdaptor_Surface AS(S);
1886       switch (AS.GetType()) {
1887       case GeomAbs_Plane: 
1888         {
1889           LPlan.Append(F);
1890           break;
1891         }
1892       case GeomAbs_Cylinder: 
1893         {
1894           LCyl.Append(F);
1895           break;
1896         }
1897       case GeomAbs_Cone: 
1898         {
1899           LCon.Append(F);
1900           break;
1901         }
1902       case GeomAbs_Sphere: 
1903         {
1904           LSphere.Append(F);
1905           break;
1906         }
1907       case GeomAbs_Torus: 
1908         {
1909           LTor.Append(F);
1910           break;
1911         }
1912       default:
1913         LOther.Append(F);
1914       }
1915     }
1916     else LTri.Append(F);
1917   }
1918   LF.Append(LTri); LF.Append(LOther); LF.Append(LTor ); LF.Append(LSphere);
1919   LF.Append(LCon); LF.Append(LCyl  ); LF.Append(LPlan);
1920
1921 }
1922