Salome HOME
untabify
[modules/geom.git] / src / STEPImport / STEPImport.cxx
1 // Copyright (C) 2007-2013  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 //  File:        STEPImport.cxx
24 //  Created:     Wed May 19 14:41:10 2004
25 //  Author:      Pavel TELKOV
26
27 #include "utilities.h"
28
29 #include <Basics_Utils.hxx>
30 #include <Basics_OCCTVersion.hxx>
31
32 #include <TDF_ChildIDIterator.hxx>
33 #include <TDF_Label.hxx>
34 #include <TDataStd_Name.hxx>
35 #include <TNaming_Builder.hxx>
36 #include <TNaming_NamedShape.hxx>
37
38 #include <IFSelect_ReturnStatus.hxx>
39 #include <Interface_InterfaceModel.hxx>
40 #include <Interface_Static.hxx>
41 #include <STEPControl_Reader.hxx>
42 #include <StepBasic_Product.hxx>
43 #include <StepBasic_ProductDefinition.hxx>
44 #include <StepBasic_ProductDefinitionFormation.hxx>
45 #include <StepGeom_GeometricRepresentationItem.hxx>
46 #include <StepShape_TopologicalRepresentationItem.hxx>
47 #include <TransferBRep.hxx>
48 #include <Transfer_Binder.hxx>
49 #include <Transfer_TransientProcess.hxx>
50 #include <XSControl_TransferReader.hxx>
51 #include <XSControl_WorkSession.hxx>
52
53 #include <BRep_Builder.hxx>
54
55 #include <TopExp.hxx>
56 #include <TopExp_Explorer.hxx>
57 #include <TopTools_IndexedMapOfShape.hxx>
58 #include <TopoDS_Compound.hxx>
59 #include <TopoDS_Iterator.hxx>
60 #include <TopoDS_Shape.hxx>
61
62 #include <TCollection_AsciiString.hxx>
63 #include <TColStd_SequenceOfAsciiString.hxx>
64
65 #include <Standard_Failure.hxx>
66 #include <Standard_ErrorHandler.hxx> // CAREFUL ! position of this file is critic : see Lucien PIGNOLONI / OCC
67
68 #ifdef WNT
69  #if defined STEPIMPORT_EXPORTS || defined STEPImport_EXPORTS
70   #if defined WIN32
71    #define STEPIMPORT_EXPORT __declspec( dllexport )
72   #else
73    #define STEPIMPORT_EXPORT
74   #endif
75  #else
76   #if defined WIN32
77    #define STEPIMPORT_EXPORT __declspec( dllimport )
78   #else
79    #define STEPIMPORT_EXPORT
80   #endif
81  #endif
82 #else
83  #define STEPIMPORT_EXPORT
84 #endif
85
86 //=============================================================================
87 /*!
88  *  Import()
89  */
90 //=============================================================================
91
92 extern "C"
93 {
94   STEPIMPORT_EXPORT
95   Handle(TCollection_HAsciiString) GetValue (const TCollection_AsciiString& theFileName,
96                                              const TCollection_AsciiString& theParameterName,
97                                              TCollection_AsciiString&       theError)
98   {
99     Handle(TCollection_HAsciiString) aValue;
100
101     if (theParameterName != "LEN_UNITS") {
102       theError = theParameterName + " parameter reading is not supported by STEP plugin";
103       return aValue;
104     }
105
106     // Set "C" numeric locale to save numbers correctly
107     Kernel_Utils::Localizer loc;
108
109     STEPControl_Reader aReader;
110
111     Interface_Static::SetCVal("xstep.cascade.unit","M");
112     Interface_Static::SetIVal("read.step.ideas", 1);
113     Interface_Static::SetIVal("read.step.nonmanifold", 1);
114
115     try {
116 #if OCC_VERSION_LARGE > 0x06010000
117       OCC_CATCH_SIGNALS;
118 #endif
119       IFSelect_ReturnStatus status = aReader.ReadFile(theFileName.ToCString());
120       if (status == IFSelect_RetDone) {
121         TColStd_SequenceOfAsciiString anUnitLengthNames;
122         TColStd_SequenceOfAsciiString anUnitAngleNames;
123         TColStd_SequenceOfAsciiString anUnitSolidAngleNames;
124         aReader.FileUnits(anUnitLengthNames, anUnitAngleNames, anUnitSolidAngleNames);
125         if (anUnitLengthNames.Length() > 0) {
126           aValue = new TCollection_HAsciiString( anUnitLengthNames.First() );
127           /*
128           TCollection_AsciiString aLenUnits = anUnitLengthNames.First();
129           if (aLenUnits == "millimetre")
130             aValue = new TCollection_HAsciiString ("MM");
131           else if (aLenUnits == "centimetre")
132             aValue = new TCollection_HAsciiString ("CM");
133           else if (aLenUnits == "metre")
134             aValue = new TCollection_HAsciiString ("M");
135           else if (aLenUnits == "INCH")
136             aValue = new TCollection_HAsciiString ("INCH");
137           // TODO (for other units than mm, cm, m or inch)
138           //else if (aLenUnits == "")
139           //  aValue = new TCollection_HAsciiString ("");
140
141           // tmp begin
142           //std::cout << "$$$ --- " << anUnitLengthNames.First();
143           //for (int ii = 2; ii <= anUnitLengthNames.Length(); ii++)
144           //  std::cout << ", " << anUnitLengthNames.Value(ii);
145           //std::cout << std::endl;
146           // tmp end
147           */
148         }
149       }
150       else {
151         theError = theFileName + " reading failed";
152       }
153     }
154     catch (Standard_Failure) {
155       Handle(Standard_Failure) aFail = Standard_Failure::Caught();
156       theError = aFail->GetMessageString();
157     }
158
159     return aValue;
160   }
161
162   STEPIMPORT_EXPORT
163   TopoDS_Shape Import (const TCollection_AsciiString& theFileName,
164                        const TCollection_AsciiString& theFormatName,
165                        TCollection_AsciiString&       theError,
166                        const TDF_Label&               theShapeLabel)
167   {
168     TopoDS_Shape aResShape;
169
170     // Set "C" numeric locale to save numbers correctly
171     Kernel_Utils::Localizer loc;
172
173     STEPControl_Reader aReader;
174
175     //VSR: 16/09/09: Convert to METERS
176     Interface_Static::SetCVal("xstep.cascade.unit","M");
177     Interface_Static::SetIVal("read.step.ideas", 1);
178     Interface_Static::SetIVal("read.step.nonmanifold", 1);
179
180     BRep_Builder B;
181     TopoDS_Compound compound;
182     B.MakeCompound(compound);
183
184     try {
185       OCC_CATCH_SIGNALS;
186
187       IFSelect_ReturnStatus status = aReader.ReadFile(theFileName.ToCString());
188
189       if (status == IFSelect_RetDone) {
190
191         // Regard or not the model units
192         if (theFormatName == "STEP_SCALE") {
193           // set UnitFlag to units from file
194           TColStd_SequenceOfAsciiString anUnitLengthNames;
195           TColStd_SequenceOfAsciiString anUnitAngleNames;
196           TColStd_SequenceOfAsciiString anUnitSolidAngleNames;
197           aReader.FileUnits(anUnitLengthNames, anUnitAngleNames, anUnitSolidAngleNames);
198           if (anUnitLengthNames.Length() > 0) {
199             TCollection_AsciiString aLenUnits = anUnitLengthNames.First();
200             if (aLenUnits == "millimetre")
201               Interface_Static::SetCVal("xstep.cascade.unit", "MM");
202             else if (aLenUnits == "centimetre")
203               Interface_Static::SetCVal("xstep.cascade.unit", "CM");
204             else if (aLenUnits == "metre" || aLenUnits.IsEmpty())
205               Interface_Static::SetCVal("xstep.cascade.unit", "M");
206             else if (aLenUnits == "INCH")
207               Interface_Static::SetCVal("xstep.cascade.unit", "INCH");
208             else {
209               theError = "The file contains not supported units.";
210               return aResShape;
211             }
212             // TODO (for other units than mm, cm, m or inch)
213             //else if (aLenUnits == "")
214             //  Interface_Static::SetCVal("xstep.cascade.unit", "???");
215           }
216         }
217         else {
218           //cout<<"need re-scale a model"<<endl;
219           // set UnitFlag to 'meter'
220           Interface_Static::SetCVal("xstep.cascade.unit","M");
221         }
222
223         Standard_Boolean failsonly = Standard_False;
224         aReader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity);
225
226         /* Root transfers */
227         Standard_Integer nbr = aReader.NbRootsForTransfer();
228         aReader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity);
229
230         for (Standard_Integer n = 1; n <= nbr; n++) {
231           Standard_Boolean ok = aReader.TransferRoot(n);
232           /* Collecting resulting entities */
233           Standard_Integer nbs = aReader.NbShapes();
234           if (!ok || nbs == 0)
235           {
236             // THROW_SALOME_CORBA_EXCEPTION("Exception catched in GEOM_Gen_i::ImportStep", SALOME::BAD_PARAM);
237             continue; // skip empty root
238           }
239           /* For a single entity */
240           else if (nbr == 1 && nbs == 1) {
241             aResShape = aReader.Shape(1);
242             // ATTENTION: this is a workaround for mantis issue 0020442 remark 0010776
243             // It should be removed after patching OCCT for bug OCC22436
244             // (fix for OCCT is expected in service pack next to OCCT6.3sp12)
245             if (aResShape.ShapeType() == TopAbs_COMPOUND) {
246               int nbSub1 = 0;
247               TopoDS_Shape currShape;
248               TopoDS_Iterator It (aResShape, Standard_True, Standard_True);
249               for (; It.More(); It.Next()) {
250                 nbSub1++;
251                 currShape = It.Value();
252               }
253               if (nbSub1 == 1)
254                 aResShape = currShape;
255             }
256             // END workaround
257             break;
258           }
259
260           for (Standard_Integer i = 1; i <= nbs; i++) {
261             TopoDS_Shape aShape = aReader.Shape(i);
262             if (aShape.IsNull()) {
263               // THROW_SALOME_CORBA_EXCEPTION("Null shape in GEOM_Gen_i::ImportStep", SALOME::BAD_PARAM) ;
264               //return aResShape;
265               continue;
266             }
267             else {
268               B.Add(compound, aShape);
269             }
270           }
271         }
272         if (aResShape.IsNull())
273           aResShape = compound;
274
275         // Check if any BRep entity has been read, there must be at least a vertex
276         if ( !TopExp_Explorer( aResShape, TopAbs_VERTEX ).More() )
277         {
278           theError = "No geometrical data in the imported file.";
279           return TopoDS_Shape();
280         }
281
282         // BEGIN: Store names of sub-shapes from file
283         TopTools_IndexedMapOfShape anIndices;
284         TopExp::MapShapes(aResShape, anIndices);
285
286         Handle(Interface_InterfaceModel) Model = aReader.WS()->Model();
287         Handle(XSControl_TransferReader) TR = aReader.WS()->TransferReader();
288         if (!TR.IsNull()) {
289           Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
290           Handle(Standard_Type) tPD  = STANDARD_TYPE(StepBasic_ProductDefinition);
291           Handle(Standard_Type) tShape  = STANDARD_TYPE(StepShape_TopologicalRepresentationItem);
292           Handle(Standard_Type) tGeom  = STANDARD_TYPE(StepGeom_GeometricRepresentationItem);
293
294           Standard_Integer nb = Model->NbEntities();
295           for (Standard_Integer ie = 1; ie <= nb; ie++) {
296             Handle(Standard_Transient) enti = Model->Value(ie);
297             Handle(TCollection_HAsciiString) aName;
298             if ( enti->IsKind( tShape ) || enti->IsKind(tGeom))
299             {
300               aName = Handle(StepRepr_RepresentationItem)::DownCast(enti)->Name();
301             }
302             else if (enti->DynamicType() == tPD)
303             {
304               Handle(StepBasic_ProductDefinition) PD =
305                 Handle(StepBasic_ProductDefinition)::DownCast(enti);
306               if (PD.IsNull()) continue;
307
308               Handle(StepBasic_Product) Prod = PD->Formation()->OfProduct();
309               aName = Prod->Name();
310             }
311             else
312             {
313               continue;
314             }
315             if ( aName->UsefullLength() < 1 )
316               continue;
317             // skip 'N0NE' name
318             if ( aName->UsefullLength() == 4 &&
319                  toupper (aName->Value(1)) == 'N' &&
320                  toupper (aName->Value(2)) == 'O' &&
321                  toupper (aName->Value(3)) == 'N' &&
322                  toupper (aName->Value(4)) == 'E')
323               continue;
324
325             // special check to pass names like "Open CASCADE STEP translator 6.3 1"
326             TCollection_AsciiString aSkipName ("Open CASCADE STEP translator");
327             if (aName->Length() >= aSkipName.Length()) {
328               if (aName->String().SubString(1, aSkipName.Length()).IsEqual(aSkipName))
329                 continue;
330             }
331             TCollection_ExtendedString aNameExt (aName->ToCString());
332
333             // find target shape
334             Handle(Transfer_Binder) binder = TP->Find(enti);
335             if (binder.IsNull()) continue;
336             TopoDS_Shape S = TransferBRep::ShapeResult(binder);
337             if (S.IsNull()) continue;
338
339             // as PRODUCT can be included in the main shape
340             // several times, we look here for all iclusions.
341             Standard_Integer isub, nbSubs = anIndices.Extent();
342             for (isub = 1; isub <= nbSubs; isub++)
343             {
344               TopoDS_Shape aSub = anIndices.FindKey(isub);
345               if (aSub.IsPartner(S)) {
346                 TDF_Label L;
347                 if (enti->IsKind(tGeom)) {
348                   // check all named shapes using iterator
349                   TDF_ChildIDIterator anIt (theShapeLabel, TDataStd_Name::GetID(), Standard_True);
350                   for (; anIt.More(); anIt.Next()) {
351                     Handle(TDataStd_Name) nameAttr =
352                       Handle(TDataStd_Name)::DownCast(anIt.Value());
353                     if (nameAttr.IsNull()) continue;
354                     TDF_Label Lab = nameAttr->Label();
355                     Handle(TNaming_NamedShape) shAttr; 
356                     if (Lab.FindAttribute(TNaming_NamedShape::GetID(), shAttr) && shAttr->Get().IsEqual(aSub))
357                       L = Lab;
358                   }
359                 }
360                 // create label and set shape
361                 if (L.IsNull())
362                 {
363                   TDF_TagSource aTag;
364                   L = aTag.NewChild(theShapeLabel);
365                   TNaming_Builder tnBuild (L);
366                   //tnBuild.Generated(S);
367                   tnBuild.Generated(aSub);
368                 }
369                 // set a name
370                 TDataStd_Name::Set(L, aNameExt);
371               }
372             }
373           }
374         }
375         // END: Store names
376       }
377       else {
378 //        switch (status) {
379 //        case IFSelect_RetVoid:
380 //          theError = "Nothing created or No data to process";
381 //          break;
382 //        case IFSelect_RetError:
383 //          theError = "Error in command or input data";
384 //          break;
385 //        case IFSelect_RetFail:
386 //          theError = "Execution was run, but has failed";
387 //          break;
388 //        case IFSelect_RetStop:
389 //          theError = "Execution has been stopped. Quite possible, an exception was raised";
390 //          break;
391 //        default:
392 //          break;
393 //        }
394         theError = "Wrong format of the imported file. Can't import file.";
395         aResShape.Nullify();
396       }
397     }
398     catch (Standard_Failure) {
399       Handle(Standard_Failure) aFail = Standard_Failure::Caught();
400       theError = aFail->GetMessageString();
401       aResShape.Nullify();
402     }
403     // Return previous locale
404     return aResShape;
405   }
406 }