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