]> SALOME platform Git repositories - modules/geom.git/blob - src/GEOMImpl/GEOMImpl_ShapeDriver.cxx
Salome HOME
Mantis issue 0021483: EDF 1638 GEOM: Retrieve non blocks solids and faces from a...
[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     aShape = MakeEdgeFromWire(aWire, LinTol, AngTol);
495   }
496   else if (aType == EDGE_CURVE_LENGTH) {
497     GEOMImpl_IVector aVI (aFunction);
498
499     // RefCurve
500     Handle(GEOM_Function) aRefCurve = aVI.GetPoint1();
501     if (aRefCurve.IsNull()) Standard_NullObject::Raise("Argument Curve is null");
502     TopoDS_Shape aRefShape1 = aRefCurve->GetValue();
503     if (aRefShape1.ShapeType() != TopAbs_EDGE) {
504       Standard_TypeMismatch::Raise
505         ("Edge On Curve creation aborted : curve shape is not an edge");
506     }
507     TopoDS_Edge aRefEdge = TopoDS::Edge(aRefShape1);
508     TopoDS_Vertex V1, V2;
509     TopExp::Vertices(aRefEdge, V1, V2, Standard_True);
510
511     // RefPoint
512     TopoDS_Vertex aRefVertex;
513     Handle(GEOM_Function) aRefPoint = aVI.GetPoint2();
514     if (aRefPoint.IsNull()) {
515       aRefVertex = V1;
516     }
517     else {
518       TopoDS_Shape aRefShape2 = aRefPoint->GetValue();
519       if (aRefShape2.ShapeType() != TopAbs_VERTEX) {
520         Standard_TypeMismatch::Raise
521           ("Edge On Curve creation aborted : start point shape is not a vertex");
522       }
523       aRefVertex = TopoDS::Vertex(aRefShape2);
524     }
525     gp_Pnt aRefPnt = BRep_Tool::Pnt(aRefVertex);
526
527     // Length
528     Standard_Real aLength = aVI.GetParameter();
529     //Standard_Real aCurveLength = IntTools::Length(aRefEdge);
530     //if (aLength > aCurveLength) {
531     //  Standard_ConstructionError::Raise
532     //    ("Edge On Curve creation aborted : given length is greater than edges length");
533     //}
534     if (fabs(aLength) < Precision::Confusion()) {
535       Standard_ConstructionError::Raise
536         ("Edge On Curve creation aborted : given length is smaller than Precision::Confusion()");
537     }
538
539     // Check orientation
540     Standard_Real UFirst, ULast;
541     Handle(Geom_Curve) EdgeCurve = BRep_Tool::Curve(aRefEdge, UFirst, ULast);
542     Handle(Geom_Curve) ReOrientedCurve = EdgeCurve;
543
544     Standard_Real dU = ULast - UFirst;
545     Standard_Real par1 = UFirst + 0.1 * dU;
546     Standard_Real par2 = ULast  - 0.1 * dU;
547
548     gp_Pnt P1 = EdgeCurve->Value(par1);
549     gp_Pnt P2 = EdgeCurve->Value(par2);
550
551     if (aRefPnt.SquareDistance(P2) < aRefPnt.SquareDistance(P1)) {
552       ReOrientedCurve = EdgeCurve->Reversed();
553       UFirst = EdgeCurve->ReversedParameter(ULast);
554     }
555
556     // Get the point by length
557     GeomAdaptor_Curve AdapCurve = GeomAdaptor_Curve(ReOrientedCurve);
558     GCPnts_AbscissaPoint anAbsPnt (AdapCurve, aLength, UFirst);
559     Standard_Real aParam = anAbsPnt.Parameter();
560
561     if (AdapCurve.IsClosed() && aLength < 0.0) {
562       Standard_Real aTmp = aParam;
563       aParam = UFirst;
564       UFirst = aTmp;
565     }
566
567     BRepBuilderAPI_MakeEdge aME (ReOrientedCurve, UFirst, aParam);
568     if (aME.IsDone())
569       aShape = aME.Shape();
570   }
571   else {
572   }
573
574   if (aShape.IsNull()) return 0;
575
576   // Check shape validity
577   BRepCheck_Analyzer ana (aShape, false);
578   if (!ana.IsValid()) {
579     //Standard_ConstructionError::Raise("Algorithm have produced an invalid shape result");
580   }
581
582   aFunction->SetValue(aShape);
583
584   log.SetTouched(Label());
585
586   if (!aWarning.IsEmpty())
587     Standard_Failure::Raise(aWarning.ToCString());
588
589   return 1;
590 }
591
592 TopoDS_Edge GEOMImpl_ShapeDriver::MakeEdgeFromWire(const TopoDS_Shape& aWire,
593                                                    const Standard_Real LinTol,
594                                                    const Standard_Real AngTol)
595 {
596     TopoDS_Edge ResEdge;
597
598     BRepLib::BuildCurves3d(aWire);
599     Handle(ShapeFix_Shape) Fixer = new ShapeFix_Shape(aWire);
600     Fixer->SetPrecision(LinTol);
601     Fixer->SetMaxTolerance(LinTol);
602     Fixer->Perform();
603     TopoDS_Wire theWire = TopoDS::Wire(Fixer->Shape());
604
605     TColGeom_SequenceOfCurve CurveSeq;
606     TopTools_SequenceOfShape LocSeq;
607     TColStd_SequenceOfReal FparSeq;
608     TColStd_SequenceOfReal LparSeq;
609     TColStd_SequenceOfReal TolSeq;
610     GeomAbs_CurveType CurType;
611     TopoDS_Vertex FirstVertex, LastVertex;
612     Standard_Boolean FinalReverse = Standard_False;
613
614     BRepTools_WireExplorer wexp(theWire) ;
615     for (; wexp.More(); wexp.Next())
616     {
617       TopoDS_Edge anEdge = wexp.Current();
618       Standard_Real fpar, lpar;
619       TopLoc_Location aLoc;
620       Handle(Geom_Curve) aCurve = BRep_Tool::Curve(anEdge, aLoc, fpar, lpar);
621       if (aCurve.IsNull())
622         continue;
623
624       BRepAdaptor_Curve BAcurve(anEdge);
625       GeomAbs_CurveType aType = BAcurve.GetType();
626
627       Handle(Geom_Curve) aBasisCurve = BAcurve.Curve().Curve();
628
629       if (aBasisCurve->IsPeriodic())
630         ElCLib::AdjustPeriodic(aBasisCurve->FirstParameter(), aBasisCurve->LastParameter(),
631                                Precision::PConfusion(), fpar, lpar);
632
633       if (CurveSeq.IsEmpty())
634       {
635         CurveSeq.Append(aCurve);
636         TopoDS_Shape aLocShape;
637         aLocShape.Location(aLoc);
638         aLocShape.Orientation(wexp.Orientation());
639         LocSeq.Append(aLocShape);
640         FparSeq.Append(fpar);
641         LparSeq.Append(lpar);
642         CurType = aType;
643         FirstVertex = wexp.CurrentVertex();
644         if (anEdge.Orientation() == TopAbs_REVERSED)
645           FinalReverse = Standard_True;
646       }
647       else
648       {
649         Standard_Boolean Done = Standard_False;
650         Standard_Real NewFpar, NewLpar;
651         GeomAdaptor_Curve GAprevcurve(CurveSeq.Last());
652         TopoDS_Vertex CurVertex = wexp.CurrentVertex();
653         TopoDS_Vertex CurFirstVer = TopExp::FirstVertex(anEdge);
654         TopAbs_Orientation ConnectByOrigin = (CurVertex.IsSame(CurFirstVer))? TopAbs_FORWARD : TopAbs_REVERSED;
655         if (aCurve == CurveSeq.Last())
656         {
657           NewFpar = fpar;
658           NewLpar = lpar;
659           if (aBasisCurve->IsPeriodic())
660           {
661             if (NewLpar < NewFpar)
662               NewLpar += aBasisCurve->Period();
663             if (ConnectByOrigin == TopAbs_FORWARD)
664               ElCLib::AdjustPeriodic(FparSeq.Last(),
665                                      FparSeq.Last() + aBasisCurve->Period(),
666                                      Precision::PConfusion(), NewFpar, NewLpar);
667             else
668               ElCLib::AdjustPeriodic(FparSeq.Last() - aBasisCurve->Period(),
669                                      FparSeq.Last(),
670                                      Precision::PConfusion(), NewFpar, NewLpar);
671           }
672           Done = Standard_True;
673         }
674         else if (aType == CurType &&
675                  aType != GeomAbs_BezierCurve &&
676                  aType != GeomAbs_BSplineCurve &&
677                  aType != GeomAbs_OtherCurve)
678         {
679           switch (aType)
680           {
681           case GeomAbs_Line:
682             {
683               gp_Lin aLine    = BAcurve.Line();
684               gp_Lin PrevLine = GAprevcurve.Line();
685               if (aLine.Contains(PrevLine.Location(), LinTol) &&
686                   aLine.Direction().IsParallel(PrevLine.Direction(), AngTol))
687               {
688                 gp_Pnt P1 = ElCLib::Value(fpar, aLine);
689                 gp_Pnt P2 = ElCLib::Value(lpar, aLine);
690                 NewFpar = ElCLib::Parameter(PrevLine, P1);
691                 NewLpar = ElCLib::Parameter(PrevLine, P2);
692                 if (NewLpar < NewFpar)
693                 {
694                   Standard_Real MemNewFpar = NewFpar;
695                   NewFpar = NewLpar;
696                   NewLpar = MemNewFpar;
697                   ConnectByOrigin = TopAbs::Reverse(ConnectByOrigin);
698                 }
699                 Done = Standard_True;
700               }
701               break;
702             }
703           case GeomAbs_Circle:
704             {
705               gp_Circ aCircle    = BAcurve.Circle();
706               gp_Circ PrevCircle = GAprevcurve.Circle();
707               if (aCircle.Location().Distance(PrevCircle.Location()) <= LinTol &&
708                   Abs(aCircle.Radius() - PrevCircle.Radius()) <= LinTol &&
709                   aCircle.Axis().IsParallel(PrevCircle.Axis(), AngTol))
710               {
711                 if (aCircle.Axis().Direction() * PrevCircle.Axis().Direction() < 0.)
712                 {
713                   Standard_Real memfpar = fpar;
714                   fpar = lpar;
715                   lpar = memfpar;
716                   ConnectByOrigin = TopAbs::Reverse(ConnectByOrigin);
717                 }
718                 gp_Pnt P1 = ElCLib::Value(fpar, aCircle);
719                 gp_Pnt P2 = ElCLib::Value(lpar, aCircle);
720                 NewFpar = ElCLib::Parameter(PrevCircle, P1);
721                 NewLpar = ElCLib::Parameter(PrevCircle, P2);
722                 if (NewLpar < NewFpar)
723                   NewLpar += 2.*M_PI;
724                 //Standard_Real MemNewFpar = NewFpar, MemNewLpar =  NewLpar;
725                 if (ConnectByOrigin == TopAbs_FORWARD)
726                   ElCLib::AdjustPeriodic(FparSeq.Last(),
727                                          FparSeq.Last() + 2.*M_PI,
728                                          Precision::PConfusion(), NewFpar, NewLpar);
729                 else
730                   ElCLib::AdjustPeriodic(FparSeq.Last() - 2.*M_PI,
731                                          FparSeq.Last(),
732                                          Precision::PConfusion(), NewFpar, NewLpar);
733                 Done = Standard_True;
734               }
735               break;
736             }
737           case GeomAbs_Ellipse:
738             {
739               gp_Elips anEllipse   = BAcurve.Ellipse();
740               gp_Elips PrevEllipse = GAprevcurve.Ellipse();
741               if (anEllipse.Focus1().Distance(PrevEllipse.Focus1()) <= LinTol &&
742                   anEllipse.Focus2().Distance(PrevEllipse.Focus2()) <= LinTol &&
743                   Abs(anEllipse.MajorRadius() - PrevEllipse.MajorRadius()) <= LinTol &&
744                   Abs(anEllipse.MinorRadius() - PrevEllipse.MinorRadius()) <= LinTol &&
745                   anEllipse.Axis().IsParallel(PrevEllipse.Axis(), AngTol))
746               {
747                 if (anEllipse.Axis().Direction() * PrevEllipse.Axis().Direction() < 0.)
748                 {
749                   Standard_Real memfpar = fpar;
750                   fpar = lpar;
751                   lpar = memfpar;
752                   ConnectByOrigin = TopAbs::Reverse(ConnectByOrigin);
753                 }
754                 gp_Pnt P1 = ElCLib::Value(fpar, anEllipse);
755                 gp_Pnt P2 = ElCLib::Value(lpar, anEllipse);
756                 NewFpar = ElCLib::Parameter(PrevEllipse, P1);
757                 NewLpar = ElCLib::Parameter(PrevEllipse, P2);
758                 if (NewLpar < NewFpar)
759                   NewLpar += 2.*M_PI;
760                 if (ConnectByOrigin == TopAbs_FORWARD)
761                   ElCLib::AdjustPeriodic(FparSeq.Last(),
762                                          FparSeq.Last() + 2.*M_PI,
763                                          Precision::PConfusion(), NewFpar, NewLpar);
764                 else
765                   ElCLib::AdjustPeriodic(FparSeq.Last() - 2.*M_PI,
766                                          FparSeq.Last(),
767                                          Precision::PConfusion(), NewFpar, NewLpar);
768                 Done = Standard_True;
769               }
770               break;
771             }
772           case GeomAbs_Hyperbola:
773             {
774               gp_Hypr aHypr    = BAcurve.Hyperbola();
775               gp_Hypr PrevHypr = GAprevcurve.Hyperbola();
776               if (aHypr.Focus1().Distance(PrevHypr.Focus1()) <= LinTol &&
777                   aHypr.Focus2().Distance(PrevHypr.Focus2()) <= LinTol &&
778                   Abs(aHypr.MajorRadius() - PrevHypr.MajorRadius()) <= LinTol &&
779                   Abs(aHypr.MinorRadius() - PrevHypr.MinorRadius()) <= LinTol &&
780                   aHypr.Axis().IsParallel(PrevHypr.Axis(), AngTol))
781               {
782                 gp_Pnt P1 = ElCLib::Value(fpar, aHypr);
783                 gp_Pnt P2 = ElCLib::Value(lpar, aHypr);
784                 NewFpar = ElCLib::Parameter(PrevHypr, P1);
785                 NewLpar = ElCLib::Parameter(PrevHypr, P2);
786                 if (NewLpar < NewFpar)
787                 {
788                   Standard_Real MemNewFpar = NewFpar;
789                   NewFpar = NewLpar;
790                   NewLpar = MemNewFpar;
791                   ConnectByOrigin = TopAbs::Reverse(ConnectByOrigin);
792                 }
793                 Done = Standard_True;
794               }
795               break;
796             }
797           case GeomAbs_Parabola:
798             {
799               gp_Parab aParab    = BAcurve.Parabola();
800               gp_Parab PrevParab = GAprevcurve.Parabola();
801               if (aParab.Location().Distance(PrevParab.Location()) <= LinTol &&
802                   aParab.Focus().Distance(PrevParab.Focus()) <= LinTol &&
803                   Abs(aParab.Focal() - PrevParab.Focal()) <= LinTol &&
804                   aParab.Axis().IsParallel(PrevParab.Axis(), AngTol))
805               {
806                 gp_Pnt P1 = ElCLib::Value(fpar, aParab);
807                 gp_Pnt P2 = ElCLib::Value(lpar, aParab);
808                 NewFpar = ElCLib::Parameter(PrevParab, P1);
809                 NewLpar = ElCLib::Parameter(PrevParab, P2);
810                 if (NewLpar < NewFpar)
811                 {
812                   Standard_Real MemNewFpar = NewFpar;
813                   NewFpar = NewLpar;
814                   NewLpar = MemNewFpar;
815                   ConnectByOrigin = TopAbs::Reverse(ConnectByOrigin);
816                 }
817                 Done = Standard_True;
818               }
819               break;
820             }
821           } //end of switch (aType)
822         } // end of else if (aType == CurType && ...
823         if (Done)
824         {
825           if (NewFpar < FparSeq.Last())
826             FparSeq(FparSeq.Length()) = NewFpar;
827           else
828             LparSeq(LparSeq.Length()) = NewLpar;
829         }
830         else
831         {
832           CurveSeq.Append(aCurve);
833           TopoDS_Shape aLocShape;
834           aLocShape.Location(aLoc);
835           aLocShape.Orientation(wexp.Orientation());
836           LocSeq.Append(aLocShape);
837           FparSeq.Append(fpar);
838           LparSeq.Append(lpar);
839           TolSeq.Append(BRep_Tool::Tolerance(CurVertex));
840           CurType = aType;
841         }
842       } // end of else (CurveSeq.IsEmpty()) -> not first time
843     } // end for (; wexp.More(); wexp.Next())
844
845     LastVertex = wexp.CurrentVertex();
846     TolSeq.Append(BRep_Tool::Tolerance(LastVertex));
847
848     TopoDS_Vertex FirstVtx_final = (FinalReverse)? LastVertex : FirstVertex;
849     FirstVtx_final.Orientation(TopAbs_FORWARD);
850     TopoDS_Vertex LastVtx_final = (FinalReverse)? FirstVertex : LastVertex;
851     LastVtx_final.Orientation(TopAbs_REVERSED);
852
853     if (!CurveSeq.IsEmpty())
854     {
855       Standard_Integer nb_curve = CurveSeq.Length();   //number of curves
856       TColGeom_Array1OfBSplineCurve tab(0,nb_curve-1);                    //array of the curves
857       TColStd_Array1OfReal tabtolvertex(0,nb_curve-1); //(0,nb_curve-2);  //array of the tolerances
858
859       Standard_Integer i;
860
861       if (nb_curve > 1)
862       {
863         for (i = 1; i <= nb_curve; i++)
864         {
865           if (CurveSeq(i)->IsInstance(STANDARD_TYPE(Geom_TrimmedCurve)))
866             CurveSeq(i) = (*((Handle(Geom_TrimmedCurve)*)&(CurveSeq(i))))->BasisCurve();
867
868           Handle(Geom_TrimmedCurve) aTrCurve = new Geom_TrimmedCurve(CurveSeq(i), FparSeq(i), LparSeq(i));
869           tab(i-1) = GeomConvert::CurveToBSplineCurve(aTrCurve);
870           tab(i-1)->Transform(LocSeq(i).Location().Transformation());
871           GeomConvert::C0BSplineToC1BSplineCurve(tab(i-1), Precision::Confusion());
872           if (LocSeq(i).Orientation() == TopAbs_REVERSED)
873             tab(i-1)->Reverse();
874
875           //Temporary
876           //char* name = new char[100];
877           //sprintf(name, "c%d", i);
878           //DrawTrSurf::Set(name, tab(i-1));
879
880           if (i > 1)
881             tabtolvertex(i-2) = TolSeq(i-1);
882         } // end for (i = 1; i <= nb_curve; i++)
883         tabtolvertex(nb_curve-1) = TolSeq(TolSeq.Length());
884
885         Standard_Boolean closed_flag = Standard_False;
886         Standard_Real closed_tolerance = 0.;
887         if (FirstVertex.IsSame(LastVertex) &&
888             GeomLProp::Continuity(tab(0), tab(nb_curve-1),
889                                   tab(0)->FirstParameter(),
890                                   tab(nb_curve-1)->LastParameter(),
891                                   Standard_False, Standard_False, LinTol, AngTol) >= GeomAbs_G1)
892         {
893           closed_flag = Standard_True ;
894           closed_tolerance = BRep_Tool::Tolerance(FirstVertex);
895         }
896
897         Handle(TColGeom_HArray1OfBSplineCurve)  concatcurve;     //array of the concatenated curves
898         Handle(TColStd_HArray1OfInteger)        ArrayOfIndices;  //array of the remining Vertex
899         GeomConvert::ConcatC1(tab,
900                               tabtolvertex,
901                               ArrayOfIndices,
902                               concatcurve,
903                               closed_flag,
904                               closed_tolerance);   //C1 concatenation
905
906         if (concatcurve->Length() > 1)
907         {
908           GeomConvert_CompCurveToBSplineCurve Concat(concatcurve->Value(concatcurve->Lower()));
909
910           for (i = concatcurve->Lower()+1; i <= concatcurve->Upper(); i++)
911             Concat.Add( concatcurve->Value(i), LinTol, Standard_True );
912
913           concatcurve->SetValue(concatcurve->Lower(), Concat.BSplineCurve());
914         }
915         // rnc : prevents the driver from building an edge without C1 continuity
916         if (concatcurve->Value(concatcurve->Lower())->Continuity()==GeomAbs_C0){
917           Standard_ConstructionError::Raise("Construction aborted : The given Wire has sharp bends between some Edges, no valid Edge can be built");
918         }
919         ResEdge = BRepLib_MakeEdge(concatcurve->Value(concatcurve->Lower()),
920                                    FirstVtx_final, LastVtx_final,
921                                    concatcurve->Value(concatcurve->Lower())->FirstParameter(),
922                                    concatcurve->Value(concatcurve->Lower())->LastParameter());
923       }
924       else
925       {
926         if (CurveSeq(1)->IsInstance(STANDARD_TYPE(Geom_TrimmedCurve)))
927           CurveSeq(1) = (*((Handle(Geom_TrimmedCurve)*)&(CurveSeq(1))))->BasisCurve();
928
929         CurveSeq(1)->Transform(LocSeq(1).Location().Transformation());
930         ResEdge = BRepLib_MakeEdge(CurveSeq(1),
931                                    FirstVtx_final, LastVtx_final,
932                                    FparSeq(1), LparSeq(1));
933       }
934     }
935
936     if (FinalReverse)
937       ResEdge.Reverse();
938
939     return ResEdge;
940 }
941
942 //=======================================================================
943 //function :  GEOMImpl_ShapeDriver_Type_
944 //purpose  :
945 //=======================================================================
946 Standard_EXPORT Handle_Standard_Type& GEOMImpl_ShapeDriver_Type_()
947 {
948
949   static Handle_Standard_Type aType1 = STANDARD_TYPE(TFunction_Driver);
950   if ( aType1.IsNull()) aType1 = STANDARD_TYPE(TFunction_Driver);
951   static Handle_Standard_Type aType2 = STANDARD_TYPE(MMgt_TShared);
952   if ( aType2.IsNull()) aType2 = STANDARD_TYPE(MMgt_TShared);
953   static Handle_Standard_Type aType3 = STANDARD_TYPE(Standard_Transient);
954   if ( aType3.IsNull()) aType3 = STANDARD_TYPE(Standard_Transient);
955
956
957   static Handle_Standard_Transient _Ancestors[]= {aType1,aType2,aType3,NULL};
958   static Handle_Standard_Type _aType = new Standard_Type("GEOMImpl_ShapeDriver",
959                                                          sizeof(GEOMImpl_ShapeDriver),
960                                                          1,
961                                                          (Standard_Address)_Ancestors,
962                                                          (Standard_Address)NULL);
963
964   return _aType;
965 }
966
967 //=======================================================================
968 //function : DownCast
969 //purpose  :
970 //=======================================================================
971 const Handle(GEOMImpl_ShapeDriver) Handle(GEOMImpl_ShapeDriver)::DownCast(const Handle(Standard_Transient)& AnObject)
972 {
973   Handle(GEOMImpl_ShapeDriver) _anOtherObject;
974
975   if (!AnObject.IsNull()) {
976      if (AnObject->IsKind(STANDARD_TYPE(GEOMImpl_ShapeDriver))) {
977        _anOtherObject = Handle(GEOMImpl_ShapeDriver)((Handle(GEOMImpl_ShapeDriver)&)AnObject);
978      }
979   }
980
981   return _anOtherObject;
982 }
983
984 //modified by NIZNHY-PKV Wed Dec 28 13:48:31 2011f
985 #include <TopoDS_Iterator.hxx>
986 #include <TopTools_HSequenceOfShape.hxx>
987 #include <ShapeAnalysis_FreeBounds.hxx>
988 #include <TopTools_MapOfShape.hxx>
989 #include <TopTools_MapOfOrientedShape.hxx>
990 #include <BRep_Builder.hxx>
991 #include <TopoDS_Wire.hxx>
992
993 //=======================================================================
994 //function : KeepEdgesOrder
995 //purpose  : 
996 //=======================================================================
997 /*
998 void KeepEdgesOrder(const Handle(TopTools_HSequenceOfShape)& aEdges,
999                     const Handle(TopTools_HSequenceOfShape)& aWires)
1000 {
1001   Standard_Integer aNbWires, aNbEdges;
1002   // 
1003   if (aEdges.IsNull()) {
1004     return;
1005   }
1006   //
1007   if (aWires.IsNull()) {
1008     return;
1009   }
1010   //
1011   aNbEdges=aEdges->Length();
1012   aNbWires=aWires->Length();
1013   if (!aNbEdges || !aNbWires) {
1014     return;
1015   }
1016   //-----
1017   Standard_Boolean bClosed;
1018   Standard_Integer i, j;
1019   TopoDS_Wire aWy;
1020   TopoDS_Iterator aIt;
1021   BRep_Builder aBB;
1022   TopTools_MapOfOrientedShape aMEx;
1023   //
1024   for (i=1; i<=aNbWires; ++i) {
1025     const TopoDS_Shape& aWx=aWires->Value(i);
1026     //
1027     aMEx.Clear();
1028     aIt.Initialize (aWx);
1029     for (; aIt.More(); aIt.Next()) {
1030       const TopoDS_Shape& aEx=aIt.Value();
1031       aMEx.Add(aEx);
1032     }
1033     // aWy
1034     aBB.MakeWire (aWy);
1035     for (j=1; j<=aNbEdges; ++j) {
1036       const TopoDS_Shape& aE=aEdges->Value(j);
1037       if (aMEx.Contains(aE)) {
1038         aBB.Add(aWy, aE);
1039       }
1040     }
1041     //
1042     bClosed=aWx.Closed();
1043     aWy.Closed(bClosed);
1044     //
1045     aWires->Append(aWy);
1046   }// for (i=1; i<=aNbWires; ++i) {
1047   //
1048   aWires->Remove(1, aNbWires);
1049 }
1050 */
1051 //modified by NIZNHY-PKV Wed Dec 28 13:48:34 2011t