Salome HOME
Small fix in the dialog box
[modules/geom.git] / src / GEOMImpl / GEOMImpl_ShapeDriver.cxx
1 // Copyright (C) 2007-2012  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 // Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Lesser General Public License for more details.
15 //
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22
23 #include <GEOMImpl_ShapeDriver.hxx>
24
25 #include <GEOMImpl_IShapes.hxx>
26 #include <GEOMImpl_IVector.hxx>
27 #include <GEOMImpl_Types.hxx>
28 #include <GEOMImpl_Block6Explorer.hxx>
29
30 #include <GEOM_Function.hxx>
31
32 // OCCT Includes
33 #include <ShapeFix_Wire.hxx>
34 #include <ShapeFix_Edge.hxx>
35 #include <ShapeFix_Shape.hxx>
36
37 #include <BRep_Builder.hxx>
38 #include <BRep_Tool.hxx>
39 #include <BRepAdaptor_Curve.hxx>
40 #include <BRepAlgo_FaceRestrictor.hxx>
41 #include <BRepBuilderAPI_Copy.hxx>
42 #include <BRepBuilderAPI_Sewing.hxx>
43 #include <BRepBuilderAPI_MakeWire.hxx>
44 #include <BRepBuilderAPI_MakeEdge.hxx>
45 #include <BRepCheck.hxx>
46 #include <BRepCheck_Analyzer.hxx>
47 #include <BRepCheck_Shell.hxx>
48 #include <BRepClass3d_SolidClassifier.hxx>
49 #include <BRepLib.hxx>
50 #include <BRepLib_MakeEdge.hxx>
51 #include <BRepTools_WireExplorer.hxx>
52
53 #include <ShapeAnalysis_FreeBounds.hxx>
54
55 #include <TopAbs.hxx>
56 #include <TopExp.hxx>
57 #include <TopExp_Explorer.hxx>
58 #include <TopoDS.hxx>
59 #include <TopoDS_Shape.hxx>
60 #include <TopoDS_Edge.hxx>
61 #include <TopoDS_Wire.hxx>
62 #include <TopoDS_Shell.hxx>
63 #include <TopoDS_Solid.hxx>
64 #include <TopoDS_Compound.hxx>
65 #include <TopoDS_Iterator.hxx>
66
67 #include <TopTools_MapOfShape.hxx>
68 #include <TopTools_HSequenceOfShape.hxx>
69
70 #include <ElCLib.hxx>
71
72 #include <GCPnts_AbscissaPoint.hxx>
73
74 #include <Geom_TrimmedCurve.hxx>
75 #include <GeomAbs_CurveType.hxx>
76 #include <GeomConvert_CompCurveToBSplineCurve.hxx>
77 #include <GeomConvert.hxx>
78 #include <GeomLProp.hxx>
79
80 #include <TColStd_SequenceOfReal.hxx>
81 #include <TColStd_HSequenceOfTransient.hxx>
82 #include <TColStd_Array1OfReal.hxx>
83 #include <TColGeom_SequenceOfCurve.hxx>
84 #include <TColGeom_Array1OfBSplineCurve.hxx>
85 #include <TColGeom_HArray1OfBSplineCurve.hxx>
86
87 #include <Precision.hxx>
88
89 #include <Standard_NullObject.hxx>
90 #include <Standard_TypeMismatch.hxx>
91 #include <Standard_ConstructionError.hxx>
92
93 //modified by NIZNHY-PKV Wed Dec 28 13:48:20 2011f
94 //static
95 //  void KeepEdgesOrder(const Handle(TopTools_HSequenceOfShape)& aEdges,
96 //                    const Handle(TopTools_HSequenceOfShape)& aWires);
97 //modified by NIZNHY-PKV Wed Dec 28 13:48:23 2011t
98
99 //=======================================================================
100 //function : GetID
101 //purpose  :
102 //=======================================================================
103 const Standard_GUID& GEOMImpl_ShapeDriver::GetID()
104 {
105   static Standard_GUID aShapeDriver("FF1BBB54-5D14-4df2-980B-3A668264EA16");
106   return aShapeDriver;
107 }
108
109
110 //=======================================================================
111 //function : GEOMImpl_ShapeDriver
112 //purpose  :
113 //=======================================================================
114 GEOMImpl_ShapeDriver::GEOMImpl_ShapeDriver()
115 {
116 }
117
118 //=======================================================================
119 //function : Execute
120 //purpose  :
121 //=======================================================================
122 Standard_Integer GEOMImpl_ShapeDriver::Execute(TFunction_Logbook& log) const
123 {
124   if (Label().IsNull()) return 0;
125   Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
126
127   GEOMImpl_IShapes aCI (aFunction);
128   Standard_Integer aType = aFunction->GetType();
129
130   TopoDS_Shape aShape;
131   TCollection_AsciiString aWarning;
132
133   BRep_Builder B;
134
135   if (aType == WIRE_EDGES) {
136     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
137     TopoDS_Wire aWire;
138     B.MakeWire(aWire);
139
140     // add edges
141     for (unsigned int ind = 1; ind <= aShapes->Length(); ind++) {
142       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
143       TopoDS_Shape aShape_i = aRefShape->GetValue();
144       if (aShape_i.IsNull()) {
145         Standard_NullObject::Raise("Shape for wire construction is null");
146       }
147      if (aShape_i.ShapeType() == TopAbs_EDGE || aShape_i.ShapeType() == TopAbs_WIRE) {
148        TopExp_Explorer exp (aShape_i, TopAbs_EDGE);
149        for (; exp.More(); exp.Next())
150          B.Add(aWire, TopoDS::Edge(exp.Current()));
151      } else {
152        Standard_TypeMismatch::Raise
153          ("Shape for wire construction is neither an edge nor a wire");
154      }
155     }
156
157     // fix edges order
158     Handle(ShapeFix_Wire) aFW = new ShapeFix_Wire;
159     aFW->Load(aWire);
160     aFW->FixReorder();
161
162     if (aFW->StatusReorder(ShapeExtend_FAIL1)) {
163       Standard_ConstructionError::Raise("Wire construction failed: several loops detected");
164     } else if (aFW->StatusReorder(ShapeExtend_FAIL)) {
165       Standard_ConstructionError::Raise("Wire construction failed");
166     } else {
167     }
168
169     // IMP 0019766: Building a Wire from unconnected edges by introducing a tolerance
170     Standard_Real aTolerance = aCI.GetTolerance();
171     if (aTolerance < Precision::Confusion())
172       aTolerance = Precision::Confusion();
173
174     aFW->ClosedWireMode() = Standard_False;
175     aFW->FixConnected(aTolerance);
176     if (aFW->StatusConnected(ShapeExtend_FAIL)) {
177       Standard_ConstructionError::Raise("Wire construction failed: cannot build connected wire");
178     }
179     // IMP 0019766
180     if (aFW->StatusConnected(ShapeExtend_DONE3)) {
181       // Confused with <prec> but not Analyzer.Precision(), set the same
182       aFW->FixGapsByRangesMode() = Standard_True;
183       if (aFW->FixGaps3d()) {
184         Handle(ShapeExtend_WireData) sbwd = aFW->WireData();
185         Handle(ShapeFix_Edge) aFe = new ShapeFix_Edge;
186         for (Standard_Integer iedge = 1; iedge <= sbwd->NbEdges(); iedge++) {
187           TopoDS_Edge aEdge = TopoDS::Edge(sbwd->Edge(iedge));
188           aFe->FixVertexTolerance(aEdge);
189           aFe->FixSameParameter(aEdge);
190         }
191       }
192       else if (aFW->StatusGaps3d(ShapeExtend_FAIL)) {
193         Standard_ConstructionError::Raise("Wire construction failed: cannot fix 3d gaps");
194       }
195     }
196       aShape = aFW->WireAPIMake();
197   }
198   else if (aType == FACE_WIRE) {
199     Handle(GEOM_Function) aRefBase = aCI.GetBase();
200     TopoDS_Shape aShapeBase = aRefBase->GetValue();
201     if (aShapeBase.IsNull()) Standard_NullObject::Raise("Argument Shape is null");
202     TopoDS_Wire W;
203     if (aShapeBase.ShapeType() == TopAbs_WIRE) {
204       W = TopoDS::Wire(aShapeBase);
205       // check the wire is closed
206       TopoDS_Vertex aV1, aV2;
207       TopExp::Vertices(W, aV1, aV2);
208       if ( !aV1.IsNull() && !aV2.IsNull() && aV1.IsSame(aV2) )
209         aShapeBase.Closed(true);
210       else
211         Standard_NullObject::Raise
212           ("Shape for face construction is not closed");
213     }
214     else if (aShapeBase.ShapeType() == TopAbs_EDGE && aShapeBase.Closed()) {
215       BRepBuilderAPI_MakeWire MW;
216       MW.Add(TopoDS::Edge(aShapeBase));
217       if (!MW.IsDone()) {
218         Standard_ConstructionError::Raise("Wire construction failed");
219       }
220       W = MW;
221     }
222     else {
223       Standard_NullObject::Raise
224         ("Shape for face construction is neither a wire nor a closed edge");
225     }
226     aWarning = GEOMImpl_Block6Explorer::MakeFace(W, aCI.GetIsPlanar(), aShape);
227     if (aShape.IsNull()) {
228       Standard_ConstructionError::Raise("Face construction failed");
229     }
230   }
231   else if (aType == FACE_WIRES) {
232     // Try to build a face from a set of wires and edges
233     int ind;
234
235     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
236     int nbshapes = aShapes->Length();
237     if (nbshapes < 1) {
238       Standard_ConstructionError::Raise("No wires or edges given");
239     }
240
241     // 1. Extract all edges from the given arguments
242     TopTools_MapOfShape aMapEdges;
243     Handle(TopTools_HSequenceOfShape) aSeqEdgesIn = new TopTools_HSequenceOfShape;
244
245     for (ind = 1; ind <= nbshapes; ind++) {
246       Handle(GEOM_Function) aRefSh_i = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
247       TopoDS_Shape aSh_i = aRefSh_i->GetValue();
248
249       TopExp_Explorer anExpE_i (aSh_i, TopAbs_EDGE);
250       for (; anExpE_i.More(); anExpE_i.Next()) {
251         if (aMapEdges.Add(anExpE_i.Current())) {
252           aSeqEdgesIn->Append(anExpE_i.Current());
253         }
254       }
255     }
256
257     // 2. Connect edges to wires of maximum length
258     Handle(TopTools_HSequenceOfShape) aSeqWiresOut;
259     ShapeAnalysis_FreeBounds::ConnectEdgesToWires(aSeqEdgesIn, Precision::Confusion(),
260                                                   /*shared*/Standard_False, aSeqWiresOut);
261     //modified by NIZNHY-PKV Wed Dec 28 13:46:55 2011f
262     //KeepEdgesOrder(aSeqEdgesIn, aSeqWiresOut);
263     //modified by NIZNHY-PKV Wed Dec 28 13:46:59 2011t
264
265     // 3. Separate closed wires
266     Handle(TopTools_HSequenceOfShape) aSeqClosedWires = new TopTools_HSequenceOfShape;
267     Handle(TopTools_HSequenceOfShape) aSeqOpenWires = new TopTools_HSequenceOfShape;
268     for (ind = 1; ind <= aSeqWiresOut->Length(); ind++) {
269       if (aSeqWiresOut->Value(ind).Closed())
270         aSeqClosedWires->Append(aSeqWiresOut->Value(ind));
271       else
272         aSeqOpenWires->Append(aSeqWiresOut->Value(ind));
273     }
274
275     if (aSeqClosedWires->Length() < 1) {
276       Standard_ConstructionError::Raise
277         ("There is no closed contour can be built from the given arguments");
278     }
279
280     // 4. Build a face / list of faces from all the obtained closed wires
281
282     // 4.a. Basic face
283     TopoDS_Shape aFFace;
284     TopoDS_Wire aW1 = TopoDS::Wire(aSeqClosedWires->Value(1));
285     aWarning = GEOMImpl_Block6Explorer::MakeFace(aW1, aCI.GetIsPlanar(), aFFace);
286     if (aFFace.IsNull()) {
287       Standard_ConstructionError::Raise("Face construction failed");
288     }
289
290     // 4.b. Add other wires
291     if (aSeqClosedWires->Length() == 1) {
292       aShape = aFFace;
293     }
294     else {
295       TopoDS_Compound C;
296       BRep_Builder aBuilder;
297       aBuilder.MakeCompound(C);
298       BRepAlgo_FaceRestrictor FR;
299
300       TopAbs_Orientation OriF = aFFace.Orientation();
301       TopoDS_Shape aLocalS = aFFace.Oriented(TopAbs_FORWARD);
302       FR.Init(TopoDS::Face(aLocalS), Standard_False, Standard_True);
303
304       for (ind = 1; ind <= aSeqClosedWires->Length(); ind++) {
305         TopoDS_Wire aW = TopoDS::Wire(aSeqClosedWires->Value(ind));
306         FR.Add(aW);
307       }
308
309       FR.Perform();
310
311       if (FR.IsDone()) {
312         int k = 0;
313         TopoDS_Shape aFace;
314         for (; FR.More(); FR.Next()) {
315           aFace = FR.Current().Oriented(OriF);
316           aBuilder.Add(C, aFace);
317           k++;
318         }
319         if (k == 1) {
320           aShape = aFace;
321         } else {
322           aShape = C;
323         }
324       }
325     }
326
327     // 5. Add all open wires to the result
328     if (aSeqOpenWires->Length() > 0) {
329       //Standard_ConstructionError::Raise("There are some open wires");
330       TopoDS_Compound C;
331       BRep_Builder aBuilder;
332       if (aSeqClosedWires->Length() == 1) {
333         aBuilder.MakeCompound(C);
334         aBuilder.Add(C, aShape);
335       }
336       else {
337         C = TopoDS::Compound(aShape);
338       }
339
340       for (ind = 1; ind <= aSeqOpenWires->Length(); ind++) {
341         aBuilder.Add(C, aSeqOpenWires->Value(ind));
342       }
343
344       aShape = C;
345     }
346   }
347   else if (aType == SHELL_FACES) {
348     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
349     unsigned int ind, nbshapes = aShapes->Length();
350
351     // add faces
352     BRepBuilderAPI_Sewing aSewing(Precision::Confusion()*10.0);
353     for (ind = 1; ind <= nbshapes; ind++) {
354       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
355       TopoDS_Shape aShape_i = aRefShape->GetValue();
356       if (aShape_i.IsNull()) {
357         Standard_NullObject::Raise("Face for shell construction is null");
358       }
359       aSewing.Add(aShape_i);
360     }
361
362     aSewing.Perform();
363
364     TopoDS_Shape sh = aSewing.SewedShape();
365     if( sh.ShapeType()==TopAbs_FACE && nbshapes==1 ) {
366       // case for creation of shell from one face - PAL12722 (skl 26.06.2006)
367       TopoDS_Shell ss;
368       B.MakeShell(ss);
369       B.Add(ss,sh);
370       aShape = ss;
371     }
372     else {
373       //TopExp_Explorer exp (aSewing.SewedShape(), TopAbs_SHELL);
374       TopExp_Explorer exp (sh, TopAbs_SHELL);
375       Standard_Integer ish = 0;
376       for (; exp.More(); exp.Next()) {
377         aShape = exp.Current();
378         ish++;
379       }
380
381       if (ish != 1)
382         aShape = aSewing.SewedShape();
383     }
384
385   }
386   else if (aType == SOLID_SHELL) {
387     Handle(GEOM_Function) aRefShell = aCI.GetBase();
388     TopoDS_Shape aShapeShell = aRefShell->GetValue();
389     if (!aShapeShell.IsNull() && aShapeShell.ShapeType() == TopAbs_COMPOUND) {
390       TopoDS_Iterator It (aShapeShell, Standard_True, Standard_True);
391       if (It.More()) aShapeShell = It.Value();
392     }
393     if (aShapeShell.IsNull() || aShapeShell.ShapeType() != TopAbs_SHELL) {
394       Standard_NullObject::Raise("Shape for solid construction is null or not a shell");
395     }
396
397     BRepCheck_Shell chkShell(TopoDS::Shell(aShapeShell));
398     if (chkShell.Closed() == BRepCheck_NotClosed) return 0;
399
400     TopoDS_Solid Sol;
401     B.MakeSolid(Sol);
402     B.Add(Sol, aShapeShell);
403     BRepClass3d_SolidClassifier SC (Sol);
404     SC.PerformInfinitePoint(Precision::Confusion());
405     if (SC.State() == TopAbs_IN) {
406       B.MakeSolid(Sol);
407       B.Add(Sol, aShapeShell.Reversed());
408     }
409
410     aShape = Sol;
411
412   }
413   else if (aType == SOLID_SHELLS) {
414     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
415     unsigned int ind, nbshapes = aShapes->Length();
416     Standard_Integer ish = 0;
417     TopoDS_Solid Sol;
418     B.MakeSolid(Sol);
419
420     // add shapes
421     for (ind = 1; ind <= nbshapes; ind++) {
422       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
423       TopoDS_Shape aShapeShell = aRefShape->GetValue();
424       if (aShapeShell.IsNull()) {
425         Standard_NullObject::Raise("Shell for solid construction is null");
426       }
427       if (aShapeShell.ShapeType() == TopAbs_COMPOUND) {
428         TopoDS_Iterator It (aShapeShell, Standard_True, Standard_True);
429         if (It.More()) aShapeShell = It.Value();
430       }
431       if (aShapeShell.ShapeType() == TopAbs_SHELL) {
432         B.Add(Sol, aShapeShell);
433         ish++;
434       }
435     }
436     if (ish == 0) return 0;
437     BRepClass3d_SolidClassifier SC (Sol);
438     SC.PerformInfinitePoint(Precision::Confusion());
439     if (SC.State() == TopAbs_IN)
440       aShape = Sol.Reversed();
441     else
442       aShape = Sol;
443   }
444   else if (aType == COMPOUND_SHAPES) {
445     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
446     unsigned int ind, nbshapes = aShapes->Length();
447
448     // add shapes
449     TopoDS_Compound C;
450     B.MakeCompound(C);
451     for (ind = 1; ind <= nbshapes; ind++) {
452       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
453       TopoDS_Shape aShape_i = aRefShape->GetValue();
454       if (aShape_i.IsNull()) {
455         Standard_NullObject::Raise("Shape for compound construction is null");
456       }
457       B.Add(C, aShape_i);
458     }
459
460     aShape = C;
461
462   }
463   /*
464   else if (aType == REVERSE_ORIENTATION) {
465     Handle(GEOM_Function) aRefShape = aCI.GetBase();
466     TopoDS_Shape aShape_i = aRefShape->GetValue();
467     if (aShape_i.IsNull()) {
468        Standard_NullObject::Raise("Shape for reverse is null");
469     }
470
471     BRepBuilderAPI_Copy Copy(aShape_i);
472     if( Copy.IsDone() ) {
473       TopoDS_Shape tds = Copy.Shape();
474       if( tds.IsNull() ) {
475         Standard_ConstructionError::Raise("Orientation aborted : Can not reverse the shape");
476       }
477
478       if( tds.Orientation() == TopAbs_FORWARD)
479         tds.Orientation(TopAbs_REVERSED);
480       else
481         tds.Orientation(TopAbs_FORWARD);
482
483       aShape = tds;
484     }
485   }
486   */
487   else if (aType == EDGE_WIRE) {
488     Handle(GEOM_Function) aRefBase = aCI.GetBase();
489     TopoDS_Shape aWire = aRefBase->GetValue();
490     Standard_Real LinTol = aCI.GetTolerance();
491     Standard_Real AngTol = aCI.GetAngularTolerance();
492     if (aWire.IsNull()) Standard_NullObject::Raise("Argument Wire is null");
493
494     TopoDS_Edge ResEdge;
495
496     BRepLib::BuildCurves3d(aWire);
497     Handle(ShapeFix_Shape) Fixer = new ShapeFix_Shape(aWire);
498     Fixer->SetPrecision(LinTol);
499     Fixer->SetMaxTolerance(LinTol);
500     Fixer->Perform();
501     TopoDS_Wire theWire = TopoDS::Wire(Fixer->Shape());
502
503     TColGeom_SequenceOfCurve CurveSeq;
504     TopTools_SequenceOfShape LocSeq;
505     TColStd_SequenceOfReal FparSeq;
506     TColStd_SequenceOfReal LparSeq;
507     TColStd_SequenceOfReal TolSeq;
508     GeomAbs_CurveType CurType;
509     TopoDS_Vertex FirstVertex, LastVertex;
510     Standard_Boolean FinalReverse = Standard_False;
511
512     BRepTools_WireExplorer wexp(theWire) ;
513     for (; wexp.More(); wexp.Next())
514     {
515       TopoDS_Edge anEdge = wexp.Current();
516       Standard_Real fpar, lpar;
517       TopLoc_Location aLoc;
518       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aLoc, fpar, lpar);
519       if (aCurve.IsNull())
520         continue;
521
522       BRepAdaptor_Curve BAcurve(anEdge);
523       GeomAbs_CurveType aType = BAcurve.GetType();
524
525       Handle(Geom_Curve) aBasisCurve = BAcurve.Curve().Curve();
526
527       if (aBasisCurve->IsPeriodic())
528         ElCLib::AdjustPeriodic(aBasisCurve->FirstParameter(), aBasisCurve->LastParameter(),
529                                Precision::PConfusion(), fpar, lpar);
530
531       if (CurveSeq.IsEmpty())
532       {
533         CurveSeq.Append(aCurve);
534         TopoDS_Shape aLocShape;
535         aLocShape.Location(aLoc);
536         aLocShape.Orientation(wexp.Orientation());
537         LocSeq.Append(aLocShape);
538         FparSeq.Append(fpar);
539         LparSeq.Append(lpar);
540         CurType = aType;
541         FirstVertex = wexp.CurrentVertex();
542         if (anEdge.Orientation() == TopAbs_REVERSED)
543           FinalReverse = Standard_True;
544       }
545       else
546       {
547         Standard_Boolean Done = Standard_False;
548         Standard_Real NewFpar, NewLpar;
549         GeomAdaptor_Curve GAprevcurve(CurveSeq.Last());
550         TopoDS_Vertex CurVertex = wexp.CurrentVertex();
551         TopoDS_Vertex CurFirstVer = TopExp::FirstVertex(anEdge);
552         TopAbs_Orientation ConnectByOrigin = (CurVertex.IsSame(CurFirstVer))? TopAbs_FORWARD : TopAbs_REVERSED;
553         if (aCurve == CurveSeq.Last())
554         {
555           NewFpar = fpar;
556           NewLpar = lpar;
557           if (aBasisCurve->IsPeriodic())
558           {
559             if (NewLpar < NewFpar)
560               NewLpar += aBasisCurve->Period();
561             if (ConnectByOrigin == TopAbs_FORWARD)
562               ElCLib::AdjustPeriodic(FparSeq.Last(),
563                                      FparSeq.Last() + aBasisCurve->Period(),
564                                      Precision::PConfusion(), NewFpar, NewLpar);
565             else
566               ElCLib::AdjustPeriodic(FparSeq.Last() - aBasisCurve->Period(),
567                                      FparSeq.Last(),
568                                      Precision::PConfusion(), NewFpar, NewLpar);
569           }
570           Done = Standard_True;
571         }
572         else if (aType == CurType &&
573                  aType != GeomAbs_BezierCurve &&
574                  aType != GeomAbs_BSplineCurve &&
575                  aType != GeomAbs_OtherCurve)
576         {
577           switch (aType)
578           {
579           case GeomAbs_Line:
580             {
581               gp_Lin aLine    = BAcurve.Line();
582               gp_Lin PrevLine = GAprevcurve.Line();
583               if (aLine.Contains(PrevLine.Location(), LinTol) &&
584                   aLine.Direction().IsParallel(PrevLine.Direction(), AngTol))
585               {
586                 gp_Pnt P1 = ElCLib::Value(fpar, aLine);
587                 gp_Pnt P2 = ElCLib::Value(lpar, aLine);
588                 NewFpar = ElCLib::Parameter(PrevLine, P1);
589                 NewLpar = ElCLib::Parameter(PrevLine, P2);
590                 if (NewLpar < NewFpar)
591                 {
592                   Standard_Real MemNewFpar = NewFpar;
593                   NewFpar = NewLpar;
594                   NewLpar = MemNewFpar;
595                   ConnectByOrigin = TopAbs::Reverse(ConnectByOrigin);
596                 }
597                 Done = Standard_True;
598               }
599               break;
600             }
601           case GeomAbs_Circle:
602             {
603               gp_Circ aCircle    = BAcurve.Circle();
604               gp_Circ PrevCircle = GAprevcurve.Circle();
605               if (aCircle.Location().Distance(PrevCircle.Location()) <= LinTol &&
606                   Abs(aCircle.Radius() - PrevCircle.Radius()) <= LinTol &&
607                   aCircle.Axis().IsParallel(PrevCircle.Axis(), AngTol))
608               {
609                 if (aCircle.Axis().Direction() * PrevCircle.Axis().Direction() < 0.)
610                 {
611                   Standard_Real memfpar = fpar;
612                   fpar = lpar;
613                   lpar = memfpar;
614                   ConnectByOrigin = TopAbs::Reverse(ConnectByOrigin);
615                 }
616                 gp_Pnt P1 = ElCLib::Value(fpar, aCircle);
617                 gp_Pnt P2 = ElCLib::Value(lpar, aCircle);
618                 NewFpar = ElCLib::Parameter(PrevCircle, P1);
619                 NewLpar = ElCLib::Parameter(PrevCircle, P2);
620                 if (NewLpar < NewFpar)
621                   NewLpar += 2.*M_PI;
622                 //Standard_Real MemNewFpar = NewFpar, MemNewLpar =  NewLpar;
623                 if (ConnectByOrigin == TopAbs_FORWARD)
624                   ElCLib::AdjustPeriodic(FparSeq.Last(),
625                                          FparSeq.Last() + 2.*M_PI,
626                                          Precision::PConfusion(), NewFpar, NewLpar);
627                 else
628                   ElCLib::AdjustPeriodic(FparSeq.Last() - 2.*M_PI,
629                                          FparSeq.Last(),
630                                          Precision::PConfusion(), NewFpar, NewLpar);
631                 Done = Standard_True;
632               }
633               break;
634             }
635           case GeomAbs_Ellipse:
636             {
637               gp_Elips anEllipse   = BAcurve.Ellipse();
638               gp_Elips PrevEllipse = GAprevcurve.Ellipse();
639               if (anEllipse.Focus1().Distance(PrevEllipse.Focus1()) <= LinTol &&
640                   anEllipse.Focus2().Distance(PrevEllipse.Focus2()) <= LinTol &&
641                   Abs(anEllipse.MajorRadius() - PrevEllipse.MajorRadius()) <= LinTol &&
642                   Abs(anEllipse.MinorRadius() - PrevEllipse.MinorRadius()) <= LinTol &&
643                   anEllipse.Axis().IsParallel(PrevEllipse.Axis(), AngTol))
644               {
645                 if (anEllipse.Axis().Direction() * PrevEllipse.Axis().Direction() < 0.)
646                 {
647                   Standard_Real memfpar = fpar;
648                   fpar = lpar;
649                   lpar = memfpar;
650                   ConnectByOrigin = TopAbs::Reverse(ConnectByOrigin);
651                 }
652                 gp_Pnt P1 = ElCLib::Value(fpar, anEllipse);
653                 gp_Pnt P2 = ElCLib::Value(lpar, anEllipse);
654                 NewFpar = ElCLib::Parameter(PrevEllipse, P1);
655                 NewLpar = ElCLib::Parameter(PrevEllipse, P2);
656                 if (NewLpar < NewFpar)
657                   NewLpar += 2.*M_PI;
658                 if (ConnectByOrigin == TopAbs_FORWARD)
659                   ElCLib::AdjustPeriodic(FparSeq.Last(),
660                                          FparSeq.Last() + 2.*M_PI,
661                                          Precision::PConfusion(), NewFpar, NewLpar);
662                 else
663                   ElCLib::AdjustPeriodic(FparSeq.Last() - 2.*M_PI,
664                                          FparSeq.Last(),
665                                          Precision::PConfusion(), NewFpar, NewLpar);
666                 Done = Standard_True;
667               }
668               break;
669             }
670           case GeomAbs_Hyperbola:
671             {
672               gp_Hypr aHypr    = BAcurve.Hyperbola();
673               gp_Hypr PrevHypr = GAprevcurve.Hyperbola();
674               if (aHypr.Focus1().Distance(PrevHypr.Focus1()) <= LinTol &&
675                   aHypr.Focus2().Distance(PrevHypr.Focus2()) <= LinTol &&
676                   Abs(aHypr.MajorRadius() - PrevHypr.MajorRadius()) <= LinTol &&
677                   Abs(aHypr.MinorRadius() - PrevHypr.MinorRadius()) <= LinTol &&
678                   aHypr.Axis().IsParallel(PrevHypr.Axis(), AngTol))
679               {
680                 gp_Pnt P1 = ElCLib::Value(fpar, aHypr);
681                 gp_Pnt P2 = ElCLib::Value(lpar, aHypr);
682                 NewFpar = ElCLib::Parameter(PrevHypr, P1);
683                 NewLpar = ElCLib::Parameter(PrevHypr, P2);
684                 if (NewLpar < NewFpar)
685                 {
686                   Standard_Real MemNewFpar = NewFpar;
687                   NewFpar = NewLpar;
688                   NewLpar = MemNewFpar;
689                   ConnectByOrigin = TopAbs::Reverse(ConnectByOrigin);
690                 }
691                 Done = Standard_True;
692               }
693               break;
694             }
695           case GeomAbs_Parabola:
696             {
697               gp_Parab aParab    = BAcurve.Parabola();
698               gp_Parab PrevParab = GAprevcurve.Parabola();
699               if (aParab.Location().Distance(PrevParab.Location()) <= LinTol &&
700                   aParab.Focus().Distance(PrevParab.Focus()) <= LinTol &&
701                   Abs(aParab.Focal() - PrevParab.Focal()) <= LinTol &&
702                   aParab.Axis().IsParallel(PrevParab.Axis(), AngTol))
703               {
704                 gp_Pnt P1 = ElCLib::Value(fpar, aParab);
705                 gp_Pnt P2 = ElCLib::Value(lpar, aParab);
706                 NewFpar = ElCLib::Parameter(PrevParab, P1);
707                 NewLpar = ElCLib::Parameter(PrevParab, P2);
708                 if (NewLpar < NewFpar)
709                 {
710                   Standard_Real MemNewFpar = NewFpar;
711                   NewFpar = NewLpar;
712                   NewLpar = MemNewFpar;
713                   ConnectByOrigin = TopAbs::Reverse(ConnectByOrigin);
714                 }
715                 Done = Standard_True;
716               }
717               break;
718             }
719           } //end of switch (aType)
720         } // end of else if (aType == CurType && ...
721         if (Done)
722         {
723           if (NewFpar < FparSeq.Last())
724             FparSeq(FparSeq.Length()) = NewFpar;
725           else
726             LparSeq(LparSeq.Length()) = NewLpar;
727         }
728         else
729         {
730           CurveSeq.Append(aCurve);
731           TopoDS_Shape aLocShape;
732           aLocShape.Location(aLoc);
733           aLocShape.Orientation(wexp.Orientation());
734           LocSeq.Append(aLocShape);
735           FparSeq.Append(fpar);
736           LparSeq.Append(lpar);
737           TolSeq.Append(BRep_Tool::Tolerance(CurVertex));
738           CurType = aType;
739         }
740       } // end of else (CurveSeq.IsEmpty()) -> not first time
741     } // end for (; wexp.More(); wexp.Next())
742
743     LastVertex = wexp.CurrentVertex();
744     TolSeq.Append(BRep_Tool::Tolerance(LastVertex));
745
746     TopoDS_Vertex FirstVtx_final = (FinalReverse)? LastVertex : FirstVertex;
747     FirstVtx_final.Orientation(TopAbs_FORWARD);
748     TopoDS_Vertex LastVtx_final = (FinalReverse)? FirstVertex : LastVertex;
749     LastVtx_final.Orientation(TopAbs_REVERSED);
750
751     if (!CurveSeq.IsEmpty())
752     {
753       Standard_Integer nb_curve = CurveSeq.Length();   //number of curves
754       TColGeom_Array1OfBSplineCurve tab(0,nb_curve-1);                    //array of the curves
755       TColStd_Array1OfReal tabtolvertex(0,nb_curve-1); //(0,nb_curve-2);  //array of the tolerances
756
757       Standard_Integer i;
758
759       if (nb_curve > 1)
760       {
761         for (i = 1; i <= nb_curve; i++)
762         {
763           if (CurveSeq(i)->IsInstance(STANDARD_TYPE(Geom_TrimmedCurve)))
764             CurveSeq(i) = (*((Handle(Geom_TrimmedCurve)*)&(CurveSeq(i))))->BasisCurve();
765
766           Handle(Geom_TrimmedCurve) aTrCurve = new Geom_TrimmedCurve(CurveSeq(i), FparSeq(i), LparSeq(i));
767           tab(i-1) = GeomConvert::CurveToBSplineCurve(aTrCurve);
768           tab(i-1)->Transform(LocSeq(i).Location().Transformation());
769           GeomConvert::C0BSplineToC1BSplineCurve(tab(i-1), Precision::Confusion());
770           if (LocSeq(i).Orientation() == TopAbs_REVERSED)
771             tab(i-1)->Reverse();
772
773           //Temporary
774           //char* name = new char[100];
775           //sprintf(name, "c%d", i);
776           //DrawTrSurf::Set(name, tab(i-1));
777
778           if (i > 1)
779             tabtolvertex(i-2) = TolSeq(i-1);
780         } // end for (i = 1; i <= nb_curve; i++)
781         tabtolvertex(nb_curve-1) = TolSeq(TolSeq.Length());
782
783         Standard_Boolean closed_flag = Standard_False;
784         Standard_Real closed_tolerance = 0.;
785         if (FirstVertex.IsSame(LastVertex) &&
786             GeomLProp::Continuity(tab(0), tab(nb_curve-1),
787                                   tab(0)->FirstParameter(),
788                                   tab(nb_curve-1)->LastParameter(),
789                                   Standard_False, Standard_False, LinTol, AngTol) >= GeomAbs_G1)
790         {
791           closed_flag = Standard_True ;
792           closed_tolerance = BRep_Tool::Tolerance(FirstVertex);
793         }
794
795         Handle(TColGeom_HArray1OfBSplineCurve)  concatcurve;     //array of the concatenated curves
796         Handle(TColStd_HArray1OfInteger)        ArrayOfIndices;  //array of the remining Vertex
797         GeomConvert::ConcatC1(tab,
798                               tabtolvertex,
799                               ArrayOfIndices,
800                               concatcurve,
801                               closed_flag,
802                               closed_tolerance);   //C1 concatenation
803
804         if (concatcurve->Length() > 1)
805         {
806           GeomConvert_CompCurveToBSplineCurve Concat(concatcurve->Value(concatcurve->Lower()));
807
808           for (i = concatcurve->Lower()+1; i <= concatcurve->Upper(); i++)
809             Concat.Add( concatcurve->Value(i), LinTol, Standard_True );
810
811           concatcurve->SetValue(concatcurve->Lower(), Concat.BSplineCurve());
812         }
813         // rnc : prevents the driver from building an edge without C1 continuity
814         if (concatcurve->Value(concatcurve->Lower())->Continuity()==GeomAbs_C0){
815           Standard_ConstructionError::Raise("Construction aborted : The given Wire has sharp bends between some Edges, no valid Edge can be built");
816         }
817         ResEdge = BRepLib_MakeEdge(concatcurve->Value(concatcurve->Lower()),
818                                    FirstVtx_final, LastVtx_final,
819                                    concatcurve->Value(concatcurve->Lower())->FirstParameter(),
820                                    concatcurve->Value(concatcurve->Lower())->LastParameter());
821       }
822       else
823       {
824         if (CurveSeq(1)->IsInstance(STANDARD_TYPE(Geom_TrimmedCurve)))
825           CurveSeq(1) = (*((Handle(Geom_TrimmedCurve)*)&(CurveSeq(1))))->BasisCurve();
826
827         CurveSeq(1)->Transform(LocSeq(1).Location().Transformation());
828         ResEdge = BRepLib_MakeEdge(CurveSeq(1),
829                                    FirstVtx_final, LastVtx_final,
830                                    FparSeq(1), LparSeq(1));
831       }
832     }
833
834     if (FinalReverse)
835       ResEdge.Reverse();
836
837     aShape = ResEdge;
838   }
839   else if (aType == EDGE_CURVE_LENGTH) {
840     GEOMImpl_IVector aVI (aFunction);
841
842     // RefCurve
843     Handle(GEOM_Function) aRefCurve = aVI.GetPoint1();
844     if (aRefCurve.IsNull()) Standard_NullObject::Raise("Argument Curve is null");
845     TopoDS_Shape aRefShape1 = aRefCurve->GetValue();
846     if (aRefShape1.ShapeType() != TopAbs_EDGE) {
847       Standard_TypeMismatch::Raise
848         ("Edge On Curve creation aborted : curve shape is not an edge");
849     }
850     TopoDS_Edge aRefEdge = TopoDS::Edge(aRefShape1);
851     TopoDS_Vertex V1, V2;
852     TopExp::Vertices(aRefEdge, V1, V2, Standard_True);
853
854     // RefPoint
855     TopoDS_Vertex aRefVertex;
856     Handle(GEOM_Function) aRefPoint = aVI.GetPoint2();
857     if (aRefPoint.IsNull()) {
858       aRefVertex = V1;
859     }
860     else {
861       TopoDS_Shape aRefShape2 = aRefPoint->GetValue();
862       if (aRefShape2.ShapeType() != TopAbs_VERTEX) {
863         Standard_TypeMismatch::Raise
864           ("Edge On Curve creation aborted : start point shape is not a vertex");
865       }
866       aRefVertex = TopoDS::Vertex(aRefShape2);
867     }
868     gp_Pnt aRefPnt = BRep_Tool::Pnt(aRefVertex);
869
870     // Length
871     Standard_Real aLength = aVI.GetParameter();
872     //Standard_Real aCurveLength = IntTools::Length(aRefEdge);
873     //if (aLength > aCurveLength) {
874     //  Standard_ConstructionError::Raise
875     //    ("Edge On Curve creation aborted : given length is greater than edges length");
876     //}
877     if (fabs(aLength) < Precision::Confusion()) {
878       Standard_ConstructionError::Raise
879         ("Edge On Curve creation aborted : given length is smaller than Precision::Confusion()");
880     }
881
882     // Check orientation
883     Standard_Real UFirst, ULast;
884     Handle(Geom_Curve) EdgeCurve = BRep_Tool::Curve(aRefEdge, UFirst, ULast);
885     Handle(Geom_Curve) ReOrientedCurve = EdgeCurve;
886
887     Standard_Real dU = ULast - UFirst;
888     Standard_Real par1 = UFirst + 0.1 * dU;
889     Standard_Real par2 = ULast  - 0.1 * dU;
890
891     gp_Pnt P1 = EdgeCurve->Value(par1);
892     gp_Pnt P2 = EdgeCurve->Value(par2);
893
894     if (aRefPnt.SquareDistance(P2) < aRefPnt.SquareDistance(P1)) {
895       ReOrientedCurve = EdgeCurve->Reversed();
896       UFirst = EdgeCurve->ReversedParameter(ULast);
897     }
898
899     // Get the point by length
900     GeomAdaptor_Curve AdapCurve = GeomAdaptor_Curve(ReOrientedCurve);
901     GCPnts_AbscissaPoint anAbsPnt (AdapCurve, aLength, UFirst);
902     Standard_Real aParam = anAbsPnt.Parameter();
903
904     if (AdapCurve.IsClosed() && aLength < 0.0) {
905       Standard_Real aTmp = aParam;
906       aParam = UFirst;
907       UFirst = aTmp;
908     }
909
910     BRepBuilderAPI_MakeEdge aME (ReOrientedCurve, UFirst, aParam);
911     if (aME.IsDone())
912       aShape = aME.Shape();
913   }
914   else {
915   }
916
917   if (aShape.IsNull()) return 0;
918
919   // Check shape validity
920   BRepCheck_Analyzer ana (aShape, false);
921   if (!ana.IsValid()) {
922     //Standard_ConstructionError::Raise("Algorithm have produced an invalid shape result");
923   }
924
925   aFunction->SetValue(aShape);
926
927   log.SetTouched(Label());
928
929   if (!aWarning.IsEmpty())
930     Standard_Failure::Raise(aWarning.ToCString());
931
932   return 1;
933 }
934
935
936 //=======================================================================
937 //function :  GEOMImpl_ShapeDriver_Type_
938 //purpose  :
939 //=======================================================================
940 Standard_EXPORT Handle_Standard_Type& GEOMImpl_ShapeDriver_Type_()
941 {
942
943   static Handle_Standard_Type aType1 = STANDARD_TYPE(TFunction_Driver);
944   if ( aType1.IsNull()) aType1 = STANDARD_TYPE(TFunction_Driver);
945   static Handle_Standard_Type aType2 = STANDARD_TYPE(MMgt_TShared);
946   if ( aType2.IsNull()) aType2 = STANDARD_TYPE(MMgt_TShared);
947   static Handle_Standard_Type aType3 = STANDARD_TYPE(Standard_Transient);
948   if ( aType3.IsNull()) aType3 = STANDARD_TYPE(Standard_Transient);
949
950
951   static Handle_Standard_Transient _Ancestors[]= {aType1,aType2,aType3,NULL};
952   static Handle_Standard_Type _aType = new Standard_Type("GEOMImpl_ShapeDriver",
953                                                          sizeof(GEOMImpl_ShapeDriver),
954                                                          1,
955                                                          (Standard_Address)_Ancestors,
956                                                          (Standard_Address)NULL);
957
958   return _aType;
959 }
960
961 //=======================================================================
962 //function : DownCast
963 //purpose  :
964 //=======================================================================
965 const Handle(GEOMImpl_ShapeDriver) Handle(GEOMImpl_ShapeDriver)::DownCast(const Handle(Standard_Transient)& AnObject)
966 {
967   Handle(GEOMImpl_ShapeDriver) _anOtherObject;
968
969   if (!AnObject.IsNull()) {
970      if (AnObject->IsKind(STANDARD_TYPE(GEOMImpl_ShapeDriver))) {
971        _anOtherObject = Handle(GEOMImpl_ShapeDriver)((Handle(GEOMImpl_ShapeDriver)&)AnObject);
972      }
973   }
974
975   return _anOtherObject;
976 }
977
978 //modified by NIZNHY-PKV Wed Dec 28 13:48:31 2011f
979 #include <TopoDS_Iterator.hxx>
980 #include <TopTools_HSequenceOfShape.hxx>
981 #include <ShapeAnalysis_FreeBounds.hxx>
982 #include <TopTools_MapOfShape.hxx>
983 #include <TopTools_MapOfOrientedShape.hxx>
984 #include <BRep_Builder.hxx>
985 #include <TopoDS_Wire.hxx>
986
987 //=======================================================================
988 //function : KeepEdgesOrder
989 //purpose  : 
990 //=======================================================================
991 /*
992 void KeepEdgesOrder(const Handle(TopTools_HSequenceOfShape)& aEdges,
993                     const Handle(TopTools_HSequenceOfShape)& aWires)
994 {
995   Standard_Integer aNbWires, aNbEdges;
996   // 
997   if (aEdges.IsNull()) {
998     return;
999   }
1000   //
1001   if (aWires.IsNull()) {
1002     return;
1003   }
1004   //
1005   aNbEdges=aEdges->Length();
1006   aNbWires=aWires->Length();
1007   if (!aNbEdges || !aNbWires) {
1008     return;
1009   }
1010   //-----
1011   Standard_Boolean bClosed;
1012   Standard_Integer i, j;
1013   TopoDS_Wire aWy;
1014   TopoDS_Iterator aIt;
1015   BRep_Builder aBB;
1016   TopTools_MapOfOrientedShape aMEx;
1017   //
1018   for (i=1; i<=aNbWires; ++i) {
1019     const TopoDS_Shape& aWx=aWires->Value(i);
1020     //
1021     aMEx.Clear();
1022     aIt.Initialize (aWx);
1023     for (; aIt.More(); aIt.Next()) {
1024       const TopoDS_Shape& aEx=aIt.Value();
1025       aMEx.Add(aEx);
1026     }
1027     // aWy
1028     aBB.MakeWire (aWy);
1029     for (j=1; j<=aNbEdges; ++j) {
1030       const TopoDS_Shape& aE=aEdges->Value(j);
1031       if (aMEx.Contains(aE)) {
1032         aBB.Add(aWy, aE);
1033       }
1034     }
1035     //
1036     bClosed=aWx.Closed();
1037     aWy.Closed(bClosed);
1038     //
1039     aWires->Append(aWy);
1040   }// for (i=1; i<=aNbWires; ++i) {
1041   //
1042   aWires->Remove(1, aNbWires);
1043 }
1044 */
1045 //modified by NIZNHY-PKV Wed Dec 28 13:48:34 2011t