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