0025334: BRepOffsetAPI_MakeOffset algorithm crashes on some customer's shape
[occt.git] / src / BRepFill / BRepFill_OffsetWire.cxx
1 // Created on: 1995-04-20
2 // Created by: Bruno DUMORTIER
3 // Copyright (c) 1995-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 //  Modified by skv - Fri Jul  8 11:21:38 2005 OCC9145
18
19 #include <stdio.h>
20
21 #include <BRepFill_OffsetWire.ixx>
22
23 #include <BRepAdaptor_Curve.hxx>
24 #include <BRepAdaptor_Surface.hxx>
25
26 #include <BRepFill_DataMapOfNodeShape.hxx>
27 #include <BRepFill_DataMapOfShapeSequenceOfPnt.hxx>
28 #include <BRepFill_DataMapOfShapeSequenceOfReal.hxx> 
29 #include <BRepFill_DataMapOfOrientedShapeListOfShape.hxx> 
30 #include <BRepFill_TrimEdgeTool.hxx>
31 #include <BRepLib.hxx>
32 #include <BRepLib_MakeVertex.hxx>
33 #include <BRepLib_MakeFace.hxx>
34 #include <BRepLib_MakeWire.hxx>
35 #include <BRepLib_MakeEdge.hxx>
36 #include <BRepTools.hxx>
37 #include <BRep_Builder.hxx>
38 #include <BRep_Tool.hxx>
39 #include <BRep_TEdge.hxx>
40 #include <BRep_CurveRepresentation.hxx>
41 #include <BRep_GCurve.hxx>
42 #include <BRepTools_WireExplorer.hxx>
43 #include <BRepMAT2d_Explorer.hxx>
44 #include <Geom2dAdaptor_Curve.hxx>
45 #include <Geom2dAdaptor_HCurve.hxx>
46 #include <Adaptor3d_OffsetCurve.hxx>
47 #include <Adaptor3d_Curve.hxx>
48 #include <Geom_Surface.hxx>
49 #include <Geom_Plane.hxx>
50 #include <Geom2d_Curve.hxx>
51 #include <Geom2d_Circle.hxx>
52 #include <Geom2d_Line.hxx>
53 #include <Geom2d_TrimmedCurve.hxx>
54 #include <Geom2d_OffsetCurve.hxx>
55 #include <GeomAPI.hxx>
56 #include <Geom_TrimmedCurve.hxx>
57 #include <Geom_Circle.hxx>
58 #include <Geom_Line.hxx>
59 #include <Geom_OffsetCurve.hxx>
60 #include <MAT_Arc.hxx>
61 #include <MAT_Node.hxx>
62 #include <MAT_Graph.hxx>
63 #include <MAT2d_CutCurve.hxx>
64 #include <Precision.hxx>
65 #include <Standard_NotImplemented.hxx>
66 #include <TColgp_SequenceOfPnt.hxx>
67 #include <TColStd_SequenceOfReal.hxx> 
68 #include <TopAbs.hxx> 
69 #include <TopExp.hxx>
70 #include <TopExp_Explorer.hxx>
71 #include <TopoDS.hxx>
72 #include <TopoDS_Wire.hxx>
73 #include <TopoDS_Compound.hxx>
74 #include <TopoDS_Iterator.hxx>
75 #include <TopTools_MapOfShape.hxx>
76 #include <TopTools_MapIteratorOfMapOfShape.hxx>
77 #include <TopTools_ListIteratorOfListOfShape.hxx>
78 #include <TopTools_DataMapOfShapeListOfShape.hxx>
79 #include <TopTools_DataMapIteratorOfDataMapOfShapeListOfShape.hxx>
80 #include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>
81 #include <TopTools_SequenceOfShape.hxx>
82 #include <TopTools_ListOfShape.hxx>    
83 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>    
84 #include <TopTools_DataMapOfShapeSequenceOfShape.hxx>
85
86 #include <gp.hxx>
87 #include <gp_Vec.hxx>
88 #include <gp_Ax2.hxx>
89 #include <gp_Pln.hxx>
90 #include <gp_Dir2d.hxx>
91
92 #include <BRep_TVertex.hxx>
93 #include <TopTools_IndexedMapOfShape.hxx>
94 #include <Geom2d_BSplineCurve.hxx>
95 #include <TColgp_Array1OfPnt2d.hxx>
96 #include <TColStd_Array1OfReal.hxx>
97 #include <TColStd_Array1OfInteger.hxx>
98 #include <BRepTools_Substitution.hxx>
99 #include <BRepLib_MakeVertex.hxx>
100 #include <Geom2dLProp_CLProps2d.hxx>
101 #include <Geom2dConvert_CompCurveToBSplineCurve.hxx>
102 #include <Standard_ErrorHandler.hxx>
103
104 #ifdef DRAW
105 #include <Draw.hxx>
106 #include <DrawTrSurf.hxx>
107 #include <DrawTrSurf_Curve2d.hxx>
108 #include <DBRep.hxx>
109 static Standard_Boolean AffichGeom  = Standard_False;
110 static Standard_Boolean Affich2d    = Standard_False;
111 static Standard_Boolean AffichEdge  = Standard_False;
112 static Standard_Integer NbTRIMEDGES = 0;
113 static Standard_Integer NbOFFSET    = 0;
114 static Standard_Integer NbEDGES     = 0;
115 static Standard_Integer NbBISSEC    = 0;
116 #endif
117
118 //  Modified by Sergey KHROMOV - Thu Nov 16 17:24:39 2000 Begin
119
120 static void QuasiFleche(const Adaptor3d_Curve& C,
121                         const Standard_Real Deflection2, 
122                         const Standard_Real Udeb,
123                         const gp_Pnt& Pdeb,
124                         const gp_Vec& Vdeb,
125                         const Standard_Real Ufin,
126                         const gp_Pnt& Pfin,
127                         const gp_Vec& Vfin,
128                         const Standard_Integer Nbmin,
129                         const Standard_Real Eps,
130                         TColStd_SequenceOfReal& Parameters,
131                         TColgp_SequenceOfPnt& Points);
132
133 static Standard_Boolean PerformCurve (TColStd_SequenceOfReal& Parameters,
134                                       TColgp_SequenceOfPnt&   Points,
135                                       const Adaptor3d_Curve& C, 
136                                       const Standard_Real Deflection,
137                                       const Standard_Real U1,
138                                       const Standard_Real U2,
139                                       const Standard_Real EPSILON,
140                                       const Standard_Integer Nbmin);
141
142 static void CheckBadEdges(const TopoDS_Face& Spine, const Standard_Real Offset,
143                           const BRepMAT2d_BisectingLocus& Locus, 
144                           const BRepMAT2d_LinkTopoBilo&   Link,
145                           TopTools_ListOfShape& BadEdges);
146
147 static Standard_Integer CutEdge (const TopoDS_Edge& E, 
148                                  const TopoDS_Face& F,
149                                        Standard_Integer ForceCut,
150                                        TopTools_ListOfShape& Cuts);
151
152
153 static void CutCurve (const Handle(Geom2d_TrimmedCurve)& C,
154                       const Standard_Integer nbParts,
155                             TColGeom2d_SequenceOfCurve& theCurves);
156 //  Modified by Sergey KHROMOV - Thu Nov 16 17:24:47 2000 End
157
158
159 static void EdgeVertices (const TopoDS_Edge&   E,
160                                 TopoDS_Vertex& V1, 
161                                 TopoDS_Vertex& V2)
162 {
163   if (E.Orientation() == TopAbs_REVERSED) {
164     TopExp::Vertices(E,V2,V1);
165   }
166   else {
167     TopExp::Vertices(E,V1,V2);
168   }
169 }
170                                       
171 static Standard_Boolean VertexFromNode
172 (const Handle(MAT_Node)&      aNode, 
173  const Standard_Real          Offset,
174  gp_Pnt2d&                    PN,
175  BRepFill_DataMapOfNodeShape& MapNodeVertex,
176  TopoDS_Vertex&               VN);
177
178 static void StoreInMap (const TopoDS_Shape& V1,
179                         const TopoDS_Shape& V2,
180                         TopTools_IndexedDataMapOfShapeShape& MapVV);
181
182 static void TrimEdge (const TopoDS_Edge&              CurrentEdge,
183                       const TopTools_ListOfShape&     D,
184                       TopTools_SequenceOfShape& Sv,  
185                       TColStd_SequenceOfReal&   MapverPar,
186                       TopTools_SequenceOfShape& S,
187                       TopTools_IndexedDataMapOfShapeShape& MapVV,
188                       const Standard_Integer IndOfE);
189
190 static Standard_Boolean DoubleOrNotInside (const TopTools_ListOfShape& EC,
191                                            const TopoDS_Vertex&        V);
192
193 static Standard_Boolean IsSmallClosedEdge(const TopoDS_Edge& anEdge,
194                                           const TopoDS_Vertex& aVertex);
195
196 static void MakeCircle 
197 (const TopoDS_Edge&                          E, 
198  const TopoDS_Vertex&                        V, 
199  const TopoDS_Face&                          F,
200  const Standard_Real                         Offset, 
201  BRepFill_IndexedDataMapOfOrientedShapeListOfShape& Map,
202  const Handle(Geom_Plane)&                   RefPlane);
203
204 static void MakeOffset 
205 (const TopoDS_Edge&                          E,
206  const TopoDS_Face&                          F,
207  const Standard_Real                         Offset, 
208  BRepFill_IndexedDataMapOfOrientedShapeListOfShape& Map,
209  const Handle(Geom_Plane)&                   RefPlane,
210  const Standard_Boolean                      IsOpenResult,
211  const TopoDS_Vertex *                       Ends);
212
213
214
215 //=======================================================================
216 //function : CheckFace
217 //purpose  : Check if face contains an edge with C0 continuity
218 //=======================================================================
219 //
220 static void CheckFace(const TopoDS_Face& theFace)
221   {
222   TopExp_Explorer ex(theFace,TopAbs_EDGE);
223   for(; ex.More(); ex.Next())
224     {
225     TopoDS_Edge anEdge=TopoDS::Edge(ex.Current());
226     Standard_Real f,l;
227     const Handle(Geom2d_Curve) C = BRep_Tool::CurveOnSurface(anEdge,theFace,f,l);
228     if (C->Continuity() == GeomAbs_C0)
229       Standard_ConstructionError::Raise("Initial shape contains an edge with C0 continuity");
230     }
231   }
232
233 //=======================================================================
234 //function : KPartCircle
235 //purpose  : 
236 //=======================================================================
237
238 static Standard_Boolean KPartCircle
239 (const TopoDS_Face&  mySpine,
240  const Standard_Real myOffset,
241  const Standard_Real Alt,
242  TopoDS_Shape&       myShape, 
243  BRepFill_IndexedDataMapOfOrientedShapeListOfShape& myMap,
244  Standard_Boolean&    myIsDone)
245 {
246   // The only contour which is a closed circle
247   TopExp_Explorer exp(mySpine,TopAbs_EDGE);
248   Standard_Integer NbEdges = 0;
249   TopoDS_Edge      E;
250
251   for (; exp.More(); exp.Next()) {
252     NbEdges++;
253     E = TopoDS::Edge(exp.Current());
254     if (NbEdges > 1) return Standard_False;
255   }
256
257   Standard_Real      f,l;
258   TopLoc_Location    L;
259   Handle(Geom_Curve) C =  BRep_Tool::Curve(E,L,f,l);
260
261   if (C->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
262     Handle(Geom_TrimmedCurve) Ct = Handle(Geom_TrimmedCurve)::DownCast(C);
263     C = Ct->BasisCurve();
264   }
265
266   TopoDS_Vertex V1,V2;
267   TopExp::Vertices(E,V1,V2);
268   if (!V1.IsSame(V2) || //open result or closed circle
269       C->IsKind(STANDARD_TYPE(Geom_Circle))) 
270   {
271     Standard_Real anOffset = myOffset;
272     if (E.Orientation() == TopAbs_REVERSED) anOffset *= -1;
273     
274     Handle(Geom2d_Curve) aPCurve = BRep_Tool::CurveOnSurface(E, mySpine, f, l);
275     Handle(Geom2dAdaptor_HCurve) AHC = new Geom2dAdaptor_HCurve(aPCurve, f, l);
276     Handle(Geom2d_Curve) OC;
277     if (AHC->GetType() == GeomAbs_Line)
278     {
279       Adaptor3d_OffsetCurve Off(AHC,anOffset);
280       OC = new Geom2d_Line(Off.Line());
281     }
282     else if (AHC->GetType() == GeomAbs_Circle)
283     {
284       gp_Circ2d theCirc = AHC->Circle();
285       if (anOffset < 0. || Abs(anOffset) < theCirc.Radius())
286         OC = new Geom2d_Circle (theCirc.Position(), theCirc.Radius() - anOffset);
287     }
288     else
289     {
290       Handle(Geom2d_TrimmedCurve) G2dT = new Geom2d_TrimmedCurve(aPCurve, f, l);
291       OC = new Geom2d_OffsetCurve( G2dT, anOffset);
292     }
293     Handle(Geom_Surface) aSurf = BRep_Tool::Surface(mySpine);
294     Handle(Geom_Plane) aPlane = Handle(Geom_Plane)::DownCast(aSurf);
295     myShape = BRepLib_MakeEdge(OC, aPlane, f, l);
296     BRepLib::BuildCurve3d(TopoDS::Edge(myShape));
297     
298     myShape.Orientation(E.Orientation());
299     myShape.Location(L);
300     if (Alt != 0.) {
301       BRepAdaptor_Surface S(mySpine,0);
302       gp_Ax1 Nor = S.Plane().Axis();
303       gp_Trsf T;
304       gp_Vec Trans(Nor.Direction());
305       Trans = Alt*Trans;
306       T.SetTranslation(Trans);
307       myShape.Move(TopLoc_Location(T));
308     }
309       
310     TopTools_ListOfShape LL;
311     LL.Append(myShape);
312     myMap.Add(E,LL);
313     
314     TopoDS_Edge myEdge = TopoDS::Edge(myShape);
315     myShape = BRepLib_MakeWire(myEdge);
316     
317     myIsDone = Standard_True;
318     return Standard_True;
319   }
320
321   return Standard_False;
322 }
323
324 //=======================================================================
325 //function : BRepFill_OffsetWire
326 //purpose  : 
327 //=======================================================================
328
329 BRepFill_OffsetWire::BRepFill_OffsetWire() 
330   : myIsOpenResult(Standard_False),
331     myIsDone(Standard_False)
332 {
333 }
334
335
336 //=======================================================================
337 //function : BRepFill_OffsetWire
338 //purpose  : 
339 //=======================================================================
340
341 BRepFill_OffsetWire::BRepFill_OffsetWire(const TopoDS_Face&     Spine,
342                                          const GeomAbs_JoinType Join,
343                                          const Standard_Boolean IsOpenResult)
344 {
345   Init(Spine,Join,IsOpenResult);
346 }
347
348 //=======================================================================
349 //function : Init
350 //purpose  : 
351 //=======================================================================
352
353 void BRepFill_OffsetWire::Init(const TopoDS_Face&     Spine,
354                                const GeomAbs_JoinType Join,
355                                const Standard_Boolean IsOpenResult)
356 {
357   myIsDone   = Standard_False;
358   TopoDS_Shape aLocalShape = Spine.Oriented(TopAbs_FORWARD);
359   mySpine    = TopoDS::Face(aLocalShape);
360 //  mySpine    = TopoDS::Face(Spine.Oriented(TopAbs_FORWARD));
361   myJoinType = Join;
362   myIsOpenResult = IsOpenResult;
363
364   CheckFace(mySpine);
365   
366   myMap.Clear();
367   myMapSpine.Clear();
368   //------------------------------------------------------------------
369   // cut the spine for bissectors.
370   //------------------------------------------------------------------
371 //  Modified by Sergey KHROMOV - Tue Nov 26 17:39:03 2002 Begin
372   static BRepMAT2d_Explorer Exp;
373
374   Exp.Perform(mySpine);
375
376 //  TopoDS_Face anOldSpine = mySpine;
377
378   mySpine = TopoDS::Face(Exp.ModifiedShape(mySpine));
379   PrepareSpine  ();
380
381 //  Modified by Sergey KHROMOV - Tue Nov 26 17:39:03 2002 End
382   TopoDS_Shape aShape;
383   BRepFill_IndexedDataMapOfOrientedShapeListOfShape aMap;
384   Standard_Boolean Done;
385   if (KPartCircle(myWorkSpine,1.,0.,aShape,aMap,Done)) return;
386   
387
388   //-----------------------------------------------------
389   // Calculate the map of bissectors to the left.  
390   // and Links Topology -> base elements of the map.
391   //-----------------------------------------------------
392   
393 //  Modified by Sergey KHROMOV - Tue Nov 26 17:39:03 2002 Begin
394 //   static BRepMAT2d_Explorer Exp;
395 //  Modified by Sergey KHROMOV - Tue Nov 26 17:39:03 2002 End
396   Exp.Perform(myWorkSpine);
397   myBilo.Compute(Exp, 1 ,MAT_Left, myJoinType, myIsOpenResult);
398   myLink.Perform(Exp, myBilo);
399 }
400
401
402 //=======================================================================
403 //function : IsDone
404 //purpose  : 
405 //=======================================================================
406
407 Standard_Boolean BRepFill_OffsetWire::IsDone() const 
408 {
409   return myIsDone;
410 }
411
412
413 //=======================================================================
414 //function : Spine
415 //purpose  : 
416 //=======================================================================
417
418 const TopoDS_Face& BRepFill_OffsetWire::Spine() const 
419 {
420   return mySpine;
421 }
422
423
424 //=======================================================================
425 //function : Shape
426 //purpose  : 
427 //=======================================================================
428
429 const TopoDS_Shape& BRepFill_OffsetWire::Shape() const 
430 {
431   return myShape;
432 }
433
434
435 //=======================================================================
436 //function : GeneratedShapes
437 //purpose  : 
438 //=======================================================================
439
440 const TopTools_ListOfShape& BRepFill_OffsetWire::GeneratedShapes
441 (const TopoDS_Shape& SpineShape)
442 {  
443   if (!myCallGen) {
444     if (!myMapSpine.IsEmpty()) {
445       // myMapSpine can be empty if passed by PerformWithBilo.
446       TopTools_DataMapIteratorOfDataMapOfShapeShape it(myMapSpine);
447       for (; it.More(); it.Next()) {
448         if (myMap.Contains(it.Key())) {
449           if (!myMap.Contains(it.Value())) {
450             TopTools_ListOfShape L;
451             myMap.Add(it.Value(),L);
452           }
453           if ( !it.Value().IsSame(it.Key())) {
454             myMap.ChangeFromKey(it.Value()).Append(myMap.ChangeFromKey(it.Key()));
455             //myMap.UnBind(it.Key());
456             TopoDS_Shape LastShape = myMap.FindKey(myMap.Extent());
457             TopTools_ListOfShape LastList;
458             LastList.Append(myMap(myMap.Extent()));
459             myMap.RemoveLast();
460             if (myMap.FindIndex(it.Key()) != 0)
461               myMap.Substitute(myMap.FindIndex(it.Key()), LastShape, LastList);
462           }
463         }
464         if (myMap.Contains(it.Key().Reversed())) {
465           if (!myMap.Contains(it.Value().Reversed())) {
466             TopTools_ListOfShape L;
467             myMap.Add(it.Value().Reversed(),L);
468           }
469           if ( !it.Value().IsSame(it.Key())) {
470             myMap.ChangeFromKey(it.Value().Reversed()).Append(myMap.ChangeFromKey(it.Key().Reversed()));
471             //myMap.UnBind(it.Key().Reversed());
472             TopoDS_Shape LastShape = myMap.FindKey(myMap.Extent());
473             TopTools_ListOfShape LastList;
474             LastList.Append(myMap(myMap.Extent()));
475             myMap.RemoveLast();
476             if (myMap.FindIndex(it.Key().Reversed()) != 0)
477               myMap.Substitute(myMap.FindIndex(it.Key().Reversed()), LastShape, LastList);
478           }
479         }
480       }
481     }
482     myCallGen = Standard_True;
483   }
484   
485   if (myMap.Contains(SpineShape)) {
486     return myMap.FindFromKey(SpineShape);
487   }
488   else {
489     static TopTools_ListOfShape Empty;
490     return Empty;
491   }
492 }
493
494
495 //=======================================================================
496 //function : JoinType
497 //purpose  : 
498 //=======================================================================
499
500 GeomAbs_JoinType BRepFill_OffsetWire::JoinType() const 
501 {
502   return myJoinType;
503 }
504
505 //=======================================================================
506 //function : Perform
507 //purpose  : 
508 //=======================================================================
509
510 void BRepFill_OffsetWire::Perform (const Standard_Real Offset,
511                                    const Standard_Real Alt)
512 {
513   //  Modified by skv - Fri Jul  8 11:21:38 2005 OCC9145 Begin
514   try
515   {
516     OCC_CATCH_SIGNALS
517       myCallGen = Standard_False;
518     if (KPartCircle(myWorkSpine,Offset,Alt,myShape,myMap,myIsDone)) return;
519
520     TopoDS_Face oldWorkSpain = myWorkSpine;
521
522     TopTools_ListOfShape BadEdges;
523     CheckBadEdges(myWorkSpine,Offset,myBilo,myLink,BadEdges);
524
525     if(!BadEdges.IsEmpty())
526     {
527       // Modification of myWorkSpine;
528       //cout << "Modification of myWorkSpine : " << BadEdges.Extent() << endl;
529       BRepTools_Substitution aSubst;
530       TopTools_ListIteratorOfListOfShape it(BadEdges);
531       TopTools_ListOfShape aL;
532       Standard_Real aDefl = .01 * Abs(Offset);
533       TColStd_SequenceOfReal Parameters;
534       TColgp_SequenceOfPnt Points;
535
536       for(; it.More(); it.Next()) {
537         aL.Clear();
538         Parameters.Clear();
539         Points.Clear();
540         const TopoDS_Shape& anE = it.Value();
541
542         TopoDS_Vertex Vf, Vl;
543         TopExp::Vertices(TopoDS::Edge(anE), Vf, Vl);
544
545         Standard_Real f, l;
546         Handle(Geom_Curve) G3d = BRep_Tool::Curve(TopoDS::Edge(anE),f,l);
547         GeomAdaptor_Curve  AC(G3d,f,l);
548
549         PerformCurve(Parameters, Points, AC, aDefl, f, 
550                                           l, Precision::Confusion(), 2);
551
552         Standard_Integer NPnts = Points.Length();
553         if(NPnts > 2)
554         {
555           //cout << NPnts << " points " << endl;
556           TopoDS_Vertex FV = Vf;
557           TopoDS_Vertex LV;
558           TopoDS_Edge newE;
559           Standard_Integer np;
560           for(np = 2; np < NPnts; np++) {
561             gp_Pnt LP = Points(np);
562             LV = BRepLib_MakeVertex(LP);
563             newE = BRepLib_MakeEdge(FV, LV);
564             aL.Append(newE);
565             FV = LV;
566           }
567           LV = Vl;
568           newE = BRepLib_MakeEdge(FV, LV);
569           aL.Append(newE);
570         }
571         else
572         {
573           //cout << " 2 points " << endl;
574           TopoDS_Edge newE = BRepLib_MakeEdge(Vf, Vl);
575           aL.Append(newE);
576         }
577         //Update myMapSpine
578         if (myMapSpine.IsBound( anE ))
579         {
580           TopTools_ListIteratorOfListOfShape newit( aL );
581           for (; newit.More(); newit.Next())
582           {
583             TopoDS_Edge NewEdge = TopoDS::Edge( newit.Value() );
584             myMapSpine.Bind( NewEdge, myMapSpine(anE) );
585             TopoDS_Vertex NewV1, NewV2;
586             EdgeVertices( NewEdge, NewV1, NewV2 );
587             if (!myMapSpine.IsBound(NewV1)) myMapSpine.Bind( NewV1, myMapSpine(anE) );
588             if (!myMapSpine.IsBound(NewV2)) myMapSpine.Bind( NewV2, myMapSpine(anE) );
589           }
590           myMapSpine.UnBind( anE );
591         }
592         ///////////////////
593         aSubst.Substitute(anE, aL);
594       }
595
596       TopTools_DataMapOfShapeListOfShape wwmap;
597       TopoDS_Iterator itws( myWorkSpine );
598       for (; itws.More(); itws.Next())
599       {
600         TopoDS_Shape aWire = itws.Value();
601         aSubst.Build( aWire );
602         if (aSubst.IsCopied(aWire))
603         {
604           TopoDS_Wire NewWire = TopoDS::Wire( aSubst.Copy(aWire).First() );
605           NewWire.Closed( aWire.Closed() );
606           TopTools_ListOfShape Lw;
607           Lw.Append( NewWire );
608           wwmap.Bind( aWire, Lw );
609         }
610       }
611       aSubst.Clear();
612       TopTools_DataMapIteratorOfDataMapOfShapeListOfShape itmap( wwmap );
613       for (; itmap.More(); itmap.Next())
614         aSubst.Substitute( itmap.Key(), itmap.Value() );
615       
616       aSubst.Build(myWorkSpine);
617       
618       if(aSubst.IsCopied(myWorkSpine)) {
619         myWorkSpine = TopoDS::Face(aSubst.Copy(myWorkSpine).First());
620
621         BRepMAT2d_Explorer newExp;
622         newExp.Perform(myWorkSpine);
623         BRepMAT2d_BisectingLocus newBilo;
624         BRepMAT2d_LinkTopoBilo newLink;
625         newBilo.Compute(newExp, 1, MAT_Left, myJoinType, myIsOpenResult);
626
627         if(!newBilo.IsDone())
628         {
629           myShape.Nullify();
630           myIsDone = Standard_False;
631           return;
632         }
633
634         newLink.Perform(newExp,newBilo);
635         PerformWithBiLo(myWorkSpine,Offset,newBilo,newLink,myJoinType,Alt);
636         myWorkSpine = oldWorkSpain;
637       }
638       else {
639         PerformWithBiLo(myWorkSpine,Offset,myBilo,myLink,myJoinType,Alt);
640       }
641     }
642     else
643     {
644       PerformWithBiLo(myWorkSpine,Offset,myBilo,myLink,myJoinType,Alt);
645     }
646   }
647   catch (...)//Every exception was caught.
648   {
649     myShape.Nullify();
650     myIsDone = Standard_False;
651 #ifdef BREPFILL_DEB
652     cout<<"An exception was caught in BRepFill_OffsetWire::Perform : ";
653     Standard_Failure::Caught()->Print(cout);
654     cout<<endl;
655 #endif
656
657     return;
658   }
659
660   //  Modified by skv - Fri Jul  8 11:21:38 2005 OCC9145 End
661   //  Modified by Sergey KHROMOV - Thu Mar 14 10:48:15 2002 Begin
662   if (!myIsOpenResult)
663   {
664     TopExp_Explorer anExp(myShape, TopAbs_WIRE);
665     
666     for (; anExp.More(); anExp.Next()) {
667       const TopoDS_Shape &aWire = anExp.Current();
668       
669       if (!aWire.Closed()) {
670         myShape.Nullify();
671         myIsDone = Standard_False;
672         Standard_ConstructionError::Raise("Offset wire is not closed.");
673       }
674     }
675   }
676   //  Modified by Sergey KHROMOV - Thu Mar 14 10:48:16 2002 End
677 }
678
679 //=======================================================================
680 //function : Compute
681 //purpose  : 
682 //=======================================================================
683
684 void Compute (const TopoDS_Face&  Spine,
685                     TopoDS_Shape& aShape,
686                     BRepFill_IndexedDataMapOfOrientedShapeListOfShape& Map,
687               const Standard_Real Alt)
688 {
689   BRep_Builder B;
690   B.MakeCompound(TopoDS::Compound(aShape));
691   Standard_Real ALT = Alt;
692   if ( Spine.Orientation() == TopAbs_REVERSED) ALT = -Alt;
693   gp_Trsf T;
694   T.SetTranslation(gp_Vec(0.,0.,ALT));
695   TopLoc_Location L(T);
696
697   for ( TopExp_Explorer exp(Spine,TopAbs_WIRE); exp.More(); exp.Next()) {
698     const TopoDS_Wire& CurW = TopoDS::Wire(exp.Current());
699     TopoDS_Shape aLocalShape = CurW.Moved(L);
700     TopoDS_Wire        NewW = TopoDS::Wire(aLocalShape);
701 //    TopoDS_Wire        NewW = TopoDS::Wire(CurW.Moved(L));
702     B.Add(aShape,NewW);
703     // update Map.
704     TopoDS_Iterator it1( CurW);
705     TopoDS_Iterator it2( NewW);
706     for ( ; it1.More(); it1.Next(), it2.Next()) {
707       TopTools_ListOfShape List;
708       List.Append(it2.Value());
709       Map.Add(it1.Value(), List);
710     }
711   }
712 }
713
714 //=======================================================================
715 //function : PerformWithBiLo
716 //purpose  : 
717 //=======================================================================
718
719 void BRepFill_OffsetWire::PerformWithBiLo
720 (const TopoDS_Face&              Spine,
721  const Standard_Real             Offset,
722  const BRepMAT2d_BisectingLocus& Locus, 
723        BRepMAT2d_LinkTopoBilo&   Link,
724  const GeomAbs_JoinType          Join,
725  const Standard_Real             Alt)
726 {
727   myIsDone     = Standard_False;
728   TopoDS_Shape aLocalShape = Spine.Oriented(TopAbs_FORWARD);
729   myWorkSpine  = TopoDS::Face(aLocalShape);
730 //  myWorkSpine  = TopoDS::Face(Spine.Oriented(TopAbs_FORWARD));
731   myJoinType   = Join;
732   myOffset     = Offset ;
733   myShape.Nullify();
734
735
736   if (mySpine.IsNull()) {
737     TopoDS_Shape aLocalShape = Spine.Oriented(TopAbs_FORWARD);
738     mySpine = TopoDS::Face(aLocalShape);
739 //    mySpine = TopoDS::Face(Spine.Oriented(TopAbs_FORWARD));
740 }
741   myMap.Clear();
742
743   if ( Abs(myOffset) < Precision::Confusion()) {
744     Compute(mySpine,myShape,myMap,Alt);
745     myIsDone = Standard_True;
746     return;
747   }
748
749   //********************************
750   // Calculate for a non null offset 
751   //********************************
752   if (KPartCircle(myWorkSpine,Offset,Alt,myShape,myMap,myIsDone))
753     return;
754
755   BRep_Builder myBuilder;
756   myBuilder.MakeCompound(TopoDS::Compound(myShape));
757   
758   //---------------------------------------------------------------------
759   // MapNodeVertex : associate to each node of the map (key1) and to
760   //                 each element of the profile (key2) a vertex (item).
761   // MapBis        : all edges or vertices (item) generated by 
762   //                 a bisectrice on a face or an edge (key) of revolution tubes.
763   // MapVerPar     : Map of parameters of vertices on parallel edges 
764   //                 the list contained in MapVerPar (E) corresponds to 
765   //                 parameters on E of vertices contained in MapBis(E);
766   //---------------------------------------------------------------------
767
768
769   BRepFill_DataMapOfNodeShape               MapNodeVertex; 
770   TopTools_DataMapOfShapeSequenceOfShape    MapBis;  
771   BRepFill_DataMapOfShapeSequenceOfReal     MapVerPar;
772
773   TopTools_DataMapOfShapeShape              EmptyMap;
774   TopTools_SequenceOfShape                  EmptySeq;
775   TopTools_ListOfShape                      EmptyList;
776   TColStd_SequenceOfReal                    EmptySeqOfReal;
777
778   Standard_Real ALT = Alt;
779   Handle(Geom_Plane) RefPlane = 
780     Handle(Geom_Plane)::DownCast(BRep_Tool::Surface(myWorkSpine));
781   if ( myWorkSpine.Orientation() == TopAbs_REVERSED) ALT = -Alt;
782   RefPlane = Handle(Geom_Plane)::DownCast
783     (RefPlane->Translated( ALT * gp_Vec(RefPlane->Axis().Direction() )));
784
785   //---------------------------------------------------------------
786   // Construction of Circles and OffsetCurves
787   //---------------------------------------------------------------
788
789   TopoDS_Vertex Ends [2];
790   if (myIsOpenResult)
791   {
792     TopoDS_Wire theWire;
793     TopoDS_Iterator iter(mySpine);
794     theWire = TopoDS::Wire(iter.Value());
795     TopExp::Vertices(theWire, Ends[0], Ends[1]);
796   }
797   
798   for (Standard_Integer ic = 1; ic <= Locus.NumberOfContours(); ic++) {
799     TopoDS_Shape PEE = Link.GeneratingShape(Locus.BasicElt(ic,Locus.NumberOfElts(ic)));
800     TopoDS_Shape& PE = PEE ;      
801     for (Standard_Integer ie = 1; ie <= Locus.NumberOfElts(ic); ie++) {
802       const TopoDS_Shape& SE = Link.GeneratingShape(Locus.BasicElt(ic,ie));
803       if (SE.ShapeType() == TopAbs_VERTEX) {
804         if (!SE.IsSame(Ends[0]) && !SE.IsSame(Ends[1]))
805           MakeCircle (TopoDS::Edge(PE),TopoDS::Vertex(SE),
806                       myWorkSpine,myOffset,myMap,RefPlane);
807       }
808       else {
809         MakeOffset (TopoDS::Edge(SE),myWorkSpine,myOffset,myMap,RefPlane,
810                     myIsOpenResult, Ends);
811         PE = SE;
812       }
813     }
814   }
815
816
817 #ifdef DRAW
818   if (AffichEdge) {
819     cout << " End Construction of geometric primitives "<<endl;
820   }
821 #endif
822
823
824   //---------------------------------------------------
825   // Construction of offset vertices.
826   //---------------------------------------------------
827   BRepFill_DataMapOfOrientedShapeListOfShape Detromp;
828   Handle(MAT_Arc)        CurrentArc;
829   Handle(Geom2d_Curve)   Bis, PCurve1, PCurve2 ;
830   Handle(Geom_Curve)     CBis;
831   Standard_Boolean       Reverse;
832   TopoDS_Edge            CurrentEdge;
833   TopoDS_Shape           S       [2];
834   TopoDS_Edge            E       [2];
835   TopLoc_Location        L;
836   Standard_Integer       j, k;
837
838   for (Standard_Integer i = 1; i <= Locus.Graph()->NumberOfArcs(); i++) {
839
840     CurrentArc           = Locus.Graph()->Arc(i);
841     Bisector_Bisec Bisec = Locus.GeomBis(CurrentArc,Reverse);
842     
843 #ifdef DRAW
844   if ( AffichGeom) {
845     char name[256];
846     sprintf(name,"BISSEC_%d",NbBISSEC++);
847     DrawTrSurf::Set(name,Bisec.Value());
848   }
849 #endif
850
851     //-------------------------------------------------------------------
852     // Return elements of the spine corresponding to separate basicElts.
853     //-------------------------------------------------------------------
854     S [0] = Link.GeneratingShape(CurrentArc->FirstElement());
855     S [1] = Link.GeneratingShape(CurrentArc->SecondElement());
856
857     TopTools_SequenceOfShape Vertices;
858     TColgp_SequenceOfPnt     Params;
859     
860     TopTools_DataMapOfShapeSequenceOfShape MapSeqVer;
861     BRepFill_DataMapOfShapeSequenceOfPnt   MapSeqPar;
862
863     //-----------------------------------------------------------
864     // Return parallel edges on each face.
865     // If no offset generated => move to the next bissectrice. 
866     //--------------------------------------------------------------
867     if (myMap.Contains(S[0]) && myMap.Contains(S[1])) {
868       E [0] = TopoDS::Edge(myMap.FindFromKey(S[0]).First());
869       E [1] = TopoDS::Edge(myMap.FindFromKey(S[1]).First());
870     }
871     else continue;
872
873     //-----------------------------------------------------------
874     // Construction of vertices corresponding to the node of the map.
875     // if they are on the offset.
876     //-----------------------------------------------------------
877     TopoDS_Vertex VS,VE;
878     Handle(MAT_Node) Node1, Node2;
879
880     if (Reverse) {
881       Node1 = CurrentArc->SecondNode();
882       Node2 = CurrentArc->FirstNode();
883     }
884     else  {
885       Node1 = CurrentArc->FirstNode();
886       Node2 = CurrentArc->SecondNode();
887     }
888     
889     Standard_Boolean StartOnEdge = 0, EndOnEdge = 0;
890     
891     if (!Node1->Infinite()) {
892       gp_Pnt2d aLocalPnt2d = Locus.GeomElt(Node1);
893       StartOnEdge = VertexFromNode(Node1, myOffset, aLocalPnt2d ,MapNodeVertex,VS);
894 //      StartOnEdge = VertexFromNode(Node1, myOffset, Locus.GeomElt(Node1),
895 //                                 MapNodeVertex,VS);
896     }
897     if (!Node2->Infinite()) {
898       gp_Pnt2d aLocalPnt2d = Locus.GeomElt(Node2) ;
899       EndOnEdge   = VertexFromNode(Node2, myOffset, aLocalPnt2d ,MapNodeVertex,VE);
900 //      EndOnEdge   = VertexFromNode(Node2, myOffset, Locus.GeomElt(Node2),
901 //                                 MapNodeVertex,VE);
902     }
903
904     //---------------------------------------------
905     // Construction of geometries.
906     //---------------------------------------------
907     BRepFill_TrimEdgeTool Trim (Bisec, 
908                                 Locus.GeomElt(CurrentArc->FirstElement()),
909                                 Locus.GeomElt(CurrentArc->SecondElement()),
910                                 myOffset);
911
912     //-----------------------------------------------------------
913     // Construction of vertices on edges parallel to the spine.
914     //-----------------------------------------------------------
915
916     Trim.IntersectWith(E [0], E [1], Params);
917
918     for (Standard_Integer s = 1; s <= Params.Length(); s++) {
919       TopoDS_Vertex VC;
920       myBuilder.MakeVertex (VC);
921       gp_Pnt2d P2  = Bisec.Value()->Value(Params.Value(s).X());
922       gp_Pnt   PVC(P2.X(),P2.Y(),0.);
923
924       myBuilder.UpdateVertex(VC,PVC,Precision::Confusion());
925       Vertices.Append(VC);
926     }
927     if (StartOnEdge) {
928       Standard_Boolean Start = 1;
929       Trim.AddOrConfuse(Start, E[0], E[1], Params);
930       if (Params.Length() == Vertices.Length()) 
931          Vertices.SetValue(1,VS);
932       
933       else
934         // the point was not found by IntersectWith
935         Vertices.Prepend(VS);
936     }
937     if (EndOnEdge) {      
938       Standard_Boolean Start = 0;
939       Trim.AddOrConfuse(Start, E[0], E[1], Params);
940       if (Params.Length() == Vertices.Length()) 
941          Vertices.SetValue(Params.Length(),VE);
942       
943       else
944         // the point was not found by IntersectWith
945         Vertices.Append(VE);
946     }
947
948     //------------------------------------------------------------
949     // Update Detromp.
950     // Detromp allows to remove vertices on the offset 
951     // corresponding to tangency zones
952     // Detromp ranks the vertices that limit
953     // the parts of the bissectrices located between the spine and the 
954     // offset.
955     //------------------------------------------------------------
956     if (!Detromp.IsBound(S[0])) Detromp.Bind(S[0],EmptyList);
957     if (!Detromp.IsBound(S[1])) Detromp.Bind(S[1],EmptyList);
958
959     
960     UpdateDetromp (Detromp, S[0], S[1], Vertices, Params, 
961                    Bisec, StartOnEdge, EndOnEdge, Trim);
962     //----------------------------------------------
963     // Storage of vertices on parallel edges.
964     // fill MapBis and MapVerPar.
965     //----------------------------------------------
966     if (!Vertices.IsEmpty()) {
967       for (k = 0; k <= 1; k++) {
968         if (!MapBis.IsBound(E[k])) {
969           MapBis   .Bind(E[k],EmptySeq);
970           MapVerPar.Bind(E[k],EmptySeqOfReal);
971         } 
972         for (Standard_Integer ii = 1; ii <= Vertices.Length(); ii++) {
973           MapBis (E[k]).Append(Vertices.Value(ii));
974           if (k == 0) MapVerPar (E[k]).Append(Params.Value(ii).Y());
975           else        MapVerPar (E[k]).Append(Params.Value(ii).Z());
976         }
977       }
978     }
979     else {
980       //------------------------------------------------------------
981       // FOR COMPLETE CIRCLES. the parallel line can be contained
982       // in the zone without intersection with the border
983       // no intersection 
984       // if myoffset is < distance of nodes the parallel can be valid.
985       //-------------------------------------------------------------
986       for (k = 0; k <= 1; k++) {
987         if (!MapBis.IsBound(E[k])) {
988           if (Node1->Distance() > myOffset && Node2->Distance() > myOffset) {
989             MapBis   .Bind(E[k],EmptySeq); 
990             MapVerPar.Bind(E[k],EmptySeqOfReal);
991           }
992         }
993       }
994     }
995   }
996   
997 #ifdef DRAW
998   if (AffichEdge) {
999     cout << " End Construction of vertices on offsets"<<endl;
1000   }
1001 #endif
1002
1003   //----------------------------------
1004   // Construction of parallel edges.
1005   //----------------------------------
1006   TopTools_IndexedDataMapOfShapeShape MapVV;
1007
1008   TopoDS_Shape CurrentSpine;
1009
1010   //BRepFill_DataMapIteratorOfDataMapOfOrientedShapeListOfShape ite1;  
1011
1012   for (j = 1; j <= myMap.Extent(); j++) {
1013     CurrentSpine = myMap.FindKey(j);
1014     CurrentEdge  = TopoDS::Edge(myMap(j).First());
1015
1016     myMap(j).Clear();
1017     if (MapBis.IsBound(CurrentEdge)) {
1018       TopTools_SequenceOfShape S;
1019       if (!MapBis(CurrentEdge).IsEmpty()) {
1020         Standard_Integer IndOfE = 0;
1021         if (myIsOpenResult)
1022         {
1023           if (j == 1)
1024             IndOfE = 1;
1025           else if (j == myMap.Extent())
1026             IndOfE = -1;
1027         }
1028         TrimEdge (CurrentEdge,
1029                   Detromp  (CurrentSpine),
1030                   MapBis   (CurrentEdge) ,  
1031                   MapVerPar(CurrentEdge) ,
1032                   S, MapVV, IndOfE);
1033         for ( k = 1; k <= S.Length(); k++) {
1034           myMap(j).Append(S.Value(k));
1035         }
1036       }
1037       else {
1038         //-----------------
1039         // Complete circles
1040         //-----------------
1041         myMap(j).Append(CurrentEdge);
1042       }
1043     }
1044   }
1045   
1046   Standard_Integer ind;
1047   for (ind = 1; ind <= MapVV.Extent(); ind++)
1048     {
1049       TopoDS_Vertex OldV = TopoDS::Vertex(MapVV.FindKey(ind));
1050       TopoDS_Vertex NewV = TopoDS::Vertex(MapVV(ind));
1051       gp_Pnt P1 = BRep_Tool::Pnt(OldV);
1052       gp_Pnt P2 = BRep_Tool::Pnt(NewV);
1053       myBuilder.UpdateVertex(NewV, P1.Distance(P2));
1054       TopTools_ListOfShape LV;
1055       LV.Append( NewV.Oriented(TopAbs_FORWARD) );
1056       BRepTools_Substitution aSubst;
1057       aSubst.Substitute( OldV, LV );
1058       for (j = 1; j <= myMap.Extent(); j++)
1059         {
1060           TopTools_ListIteratorOfListOfShape itl(myMap(j));
1061           for (; itl.More(); itl.Next())
1062             {
1063               aSubst.Build(itl.Value());
1064               if (aSubst.IsCopied(itl.Value()))
1065                 {
1066                   const TopTools_ListOfShape& listSh = aSubst.Copy(itl.Value());
1067                   TopAbs_Orientation SaveOr = itl.Value().Orientation();
1068                   itl.Value() = listSh.First();
1069                   itl.Value().Orientation(SaveOr);
1070                 }
1071             }
1072         }
1073     }
1074       
1075   //----------------------------------
1076   // Construction of offset wires.
1077   //----------------------------------
1078   MakeWires ();
1079
1080   // Update vertices ( Constructed in the plane Z = 0) !!!
1081   TopTools_MapOfShape MapVertex;
1082   for ( TopExp_Explorer exp(myShape,TopAbs_VERTEX); exp.More(); exp.Next()) {
1083     TopoDS_Vertex V = TopoDS::Vertex(exp.Current());
1084     if ( MapVertex.Add(V)) {
1085       gp_Pnt        P = BRep_Tool::Pnt(V);
1086       P = RefPlane->Value(P.X(),P.Y());
1087       myBuilder.UpdateVertex(V,P, Precision::Confusion());
1088     }
1089   }
1090
1091   // Construction of curves 3d.
1092   BRepLib::BuildCurves3d(myShape);
1093   MapVertex.Clear();
1094   TopExp_Explorer Explo( myShape, TopAbs_EDGE );
1095   for (; Explo.More(); Explo.Next())
1096     {
1097       TopoDS_Edge E = TopoDS::Edge( Explo.Current() );
1098       TopoDS_Vertex V1, V2;
1099       TopExp::Vertices( E, V1, V2 );
1100       Handle(BRep_TVertex)& TV1 = *((Handle(BRep_TVertex)*) &(V1).TShape());
1101       Handle(BRep_TVertex)& TV2 = *((Handle(BRep_TVertex)*) &(V2).TShape());
1102       
1103       TopLoc_Location loc;
1104       Standard_Real f, l;
1105       Handle( Geom_Curve ) theCurve = BRep_Tool::Curve( E, loc, f, l );
1106       theCurve = Handle( Geom_Curve )::DownCast( theCurve->Copy() );
1107       theCurve->Transform( loc.Transformation() );
1108       gp_Pnt f3d = theCurve->Value( f );
1109       gp_Pnt l3d = theCurve->Value( l );
1110
1111       Standard_Real dist1, dist2;
1112       dist1 = f3d.Distance( TV1->Pnt() );
1113       dist2 = l3d.Distance( TV2->Pnt() );
1114       if (! MapVertex.Contains( V1 ))
1115         {
1116           TV1->Pnt( f3d );
1117           MapVertex.Add( V1 );
1118         }
1119       else
1120         TV1->UpdateTolerance( 1.5*dist1 );
1121       if (! MapVertex.Contains( V2 ))
1122         {
1123           TV2->Pnt( l3d );
1124           MapVertex.Add( V2 );
1125         }
1126       else
1127         TV2->UpdateTolerance( 1.5*dist2 );
1128     }
1129
1130   FixHoles();
1131
1132   myIsDone = Standard_True;
1133 }
1134
1135
1136 //=======================================================================
1137 //function : Generated
1138 //purpose  : 
1139 //=======================================================================
1140
1141 BRepFill_IndexedDataMapOfOrientedShapeListOfShape& 
1142 BRepFill_OffsetWire::Generated() 
1143 {
1144   return myMap;
1145 }
1146
1147
1148 //=======================================================================
1149 //function : PrepareSpine
1150 //purpose  : 
1151 //=======================================================================
1152
1153 void BRepFill_OffsetWire::PrepareSpine()
1154 {
1155   BRep_Builder      B;
1156   TopTools_ListOfShape Cuts;
1157   TopTools_ListIteratorOfListOfShape IteCuts;
1158   TopoDS_Vertex V1,V2;
1159
1160   myWorkSpine.Nullify();
1161   myMapSpine.Clear();
1162
1163   TopLoc_Location L;
1164   const Handle(Geom_Surface)& S    = BRep_Tool::Surface  (mySpine,L);
1165   Standard_Real               TolF = BRep_Tool::Tolerance(mySpine);
1166   B.MakeFace(myWorkSpine,S,L,TolF);
1167   
1168   for (TopoDS_Iterator IteF(mySpine) ; IteF.More(); IteF.Next()) {
1169
1170     TopoDS_Wire NW;
1171     B.MakeWire (NW);
1172
1173 //  Modified by Sergey KHROMOV - Thu Nov 16 17:29:55 2000 Begin
1174     Standard_Integer ForcedCut = 0;
1175     Standard_Integer nbResEdges = -1;
1176     TopTools_IndexedMapOfShape EdgeMap;
1177
1178     TopExp::MapShapes(IteF.Value(), TopAbs_EDGE, EdgeMap);
1179     Standard_Integer nbEdges = EdgeMap.Extent();
1180     
1181     if (nbEdges == 1 && !myIsOpenResult) //in case of open wire there's no need to do it
1182       ForcedCut = 2;
1183 //  Modified by Sergey KHROMOV - Thu Nov 16 17:29:48 2000 End
1184
1185     for (TopoDS_Iterator IteW(IteF.Value()); IteW.More(); IteW.Next()) {
1186       
1187       const TopoDS_Edge& E = TopoDS::Edge(IteW.Value());
1188       EdgeVertices(E,V1,V2);
1189       myMapSpine.Bind(V1,V1);
1190       myMapSpine.Bind(V2,V2);
1191       Cuts.Clear();
1192
1193       // Cut
1194       TopoDS_Shape aLocalShape = E.Oriented(TopAbs_FORWARD);
1195 //  Modified by Sergey KHROMOV - Thu Nov 16 17:29:29 2000 Begin
1196       if (nbEdges == 2 && nbResEdges == 0)
1197         ForcedCut = 1;
1198 //  Modified by Sergey KHROMOV - Thu Nov 16 17:29:33 2000 End
1199       nbResEdges = CutEdge (TopoDS::Edge(aLocalShape), mySpine, ForcedCut, Cuts);
1200       
1201       if (Cuts.IsEmpty()) {
1202         B.Add(NW,E);
1203         myMapSpine.Bind(E,E);
1204       }
1205       else {    
1206         for (IteCuts.Initialize(Cuts); IteCuts.More(); IteCuts.Next()) {
1207           TopoDS_Edge NE = TopoDS::Edge(IteCuts.Value());
1208           NE.Orientation(E.Orientation());
1209           B.Add(NW,NE);
1210           myMapSpine.Bind(NE,E);
1211           EdgeVertices(NE,V1,V2);
1212           if (!myMapSpine.IsBound(V1)) myMapSpine.Bind(V1,E);
1213           if (!myMapSpine.IsBound(V2)) myMapSpine.Bind(V2,E);
1214         }
1215       }
1216     }
1217 //  Modified by Sergey KHROMOV - Thu Mar  7 09:17:41 2002 Begin
1218     TopoDS_Vertex aV1;
1219     TopoDS_Vertex aV2;
1220
1221     TopExp::Vertices(NW, aV1, aV2);
1222
1223     NW.Closed(aV1.IsSame(aV2));
1224 //  Modified by Sergey KHROMOV - Thu Mar  7 09:17:43 2002 End
1225     B.Add(myWorkSpine, NW);
1226   }
1227
1228 #ifdef DRAW
1229   if ( AffichEdge) {
1230     DBRep::Set("WS",myWorkSpine);
1231   }
1232 #endif
1233
1234 }
1235
1236 //=======================================================================
1237 //function : UpdateDetromp
1238 //purpose  : For each interval on bissectrice defined by parameters
1239 //           test if the medium point is at a distance > offset 
1240 //           in this case vertices corresponding to the extremities of the interval
1241 //           are ranked in the proofing.
1242 //           => If the same vertex appears in the proofing, the 
1243 //           border of the zone of proximity is tangent to the offset .
1244 //=======================================================================
1245
1246 void BRepFill_OffsetWire::UpdateDetromp (BRepFill_DataMapOfOrientedShapeListOfShape& Detromp,
1247                                          const TopoDS_Shape& Shape1,
1248                                          const TopoDS_Shape& Shape2,
1249                                          const TopTools_SequenceOfShape& Vertices, 
1250                                          const TColgp_SequenceOfPnt&     Params, 
1251                                          const Bisector_Bisec&           Bisec,
1252                                          const Standard_Boolean          SOnE,
1253                                          const Standard_Boolean          EOnE,
1254                                          const BRepFill_TrimEdgeTool&    Trim) const
1255 {
1256   if (myJoinType == GeomAbs_Intersection &&
1257       Vertices.Length() == 1 &&
1258       !EOnE)
1259   {
1260     TopTools_IndexedMapOfShape Vmap1, Vmap2;
1261     TopExp::MapShapes(Shape1, TopAbs_VERTEX, Vmap1);
1262     TopExp::MapShapes(Shape2, TopAbs_VERTEX, Vmap2);
1263     Standard_Boolean Adjacent = Standard_False;
1264     for (Standard_Integer i = 1; i <= Vmap1.Extent(); i++)
1265       for (Standard_Integer j = 1; j <= Vmap2.Extent(); j++)
1266         if (Vmap1(i).IsSame(Vmap2(j)))
1267         {
1268           Adjacent = Standard_True;
1269           break;
1270         }
1271     if (Adjacent)
1272     {
1273       Detromp(Shape1).Append(Vertices.First());
1274       Detromp(Shape2).Append(Vertices.First());
1275       return;
1276     }
1277   }
1278   
1279   Standard_Integer ii = 1;
1280   Standard_Real    U1,U2;
1281   TopoDS_Vertex    V1,V2;
1282
1283   Handle(Geom2d_Curve) Bis = Bisec.Value();
1284
1285   U1 = Bis->FirstParameter();
1286   
1287   if (SOnE) { 
1288     // the first point of the bissectrice is on the offset
1289     V1 = TopoDS::Vertex(Vertices.Value(ii));
1290     ii++; 
1291   }
1292
1293   while (ii <= Vertices.Length()) {
1294     U2 = Params.Value(ii).X();
1295     V2 = TopoDS::Vertex(Vertices.Value(ii));
1296
1297     gp_Pnt2d P = Bis->Value((U2 + U1)*0.5);  
1298     if (!Trim.IsInside(P)) {
1299       if (!V1.IsNull()) {
1300         Detromp(Shape1).Append(V1);
1301         Detromp(Shape2).Append(V1);
1302       }
1303       Detromp(Shape1).Append(V2);
1304       Detromp(Shape2).Append(V2);
1305     }
1306     U1 = U2;
1307     V1 = V2;
1308     ii ++;
1309   }
1310
1311   // test medium point between the last parameter and the end of the bissectrice.
1312   U2 = Bis->LastParameter();
1313   if (!EOnE) {
1314     if (!Precision::IsInfinite(U2)) {
1315       gp_Pnt2d P = Bis->Value((U2 + U1)*0.5);  
1316       if (!Trim.IsInside(P)) {
1317         if (!V1.IsNull()) {
1318           Detromp(Shape1).Append(V1);
1319           Detromp(Shape2).Append(V1);
1320         }
1321       }
1322     }
1323     else {
1324       if (!V1.IsNull()) {
1325         Detromp(Shape1).Append(V1);
1326         Detromp(Shape2).Append(V1);
1327       }
1328     }
1329   }    
1330 }
1331
1332 //=======================================================================
1333 //function : MakeWires
1334 //purpose  : 
1335 //=======================================================================
1336
1337 void BRepFill_OffsetWire::MakeWires()
1338 {
1339   //--------------------------------------------------------
1340   // creation of a single list of created parallel edges.
1341   //--------------------------------------------------------
1342   TopTools_SequenceOfShape TheEdges;
1343   TopTools_ListOfShape     TheWires;
1344   TopTools_ListIteratorOfListOfShape                          itl;
1345   //BRepFill_DataMapIteratorOfDataMapOfOrientedShapeListOfShape ite;  
1346   TopTools_IndexedDataMapOfShapeListOfShape                   MVE;
1347   //TopTools_DataMapIteratorOfDataMapOfShapeListOfShape         MVEit;
1348   TopoDS_Vertex V1,V2,VF,CV;
1349   Standard_Integer i;
1350
1351   for (i = 1; i <= myMap.Extent(); i++) {    
1352     for (itl.Initialize(myMap(i)); itl.More(); itl.Next()) {
1353       const TopoDS_Edge& E = TopoDS::Edge(itl.Value());
1354       TopExp::Vertices (E,V1,V2);
1355       if (V1.IsSame(V2) && IsSmallClosedEdge(E, V1))
1356         continue; //remove small closed edges
1357       if (!MVE.Contains(V1)) {
1358         TopTools_ListOfShape empty;
1359         MVE.Add(V1,empty);
1360       }
1361       MVE.ChangeFromKey(V1).Append(E);
1362       if (!MVE.Contains(V2)) {
1363         TopTools_ListOfShape empty;
1364         MVE.Add(V2,empty);
1365       }
1366       MVE.ChangeFromKey(V2).Append(E);
1367     }
1368   }
1369
1370   //--------------------------------------
1371   // Creation of parallel wires.
1372   //--------------------------------------
1373   BRep_Builder B;
1374
1375 //  Standard_Integer NbEdges;
1376 //  Standard_Boolean NewWire  = Standard_True;
1377 //  Standard_Boolean AddEdge  = Standard_False;
1378
1379   TopoDS_Wire      NW;
1380   Standard_Boolean End;
1381   TopoDS_Edge CE;
1382
1383   while (!MVE.IsEmpty()) {
1384     B.MakeWire(NW);
1385
1386     //MVEit.Initialize(MVE);
1387     for (i = 1; i <= MVE.Extent(); i++)
1388       if(MVE(i).Extent() == 1)
1389         break;
1390
1391     //if(!MVEit.More()) MVEit.Initialize(MVE);
1392     if (i > MVE.Extent())
1393       i = 1;
1394     
1395     CV  = VF = TopoDS::Vertex(MVE.FindKey(i));
1396     CE  = TopoDS::Edge(MVE(i).First());
1397     End = Standard_False;
1398     MVE.ChangeFromKey(CV).RemoveFirst(); 
1399
1400 //  Modified by Sergey KHROMOV - Thu Mar 14 11:29:59 2002 Begin
1401     Standard_Boolean isClosed = Standard_False;
1402 //  Modified by Sergey KHROMOV - Thu Mar 14 11:30:00 2002 End
1403
1404     while(!End) {      
1405       //-------------------------------
1406       // Construction of a wire.
1407       //-------------------------------
1408       TopExp::Vertices(CE,V1,V2);
1409       if (!CV.IsSame(V1)) CV = V1; else CV = V2;
1410
1411       B.Add (NW,CE);
1412
1413       if (VF.IsSame(CV) || !MVE.Contains(CV)) {
1414 //  Modified by Sergey KHROMOV - Thu Mar 14 11:30:14 2002 Begin
1415         isClosed = VF.IsSame(CV);
1416 //  Modified by Sergey KHROMOV - Thu Mar 14 11:30:15 2002 End
1417         End = Standard_True;
1418         //MVE.UnBind(VF);
1419         TopoDS_Shape LastShape = MVE.FindKey(MVE.Extent());
1420         TopTools_ListOfShape LastList;
1421         LastList.Append(MVE(MVE.Extent()));
1422         MVE.RemoveLast();
1423         if (MVE.FindIndex(VF) != 0)
1424           MVE.Substitute(MVE.FindIndex(VF), LastShape, LastList);
1425       }
1426
1427       if (!End) {
1428         if (MVE.FindFromKey(CV).Extent() > 2) {
1429           //cout <<"vertex on more that 2 edges in a face."<<endl;
1430         }
1431         for ( itl.Initialize(MVE.FindFromKey(CV)); itl.More(); itl.Next()) {
1432           if (itl.Value().IsSame(CE)) {
1433             MVE.ChangeFromKey(CV).Remove(itl);
1434             break;
1435           }
1436         }
1437         if (!MVE.FindFromKey(CV).IsEmpty()) {
1438           CE = TopoDS::Edge(MVE.FindFromKey(CV).First());
1439           MVE.ChangeFromKey(CV).RemoveFirst();
1440         }
1441         if (MVE.FindFromKey(CV).IsEmpty())
1442         {
1443           //MVE.UnBind(CV);
1444           TopoDS_Shape LastShape = MVE.FindKey(MVE.Extent());
1445           TopTools_ListOfShape LastList;
1446           LastList.Append(MVE(MVE.Extent()));
1447           MVE.RemoveLast();
1448           if (MVE.FindIndex(CV) != 0)
1449             MVE.Substitute(MVE.FindIndex(CV), LastShape, LastList);
1450         }
1451       }
1452     }
1453 //  Modified by Sergey KHROMOV - Thu Mar 14 11:29:31 2002 Begin
1454 //     NW.Closed(Standard_True);
1455     NW.Closed(isClosed);
1456 //  Modified by Sergey KHROMOV - Thu Mar 14 11:29:37 2002 End
1457     TheWires.Append(NW);
1458   }
1459
1460   // update myShape :
1461   //      -- if only one wire : myShape is a Wire
1462   //      -- if several wires : myShape is a Compound.
1463   if ( TheWires.Extent() == 1) {
1464     myShape = TheWires.First();
1465   }
1466   else {
1467     TopoDS_Compound R;
1468     B.MakeCompound(R);
1469     TopTools_ListIteratorOfListOfShape it(TheWires);
1470     for ( ; it.More(); it.Next()) {
1471       B.Add(R, it.Value());
1472     }
1473     myShape = R;
1474   }
1475   
1476 }
1477
1478 //=======================================================================
1479 //function : FixHoles
1480 //purpose  : 
1481 //=======================================================================
1482
1483 void BRepFill_OffsetWire::FixHoles()
1484 {
1485   TopTools_SequenceOfShape ClosedWires, UnclosedWires, IsolatedWires;
1486
1487   Standard_Real MaxTol = 0.;
1488   Standard_Integer i;
1489   BRep_Builder BB;
1490
1491   TopExp_Explorer Explo( mySpine, TopAbs_VERTEX );
1492   for (; Explo.More(); Explo.Next())
1493   {
1494     const TopoDS_Vertex& aVertex = TopoDS::Vertex( Explo.Current() );
1495     Standard_Real Tol = BRep_Tool::Tolerance(aVertex);
1496     if (Tol > MaxTol)
1497       MaxTol = Tol;
1498   }
1499   MaxTol *= 100.;
1500
1501   Explo.Init( myShape, TopAbs_WIRE );
1502   for (; Explo.More(); Explo.Next())
1503   {
1504     TopoDS_Shape aWire = Explo.Current();
1505     // Remove duplicated edges
1506     TopTools_DataMapOfShapeListOfShape EEmap;
1507     TopoDS_Iterator it( aWire );
1508     for (; it.More(); it.Next())
1509     {
1510       const TopoDS_Shape& anEdge = it.Value();
1511       if (! EEmap.IsBound( anEdge ))
1512       {
1513         TopTools_ListOfShape LE;
1514         EEmap.Bind( anEdge, LE );
1515       }
1516       else
1517         EEmap(anEdge).Append( anEdge );
1518     }
1519     aWire.Free( Standard_True );
1520     TopTools_DataMapIteratorOfDataMapOfShapeListOfShape mapit( EEmap );
1521     for (; mapit.More(); mapit.Next())
1522     {
1523       const TopTools_ListOfShape& LE = mapit.Value();
1524       TopTools_ListIteratorOfListOfShape itl( LE );
1525       for (; itl.More(); itl.Next())
1526         BB.Remove( aWire, itl.Value() );
1527     }
1528     // Sorting
1529     if (aWire.Closed())
1530       ClosedWires.Append( aWire );
1531     else
1532       UnclosedWires.Append( aWire );
1533   }
1534
1535   while (!UnclosedWires.IsEmpty())
1536   {
1537     TopoDS_Wire& Base = TopoDS::Wire( UnclosedWires(1) );
1538     TopoDS_Vertex Vf, Vl;
1539     TopExp::Vertices( Base, Vf, Vl );
1540     if(Vf.IsNull() || Vl.IsNull())
1541       Standard_Failure::Raise("BRepFill_OffsetWire::FixHoles(): Wrong wire.");
1542     gp_Pnt Pf, Pl;
1543     Pf = BRep_Tool::Pnt(Vf);
1544     Pl = BRep_Tool::Pnt(Vl);
1545     Standard_Real DistF = RealLast(), DistL = RealLast();
1546     Standard_Integer IndexF = 1, IndexL = 1;
1547     Standard_Boolean IsFirstF = Standard_False, IsFirstL = Standard_False;
1548     for (Standard_Integer i = 2; i <= UnclosedWires.Length(); i++)
1549     {
1550       TopoDS_Wire aWire = TopoDS::Wire( UnclosedWires(i) );
1551       TopoDS_Vertex V1, V2;
1552       TopExp::Vertices( aWire, V1, V2 );
1553
1554       if(V1.IsNull() || V2.IsNull())
1555         Standard_Failure::Raise("BRepFill_OffsetWire::FixHoles(): Wrong wire.");
1556
1557       gp_Pnt P1, P2;
1558       P1 = BRep_Tool::Pnt(V1);
1559       P2 = BRep_Tool::Pnt(V2);
1560       Standard_Real dist = Pf.Distance( P1 );
1561       if (dist < DistF)
1562       {
1563         DistF = dist;
1564         IndexF = i;
1565         IsFirstF = Standard_True;
1566       }
1567       dist = Pf.Distance( P2 );
1568       if (dist < DistF)
1569       {
1570         DistF = dist;
1571         IndexF = i;
1572         IsFirstF = Standard_False;
1573       }
1574       dist = Pl.Distance( P1 );
1575       if (dist < DistL)
1576       {
1577         DistL = dist;
1578         IndexL = i;
1579         IsFirstL = Standard_True;
1580       }
1581       dist = Pl.Distance( P2 );
1582       if (dist < DistL)
1583       {
1584         DistL = dist;
1585         IndexL = i;
1586         IsFirstL = Standard_False;
1587       }
1588     }
1589     TopoDS_Wire theWire;
1590     TopoDS_Edge theEdge;
1591     TopoDS_Vertex theVertex;
1592     Standard_Real CommonTol;
1593     Standard_Boolean TryToClose = Standard_True;
1594     if (DistF <= MaxTol && DistL <= MaxTol && IndexF == IndexL && IsFirstF == IsFirstL)
1595     {
1596       if (DistF < DistL)
1597       {
1598         DistL = RealLast();
1599         IndexL++;
1600       }
1601       else
1602       {
1603         DistF = RealLast();
1604         IndexF++;
1605       }
1606       TryToClose = Standard_False;
1607     }
1608     if (DistF <= MaxTol)
1609     {
1610       theWire = TopoDS::Wire( UnclosedWires(IndexF) );
1611       TopoDS_Vertex V1, V2;
1612       TopExp::Vertices( theWire, V1, V2 );
1613       TopTools_IndexedDataMapOfShapeListOfShape VEmap;
1614       TopExp::MapShapesAndAncestors( theWire, TopAbs_VERTEX, TopAbs_EDGE, VEmap );
1615       theEdge = (IsFirstF)? TopoDS::Edge(VEmap.FindFromKey( V1 ).First()) :
1616         TopoDS::Edge(VEmap.FindFromKey( V2 ).First());
1617       TopoDS_Iterator it( theWire );
1618       for (; it.More(); it.Next())
1619       {
1620         TopoDS_Edge anEdge = TopoDS::Edge( it.Value() );
1621         if (IsFirstF) anEdge.Reverse();
1622         if (!anEdge.IsSame( theEdge ))
1623           BB.Add( Base, anEdge );
1624       }
1625       theVertex = (IsFirstF)? V1 : V2;
1626       CommonTol = Max( BRep_Tool::Tolerance(Vf), BRep_Tool::Tolerance(theVertex) );
1627       if (DistF <= CommonTol)
1628       {
1629         theEdge.Free( Standard_True );
1630         Vf.Orientation( theVertex.Orientation() );
1631         BB.Remove( theEdge, theVertex );
1632         BB.Add( theEdge, Vf );
1633         BB.UpdateVertex( Vf, CommonTol );
1634         if (IsFirstF) theEdge.Reverse();
1635         BB.Add( Base, theEdge );
1636       }
1637       else
1638       {
1639         if (IsFirstF) theEdge.Reverse();
1640         BB.Add( Base, theEdge );
1641         // Creating new edge from theVertex to Vf
1642         TopoDS_Edge NewEdge = BRepLib_MakeEdge( theVertex, Vf );
1643         BB.Add( Base, NewEdge );
1644       }
1645     }
1646     if (DistL <= MaxTol && IndexL != IndexF)
1647     {
1648       theWire = TopoDS::Wire( UnclosedWires(IndexL) );
1649       TopoDS_Vertex V1, V2;
1650       TopExp::Vertices( theWire, V1, V2 );
1651       TopTools_IndexedDataMapOfShapeListOfShape VEmap;
1652       TopExp::MapShapesAndAncestors( theWire, TopAbs_VERTEX, TopAbs_EDGE, VEmap );
1653       theEdge = (IsFirstL)? TopoDS::Edge(VEmap.FindFromKey( V1 ).First()) :
1654         TopoDS::Edge(VEmap.FindFromKey( V2 ).First());
1655       TopoDS_Iterator it( theWire );
1656       for (; it.More(); it.Next())
1657       {
1658         TopoDS_Edge anEdge = TopoDS::Edge( it.Value() );
1659         if (!IsFirstL) anEdge.Reverse();
1660         if (!anEdge.IsSame( theEdge ))
1661           BB.Add( Base, anEdge );
1662       }
1663       theVertex = (IsFirstL)? V1 : V2;
1664       CommonTol = Max( BRep_Tool::Tolerance(Vl), BRep_Tool::Tolerance(theVertex) );
1665       if (DistL <= CommonTol)
1666       {
1667         theEdge.Free( Standard_True );
1668         Vl.Orientation( theVertex.Orientation() );
1669         BB.Remove( theEdge, theVertex );
1670         BB.Add( theEdge, Vl );
1671         BB.UpdateVertex( Vl, CommonTol );
1672         if (!IsFirstL) theEdge.Reverse();
1673         BB.Add( Base, theEdge );
1674       }
1675       else
1676       {
1677         if (!IsFirstL) theEdge.Reverse();
1678         BB.Add( Base, theEdge );
1679         // Creating new edge from Vl to theVertex
1680         TopoDS_Edge NewEdge = BRepLib_MakeEdge( Vl, theVertex );
1681         BB.Add( Base, NewEdge );
1682       }
1683     }
1684     // Check if it is possible to close resulting wire
1685     if (TryToClose)
1686     {
1687       TopExp::Vertices( Base, Vf, Vl );
1688       CommonTol = Max( BRep_Tool::Tolerance(Vf), BRep_Tool::Tolerance(Vl) );
1689       TopTools_IndexedDataMapOfShapeListOfShape VEmap;
1690       TopExp::MapShapesAndAncestors( Base, TopAbs_VERTEX, TopAbs_EDGE, VEmap );
1691       TopoDS_Edge Efirst, Elast;
1692       Efirst = TopoDS::Edge(VEmap.FindFromKey( Vf ).First());
1693       Elast  = TopoDS::Edge(VEmap.FindFromKey( Vl ).First());
1694       Pf = BRep_Tool::Pnt(Vf);
1695       Pl = BRep_Tool::Pnt(Vl);
1696       Standard_Real Dist = Pf.Distance(Pl);
1697       if (Dist <= CommonTol)
1698       {
1699         Elast.Free( Standard_True );
1700         Vf.Orientation( Vl.Orientation() );
1701         BB.Remove( Elast, Vl );
1702         BB.Add( Elast, Vf );
1703         BB.UpdateVertex( Vf, CommonTol );
1704         Base.Closed( Standard_True );
1705       }
1706       else if (Dist <= MaxTol)
1707       {
1708         // Creating new edge from Vl to Vf
1709         TopoDS_Edge NewEdge = BRepLib_MakeEdge( Vf, Vl );
1710         BB.Add( Base, NewEdge );
1711         Base.Closed( Standard_True );
1712       }
1713     }
1714     // Updating sequences ClosedWires and UnclosedWires
1715     if (DistF <= MaxTol)
1716       UnclosedWires.Remove( IndexF );
1717     if (DistL <= MaxTol && IndexL != IndexF)
1718     {
1719       if (DistF <= MaxTol && IndexL > IndexF)
1720         IndexL--;
1721       UnclosedWires.Remove( IndexL );
1722     }
1723     if (Base.Closed())
1724     {
1725       ClosedWires.Append( Base );
1726       UnclosedWires.Remove( 1 );
1727     }
1728     else if (DistF > MaxTol && DistL > MaxTol)
1729     {
1730       IsolatedWires.Append( Base );
1731       UnclosedWires.Remove( 1 );
1732     }
1733   }
1734
1735   // Updating myShape
1736   if (ClosedWires.Length() + IsolatedWires.Length() == 1)
1737   {
1738     if (!ClosedWires.IsEmpty())
1739       myShape = ClosedWires.First();
1740     else
1741       myShape = IsolatedWires.First();
1742   }
1743   else
1744   {
1745     TopoDS_Compound R;
1746     BB.MakeCompound( R );
1747     for (i = 1; i <= ClosedWires.Length(); i++)
1748       BB.Add( R, ClosedWires(i) );
1749     for (i = 1; i <= IsolatedWires.Length(); i++)
1750       BB.Add( R, IsolatedWires(i) );
1751     myShape = R;
1752   }
1753 }
1754
1755 //=======================================================================
1756 //function : CutEdge
1757 //purpose  : Cut edge at the extrema of curvatures and points of inflexion.
1758 //           So, closed circles are cut in two.
1759 //           If <Cuts> is empty, the edge is not modified.
1760 //           The first and the last vertex of the initial edge 
1761 //           belong to the first and the last parts respectively.
1762 //=======================================================================
1763 Standard_Integer CutEdge (const TopoDS_Edge& E, 
1764                           const TopoDS_Face& F,
1765                                 Standard_Integer ForceCut,
1766                                 TopTools_ListOfShape& Cuts)
1767 {
1768   Cuts.Clear();
1769   MAT2d_CutCurve              Cuter;
1770   TColGeom2d_SequenceOfCurve  theCurves;
1771   Standard_Real               f,l;
1772   Handle(Geom2d_Curve)        C2d;
1773   Handle(Geom2d_TrimmedCurve) CT2d;
1774 //  Modified by Sergey KHROMOV - Wed Mar  6 17:36:25 2002 Begin
1775   Standard_Real               aTol = BRep_Tool::Tolerance(E);
1776   Handle(Geom_Curve)          aC;
1777 //  Modified by Sergey KHROMOV - Wed Mar  6 17:36:25 2002 End
1778   
1779   TopoDS_Vertex V1,V2,VF,VL;
1780   TopExp::Vertices (E,V1,V2);
1781   BRep_Builder B;
1782   
1783   C2d  = BRep_Tool::CurveOnSurface (E,F,f,l);
1784 //  Modified by Sergey KHROMOV - Wed Mar  6 17:36:54 2002 Begin
1785   aC   = BRep_Tool::Curve(E,f,l);
1786 //  Modified by Sergey KHROMOV - Wed Mar  6 17:36:54 2002 End
1787   CT2d = new Geom2d_TrimmedCurve(C2d,f,l);
1788   //if (E.Orientation() == TopAbs_REVERSED) CT2d->Reverse();
1789
1790   if (CT2d->BasisCurve()->IsKind(STANDARD_TYPE(Geom2d_Circle)) &&
1791       ( Abs(f-l) >= M_PI) ) {
1792     return 0;
1793   }
1794
1795   //-------------------------
1796   // Cut curve.
1797   //-------------------------
1798   Cuter.Perform(CT2d);
1799
1800 //  Modified by Sergey KHROMOV - Thu Nov 16 17:28:29 2000 Begin
1801   if (ForceCut == 0) {
1802     if (Cuter.UnModified()) {
1803     //-----------------------------
1804     // edge not modified => return.
1805     //-----------------------------
1806       return 0;
1807     } else {
1808       for (Standard_Integer k = 1; k <= Cuter.NbCurves(); k++)
1809         theCurves.Append(Cuter.Value(k));
1810     }
1811   } else if (ForceCut == 1) {
1812     if (Cuter.UnModified()) {
1813       CutCurve (CT2d, 2, theCurves);
1814     } else {
1815       for (Standard_Integer k = 1; k <= Cuter.NbCurves(); k++)
1816         theCurves.Append(Cuter.Value(k));
1817     }
1818   } else if (ForceCut == 2) {
1819     if (Cuter.UnModified()) {
1820       CutCurve (CT2d, 3, theCurves);
1821     } else {
1822       if (Cuter.NbCurves() == 2) {
1823         Handle(Geom2d_TrimmedCurve)CC = Cuter.Value(1);
1824
1825         if (CC->LastParameter() > (l+f)/2.) {
1826           CutCurve (CC, 2, theCurves);
1827           theCurves.Append(Cuter.Value(2));
1828         } else {
1829           theCurves.Append(CC);
1830           CutCurve (Cuter.Value(2), 2, theCurves);
1831         }
1832       } else {
1833         for (Standard_Integer k = 1; k <= Cuter.NbCurves(); k++)
1834           theCurves.Append(Cuter.Value(k));
1835       }
1836     }
1837   }
1838 //  Modified by Sergey KHROMOV - Thu Nov 16 17:28:37 2000 End
1839
1840   //--------------------------------------
1841   // Creation of cut edges.
1842   //--------------------------------------
1843   VF = V1;
1844
1845   for (Standard_Integer k = 1; k <= theCurves.Length(); k++) {
1846
1847     Handle(Geom2d_TrimmedCurve)CC = Handle(Geom2d_TrimmedCurve)::DownCast(theCurves.Value(k));
1848
1849     if (k == theCurves.Length()) {VL = V2;}
1850     else { 
1851 //  Modified by Sergey KHROMOV - Wed Mar  6 17:38:02 2002 Begin
1852       gp_Pnt        P = aC->Value(CC->LastParameter());
1853
1854       VL = BRepLib_MakeVertex(P);
1855       B.UpdateVertex(VL, aTol);
1856 //  Modified by Sergey KHROMOV - Wed Mar  6 17:38:05 2002 End
1857     }
1858     TopoDS_Shape aLocalShape = E.EmptyCopied();
1859     TopoDS_Edge NE = TopoDS::Edge(aLocalShape);
1860 //      TopoDS_Edge NE = TopoDS::Edge(E.EmptyCopied());
1861     NE.Orientation(TopAbs_FORWARD);
1862     B.Add  (NE,VF.Oriented(TopAbs_FORWARD));
1863     B.Add  (NE,VL.Oriented(TopAbs_REVERSED));      
1864     B.Range(NE,CC->FirstParameter(),CC->LastParameter());
1865     Cuts.Append(NE.Oriented(E.Orientation()));
1866     VF = VL;
1867   }
1868
1869   return theCurves.Length();
1870 }
1871
1872 //  Modified by Sergey KHROMOV - Thu Nov 16 17:27:56 2000 Begin
1873 //=======================================================================
1874 //function : CutCurve
1875 //purpose  : 
1876 //=======================================================================
1877
1878 void CutCurve (const Handle(Geom2d_TrimmedCurve)& C,
1879                const Standard_Integer nbParts,
1880                      TColGeom2d_SequenceOfCurve& theCurves)
1881 {
1882   Handle(Geom2d_TrimmedCurve) TrimC;
1883   Standard_Real               UF,UL,UC;
1884   Standard_Real               Step;
1885   gp_Pnt2d                    PF,PL,PC;
1886   Standard_Real               PTol  = Precision::PConfusion()*10;
1887   Standard_Real               Tol   = Precision::Confusion()*10;
1888   Standard_Boolean            YaCut = Standard_False;
1889
1890   UF = C->FirstParameter();
1891   UL = C->LastParameter ();
1892   PF = C->Value(UF);
1893   PL = C->Value(UL);
1894
1895   Step = (UL - UF)/nbParts;
1896
1897   for (Standard_Integer i = 1; i < nbParts; i++) {
1898
1899     UC = UF + i*Step;
1900     PC = C->Value(UC);
1901
1902     if (UC - UF > PTol && PC.Distance(PF) > Tol) {
1903       if ( UL - UC < PTol || PL.Distance(PC) < Tol)
1904         continue;
1905
1906       TrimC = new Geom2d_TrimmedCurve(C,UF,UC);
1907       theCurves.Append(TrimC);
1908       UF = UC;
1909       PF = PC;
1910       YaCut = Standard_True;
1911     }
1912   }
1913   if (YaCut) {
1914     TrimC = new Geom2d_TrimmedCurve(C,UF,UL);
1915     theCurves.Append(TrimC);
1916   } else
1917     theCurves.Append(C);
1918 }
1919 //  Modified by Sergey KHROMOV - Thu Nov 16 17:28:13 2000 End
1920
1921 //=======================================================================
1922 //function : MakeCircle
1923 //purpose  : 
1924 //=======================================================================
1925
1926 void MakeCircle (const TopoDS_Edge&          E,
1927                  const TopoDS_Vertex&        V,
1928                  const TopoDS_Face&          F,
1929                  const Standard_Real         Offset, 
1930                        BRepFill_IndexedDataMapOfOrientedShapeListOfShape& Map,
1931                  const Handle(Geom_Plane)&   RefPlane)
1932 {
1933   // evaluate the Axis of the Circle.
1934   Standard_Real f,l;
1935   Handle(Geom2d_Curve) GC = BRep_Tool::CurveOnSurface(E,F,f,l);
1936   gp_Vec2d DX;
1937   gp_Pnt2d P;
1938
1939   if (E.Orientation() == TopAbs_FORWARD) {
1940     GC->D1(l,P,DX);
1941     DX.Reverse();
1942   }
1943   else GC->D1(f,P,DX);
1944
1945   gp_Ax2d Axis(P,gp_Dir2d(DX));
1946   Handle(Geom2d_Circle) Circ 
1947     = new  Geom2d_Circle(Axis, Abs(Offset), Offset < 0.);
1948
1949   // Bind the edges in my Map.
1950   TopoDS_Edge OE = BRepLib_MakeEdge(Circ, RefPlane);
1951   TopTools_ListOfShape LL;
1952
1953   LL.Append(OE);
1954   Map.Add(V,LL);
1955
1956 #ifdef DRAW
1957   if ( AffichGeom && !OE.IsNull()) {
1958     char name[256];
1959     sprintf(name,"OFFSET_%d",++NbOFFSET);
1960     DBRep::Set(name,OE);
1961   }
1962 #endif
1963 }
1964
1965 //=======================================================================
1966 //function : MakeOffset
1967 //purpose  : 
1968 //=======================================================================
1969
1970 void MakeOffset (const TopoDS_Edge&        E, 
1971                  const TopoDS_Face&        F,
1972                  const Standard_Real       Offset, 
1973                        BRepFill_IndexedDataMapOfOrientedShapeListOfShape& Map,
1974                  const Handle(Geom_Plane)& RefPlane,
1975                  const Standard_Boolean    IsOpenResult,
1976                  const TopoDS_Vertex *     Ends)
1977 {
1978   Standard_Real f,l;
1979   Standard_Real anOffset = Offset;
1980
1981   if (E.Orientation() == TopAbs_REVERSED) anOffset *= -1;
1982
1983   Handle(Geom2d_Curve) G2d = BRep_Tool::CurveOnSurface(E,F,f,l);
1984   Handle(Geom2d_Curve) G2dOC;
1985
1986   Standard_Boolean ToExtendFirstPar = Standard_True;
1987   Standard_Boolean ToExtendLastPar  = Standard_True;
1988   if (IsOpenResult)
1989   {
1990     TopoDS_Vertex V1, V2;
1991     TopExp::Vertices(E, V1, V2);
1992     if (V1.IsSame(Ends[0]) ||
1993         V1.IsSame(Ends[1]))
1994       ToExtendFirstPar = Standard_False;
1995     if (V2.IsSame(Ends[0]) ||
1996         V2.IsSame(Ends[1]))
1997       ToExtendLastPar  = Standard_False;
1998   }
1999
2000   Geom2dAdaptor_Curve  AC(G2d,f,l);
2001   if ( AC.GetType() == GeomAbs_Circle) {
2002     // if the offset is greater otr equal to the radius and the side of the  
2003     // concavity of the circle => edge null.
2004     gp_Circ2d C1(AC.Circle());
2005     gp_Ax22d axes( C1.Axis());
2006     gp_Dir2d Xd = axes.XDirection();
2007     gp_Dir2d Yd = axes.YDirection();
2008     Standard_Real Crossed = Xd.X()*Yd.Y()-Xd.Y()*Yd.X();
2009     Standard_Real Signe = ( Crossed > 0.) ? 1. : -1.;
2010
2011     if (anOffset*Signe < AC.Circle().Radius() - Precision::Confusion()) {
2012
2013       Handle(Geom2dAdaptor_HCurve) AHC = 
2014         new Geom2dAdaptor_HCurve(G2d);
2015       Adaptor3d_OffsetCurve   Off(AHC,-anOffset);
2016       Handle(Geom2d_Circle) CC = new Geom2d_Circle(Off.Circle());      
2017
2018       Standard_Real Delta = 2*M_PI - l + f;
2019       if (ToExtendFirstPar)
2020         f -= 0.2*Delta;
2021       if (ToExtendLastPar)
2022         l += 0.2*Delta;
2023
2024       G2dOC = new Geom2d_TrimmedCurve(CC,f,l);
2025     }
2026   }
2027   else if (AC.GetType() == GeomAbs_Line) {
2028     Handle(Geom2dAdaptor_HCurve) AHC = 
2029       new Geom2dAdaptor_HCurve(G2d);
2030     Adaptor3d_OffsetCurve Off(AHC,anOffset);
2031     Handle(Geom2d_Line)       CC = new Geom2d_Line(Off.Line());
2032     Standard_Real Delta = (l - f);
2033     if (ToExtendFirstPar)
2034       f -= Delta;
2035     if (ToExtendLastPar)
2036       l += Delta;
2037     G2dOC = new Geom2d_TrimmedCurve(CC,f,l);
2038   }
2039   else {
2040
2041     anOffset = -anOffset;
2042     Handle(Geom2d_TrimmedCurve) G2dT = new Geom2d_TrimmedCurve(G2d,f,l);
2043     G2dOC = new Geom2d_OffsetCurve( G2dT, anOffset);
2044
2045   }
2046
2047   // Bind the edges in my Map.
2048   if (!G2dOC.IsNull()) {
2049     TopoDS_Edge OE = BRepLib_MakeEdge(G2dOC, RefPlane);
2050     OE.Orientation(E.Orientation());
2051     TopTools_ListOfShape LL;
2052     LL.Append(OE);
2053     Map.Add(E,LL);
2054
2055 #ifdef DRAW  
2056     if (AffichGeom && !OE.IsNull()) {
2057       char name[256];
2058       sprintf(name,"OFFSET_%d",++NbOFFSET);
2059       DBRep::Set(name,OE);
2060       Standard_Real ii = 0;
2061     }
2062 #endif
2063     
2064   }
2065 }  
2066
2067
2068 //=======================================================================
2069 //function : VertexFromNode
2070 //purpose  : 
2071 //=======================================================================
2072
2073 Standard_Boolean VertexFromNode (const Handle(MAT_Node)&      aNode, 
2074                                  const Standard_Real          Offset,
2075                                   gp_Pnt2d&                   PN,
2076                                  BRepFill_DataMapOfNodeShape& MapNodeVertex,
2077                                  TopoDS_Vertex&               VN)
2078 {  
2079   Standard_Boolean Status;
2080   Standard_Real    Tol = Precision::Confusion();
2081   BRep_Builder     B;
2082
2083   if (!aNode->Infinite() && Abs(aNode->Distance()-Offset) < Tol) {
2084     //------------------------------------------------
2085     // the Node gives a vertex on the offset
2086     //------------------------------------------------
2087     if (MapNodeVertex.IsBound(aNode)) {
2088       VN = TopoDS::Vertex(MapNodeVertex(aNode));
2089     }
2090     else { 
2091       gp_Pnt P(PN.X(),PN.Y(),0.);
2092       B.MakeVertex (VN);
2093       B.UpdateVertex(VN,P, Precision::Confusion());
2094       MapNodeVertex.Bind(aNode,VN);
2095     }
2096     Status = Standard_True;
2097   }
2098   else Status = Standard_False;
2099
2100   return Status;
2101 }
2102
2103
2104 //=======================================================================
2105 //function : StoreInMap
2106 //purpose  : 
2107 //=======================================================================
2108
2109 void StoreInMap (const TopoDS_Shape& V1,
2110                  const TopoDS_Shape& V2,
2111                  TopTools_IndexedDataMapOfShapeShape& MapVV)
2112 {
2113   TopoDS_Shape OldV = V1, NewV = V2;
2114   Standard_Integer i;
2115
2116   if (MapVV.Contains(V2))
2117     NewV = MapVV.FindFromKey(V2);
2118
2119   if (MapVV.Contains(V1))
2120     MapVV.ChangeFromKey(V1) = NewV;
2121
2122   for (i = 1; i <= MapVV.Extent(); i++)
2123     if (MapVV(i).IsSame(V1))
2124       MapVV(i) = NewV;
2125
2126   MapVV.Add(V1, NewV);
2127 }
2128
2129 //=======================================================================
2130 //function : TrimEdge
2131 //purpose  : 
2132 //=======================================================================
2133
2134 void TrimEdge (const TopoDS_Edge&              E,
2135                const TopTools_ListOfShape&     Detromp,
2136                TopTools_SequenceOfShape& TheVer,
2137                TColStd_SequenceOfReal&   ThePar,
2138                TopTools_SequenceOfShape& S,
2139                TopTools_IndexedDataMapOfShapeShape& MapVV,
2140                const Standard_Integer IndOfE)
2141 {
2142   Standard_Boolean         Change = Standard_True;
2143   BRep_Builder             TheBuilder;
2144   S.Clear();
2145
2146   //-----------------------------------------------------------
2147   // Parse two sequences depending on the parameter on the edge.
2148   //-----------------------------------------------------------
2149   while (Change) {
2150     Change = Standard_False;
2151     for (Standard_Integer i = 1; i < ThePar.Length(); i++) {
2152       if (ThePar.Value(i) > ThePar.Value(i+1)) {
2153         ThePar.Exchange(i,i+1);
2154         TheVer.Exchange(i,i+1);
2155         Change = Standard_True;
2156       }
2157     }
2158   }
2159
2160   //----------------------------------------------------------
2161   // If a vertex is not in the proofing, it is eliminated.
2162   //----------------------------------------------------------
2163   if (!BRep_Tool::Degenerated(E)) {
2164     for (Standard_Integer k = 1; k <= TheVer.Length(); k ++) {
2165       if ( DoubleOrNotInside (Detromp,
2166                               TopoDS::Vertex(TheVer.Value(k)))) {
2167         TheVer.Remove(k);
2168         ThePar.Remove(k);
2169         k--;
2170       }
2171     }
2172   }
2173
2174   //----------------------------------------------------------
2175   // If a vertex_double appears twice in the proofing 
2176   // the vertex is removed.
2177   // otherwise preserve only one of its representations.
2178   //----------------------------------------------------------
2179   if (!BRep_Tool::Degenerated(E)) {
2180     for (Standard_Integer k = 1; k < TheVer.Length(); k ++) {
2181       if (TheVer.Value(k).IsSame(TheVer.Value(k+1)) || 
2182          Abs(ThePar.Value(k)-ThePar.Value(k+1)) <= Precision::PConfusion()) {
2183
2184         if(k+1 == TheVer.Length()) {
2185           StoreInMap(TheVer(k), TheVer(k+1), MapVV);
2186           TheVer.Remove(k);
2187           ThePar.Remove(k);
2188         }
2189         else {
2190           StoreInMap(TheVer(k+1), TheVer(k), MapVV);
2191           TheVer.Remove(k+1);
2192           ThePar.Remove(k+1);
2193         }
2194         /*
2195         if ( DoubleOrNotInside (Detromp,
2196                                 TopoDS::Vertex(TheVer.Value(k)))) {
2197           TheVer.Remove(k);
2198           ThePar.Remove(k);
2199           k--;
2200         }
2201         */
2202         k--;
2203       }
2204     }
2205   }
2206   //-----------------------------------------------------------
2207   // Creation of edges.
2208   // the number of vertices should be even. The created edges  
2209   // go from a vertex with uneven index i to vertex i+1;
2210   //-----------------------------------------------------------
2211   if (IndOfE == 1 || IndOfE == -1) //open result and extreme edges of result
2212   {
2213     TopoDS_Shape aLocalShape = E.EmptyCopied();
2214     TopoDS_Edge NewEdge = TopoDS::Edge(aLocalShape);
2215     TopoDS_Vertex V1, V2;
2216     TopExp::Vertices(E, V1, V2);
2217     Standard_Real fpar, lpar;
2218     BRep_Tool::Range(E, fpar, lpar);
2219     if (IndOfE == 1) //first edge of open wire
2220     {
2221       if (NewEdge.Orientation() == TopAbs_FORWARD)
2222       {
2223         TheBuilder.Add(NewEdge, V1.Oriented(TopAbs_FORWARD));
2224         TheBuilder.Add(NewEdge, TheVer.First().Oriented(TopAbs_REVERSED));
2225         TheBuilder.Range(NewEdge, fpar, ThePar.First());
2226       }
2227       else
2228       {
2229         //TheBuilder.Add(NewEdge, V1.Oriented(TopAbs_REVERSED));
2230         //TheBuilder.Add(NewEdge, TheVer.First().Oriented(TopAbs_FORWARD));
2231         TheBuilder.Add(NewEdge, TheVer.First().Oriented(TopAbs_REVERSED));
2232         TheBuilder.Add(NewEdge, V2.Oriented(TopAbs_FORWARD));
2233         TheBuilder.Range(NewEdge, ThePar.First(), lpar);
2234       }
2235     }
2236     else //last edge of open wire
2237     {
2238       if (NewEdge.Orientation() == TopAbs_FORWARD)
2239       {
2240         TheBuilder.Add(NewEdge, TheVer.First().Oriented(TopAbs_FORWARD));
2241         TheBuilder.Add(NewEdge, V2.Oriented(TopAbs_REVERSED));
2242         TheBuilder.Range(NewEdge, ThePar.First(), lpar);
2243       }
2244       else
2245       {
2246         //TheBuilder.Add(NewEdge, TheVer.First().Oriented(TopAbs_REVERSED));
2247         //TheBuilder.Add(NewEdge, V2.Oriented(TopAbs_FORWARD));
2248         TheBuilder.Add(NewEdge, V1.Oriented(TopAbs_REVERSED));
2249         TheBuilder.Add(NewEdge, TheVer.First().Oriented(TopAbs_FORWARD));
2250         TheBuilder.Range(NewEdge, fpar, ThePar.First());
2251       }
2252     }
2253     S.Append(NewEdge);
2254   }
2255   else
2256   {
2257     for (Standard_Integer k = 1; k < TheVer.Length(); k = k+2) {
2258       TopoDS_Shape aLocalShape = E.EmptyCopied();
2259       TopoDS_Edge NewEdge = TopoDS::Edge(aLocalShape);
2260       //    TopoDS_Edge NewEdge = TopoDS::Edge(E.EmptyCopied());
2261       
2262       if (NewEdge.Orientation() == TopAbs_REVERSED) {
2263         TheBuilder.Add  (NewEdge,TheVer.Value(k)  .Oriented(TopAbs_REVERSED));
2264         TheBuilder.Add  (NewEdge,TheVer.Value(k+1).Oriented(TopAbs_FORWARD));
2265       }
2266       else {      
2267         TheBuilder.Add  (NewEdge,TheVer.Value(k)  .Oriented(TopAbs_FORWARD));
2268         TheBuilder.Add  (NewEdge,TheVer.Value(k+1).Oriented(TopAbs_REVERSED));
2269       }
2270       
2271       
2272       TheBuilder.Range(NewEdge,ThePar.Value(k),ThePar.Value(k+1));
2273       
2274 #ifdef DRAW
2275       if ( AffichEdge) {
2276         char name[256];
2277         sprintf(name,"TRIMEDGE_%d",NbTRIMEDGES);
2278         DBRep::Set(name,NewEdge);  
2279       }
2280       if (Affich2d) {
2281         TopLoc_Location L;
2282         Standard_Real f,l;
2283         Handle(Geom_Surface) Surf;  
2284         Handle(Geom2d_Curve) C;
2285         BRep_Tool::CurveOnSurface(NewEdge,C,Surf,L,f,l);
2286         char name[256];
2287         sprintf(name,"OFFSET2d_%d",NbTRIMEDGES++);
2288         Handle(Geom2d_TrimmedCurve) C2d = new Geom2d_TrimmedCurve(C,f,l);
2289         Handle(DrawTrSurf_Curve2d) dr =
2290           new DrawTrSurf_Curve2d(C2d,Standard_False);
2291         dr->SetColor(Draw_bleu);
2292         Draw::Set(name,dr);
2293       }
2294 #endif
2295       
2296       S.Append(NewEdge);
2297     }
2298   }
2299 }
2300
2301 //=======================================================================
2302 //function : DoubleOrNotInside
2303 //purpose  : return True if V appears twice in LV or is not inside.
2304 //=======================================================================
2305
2306 Standard_Boolean DoubleOrNotInside (const TopTools_ListOfShape& LV,
2307                                     const TopoDS_Vertex&        V)
2308 {  
2309   Standard_Boolean Vu = Standard_False;
2310   TopTools_ListIteratorOfListOfShape it(LV);
2311
2312   for ( ; it.More(); it.Next()) {
2313     if (V.IsSame(it.Value())) {
2314       if  (Vu) return Standard_True;
2315       else       Vu = Standard_True;
2316     }
2317   }
2318   if (Vu) return Standard_False;
2319   else    return Standard_True;   
2320 }
2321
2322 Standard_Boolean IsSmallClosedEdge(const TopoDS_Edge& anEdge,
2323                                    const TopoDS_Vertex& aVertex)
2324 {
2325   gp_Pnt PV = BRep_Tool::Pnt(aVertex);
2326   gp_Pnt2d PV2d, Pfirst, Plast, Pmid;
2327   PV2d.SetCoord( PV.X(), PV.Y() );
2328
2329   Handle(Geom2d_Curve) PCurve;
2330   Handle( BRep_CurveRepresentation ) CurveRep =
2331     ((Handle(BRep_TEdge)::DownCast(anEdge.TShape()))->Curves()).First();
2332   PCurve = CurveRep->PCurve();
2333
2334   Standard_Real fpar = (Handle(BRep_GCurve)::DownCast(CurveRep))->First();
2335   Standard_Real lpar = (Handle(BRep_GCurve)::DownCast(CurveRep))->Last();
2336   Pfirst = PCurve->Value(fpar);
2337   Plast  = PCurve->Value(lpar);
2338   Pmid   = PCurve->Value((fpar + lpar)*0.5);
2339
2340   Standard_Real theTol = BRep_Tool::Tolerance(aVertex);
2341   theTol *= 1.5;
2342
2343   Standard_Real dist1 = Pfirst.Distance(PV2d);
2344   Standard_Real dist2 = Plast.Distance(PV2d);
2345   Standard_Real dist3 = Pmid.Distance(PV2d);
2346
2347   if (dist1 <= theTol && dist2 <= theTol && dist3 <= theTol)
2348     return Standard_True;
2349
2350   return Standard_False;
2351 }
2352
2353 static void CheckBadEdges(const TopoDS_Face& Spine, const Standard_Real Offset,
2354                           const BRepMAT2d_BisectingLocus& Locus, 
2355                           const BRepMAT2d_LinkTopoBilo&   Link,
2356                           TopTools_ListOfShape& BadEdges)
2357 {
2358
2359   TopoDS_Face F = TopoDS::Face(Spine.Oriented(TopAbs_FORWARD));
2360   Standard_Real eps = Precision::Confusion(); 
2361   Standard_Real LimCurv = 1./Offset;
2362
2363   TopTools_MapOfShape aMap;
2364
2365   for (Standard_Integer ic = 1; ic <= Locus.NumberOfContours(); ic++) {
2366     for (Standard_Integer ie = 1; ie <= Locus.NumberOfElts(ic); ie++) {
2367       const TopoDS_Shape& SE = Link.GeneratingShape(Locus.BasicElt(ic,ie));
2368       if (SE.ShapeType() == TopAbs_EDGE) {
2369
2370         if (aMap.Contains(SE)) {
2371           //cout << "Edge is treated second time" << endl;
2372           continue;
2373         }
2374
2375         TopoDS_Edge E = TopoDS::Edge(SE);
2376
2377         Standard_Real f,l;
2378
2379         Handle(Geom2d_Curve) G2d = BRep_Tool::CurveOnSurface(E,F,f,l);
2380
2381         Geom2dAdaptor_Curve  AC(G2d,f,l);
2382         GeomAbs_CurveType aCType = AC.GetType();
2383
2384         if(aCType != GeomAbs_Line && aCType != GeomAbs_Circle) {
2385
2386           Standard_Boolean reverse = Standard_False;
2387           if (E.Orientation() == TopAbs_FORWARD) reverse = Standard_True;
2388
2389           gp_Pnt2d P, Pc;
2390           gp_Dir2d N;
2391
2392           Geom2dLProp_CLProps2d aCLProps(G2d, 2, eps);
2393
2394           aCLProps.SetParameter(f);
2395           if(!aCLProps.IsTangentDefined()) {
2396             BadEdges.Append(SE);
2397             aMap.Add(SE);
2398             continue;
2399           }
2400
2401           P = aCLProps.Value();
2402           Standard_Real Crv = aCLProps.Curvature();
2403
2404           if(Crv >= eps) {
2405             aCLProps.Tangent(N);
2406             Standard_Real x = N.Y(), y = -N.X();
2407             N.SetCoord(x, y);
2408             if (reverse) N.Reverse();
2409             aCLProps.CentreOfCurvature(Pc);
2410             gp_Vec2d Dir( P, Pc );
2411             if (N.Dot(Dir) > 0.) {
2412               if (LimCurv <= Crv + eps) {
2413                 BadEdges.Append(SE);
2414                 aMap.Add(SE);
2415                 continue;
2416               }
2417             }
2418           }  
2419
2420           aCLProps.SetParameter(l);
2421           if(!aCLProps.IsTangentDefined()) {
2422             BadEdges.Append(SE);
2423             aMap.Add(SE);
2424             continue;
2425           }
2426
2427           P = aCLProps.Value();
2428           Crv = aCLProps.Curvature();
2429
2430           if(Crv >= eps) {
2431             aCLProps.Tangent(N);
2432             Standard_Real x = N.Y(), y = -N.X();
2433             N.SetCoord(x, y);
2434             if (reverse) N.Reverse();
2435             aCLProps.CentreOfCurvature(Pc);
2436             gp_Vec2d Dir( P, Pc );
2437             if (N.Dot(Dir) > 0.) {
2438               if (LimCurv <= Crv + eps) {
2439                 BadEdges.Append(SE);
2440                 aMap.Add(SE);
2441                 continue;
2442               }
2443             }
2444           }  
2445         }
2446       }
2447     }
2448   }
2449 }
2450
2451
2452 //=======================================================================
2453 //function : PerformCurve
2454 //purpose  : 
2455 //=======================================================================
2456
2457 static Standard_Boolean PerformCurve (TColStd_SequenceOfReal& Parameters,
2458                                       TColgp_SequenceOfPnt&   Points,
2459                                       const Adaptor3d_Curve& C, 
2460                                       const Standard_Real Deflection,
2461                                       const Standard_Real U1,
2462                                       const Standard_Real U2,
2463                                       const Standard_Real EPSILON,
2464                                       const Standard_Integer Nbmin)
2465 {
2466   Standard_Real UU1 = Min(U1, U2);
2467   Standard_Real UU2 = Max(U1, U2);
2468
2469   gp_Pnt Pdeb, Pfin;
2470   gp_Vec Ddeb,Dfin;
2471   C.D1(UU1,Pdeb,Ddeb);
2472   Parameters.Append(UU1);
2473   Points.Append(Pdeb);
2474
2475   C.D1(UU2,Pfin,Dfin);
2476
2477   const Standard_Real aDelta = UU2 - UU1;
2478   const Standard_Real aDist = Pdeb.Distance(Pfin);
2479
2480   if((aDelta/aDist) > 5.0e-14)
2481   {
2482     QuasiFleche(C,Deflection*Deflection,
2483                       UU1,Pdeb,
2484                       Ddeb,
2485                       UU2,Pfin,
2486                       Dfin,
2487                       Nbmin,
2488                       EPSILON*EPSILON,
2489                       Parameters,Points);
2490   }
2491
2492   return Standard_True;
2493 }
2494 //=======================================================================
2495 //function : QuasiFleche
2496 //purpose  : 
2497 //=======================================================================
2498
2499 static void QuasiFleche(const Adaptor3d_Curve& C,
2500                         const Standard_Real Deflection2, 
2501                         const Standard_Real Udeb,
2502                         const gp_Pnt& Pdeb,
2503                         const gp_Vec& Vdeb,
2504                         const Standard_Real Ufin,
2505                         const gp_Pnt& Pfin,
2506                         const gp_Vec& Vfin,
2507                         const Standard_Integer Nbmin,
2508                         const Standard_Real Eps,
2509                         TColStd_SequenceOfReal& Parameters,
2510                         TColgp_SequenceOfPnt& Points)
2511 {
2512   Standard_Integer Ptslength = Points.Length();
2513   Standard_Real Udelta = Ufin-Udeb;
2514   gp_Pnt Pdelta;
2515   gp_Vec Vdelta;
2516   if (Nbmin > 2) {
2517     Udelta /=(Nbmin-1);
2518     C.D1(Udeb+Udelta,Pdelta,Vdelta);
2519   }
2520   else {
2521     Pdelta = Pfin;
2522     Vdelta = Vfin;
2523   }
2524
2525
2526   Standard_Real Norme = gp_Vec(Pdeb,Pdelta).SquareMagnitude();
2527   Standard_Real theFleche=0;
2528   Standard_Boolean flecheok = Standard_False;
2529   if (Norme > Eps) { 
2530     // Evaluation of the arrow by interpolation. See IntWalk_IWalking_5.gxx
2531     Standard_Real N1 = Vdeb.SquareMagnitude();
2532     Standard_Real N2 = Vdelta.SquareMagnitude();
2533     if (N1 > Eps && N2 > Eps) {
2534       Standard_Real Normediff = 
2535         (Vdeb.Normalized().XYZ()-Vdelta.Normalized().XYZ()).SquareModulus();
2536       if (Normediff > Eps) {
2537         theFleche = Normediff*Norme/64.;
2538         flecheok = Standard_True;
2539       }
2540     }
2541   }
2542   if (!flecheok) {
2543     gp_Pnt Pmid((Pdeb.XYZ()+Pdelta.XYZ())/2.);
2544     gp_Pnt Pverif(C.Value(Udeb+Udelta/2.));
2545     theFleche = Pmid.SquareDistance(Pverif);
2546   }
2547
2548   if (theFleche < Deflection2) {
2549     Parameters.Append(Udeb+Udelta);
2550     Points.Append(Pdelta);
2551   }
2552   else {
2553     QuasiFleche(C,Deflection2,Udeb,Pdeb,
2554                 Vdeb,
2555                 Udeb+Udelta,Pdelta,
2556                 Vdelta,
2557                 3,
2558                 Eps,
2559                 Parameters,Points);
2560
2561   }
2562
2563   if (Nbmin > 2) {
2564     QuasiFleche(C,Deflection2,Udeb+Udelta,Pdelta,
2565                 Vdelta,
2566                 Ufin,Pfin,
2567                 Vfin,
2568                 Nbmin-(Points.Length()-Ptslength),
2569                 Eps,
2570                 Parameters,Points);
2571   }
2572 }
2573