Salome HOME
Merge from V5_1_3_BR branch (07/12/09)
[modules/geom.git] / src / GEOMImpl / GEOMImpl_ShapeDriver.cxx
1 //  Copyright (C) 2007-2008  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_Types.hxx>
26 #include <GEOMImpl_Block6Explorer.hxx>
27
28 #include <GEOM_Function.hxx>
29
30 // OCCT Includes
31 #include <ShapeFix_Wire.hxx>
32 #include <ShapeFix_Edge.hxx>
33
34 #include <BRep_Tool.hxx>
35 #include <BRep_Builder.hxx>
36 #include <BRepAlgo_FaceRestrictor.hxx>
37 #include <BRepBuilderAPI_Sewing.hxx>
38 #include <BRepBuilderAPI_Copy.hxx>
39 #include <BRepCheck.hxx>
40 #include <BRepCheck_Analyzer.hxx>
41 #include <BRepCheck_Shell.hxx>
42 #include <BRepClass3d_SolidClassifier.hxx>
43 #include <BRepBuilderAPI_MakeWire.hxx>
44 #include <BRepBuilderAPI_Sewing.hxx>
45
46 #include <ShapeAnalysis_FreeBounds.hxx>
47
48 #include <TopAbs.hxx>
49 #include <TopoDS.hxx>
50 #include <TopoDS_Shape.hxx>
51 #include <TopoDS_Edge.hxx>
52 #include <TopoDS_Wire.hxx>
53 #include <TopoDS_Shell.hxx>
54 #include <TopoDS_Solid.hxx>
55 #include <TopoDS_Compound.hxx>
56 #include <TopoDS_Iterator.hxx>
57 #include <TopExp.hxx>
58 #include <TopExp_Explorer.hxx>
59
60 #include <TopTools_MapOfShape.hxx>
61 #include <TopTools_HSequenceOfShape.hxx>
62
63 #include <TColStd_HSequenceOfTransient.hxx>
64
65 #include <Precision.hxx>
66 #include <Standard_NullObject.hxx>
67 #include <Standard_TypeMismatch.hxx>
68 #include <Standard_ConstructionError.hxx>
69
70 //=======================================================================
71 //function : GetID
72 //purpose  :
73 //=======================================================================
74 const Standard_GUID& GEOMImpl_ShapeDriver::GetID()
75 {
76   static Standard_GUID aShapeDriver("FF1BBB54-5D14-4df2-980B-3A668264EA16");
77   return aShapeDriver;
78 }
79
80
81 //=======================================================================
82 //function : GEOMImpl_ShapeDriver
83 //purpose  :
84 //=======================================================================
85 GEOMImpl_ShapeDriver::GEOMImpl_ShapeDriver()
86 {
87 }
88
89 //=======================================================================
90 //function : Execute
91 //purpose  :
92 //=======================================================================
93 Standard_Integer GEOMImpl_ShapeDriver::Execute(TFunction_Logbook& log) const
94 {
95   if (Label().IsNull()) return 0;
96   Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
97
98   GEOMImpl_IShapes aCI (aFunction);
99   Standard_Integer aType = aFunction->GetType();
100
101   TopoDS_Shape aShape;
102   BRep_Builder B;
103
104   if (aType == WIRE_EDGES) {
105     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
106     unsigned int ind, nbshapes = aShapes->Length();
107
108     TopoDS_Wire aWire;
109     B.MakeWire(aWire);
110     BRepBuilderAPI_MakeWire MW;
111     bool isMWDone = true;
112
113     // add edges
114     for (ind = 1; ind <= nbshapes; ind++) {
115       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
116       TopoDS_Shape aShape_i = aRefShape->GetValue();
117       if (aShape_i.IsNull()) {
118         Standard_NullObject::Raise("Shape for wire construction is null");
119       }
120       if (aShape_i.ShapeType() == TopAbs_EDGE) {
121         B.Add(aWire, TopoDS::Edge(aShape_i));
122         MW.Add(TopoDS::Edge(aShape_i));
123         if (!MW.IsDone()) {
124           // check status after each edge/wire addition, because the final status
125           // can be OK even in case, when some edges/wires was not accepted.
126           isMWDone = false;
127         }
128       } else if (aShape_i.ShapeType() == TopAbs_WIRE) {
129         TopExp_Explorer exp (aShape_i, TopAbs_EDGE);
130         for (; exp.More(); exp.Next()) {
131           B.Add(aWire, TopoDS::Edge(exp.Current()));
132           MW.Add(TopoDS::Edge(exp.Current()));
133           if (!MW.IsDone()) {
134             // check status after each edge/wire addition, because the final status
135             // can be OK even in case, when some edges/wires was not accepted.
136             isMWDone = false;
137           }
138         }
139       } else {
140         Standard_TypeMismatch::Raise
141           ("Shape for wire construction is neither an edge nor a wire");
142       }
143     }
144
145     if (isMWDone) {
146       aShape = MW;
147     } else {
148       // fix edges order
149       Handle(ShapeFix_Wire) aFW = new ShapeFix_Wire;
150       aFW->Load(aWire);
151       aFW->FixReorder();
152
153       if        (aFW->StatusReorder(ShapeExtend_FAIL1)) {
154         Standard_ConstructionError::Raise("Wire construction failed: several loops detected");
155       } else if (aFW->StatusReorder(ShapeExtend_FAIL)) {
156         Standard_ConstructionError::Raise("Wire construction failed");
157       //} else if (aFW->StatusReorder(ShapeExtend_DONE2)) {
158       //  Standard_ConstructionError::Raise("Wire construction failed: some gaps detected");
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
190       aShape = aFW->WireAPIMake();
191     }
192   }
193   else if (aType == FACE_WIRE) {
194     Handle(GEOM_Function) aRefBase = aCI.GetBase();
195     TopoDS_Shape aShapeBase = aRefBase->GetValue();
196     if (aShapeBase.IsNull()) Standard_NullObject::Raise("Argument Shape is null");
197     TopoDS_Wire W;
198     if (aShapeBase.ShapeType() == TopAbs_WIRE) {
199       W = TopoDS::Wire(aShapeBase);
200       // check the wire is closed
201       TopoDS_Vertex aV1, aV2;
202       TopExp::Vertices(W, aV1, aV2);
203       if ( !aV1.IsNull() && !aV2.IsNull() && aV1.IsSame(aV2) )
204         aShapeBase.Closed(true);
205       else
206         Standard_NullObject::Raise
207           ("Shape for face construction is not closed");
208     }
209     else if (aShapeBase.ShapeType() == TopAbs_EDGE && aShapeBase.Closed()) {
210       BRepBuilderAPI_MakeWire MW;
211       MW.Add(TopoDS::Edge(aShapeBase));
212       if (!MW.IsDone()) {
213         Standard_ConstructionError::Raise("Wire construction failed");
214       }
215           W = MW;
216     }
217     else {
218       Standard_NullObject::Raise
219         ("Shape for face construction is neither a wire nor a closed edge");
220     }
221     GEOMImpl_Block6Explorer::MakeFace(W, aCI.GetIsPlanar(), aShape);
222     if (aShape.IsNull()) {
223       Standard_ConstructionError::Raise("Face construction failed");
224     }
225   }
226   else if (aType == FACE_WIRES) {
227     // Try to build a face from a set of wires and edges
228     int ind;
229
230     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
231     int nbshapes = aShapes->Length();
232     if (nbshapes < 1) {
233       Standard_ConstructionError::Raise("No wires or edges given");
234     }
235
236     // 1. Extract all edges from the given arguments
237     TopTools_MapOfShape aMapEdges;
238     Handle(TopTools_HSequenceOfShape) aSeqEdgesIn = new TopTools_HSequenceOfShape;
239
240     BRep_Builder B;
241     for (ind = 1; ind <= nbshapes; ind++) {
242       Handle(GEOM_Function) aRefSh_i = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
243       TopoDS_Shape aSh_i = aRefSh_i->GetValue();
244
245       TopExp_Explorer anExpE_i (aSh_i, TopAbs_EDGE);
246       for (; anExpE_i.More(); anExpE_i.Next()) {
247         if (aMapEdges.Add(anExpE_i.Current())) {
248           aSeqEdgesIn->Append(anExpE_i.Current());
249         }
250       }
251     }
252
253     // 2. Connect edges to wires of maximum length
254     Handle(TopTools_HSequenceOfShape) aSeqWiresOut;
255     ShapeAnalysis_FreeBounds::ConnectEdgesToWires(aSeqEdgesIn, Precision::Confusion(),
256                                                   /*shared*/Standard_False, aSeqWiresOut);
257
258     // 3. Separate closed wires
259     Handle(TopTools_HSequenceOfShape) aSeqClosedWires = new TopTools_HSequenceOfShape;
260     Handle(TopTools_HSequenceOfShape) aSeqOpenWires = new TopTools_HSequenceOfShape;
261     for (ind = 1; ind <= aSeqWiresOut->Length(); ind++) {
262       if (aSeqWiresOut->Value(ind).Closed())
263         aSeqClosedWires->Append(aSeqWiresOut->Value(ind));
264       else
265         aSeqOpenWires->Append(aSeqWiresOut->Value(ind));
266     }
267
268     if (aSeqClosedWires->Length() < 1) {
269       Standard_ConstructionError::Raise
270         ("There is no closed contour can be built from the given arguments");
271     }
272
273     // 4. Build a face / list of faces from all the obtained closed wires
274
275     // 4.a. Basic face
276     TopoDS_Shape aFFace;
277     TopoDS_Wire aW1 = TopoDS::Wire(aSeqClosedWires->Value(1));
278     GEOMImpl_Block6Explorer::MakeFace(aW1, aCI.GetIsPlanar(), aFFace);
279     if (aFFace.IsNull()) {
280       Standard_ConstructionError::Raise("Face construction failed");
281     }
282
283     // 4.b. Add other wires
284     if (aSeqClosedWires->Length() == 1) {
285       aShape = aFFace;
286     }
287     else {
288       TopoDS_Compound C;
289       BRep_Builder aBuilder;
290       aBuilder.MakeCompound(C);
291       BRepAlgo_FaceRestrictor FR;
292
293       TopAbs_Orientation OriF = aFFace.Orientation();
294       TopoDS_Shape aLocalS = aFFace.Oriented(TopAbs_FORWARD);
295       FR.Init(TopoDS::Face(aLocalS), Standard_False, Standard_True);
296
297       for (ind = 1; ind <= aSeqClosedWires->Length(); ind++) {
298         TopoDS_Wire aW = TopoDS::Wire(aSeqClosedWires->Value(ind));
299         FR.Add(aW);
300       }
301
302       FR.Perform();
303
304       if (FR.IsDone()) {
305         int k = 0;
306         TopoDS_Shape aFace;
307         for (; FR.More(); FR.Next()) {
308           aFace = FR.Current().Oriented(OriF);
309           aBuilder.Add(C, aFace);
310           k++;
311         }
312         if (k == 1) {
313           aShape = aFace;
314         } else {
315           aShape = C;
316         }
317       }
318     }
319
320     // 5. Add all open wires to the result
321     if (aSeqOpenWires->Length() > 0) {
322       //Standard_ConstructionError::Raise("There are some open wires");
323       TopoDS_Compound C;
324       BRep_Builder aBuilder;
325       if (aSeqClosedWires->Length() == 1) {
326         aBuilder.MakeCompound(C);
327         aBuilder.Add(C, aShape);
328       }
329       else {
330         C = TopoDS::Compound(aShape);
331       }
332
333       for (ind = 1; ind <= aSeqOpenWires->Length(); ind++) {
334         aBuilder.Add(C, aSeqOpenWires->Value(ind));
335       }
336
337       aShape = C;
338     }
339   }
340   else if (aType == SHELL_FACES) {
341     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
342     unsigned int ind, nbshapes = aShapes->Length();
343
344     // add faces
345     BRepBuilderAPI_Sewing aSewing(Precision::Confusion()*10.0);
346     for (ind = 1; ind <= nbshapes; ind++) {
347       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
348       TopoDS_Shape aShape_i = aRefShape->GetValue();
349       if (aShape_i.IsNull()) {
350         Standard_NullObject::Raise("Face for shell construction is null");
351       }
352       aSewing.Add(aShape_i);
353     }
354
355     aSewing.Perform();
356
357     TopoDS_Shape sh = aSewing.SewedShape();
358     if( sh.ShapeType()==TopAbs_FACE && nbshapes==1 ) {
359       // case for creation of shell from one face - PAL12722 (skl 26.06.2006)
360       TopoDS_Shell ss;
361       B.MakeShell(ss);
362       B.Add(ss,sh);
363       aShape = ss;
364     }
365     else {
366       //TopExp_Explorer exp (aSewing.SewedShape(), TopAbs_SHELL);
367       TopExp_Explorer exp (sh, TopAbs_SHELL);
368       Standard_Integer ish = 0;
369       for (; exp.More(); exp.Next()) {
370         aShape = exp.Current();
371         ish++;
372       }
373
374       if (ish != 1)
375         aShape = aSewing.SewedShape();
376     }
377
378   }
379   else if (aType == SOLID_SHELL) {
380     Handle(GEOM_Function) aRefShell = aCI.GetBase();
381     TopoDS_Shape aShapeShell = aRefShell->GetValue();
382     if (aShapeShell.IsNull() || aShapeShell.ShapeType() != TopAbs_SHELL) {
383       Standard_NullObject::Raise("Shape for solid construction is null or not a shell");
384     }
385
386     BRepCheck_Shell chkShell(TopoDS::Shell(aShapeShell));
387     if(chkShell.Closed() == BRepCheck_NotClosed) return 0;
388
389     TopoDS_Solid Sol;
390     B.MakeSolid(Sol);
391     B.Add(Sol, aShapeShell);
392     BRepClass3d_SolidClassifier SC (Sol);
393     SC.PerformInfinitePoint(Precision::Confusion());
394     if (SC.State() == TopAbs_IN) {
395       B.MakeSolid(Sol);
396       B.Add(Sol, aShapeShell.Reversed());
397     }
398
399     aShape = Sol;
400
401   }
402   else if (aType == SOLID_SHELLS) {
403     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
404     unsigned int ind, nbshapes = aShapes->Length();
405     Standard_Integer ish = 0;
406     TopoDS_Solid Sol;
407     B.MakeSolid(Sol);
408
409     // add shapes
410     for (ind = 1; ind <= nbshapes; ind++) {
411       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
412       TopoDS_Shape aShapeShell = aRefShape->GetValue();
413       if (aShapeShell.IsNull()) {
414         Standard_NullObject::Raise("Shell for solid construction is null");
415       }
416       if (aShapeShell.ShapeType() == TopAbs_SHELL) {
417         B.Add(Sol, aShapeShell);
418         ish++;
419       }
420     }
421     if ( ish == 0 ) return 0;
422     BRepClass3d_SolidClassifier SC (Sol);
423     SC.PerformInfinitePoint(Precision::Confusion());
424     if (SC.State() == TopAbs_IN)
425       aShape = Sol.Reversed();
426     else
427       aShape = Sol;
428   }
429   else if (aType == COMPOUND_SHAPES) {
430     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
431     unsigned int ind, nbshapes = aShapes->Length();
432
433     // add shapes
434     TopoDS_Compound C;
435     B.MakeCompound(C);
436     for (ind = 1; ind <= nbshapes; ind++) {
437       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
438       TopoDS_Shape aShape_i = aRefShape->GetValue();
439       if (aShape_i.IsNull()) {
440         Standard_NullObject::Raise("Shape for compound construction is null");
441       }
442       B.Add(C, aShape_i);
443     }
444
445     aShape = C;
446
447   }
448   else if (aType == REVERSE_ORIENTATION) {
449     Handle(GEOM_Function) aRefShape = aCI.GetBase();
450     TopoDS_Shape aShape_i = aRefShape->GetValue();
451     if (aShape_i.IsNull()) {
452        Standard_NullObject::Raise("Shape for reverse is null");
453     }
454
455     BRepBuilderAPI_Copy Copy(aShape_i);
456     if( Copy.IsDone() ) {
457       TopoDS_Shape tds = Copy.Shape();
458       if( tds.IsNull() ) {
459         Standard_ConstructionError::Raise("Orientation aborted : Can not reverse the shape");
460       }
461
462       if( tds.Orientation() == TopAbs_FORWARD)
463         tds.Orientation(TopAbs_REVERSED);
464       else
465         tds.Orientation(TopAbs_FORWARD);
466
467       aShape = tds;
468     }
469   }
470
471   if (aShape.IsNull()) return 0;
472
473   // Check shape validity
474   BRepCheck_Analyzer ana (aShape, false);
475   if (!ana.IsValid()) {
476     //Standard_ConstructionError::Raise("Algorithm have produced an invalid shape result");
477   }
478
479   aFunction->SetValue(aShape);
480
481   log.SetTouched(Label());
482
483   return 1;
484 }
485
486
487 //=======================================================================
488 //function :  GEOMImpl_ShapeDriver_Type_
489 //purpose  :
490 //=======================================================================
491 Standard_EXPORT Handle_Standard_Type& GEOMImpl_ShapeDriver_Type_()
492 {
493
494   static Handle_Standard_Type aType1 = STANDARD_TYPE(TFunction_Driver);
495   if ( aType1.IsNull()) aType1 = STANDARD_TYPE(TFunction_Driver);
496   static Handle_Standard_Type aType2 = STANDARD_TYPE(MMgt_TShared);
497   if ( aType2.IsNull()) aType2 = STANDARD_TYPE(MMgt_TShared);
498   static Handle_Standard_Type aType3 = STANDARD_TYPE(Standard_Transient);
499   if ( aType3.IsNull()) aType3 = STANDARD_TYPE(Standard_Transient);
500
501
502   static Handle_Standard_Transient _Ancestors[]= {aType1,aType2,aType3,NULL};
503   static Handle_Standard_Type _aType = new Standard_Type("GEOMImpl_ShapeDriver",
504                                                          sizeof(GEOMImpl_ShapeDriver),
505                                                          1,
506                                                          (Standard_Address)_Ancestors,
507                                                          (Standard_Address)NULL);
508
509   return _aType;
510 }
511
512 //=======================================================================
513 //function : DownCast
514 //purpose  :
515 //=======================================================================
516 const Handle(GEOMImpl_ShapeDriver) Handle(GEOMImpl_ShapeDriver)::DownCast(const Handle(Standard_Transient)& AnObject)
517 {
518   Handle(GEOMImpl_ShapeDriver) _anOtherObject;
519
520   if (!AnObject.IsNull()) {
521      if (AnObject->IsKind(STANDARD_TYPE(GEOMImpl_ShapeDriver))) {
522        _anOtherObject = Handle(GEOMImpl_ShapeDriver)((Handle(GEOMImpl_ShapeDriver)&)AnObject);
523      }
524   }
525
526   return _anOtherObject;
527 }