Salome HOME
Fix for bug Bug IPAL20288 (4x: CRASH after trying to build a sketch).
[modules/geom.git] / src / GEOMImpl / GEOMImpl_ShapeDriver.cxx
1 // Copyright (C) 2005  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
2 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
3 // 
4 // This library is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU Lesser General Public
6 // License as published by the Free Software Foundation; either 
7 // version 2.1 of the License.
8 // 
9 // This library is distributed in the hope that it will be useful 
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
12 // Lesser General Public License for more details.
13 //
14 // You should have received a copy of the GNU Lesser General Public  
15 // License along with this library; if not, write to the Free Software 
16 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 //
18 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 //
20
21 #include <GEOMImpl_ShapeDriver.hxx>
22
23 #include <GEOMImpl_IShapes.hxx>
24 #include <GEOMImpl_Types.hxx>
25 #include <GEOMImpl_Block6Explorer.hxx>
26
27 #include <GEOM_Function.hxx>
28
29 // OCCT Includes
30 #include <ShapeFix_Wire.hxx>
31
32 #include <BRep_Tool.hxx>
33 #include <BRep_Builder.hxx>
34 #include <BRepAlgo_FaceRestrictor.hxx>
35 #include <BRepBuilderAPI_Sewing.hxx>
36 #include <BRepBuilderAPI_Copy.hxx>
37 #include <BRepCheck.hxx>
38 #include <BRepCheck_Analyzer.hxx>
39 #include <BRepCheck_Shell.hxx>
40 #include <BRepClass3d_SolidClassifier.hxx>
41 #include <BRepBuilderAPI_MakeWire.hxx>
42 #include <BRepBuilderAPI_Sewing.hxx>
43
44 #include <ShapeAnalysis_FreeBounds.hxx>
45
46 #include <TopAbs.hxx>
47 #include <TopoDS.hxx>
48 #include <TopoDS_Shape.hxx>
49 #include <TopoDS_Edge.hxx>
50 #include <TopoDS_Wire.hxx>
51 #include <TopoDS_Shell.hxx>
52 #include <TopoDS_Solid.hxx>
53 #include <TopoDS_Compound.hxx>
54 #include <TopoDS_Iterator.hxx>
55 #include <TopExp_Explorer.hxx>
56
57 #include <TopTools_MapOfShape.hxx>
58 #include <TopTools_HSequenceOfShape.hxx>
59
60 #include <TColStd_HSequenceOfTransient.hxx>
61
62 #include <Precision.hxx>
63 #include <Standard_NullObject.hxx>
64 #include <Standard_TypeMismatch.hxx>
65 #include <Standard_ConstructionError.hxx>
66
67 //=======================================================================
68 //function : GetID
69 //purpose  :
70 //=======================================================================
71 const Standard_GUID& GEOMImpl_ShapeDriver::GetID()
72 {
73   static Standard_GUID aShapeDriver("FF1BBB54-5D14-4df2-980B-3A668264EA16");
74   return aShapeDriver;
75 }
76
77
78 //=======================================================================
79 //function : GEOMImpl_ShapeDriver
80 //purpose  :
81 //=======================================================================
82 GEOMImpl_ShapeDriver::GEOMImpl_ShapeDriver()
83 {
84 }
85
86 //=======================================================================
87 //function : Execute
88 //purpose  :
89 //=======================================================================
90 Standard_Integer GEOMImpl_ShapeDriver::Execute(TFunction_Logbook& log) const
91 {
92   if (Label().IsNull()) return 0;
93   Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());
94
95   GEOMImpl_IShapes aCI (aFunction);
96   Standard_Integer aType = aFunction->GetType();
97
98   TopoDS_Shape aShape;
99   BRep_Builder B;
100
101   if (aType == WIRE_EDGES) {
102     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
103     unsigned int ind, nbshapes = aShapes->Length();
104
105     TopoDS_Wire aWire;
106     B.MakeWire(aWire);
107     BRepBuilderAPI_MakeWire MW;
108     bool isMWDone = true;
109
110     // add edges
111     for (ind = 1; ind <= nbshapes; ind++) {
112       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
113       TopoDS_Shape aShape_i = aRefShape->GetValue();
114       if (aShape_i.IsNull()) {
115         Standard_NullObject::Raise("Shape for wire construction is null");
116       }
117       if (aShape_i.ShapeType() == TopAbs_EDGE) {
118         B.Add(aWire, TopoDS::Edge(aShape_i));
119         MW.Add(TopoDS::Edge(aShape_i));
120         if (!MW.IsDone()) {
121           // check status after each edge/wire addition, because the final status
122           // can be OK even in case, when some edges/wires was not accepted.
123           isMWDone = false;
124         }
125       } else if (aShape_i.ShapeType() == TopAbs_WIRE) {
126         TopExp_Explorer exp (aShape_i, TopAbs_EDGE);
127         for (; exp.More(); exp.Next()) {
128           B.Add(aWire, TopoDS::Edge(exp.Current()));
129           MW.Add(TopoDS::Edge(exp.Current()));
130           if (!MW.IsDone()) {
131             // check status after each edge/wire addition, because the final status
132             // can be OK even in case, when some edges/wires was not accepted.
133             isMWDone = false;
134           }
135         }
136       } else {
137         Standard_TypeMismatch::Raise
138           ("Shape for wire construction is neither an edge nor a wire");
139       }
140     }
141
142     if (isMWDone) {
143       aShape = MW;
144     } else {
145       // fix edges order
146       Handle(ShapeFix_Wire) aFW = new ShapeFix_Wire;
147       aFW->Load(aWire);
148       aFW->FixReorder();
149
150       if        (aFW->StatusReorder(ShapeExtend_FAIL1)) {
151         Standard_ConstructionError::Raise("Wire construction failed: several loops detected");
152       } else if (aFW->StatusReorder(ShapeExtend_FAIL)) {
153         Standard_ConstructionError::Raise("Wire construction failed");
154       } else if (aFW->StatusReorder(ShapeExtend_DONE2)) {
155         Standard_ConstructionError::Raise("Wire construction failed: some gaps detected");
156       } else {
157       }
158
159       aFW->ClosedWireMode() = Standard_False;
160       aFW->FixConnected();
161       if (aFW->StatusConnected(ShapeExtend_FAIL)) {
162         Standard_ConstructionError::Raise("Wire construction failed: cannot build connected wire");
163       }
164
165       aShape = aFW->WireAPIMake();
166     }
167   }
168   else if (aType == FACE_WIRE) {
169     Handle(GEOM_Function) aRefBase = aCI.GetBase();
170     TopoDS_Shape aShapeBase = aRefBase->GetValue();
171     if (aShapeBase.IsNull()) Standard_NullObject::Raise("Argument Shape is null");
172     TopoDS_Wire W;
173     if (aShapeBase.ShapeType() == TopAbs_WIRE) {
174       W = TopoDS::Wire(aShapeBase);
175     }
176     else if (aShapeBase.ShapeType() == TopAbs_EDGE && aShapeBase.Closed()) {
177       BRepBuilderAPI_MakeWire MW;
178       MW.Add(TopoDS::Edge(aShapeBase));
179       if (!MW.IsDone()) {
180         Standard_ConstructionError::Raise("Wire construction failed");
181       }
182           W = MW;
183     }
184     else {
185       Standard_NullObject::Raise
186         ("Shape for face construction is neither a wire nor a closed edge");
187     }
188     GEOMImpl_Block6Explorer::MakeFace(W, aCI.GetIsPlanar(), aShape);
189     if (aShape.IsNull()) {
190       Standard_ConstructionError::Raise("Face construction failed");
191     }
192   }
193   else if (aType == FACE_WIRES) {
194     // Try to build a face from a set of wires and edges
195     int ind;
196
197     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
198     int nbshapes = aShapes->Length();
199     if (nbshapes < 1) {
200       Standard_ConstructionError::Raise("No wires or edges given");
201     }
202
203     // 1. Extract all edges from the given arguments
204     TopTools_MapOfShape aMapEdges;
205     Handle(TopTools_HSequenceOfShape) aSeqEdgesIn = new TopTools_HSequenceOfShape;
206
207     BRep_Builder B;
208     for (ind = 1; ind <= nbshapes; ind++) {
209       Handle(GEOM_Function) aRefSh_i = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
210       TopoDS_Shape aSh_i = aRefSh_i->GetValue();
211
212       TopExp_Explorer anExpE_i (aSh_i, TopAbs_EDGE);
213       for (; anExpE_i.More(); anExpE_i.Next()) {
214         if (aMapEdges.Add(anExpE_i.Current())) {
215           aSeqEdgesIn->Append(anExpE_i.Current());
216         }
217       }
218     }
219
220     // 2. Connect edges to wires of maximum length
221     Handle(TopTools_HSequenceOfShape) aSeqWiresOut;
222     ShapeAnalysis_FreeBounds::ConnectEdgesToWires(aSeqEdgesIn, Precision::Confusion(),
223                                                   /*shared*/Standard_False, aSeqWiresOut);
224
225     // 3. Separate closed wires
226     Handle(TopTools_HSequenceOfShape) aSeqClosedWires = new TopTools_HSequenceOfShape;
227     Handle(TopTools_HSequenceOfShape) aSeqOpenWires = new TopTools_HSequenceOfShape;
228     for (ind = 1; ind <= aSeqWiresOut->Length(); ind++) {
229       if (aSeqWiresOut->Value(ind).Closed())
230         aSeqClosedWires->Append(aSeqWiresOut->Value(ind));
231       else
232         aSeqOpenWires->Append(aSeqWiresOut->Value(ind));
233     }
234
235     if (aSeqClosedWires->Length() < 1) {
236       Standard_ConstructionError::Raise
237         ("There is no closed contour can be built from the given arguments");
238     }
239
240     // 4. Build a face / list of faces from all the obtained closed wires
241
242     // 4.a. Basic face
243     TopoDS_Shape aFFace;
244     TopoDS_Wire aW1 = TopoDS::Wire(aSeqClosedWires->Value(1));
245     GEOMImpl_Block6Explorer::MakeFace(aW1, aCI.GetIsPlanar(), aFFace);
246     if (aFFace.IsNull()) {
247       Standard_ConstructionError::Raise("Face construction failed");
248     }
249
250     // 4.b. Add other wires
251     if (aSeqClosedWires->Length() == 1) {
252       aShape = aFFace;
253     }
254     else {
255       TopoDS_Compound C;
256       BRep_Builder aBuilder;
257       aBuilder.MakeCompound(C);
258       BRepAlgo_FaceRestrictor FR;
259
260       TopAbs_Orientation OriF = aFFace.Orientation();
261       TopoDS_Shape aLocalS = aFFace.Oriented(TopAbs_FORWARD);
262       FR.Init(TopoDS::Face(aLocalS), Standard_False, Standard_True);
263
264       for (ind = 1; ind <= aSeqClosedWires->Length(); ind++) {
265         TopoDS_Wire aW = TopoDS::Wire(aSeqClosedWires->Value(ind));
266         FR.Add(aW);
267       }
268
269       FR.Perform();
270
271       if (FR.IsDone()) {
272         int k = 0;
273         TopoDS_Shape aFace;
274         for (; FR.More(); FR.Next()) {
275           aFace = FR.Current().Oriented(OriF);
276           aBuilder.Add(C, aFace);
277           k++;
278         }
279         if (k == 1) {
280           aShape = aFace;
281         } else {
282           aShape = C;
283         }
284       }
285     }
286
287     // 5. Add all open wires to the result
288     if (aSeqOpenWires->Length() > 0) {
289       //Standard_ConstructionError::Raise("There are some open wires");
290       TopoDS_Compound C;
291       BRep_Builder aBuilder;
292       if (aSeqClosedWires->Length() == 1) {
293         aBuilder.MakeCompound(C);
294         aBuilder.Add(C, aShape);
295       }
296       else {
297         C = TopoDS::Compound(aShape);
298       }
299
300       for (ind = 1; ind <= aSeqOpenWires->Length(); ind++) {
301         aBuilder.Add(C, aSeqOpenWires->Value(ind));
302       }
303
304       aShape = C;
305     }
306   }
307   else if (aType == SHELL_FACES) {
308     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
309     unsigned int ind, nbshapes = aShapes->Length();
310
311     // add faces
312     BRepBuilderAPI_Sewing aSewing(Precision::Confusion()*10.0);
313     for (ind = 1; ind <= nbshapes; ind++) {
314       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
315       TopoDS_Shape aShape_i = aRefShape->GetValue();
316       if (aShape_i.IsNull()) {
317         Standard_NullObject::Raise("Face for shell construction is null");
318       }
319       aSewing.Add(aShape_i);
320     }
321
322     aSewing.Perform();
323
324     TopoDS_Shape sh = aSewing.SewedShape();
325     if( sh.ShapeType()==TopAbs_FACE && nbshapes==1 ) {
326       // case for creation of shell from one face - PAL12722 (skl 26.06.2006)
327       TopoDS_Shell ss;
328       B.MakeShell(ss);
329       B.Add(ss,sh);
330       aShape = ss;
331     }
332     else {
333       //TopExp_Explorer exp (aSewing.SewedShape(), TopAbs_SHELL);
334       TopExp_Explorer exp (sh, TopAbs_SHELL);
335       Standard_Integer ish = 0;
336       for (; exp.More(); exp.Next()) {
337         aShape = exp.Current();
338         ish++;
339       }
340
341       if (ish != 1)
342         aShape = aSewing.SewedShape();
343     }
344
345   }
346   else if (aType == SOLID_SHELL) {
347     Handle(GEOM_Function) aRefShell = aCI.GetBase();
348     TopoDS_Shape aShapeShell = aRefShell->GetValue();
349     if (aShapeShell.IsNull() || aShapeShell.ShapeType() != TopAbs_SHELL) {
350       Standard_NullObject::Raise("Shape for solid construction is null or not a shell");
351     }
352
353     BRepCheck_Shell chkShell(TopoDS::Shell(aShapeShell));
354     if(chkShell.Closed() == BRepCheck_NotClosed) return 0;
355
356     TopoDS_Solid Sol;
357     B.MakeSolid(Sol);
358     B.Add(Sol, aShapeShell);
359     BRepClass3d_SolidClassifier SC (Sol);
360     SC.PerformInfinitePoint(Precision::Confusion());
361     if (SC.State() == TopAbs_IN) {
362       B.MakeSolid(Sol);
363       B.Add(Sol, aShapeShell.Reversed());
364     }
365
366     aShape = Sol;
367
368   }
369   else if (aType == SOLID_SHELLS) {
370     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
371     unsigned int ind, nbshapes = aShapes->Length();
372     Standard_Integer ish = 0;
373     TopoDS_Solid Sol;
374     B.MakeSolid(Sol);
375
376     // add shapes
377     for (ind = 1; ind <= nbshapes; ind++) {
378       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
379       TopoDS_Shape aShapeShell = aRefShape->GetValue();
380       if (aShapeShell.IsNull()) {
381         Standard_NullObject::Raise("Shell for solid construction is null");
382       }
383       if (aShapeShell.ShapeType() == TopAbs_SHELL) {
384         B.Add(Sol, aShapeShell);
385         ish++;
386       }
387     }
388     if ( ish == 0 ) return 0;
389     BRepClass3d_SolidClassifier SC (Sol);
390     SC.PerformInfinitePoint(Precision::Confusion());
391     switch (SC.State()) {
392     case TopAbs_IN:
393       aShape = Sol.Reversed(); break;
394     case TopAbs_OUT:
395       aShape = Sol; break;
396     default: // not closed shell?
397       return 0;
398     }
399
400   }
401   else if (aType == COMPOUND_SHAPES) {
402     Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();
403     unsigned int ind, nbshapes = aShapes->Length();
404
405     // add shapes
406     TopoDS_Compound C;
407     B.MakeCompound(C);
408     for (ind = 1; ind <= nbshapes; ind++) {
409       Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));
410       TopoDS_Shape aShape_i = aRefShape->GetValue();
411       if (aShape_i.IsNull()) {
412         Standard_NullObject::Raise("Shape for compound construction is null");
413       }
414       B.Add(C, aShape_i);
415     }
416
417     aShape = C;
418
419   }
420   else if (aType == REVERSE_ORIENTATION) {
421     Handle(GEOM_Function) aRefShape = aCI.GetBase();
422     TopoDS_Shape aShape_i = aRefShape->GetValue();
423     if (aShape_i.IsNull()) {
424        Standard_NullObject::Raise("Shape for reverse is null");
425     }
426
427     BRepBuilderAPI_Copy Copy(aShape_i);
428     if( Copy.IsDone() ) {
429       TopoDS_Shape tds = Copy.Shape();
430       if( tds.IsNull() ) {
431         Standard_ConstructionError::Raise("Orientation aborted : Can not reverse the shape");
432       }
433
434       if( tds.Orientation() == TopAbs_FORWARD)
435         tds.Orientation(TopAbs_REVERSED);
436       else
437         tds.Orientation(TopAbs_FORWARD);
438
439       aShape = tds;
440     }
441   }
442
443   if (aShape.IsNull()) return 0;
444
445   // Check shape validity
446   BRepCheck_Analyzer ana (aShape, false);
447   if (!ana.IsValid()) {
448     Standard_ConstructionError::Raise("Algorithm have produced an invalid shape result");
449   }
450
451   aFunction->SetValue(aShape);
452
453   log.SetTouched(Label());
454
455   return 1;
456 }
457
458
459 //=======================================================================
460 //function :  GEOMImpl_ShapeDriver_Type_
461 //purpose  :
462 //=======================================================================
463 Standard_EXPORT Handle_Standard_Type& GEOMImpl_ShapeDriver_Type_()
464 {
465
466   static Handle_Standard_Type aType1 = STANDARD_TYPE(TFunction_Driver);
467   if ( aType1.IsNull()) aType1 = STANDARD_TYPE(TFunction_Driver);
468   static Handle_Standard_Type aType2 = STANDARD_TYPE(MMgt_TShared);
469   if ( aType2.IsNull()) aType2 = STANDARD_TYPE(MMgt_TShared);
470   static Handle_Standard_Type aType3 = STANDARD_TYPE(Standard_Transient);
471   if ( aType3.IsNull()) aType3 = STANDARD_TYPE(Standard_Transient);
472
473
474   static Handle_Standard_Transient _Ancestors[]= {aType1,aType2,aType3,NULL};
475   static Handle_Standard_Type _aType = new Standard_Type("GEOMImpl_ShapeDriver",
476                                                          sizeof(GEOMImpl_ShapeDriver),
477                                                          1,
478                                                          (Standard_Address)_Ancestors,
479                                                          (Standard_Address)NULL);
480
481   return _aType;
482 }
483
484 //=======================================================================
485 //function : DownCast
486 //purpose  :
487 //=======================================================================
488 const Handle(GEOMImpl_ShapeDriver) Handle(GEOMImpl_ShapeDriver)::DownCast(const Handle(Standard_Transient)& AnObject)
489 {
490   Handle(GEOMImpl_ShapeDriver) _anOtherObject;
491
492   if (!AnObject.IsNull()) {
493      if (AnObject->IsKind(STANDARD_TYPE(GEOMImpl_ShapeDriver))) {
494        _anOtherObject = Handle(GEOMImpl_ShapeDriver)((Handle(GEOMImpl_ShapeDriver)&)AnObject);
495      }
496   }
497
498   return _anOtherObject;
499 }