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