0023367: New functionality restoring the middle path of pipe-like shape
[occt.git] / src / ShapeUpgrade / ShapeUpgrade_UnifySameDomain.cxx
1 // File:      ShapeUpgrade_UnifySameDomain.cxx
2 // Created:   09.06.12 14:35:07
3 // Author:    jgv@ROLEX
4 // Copyright: Open CASCADE 2012
5
6 #include <ShapeUpgrade_UnifySameDomain.ixx>
7 #include <ShapeUpgrade_UnifySameDomain.hxx>
8 #include <TopTools_SequenceOfShape.hxx>
9 #include <TopTools_IndexedMapOfShape.hxx>
10 #include <TopExp_Explorer.hxx>
11 #include <Geom_Surface.hxx>
12 #include <Geom_Line.hxx>
13 #include <gp_Dir.hxx>
14 #include <Geom_CylindricalSurface.hxx>
15 #include <gp_Cylinder.hxx>
16 #include <Geom_SurfaceOfRevolution.hxx>
17 #include <Geom_SurfaceOfLinearExtrusion.hxx>
18 #include <gp_Lin.hxx>
19 #include <Geom_Circle.hxx>
20 #include <Geom_RectangularTrimmedSurface.hxx>
21 #include <TopoDS_Face.hxx>
22 #include <BRep_Tool.hxx>
23 #include <GeomAdaptor_HSurface.hxx>
24 #include <BRepTopAdaptor_TopolTool.hxx>
25 #include <IntPatch_ImpImpIntersection.hxx>
26 #include <GeomLib_IsPlanarSurface.hxx>
27 #include <BRep_Builder.hxx>
28 #include <ShapeFix_Wire.hxx>
29 #include <TopoDS.hxx>
30 #include <ShapeAnalysis_Edge.hxx>
31 #include <TopoDS_Edge.hxx>
32 #include <TColGeom_SequenceOfSurface.hxx>
33 #include <BRep_ListIteratorOfListOfCurveRepresentation.hxx>
34 #include <BRep_TEdge.hxx>
35 #include <BRep_CurveRepresentation.hxx>
36 #include <TColGeom_Array1OfBSplineCurve.hxx>
37 #include <TColGeom_HArray1OfBSplineCurve.hxx>
38 #include <TColGeom2d_Array1OfBSplineCurve.hxx>
39 #include <TColGeom2d_HArray1OfBSplineCurve.hxx>
40 #include <TColStd_Array1OfReal.hxx>
41 #include <TopExp.hxx>
42 #include <Geom_TrimmedCurve.hxx>
43 #include <Geom2d_TrimmedCurve.hxx>
44 #include <GeomConvert.hxx>
45 #include <Geom2dConvert.hxx>
46 #include <GeomConvert_CompCurveToBSplineCurve.hxx>
47 #include <Geom2dConvert_CompCurveToBSplineCurve.hxx>
48 #include <TColGeom2d_SequenceOfBoundedCurve.hxx>
49 #include <BRepLib_MakeEdge.hxx>
50 #include <TColStd_MapOfInteger.hxx>
51 #include <BRepLib.hxx>
52 #include <GC_MakeCircle.hxx>
53 #include <Geom_BezierCurve.hxx>
54 #include <ShapeBuild_ReShape.hxx>
55 #include <TopTools_IndexedDataMapOfShapeListOfShape.hxx>
56 #include <TopTools_MapOfShape.hxx>
57 #include <TopTools_ListIteratorOfListOfShape.hxx>
58 #include <ShapeAnalysis_WireOrder.hxx>
59 #include <ShapeBuild_Edge.hxx>
60 #include <Geom2d_Line.hxx>
61 #include <ShapeFix_Face.hxx>
62 #include <TColGeom_HArray2OfSurface.hxx>
63 #include <ShapeExtend_CompositeSurface.hxx>
64 #include <ShapeFix_ComposeShell.hxx>
65 #include <ShapeFix_SequenceOfWireSegment.hxx>
66 #include <ShapeFix_WireSegment.hxx>
67 #include <ShapeFix_Edge.hxx>
68 #include <ShapeFix_Shell.hxx>
69 #include <ShapeUpgrade_RemoveLocations.hxx>
70
71
72 //=======================================================================
73 //function : AddOrdinaryEdges
74 //purpose  : auxilary
75 //=======================================================================
76 // adds edges from the shape to the sequence
77 // seams and equal edges are dropped
78 // Returns true if one of original edges dropped
79 static Standard_Boolean AddOrdinaryEdges(TopTools_SequenceOfShape& edges,
80                                          const TopoDS_Shape aShape,
81                                          Standard_Integer& anIndex)
82 {
83   //map of edges
84   TopTools_IndexedMapOfShape aNewEdges;
85   //add edges without seams
86   for(TopExp_Explorer exp(aShape,TopAbs_EDGE); exp.More(); exp.Next()) {
87     TopoDS_Shape edge = exp.Current();
88     if(aNewEdges.Contains(edge))
89     {
90       //aNewEdges.Remove(edge);
91       TopoDS_Shape LastEdge = aNewEdges(aNewEdges.Extent());
92       aNewEdges.RemoveLast();
93       if (aNewEdges.FindIndex(edge) != 0)
94         aNewEdges.Substitute(aNewEdges.FindIndex(edge), LastEdge);
95       /////////////////////////
96     }
97     else
98       aNewEdges.Add(edge);
99   }
100
101   Standard_Boolean isDropped = Standard_False;
102   //merge edges and drop seams
103   Standard_Integer i;
104   for (i = 1; i <= edges.Length(); i++) {
105     TopoDS_Shape current = edges(i);
106     if(aNewEdges.Contains(current)) {
107
108       //aNewEdges.Remove(current);
109       TopoDS_Shape LastEdge = aNewEdges(aNewEdges.Extent());
110       aNewEdges.RemoveLast();
111       if (aNewEdges.FindIndex(current) != 0)
112         aNewEdges.Substitute(aNewEdges.FindIndex(current), LastEdge);
113       /////////////////////////
114       edges.Remove(i);
115       i--;
116
117       if(!isDropped) {
118         isDropped = Standard_True;
119         anIndex = i;
120       }
121     }
122   }
123
124   //add edges to the sequemce
125   for (i = 1; i <= aNewEdges.Extent(); i++)
126     edges.Append(aNewEdges(i));
127
128   return isDropped;
129 }
130
131 //=======================================================================
132 //function : getCylinder
133 //purpose  : auxilary
134 //=======================================================================
135 static Standard_Boolean getCylinder(Handle(Geom_Surface)& theInSurface,
136                                     gp_Cylinder& theOutCylinder)
137 {
138   Standard_Boolean isCylinder = Standard_False;
139
140   if (theInSurface->IsKind(STANDARD_TYPE(Geom_CylindricalSurface))) {
141     Handle(Geom_CylindricalSurface) aGC = Handle(Geom_CylindricalSurface)::DownCast(theInSurface);
142
143     theOutCylinder = aGC->Cylinder();
144     isCylinder = Standard_True;
145   }
146   else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfRevolution))) {
147     Handle(Geom_SurfaceOfRevolution) aRS =
148       Handle(Geom_SurfaceOfRevolution)::DownCast(theInSurface);
149     Handle(Geom_Curve) aBasis = aRS->BasisCurve();
150     if (aBasis->IsKind(STANDARD_TYPE(Geom_Line))) {
151       Handle(Geom_Line) aBasisLine = Handle(Geom_Line)::DownCast(aBasis);
152       gp_Dir aDir = aRS->Direction();
153       gp_Dir aBasisDir = aBasisLine->Position().Direction();
154       if (aBasisDir.IsParallel(aDir, Precision::Angular())) {
155         // basis line is parallel to the revolution axis: it is a cylinder
156         gp_Pnt aLoc = aRS->Location();
157         Standard_Real aR = aBasisLine->Lin().Distance(aLoc);
158         gp_Ax3 aCylAx (aLoc, aDir);
159
160         theOutCylinder = gp_Cylinder(aCylAx, aR);
161         isCylinder = Standard_True;
162       }
163     }
164   }
165   else if (theInSurface->IsKind(STANDARD_TYPE(Geom_SurfaceOfLinearExtrusion))) {
166     Handle(Geom_SurfaceOfLinearExtrusion) aLES =
167       Handle(Geom_SurfaceOfLinearExtrusion)::DownCast(theInSurface);
168     Handle(Geom_Curve) aBasis = aLES->BasisCurve();
169     if (aBasis->IsKind(STANDARD_TYPE(Geom_Circle))) {
170       Handle(Geom_Circle) aBasisCircle = Handle(Geom_Circle)::DownCast(aBasis);
171       gp_Dir aDir = aLES->Direction();
172       gp_Dir aBasisDir = aBasisCircle->Position().Direction();
173       if (aBasisDir.IsParallel(aDir, Precision::Angular())) {
174         // basis circle is normal to the extrusion axis: it is a cylinder
175         gp_Pnt aLoc = aBasisCircle->Location();
176         Standard_Real aR = aBasisCircle->Radius();
177         gp_Ax3 aCylAx (aLoc, aDir);
178
179         theOutCylinder = gp_Cylinder(aCylAx, aR);
180         isCylinder = Standard_True;
181       }
182     }
183   }
184   else {
185   }
186
187   return isCylinder;
188 }
189
190 //=======================================================================
191 //function : ClearRts
192 //purpose  : auxilary
193 //=======================================================================
194 static Handle(Geom_Surface) ClearRts(const Handle(Geom_Surface)& aSurface)
195 {
196   if(aSurface->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) {
197     Handle(Geom_RectangularTrimmedSurface) rts =
198       Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurface);
199     return rts->BasisSurface();
200   }
201   return aSurface;
202 }
203
204 //=======================================================================
205 //function : IsSameDomain
206 //purpose  : 
207 //=======================================================================
208 static Standard_Boolean IsSameDomain(const TopoDS_Face& aFace,
209                                      const TopoDS_Face& aCheckedFace)
210 {
211   //checking the same handles
212   TopLoc_Location L1, L2;
213   Handle(Geom_Surface) S1, S2;
214
215   S1 = BRep_Tool::Surface(aFace,L1);
216   S2 = BRep_Tool::Surface(aCheckedFace,L2);
217
218   if (S1 == S2 && L1 == L2)
219     return Standard_True;
220
221   // planar and cylindrical cases (IMP 20052)
222   Standard_Real aPrec = Precision::Confusion();
223
224   S1 = BRep_Tool::Surface(aFace);
225   S2 = BRep_Tool::Surface(aCheckedFace);
226
227   S1 = ClearRts(S1);
228   S2 = ClearRts(S2);
229
230   //Handle(Geom_OffsetSurface) aGOFS1, aGOFS2;
231   //aGOFS1 = Handle(Geom_OffsetSurface)::DownCast(S1);
232   //aGOFS2 = Handle(Geom_OffsetSurface)::DownCast(S2);
233   //if (!aGOFS1.IsNull()) S1 = aGOFS1->BasisSurface();
234   //if (!aGOFS2.IsNull()) S2 = aGOFS2->BasisSurface();
235
236   // case of two elementary surfaces: use OCCT tool
237   // elementary surfaces: ConicalSurface, CylindricalSurface,
238   //                      Plane, SphericalSurface and ToroidalSurface
239   if (S1->IsKind(STANDARD_TYPE(Geom_ElementarySurface)) &&
240       S2->IsKind(STANDARD_TYPE(Geom_ElementarySurface)))
241   {
242     Handle(GeomAdaptor_HSurface) aGA1 = new GeomAdaptor_HSurface(S1);
243     Handle(GeomAdaptor_HSurface) aGA2 = new GeomAdaptor_HSurface(S2);
244
245     Handle(BRepTopAdaptor_TopolTool) aTT1 = new BRepTopAdaptor_TopolTool();
246     Handle(BRepTopAdaptor_TopolTool) aTT2 = new BRepTopAdaptor_TopolTool();
247
248     try {
249       IntPatch_ImpImpIntersection anIIInt (aGA1, aTT1, aGA2, aTT2, aPrec, aPrec);
250       if (!anIIInt.IsDone() || anIIInt.IsEmpty())
251         return Standard_False;
252
253       return anIIInt.TangentFaces();
254     }
255     catch (Standard_Failure) {
256       return Standard_False;
257     }
258   }
259
260   // case of two planar surfaces:
261   // all kinds of surfaces checked, including b-spline and bezier
262   GeomLib_IsPlanarSurface aPlanarityChecker1 (S1, aPrec);
263   if (aPlanarityChecker1.IsPlanar()) {
264     GeomLib_IsPlanarSurface aPlanarityChecker2 (S2, aPrec);
265     if (aPlanarityChecker2.IsPlanar()) {
266       gp_Pln aPln1 = aPlanarityChecker1.Plan();
267       gp_Pln aPln2 = aPlanarityChecker2.Plan();
268
269       if (aPln1.Position().Direction().IsParallel(aPln2.Position().Direction(),Precision::Angular()) &&
270           aPln1.Distance(aPln2) < aPrec) {
271         return Standard_True;
272       }
273     }
274   }
275
276   // case of two cylindrical surfaces, at least one of which is a swept surface
277   // swept surfaces: SurfaceOfLinearExtrusion, SurfaceOfRevolution
278   if ((S1->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
279        S1->IsKind(STANDARD_TYPE(Geom_SweptSurface))) &&
280       (S2->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ||
281        S2->IsKind(STANDARD_TYPE(Geom_SweptSurface))))
282   {
283     gp_Cylinder aCyl1, aCyl2;
284     if (getCylinder(S1, aCyl1) && getCylinder(S2, aCyl2)) {
285       if (fabs(aCyl1.Radius() - aCyl2.Radius()) < aPrec) {
286         gp_Dir aDir1 = aCyl1.Position().Direction();
287         gp_Dir aDir2 = aCyl2.Position().Direction();
288         if (aDir1.IsParallel(aDir2, Precision::Angular())) {
289           gp_Pnt aLoc1 = aCyl1.Location();
290           gp_Pnt aLoc2 = aCyl2.Location();
291           gp_Vec aVec12 (aLoc1, aLoc2);
292           if (aVec12.SquareMagnitude() < aPrec*aPrec ||
293               aVec12.IsParallel(aDir1, Precision::Angular())) {
294             return Standard_True;
295           }
296         }
297       }
298     }
299   }
300
301   return Standard_False;
302 }
303
304 //=======================================================================
305 //function : MovePCurves
306 //purpose  :
307 //=======================================================================
308 static void MovePCurves(TopoDS_Face& aTarget,
309                         const TopoDS_Face& aSource)
310 {
311   BRep_Builder B;
312   for(TopExp_Explorer wexp(aSource,TopAbs_WIRE);wexp.More();wexp.Next()) {
313     Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(TopoDS::Wire(wexp.Current()),
314                                                   aTarget, Precision::Confusion());
315     sfw->FixReorder();
316     Standard_Boolean isReoredFailed = sfw->StatusReorder ( ShapeExtend_FAIL );
317     sfw->FixEdgeCurves();
318     if(isReoredFailed)
319       continue;
320
321     sfw->FixShifted();
322     sfw->FixDegenerated();
323
324     // remove degenerated edges from not degenerated points
325     ShapeAnalysis_Edge sae;
326     Handle(ShapeExtend_WireData) sewd = sfw->WireData();
327     for(Standard_Integer i = 1; i<=sewd->NbEdges();i++) {
328       TopoDS_Edge E = sewd->Edge(i);
329       if(BRep_Tool::Degenerated(E)&&!sae.HasPCurve(E,aTarget)) {
330         sewd->Remove(i);
331         i--;
332       }
333     }
334
335     TopoDS_Wire ResWire = sfw->Wire();
336     B.Add(aTarget,ResWire);
337   }
338 }
339
340 //=======================================================================
341 //function : GlueEdgesWithPCurves
342 //purpose  : Glues the pcurves of the sequence of edges
343 //           and glues their 3d curves
344 //=======================================================================
345 static TopoDS_Edge GlueEdgesWithPCurves(const TopTools_SequenceOfShape& aChain,
346                                         const TopoDS_Vertex& FirstVertex,
347                                         const TopoDS_Vertex& LastVertex)
348 {
349   Standard_Integer i, j;
350
351   TopoDS_Edge FirstEdge = TopoDS::Edge(aChain(1));
352   //TColGeom2d_SequenceOfCurve PCurveSeq;
353   TColGeom_SequenceOfSurface SurfSeq;
354   //TopTools_SequenceOfShape LocSeq;
355   
356   BRep_ListIteratorOfListOfCurveRepresentation itr( (Handle(BRep_TEdge)::DownCast(FirstEdge.TShape()))->Curves() );
357   for (; itr.More(); itr.Next())
358   {
359     Handle(BRep_CurveRepresentation) CurveRep = itr.Value();
360     if (CurveRep->IsCurveOnSurface())
361     {
362       //PCurveSeq.Append(CurveRep->PCurve());
363       SurfSeq.Append(CurveRep->Surface());
364       /*
365       TopoDS_Shape aLocShape;
366       aLocShape.Location(CurveRep->Location());
367       LocSeq.Append(aLocShape);
368       */
369     }
370   }
371
372   Standard_Real fpar, lpar;
373   BRep_Tool::Range(FirstEdge, fpar, lpar);
374   TopoDS_Edge PrevEdge = FirstEdge;
375   TopoDS_Vertex CV;
376   Standard_Real MaxTol = 0.;
377   
378   TopoDS_Edge ResEdge;
379   BRep_Builder BB;
380
381   Standard_Integer nb_curve = aChain.Length();   //number of curves
382   TColGeom_Array1OfBSplineCurve tab_c3d(0,nb_curve-1);                    //array of the curves
383   TColStd_Array1OfReal tabtolvertex(0,nb_curve-1); //(0,nb_curve-2);  //array of the tolerances
384     
385   TopoDS_Vertex PrevVertex = FirstVertex;
386   for (i = 1; i <= nb_curve; i++)
387   {
388     TopoDS_Edge anEdge = TopoDS::Edge(aChain(i));
389     TopoDS_Vertex VF, VL;
390     TopExp::Vertices(anEdge, VF, VL);
391     Standard_Boolean ToReverse = (!VF.IsSame(PrevVertex));
392     
393     Standard_Real Tol1 = BRep_Tool::Tolerance(VF);
394     Standard_Real Tol2 = BRep_Tool::Tolerance(VL);
395     if (Tol1 > MaxTol)
396       MaxTol = Tol1;
397     if (Tol2 > MaxTol)
398       MaxTol = Tol2;
399     
400     if (i > 1)
401     {
402       TopExp::CommonVertex(PrevEdge, anEdge, CV);
403       Standard_Real Tol = BRep_Tool::Tolerance(CV);
404       tabtolvertex(i-2) = Tol;
405     }
406     
407     Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, fpar, lpar);
408     Handle(Geom_TrimmedCurve) aTrCurve = new Geom_TrimmedCurve(aCurve, fpar, lpar);
409     tab_c3d(i-1) = GeomConvert::CurveToBSplineCurve(aTrCurve);
410     GeomConvert::C0BSplineToC1BSplineCurve(tab_c3d(i-1), Precision::Confusion());
411     if (ToReverse)
412       tab_c3d(i-1)->Reverse();
413     PrevVertex = (ToReverse)? VF : VL;
414     PrevEdge = anEdge;
415   }
416   Handle(TColGeom_HArray1OfBSplineCurve)  concatcurve;     //array of the concatenated curves
417   Handle(TColStd_HArray1OfInteger)        ArrayOfIndices;  //array of the remining Vertex
418   GeomConvert::ConcatC1(tab_c3d,
419                         tabtolvertex,
420                         ArrayOfIndices,
421                         concatcurve,
422                         Standard_False,
423                         Precision::Confusion());   //C1 concatenation
424   
425   if (concatcurve->Length() > 1)
426   {
427     GeomConvert_CompCurveToBSplineCurve Concat(concatcurve->Value(concatcurve->Lower()));
428     
429     for (i = concatcurve->Lower()+1; i <= concatcurve->Upper(); i++)
430       Concat.Add( concatcurve->Value(i), MaxTol, Standard_True );
431     
432     concatcurve->SetValue(concatcurve->Lower(), Concat.BSplineCurve());
433   }
434   Handle(Geom_BSplineCurve) ResCurve = concatcurve->Value(concatcurve->Lower());
435   
436   TColGeom2d_SequenceOfBoundedCurve ResPCurves;
437   TopLoc_Location aLoc;
438   for (j = 1; j <= SurfSeq.Length(); j++)
439   {
440     TColGeom2d_Array1OfBSplineCurve tab_c2d(0,nb_curve-1); //array of the pcurves
441     
442     PrevVertex = FirstVertex;
443     PrevEdge = FirstEdge;
444     //TopLoc_Location theLoc = LocSeq(j).Location();
445     for (i = 1; i <= nb_curve; i++)
446     {
447       TopoDS_Edge anEdge = TopoDS::Edge(aChain(i));
448       TopoDS_Vertex VF, VL;
449       TopExp::Vertices(anEdge, VF, VL);
450       Standard_Boolean ToReverse = (!VF.IsSame(PrevVertex));
451
452       /*
453       Handle(Geom2d_Curve) aPCurve =
454         BRep_Tool::CurveOnSurface(anEdge, SurfSeq(j), anEdge.Location()*theLoc, fpar, lpar);
455       */
456       Handle(Geom2d_Curve) aPCurve =
457         BRep_Tool::CurveOnSurface(anEdge, SurfSeq(j), aLoc, fpar, lpar);
458       Handle(Geom2d_TrimmedCurve) aTrPCurve = new Geom2d_TrimmedCurve(aPCurve, fpar, lpar);
459       tab_c2d(i-1) = Geom2dConvert::CurveToBSplineCurve(aTrPCurve);
460       Geom2dConvert::C0BSplineToC1BSplineCurve(tab_c2d(i-1), Precision::Confusion());
461       if (ToReverse)
462         tab_c2d(i-1)->Reverse();
463       PrevVertex = (ToReverse)? VF : VL;
464       PrevEdge = anEdge;
465     }
466     Handle(TColGeom2d_HArray1OfBSplineCurve)  concatc2d;     //array of the concatenated curves
467     Handle(TColStd_HArray1OfInteger)        ArrayOfInd2d;  //array of the remining Vertex
468     Geom2dConvert::ConcatC1(tab_c2d,
469                             tabtolvertex,
470                             ArrayOfInd2d,
471                             concatc2d,
472                             Standard_False,
473                             Precision::Confusion());   //C1 concatenation
474     
475     if (concatc2d->Length() > 1)
476     {
477       Geom2dConvert_CompCurveToBSplineCurve Concat2d(concatc2d->Value(concatc2d->Lower()));
478       
479       for (i = concatc2d->Lower()+1; i <= concatc2d->Upper(); i++)
480         Concat2d.Add( concatc2d->Value(i), MaxTol, Standard_True );
481       
482       concatc2d->SetValue(concatc2d->Lower(), Concat2d.BSplineCurve());
483     }
484     Handle(Geom2d_BSplineCurve) aResPCurve = concatc2d->Value(concatc2d->Lower());
485     ResPCurves.Append(aResPCurve);
486   }
487   
488   ResEdge = BRepLib_MakeEdge(ResCurve,
489                              FirstVertex, LastVertex,
490                              ResCurve->FirstParameter(), ResCurve->LastParameter());
491   BB.SameRange(ResEdge, Standard_False);
492   BB.SameParameter(ResEdge, Standard_False);
493   for (j = 1; j <= ResPCurves.Length(); j++)
494   {
495     BB.UpdateEdge(ResEdge, ResPCurves(j), SurfSeq(j), aLoc, MaxTol);
496     BB.Range(ResEdge, SurfSeq(j), aLoc, ResPCurves(j)->FirstParameter(), ResPCurves(j)->LastParameter());
497   }
498
499   BRepLib::SameParameter(ResEdge, MaxTol, Standard_True);
500   
501   return ResEdge;
502 }
503
504 //=======================================================================
505 //function : MergeEdges
506 //purpose  : auxilary
507 //=======================================================================
508 static Standard_Boolean MergeEdges(const TopTools_SequenceOfShape& SeqEdges,
509                                    const TopoDS_Face& aFace,
510                                    const Standard_Real Tol,
511                                    const Standard_Boolean ConcatBSplines,
512                                    TopoDS_Edge& anEdge)
513 {
514   // make chain for union
515   BRep_Builder B;
516   ShapeAnalysis_Edge sae;
517   TopoDS_Edge FirstE = TopoDS::Edge(SeqEdges.Value(1));
518   TopoDS_Edge LastE = FirstE;
519   TopoDS_Vertex VF = sae.FirstVertex(FirstE);
520   TopoDS_Vertex VL = sae.LastVertex(LastE);
521   TopTools_SequenceOfShape aChain;
522   aChain.Append(FirstE);
523   TColStd_MapOfInteger IndUsedEdges;
524   IndUsedEdges.Add(1);
525   Standard_Integer j;
526   for (j = 1; j <= SeqEdges.Length(); j++)
527   {
528     TopoDS_Edge anEdge = TopoDS::Edge(SeqEdges(j));
529     if (BRep_Tool::Degenerated(anEdge))
530       return Standard_False;
531   }
532   
533   for(j=2; j<=SeqEdges.Length(); j++) {
534     for(Standard_Integer k=2; k<=SeqEdges.Length(); k++) {
535       if(IndUsedEdges.Contains(k)) continue;
536       TopoDS_Edge edge = TopoDS::Edge(SeqEdges.Value(k));
537       TopoDS_Vertex VF2 = sae.FirstVertex(edge);
538       TopoDS_Vertex VL2 = sae.LastVertex(edge);
539       if(sae.FirstVertex(edge).IsSame(VL)) {
540         aChain.Append(edge);
541         LastE = edge;
542         VL = sae.LastVertex(LastE);
543         IndUsedEdges.Add(k);
544       }
545       else if(sae.LastVertex(edge).IsSame(VF)) {
546         aChain.Prepend(edge);
547         FirstE = edge;
548         VF = sae.FirstVertex(FirstE);
549         IndUsedEdges.Add(k);
550       }
551     }
552   }
553   if(aChain.Length()<SeqEdges.Length()) {
554 #ifdef DEB
555     cout<<"can not create correct chain..."<<endl;
556 #endif
557     return Standard_False;
558   }
559   // union edges in chain
560   // first step: union lines and circles
561   TopLoc_Location Loc;
562   Standard_Real fp1,lp1,fp2,lp2;
563   for(j=1; j<aChain.Length(); j++) {
564     TopoDS_Edge edge1 = TopoDS::Edge(aChain.Value(j));
565     Handle(Geom_Curve) c3d1 = BRep_Tool::Curve(edge1,Loc,fp1,lp1);
566     if(c3d1.IsNull()) break;
567     while(c3d1->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
568       Handle(Geom_TrimmedCurve) tc =
569         Handle(Geom_TrimmedCurve)::DownCast(c3d1);
570       c3d1 = tc->BasisCurve();
571     }
572     TopoDS_Edge edge2 = TopoDS::Edge(aChain.Value(j+1));
573     Handle(Geom_Curve) c3d2 = BRep_Tool::Curve(edge2,Loc,fp2,lp2);
574     if(c3d2.IsNull()) break;
575     while(c3d2->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
576       Handle(Geom_TrimmedCurve) tc =
577         Handle(Geom_TrimmedCurve)::DownCast(c3d2);
578       c3d2 = tc->BasisCurve();
579     }
580     if( c3d1->IsKind(STANDARD_TYPE(Geom_Line)) && c3d2->IsKind(STANDARD_TYPE(Geom_Line)) ) {
581       // union lines
582       Handle(Geom_Line) L1 = Handle(Geom_Line)::DownCast(c3d1);
583       Handle(Geom_Line) L2 = Handle(Geom_Line)::DownCast(c3d2);
584       gp_Dir Dir1 = L1->Position().Direction();
585       gp_Dir Dir2 = L2->Position().Direction();
586       //if(!Dir1.IsEqual(Dir2,Precision::Angular())) { 
587       //if(!Dir1.IsParallel(Dir2,Precision::Angular())) { 
588       if(!Dir1.IsParallel(Dir2,Tol)) { 
589         continue;
590       }
591       // can union lines => create new edge
592       TopoDS_Vertex V1 = sae.FirstVertex(edge1);
593       gp_Pnt PV1 = BRep_Tool::Pnt(V1);
594       TopoDS_Vertex V2 = sae.LastVertex(edge2);
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       //ShapeFix_Edge sfe;
606       //sfe.FixAddPCurve(E,aFace,Standard_False);
607       //sfe.FixSameParameter(E);
608       aChain.Remove(j);
609       aChain.SetValue(j,E);
610       j--;
611     }
612     if( c3d1->IsKind(STANDARD_TYPE(Geom_Circle)) && c3d2->IsKind(STANDARD_TYPE(Geom_Circle)) ) {
613       // union circles
614       Handle(Geom_Circle) C1 = Handle(Geom_Circle)::DownCast(c3d1);
615       Handle(Geom_Circle) C2 = Handle(Geom_Circle)::DownCast(c3d2);
616       gp_Pnt P01 = C1->Location();
617       gp_Pnt P02 = C2->Location();
618       if (P01.Distance(P02) > Precision::Confusion()) continue;
619       // can union circles => create new edge
620       TopoDS_Vertex V1 = sae.FirstVertex(edge1);
621       gp_Pnt PV1 = BRep_Tool::Pnt(V1);
622       TopoDS_Vertex V2 = sae.LastVertex(edge2);
623       gp_Pnt PV2 = BRep_Tool::Pnt(V2);
624       TopoDS_Vertex VM = sae.LastVertex(edge1);
625       gp_Pnt PVM = BRep_Tool::Pnt(VM);
626       GC_MakeCircle MC (PV1,PVM,PV2);
627       Handle(Geom_Circle) C = MC.Value();
628       TopoDS_Edge E;
629       if (!MC.IsDone() || C.IsNull()) {
630         // jfa for Mantis issue 0020228
631         if (PV1.Distance(PV2) > Precision::Confusion()) continue;
632         // closed chain
633         C = C1;
634         B.MakeEdge (E,C,Precision::Confusion());
635         B.Add(E,V1);
636         B.Add(E,V2);
637       }
638       else {
639         gp_Pnt P0 = C->Location();
640         gp_Dir D1(gp_Vec(P0,PV1));
641         gp_Dir D2(gp_Vec(P0,PV2));
642         Standard_Real fpar = C->XAxis().Direction().Angle(D1);
643         if(fabs(fpar)>Precision::Confusion()) {
644           // check orientation
645           gp_Dir ND =  C->XAxis().Direction().Crossed(D1);
646           if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
647             fpar = -fpar;
648           }
649         }
650         Standard_Real lpar = C->XAxis().Direction().Angle(D2);
651         if(fabs(lpar)>Precision::Confusion()) {
652           // check orientation
653           gp_Dir ND =  C->XAxis().Direction().Crossed(D2);
654           if(ND.IsOpposite(C->Axis().Direction(),Precision::Confusion())) {
655             lpar = -lpar;
656           }
657         }
658         if (lpar < fpar) lpar += 2*M_PI;
659         Handle(Geom_TrimmedCurve) tc = new Geom_TrimmedCurve(C,fpar,lpar);
660         B.MakeEdge (E,tc,Precision::Confusion());
661         B.Add(E,V1);
662         B.Add(E,V2);
663         B.UpdateVertex(V1, fpar, E, 0.);
664         B.UpdateVertex(V2, lpar, E, 0.);
665       }
666       aChain.Remove(j);
667       aChain.SetValue(j,E);
668       j--;
669     }
670   }
671   if (j < aChain.Length()) {
672 #ifdef DEB
673     cout<<"null curve3d in edge..."<<endl;
674 #endif
675     return Standard_False;
676   }
677   if (aChain.Length() > 1 && ConcatBSplines) {
678     // second step: union edges with various curves
679     // skl for bug 0020052 from Mantis: perform such unions
680     // only if curves are bspline or bezier
681     bool NeedUnion = true;
682     for(j=1; j<=aChain.Length(); j++) {
683       TopoDS_Edge edge = TopoDS::Edge(aChain.Value(j));
684       Handle(Geom_Curve) c3d = BRep_Tool::Curve(edge,Loc,fp1,lp1);
685       if(c3d.IsNull()) continue;
686       while(c3d->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) {
687         Handle(Geom_TrimmedCurve) tc =
688           Handle(Geom_TrimmedCurve)::DownCast(c3d);
689         c3d = tc->BasisCurve();
690       }
691       if( ( c3d->IsKind(STANDARD_TYPE(Geom_BSplineCurve)) ||
692             c3d->IsKind(STANDARD_TYPE(Geom_BezierCurve)) ) ) continue;
693       NeedUnion = false;
694       break;
695     }
696     if(NeedUnion) {
697 #ifdef DEB
698       cout<<"can not make analitical union => make approximation"<<endl;
699 #endif
700       TopoDS_Edge E = GlueEdgesWithPCurves(aChain, VF, VL);
701       /*
702       TopoDS_Wire W;
703       B.MakeWire(W);
704       for(j=1; j<=aChain.Length(); j++) {
705         TopoDS_Edge edge = TopoDS::Edge(aChain.Value(j));
706         B.Add(W,edge);
707       }
708       Handle(BRepAdaptor_HCompCurve) Adapt = new BRepAdaptor_HCompCurve(W);
709       Approx_Curve3d Conv(Adapt,Tol,GeomAbs_C1,9,1000);
710       Handle(Geom_BSplineCurve) bc = Conv.Curve();
711       TopoDS_Edge E;
712       B.MakeEdge (E,bc,Precision::Confusion());
713       B.Add (E,VF);
714       B.Add (E,VL);
715       */
716       aChain.SetValue(1,E);
717     }
718     else {
719 #ifdef DEB
720       cout<<"can not make approximation for such types of curves"<<endl;
721 #endif
722       return Standard_False;
723     }
724   }
725
726   anEdge = TopoDS::Edge(aChain.Value(1));
727   return Standard_True;
728 }
729
730 //=======================================================================
731 //function : ShapeUpgrade_UnifySameDomain
732 //purpose  : Constructor
733 //=======================================================================
734
735 ShapeUpgrade_UnifySameDomain::ShapeUpgrade_UnifySameDomain()
736 {
737   myUnifyEdges = Standard_True;
738   myUnifyFaces = Standard_True;
739   myConcatBSplines = Standard_False;
740
741   myContext = new ShapeBuild_ReShape;
742 }
743
744 //=======================================================================
745 //function : ShapeUpgrade_UnifySameDomain
746 //purpose  : Constructor
747 //=======================================================================
748
749 ShapeUpgrade_UnifySameDomain::ShapeUpgrade_UnifySameDomain(const TopoDS_Shape& aShape,
750                                                            const Standard_Boolean UnifyEdges,
751                                                            const Standard_Boolean UnifyFaces,
752                                                            const Standard_Boolean ConcatBSplines)
753 {
754   myInitShape = aShape;
755   myShape = aShape;
756   myUnifyEdges = UnifyEdges;
757   myUnifyFaces = UnifyFaces;
758   myConcatBSplines = ConcatBSplines;
759
760   myContext = new ShapeBuild_ReShape;
761 }
762
763 //=======================================================================
764 //function : Initialize
765 //purpose  : 
766 //=======================================================================
767
768 void ShapeUpgrade_UnifySameDomain::Initialize(const TopoDS_Shape& aShape,
769                                               const Standard_Boolean UnifyEdges,
770                                               const Standard_Boolean UnifyFaces,
771                                               const Standard_Boolean ConcatBSplines)
772 {
773   myInitShape = aShape;
774   myShape = aShape;
775   myUnifyEdges = UnifyEdges;
776   myUnifyFaces = UnifyFaces;
777   myConcatBSplines = ConcatBSplines;
778
779   myContext->Clear();
780   //myOldNewMap.Clear();
781   //myGenerated.Clear();
782 }
783
784 //=======================================================================
785 //function : UnifyFaces
786 //purpose  : 
787 //=======================================================================
788
789 void ShapeUpgrade_UnifySameDomain::UnifyFaces()
790 {
791   //Handle(ShapeBuild_ReShape) myContext = new ShapeBuild_ReShape;
792   TopoDS_Shape aResShape = myContext->Apply(myShape);
793
794   // processing each shell
795   TopExp_Explorer exps;
796   for (exps.Init(myShape, TopAbs_SHELL); exps.More(); exps.Next()) {
797     TopoDS_Shell aShell = TopoDS::Shell(exps.Current());
798
799     // creating map of edge faces
800     TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
801     TopExp::MapShapesAndAncestors(aShell, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
802
803     // map of processed shapes
804     TopTools_MapOfShape aProcessed;
805
806     //Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
807
808     Standard_Integer NbModif = 0;
809     Standard_Boolean hasFailed = Standard_False;
810     Standard_Real tol = Precision::Confusion();
811
812     // count faces
813     Standard_Integer nbf = 0;
814     TopExp_Explorer exp;
815     TopTools_MapOfShape mapF;
816     for (exp.Init(aShell, TopAbs_FACE); exp.More(); exp.Next()) {
817       if (mapF.Add(exp.Current()))
818         nbf++;
819     }
820
821     // processing each face
822     mapF.Clear();
823     for (exp.Init(aShell, TopAbs_FACE); exp.More(); exp.Next()) {
824       TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
825
826       if (aProcessed.Contains(aFace))
827         continue;
828
829       Standard_Integer dummy;
830       TopTools_SequenceOfShape edges;
831       AddOrdinaryEdges(edges,aFace,dummy);
832
833       TopTools_SequenceOfShape faces;
834       faces.Append(aFace);
835
836       //surface and location to construct result
837       TopLoc_Location aBaseLocation;
838       Handle(Geom_Surface) aBaseSurface = BRep_Tool::Surface(aFace,aBaseLocation);
839       aBaseSurface = ClearRts(aBaseSurface);
840
841       // find adjacent faces to union
842       Standard_Integer i;
843       for (i = 1; i <= edges.Length(); i++) {
844         TopoDS_Edge edge = TopoDS::Edge(edges(i));
845         if (BRep_Tool::Degenerated(edge))
846           continue;
847
848         const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
849         TopTools_ListIteratorOfListOfShape anIter(aList);
850         for (; anIter.More(); anIter.Next()) {
851           TopoDS_Face anCheckedFace = TopoDS::Face(anIter.Value().Oriented(TopAbs_FORWARD));
852           if (anCheckedFace.IsSame(aFace))
853             continue;
854
855           if (aProcessed.Contains(anCheckedFace))
856             continue;
857
858           if (IsSameDomain(aFace,anCheckedFace)) {
859
860             if (aList.Extent() != 2) {
861               // non mainfold case is not processed
862               continue;
863             }
864
865             // replacing pcurves
866             TopoDS_Face aMockUpFace;
867             BRep_Builder B;
868             B.MakeFace(aMockUpFace,aBaseSurface,aBaseLocation,0.);
869             MovePCurves(aMockUpFace,anCheckedFace);
870
871             if (AddOrdinaryEdges(edges,aMockUpFace,dummy)) {
872               // sequence edges is modified
873               i = dummy;
874             }
875
876             faces.Append(anCheckedFace);
877             aProcessed.Add(anCheckedFace);
878             break;
879           }
880         }
881       }
882
883       // all faces collected in the sequence. Perform union of faces
884       if (faces.Length() > 1) {
885         NbModif++;
886         TopoDS_Face aResult;
887         BRep_Builder B;
888         B.MakeFace(aResult,aBaseSurface,aBaseLocation,0);
889         Standard_Integer nbWires = 0;
890
891         // connecting wires
892         while (edges.Length()>0) {
893
894           Standard_Boolean isEdge3d = Standard_False;
895           nbWires++;
896           TopTools_MapOfShape aVertices;
897           TopoDS_Wire aWire;
898           B.MakeWire(aWire);
899
900           TopoDS_Edge anEdge = TopoDS::Edge(edges(1));
901           edges.Remove(1);
902
903           isEdge3d |= !BRep_Tool::Degenerated(anEdge);
904           B.Add(aWire,anEdge);
905           TopoDS_Vertex V1,V2;
906           TopExp::Vertices(anEdge,V1,V2);
907           aVertices.Add(V1);
908           aVertices.Add(V2);
909
910           Standard_Boolean isNewFound = Standard_False;
911           do {
912             isNewFound = Standard_False;
913             for(Standard_Integer j = 1; j <= edges.Length(); j++) {
914               anEdge = TopoDS::Edge(edges(j));
915               TopExp::Vertices(anEdge,V1,V2);
916               if(aVertices.Contains(V1) || aVertices.Contains(V2)) {
917                 isEdge3d |= !BRep_Tool::Degenerated(anEdge);
918                 aVertices.Add(V1);
919                 aVertices.Add(V2);
920                 B.Add(aWire,anEdge);
921                 edges.Remove(j);
922                 j--;
923                 isNewFound = Standard_True;
924               }
925             }
926           } while (isNewFound);
927
928           // sorting any type of edges
929           //aWire = TopoDS::Wire(aContext->Apply(aWire));
930           aWire = TopoDS::Wire(myContext->Apply(aWire));
931
932           //TopoDS_Face tmpF = TopoDS::Face(aContext->Apply(faces(1).Oriented(TopAbs_FORWARD)));
933           TopoDS_Face tmpF = TopoDS::Face(myContext->Apply(faces(1).Oriented(TopAbs_FORWARD)));
934           Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(aWire,tmpF,Precision::Confusion());
935           sfw->FixReorder();
936           Standard_Boolean isDegRemoved = Standard_False;
937           if(!sfw->StatusReorder ( ShapeExtend_FAIL )) {
938             // clear degenerated edges if at least one with 3d curve exist
939             if(isEdge3d) {
940               Handle(ShapeExtend_WireData) sewd = sfw->WireData();
941               for(Standard_Integer j = 1; j<=sewd->NbEdges();j++) {
942                 TopoDS_Edge E = sewd->Edge(j);
943                 if(BRep_Tool::Degenerated(E)) {
944                   sewd->Remove(j);
945                   isDegRemoved = Standard_True;
946                   j--;
947                 }
948               }
949             }
950             sfw->FixShifted();
951             if(isDegRemoved)
952               sfw->FixDegenerated();
953           }
954           TopoDS_Wire aWireFixed = sfw->Wire();
955           //aContext->Replace(aWire,aWireFixed);
956           myContext->Replace(aWire,aWireFixed);
957           //for history
958           /*
959           if (!myOldNewMap.IsBound(aWire))
960           {
961             TopTools_ListOfShape EmptyList;
962             myOldNewMap.Bind(aWire, EmptyList);
963           }
964           myOldNewMap(aWire).Clear();
965           myOldNewMap(aWire).Append(aWireFixed);
966           */
967           /////////////
968           
969           // add resulting wire
970           if(isEdge3d) {
971             B.Add(aResult,aWireFixed);
972           }
973           else  {
974             // sorting edges
975             Handle(ShapeExtend_WireData) sbwd = sfw->WireData();
976             Standard_Integer nbEdges = sbwd->NbEdges();
977             // sort degenerated edges and create one edge instead of several ones
978             ShapeAnalysis_WireOrder sawo(Standard_False, 0);
979             ShapeAnalysis_Edge sae;
980             Standard_Integer aLastEdge = nbEdges;
981             for(Standard_Integer j = 1; j <= nbEdges; j++) {
982               Standard_Real f,l;
983               //smh protection on NULL pcurve
984               Handle(Geom2d_Curve) c2d;
985               if(!sae.PCurve(sbwd->Edge(j),tmpF,c2d,f,l)) {
986                 aLastEdge--;
987                 continue;
988               }
989               sawo.Add(c2d->Value(f).XY(),c2d->Value(l).XY());
990             }
991             sawo.Perform();
992
993             // constructind one degenerative edge
994             gp_XY aStart, anEnd, tmp;
995             Standard_Integer nbFirst = sawo.Ordered(1);
996             TopoDS_Edge anOrigE = TopoDS::Edge(sbwd->Edge(nbFirst).Oriented(TopAbs_FORWARD));
997             ShapeBuild_Edge sbe;
998             TopoDS_Vertex aDummyV;
999             TopoDS_Edge E = sbe.CopyReplaceVertices(anOrigE,aDummyV,aDummyV);
1000             sawo.XY(nbFirst,aStart,tmp);
1001             sawo.XY(sawo.Ordered(aLastEdge),tmp,anEnd);
1002
1003             gp_XY aVec = anEnd-aStart;
1004             Handle(Geom2d_Line) aLine = new Geom2d_Line(aStart,gp_Dir2d(anEnd-aStart));
1005
1006             B.UpdateEdge(E,aLine,tmpF,0.);
1007             B.Range(E,tmpF,0.,aVec.Modulus());
1008             Handle(Geom_Curve) C3d;
1009             B.UpdateEdge(E,C3d,0.);
1010             B.Degenerated(E,Standard_True);
1011             TopoDS_Wire aW;
1012             B.MakeWire(aW);
1013             B.Add(aW,E);
1014             B.Add(aResult,aW);
1015           }
1016         }
1017
1018         // perform substitution of face
1019         //aContext->Replace(aContext->Apply(aFace),aResult);
1020         myContext->Replace(myContext->Apply(aFace),aResult);
1021         //for history
1022         /*
1023         if (!myOldNewMap.IsBound(aFace))
1024         {
1025           TopTools_ListOfShape EmptyList;
1026           myOldNewMap.Bind(aFace, EmptyList);
1027         }
1028         myOldNewMap(aFace).Clear();
1029         myOldNewMap(aFace).Append(aResult);
1030         */
1031         /////////////
1032
1033         ShapeFix_Face sff (aResult);
1034         //Intializing by tolerances
1035         sff.SetPrecision(Precision::Confusion());
1036         sff.SetMinTolerance(tol);
1037         sff.SetMaxTolerance(1.);
1038         //Setting modes
1039         sff.FixOrientationMode() = 0;
1040         //sff.FixWireMode() = 0;
1041         //sff.SetContext(aContext);
1042         sff.SetContext(myContext);
1043         // Applying the fixes
1044         sff.Perform();
1045         if(sff.Status(ShapeExtend_FAIL))
1046         hasFailed = Standard_True;
1047
1048         // breaking down to several faces
1049         //TopoDS_Shape theResult = aContext->Apply(aResult);
1050         TopoDS_Shape theResult = myContext->Apply(aResult);
1051         for (TopExp_Explorer aFaceExp (theResult,TopAbs_FACE); aFaceExp.More(); aFaceExp.Next()) {
1052           TopoDS_Face aCurrent = TopoDS::Face(aFaceExp.Current().Oriented(TopAbs_FORWARD));
1053           Handle(TColGeom_HArray2OfSurface) grid = new TColGeom_HArray2OfSurface ( 1, 1, 1, 1 );
1054           grid->SetValue ( 1, 1, aBaseSurface );
1055           Handle(ShapeExtend_CompositeSurface) G = new ShapeExtend_CompositeSurface ( grid );
1056           ShapeFix_ComposeShell CompShell;
1057           CompShell.Init ( G, aBaseLocation, aCurrent, ::Precision::Confusion() );//myPrecision
1058           //CompShell.SetContext( aContext );
1059           CompShell.SetContext( myContext );
1060
1061           TopTools_SequenceOfShape parts;
1062           ShapeFix_SequenceOfWireSegment wires;
1063           for(TopExp_Explorer W_Exp(aCurrent,TopAbs_WIRE);W_Exp.More();W_Exp.Next()) {
1064             Handle(ShapeExtend_WireData) sbwd =
1065               new ShapeExtend_WireData ( TopoDS::Wire(W_Exp.Current() ));
1066             ShapeFix_WireSegment seg ( sbwd, TopAbs_REVERSED );
1067             wires.Append(seg);
1068           }
1069
1070           CompShell.DispatchWires ( parts,wires );
1071           for (Standard_Integer j=1; j <= parts.Length(); j++ ) {
1072             ShapeFix_Face aFixOrient(TopoDS::Face(parts(j)));
1073             //aFixOrient.SetContext(aContext);
1074             aFixOrient.SetContext(myContext);
1075             aFixOrient.FixOrientation();
1076           }
1077
1078           TopoDS_Shape CompRes;
1079           if ( faces.Length() !=1 ) {
1080             TopoDS_Shell S;
1081             B.MakeShell ( S );
1082             for ( i=1; i <= parts.Length(); i++ )
1083               B.Add ( S, parts(i) );
1084             CompRes = S;
1085           }
1086           else CompRes = parts(1);
1087
1088           //aContext->Replace(aCurrent,CompRes);
1089           myContext->Replace(aCurrent,CompRes);
1090           //for history
1091           /*
1092           if (!myOldNewMap.IsBound(aCurrent))
1093           {
1094             TopTools_ListOfShape EmptyList;
1095             myOldNewMap.Bind(aCurrent, EmptyList);
1096           }
1097           myOldNewMap(aCurrent).Clear();
1098           myOldNewMap(aCurrent).Append(CompRes);
1099           */
1100           /////////////
1101         }
1102
1103         // remove the remaining faces
1104         for(i = 2; i <= faces.Length(); i++)
1105           //aContext->Remove(faces(i));
1106           myContext->Remove(faces(i));
1107       }
1108     } // end processing each face
1109
1110     //TopoDS_Shape aResult = Shape;
1111     if (NbModif > 0 && !hasFailed) {
1112       //TopoDS_Shape aResult = aContext->Apply(aShell);
1113       TopoDS_Shape aResult = myContext->Apply(aShell);
1114
1115       ShapeFix_Edge sfe;
1116       for (exp.Init(aResult,TopAbs_EDGE); exp.More(); exp.Next()) {
1117         TopoDS_Edge E = TopoDS::Edge(exp.Current());
1118         sfe.FixVertexTolerance (E);
1119         // ptv add fix same parameter
1120         sfe.FixSameParameter(E, Precision::Confusion());
1121       }
1122
1123       myContext->Replace(aShell, aResult);
1124       //for history
1125       /*
1126       if (!myOldNewMap.IsBound(aShell))
1127       {
1128         TopTools_ListOfShape EmptyList;
1129         myOldNewMap.Bind(aShell, EmptyList);
1130       }
1131       myOldNewMap(aShell).Clear();
1132       myOldNewMap(aShell).Append(aResult);
1133       */
1134       /////////////
1135     }
1136     //else
1137     {
1138       for (exp.Init(aShell, TopAbs_FACE); exp.More(); exp.Next()) {
1139         TopoDS_Face aFace = TopoDS::Face(exp.Current().Oriented(TopAbs_FORWARD));
1140         Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire;
1141         sfw->SetContext(myContext);
1142         sfw->SetPrecision(Precision::Confusion());
1143         sfw->SetMinTolerance(Precision::Confusion());
1144         sfw->SetMaxTolerance(1.);
1145         sfw->SetFace(aFace);
1146         for (TopoDS_Iterator iter (aFace,Standard_False); iter.More(); iter.Next()) {
1147           TopoDS_Wire wire = TopoDS::Wire(iter.Value());
1148           sfw->Load(wire);
1149           sfw->FixReorder();
1150           sfw->FixShifted();
1151         }
1152       }
1153     }
1154   } // end processing each shell
1155
1156   myShape = myContext->Apply(myShape);
1157 }
1158
1159 //=======================================================================
1160 //function : UnifyEdges
1161 //purpose  : 
1162 //=======================================================================
1163
1164 void ShapeUpgrade_UnifySameDomain::UnifyEdges()
1165 {
1166   Standard_Real Tol = Precision::Confusion();
1167   
1168   //Handle(ShapeBuild_ReShape) myContext = new ShapeBuild_ReShape;
1169   Standard_Real myTolerance = Precision::Confusion();
1170   TopoDS_Shape aResult = myContext->Apply(myShape);
1171
1172   // processing each solid
1173   TopAbs_ShapeEnum aType = TopAbs_SOLID;
1174   TopExp_Explorer exps (myShape, aType);
1175   if (!exps.More()) {
1176     aType = TopAbs_SHELL;
1177     exps.Init(myShape, aType);
1178   }
1179   for (; exps.More(); exps.Next()) {
1180     //TopoDS_Solid aSolid = TopoDS::Solid(exps.Current());
1181     TopoDS_Shape aSolid = exps.Current();
1182
1183     TopTools_IndexedMapOfShape ChangedFaces;
1184
1185     // creating map of edge faces
1186     TopTools_IndexedDataMapOfShapeListOfShape aMapEdgeFaces;
1187     TopExp::MapShapesAndAncestors(aSolid, TopAbs_EDGE, TopAbs_FACE, aMapEdgeFaces);
1188
1189     //Handle(ShapeBuild_ReShape) aContext = new ShapeBuild_ReShape;
1190     TopoDS_Shape aRes = aSolid;
1191     //aRes = aContext->Apply(aSolid);
1192     aRes = myContext->Apply(aSolid);
1193
1194     // processing each face
1195     TopExp_Explorer exp;
1196     for (exp.Init(aRes, TopAbs_FACE); exp.More(); exp.Next()) {
1197       //TopoDS_Face aFace = TopoDS::Face(aContext->Apply(exp.Current().Oriented(TopAbs_FORWARD)));
1198       TopoDS_Face aFace = TopoDS::Face(myContext->Apply(exp.Current().Oriented(TopAbs_FORWARD)));
1199       TopTools_IndexedDataMapOfShapeListOfShape aMapFacesEdges;
1200
1201       for (TopExp_Explorer expe(aFace,TopAbs_EDGE); expe.More(); expe.Next()) {
1202         TopoDS_Edge edge = TopoDS::Edge(expe.Current());
1203         if (!aMapEdgeFaces.Contains(edge)) continue;
1204         const TopTools_ListOfShape& aList = aMapEdgeFaces.FindFromKey(edge);
1205         TopTools_ListIteratorOfListOfShape anIter(aList);
1206         for ( ; anIter.More(); anIter.Next()) {
1207           TopoDS_Face face = TopoDS::Face(anIter.Value());
1208           //TopoDS_Face face1 = TopoDS::Face(aContext->Apply(anIter.Value()));
1209           TopoDS_Face face1 = TopoDS::Face(myContext->Apply(anIter.Value()));
1210           if (face1.IsSame(aFace)) continue;
1211           if (aMapFacesEdges.Contains(face)) {
1212             aMapFacesEdges.ChangeFromKey(face).Append(edge);
1213           }
1214           else {
1215             TopTools_ListOfShape ListEdges;
1216             ListEdges.Append(edge);
1217             aMapFacesEdges.Add(face,ListEdges);
1218           }
1219         }
1220       }
1221
1222       for (Standard_Integer i=1; i<=aMapFacesEdges.Extent(); i++) {
1223         const TopTools_ListOfShape& ListEdges = aMapFacesEdges.FindFromIndex(i);
1224         TopTools_SequenceOfShape SeqEdges;
1225         TopTools_ListIteratorOfListOfShape anIter(ListEdges);
1226         for ( ; anIter.More(); anIter.Next()) {
1227           SeqEdges.Append(anIter.Value());
1228         }
1229         if (SeqEdges.Length()==1) continue;
1230         TopoDS_Edge E;
1231         if ( MergeEdges(SeqEdges,aFace,Tol,myConcatBSplines,E) ) {
1232           // now we have only one edge - aChain.Value(1)
1233           // we have to replace old ListEdges with this new edge
1234           //aContext->Replace(SeqEdges(1),E);
1235           myContext->Replace(SeqEdges(1),E);
1236           Standard_Integer j;
1237           for (j = 2; j <= SeqEdges.Length(); j++) {
1238             //aContext->Remove(SeqEdges(j));
1239             myContext->Remove(SeqEdges(j));
1240             //myOldNewMap.Bind(SeqEdges(j), E);
1241           }
1242           //for history
1243           /*
1244           for (j = 1; j <= SeqEdges.Length(); j++)
1245           {
1246             if (!myOldNewMap.IsBound(SeqEdges(j)))
1247             {
1248               TopTools_ListOfShape EmptyList;
1249               myOldNewMap.Bind(SeqEdges(j), EmptyList);
1250             }
1251             myOldNewMap(SeqEdges(j)).Clear();
1252             myOldNewMap(SeqEdges(j)).Append(E);
1253           }
1254           */
1255           /////////////
1256           
1257           TopoDS_Face tmpF = TopoDS::Face(exp.Current());
1258           if ( !ChangedFaces.Contains(tmpF) )
1259             ChangedFaces.Add(tmpF);
1260           tmpF = TopoDS::Face(aMapFacesEdges.FindKey(i));
1261           if ( !ChangedFaces.Contains(tmpF) )
1262             ChangedFaces.Add(tmpF);
1263         }
1264       }
1265
1266     } // end processing each face
1267
1268     // fix changed faces and replace them in the local context
1269     for (Standard_Integer i=1; i<=ChangedFaces.Extent(); i++) {
1270       //TopoDS_Face aFace = TopoDS::Face(aContext->Apply(ChangedFaces.FindKey(i)));
1271       TopoDS_Face aFace = TopoDS::Face(myContext->Apply(ChangedFaces.FindKey(i)));
1272       Handle(ShapeFix_Face) sff = new ShapeFix_Face(aFace);
1273       sff->SetContext(myContext);
1274       sff->SetPrecision(myTolerance);
1275       sff->SetMinTolerance(myTolerance);
1276       sff->SetMaxTolerance(Max(1.,myTolerance*1000.));
1277       sff->Perform();
1278       TopoDS_Shape aNewFace = sff->Face();
1279       //aContext->Replace(aFace,aNewFace);
1280       myContext->Replace(aFace,aNewFace);
1281       //for history
1282       /*
1283       if (!myOldNewMap.IsBound(aFace))
1284       {
1285         TopTools_ListOfShape EmptyList;
1286         myOldNewMap.Bind(aFace, EmptyList);
1287       }
1288       myOldNewMap(aFace).Clear();
1289       myOldNewMap(aFace).Append(aNewFace);
1290       */
1291       /////////////
1292     }
1293
1294     if (ChangedFaces.Extent() > 0) {
1295       // fix changed shell and replace it in the local context
1296       //TopoDS_Shape aRes1 = aContext->Apply(aRes);
1297       TopoDS_Shape aRes1 = myContext->Apply(aRes);
1298       TopExp_Explorer expsh;
1299       for (expsh.Init(aRes1, TopAbs_SHELL); expsh.More(); expsh.Next()) {
1300         TopoDS_Shell aShell = TopoDS::Shell(expsh.Current());
1301         Handle(ShapeFix_Shell) sfsh = new ShapeFix_Shell;
1302         sfsh->FixFaceOrientation(aShell);
1303         TopoDS_Shape aNewShell = sfsh->Shell();
1304         //aContext->Replace(aShell,aNewShell);
1305         myContext->Replace(aShell,aNewShell);
1306         //for history
1307         /*
1308         if (!myOldNewMap.IsBound(aShell))
1309         {
1310           TopTools_ListOfShape EmptyList;
1311           myOldNewMap.Bind(aShell, EmptyList);
1312         }
1313         myOldNewMap(aShell).Clear();
1314         myOldNewMap(aShell).Append(aNewShell);
1315         */
1316         /////////////
1317       }
1318       //TopoDS_Shape aRes2 = aContext->Apply(aRes1);
1319       TopoDS_Shape aRes2 = myContext->Apply(aRes1);
1320       // put new solid into global context
1321       myContext->Replace(aSolid,aRes2);
1322       //for history
1323       /*
1324       if (!myOldNewMap.IsBound(aSolid))
1325       {
1326         TopTools_ListOfShape EmptyList;
1327         myOldNewMap.Bind(aSolid, EmptyList);
1328       }
1329       myOldNewMap(aSolid).Clear();
1330       myOldNewMap(aSolid).Append(aRes2);
1331       */
1332       /////////////
1333     }
1334
1335   } // end processing each solid
1336
1337   myShape = myContext->Apply(myShape);
1338 }
1339
1340 //=======================================================================
1341 //function : UnifyFacesAndEdges
1342 //purpose  : 
1343 //=======================================================================
1344
1345 void ShapeUpgrade_UnifySameDomain::UnifyFacesAndEdges()
1346 {
1347   UnifyFaces();
1348   
1349   /*
1350   ShapeUpgrade_RemoveLocations RemLoc;
1351   RemLoc.Remove(myShape);
1352   myShape = RemLoc.GetResult();
1353   */
1354
1355   UnifyEdges();
1356 }
1357
1358 //=======================================================================
1359 //function : Build
1360 //purpose  : builds the resulting shape
1361 //======================================================================
1362 void ShapeUpgrade_UnifySameDomain::Build() 
1363 {
1364   if (myUnifyFaces && myUnifyEdges)
1365     UnifyFacesAndEdges();
1366
1367   else if (myUnifyEdges)
1368     UnifyEdges();
1369   else if (myUnifyFaces)
1370     UnifyFaces();
1371
1372   //Done();
1373 }
1374
1375 //=======================================================================
1376 //function : Shape
1377 //purpose  : give the resulting shape
1378 //=======================================================================
1379 const TopoDS_Shape& ShapeUpgrade_UnifySameDomain::Shape() const
1380 {
1381   return myShape;
1382 }
1383
1384 //=======================================================================
1385 //function : Generated
1386 //purpose  : returns the new shape from the old one
1387 //=======================================================================
1388 TopoDS_Shape ShapeUpgrade_UnifySameDomain::Generated(const TopoDS_Shape& aShape) const
1389 {
1390   TopoDS_Shape aNewShape = myContext->Apply(aShape);
1391   /*
1392   if (aNewShape.IsNull())
1393     aNewShape = myOldNewMap(aShape);
1394   */
1395   
1396   return aNewShape;
1397 }