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