0027085: ShapeUpgrade_UnifySameDomain very large performance difference for seemingly...
[occt.git] / src / ShapeUpgrade / ShapeUpgrade_UnifySameDomain.cxx
1 // Created on: 2012-06-09
2 // Created by: jgv@ROLEX
3 // Copyright (c) 2012-2014 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16
17 #include <BRep_Builder.hxx>
18 #include <BRep_CurveRepresentation.hxx>
19 #include <BRep_ListIteratorOfListOfCurveRepresentation.hxx>
20 #include <BRep_TEdge.hxx>
21 #include <BRep_Tool.hxx>
22 #include <BRepLib.hxx>
23 #include <BRepLib_MakeEdge.hxx>
24 #include <BRepTopAdaptor_TopolTool.hxx>
25 #include <GC_MakeCircle.hxx>
26 #include <Geom2d_Line.hxx>
27 #include <Geom2d_TrimmedCurve.hxx>
28 #include <Geom2dConvert.hxx>
29 #include <Geom2dConvert_CompCurveToBSplineCurve.hxx>
30 #include <Geom_BezierCurve.hxx>
31 #include <Geom_BSplineCurve.hxx>
32 #include <Geom_Circle.hxx>
33 #include <Geom_CylindricalSurface.hxx>
34 #include <Geom_ElementarySurface.hxx>
35 #include <Geom_Line.hxx>
36 #include <Geom_OffsetSurface.hxx>
37 #include <Geom_RectangularTrimmedSurface.hxx>
38 #include <Geom_Surface.hxx>
39 #include <Geom_SurfaceOfLinearExtrusion.hxx>
40 #include <Geom_SurfaceOfRevolution.hxx>
41 #include <Geom_SweptSurface.hxx>
42 #include <Geom_TrimmedCurve.hxx>
43 #include <GeomAdaptor_HSurface.hxx>
44 #include <GeomConvert.hxx>
45 #include <GeomConvert_CompCurveToBSplineCurve.hxx>
46 #include <GeomLib_IsPlanarSurface.hxx>
47 #include <gp_Cylinder.hxx>
48 #include <gp_Dir.hxx>
49 #include <gp_Lin.hxx>
50 #include <IntPatch_ImpImpIntersection.hxx>
51 #include <ShapeAnalysis_Edge.hxx>
52 #include <ShapeAnalysis_WireOrder.hxx>
53 #include <ShapeBuild_Edge.hxx>
54 #include <ShapeBuild_ReShape.hxx>
55 #include <ShapeExtend_CompositeSurface.hxx>
56 #include <ShapeFix_ComposeShell.hxx>
57 #include <ShapeFix_Edge.hxx>
58 #include <ShapeFix_Face.hxx>
59 #include <ShapeFix_SequenceOfWireSegment.hxx>
60 #include <ShapeFix_Shell.hxx>
61 #include <ShapeFix_Wire.hxx>
62 #include <ShapeFix_WireSegment.hxx>
63 #include <ShapeUpgrade_RemoveLocations.hxx>
64 #include <ShapeUpgrade_UnifySameDomain.hxx>
65 #include <Standard_Type.hxx>
66 #include <TColGeom2d_Array1OfBSplineCurve.hxx>
67 #include <TColGeom2d_HArray1OfBSplineCurve.hxx>
68 #include <TColGeom2d_SequenceOfBoundedCurve.hxx>
69 #include <TColGeom_Array1OfBSplineCurve.hxx>
70 #include <TColGeom_HArray1OfBSplineCurve.hxx>
71 #include <TColGeom_HArray2OfSurface.hxx>
72 #include <TColGeom_SequenceOfSurface.hxx>
73 #include <TColStd_Array1OfReal.hxx>
74 #include <TColStd_MapOfInteger.hxx>
75 #include <TopExp.hxx>
76 #include <TopExp_Explorer.hxx>
77 #include <TopoDS.hxx>
78 #include <TopoDS_Edge.hxx>
79 #include <TopoDS_Face.hxx>
80 #include <TopoDS_Shape.hxx>
81 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
82 #include <TopTools_IndexedMapOfShape.hxx>
83 #include <TopTools_ListIteratorOfListOfShape.hxx>
84 #include <TopTools_MapOfShape.hxx>
85 #include <TopTools_SequenceOfShape.hxx>
86 #include <gp_Circ.hxx>
87 #include <BRepAdaptor_Curve.hxx>
88 #include <BRepClass_FaceClassifier.hxx>
89
90 IMPLEMENT_STANDARD_RTTIEXT(ShapeUpgrade_UnifySameDomain,MMgt_TShared)
91
92 struct SubSequenceOfEdges
93 {
94   TopTools_SequenceOfShape SeqsEdges;
95   TopoDS_Edge UnionEdges;
96 };
97
98
99 //=======================================================================
100 //function : AddOrdinaryEdges
101 //purpose  : auxilary
102 //=======================================================================
103 // adds edges from the shape to the sequence
104 // seams and equal edges are dropped
105 // Returns true if one of original edges dropped
106 static Standard_Boolean AddOrdinaryEdges(TopTools_SequenceOfShape& edges,
107                                          const TopoDS_Shape aShape,
108                                          Standard_Integer& anIndex)
109 {
110   //map of edges
111   TopTools_IndexedMapOfShape aNewEdges;
112   //add edges without seams
113   for(TopExp_Explorer exp(aShape,TopAbs_EDGE); exp.More(); exp.Next()) {
114     TopoDS_Shape edge = exp.Current();
115     if(aNewEdges.Contains(edge))
116     {
117       //aNewEdges.Remove(edge);
118       TopoDS_Shape LastEdge = aNewEdges(aNewEdges.Extent());
119       aNewEdges.RemoveLast();
120       if (aNewEdges.FindIndex(edge) != 0)
121         aNewEdges.Substitute(aNewEdges.FindIndex(edge), LastEdge);
122       /////////////////////////
123     }
124     else
125       aNewEdges.Add(edge);
126   }
127
128   Standard_Boolean isDropped = Standard_False;
129   //merge edges and drop seams
130   Standard_Integer i;
131   for (i = 1; i <= edges.Length(); i++) {
132     TopoDS_Shape current = edges(i);
133     if(aNewEdges.Contains(current)) {
134
135       //aNewEdges.Remove(current);
136       TopoDS_Shape LastEdge = aNewEdges(aNewEdges.Extent());
137       aNewEdges.RemoveLast();
138       if (aNewEdges.FindIndex(current) != 0)
139         aNewEdges.Substitute(aNewEdges.FindIndex(current), LastEdge);
140       /////////////////////////
141       edges.Remove(i);
142       i--;
143
144       if(!isDropped) {
145         isDropped = Standard_True;
146         anIndex = i;
147       }
148     }
149   }
150
151   //add edges to the sequemce
152   for (i = 1; i <= aNewEdges.Extent(); i++)
153     edges.Append(aNewEdges(i));
154
155   return isDropped;
156 }
157
158 //=======================================================================
159 //function : getCylinder
160 //purpose  : auxilary
161 //=======================================================================
162 static Standard_Boolean getCylinder(Handle(Geom_Surface)& theInSurface,
163                                     gp_Cylinder& theOutCylinder)
164 {
165   Standard_Boolean isCylinder = Standard_False;
166
167   if (theInSurface->IsKind(STANDARD_TYPE(Geom_CylindricalSurface))) {
168     Handle(Geom_CylindricalSurface) aGC = Handle(Geom_CylindricalSurface)::DownCast(theInSurface);
169
170     theOutCylinder = aGC->Cylinder();
171     isCylinder = Standard_True;
172   }
173   else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfRevolution))) {
174     Handle(Geom_SurfaceOfRevolution) aRS =
175       Handle(Geom_SurfaceOfRevolution)::DownCast(theInSurface);
176     Handle(Geom_Curve) aBasis = aRS->BasisCurve();
177     if (aBasis->IsKind(STANDARD_TYPE(Geom_Line))) {
178       Handle(Geom_Line) aBasisLine = Handle(Geom_Line)::DownCast(aBasis);
179       gp_Dir aDir = aRS->Direction();
180       gp_Dir aBasisDir = aBasisLine->Position().Direction();
181       if (aBasisDir.IsParallel(aDir, Precision::Angular())) {
182         // basis line is parallel to the revolution axis: it is a cylinder
183         gp_Pnt aLoc = aRS->Location();
184         Standard_Real aR = aBasisLine->Lin().Distance(aLoc);
185         gp_Ax3 aCylAx (aLoc, aDir);
186
187         theOutCylinder = gp_Cylinder(aCylAx, aR);
188         isCylinder = Standard_True;
189       }
190     }
191   }
192   else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfLinearExtrusion))) {
193     Handle(Geom_SurfaceOfLinearExtrusion) aLES =
194       Handle(Geom_SurfaceOfLinearExtrusion)::DownCast(theInSurface);
195     Handle(Geom_Curve) aBasis = aLES->BasisCurve();
196     if (aBasis->IsKind(STANDARD_TYPE(Geom_Circle))) {
197       Handle(Geom_Circle) aBasisCircle = Handle(Geom_Circle)::DownCast(aBasis);
198       gp_Dir aDir = aLES->Direction();
199       gp_Dir aBasisDir = aBasisCircle->Position().Direction();
200       if (aBasisDir.IsParallel(aDir, Precision::Angular())) {
201         // basis circle is normal to the extrusion axis: it is a cylinder
202         gp_Pnt aLoc = aBasisCircle->Location();
203         Standard_Real aR = aBasisCircle->Radius();
204         gp_Ax3 aCylAx (aLoc, aDir);
205
206         theOutCylinder = gp_Cylinder(aCylAx, aR);
207         isCylinder = Standard_True;
208       }
209     }
210   }
211   else {
212   }
213
214   return isCylinder;
215 }
216
217 //=======================================================================
218 //function : ClearRts
219 //purpose  : auxilary
220 //=======================================================================
221 static Handle(Geom_Surface) ClearRts(const Handle(Geom_Surface)& aSurface)
222 {
223   if(aSurface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) {
224     Handle(Geom_RectangularTrimmedSurface) rts =
225       Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurface);
226     return rts->BasisSurface();
227   }
228   return aSurface;
229 }
230
231 //=======================================================================
232 //function : IsSameDomain
233 //purpose  : 
234 //=======================================================================
235 static Standard_Boolean IsSameDomain(const TopoDS_Face& aFace,
236                                      const TopoDS_Face& aCheckedFace)
237 {
238   //checking the same handles
239   TopLoc_Location L1, L2;
240   Handle(Geom_Surface) S1, S2;
241
242   S1 = BRep_Tool::Surface(aFace,L1);
243   S2 = BRep_Tool::Surface(aCheckedFace,L2);
244
245   if (S1 == S2 && L1 == L2)
246     return Standard_True;
247
248   // planar and cylindrical cases (IMP 20052)
249   Standard_Real aPrec = Precision::Confusion();
250
251   S1 = BRep_Tool::Surface(aFace);
252   S2 = BRep_Tool::Surface(aCheckedFace);
253
254   S1 = ClearRts(S1);
255   S2 = ClearRts(S2);
256
257   //Handle(Geom_OffsetSurface) aGOFS1, aGOFS2;
258   //aGOFS1 = Handle(Geom_OffsetSurface)::DownCast(S1);
259   //aGOFS2 = Handle(Geom_OffsetSurface)::DownCast(S2);
260   //if (!aGOFS1.IsNull()) S1 = aGOFS1->BasisSurface();
261   //if (!aGOFS2.IsNull()) S2 = aGOFS2->BasisSurface();
262
263   // case of two elementary surfaces: use OCCT tool
264   // elementary surfaces: ConicalSurface, CylindricalSurface,
265   //                      Plane, SphericalSurface and ToroidalSurface
266   if (S1->IsKind(STANDARD_TYPE(Geom_ElementarySurface)) &&
267       S2->IsKind(STANDARD_TYPE(Geom_ElementarySurface)))
268   {
269     Handle(GeomAdaptor_HSurface) aGA1 = new GeomAdaptor_HSurface(S1);
270     Handle(GeomAdaptor_HSurface) aGA2 = new GeomAdaptor_HSurface(S2);
271
272     Handle(BRepTopAdaptor_TopolTool) aTT1 = new BRepTopAdaptor_TopolTool();
273     Handle(BRepTopAdaptor_TopolTool) aTT2 = new BRepTopAdaptor_TopolTool();
274
275     try {
276       IntPatch_ImpImpIntersection anIIInt (aGA1, aTT1, aGA2, aTT2, aPrec, aPrec);
277       if (!anIIInt.IsDone() || anIIInt.IsEmpty())
278         return Standard_False;
279
280       return anIIInt.TangentFaces();
281     }
282     catch (Standard_Failure) {
283       return Standard_False;
284     }
285   }
286
287   // case of two planar surfaces:
288   // all kinds of surfaces checked, including b-spline and bezier
289   GeomLib_IsPlanarSurface aPlanarityChecker1 (S1, aPrec);
290   if (aPlanarityChecker1.IsPlanar()) {
291     GeomLib_IsPlanarSurface aPlanarityChecker2 (S2, aPrec);
292     if (aPlanarityChecker2.IsPlanar()) {
293       gp_Pln aPln1 = aPlanarityChecker1.Plan();
294       gp_Pln aPln2 = aPlanarityChecker2.Plan();
295
296       if (aPln1.Position().Direction().IsParallel(aPln2.Position().Direction(),Precision::Angular()) &&
297           aPln1.Distance(aPln2) < aPrec) {
298         return Standard_True;
299       }
300     }
301   }
302
303   // case of two cylindrical surfaces, at least one of which is a swept surface
304   // swept surfaces: SurfaceOfLinearExtrusion, SurfaceOfRevolution
305   if ((S1->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
306        S1->IsKind(STANDARD_TYPE(Geom_SweptSurface))) &&
307       (S2->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
308        S2->IsKind(STANDARD_TYPE(Geom_SweptSurface))))
309   {
310     gp_Cylinder aCyl1, aCyl2;
311     if (getCylinder(S1, aCyl1) && getCylinder(S2, aCyl2)) {
312       if (fabs(aCyl1.Radius() - aCyl2.Radius()) < aPrec) {
313         gp_Dir aDir1 = aCyl1.Position().Direction();
314         gp_Dir aDir2 = aCyl2.Position().Direction();
315         if (aDir1.IsParallel(aDir2, Precision::Angular())) {
316           gp_Pnt aLoc1 = aCyl1.Location();
317           gp_Pnt aLoc2 = aCyl2.Location();
318           gp_Vec aVec12 (aLoc1, aLoc2);
319           if (aVec12.SquareMagnitude() < aPrec*aPrec ||
320               aVec12.IsParallel(aDir1, Precision::Angular())) {
321             return Standard_True;
322           }
323         }
324       }
325     }
326   }
327
328   return Standard_False;
329 }
330
331 //=======================================================================
332 //function : MovePCurves
333 //purpose  :
334 //=======================================================================
335 static void MovePCurves(TopoDS_Face& aTarget,
336                         const TopoDS_Face& aSource)
337 {
338   BRep_Builder B;
339   for(TopExp_Explorer wexp(aSource,TopAbs_WIRE);wexp.More();wexp.Next()) {
340     Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(TopoDS::Wire(wexp.Current()),
341                                                   aTarget, Precision::Confusion());
342     sfw->FixReorder();
343     Standard_Boolean isReoredFailed = sfw->StatusReorder ( ShapeExtend_FAIL );
344     sfw->FixEdgeCurves();
345     if(isReoredFailed)
346       continue;
347
348     sfw->FixShifted();
349     sfw->FixDegenerated();
350
351     // remove degenerated edges from not degenerated points
352     ShapeAnalysis_Edge sae;
353     Handle(ShapeExtend_WireData) sewd = sfw->WireData();
354     for(Standard_Integer i = 1; i<=sewd->NbEdges();i++) {
355       TopoDS_Edge E = sewd->Edge(i);
356       if(BRep_Tool::Degenerated(E)&&!sae.HasPCurve(E,aTarget)) {
357         sewd->Remove(i);
358         i--;
359       }
360     }
361
362     TopoDS_Wire ResWire = sfw->Wire();
363     B.Add(aTarget,ResWire);
364   }
365 }
366
367 //=======================================================================
368 //function : GlueEdgesWithPCurves
369 //purpose  : Glues the pcurves of the sequence of edges
370 //           and glues their 3d curves
371 //=======================================================================
372 static TopoDS_Edge GlueEdgesWithPCurves(const TopTools_SequenceOfShape& aChain,
373                                         const TopoDS_Vertex& FirstVertex,
374                                         const TopoDS_Vertex& LastVertex)
375 {
376   Standard_Integer i, j;
377
378   TopoDS_Edge FirstEdge = TopoDS::Edge(aChain(1));
379   //TColGeom2d_SequenceOfCurve PCurveSeq;
380   TColGeom_SequenceOfSurface SurfSeq;
381   //TopTools_SequenceOfShape LocSeq;
382   
383   BRep_ListIteratorOfListOfCurveRepresentation itr( (Handle(BRep_TEdge)::DownCast(FirstEdge.TShape()))->Curves() );
384   for (; itr.More(); itr.Next())
385   {
386     Handle(BRep_CurveRepresentation) CurveRep = itr.Value();
387     if (CurveRep->IsCurveOnSurface())
388     {
389       //PCurveSeq.Append(CurveRep->PCurve());
390       SurfSeq.Append(CurveRep->Surface());
391       /*
392       TopoDS_Shape aLocShape;
393       aLocShape.Location(CurveRep->Location());
394       LocSeq.Append(aLocShape);
395       */
396     }
397   }
398
399   Standard_Real fpar, lpar;
400   BRep_Tool::Range(FirstEdge, fpar, lpar);
401   TopoDS_Edge PrevEdge = FirstEdge;
402   TopoDS_Vertex CV;
403   Standard_Real MaxTol = 0.;
404   
405   TopoDS_Edge ResEdge;
406   BRep_Builder BB;
407
408   Standard_Integer nb_curve = aChain.Length();   //number of curves
409   TColGeom_Array1OfBSplineCurve tab_c3d(0,nb_curve-1);                    //array of the curves
410   TColStd_Array1OfReal tabtolvertex(0,nb_curve-1); //(0,nb_curve-2);  //array of the tolerances
411     
412   TopoDS_Vertex PrevVertex = FirstVertex;
413   for (i = 1; i <= nb_curve; i++)
414   {
415     TopoDS_Edge anEdge = TopoDS::Edge(aChain(i));
416     TopoDS_Vertex VF, VL;
417     TopExp::Vertices(anEdge, VF, VL);
418     Standard_Boolean ToReverse = (!VF.IsSame(PrevVertex));
419     
420     Standard_Real Tol1 = BRep_Tool::Tolerance(VF);
421     Standard_Real Tol2 = BRep_Tool::Tolerance(VL);
422     if (Tol1 > MaxTol)
423       MaxTol = Tol1;
424     if (Tol2 > MaxTol)
425       MaxTol = Tol2;
426     
427     if (i > 1)
428     {
429       TopExp::CommonVertex(PrevEdge, anEdge, CV);
430       Standard_Real Tol = BRep_Tool::Tolerance(CV);
431       tabtolvertex(i-2) = Tol;
432     }
433     
434     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, fpar, lpar);
435     Handle(Geom_TrimmedCurve) aTrCurve = new Geom_TrimmedCurve(aCurve, fpar, lpar);
436     tab_c3d(i-1) = GeomConvert::CurveToBSplineCurve(aTrCurve);
437     GeomConvert::C0BSplineToC1BSplineCurve(tab_c3d(i-1), Precision::Confusion());
438     if (ToReverse)
439       tab_c3d(i-1)->Reverse();
440     PrevVertex = (ToReverse)? VF : VL;
441     PrevEdge = anEdge;
442   }
443   Handle(TColGeom_HArray1OfBSplineCurve)  concatcurve;     //array of the concatenated curves
444   Handle(TColStd_HArray1OfInteger)        ArrayOfIndices;  //array of the remining Vertex
445   GeomConvert::ConcatC1(tab_c3d,
446                         tabtolvertex,
447                         ArrayOfIndices,
448                         concatcurve,
449                         Standard_False,
450                         Precision::Confusion());   //C1 concatenation
451   
452   if (concatcurve->Length() > 1)
453   {
454     GeomConvert_CompCurveToBSplineCurve Concat(concatcurve->Value(concatcurve->Lower()));
455     
456     for (i = concatcurve->Lower()+1; i <= concatcurve->Upper(); i++)
457       Concat.Add( concatcurve->Value(i), MaxTol, Standard_True );
458     
459     concatcurve->SetValue(concatcurve->Lower(), Concat.BSplineCurve());
460   }
461   Handle(Geom_BSplineCurve) ResCurve = concatcurve->Value(concatcurve->Lower());
462   
463   TColGeom2d_SequenceOfBoundedCurve ResPCurves;
464   TopLoc_Location aLoc;
465   for (j = 1; j <= SurfSeq.Length(); j++)
466   {
467     TColGeom2d_Array1OfBSplineCurve tab_c2d(0,nb_curve-1); //array of the pcurves
468     
469     PrevVertex = FirstVertex;
470     PrevEdge = FirstEdge;
471     //TopLoc_Location theLoc = LocSeq(j).Location();
472     for (i = 1; i <= nb_curve; i++)
473     {
474       TopoDS_Edge anEdge = TopoDS::Edge(aChain(i));
475       TopoDS_Vertex VF, VL;
476       TopExp::Vertices(anEdge, VF, VL);
477       Standard_Boolean ToReverse = (!VF.IsSame(PrevVertex));
478
479       /*
480       Handle(Geom2d_Curve) aPCurve =
481         BRep_Tool::CurveOnSurface(anEdge, SurfSeq(j), anEdge.Location()*theLoc, fpar, lpar);
482       */
483       Handle(Geom2d_Curve) aPCurve =
484         BRep_Tool::CurveOnSurface(anEdge, SurfSeq(j), aLoc, fpar, lpar);
485       Handle(Geom2d_TrimmedCurve) aTrPCurve = new Geom2d_TrimmedCurve(aPCurve, fpar, lpar);
486       tab_c2d(i-1) = Geom2dConvert::CurveToBSplineCurve(aTrPCurve);
487       Geom2dConvert::C0BSplineToC1BSplineCurve(tab_c2d(i-1), Precision::Confusion());
488       if (ToReverse)
489         tab_c2d(i-1)->Reverse();
490       PrevVertex = (ToReverse)? VF : VL;
491       PrevEdge = anEdge;
492     }
493     Handle(TColGeom2d_HArray1OfBSplineCurve)  concatc2d;     //array of the concatenated curves
494     Handle(TColStd_HArray1OfInteger)        ArrayOfInd2d;  //array of the remining Vertex
495     Geom2dConvert::ConcatC1(tab_c2d,
496                             tabtolvertex,
497                             ArrayOfInd2d,
498                             concatc2d,
499                             Standard_False,
500                             Precision::Confusion());   //C1 concatenation
501     
502     if (concatc2d->Length() > 1)
503     {
504       Geom2dConvert_CompCurveToBSplineCurve Concat2d(concatc2d->Value(concatc2d->Lower()));
505       
506       for (i = concatc2d->Lower()+1; i <= concatc2d->Upper(); i++)
507         Concat2d.Add( concatc2d->Value(i), MaxTol, Standard_True );
508       
509       concatc2d->SetValue(concatc2d->Lower(), Concat2d.BSplineCurve());
510     }
511     Handle(Geom2d_BSplineCurve) aResPCurve = concatc2d->Value(concatc2d->Lower());
512     ResPCurves.Append(aResPCurve);
513   }
514   
515   ResEdge = BRepLib_MakeEdge(ResCurve,
516                              FirstVertex, LastVertex,
517                              ResCurve->FirstParameter(), ResCurve->LastParameter());
518   BB.SameRange(ResEdge, Standard_False);
519   BB.SameParameter(ResEdge, Standard_False);
520   for (j = 1; j <= ResPCurves.Length(); j++)
521   {
522     BB.UpdateEdge(ResEdge, ResPCurves(j), SurfSeq(j), aLoc, MaxTol);
523     BB.Range(ResEdge, SurfSeq(j), aLoc, ResPCurves(j)->FirstParameter(), ResPCurves(j)->LastParameter());
524   }
525
526   BRepLib::SameParameter(ResEdge, MaxTol, Standard_True);
527   
528   return ResEdge;
529 }
530
531 //=======================================================================
532 //function : MergeSubSeq
533 //purpose  : Merges a sequence of edges into one edge if possible
534 //=======================================================================
535
536 static Standard_Boolean MergeSubSeq(const TopTools_SequenceOfShape& aChain, TopoDS_Edge& OutEdge, double Tol, Standard_Boolean ConcatBSplines) 
537 {
538   ShapeAnalysis_Edge sae;
539   BRep_Builder B;
540   // union edges in chain
541   int j;
542   Standard_Real fp1,lp1,fp2,lp2;
543   Standard_Boolean IsUnionOfLinesPossible = Standard_True;
544   Standard_Boolean IsUnionOfCirclesPossible = Standard_True;
545   Handle(Geom_Curve) c3d1, c3d2;
546   for(j=1; j<aChain.Length(); j++) 
547   {
548     TopoDS_Edge edge1 = TopoDS::Edge(aChain.Value(j));
549     c3d1 = BRep_Tool::Curve(edge1,fp1,lp1);
550
551     TopoDS_Edge edge2 = TopoDS::Edge(aChain.Value(j+1));
552     c3d2 = BRep_Tool::Curve(edge2,fp2,lp2);
553
554     if(c3d1.IsNull() || c3d2.IsNull()) 
555       return Standard_False;
556
557     while(c3d1->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
558       Handle(Geom_TrimmedCurve) tc =
559         Handle(Geom_TrimmedCurve)::DownCast(c3d1);
560       c3d1 = tc->BasisCurve();
561     }
562     while(c3d2->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
563       Handle(Geom_TrimmedCurve) tc =
564         Handle(Geom_TrimmedCurve)::DownCast(c3d2);
565       c3d2 = tc->BasisCurve();
566     }
567     if( c3d1->IsKind(STANDARD_TYPE(Geom_Line)) && c3d2->IsKind(STANDARD_TYPE(Geom_Line)) ) {
568       Handle(Geom_Line) L1 = Handle(Geom_Line)::DownCast(c3d1);
569       Handle(Geom_Line) L2 = Handle(Geom_Line)::DownCast(c3d2);
570       gp_Dir Dir1 = L1->Position().Direction();
571       gp_Dir Dir2 = L2->Position().Direction();
572       if(!Dir1.IsParallel(Dir2,Tol))  
573         IsUnionOfLinesPossible = Standard_False;
574     }
575     else
576       IsUnionOfLinesPossible = Standard_False;
577     if( c3d1->IsKind(STANDARD_TYPE(Geom_Circle)) && c3d2->IsKind(STANDARD_TYPE(Geom_Circle)) ) {
578       Handle(Geom_Circle) C1 = Handle(Geom_Circle)::DownCast(c3d1);
579       Handle(Geom_Circle) C2 = Handle(Geom_Circle)::DownCast(c3d2);
580       gp_Pnt P01 = C1->Location();
581       gp_Pnt P02 = C2->Location();
582       if (P01.Distance(P02) > Precision::Confusion())
583         IsUnionOfCirclesPossible = Standard_False;
584     }
585     else
586       IsUnionOfCirclesPossible = Standard_False;
587   }
588   if (IsUnionOfLinesPossible && IsUnionOfCirclesPossible)
589     return Standard_False;
590
591   //union of lines is possible
592   if (IsUnionOfLinesPossible)
593   {
594     TopoDS_Vertex V1 = sae.FirstVertex(TopoDS::Edge(aChain.First()));
595     gp_Pnt PV1 = BRep_Tool::Pnt(V1);
596     TopoDS_Vertex V2 = sae.LastVertex(TopoDS::Edge(aChain.Last()));
597     gp_Pnt PV2 = BRep_Tool::Pnt(V2);
598     gp_Vec Vec(PV1, PV2);
599     Handle(Geom_Line) L = new Geom_Line(gp_Ax1(PV1,Vec));
600     Standard_Real dist = PV1.Distance(PV2);
601     Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(L,0.0,dist);
602     TopoDS_Edge E;
603     B.MakeEdge (E, tc ,Precision::Confusion());
604     B.Add (E,V1);  B.Add (E,V2);
605     B.UpdateVertex(V1, 0., E, 0.);
606     B.UpdateVertex(V2, dist, E, 0.);
607     OutEdge = E;
608     return Standard_True;
609   }
610
611   if (IsUnionOfCirclesPossible)
612   {
613     double f,l;
614     TopoDS_Edge FE = TopoDS::Edge(aChain.First());
615     Handle(Geom_Curve) c3d = BRep_Tool::Curve(FE,f,l);
616
617     while(c3d->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
618       Handle(Geom_TrimmedCurve) tc =
619         Handle(Geom_TrimmedCurve)::DownCast(c3d);
620       c3d = tc->BasisCurve();
621     }
622     Handle(Geom_Circle) Cir = Handle(Geom_Circle)::DownCast(c3d);
623
624     TopoDS_Vertex V1 = sae.FirstVertex(FE);
625     TopoDS_Vertex V2 = sae.LastVertex(TopoDS::Edge(aChain.Last()));
626     TopoDS_Edge E;
627     if (V1.IsSame(V2)) {
628       // closed chain
629       BRepAdaptor_Curve adef(FE);
630       Handle(Geom_Circle) Cir1;
631       double FP, LP;
632       if ( FE.Orientation() == TopAbs_FORWARD)
633       {
634         FP = adef.FirstParameter();
635         LP = adef.LastParameter();
636       }
637       else
638       {
639         FP = adef.LastParameter();
640         LP = adef.FirstParameter();
641       }
642       if (Abs(FP) < Precision::PConfusion())
643       {
644         B.MakeEdge (E,Cir, Precision::Confusion());
645         B.Add(E,V1);
646         B.Add(E,V2);
647         E.Orientation(FE.Orientation());
648       }
649       else
650       {
651         GC_MakeCircle MC1 (adef.Value(FP), adef.Value((FP + LP) * 0.5), adef.Value(LP));
652         if (MC1.IsDone())
653           Cir1 = MC1.Value();
654         else
655           return Standard_False;
656         B.MakeEdge (E, Cir1, Precision::Confusion());
657         B.Add(E,V1);
658         B.Add(E,V2);
659       }
660     }
661     else {
662       gp_Pnt PV1 = BRep_Tool::Pnt(V1);
663       gp_Pnt PV2 = BRep_Tool::Pnt(V2);
664       TopoDS_Vertex VM = sae.LastVertex(FE);
665       gp_Pnt PVM = BRep_Tool::Pnt(VM);
666       GC_MakeCircle MC (PV1,PVM,PV2);
667       Handle(Geom_Circle) C = MC.Value();
668       gp_Pnt P0 = C->Location();
669       gp_Dir D1(gp_Vec(P0,PV1));
670       gp_Dir D2(gp_Vec(P0,PV2));
671       Standard_Real fpar = C->XAxis().Direction().Angle(D1);
672       if(fabs(fpar)>Precision::Confusion()) {
673         // check orientation
674         gp_Dir ND =  C->XAxis().Direction().Crossed(D1);
675         if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
676           fpar = -fpar;
677         }
678       }
679       Standard_Real lpar = C->XAxis().Direction().Angle(D2);
680       if(fabs(lpar)>Precision::Confusion()) {
681         // check orientation
682         gp_Dir ND =  C->XAxis().Direction().Crossed(D2);
683         if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
684           lpar = -lpar;
685         }
686       }
687       if (lpar < fpar) lpar += 2*M_PI;
688       Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(C,fpar,lpar);
689       B.MakeEdge (E,tc,Precision::Confusion());
690       B.Add(E,V1);
691       B.Add(E,V2);
692       B.UpdateVertex(V1, fpar, E, 0.);
693       B.UpdateVertex(V2, lpar, E, 0.);
694     }
695     OutEdge = E;
696     return Standard_True;
697   }
698   if (aChain.Length() > 1 && ConcatBSplines) {
699     // second step: union edges with various curves
700     // skl for bug 0020052 from Mantis: perform such unions
701     // only if curves are bspline or bezier
702
703     TopoDS_Vertex VF = sae.FirstVertex(TopoDS::Edge(aChain.First()));
704     TopoDS_Vertex VL = sae.LastVertex(TopoDS::Edge(aChain.Last()));
705     Standard_Boolean NeedUnion = Standard_True;
706     for(j=1; j<=aChain.Length(); j++) {
707       TopoDS_Edge edge = TopoDS::Edge(aChain.Value(j));
708       TopLoc_Location Loc;
709       Handle(Geom_Curve) c3d = BRep_Tool::Curve(edge,Loc,fp1,lp1);
710       if(c3d.IsNull()) continue;
711       while(c3d->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
712         Handle(Geom_TrimmedCurve) tc =
713           Handle(Geom_TrimmedCurve)::DownCast(c3d);
714         c3d = tc->BasisCurve();
715       }
716       if( ( c3d->IsKind(STANDARD_TYPE(Geom_BSplineCurve)) ||
717             c3d->IsKind(STANDARD_TYPE(Geom_BezierCurve)) ) ) continue;
718       NeedUnion = Standard_False;
719       break;
720     }
721     if(NeedUnion) {
722 #ifdef OCCT_DEBUG
723       cout<<"can not make analitical union => make approximation"<<endl;
724 #endif
725       TopoDS_Edge E = GlueEdgesWithPCurves(aChain, VF, VL);
726       OutEdge = E;
727       return Standard_True;
728     }
729     else {
730 #ifdef OCCT_DEBUG
731       cout<<"can not make approximation for such types of curves"<<endl;
732 #endif
733       return Standard_False;
734     }
735   }
736   return Standard_False;
737 }
738
739 //=======================================================================
740 //function : IsMergingPossible
741 //purpose  : Checks if merging of two edges is possible
742 //=======================================================================
743
744 static Standard_Boolean IsMergingPossible(const TopoDS_Edge& edge1, const TopoDS_Edge& edge2, 
745                                           double Tol, const TopTools_MapOfShape& DegEdgeVrt)
746 {
747   TopoDS_Vertex CV = TopExp::LastVertex(edge1, Standard_True);
748   if (CV.IsNull() || DegEdgeVrt.Contains(CV))
749     return Standard_False;
750
751   BRepAdaptor_Curve ade1(edge1);
752   BRepAdaptor_Curve ade2(edge2);
753
754   GeomAbs_CurveType t1 = ade1.GetType();
755   GeomAbs_CurveType t2 = ade2.GetType();
756
757   if( t1 == GeomAbs_Circle && t2 == GeomAbs_Circle)
758   {
759     if (ade1.Circle().Location().Distance(ade2.Circle().Location()) > Precision::Confusion())
760       return Standard_False;
761   }
762
763   if( ( (t1 != GeomAbs_BezierCurve && t1 != GeomAbs_BSplineCurve) ||
764       (t2 != GeomAbs_BezierCurve && t2 != GeomAbs_BSplineCurve)) && t1 != t2)
765     return Standard_False;
766
767   gp_Vec Diff1, Diff2;
768   gp_Pnt P1, P2;
769   if (edge1.Orientation() == TopAbs_FORWARD)
770     ade1.D1(ade1.LastParameter(), P1, Diff1);
771   else
772   {
773     ade1.D1(ade1.FirstParameter(), P1, Diff1);
774     Diff1 = -Diff1;
775   }
776
777   if (edge2.Orientation() == TopAbs_FORWARD)
778     ade2.D1(ade2.FirstParameter(), P2, Diff2);
779   else
780   {
781     ade2.D1(ade2.LastParameter(), P2, Diff2);
782     Diff2 = -Diff2;
783   }
784
785   if (Diff1.Angle(Diff2) > Tol)
786     return Standard_False;
787
788   return Standard_True;
789 }
790
791 //=======================================================================
792 //function : GenerateSubSeq
793 //purpose  : Generates sub-sequences of edges from sequence of edges
794 //Edges from each subsequences can be merged into the one edge  
795 //=======================================================================
796
797 static void GenerateSubSeq (const TopTools_SequenceOfShape& anInpEdgeSeq,
798                             NCollection_Sequence<SubSequenceOfEdges>& SeqOfSubSeqOfEdges,
799                             Standard_Boolean IsClosed, double Tol, const TopTools_MapOfShape& DegEdgeVrt )
800 {
801   Standard_Boolean isOk = Standard_False;
802   TopoDS_Edge edge1, edge2;
803
804   SubSequenceOfEdges SubSeq;
805   SubSeq.SeqsEdges.Append(TopoDS::Edge(anInpEdgeSeq(1)));
806   SeqOfSubSeqOfEdges.Append(SubSeq);
807
808   for (int i = 1; i < anInpEdgeSeq.Length(); i++)
809   {
810     edge1 = TopoDS::Edge(anInpEdgeSeq(i));
811     edge2 = TopoDS::Edge(anInpEdgeSeq(i+1));
812     isOk = IsMergingPossible(edge1, edge2, Tol, DegEdgeVrt);
813     if (!isOk)
814     {
815       SubSequenceOfEdges aSubSeq;
816       aSubSeq.SeqsEdges.Append(edge2);
817       SeqOfSubSeqOfEdges.Append(aSubSeq);
818     }
819     else
820       SeqOfSubSeqOfEdges.ChangeLast().SeqsEdges.Append(edge2);
821   }
822   /// check first and last chain segments
823   if (IsClosed && SeqOfSubSeqOfEdges.Length() > 1)
824   {
825     edge1 = TopoDS::Edge(anInpEdgeSeq.Last());
826     edge2 = TopoDS::Edge(anInpEdgeSeq.First());
827     if (IsMergingPossible(edge1, edge2, Tol, DegEdgeVrt))
828     {
829       SeqOfSubSeqOfEdges.ChangeLast().SeqsEdges.Append(SeqOfSubSeqOfEdges.ChangeFirst().SeqsEdges);
830       SeqOfSubSeqOfEdges.Remove(1);
831     }
832   }
833 }
834
835
836 //=======================================================================
837 //function : MergeEdges
838 //purpose  : auxilary
839 //=======================================================================
840 static Standard_Boolean MergeEdges(const TopTools_SequenceOfShape& SeqEdges,
841                                    const Standard_Real Tol,
842                                    const Standard_Boolean ConcatBSplines,
843                                    NCollection_Sequence<SubSequenceOfEdges>& SeqOfSubSeqOfEdges,
844                                    const TopTools_MapOfShape& NonMergVrt )
845 {
846   // make chain for union
847   //BRep_Builder B;
848   ShapeAnalysis_Edge sae;
849   TopoDS_Edge FirstE = TopoDS::Edge(SeqEdges.Value(1));
850   TopoDS_Edge LastE = FirstE;
851   TopoDS_Vertex VF = sae.FirstVertex(FirstE);
852   TopoDS_Vertex VL = sae.LastVertex(LastE);
853   TopTools_SequenceOfShape aChain;
854   aChain.Append(FirstE);
855   TColStd_MapOfInteger IndUsedEdges;
856   IndUsedEdges.Add(1);
857   Standard_Integer j;
858   TopTools_MapOfShape VerticesToAvoid;
859   TopTools_SequenceOfShape SeqEdges1;
860   for (j = 1; j <= SeqEdges.Length(); j++)
861   {
862     TopoDS_Edge anEdge = TopoDS::Edge(SeqEdges(j));
863     if (BRep_Tool::Degenerated(anEdge))
864     {
865       TopoDS_Vertex V1, V2;
866       TopExp::Vertices(anEdge, V1, V2);
867       VerticesToAvoid.Add(V1);
868       VerticesToAvoid.Add(V2);
869       continue;
870     }
871     SeqEdges1.Append(anEdge);
872   }
873
874   for(j=2; j<=SeqEdges1.Length(); j++) {
875     for(Standard_Integer k=2; k<=SeqEdges1.Length(); k++) {
876       if(IndUsedEdges.Contains(k)) continue;
877       TopoDS_Edge edge = TopoDS::Edge(SeqEdges1.Value(k));
878       TopoDS_Vertex VF2 = sae.FirstVertex(edge);
879       TopoDS_Vertex VL2 = sae.LastVertex(edge);
880       if(VF2.IsSame(VL)) {
881         aChain.Append(edge);
882         LastE = edge;
883         VL = sae.LastVertex(LastE);
884         IndUsedEdges.Add(k);
885       }
886       else if(VL2.IsSame(VF)) {
887         aChain.Prepend(edge);
888         FirstE = edge;
889         VF = sae.FirstVertex(FirstE);
890         IndUsedEdges.Add(k);
891       }
892     }
893   }
894
895   Standard_Boolean IsClosed = Standard_False;
896   if (VF.IsSame ( VL ))
897     IsClosed = Standard_True;
898
899   VerticesToAvoid.Unite(NonMergVrt);
900   GenerateSubSeq(aChain, SeqOfSubSeqOfEdges, IsClosed, Tol, VerticesToAvoid);
901
902   for (int i = 1; i <= SeqOfSubSeqOfEdges.Length(); i++)
903   {
904     TopoDS_Edge UE;
905     if (SeqOfSubSeqOfEdges(i).SeqsEdges.Length() < 2)
906       continue;
907     if (MergeSubSeq(SeqOfSubSeqOfEdges(i).SeqsEdges, UE, Tol, ConcatBSplines))
908       SeqOfSubSeqOfEdges(i).UnionEdges = UE;
909   }
910   return Standard_True;
911 }
912
913 //=======================================================================
914 //function : MergeSeq
915 //purpose  : Tries to unify the sequence of edges with the set of another edges 
916 //which lies on the same geometry
917 //=======================================================================
918
919 static Standard_Boolean MergeSeq (const TopTools_SequenceOfShape& SeqEdges,
920                                   const Standard_Real Tol,
921                                   const Standard_Boolean ConcatBSplines,
922                                   Handle(ShapeBuild_ReShape)& theContext,
923                                   TopTools_DataMapOfShapeShape& theOldShapes,
924                                   const TopTools_MapOfShape& nonMergVert,
925                                   const TopTools_DataMapOfShapeShape& NewEdges2OldEdges)
926
927   NCollection_Sequence<SubSequenceOfEdges> SeqOfSubsSeqOfEdges;
928   int k = 1;
929   if ( MergeEdges(SeqEdges, Tol, ConcatBSplines, SeqOfSubsSeqOfEdges, nonMergVert) )
930   {
931     for (Standard_Integer i = 1; i <= SeqOfSubsSeqOfEdges.Length(); i++ )
932     {
933       if (SeqOfSubsSeqOfEdges(i).UnionEdges.IsNull())
934         continue;
935       theContext->Replace(SeqOfSubsSeqOfEdges(i).SeqsEdges(1), SeqOfSubsSeqOfEdges(i).UnionEdges);
936       k++;
937       for (Standard_Integer j = 2; j <= SeqOfSubsSeqOfEdges(i).SeqsEdges.Length(); j++)
938       {
939         TopoDS_Shape OldEdge = NewEdges2OldEdges(SeqOfSubsSeqOfEdges(i).SeqsEdges(j));
940         theOldShapes.Bind(OldEdge, SeqOfSubsSeqOfEdges(i).UnionEdges);
941         theContext->Remove(SeqOfSubsSeqOfEdges(i).SeqsEdges(j));
942       }
943     }
944     return Standard_True;
945   }
946   else
947     return Standard_False;
948 }
949
950 //=======================================================================
951 //function : CheckSharedVertices
952 //purpose  : Checks the sequence of edges on the presence of shared vertex 
953 //=======================================================================
954
955 static void CheckSharedVertices(const TopTools_SequenceOfShape& theSeqEdges, 
956                                 const TopTools_IndexedDataMapOfShapeListOfShape& theMapEdgesVertex,
957                                 TopTools_MapOfShape& theShareVertMap)
958 {
959   ShapeAnalysis_Edge sae;
960   TopTools_SequenceOfShape SeqVertexes;
961   TopTools_MapOfShape MapVertexes;
962   for (Standard_Integer k = 1; k <= theSeqEdges.Length(); k++ )
963   {
964     TopoDS_Vertex aV1 = sae.FirstVertex(TopoDS::Edge(theSeqEdges(k)));
965     TopoDS_Vertex aV2 = sae.LastVertex(TopoDS::Edge(theSeqEdges(k)));
966     if (!MapVertexes.Add(aV1))
967       SeqVertexes.Append(aV1);
968     if (!MapVertexes.Add(aV2))
969       SeqVertexes.Append(aV2);
970   }
971
972   for (Standard_Integer k = 1; k <= SeqVertexes.Length()/* && !IsSharedVertexPresent*/; k++ )
973   {
974     const TopTools_ListOfShape& ListEdgesV1 = theMapEdgesVertex.FindFromKey(SeqVertexes(k));
975     TopTools_MapOfShape aMapOfEdges;
976     TopTools_ListIteratorOfListOfShape iter(ListEdgesV1);
977     for (; iter.More(); iter.Next())
978       aMapOfEdges.Add(iter.Value());
979     if (aMapOfEdges.Extent() > 2)
980       theShareVertMap.Add(SeqVertexes(k));
981   }
982   //return theShareVertMap.IsEmpty() ? false : true;
983 }
984
985 //=======================================================================
986 //function : ShapeUpgrade_UnifySameDomain
987 //purpose  : Constructor
988 //=======================================================================
989
990 ShapeUpgrade_UnifySameDomain::ShapeUpgrade_UnifySameDomain()
991 {
992   myUnifyEdges = Standard_True;
993   myUnifyFaces = Standard_True;
994   myConcatBSplines = Standard_False;
995
996   myContext = new ShapeBuild_ReShape;
997 }
998
999 //=======================================================================
1000 //function : ShapeUpgrade_UnifySameDomain
1001 //purpose  : Constructor
1002 //=======================================================================
1003
1004 ShapeUpgrade_UnifySameDomain::ShapeUpgrade_UnifySameDomain(const TopoDS_Shape& aShape,
1005                                                            const Standard_Boolean UnifyEdges,
1006                                                            const Standard_Boolean UnifyFaces,
1007                                                            const Standard_Boolean ConcatBSplines)
1008 {
1009   myInitShape = aShape;
1010   myShape = aShape;
1011   myUnifyEdges = UnifyEdges;
1012   myUnifyFaces = UnifyFaces;
1013   myConcatBSplines = ConcatBSplines;
1014
1015   myContext = new ShapeBuild_ReShape;
1016 }
1017
1018 //=======================================================================
1019 //function : Initialize
1020 //purpose  : 
1021 //=======================================================================
1022
1023 void ShapeUpgrade_UnifySameDomain::Initialize(const TopoDS_Shape& aShape,
1024                                               const Standard_Boolean UnifyEdges,
1025                                               const Standard_Boolean UnifyFaces,
1026                                               const Standard_Boolean ConcatBSplines)
1027 {
1028   myInitShape = aShape;
1029   myShape = aShape;
1030   myUnifyEdges = UnifyEdges;
1031   myUnifyFaces = UnifyFaces;
1032   myConcatBSplines = ConcatBSplines;
1033
1034   myContext->Clear();
1035   myOldShapes.Clear();
1036   //myGenerated.Clear();
1037 }
1038
1039 //=======================================================================
1040 //function : putIntWires
1041 //purpose  : Add internal wires that are classified inside the face as a subshape,
1042 //           and remove them from the sequence
1043 //=======================================================================
1044 static void putIntWires(TopoDS_Shape& theFace, TopTools_SequenceOfShape& theWires)
1045 {
1046   TopoDS_Face& aFace = TopoDS::Face(theFace);
1047   for (Standard_Integer i=1; i <= theWires.Length(); i++)
1048   {
1049     TopoDS_Shape aWire = theWires(i);
1050     gp_Pnt2d aP2d;
1051     Standard_Boolean isP2d = Standard_False;
1052     for (TopoDS_Iterator it(aWire); it.More() && !isP2d; it.Next())
1053     {
1054       const TopoDS_Edge& anEdge = TopoDS::Edge(it.Value());
1055       Standard_Real aFirst, aLast;
1056       Handle(Geom2d_Curve) aC2d = BRep_Tool::CurveOnSurface(anEdge, aFace, aFirst, aLast);
1057       aC2d->D0((aFirst + aLast) * 0.5, aP2d);
1058       isP2d = Standard_True;
1059     }
1060     BRepClass_FaceClassifier aClass(aFace, aP2d, Precision::PConfusion());
1061     if (aClass.State() == TopAbs_IN)
1062     {
1063       BRep_Builder().Add(aFace, aWire);
1064       theWires.Remove(i);
1065       i--;
1066     }
1067   }
1068 }
1069
1070 //=======================================================================
1071 //function : UnifyFaces
1072 //purpose  : 
1073 //=======================================================================
1074
1075 void ShapeUpgrade_UnifySameDomain::UnifyFaces()
1076 {
1077   // creating map of edge faces
1078   TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
1079   TopExp::MapShapesAndAncestors(myShape, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
1080   // processing each shell
1081   TopExp_Explorer exps;
1082   for (exps.Init(myShape, TopAbs_SHELL); exps.More(); exps.Next()) {
1083     TopoDS_Shell aShell = TopoDS::Shell(exps.Current());
1084
1085     // map of processed shapes
1086     TopTools_MapOfShape aProcessed;
1087
1088     Standard_Integer NbModif = 0;
1089     Standard_Boolean hasFailed = Standard_False;
1090     Standard_Real tol = Precision::Confusion();
1091
1092     // count faces
1093     Standard_Integer nbf = 0;
1094     TopExp_Explorer exp;
1095     TopTools_MapOfShape mapF;
1096     for (exp.Init(aShell, TopAbs_FACE); exp.More(); exp.Next()) {
1097       if (mapF.Add(exp.Current()))
1098         nbf++;
1099     }
1100
1101     // processing each face
1102     mapF.Clear();
1103     for (exp.Init(aShell, TopAbs_FACE); exp.More(); exp.Next()) {
1104       TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
1105
1106       if (aProcessed.Contains(aFace))
1107         continue;
1108
1109       Standard_Integer dummy;
1110       TopTools_SequenceOfShape edges;
1111       AddOrdinaryEdges(edges,aFace,dummy);
1112
1113       TopTools_SequenceOfShape faces;
1114       faces.Append(aFace);
1115
1116       //surface and location to construct result
1117       TopLoc_Location aBaseLocation;
1118       Handle(Geom_Surface) aBaseSurface = BRep_Tool::Surface(aFace,aBaseLocation);
1119       aBaseSurface = ClearRts(aBaseSurface);
1120
1121       // find adjacent faces to union
1122       Standard_Integer i;
1123       for (i = 1; i <= edges.Length(); i++) {
1124         TopoDS_Edge edge = TopoDS::Edge(edges(i));
1125         if (BRep_Tool::Degenerated(edge))
1126           continue;
1127
1128         const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
1129         TopTools_ListIteratorOfListOfShape anIter(aList);
1130         for (; anIter.More(); anIter.Next()) {
1131           TopoDS_Face anCheckedFace = TopoDS::Face(anIter.Value().Oriented(TopAbs_FORWARD));
1132           if (anCheckedFace.IsSame(aFace))
1133             continue;
1134
1135           if (aProcessed.Contains(anCheckedFace))
1136             continue;
1137
1138           if (IsSameDomain(aFace,anCheckedFace)) {
1139
1140             if (aList.Extent() != 2) {
1141               // non mainfold case is not processed
1142               continue;
1143             }
1144
1145             // replacing pcurves
1146             TopoDS_Face aMockUpFace;
1147             BRep_Builder B;
1148             B.MakeFace(aMockUpFace,aBaseSurface,aBaseLocation,0.);
1149             MovePCurves(aMockUpFace,anCheckedFace);
1150
1151             if (AddOrdinaryEdges(edges,aMockUpFace,dummy)) {
1152               // sequence edges is modified
1153               i = dummy;
1154             }
1155
1156             faces.Append(anCheckedFace);
1157             aProcessed.Add(anCheckedFace);
1158             break;
1159           }
1160         }
1161       }
1162
1163       // all faces collected in the sequence. Perform union of faces
1164       if (faces.Length() > 1) {
1165         NbModif++;
1166         TopoDS_Face aResult;
1167         BRep_Builder B;
1168         B.MakeFace(aResult,aBaseSurface,aBaseLocation,0);
1169         Standard_Integer nbWires = 0;
1170
1171         TopoDS_Face tmpF = TopoDS::Face(myContext->Apply(faces(1).Oriented(TopAbs_FORWARD)));
1172         // connecting wires
1173         while (edges.Length()>0) {
1174
1175           Standard_Boolean isEdge3d = Standard_False;
1176           nbWires++;
1177           TopTools_MapOfShape aVertices;
1178           TopoDS_Wire aWire;
1179           B.MakeWire(aWire);
1180
1181           TopoDS_Edge anEdge = TopoDS::Edge(edges(1));
1182           edges.Remove(1);
1183           // collect internal edges in separate wires
1184           Standard_Boolean isInternal = (anEdge.Orientation() == TopAbs_INTERNAL);
1185
1186           isEdge3d |= !BRep_Tool::Degenerated(anEdge);
1187           B.Add(aWire,anEdge);
1188           TopoDS_Vertex V1,V2;
1189           TopExp::Vertices(anEdge,V1,V2);
1190           aVertices.Add(V1);
1191           aVertices.Add(V2);
1192
1193           Standard_Boolean isNewFound = Standard_False;
1194           do {
1195             isNewFound = Standard_False;
1196             for(Standard_Integer j = 1; j <= edges.Length(); j++) {
1197               anEdge = TopoDS::Edge(edges(j));
1198               // check if the current edge orientation corresponds to the first one
1199               Standard_Boolean isCurrInternal = (anEdge.Orientation() == TopAbs_INTERNAL);
1200               if (isCurrInternal != isInternal)
1201                 continue;
1202               TopExp::Vertices(anEdge,V1,V2);
1203               if(aVertices.Contains(V1) || aVertices.Contains(V2)) {
1204                 isEdge3d |= !BRep_Tool::Degenerated(anEdge);
1205                 aVertices.Add(V1);
1206                 aVertices.Add(V2);
1207                 B.Add(aWire,anEdge);
1208                 edges.Remove(j);
1209                 j--;
1210                 isNewFound = Standard_True;
1211               }
1212             }
1213           } while (isNewFound);
1214
1215           // sorting any type of edges
1216           aWire.Closed (BRep_Tool::IsClosed (aWire));
1217           aWire = TopoDS::Wire(myContext->Apply(aWire));
1218
1219           Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(aWire,tmpF,Precision::Confusion());
1220           sfw->FixReorder();
1221           Standard_Boolean isDegRemoved = Standard_False;
1222           if(!sfw->StatusReorder ( ShapeExtend_FAIL )) {
1223             // clear degenerated edges if at least one with 3d curve exist
1224             if(isEdge3d) {
1225               Handle(ShapeExtend_WireData) sewd = sfw->WireData();
1226               for(Standard_Integer j = 1; j<=sewd->NbEdges();j++) {
1227                 TopoDS_Edge E = sewd->Edge(j);
1228                 if(BRep_Tool::Degenerated(E)) {
1229                   sewd->Remove(j);
1230                   isDegRemoved = Standard_True;
1231                   j--;
1232                 }
1233               }
1234             }
1235             sfw->FixShifted();
1236             if(isDegRemoved)
1237               sfw->FixDegenerated();
1238           }
1239           TopoDS_Wire aWireFixed = sfw->Wire();
1240           //aContext->Replace(aWire,aWireFixed);
1241           myContext->Replace(aWire,aWireFixed);
1242           //for history
1243           /*
1244           if (!myOldNewMap.IsBound(aWire))
1245           {
1246             TopTools_ListOfShape EmptyList;
1247             myOldNewMap.Bind(aWire, EmptyList);
1248           }
1249           myOldNewMap(aWire).Clear();
1250           myOldNewMap(aWire).Append(aWireFixed);
1251           */
1252           /////////////
1253           
1254           // add resulting wire
1255           if(isEdge3d) {
1256             B.Add(aResult,aWireFixed);
1257           }
1258           else  {
1259             // sorting edges
1260             Handle(ShapeExtend_WireData) sbwd = sfw->WireData();
1261             Standard_Integer nbEdges = sbwd->NbEdges();
1262             // sort degenerated edges and create one edge instead of several ones
1263             ShapeAnalysis_WireOrder sawo(Standard_False, 0);
1264             ShapeAnalysis_Edge sae;
1265             Standard_Integer aLastEdge = nbEdges;
1266             for(Standard_Integer j = 1; j <= nbEdges; j++) {
1267               Standard_Real f,l;
1268               //smh protection on NULL pcurve
1269               Handle(Geom2d_Curve) c2d;
1270               if(!sae.PCurve(sbwd->Edge(j),tmpF,c2d,f,l)) {
1271                 aLastEdge--;
1272                 continue;
1273               }
1274               sawo.Add(c2d->Value(f).XY(),c2d->Value(l).XY());
1275             }
1276             sawo.Perform();
1277
1278             // constructind one degenerative edge
1279             gp_XY aStart, anEnd, tmp;
1280             Standard_Integer nbFirst = sawo.Ordered(1);
1281             TopoDS_Edge anOrigE = TopoDS::Edge(sbwd->Edge(nbFirst).Oriented(TopAbs_FORWARD));
1282             ShapeBuild_Edge sbe;
1283             TopoDS_Vertex aDummyV;
1284             TopoDS_Edge E = sbe.CopyReplaceVertices(anOrigE,aDummyV,aDummyV);
1285             sawo.XY(nbFirst,aStart,tmp);
1286             sawo.XY(sawo.Ordered(aLastEdge),tmp,anEnd);
1287
1288             gp_XY aVec = anEnd-aStart;
1289             Handle(Geom2d_Line) aLine = new Geom2d_Line(aStart,gp_Dir2d(anEnd-aStart));
1290
1291             B.UpdateEdge(E,aLine,tmpF,0.);
1292             B.Range(E,tmpF,0.,aVec.Modulus());
1293             Handle(Geom_Curve) C3d;
1294             B.UpdateEdge(E,C3d,0.);
1295             B.Degenerated(E,Standard_True);
1296             TopoDS_Wire aW;
1297             B.MakeWire(aW);
1298             B.Add(aW,E);
1299             aW.Closed (Standard_True);
1300             B.Add(aResult,aW);
1301           }
1302         }
1303
1304         // perform substitution of face
1305         //aContext->Replace(aContext->Apply(aFace),aResult);
1306         myContext->Replace(myContext->Apply(aFace),aResult);
1307         //for history
1308         /*
1309         if (!myOldNewMap.IsBound(aFace))
1310         {
1311           TopTools_ListOfShape EmptyList;
1312           myOldNewMap.Bind(aFace, EmptyList);
1313         }
1314         myOldNewMap(aFace).Clear();
1315         myOldNewMap(aFace).Append(aResult);
1316         */
1317         /////////////
1318
1319         ShapeFix_Face sff (aResult);
1320         //Intializing by tolerances
1321         sff.SetPrecision(Precision::Confusion());
1322         sff.SetMinTolerance(tol);
1323         sff.SetMaxTolerance(1.);
1324         //Setting modes
1325         sff.FixOrientationMode() = 0;
1326         //sff.FixWireMode() = 0;
1327         //sff.SetContext(aContext);
1328         sff.SetContext(myContext);
1329         // Applying the fixes
1330         sff.Perform();
1331         if(sff.Status(ShapeExtend_FAIL))
1332         hasFailed = Standard_True;
1333
1334         // breaking down to several faces
1335         //TopoDS_Shape theResult = aContext->Apply(aResult);
1336         TopoDS_Shape theResult = myContext->Apply(aResult);
1337         for (TopExp_Explorer aFaceExp (theResult,TopAbs_FACE); aFaceExp.More(); aFaceExp.Next()) {
1338           TopoDS_Face aCurrent = TopoDS::Face(aFaceExp.Current().Oriented(TopAbs_FORWARD));
1339           Handle(TColGeom_HArray2OfSurface) grid = new TColGeom_HArray2OfSurface ( 1, 1, 1, 1 );
1340           grid->SetValue ( 1, 1, aBaseSurface );
1341           Handle(ShapeExtend_CompositeSurface) G = new ShapeExtend_CompositeSurface ( grid );
1342           ShapeFix_ComposeShell CompShell;
1343           CompShell.Init ( G, aBaseLocation, aCurrent, ::Precision::Confusion() );//myPrecision
1344           //CompShell.SetContext( aContext );
1345           CompShell.SetContext( myContext );
1346
1347           TopTools_SequenceOfShape parts, anIntWires;
1348           ShapeFix_SequenceOfWireSegment wires;
1349           for(TopExp_Explorer W_Exp(aCurrent,TopAbs_WIRE);W_Exp.More();W_Exp.Next()) {
1350             const TopoDS_Wire& aWire = TopoDS::Wire(W_Exp.Current());
1351             // check if the wire is ordinary (contains non-internal edges)
1352             Standard_Boolean isInternal = Standard_True;
1353             for (TopoDS_Iterator it(aWire); it.More() && isInternal; it.Next())
1354               isInternal = (it.Value().Orientation() == TopAbs_INTERNAL);
1355             if (isInternal)
1356             {
1357               // place internal wire separately
1358               anIntWires.Append(aWire);
1359             }
1360             else
1361             {
1362             Handle(ShapeExtend_WireData) sbwd =
1363                 new ShapeExtend_WireData (aWire);
1364             ShapeFix_WireSegment seg ( sbwd, TopAbs_REVERSED );
1365             wires.Append(seg);
1366           }
1367           }
1368
1369           CompShell.DispatchWires ( parts,wires );
1370           for (Standard_Integer j=1; j <= parts.Length(); j++ ) {
1371             ShapeFix_Face aFixOrient(TopoDS::Face(parts(j)));
1372             //aFixOrient.SetContext(aContext);
1373             aFixOrient.SetContext(myContext);
1374             aFixOrient.FixOrientation();
1375             // put internal wires to faces
1376             putIntWires(parts(j), anIntWires);
1377           }
1378
1379           TopoDS_Shape CompRes;
1380           if ( parts.Length() !=1 ) {
1381             TopoDS_Shell S;
1382             B.MakeShell ( S );
1383             for ( i=1; i <= parts.Length(); i++ )
1384               B.Add ( S, parts(i) );
1385             S.Closed (BRep_Tool::IsClosed (S));
1386             CompRes = S;
1387           }
1388           else CompRes = parts(1);
1389
1390           //aContext->Replace(aCurrent,CompRes);
1391           myContext->Replace(aCurrent,CompRes);
1392           //for history
1393           /*
1394           if (!myOldNewMap.IsBound(aCurrent))
1395           {
1396             TopTools_ListOfShape EmptyList;
1397             myOldNewMap.Bind(aCurrent, EmptyList);
1398           }
1399           myOldNewMap(aCurrent).Clear();
1400           myOldNewMap(aCurrent).Append(CompRes);
1401           */
1402           /////////////
1403         }
1404
1405         // remove the remaining faces
1406         for(i = 2; i <= faces.Length(); i++)
1407         { 
1408           myOldShapes.Bind(faces(i), theResult);
1409           myContext->Remove(faces(i));
1410         }
1411       }
1412     } // end processing each face
1413
1414     //TopoDS_Shape aResult = Shape;
1415     if (NbModif > 0 && !hasFailed) {
1416       //TopoDS_Shape aResult = aContext->Apply(aShell);
1417       TopoDS_Shape aResult = myContext->Apply(aShell);
1418
1419       ShapeFix_Edge sfe;
1420       if (!myContext.IsNull()) sfe.SetContext(myContext);
1421       for (exp.Init(aResult,TopAbs_EDGE); exp.More(); exp.Next()) {
1422         TopoDS_Edge E = TopoDS::Edge(exp.Current());
1423         sfe.FixVertexTolerance (E);
1424         // ptv add fix same parameter
1425         sfe.FixSameParameter(E, Precision::Confusion());
1426       }
1427
1428       myContext->Replace(aShell, aResult);
1429       //for history
1430       /*
1431       if (!myOldNewMap.IsBound(aShell))
1432       {
1433         TopTools_ListOfShape EmptyList;
1434         myOldNewMap.Bind(aShell, EmptyList);
1435       }
1436       myOldNewMap(aShell).Clear();
1437       myOldNewMap(aShell).Append(aResult);
1438       */
1439       /////////////
1440     }
1441     //else
1442     {
1443       for (exp.Init(aShell, TopAbs_FACE); exp.More(); exp.Next()) {
1444         TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
1445         Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire;
1446         sfw->SetContext(myContext);
1447         sfw->SetPrecision(Precision::Confusion());
1448         sfw->SetMinTolerance(Precision::Confusion());
1449         sfw->SetMaxTolerance(1.);
1450         sfw->SetFace(aFace);
1451         for (TopoDS_Iterator iter (aFace,Standard_False); iter.More(); iter.Next()) {
1452           TopoDS_Wire wire = TopoDS::Wire(iter.Value());
1453           sfw->Load(wire);
1454           sfw->FixReorder();
1455           sfw->FixShifted();
1456         }
1457       }
1458     }
1459   } // end processing each shell
1460
1461   myShape = myContext->Apply(myShape);
1462 }
1463
1464 //=======================================================================
1465 //function : UnifyEdges
1466 //purpose  : 
1467 //=======================================================================
1468 void ShapeUpgrade_UnifySameDomain::UnifyEdges()
1469 {
1470   Standard_Real Tol = Precision::Confusion();
1471   
1472   //Handle(ShapeBuild_ReShape) myContext = new ShapeBuild_ReShape;
1473   Standard_Real myTolerance = Precision::Confusion();
1474   TopoDS_Shape aResult = myContext->Apply(myShape);
1475
1476   TopTools_IndexedMapOfShape ChangedFaces;
1477
1478   // creating map of edge faces
1479   TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
1480   TopExp::MapShapesAndAncestors(myShape, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
1481   
1482   // creating map of vertex edges
1483   TopTools_IndexedDataMapOfShapeListOfShape aMapEdgesVertex;
1484   TopExp::MapShapesAndAncestors(myShape, TopAbs_VERTEX, TopAbs_EDGE, aMapEdgesVertex);
1485
1486   //Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
1487   TopoDS_Shape aRes = myShape;
1488   //aRes = aContext->Apply(aSolid);
1489   aRes = myContext->Apply(myShape);
1490   
1491   TopTools_MapOfShape SharedVert;
1492
1493   
1494   TopTools_IndexedMapOfShape anOldEdges;
1495   TopExp::MapShapes(myInitShape, TopAbs_EDGE, anOldEdges);
1496
1497   TopTools_DataMapOfShapeShape NewEdges2OldEdges;
1498   for (int i = 1; i <= anOldEdges.Extent(); i++)
1499   {
1500     TopoDS_Shape NewEdge = myContext->Apply(anOldEdges(i));
1501     if (!NewEdge.IsNull())
1502       NewEdges2OldEdges.Bind(NewEdge, anOldEdges(i));
1503   }
1504
1505   TopExp_Explorer exp;
1506   // processing separate wires
1507   for (exp.Init(aRes, TopAbs_WIRE, TopAbs_FACE); exp.More(); exp.Next()) 
1508   {
1509     TopTools_SequenceOfShape SeqEdges;
1510     TopExp_Explorer expE(exp.Current(), TopAbs_EDGE);
1511     for (; expE.More(); expE.Next())
1512       SeqEdges.Append(expE.Current());
1513     SharedVert.Clear();
1514     CheckSharedVertices(SeqEdges, aMapEdgesVertex, SharedVert); 
1515     MergeSeq(SeqEdges, Tol, myConcatBSplines, myContext, myOldShapes, SharedVert, NewEdges2OldEdges);
1516   }
1517
1518   TopTools_DataMapOfShapeShape oldFaces2NewFaces;
1519   for (exp.Init(myShape, TopAbs_FACE); exp.More(); exp.Next()) 
1520   {
1521     const TopoDS_Face& f = TopoDS::Face(exp.Current());
1522     TopoDS_Face NewF = TopoDS::Face(myContext->Apply(f));
1523     if (!NewF.IsNull())
1524       oldFaces2NewFaces.Bind(f, NewF);
1525   }
1526
1527   // processing each face
1528   for (exp.Init(aRes, TopAbs_FACE); exp.More(); exp.Next()) {
1529     //TopoDS_Face aFace = TopoDS::Face(aContext->Apply(exp.Current().Oriented(TopAbs_FORWARD)));
1530     TopoDS_Face aFace = TopoDS::Face(myContext->Apply(exp.Current().Oriented(TopAbs_FORWARD)));
1531     TopTools_IndexedDataMapOfShapeListOfShape aMapFacesEdges;
1532     TopTools_SequenceOfShape aNonSharedEdges;
1533     for (TopExp_Explorer expe(aFace,TopAbs_EDGE); expe.More(); expe.Next()) {
1534       TopoDS_Edge edge = TopoDS::Edge(expe.Current());
1535       if (!aMapEdgeFaces.Contains(edge)) continue;
1536       const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
1537       TopTools_ListIteratorOfListOfShape anIter(aList);
1538       Standard_Integer NbFacesPerEdge = aList.Extent();
1539       for ( ; anIter.More(); anIter.Next()) {
1540         TopoDS_Face face = TopoDS::Face(anIter.Value());
1541         TopoDS_Face face1 = TopoDS::Face(oldFaces2NewFaces(anIter.Value()));
1542         if (face1.IsSame(aFace) && NbFacesPerEdge != 1)
1543           continue;
1544         if (NbFacesPerEdge == 1)
1545           //store non-shared edges separately 
1546           aNonSharedEdges.Append(edge);
1547         else 
1548         {
1549           if (aMapFacesEdges.Contains(face))
1550             aMapFacesEdges.ChangeFromKey(face).Append(edge);
1551           else 
1552           {
1553             TopTools_ListOfShape ListEdges;
1554             ListEdges.Append(edge);
1555             aMapFacesEdges.Add(face,ListEdges);
1556           }
1557         }
1558       }
1559     }
1560       
1561     for (Standard_Integer i=1; i<=aMapFacesEdges.Extent(); i++)
1562     {
1563       const TopTools_ListOfShape& ListEdges = aMapFacesEdges.FindFromIndex(i);
1564       TopTools_SequenceOfShape SeqEdges;
1565       TopTools_ListIteratorOfListOfShape anIter(ListEdges);
1566       for ( ; anIter.More(); anIter.Next())
1567         SeqEdges.Append(anIter.Value());
1568       if (SeqEdges.Length()==1) 
1569         continue;  
1570
1571       SharedVert.Clear();
1572       CheckSharedVertices(SeqEdges, aMapEdgesVertex, SharedVert);
1573       //if (!SharedVert.IsEmpty()) 
1574       //  continue;
1575       if ( MergeSeq(SeqEdges,Tol,myConcatBSplines, myContext, myOldShapes, SharedVert, NewEdges2OldEdges) )
1576       {
1577         //for history
1578         /*
1579         for (j = 1; j <= SeqEdges.Length(); j++)
1580         {
1581           if (!myOldNewMap.IsBound(SeqEdges(j)))
1582           {
1583             TopTools_ListOfShape EmptyList;
1584             myOldNewMap.Bind(SeqEdges(j), EmptyList);
1585           }
1586           myOldNewMap(SeqEdges(j)).Clear();
1587           myOldNewMap(SeqEdges(j)).Append(E);
1588         }
1589         */
1590         /////////////
1591         
1592         TopoDS_Face tmpF = TopoDS::Face(exp.Current());
1593         if ( !ChangedFaces.Contains(tmpF) )
1594           ChangedFaces.Add(tmpF);
1595         tmpF = TopoDS::Face(aMapFacesEdges.FindKey(i));
1596         if ( !ChangedFaces.Contains(tmpF) )
1597           ChangedFaces.Add(tmpF);
1598       }
1599     }
1600     
1601     if ( aNonSharedEdges.Length() > 1 )
1602     {
1603       SharedVert.Clear();
1604       CheckSharedVertices(aNonSharedEdges, aMapEdgesVertex, SharedVert); 
1605       if ( MergeSeq(aNonSharedEdges, Tol, myConcatBSplines, myContext, myOldShapes, SharedVert, NewEdges2OldEdges) )
1606       {
1607         TopoDS_Face tmpF = TopoDS::Face(exp.Current());
1608         if ( !ChangedFaces.Contains(tmpF) )
1609           ChangedFaces.Add(tmpF);
1610       }
1611     }
1612
1613   } // end processing each face
1614
1615   // fix changed faces and replace them in the local context
1616   for (Standard_Integer i=1; i<=ChangedFaces.Extent(); i++) {
1617     //TopoDS_Face aFace = TopoDS::Face(aContext->Apply(ChangedFaces.FindKey(i)));
1618     TopoDS_Face aFace = TopoDS::Face(myContext->Apply(ChangedFaces.FindKey(i)));
1619     if (aFace.IsNull())
1620       continue;
1621     Handle(ShapeFix_Face) sff = new ShapeFix_Face(aFace);
1622     sff->SetContext(myContext);
1623     sff->SetPrecision(myTolerance);
1624     sff->SetMinTolerance(myTolerance);
1625     sff->SetMaxTolerance(Max(1.,myTolerance*1000.));
1626     sff->Perform();
1627     TopoDS_Shape aNewFace = sff->Face();
1628     //aContext->Replace(aFace,aNewFace);
1629     myContext->Replace(aFace,aNewFace);
1630     //for history
1631     /*
1632     if (!myOldNewMap.IsBound(aFace))
1633     {
1634       TopTools_ListOfShape EmptyList;
1635       myOldNewMap.Bind(aFace, EmptyList);
1636     }
1637     myOldNewMap(aFace).Clear();
1638     myOldNewMap(aFace).Append(aNewFace);
1639     */
1640     /////////////
1641   }
1642
1643   if (ChangedFaces.Extent() > 0) {
1644     // fix changed shell and replace it in the local context
1645     //TopoDS_Shape aRes1 = aContext->Apply(aRes);
1646     TopoDS_Shape aRes1 = myContext->Apply(aRes);
1647     TopExp_Explorer expsh;
1648     for (expsh.Init(aRes1, TopAbs_SHELL); expsh.More(); expsh.Next()) {
1649       TopoDS_Shell aShell = TopoDS::Shell(expsh.Current());
1650       Handle(ShapeFix_Shell) sfsh = new ShapeFix_Shell;
1651       sfsh->FixFaceOrientation(aShell);
1652       TopoDS_Shape aNewShell = sfsh->Shell();
1653       //aContext->Replace(aShell,aNewShell);
1654       myContext->Replace(aShell,aNewShell);
1655       //for history
1656       /*
1657       if (!myOldNewMap.IsBound(aShell))
1658       {
1659         TopTools_ListOfShape EmptyList;
1660         myOldNewMap.Bind(aShell, EmptyList);
1661       }
1662       myOldNewMap(aShell).Clear();
1663       myOldNewMap(aShell).Append(aNewShell);
1664       */
1665       /////////////
1666     }
1667     //TopoDS_Shape aRes2 = aContext->Apply(aRes1);
1668     TopoDS_Shape aRes2 = myContext->Apply(aRes1);
1669     myContext->Replace(myShape,aRes2);
1670     //for history
1671     /*
1672     if (!myOldNewMap.IsBound(aSolid))
1673     {
1674       TopTools_ListOfShape EmptyList;
1675       myOldNewMap.Bind(aSolid, EmptyList);
1676     }
1677     myOldNewMap(aSolid).Clear();
1678     myOldNewMap(aSolid).Append(aRes2);
1679     */
1680     /////////////
1681   }
1682
1683   myShape = myContext->Apply(myShape);
1684 }
1685
1686 //=======================================================================
1687 //function : UnifyFacesAndEdges
1688 //purpose  : 
1689 //=======================================================================
1690
1691 void ShapeUpgrade_UnifySameDomain::UnifyFacesAndEdges()
1692 {
1693   UnifyFaces();
1694   
1695   /*
1696   ShapeUpgrade_RemoveLocations RemLoc;
1697   RemLoc.Remove(myShape);
1698   myShape = RemLoc.GetResult();
1699   */
1700
1701   UnifyEdges();
1702 }
1703
1704 //=======================================================================
1705 //function : Build
1706 //purpose  : builds the resulting shape
1707 //======================================================================
1708 void ShapeUpgrade_UnifySameDomain::Build() 
1709 {
1710   if (myUnifyFaces && myUnifyEdges)
1711     UnifyFacesAndEdges();
1712
1713   else if (myUnifyEdges)
1714     UnifyEdges();
1715   else if (myUnifyFaces)
1716     UnifyFaces();
1717
1718   //Done();
1719 }
1720
1721 //=======================================================================
1722 //function : Shape
1723 //purpose  : give the resulting shape
1724 //=======================================================================
1725 const TopoDS_Shape& ShapeUpgrade_UnifySameDomain::Shape() const
1726 {
1727   return myShape;
1728 }
1729
1730 //=======================================================================
1731 //function : Generated
1732 //purpose  : returns the new shape from the old one
1733 //=======================================================================
1734 TopoDS_Shape ShapeUpgrade_UnifySameDomain::Generated(const TopoDS_Shape& aShape) const
1735 {
1736   TopoDS_Shape aNewShape = myContext->Apply(aShape);
1737
1738   if (aNewShape.IsNull())
1739     aNewShape = myContext->Apply(myOldShapes(aShape));
1740   
1741   return aNewShape;
1742 }