Salome HOME
Update copyright
[modules/geom.git] / src / STEPImport / STEPImport.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 //  File:        STEPImport.cxx
23 //  Created:     Wed May 19 14:41:10 2004
24 //  Author:      Pavel TELKOV
25
26 #include "utilities.h"
27
28 #include <Basics_Utils.hxx>
29
30 #include <BRep_Builder.hxx>
31
32 #include <IFSelect_ReturnStatus.hxx>
33
34 #include <STEPControl_Reader.hxx>
35 #include <StepBasic_ProductDefinition.hxx>
36 #include <StepBasic_ProductDefinitionFormation.hxx>
37 #include <StepBasic_Product.hxx>
38 #include <Interface_InterfaceModel.hxx>
39 #include <XSControl_TransferReader.hxx>
40 #include <XSControl_WorkSession.hxx>
41
42 #include <Transfer_Binder.hxx>
43 #include <TNaming_Builder.hxx>
44 #include <TDataStd_Name.hxx>
45 #include <Transfer_TransientProcess.hxx>
46 #include <TransferBRep.hxx>
47
48 #include <TCollection_AsciiString.hxx>
49 #include <TopoDS_Compound.hxx>
50 #include <TopoDS_Shape.hxx>
51 #include <TDF_Label.hxx>
52 #include <TDF_Tool.hxx>
53 #include <Interface_Static.hxx>
54
55 #include <TopTools_IndexedMapOfShape.hxx>
56 #include <TopExp.hxx>
57 #include <TopoDS_Iterator.hxx>
58 #include <BRepTools.hxx>
59
60 #include <Standard_Failure.hxx>
61 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
62
63 #ifdef WNT
64  #if defined STEPIMPORT_EXPORTS || defined STEPImport_EXPORTS
65   #if defined WIN32
66    #define STEPIMPORT_EXPORT __declspec( dllexport )
67   #else
68    #define STEPIMPORT_EXPORT
69   #endif
70  #else
71   #if defined WIN32
72    #define STEPIMPORT_EXPORT __declspec( dllimport )
73   #else
74    #define STEPIMPORT_EXPORT
75   #endif
76  #endif
77 #else
78  #define STEPIMPORT_EXPORT
79 #endif
80
81 //=============================================================================
82 /*!
83  *  Import()
84  */
85 //=============================================================================
86
87 extern "C"
88 {
89   STEPIMPORT_EXPORT
90   TopoDS_Shape Import (const TCollection_AsciiString& theFileName,
91                        const TCollection_AsciiString& /*theFormatName*/,
92                        TCollection_AsciiString&       theError,
93                        const TDF_Label&               theShapeLabel)
94   {
95     MESSAGE("Import STEP model from file " << theFileName.ToCString());
96     // Set "C" numeric locale to save numbers correctly
97     Kernel_Utils::Localizer loc;
98     TopoDS_Shape aResShape;
99     //VRV: OCC 4.0 migration
100     STEPControl_Reader aReader;
101     //VSR: 16/09/09: Convert to METERS
102     Interface_Static::SetCVal("xstep.cascade.unit","M");
103     Interface_Static::SetIVal("read.step.ideas", 1);
104     Interface_Static::SetIVal("read.step.nonmanifold", 1);
105     //VRV: OCC 4.0 migration
106     TopoDS_Compound compound;
107     BRep_Builder B;
108     B.MakeCompound(compound);
109     try {
110 #if (OCC_VERSION_MAJOR << 16 | OCC_VERSION_MINOR << 8 | OCC_VERSION_MAINTENANCE) > 0x060100
111       OCC_CATCH_SIGNALS;
112 #endif
113       IFSelect_ReturnStatus status = aReader.ReadFile(theFileName.ToCString());
114
115       if (status == IFSelect_RetDone) {
116         Standard_Boolean failsonly = Standard_False;
117         aReader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity);
118         /* Root transfers */
119         Standard_Integer nbr = aReader.NbRootsForTransfer();
120         aReader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity);
121
122         for (Standard_Integer n = 1; n <= nbr; n++) {
123           Standard_Boolean ok = aReader.TransferRoot(n);
124           /* Collecting resulting entities */
125           Standard_Integer nbs = aReader.NbShapes();
126           if (!ok || nbs == 0)
127           {
128             // THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ImportStep", SALOME::BAD_PARAM);
129             continue; // skip empty root
130           }
131           /* For a single entity */
132           else if (nbr == 1 && nbs == 1) {
133             aResShape = aReader.Shape(1);
134             // ATTENTION: this is a workaround for mantis issue 0020442 remark 0010776
135             // It should be removed after patching OCCT for bug OCC22436
136             // (fix for OCCT is expected in service pack next to OCCT6.3sp12)
137             if (aResShape.ShapeType() == TopAbs_COMPOUND) {
138               int nbSub1 = 0;
139               TopoDS_Shape currShape;
140               TopoDS_Iterator It (aResShape, Standard_True, Standard_True);
141               for (; It.More(); It.Next()) {
142                 nbSub1++;
143                 currShape = It.Value();
144               }
145               if (nbSub1 == 1)
146                 aResShape = currShape;
147             }
148             // END workaround
149             break;
150           }
151
152           for (Standard_Integer i = 1; i <= nbs; i++) {
153             TopoDS_Shape aShape = aReader.Shape(i);
154             if (aShape.IsNull()) {
155               // THROW_SALOME_CORBA_EXCEPTION("Null shape in GEOM_Gen_i::ImportStep", SALOME::BAD_PARAM) ;
156               //return aResShape;
157               continue;
158             }
159             else {
160               B.Add(compound, aShape);
161             }
162           }
163         }
164         if (aResShape.IsNull())
165           aResShape = compound;
166
167         // BEGIN: Store names of sub-shapes from file
168         TopTools_IndexedMapOfShape anIndices;
169         TopExp::MapShapes(aResShape, anIndices);
170
171         Handle(Interface_InterfaceModel) Model = aReader.WS()->Model();
172         Handle(XSControl_TransferReader) TR = aReader.WS()->TransferReader();
173         if (!TR.IsNull()) {
174           Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
175           Handle(Standard_Type) tPD  = STANDARD_TYPE(StepBasic_ProductDefinition);
176
177           Standard_Integer nb = Model->NbEntities();
178           for (Standard_Integer ie = 1; ie <= nb; ie++) {
179             Handle(Standard_Transient) enti = Model->Value(ie);
180             if (enti->DynamicType() != tPD) continue;
181
182             Handle(StepBasic_ProductDefinition) PD =
183               Handle(StepBasic_ProductDefinition)::DownCast(enti);
184             if (PD.IsNull()) continue;
185
186             Handle(StepBasic_Product) Prod = PD->Formation()->OfProduct();
187             if (Prod->Name()->UsefullLength() <= 0) continue;
188
189             Handle(TCollection_HAsciiString) aName = Prod->Name();
190             TCollection_ExtendedString aNameExt (aName->ToCString());
191
192             // special check to pass names like "Open CASCADE STEP translator 6.3 1"
193             TCollection_AsciiString aSkipName ("Open CASCADE STEP translator");
194             if (aName->Length() >= aSkipName.Length()) {
195               if (aName->String().SubString(1, aSkipName.Length()).IsEqual(aSkipName))
196                 continue;
197             }
198
199             // find target shape
200             Handle(Transfer_Binder) binder = TP->Find(enti);
201             if (binder.IsNull()) continue;
202             TopoDS_Shape S = TransferBRep::ShapeResult(binder);
203             if (S.IsNull()) continue;
204
205             // as PRODUCT can be included in the main shape
206             // several times, we look here for all iclusions.
207             Standard_Integer isub, nbSubs = anIndices.Extent();
208             for (isub = 1; isub <= nbSubs; isub++)
209             {
210               TopoDS_Shape aSub = anIndices.FindKey(isub);
211               if (aSub.IsPartner(S)) {
212                 // create label and set shape
213                 TDF_Label L;
214                 TDF_TagSource aTag;
215                 L = aTag.NewChild(theShapeLabel);
216                 TNaming_Builder tnBuild (L);
217                 //tnBuild.Generated(S);
218                 tnBuild.Generated(aSub);
219
220                 // set a name
221                 TDataStd_Name::Set(L, aNameExt);
222               }
223             }
224           }
225         }
226         // END: Store names
227       }
228       else {
229 //        switch (status) {
230 //        case IFSelect_RetVoid:
231 //          theError = "Nothing created or No data to process";
232 //          break;
233 //        case IFSelect_RetError:
234 //          theError = "Error in command or input data";
235 //          break;
236 //        case IFSelect_RetFail:
237 //          theError = "Execution was run, but has failed";
238 //          break;
239 //        case IFSelect_RetStop:
240 //          theError = "Execution has been stopped. Quite possible, an exception was raised";
241 //          break;
242 //        default:
243 //          break;
244 //        }
245         theError = "Wrong format of the imported file. Can't import file.";
246         aResShape.Nullify();
247       }
248     }
249     catch (Standard_Failure) {
250       Handle(Standard_Failure) aFail = Standard_Failure::Caught();
251       theError = aFail->GetMessageString();
252       aResShape.Nullify();
253     }
254     // Return previous locale
255     return aResShape;
256   }
257 }