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