0024947: Redesign OCCT legacy type system -- automatic
[occt.git] / src / STEPCAFControl / STEPCAFControl_Reader.cxx
1 // Created on: 2000-08-15
2 // Created by: Andrey BETENEV
3 // Copyright (c) 2000-2014 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16 #include <STEPCAFControl_Reader.ixx>
17
18 #include <Quantity_Color.hxx>
19 #include <TCollection_HAsciiString.hxx>
20 #include <TopoDS_Shape.hxx>
21 #include <TopoDS_Iterator.hxx>
22 #include <TopTools_MapOfShape.hxx>
23 #include <TopoDS_Compound.hxx>
24
25 #include <Transfer_TransientProcess.hxx>
26 #include <TransferBRep.hxx>
27 #include <Transfer_Binder.hxx>
28 #include <Interface_InterfaceModel.hxx>
29 #include <XSControl_TransferReader.hxx>
30
31 #include <StepBasic_Product.hxx>
32 #include <StepBasic_ProductDefinition.hxx>
33 #include <StepBasic_ProductDefinitionRelationship.hxx>
34 #include <StepBasic_ProductDefinitionFormation.hxx>
35 #include <StepShape_ContextDependentShapeRepresentation.hxx>
36 #include <StepShape_ShapeDefinitionRepresentation.hxx>
37 #include <StepShape_ShapeDefinitionRepresentation.hxx>
38 #include <StepRepr_ProductDefinitionShape.hxx>
39 #include <StepRepr_PropertyDefinition.hxx>
40 #include <StepRepr_ShapeAspect.hxx>
41 #include <StepRepr_MeasureRepresentationItem.hxx>
42 #include <StepRepr_DescriptiveRepresentationItem.hxx>
43 #include <StepRepr_SequenceOfRepresentationItem.hxx>
44 #include <StepVisual_StyledItem.hxx>
45 #include <StepAP214_AppliedExternalIdentificationAssignment.hxx>
46
47 #include <STEPConstruct.hxx>
48 #include <STEPConstruct_Styles.hxx>
49 #include <STEPConstruct_ExternRefs.hxx>
50 #include <STEPConstruct_UnitContext.hxx>
51 #include <STEPCAFControl_Controller.hxx>
52 #include <STEPCAFControl_DataMapOfSDRExternFile.hxx>
53
54 #include <TDataStd_Name.hxx>
55 #include <TDF_Label.hxx>
56 #include <XCAFDoc_ColorTool.hxx>
57 #include <XCAFDoc_ShapeTool.hxx>
58 #include <XCAFDoc_DocumentTool.hxx>
59 #include <XCAFDoc_DimTolTool.hxx>
60 #include <XCAFDoc_MaterialTool.hxx>
61 #include <XCAFDoc_DataMapOfShapeLabel.hxx>
62 #include <STEPConstruct_ValidationProps.hxx>
63 #include <StepRepr_Representation.hxx>
64 #include <XCAFDoc_Area.hxx>
65 #include <XCAFDoc_Volume.hxx>
66 #include <XCAFDoc_Centroid.hxx>
67 #include <StepVisual_PresentationLayerAssignment.hxx>
68 #include <TColStd_HSequenceOfTransient.hxx>
69 #include <StepVisual_LayeredItem.hxx>
70 #include <XCAFDoc_LayerTool.hxx>
71 #include <Interface_EntityIterator.hxx>
72 #include <StepRepr_ShapeRepresentationRelationship.hxx>
73 #include <STEPConstruct_Assembly.hxx>
74 #include <TDF_Tool.hxx>
75 #include <StepVisual_Invisibility.hxx>
76 #include <TDataStd_UAttribute.hxx>
77 #include <XCAFDoc.hxx>
78 #include <OSD_Path.hxx>
79 #include <TColStd_SequenceOfHAsciiString.hxx>
80
81 #include <TDataStd_TreeNode.hxx>
82 #include <TNaming_NamedShape.hxx>
83 #include <BRep_Builder.hxx>
84
85 #include <STEPCAFControl_DataMapOfShapePD.hxx>
86 #include <STEPCAFControl_DataMapOfPDExternFile.hxx>
87 #include <StepVisual_PresentationStyleByContext.hxx>
88 #include <StepVisual_StyleContextSelect.hxx>
89 #include <StepRepr_RepresentedDefinition.hxx>
90 #include <StepRepr_CharacterizedDefinition.hxx>
91 #include <StepRepr_SpecifiedHigherUsageOccurrence.hxx>
92 #include <XCAFDoc_GraphNode.hxx>
93 #include <STEPCAFControl_Reader.hxx>
94
95 // skl 21.08.2003 for reading G&DT
96 #include <StepShape_DimensionalSize.hxx>
97 #include <StepDimTol_GeometricTolerance.hxx>
98 #include <StepShape_EdgeCurve.hxx>
99 #include <StepShape_DimensionalCharacteristicRepresentation.hxx>
100 #include <StepShape_ShapeDimensionRepresentation.hxx>
101 #include <StepRepr_ValueRange.hxx>
102 #include <StepRepr_ReprItemAndLengthMeasureWithUnit.hxx>
103 #include <StepBasic_MeasureWithUnit.hxx>
104 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol.hxx>
105 #include <StepDimTol_ModifiedGeometricTolerance.hxx>
106 #include <StepDimTol_GeometricToleranceWithDatumReference.hxx>
107 //#include <StepRepr_CompoundItemDefinition.hxx>
108 //#include <StepRepr_CompoundItemDefinitionMember.hxx>
109 #include <TColStd_HArray1OfTransient.hxx>
110 #include <StepRepr_HArray1OfRepresentationItem.hxx>
111 #include <TColStd_IndexedDataMapOfTransientTransient.hxx>
112 //#include <StepBasic_ConversionBasedUnit.hxx>
113 #include <StepBasic_Unit.hxx>
114 #include <StepBasic_NamedUnit.hxx>
115 #include <StepBasic_SiUnit.hxx>
116 #include <StepBasic_ConversionBasedUnitAndLengthUnit.hxx>
117 #include <StepBasic_ConversionBasedUnitAndMassUnit.hxx>
118 #include <StepBasic_DerivedUnit.hxx>
119 #include <StepBasic_DerivedUnitElement.hxx>
120 #include <StepBasic_MeasureValueMember.hxx>
121
122 //#include <TDataStd_Real.hxx>
123 //#include <TDataStd_Constraint.hxx>
124 //#include <TDataStd_ConstraintEnum.hxx>
125 //#include <TNaming_Tool.hxx>
126 //#include <AIS_InteractiveObject.hxx>
127 //#include <TPrsStd_ConstraintTools.hxx>
128 //#include <AIS_DiameterDimension.hxx>
129 //#include <TPrsStd_Position.hxx>
130 //#include <TPrsStd_AISPresentation.hxx>
131 //#include <TNaming_Builder.hxx>
132 #include <TColStd_HArray1OfReal.hxx>
133 #include <StepShape_AdvancedFace.hxx>
134 #include <StepDimTol_HArray1OfDatumReference.hxx>
135 #include <StepDimTol_DatumReference.hxx>
136 #include <StepDimTol_Datum.hxx>
137 #include <StepDimTol_DatumFeature.hxx>
138 #include <StepRepr_ShapeAspectRelationship.hxx>
139
140 #include <StepDimTol_AngularityTolerance.hxx>
141 #include <StepDimTol_CircularRunoutTolerance.hxx>
142 #include <StepDimTol_CoaxialityTolerance.hxx>
143 #include <StepDimTol_ConcentricityTolerance.hxx>
144 #include <StepDimTol_ParallelismTolerance.hxx>
145 #include <StepDimTol_PerpendicularityTolerance.hxx>
146 #include <StepDimTol_SymmetryTolerance.hxx>
147 #include <StepDimTol_TotalRunoutTolerance.hxx>
148 #include <StepDimTol_CylindricityTolerance.hxx>
149 #include <StepDimTol_FlatnessTolerance.hxx>
150 #include <StepDimTol_LineProfileTolerance.hxx>
151 #include <StepDimTol_PositionTolerance.hxx>
152 #include <StepDimTol_RoundnessTolerance.hxx>
153 #include <StepDimTol_StraightnessTolerance.hxx>
154 #include <StepDimTol_SurfaceProfileTolerance.hxx>
155
156 #include <StepShape_SolidModel.hxx>
157 #include <StepShape_ShellBasedSurfaceModel.hxx>
158 #include <StepShape_GeometricSet.hxx>
159 #include <StepBasic_ProductDefinition.hxx>
160 #include <NCollection_DataMap.hxx>
161 #include <StepShape_ManifoldSolidBrep.hxx>
162 #include <Interface_Static.hxx>
163 #include <TColStd_MapOfTransient.hxx>
164 #include <TColStd_MapIteratorOfMapOfTransient.hxx>
165 #include <TopTools_ListOfShape.hxx>
166 #include <TopTools_ListIteratorOfListOfShape.hxx>
167 #include <STEPCAFControl_DataMapIteratorOfDataMapOfShapePD.hxx>
168 #include <StepShape_ClosedShell.hxx>
169 #include <StepShape_HArray1OfFace.hxx>
170 #include <StepShape_HArray1OfFaceBound.hxx>
171 #include <StepShape_Loop.hxx>
172 #include <StepShape_EdgeLoop.hxx>
173 #include <StepShape_HArray1OfOrientedEdge.hxx>
174 #include <StepShape_HArray1OfShell.hxx>
175 #include <StepShape_ShapeRepresentation.hxx>
176 #include <StepRepr_NextAssemblyUsageOccurrence.hxx>
177 #include <StepRepr_AssemblyComponentUsage.hxx>
178 #include <StepRepr_PropertyDefinitionRepresentation.hxx>
179 #include <StepRepr_RepresentationItem.hxx>
180 #include <StepRepr_RepresentationRelationship.hxx>
181
182 #ifdef OCCT_DEBUG
183 //! Converts address of the passed shape (TShape) to string.
184 //! \param theShape [in] Shape to dump.
185 //! \return corresponding string.
186 TCollection_AsciiString AddrToString(const TopoDS_Shape& theShape)
187 {
188   std::string anAddrStr;
189   std::ostringstream ost;
190   ost << theShape.TShape().Access();
191   anAddrStr = ost.str();
192
193   TCollection_AsciiString aStr =
194     TCollection_AsciiString("[").Cat( anAddrStr.c_str() ).Cat("]");
195
196   return aStr;
197 }
198 #endif
199
200 //=======================================================================
201 //function : IsEqual
202 //purpose  : global function to check equality of topological shapes
203 //=======================================================================
204
205 inline Standard_Boolean IsEqual(const TopoDS_Shape& theShape1,
206                                 const TopoDS_Shape& theShape2) 
207 {
208   return theShape1.IsEqual(theShape2);
209 }
210
211 //=======================================================================
212 //function : AllocateSubLabel
213 //purpose  :
214 //=======================================================================
215
216 static TDF_Label AllocateSubLabel(TDF_Label& theRoot)
217 {
218   return TDF_TagSource::NewChild(theRoot);
219 }
220
221 //=======================================================================
222 //function : STEPCAFControl_Reader
223 //purpose  : 
224 //=======================================================================
225
226 STEPCAFControl_Reader::STEPCAFControl_Reader ():
227        myColorMode( Standard_True ),
228        myNameMode ( Standard_True ),
229        myLayerMode( Standard_True ),
230        myPropsMode( Standard_True ),
231            mySHUOMode ( Standard_False ),
232        myGDTMode  ( Standard_True ),
233        myMatMode  ( Standard_True )
234 {
235   STEPCAFControl_Controller::Init();
236   myFiles = new STEPCAFControl_DictionaryOfExternFile;
237 }
238
239
240 //=======================================================================
241 //function : STEPCAFControl_Reader
242 //purpose  : 
243 //=======================================================================
244
245 STEPCAFControl_Reader::STEPCAFControl_Reader (const Handle(XSControl_WorkSession)& WS,
246                                               const Standard_Boolean scratch) :
247        myColorMode( Standard_True ),
248        myNameMode ( Standard_True ),
249        myLayerMode( Standard_True ),
250        myPropsMode( Standard_True ),
251            mySHUOMode ( Standard_False ),
252        myGDTMode  ( Standard_True ),
253        myMatMode  ( Standard_True )
254 {
255   STEPCAFControl_Controller::Init();
256   Init ( WS, scratch );
257 }
258
259
260 //=======================================================================
261 //function : Init
262 //purpose  : 
263 //=======================================================================
264
265 void STEPCAFControl_Reader::Init (const Handle(XSControl_WorkSession)& WS,
266                                   const Standard_Boolean scratch)
267 {
268 // necessary only in Writer, to set good actor:  WS->SelectNorm ( "STEP" );
269   myReader.SetWS (WS,scratch);
270   myFiles = new STEPCAFControl_DictionaryOfExternFile;
271 }
272
273
274 //=======================================================================
275 //function : ReadFile
276 //purpose  : 
277 //=======================================================================
278
279 IFSelect_ReturnStatus STEPCAFControl_Reader::ReadFile (const Standard_CString filename)
280 {
281   return myReader.ReadFile ( filename );
282 }
283
284
285 //=======================================================================
286 //function : NbRootsForTransfer
287 //purpose  : 
288 //=======================================================================
289
290 Standard_Integer STEPCAFControl_Reader::NbRootsForTransfer () 
291 {
292   return myReader.NbRootsForTransfer();
293 }
294
295
296 //=======================================================================
297 //function : TransferOneRoot
298 //purpose  : 
299 //=======================================================================
300
301 Standard_Boolean STEPCAFControl_Reader::TransferOneRoot (const Standard_Integer num,
302                                                          Handle(TDocStd_Document) &doc) 
303 {
304   TDF_LabelSequence Lseq;
305   return Transfer ( myReader, num, doc, Lseq );
306 }
307
308
309 //=======================================================================
310 //function : Transfer
311 //purpose  : 
312 //=======================================================================
313
314 Standard_Boolean STEPCAFControl_Reader::Transfer (Handle(TDocStd_Document) &doc)
315 {
316   TDF_LabelSequence Lseq;
317   return Transfer ( myReader, 0, doc, Lseq );
318 }
319
320
321 //=======================================================================
322 //function : Perform
323 //purpose  : 
324 //=======================================================================
325
326 Standard_Boolean STEPCAFControl_Reader::Perform (const Standard_CString filename,
327                                                  Handle(TDocStd_Document) &doc)
328 {
329   if ( ReadFile ( filename ) != IFSelect_RetDone ) return Standard_False;
330   return Transfer ( doc );
331 }
332   
333
334 //=======================================================================
335 //function : Perform
336 //purpose  : 
337 //=======================================================================
338
339 Standard_Boolean STEPCAFControl_Reader::Perform (const TCollection_AsciiString &filename,
340                                                  Handle(TDocStd_Document) &doc)
341 {
342   if ( ReadFile ( filename.ToCString() ) != IFSelect_RetDone ) return Standard_False;
343   return Transfer ( doc );
344 }
345   
346
347 //=======================================================================
348 //function : ExternFiles
349 //purpose  : 
350 //=======================================================================
351
352 const Handle(STEPCAFControl_DictionaryOfExternFile) &STEPCAFControl_Reader::ExternFiles () const
353 {
354   return myFiles;
355 }
356         
357
358 //=======================================================================
359 //function : ExternFile
360 //purpose  : 
361 //=======================================================================
362
363 Standard_Boolean STEPCAFControl_Reader::ExternFile (const Standard_CString name,
364                                                     Handle(STEPCAFControl_ExternFile) &ef) const
365 {
366   ef.Nullify();
367   if ( myFiles.IsNull() || ! myFiles->HasItem ( name ) ) 
368     return Standard_False;
369   ef = myFiles->Item ( name );
370   return Standard_True;
371 }
372
373
374 //=======================================================================
375 //function : Reader
376 //purpose  : 
377 //=======================================================================
378
379 STEPControl_Reader &STEPCAFControl_Reader::ChangeReader () 
380 {
381   return myReader;
382 }
383   
384
385 //=======================================================================
386 //function : Reader
387 //purpose  : 
388 //=======================================================================
389
390 const STEPControl_Reader &STEPCAFControl_Reader::Reader () const
391 {
392   return myReader;
393 }
394   
395
396 //=======================================================================
397 //function : FillShapesMap
398 //purpose  : auxiliary: fill a map by all compounds and their components
399 //=======================================================================
400
401 static void FillShapesMap (const TopoDS_Shape &S, TopTools_MapOfShape &map)
402 {
403   TopoDS_Shape S0 = S;
404   TopLoc_Location loc;
405   S0.Location ( loc );
406   map.Add ( S0 );
407   if ( S.ShapeType() != TopAbs_COMPOUND ) return;
408   for ( TopoDS_Iterator it(S); it.More(); it.Next() ) 
409     FillShapesMap ( it.Value(), map );
410 }
411
412
413 //=======================================================================
414 //function : Transfer
415 //purpose  : basic working method
416 //=======================================================================
417
418 Standard_Boolean STEPCAFControl_Reader::Transfer (STEPControl_Reader &reader,
419                                                   const Standard_Integer nroot,
420                                                   Handle(TDocStd_Document) &doc,
421                                                   TDF_LabelSequence &Lseq,
422                                                   const Standard_Boolean asOne)
423 {
424   reader.ClearShapes();
425   Standard_Integer i;
426   
427   // Read all shapes
428   Standard_Integer num = reader.NbRootsForTransfer();
429   if ( num <=0 ) return Standard_False;
430   if ( nroot ) {
431     if ( nroot > num ) return Standard_False;
432     reader.TransferOneRoot ( nroot );
433   }
434   else {
435     for ( i=1; i <= num; i++ ) reader.TransferOneRoot ( i );
436   }
437   num = reader.NbShapes();
438   if ( num <=0 ) return Standard_False;
439
440   // Fill a map of (top-level) shapes resulting from that transfer
441   // Only these shapes will be considered further
442   TopTools_MapOfShape ShapesMap, NewShapesMap;
443   for ( i=1; i <= num; i++ ) FillShapesMap ( reader.Shape(i), ShapesMap );
444   
445   // Collect information on shapes originating from SDRs
446   // this will be used to distinguish compounds representing assemblies
447   // from the ones representing hybrid models and shape sets
448   STEPCAFControl_DataMapOfShapePD ShapePDMap;
449   STEPCAFControl_DataMapOfPDExternFile PDFileMap;
450   Handle(Interface_InterfaceModel) Model = reader.Model();
451   Handle(Transfer_TransientProcess) TP = reader.WS()->TransferReader()->TransientProcess();
452   Standard_Integer nb = Model->NbEntities();
453
454   Handle(TColStd_HSequenceOfTransient) SeqPDS = new TColStd_HSequenceOfTransient;
455
456   for (i = 1; i <= nb; i ++) {
457     Handle(Standard_Transient) enti = Model->Value(i);
458     if(enti->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape))) {
459       // sequence for acceleration ReadMaterials
460       SeqPDS->Append(enti);
461     }
462     if ( enti->IsKind ( STANDARD_TYPE(StepBasic_ProductDefinition ) ) ) {
463       Handle(StepBasic_ProductDefinition) PD = 
464         Handle(StepBasic_ProductDefinition)::DownCast(enti);
465       Standard_Integer index = TP->MapIndex(PD);
466       if ( index >0 ) {
467         Handle(Transfer_Binder) binder = TP->MapItem (index);
468         TopoDS_Shape S = TransferBRep::ShapeResult(binder);
469         if ( ! S.IsNull() && ShapesMap.Contains(S) ) {
470           NewShapesMap.Add(S);
471           ShapePDMap.Bind ( S, PD ); 
472           Handle(STEPCAFControl_ExternFile) EF;
473           PDFileMap.Bind ( PD, EF );
474         }
475       }
476     }
477     if ( enti->IsKind ( STANDARD_TYPE(StepShape_ShapeRepresentation) ) ) {
478       Standard_Integer index = TP->MapIndex(enti);
479       if ( index >0 ) {
480         Handle(Transfer_Binder) binder = TP->MapItem (index);
481         TopoDS_Shape S = TransferBRep::ShapeResult(binder);
482         if ( ! S.IsNull() && ShapesMap.Contains(S) )
483           NewShapesMap.Add(S);
484       }
485     }
486   }
487
488   // get directory name of the main file
489   OSD_Path mainfile ( reader.WS()->LoadedFile() );
490   mainfile.SetName ( "" );
491   mainfile.SetExtension ( "" );
492   TCollection_AsciiString dpath;
493   mainfile.SystemName ( dpath );
494
495   // Load external references (only for relevant SDRs)
496   // and fill map SDR -> extern file
497   STEPConstruct_ExternRefs ExtRefs ( reader.WS() );
498   ExtRefs.LoadExternRefs();
499   for ( i=1; i <= ExtRefs.NbExternRefs(); i++ ) {
500     // check extern ref format
501     Handle(TCollection_HAsciiString) format = ExtRefs.Format(i);
502     if ( ! format.IsNull() ) {
503       static Handle(TCollection_HAsciiString) ap203 = new TCollection_HAsciiString ( "STEP AP203" );
504       static Handle(TCollection_HAsciiString) ap214 = new TCollection_HAsciiString ( "STEP AP214" );
505       if ( ! format->IsSameString ( ap203, Standard_False ) && 
506            ! format->IsSameString ( ap214, Standard_False ) ) {
507 #ifdef OCCT_DEBUG
508         cout << "Warning: STEPCAFControl_Reader::Transfer: Extern document is neither STEP AP203 nor AP214" << endl;
509 #else
510         continue;
511 #endif
512       }
513     }
514 #ifdef OCCT_DEBUG
515     else cout << "Warning: STEPCAFControl_Reader::Transfer: Extern document format not defined" << endl;
516 #endif
517     
518     // get and check filename of the current extern ref
519     const Standard_CString filename = ExtRefs.FileName(i);
520
521 #ifdef OCCT_DEBUG
522     cout<<"filename="<<filename<<endl;
523 #endif
524
525     if ( ! filename || ! filename[0] ) {
526 #ifdef OCCT_DEBUG
527       cout << "Warning: STEPCAFControl_Reader::Transfer: Extern reference file name is empty" << endl;
528 #endif
529       continue; // not a valid extern ref
530     }
531
532     // compute true path to the extern file
533     TCollection_AsciiString fullname = OSD_Path::AbsolutePath ( dpath, filename );
534     if ( fullname.Length() <= 0 ) fullname = filename;
535
536 /*    
537     char fullname[1024];
538     char *mainfile = reader.WS()->LoadedFile();
539     if ( ! mainfile ) mainfile = "";
540     Standard_Integer slash = 0;
541     for ( Standard_Integer k=0; mainfile[k]; k++ )
542       if ( mainfile[k] == '/' ) slash = k;
543     strncpy ( fullname, mainfile, slash );
544     sprintf ( &fullname[slash], "%s%s", ( mainfile[0] ? "/" : "" ), filename );
545 */
546     
547     // get and check PD associated with the current extern ref
548     Handle(StepBasic_ProductDefinition) PD = ExtRefs.ProdDef(i);
549     if ( PD.IsNull() ) continue; // not a valid extern ref
550     if ( ! PDFileMap.IsBound ( PD ) ) continue; // this PD is not concerned by current transfer
551     
552     // read extern file (or use existing data) and record its data
553     Handle(STEPCAFControl_ExternFile) EF = 
554       ReadExternFile ( filename, fullname.ToCString(), doc );
555     PDFileMap.Bind ( PD, EF );
556   }
557   
558   // and insert them to the document
559   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( doc->Main() );
560   if ( STool.IsNull() ) return Standard_False;
561   XCAFDoc_DataMapOfShapeLabel map;
562   if ( asOne )
563     Lseq.Append ( AddShape ( reader.OneShape(), STool, NewShapesMap, ShapePDMap, PDFileMap, map ) );
564   else {
565     for ( i=1; i <= num; i++ ) {
566       Lseq.Append ( AddShape ( reader.Shape(i), STool, NewShapesMap, ShapePDMap, PDFileMap, map ) );
567     }
568   }
569   
570   // read colors
571   if ( GetColorMode() )
572     ReadColors ( reader.WS(), doc, PDFileMap, map );
573   
574   // read names
575   if ( GetNameMode() )
576     ReadNames ( reader.WS(), doc, PDFileMap, map );
577
578   // read validation props
579   if ( GetPropsMode() )
580     ReadValProps ( reader.WS(), doc, PDFileMap, map );
581
582   // read layers
583   if ( GetLayerMode() )
584     ReadLayers ( reader.WS(), doc );
585   
586   // read SHUO entities from STEP model
587   if ( GetSHUOMode() )
588     ReadSHUOs ( reader.WS(), doc, PDFileMap, map );
589
590   // read GDT entities from STEP model
591   if(GetGDTMode())
592     ReadGDTs(reader.WS(),doc);
593
594   // read Material entities from STEP model
595   if(GetMatMode())
596     ReadMaterials(reader.WS(),doc,SeqPDS);
597
598   // Expand resulting CAF structure for sub-shapes (optionally with their
599   // names) if requested
600   ExpandSubShapes(STool, map, ShapePDMap);
601
602   return Standard_True;
603 }
604
605 //=======================================================================
606 //function : AddShape
607 //purpose  : 
608 //=======================================================================
609
610 TDF_Label STEPCAFControl_Reader::AddShape (const TopoDS_Shape &S, 
611                                            const Handle(XCAFDoc_ShapeTool) &STool,
612                                            const TopTools_MapOfShape &NewShapesMap,
613                                            const STEPCAFControl_DataMapOfShapePD &ShapePDMap,
614                                            const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
615                                            XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
616 {
617   // if shape has already been mapped, just return corresponding label
618   if ( ShapeLabelMap.IsBound ( S ) ) {
619     return ShapeLabelMap.Find ( S );
620   }
621   
622   // if shape is located, create instance
623   if ( ! S.Location().IsIdentity() ) {
624     TopoDS_Shape S0 = S;
625     TopLoc_Location loc;
626     S0.Location ( loc );
627     AddShape ( S0, STool, NewShapesMap, ShapePDMap, PDFileMap, ShapeLabelMap );
628     TDF_Label L = STool->AddShape ( S, Standard_False ); // should create reference
629     ShapeLabelMap.Bind ( S, L );
630     return L;
631   }
632   
633   // if shape is not compound, simple add it
634   if ( S.ShapeType() != TopAbs_COMPOUND ) {
635     TDF_Label L = STool->AddShape ( S, Standard_False );
636     ShapeLabelMap.Bind ( S, L );
637     return L;
638   }
639   
640   // for compounds, compute number of subshapes and check whether this is assembly
641   Standard_Boolean isAssembly = Standard_False;
642   Standard_Integer nbComponents = 0;
643   TopoDS_Iterator it;
644   for ( it.Initialize(S); it.More(); it.Next(), nbComponents++ ) {
645     TopoDS_Shape Sub0 = it.Value();
646     TopLoc_Location loc;
647     Sub0.Location ( loc );
648     if ( NewShapesMap.Contains ( Sub0 ) ) isAssembly = Standard_True;
649   }
650
651 //  if(nbComponents>0) isAssembly = Standard_True;
652   
653   // check whether it has associated external ref
654   TColStd_SequenceOfHAsciiString SHAS;
655   if ( ShapePDMap.IsBound ( S ) && PDFileMap.IsBound ( ShapePDMap.Find(S) ) ) {
656     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( ShapePDMap.Find(S) );
657     if ( ! EF.IsNull() ) {
658       // (store information on extern refs in the document)
659       SHAS.Append(EF->GetName());
660       // if yes, just return corresponding label
661       if ( ! EF->GetLabel().IsNull() ) {
662         // but if components >0, ignore extern ref!
663         if ( nbComponents <=0 ) {
664           ShapeLabelMap.Bind ( S, EF->GetLabel() );
665           STool->SetExternRefs(EF->GetLabel(),SHAS);
666           return EF->GetLabel();
667         }
668       }
669 #ifdef OCCT_DEBUG
670       if ( ! EF->GetLabel().IsNull() )
671         cout << "Warning: STEPCAFControl_Reader::AddShape: Non-empty shape with external ref; ref is ignored" << endl;
672       else if ( nbComponents <=0 ) 
673         cout << "Warning: STEPCAFControl_Reader::AddShape: Result of reading extern ref is Null" << endl;
674 #endif
675     }
676   }
677   
678   // add compound either as a whole,
679   if ( ! isAssembly ) {
680     TDF_Label L = STool->AddShape ( S, Standard_False );
681     if ( SHAS.Length() >0 ) STool->SetExternRefs(L,SHAS);
682     ShapeLabelMap.Bind ( S, L );
683     return L;
684   }
685   
686   // or as assembly, component-by-component
687   TDF_Label L = STool->NewShape();
688   for ( it.Initialize(S); it.More(); it.Next(), nbComponents++ ) {
689     TopoDS_Shape Sub0 = it.Value();
690     TopLoc_Location loc;
691     Sub0.Location ( loc );
692     TDF_Label subL = AddShape ( Sub0, STool, NewShapesMap, ShapePDMap, PDFileMap, ShapeLabelMap );
693     if ( ! subL.IsNull() ) {
694       STool->AddComponent ( L, subL, it.Value().Location() );
695     }
696   }
697   if ( SHAS.Length() >0 ) STool->SetExternRefs(L,SHAS);
698   ShapeLabelMap.Bind ( S, L );
699   //STool->SetShape ( L, S ); // it is necessary for assemblies OCC1747 // commemted by skl for OCC2941
700
701   return L;
702 }
703
704 //=======================================================================
705 //function : ReadExternFile
706 //purpose  : 
707 //=======================================================================
708
709 Handle(STEPCAFControl_ExternFile) STEPCAFControl_Reader::ReadExternFile (const Standard_CString file, 
710                                                                          const Standard_CString fullname, 
711                                                                          Handle(TDocStd_Document)& doc) 
712 {
713   // if the file is already read, associate it with SDR
714   if ( myFiles->HasItem ( file, Standard_True ) ) {
715     return myFiles->Item ( file );
716   }
717
718 #ifdef OCCT_DEBUG
719   cout << "Reading extern file: " << fullname << endl;
720 #endif
721  
722   // create new WorkSession and Reader
723   Handle(XSControl_WorkSession) newWS = new XSControl_WorkSession;
724   newWS->SelectNorm ( "STEP" );
725   STEPControl_Reader sr ( newWS, Standard_False );
726   
727   // start to fill the resulting ExternFile structure
728   Handle(STEPCAFControl_ExternFile) EF = new STEPCAFControl_ExternFile;
729   EF->SetWS ( newWS );
730   EF->SetName ( new TCollection_HAsciiString ( file ) );
731   
732   // read file
733   EF->SetLoadStatus ( sr.ReadFile ( fullname ) );
734   
735   // transfer in single-result mode
736   if ( EF->GetLoadStatus() == IFSelect_RetDone ) {
737     TDF_LabelSequence labels;
738     EF->SetTransferStatus ( Transfer ( sr, 0, doc, labels, Standard_True ) );
739     if ( labels.Length() >0 ) EF->SetLabel ( labels.Value(1) );
740   }
741   
742   // add read file to dictionary
743   myFiles->SetItem ( file, EF );
744   
745   return EF;
746 }
747
748
749 //=======================================================================
750 //function : SetColorToSubshape
751 //purpose  : auxilary
752 //=======================================================================
753 static void SetColorToSubshape(const Handle(XCAFDoc_ColorTool) & CTool,
754                                const TopoDS_Shape & S,
755                                const Quantity_Color& col,
756                                const XCAFDoc_ColorType type)
757 {
758   for (TopoDS_Iterator it(S); it.More(); it.Next())
759     if (! CTool->SetColor( it.Value(), col, type)) break;
760 }
761
762
763 //=======================================================================
764 //function : findStyledSR
765 //purpose  : auxilary
766 //=======================================================================
767 static void findStyledSR (const Handle(StepVisual_StyledItem) &style,
768                           Handle(StepShape_ShapeRepresentation)& aSR)
769 {
770   // search Shape Represenatation for component styled item
771   for ( Standard_Integer j=1; j <= style->NbStyles(); j++ ) {
772     Handle(StepVisual_PresentationStyleByContext) PSA = 
773       Handle(StepVisual_PresentationStyleByContext)::DownCast(style->StylesValue ( j ));
774     if ( PSA.IsNull() )
775       continue;
776     StepVisual_StyleContextSelect aStyleCntxSlct = PSA->StyleContext();
777     Handle(StepShape_ShapeRepresentation) aCurrentSR = 
778       Handle(StepShape_ShapeRepresentation)::DownCast(aStyleCntxSlct.Representation());
779     if ( aCurrentSR.IsNull() )
780       continue;
781     aSR = aCurrentSR;
782       break;
783   }
784 }
785
786
787 //=======================================================================
788 //function : ReadColors
789 //purpose  : 
790 //=======================================================================
791
792 Standard_Boolean STEPCAFControl_Reader::ReadColors (const Handle(XSControl_WorkSession) &WS,
793                                                     Handle(TDocStd_Document)& Doc,
794                                                     const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
795                                                     const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
796 {
797   STEPConstruct_Styles Styles ( WS );
798   if ( ! Styles.LoadStyles() ) {
799 #ifdef OCCT_DEBUG
800     cout << "Warning: no styles are found in the model" << endl;
801 #endif
802     return Standard_False;
803   }
804   // searching for invisible items in the model
805   Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
806   Styles.LoadInvisStyles( aHSeqOfInvisStyle );
807   
808   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( Doc->Main() );
809   if ( CTool.IsNull() ) return Standard_False;
810
811   // parse and search for color attributes
812   Standard_Integer nb = Styles.NbStyles();
813   for ( Standard_Integer i=1; i <= nb; i++ ) {
814     Handle(StepVisual_StyledItem) style = Styles.Style ( i );
815     if ( style.IsNull() ) continue;
816     
817     Standard_Boolean IsVisible = Standard_True;
818     // check the visibility of styled item.
819     for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++ ) {
820       if ( style != aHSeqOfInvisStyle->Value( si ) )
821         continue;
822       // found that current style is invisible.
823       IsVisible = Standard_False;
824       break;
825     }
826
827     Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol;
828     // check if it is component style
829     Standard_Boolean IsComponent = Standard_False;
830     if ( ! Styles.GetColors ( style, SurfCol, BoundCol, CurveCol, IsComponent ) && IsVisible )
831       continue;
832     
833     // find shape
834     TopoDS_Shape S = STEPConstruct::FindShape ( Styles.TransientProcess(), style->Item() );
835     Standard_Boolean isSkipSHUOstyle = Standard_False;
836     // take shape with real location.
837     while ( IsComponent ) {
838       // take SR of NAUO
839       Handle(StepShape_ShapeRepresentation) aSR;
840       findStyledSR( style, aSR );
841       // search for SR along model
842       if (aSR.IsNull())
843         break;
844 //       Handle(Interface_InterfaceModel) Model = WS->Model();
845       Handle(XSControl_TransferReader) TR = WS->TransferReader();
846       Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
847       Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings( aSR );
848       Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
849       for (subs.Start(); subs.More(); subs.Next()) {
850         aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
851         if ( aSDR.IsNull() )
852           continue;
853         StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
854         Handle(StepRepr_ProductDefinitionShape) PDS = 
855           Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
856         if ( PDS.IsNull() )
857           continue;
858         StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
859         
860         Handle(StepRepr_AssemblyComponentUsage) ACU = 
861           Handle(StepRepr_AssemblyComponentUsage)::DownCast(aCharDef.ProductDefinitionRelationship());
862         // PTV 10.02.2003 skip styled item that refer to SHUO
863         if (ACU->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
864           isSkipSHUOstyle = Standard_True;
865           break;
866         }
867         Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO =
868           Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(ACU);
869         if ( NAUO.IsNull() )
870           continue;
871         
872         TopoDS_Shape aSh;
873         // PTV 10.02.2003 to find component of assembly CORRECTLY
874         STEPConstruct_Tool Tool( WS );
875         TDF_Label aShLab = FindInstance ( NAUO, CTool->ShapeTool(), Tool, PDFileMap, ShapeLabelMap );
876         aSh = CTool->ShapeTool()->GetShape(aShLab);
877 //         Handle(Transfer_Binder) binder = TP->Find(NAUO);
878 //         if ( binder.IsNull() || ! binder->HasResult() )
879 //           continue;
880 //         aSh = TransferBRep::ShapeResult ( TP, binder );
881         if (!aSh.IsNull()) {
882           S = aSh;
883           break;
884         }
885       }
886       break;
887     }
888     if (isSkipSHUOstyle)
889       continue; // skip styled item which refer to SHUO
890     
891     if ( S.IsNull() )
892       continue;
893     
894     if ( ! SurfCol.IsNull() ) {
895       Quantity_Color col;
896       Styles.DecodeColor ( SurfCol, col );
897       if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorSurf ))
898         SetColorToSubshape( CTool, S, col, XCAFDoc_ColorSurf );
899     }
900     if ( ! BoundCol.IsNull() ) {
901       Quantity_Color col;
902       Styles.DecodeColor ( BoundCol, col );
903       if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorCurv ))
904         SetColorToSubshape(  CTool, S, col, XCAFDoc_ColorCurv );
905     }
906     if ( ! CurveCol.IsNull() ) {
907       Quantity_Color col;
908       Styles.DecodeColor ( CurveCol, col );
909       if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorCurv ))
910         SetColorToSubshape(  CTool, S, col, XCAFDoc_ColorCurv );
911     }
912     if ( !IsVisible ) {
913       // sets the invisibility for shape.
914       TDF_Label aInvL;
915       if ( CTool->ShapeTool()->Search( S, aInvL ) )
916         CTool->SetVisibility( aInvL, Standard_False );
917     }
918   }
919   CTool->ReverseChainsOfTreeNodes();
920   return Standard_True;
921 }
922
923 //=======================================================================
924 //function : GetLabelFromPD
925 //purpose  : 
926 //=======================================================================
927
928 static TDF_Label GetLabelFromPD (const Handle(StepBasic_ProductDefinition) &PD,
929                                  const Handle(XCAFDoc_ShapeTool) &STool,
930                                  const Handle(Transfer_TransientProcess) &TP,
931                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
932                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
933 {
934   TDF_Label L;
935   if ( PDFileMap.IsBound ( PD ) ) {
936     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( PD );
937     if ( ! EF.IsNull() ) {
938       L = EF->GetLabel();
939       if ( ! L.IsNull() ) return L;
940     }
941   }
942
943   TopoDS_Shape S;
944   Handle(Transfer_Binder) binder = TP->Find(PD);
945   if ( binder.IsNull() || ! binder->HasResult() ) return L;
946   S = TransferBRep::ShapeResult ( TP, binder );
947   if ( S.IsNull() ) return L;
948
949   if ( S.IsNull() ) return L;
950   if ( ShapeLabelMap.IsBound ( S ) )
951     L = ShapeLabelMap.Find ( S );
952   if ( L.IsNull() )
953     STool->Search ( S, L, Standard_True, Standard_True, Standard_False );
954   return L;
955 }
956
957 //=======================================================================
958 //function : FindInstance
959 //purpose  : 
960 //=======================================================================
961
962 TDF_Label STEPCAFControl_Reader::FindInstance (const Handle(StepRepr_NextAssemblyUsageOccurrence) &NAUO,
963                                                const Handle(XCAFDoc_ShapeTool) &STool,
964                                                const STEPConstruct_Tool &Tool,
965                                                const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
966                                                const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
967 {
968   TDF_Label L;
969   
970   // get shape resulting from CDSR (in fact, only location is interesting)
971   Handle(Transfer_TransientProcess) TP = Tool.TransientProcess();
972   Handle(Transfer_Binder) binder = TP->Find(NAUO);
973   if ( binder.IsNull() || ! binder->HasResult() ) {
974 #ifdef OCCT_DEBUG
975     cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << endl;
976 #endif
977     return L;
978   }
979   
980   TopoDS_Shape S = TransferBRep::ShapeResult ( TP, binder );
981   if ( S.IsNull() ) {
982 #ifdef OCCT_DEBUG
983     cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << endl;
984 #endif
985     return L;
986   }
987
988   // find component`s original label
989   Handle(StepBasic_ProductDefinition) PD = NAUO->RelatedProductDefinition();
990   if ( PD.IsNull() ) return L;
991   TDF_Label Lref = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
992   if ( Lref.IsNull() ) return L;
993   
994   // find main shape (assembly) label
995   PD.Nullify();
996   PD = NAUO->RelatingProductDefinition();
997   if ( PD.IsNull() ) return L;
998   TDF_Label L0 = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
999   if ( L0.IsNull() ) return L;
1000   
1001   // if CDSR and NAUO are reversed, swap labels
1002   Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1003   Interface_EntityIterator subs1 = Tool.Graph().Sharings(NAUO);
1004   for (subs1.Start(); subs1.More(); subs1.Next()) {
1005     Handle(StepRepr_ProductDefinitionShape) PDS = 
1006       Handle(StepRepr_ProductDefinitionShape)::DownCast(subs1.Value());
1007     if(PDS.IsNull()) continue;
1008     Interface_EntityIterator subs2 = Tool.Graph().Sharings(PDS);
1009     for (subs2.Start(); subs2.More(); subs2.Next()) {
1010       Handle(StepShape_ContextDependentShapeRepresentation) CDSRtmp = 
1011         Handle(StepShape_ContextDependentShapeRepresentation)::DownCast(subs2.Value());
1012       if (CDSRtmp.IsNull()) continue;
1013       CDSR = CDSRtmp;
1014     }
1015   }
1016   if (CDSR.IsNull()) return L;
1017 //  if ( STEPConstruct_Assembly::CheckSRRReversesNAUO ( Tool.Model(), CDSR ) ) {
1018 //    TDF_Label Lsw = L0; L0 = Lref; Lref = Lsw;
1019 //  }
1020   
1021   // iterate on components to find proper one
1022   TDF_LabelSequence seq;
1023   XCAFDoc_ShapeTool::GetComponents ( L0, seq );
1024   for ( Standard_Integer k=1; L.IsNull() && k <= seq.Length(); k++ ) {
1025     TDF_Label Lcomp = seq(k), Lref2;
1026     if ( XCAFDoc_ShapeTool::GetReferredShape ( Lcomp, Lref2 ) && 
1027         Lref2 == Lref &&
1028         S.Location() == XCAFDoc_ShapeTool::GetLocation ( Lcomp ) ) 
1029       L = Lcomp;
1030   }
1031   
1032   return L;
1033 }
1034
1035 //=======================================================================
1036 //function : ReadNames
1037 //purpose  : 
1038 //=======================================================================
1039
1040 Standard_Boolean STEPCAFControl_Reader::ReadNames (const Handle(XSControl_WorkSession) &WS,
1041                                                    Handle(TDocStd_Document)& Doc,
1042                                                    const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1043                                                    const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1044 {
1045   // get starting data
1046   Handle(Interface_InterfaceModel) Model = WS->Model();
1047   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1048   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1049   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1050   if ( STool.IsNull() ) return Standard_False;
1051   STEPConstruct_Tool Tool ( WS );
1052
1053   // iterate on model to find all SDRs and CDSRs
1054   Standard_Integer nb = Model->NbEntities();
1055   Handle(Standard_Type) tNAUO = STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence);
1056   Handle(Standard_Type) tPD  = STANDARD_TYPE(StepBasic_ProductDefinition);
1057   Handle(TCollection_HAsciiString) name;
1058   TDF_Label L;
1059   for (Standard_Integer i = 1; i <= nb; i++) {
1060     Handle(Standard_Transient) enti = Model->Value(i);
1061
1062     // get description of NAUO
1063     if ( enti->DynamicType() == tNAUO ) {
1064       L.Nullify();
1065       Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO = 
1066         Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(enti);
1067       if(NAUO.IsNull()) continue;
1068       Interface_EntityIterator subs = WS->Graph().Sharings(NAUO);
1069       for (subs.Start(); subs.More(); subs.Next()) {
1070         Handle(StepRepr_ProductDefinitionShape) PDS = 
1071           Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
1072         if(PDS.IsNull()) continue;
1073         Handle(StepBasic_ProductDefinitionRelationship) PDR = PDS->Definition().ProductDefinitionRelationship();
1074         if ( PDR.IsNull() ) continue;
1075         if ( PDR->HasDescription() && 
1076             PDR->Description()->Length() >0 ) name = PDR->Description();
1077         else if ( !PDR->Name().IsNull() && PDR->Name()->Length() >0 ) name = PDR->Name();
1078         else if ( !PDR->Id().IsNull()) name = PDR->Id();
1079         else name = new TCollection_HAsciiString;
1080       }
1081       // find proper label
1082       L = FindInstance ( NAUO, STool, Tool, PDFileMap, ShapeLabelMap );
1083       if ( L.IsNull() ) continue;
1084       TCollection_ExtendedString str ( name->String() );
1085       TDataStd_Name::Set ( L, str );
1086     }
1087
1088     // for PD get name of associated product
1089     if ( enti->DynamicType() == tPD ) {
1090       L.Nullify();
1091       Handle(StepBasic_ProductDefinition) PD = 
1092         Handle(StepBasic_ProductDefinition)::DownCast(enti);
1093       if(PD.IsNull()) continue;
1094       Handle(StepBasic_Product) Prod = PD->Formation()->OfProduct();
1095       if(!Prod->Name().IsNull() && Prod->Name()->UsefullLength()>0) name = Prod->Name();
1096       else if (!Prod->Id().IsNull()) name = Prod->Id();
1097       else name = new TCollection_HAsciiString;
1098       L = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
1099       if ( L.IsNull() ) continue;
1100       TCollection_ExtendedString str ( name->String() );
1101       TDataStd_Name::Set ( L, str );
1102     }
1103     // set a name to the document
1104     //TCollection_ExtendedString str ( name->String() );
1105     //TDataStd_Name::Set ( L, str );
1106   }
1107
1108   return Standard_True;
1109 }
1110
1111 //=======================================================================
1112 //function : GetLabelFromPD
1113 //purpose  : 
1114 //=======================================================================
1115
1116 static TDF_Label GetLabelFromPD (const Handle(StepBasic_ProductDefinition) &PD,
1117                                  const Handle(XCAFDoc_ShapeTool) &STool,
1118                                  const STEPConstruct_ValidationProps &Props,
1119                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1120                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1121 {
1122   TDF_Label L;
1123   if ( PDFileMap.IsBound ( PD ) ) {
1124     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( PD );
1125     if ( ! EF.IsNull() ) {
1126       L = EF->GetLabel();
1127       if ( ! L.IsNull() ) return L;
1128     }
1129   }
1130   TopoDS_Shape S = Props.GetPropShape ( PD );
1131   if ( S.IsNull() ) return L;
1132   if ( ShapeLabelMap.IsBound ( S ) )
1133     L = ShapeLabelMap.Find ( S );
1134   if ( L.IsNull() )
1135     STool->Search ( S, L, Standard_True, Standard_True, Standard_False );
1136   return L;
1137 }
1138
1139 //=======================================================================
1140 //function : ReadValProps
1141 //purpose  : 
1142 //=======================================================================
1143
1144 Standard_Boolean STEPCAFControl_Reader::ReadValProps (const Handle(XSControl_WorkSession) &WS,
1145                                                       Handle(TDocStd_Document)& Doc,
1146                                                       const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1147                                                       const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1148 {
1149   // get starting data
1150   Handle(Interface_InterfaceModel) Model = WS->Model();
1151   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1152   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1153   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1154   if ( STool.IsNull() ) return Standard_False;
1155
1156   // load props from the STEP model
1157   TColStd_SequenceOfTransient props;
1158   STEPConstruct_ValidationProps Props ( WS );
1159   if ( ! Props.LoadProps ( props ) ) {
1160 #ifdef OCCT_DEBUG
1161     cout << "Warning: no validation props found in the model" << endl;
1162 #endif
1163     return Standard_False;
1164   }
1165
1166   // interpret props one by one
1167   for (Standard_Integer i = 1; i <= props.Length(); i ++) {
1168     Handle(StepRepr_PropertyDefinitionRepresentation) PDR = 
1169       Handle(StepRepr_PropertyDefinitionRepresentation)::DownCast ( props.Value(i) );
1170     if ( PDR.IsNull() ) continue;
1171
1172     TDF_Label L;
1173
1174     Handle(StepRepr_PropertyDefinition) PD = PDR->Definition().PropertyDefinition();
1175     Interface_EntityIterator subs = Props.Graph().Shareds(PD);
1176     for (subs.Start(); L.IsNull() && subs.More(); subs.Next()) {
1177       if ( subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape)) ) {
1178         Handle(StepRepr_ProductDefinitionShape) PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
1179         if(PDS.IsNull()) continue;
1180         // find corresponding NAUO
1181         Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO;
1182         Interface_EntityIterator subs1 = Props.Graph().Shareds(PDS);
1183         for (subs1.Start(); NAUO.IsNull() && subs1.More(); subs1.Next()) {
1184           if ( subs1.Value()->IsKind(STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence)) ) 
1185             NAUO = Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subs1.Value());
1186         }
1187         if ( !NAUO.IsNull() ) {
1188           L = FindInstance ( NAUO, STool, WS, PDFileMap, ShapeLabelMap );
1189           if ( L.IsNull() ) continue;
1190         }
1191         else {
1192           // find corresponding ProductDefinition:
1193           Handle(StepBasic_ProductDefinition) ProdDef;
1194           Interface_EntityIterator subsPDS = Props.Graph().Shareds(PDS);
1195           for (subsPDS.Start(); ProdDef.IsNull() && subsPDS.More(); subsPDS.Next()) {
1196             if ( subsPDS.Value()->IsKind(STANDARD_TYPE(StepBasic_ProductDefinition)) ) 
1197               ProdDef = Handle(StepBasic_ProductDefinition)::DownCast(subsPDS.Value());
1198           }
1199           if ( ProdDef.IsNull() ) continue;
1200           L = GetLabelFromPD ( ProdDef, STool, Props, PDFileMap, ShapeLabelMap );
1201         }
1202       }
1203
1204       if ( subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)) ) {
1205         Handle(StepRepr_ShapeAspect) SA = Handle(StepRepr_ShapeAspect)::DownCast(subs.Value());
1206         if(SA.IsNull()) continue;
1207         // find ShapeRepresentation
1208         Handle(StepShape_ShapeRepresentation) SR;
1209         Interface_EntityIterator subs1 = Props.Graph().Sharings(SA);
1210         for(subs1.Start(); subs1.More() && SR.IsNull(); subs1.Next()) {
1211           Handle(StepRepr_PropertyDefinition) PropD1 = 
1212             Handle(StepRepr_PropertyDefinition)::DownCast(subs1.Value());
1213           if(PropD1.IsNull()) continue;
1214           Interface_EntityIterator subs2 = Props.Graph().Sharings(PropD1);
1215           for(subs2.Start(); subs2.More() && SR.IsNull(); subs2.Next()) {
1216             Handle(StepShape_ShapeDefinitionRepresentation) SDR =
1217               Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs2.Value());
1218             if(SDR.IsNull()) continue;
1219             SR = Handle(StepShape_ShapeRepresentation)::DownCast(SDR->UsedRepresentation());
1220           }
1221         }
1222         if(SR.IsNull()) continue;
1223         Handle(Transfer_Binder) binder;
1224         for(Standard_Integer ir=1; ir<=SR->NbItems() && binder.IsNull(); ir++) {
1225           if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_SolidModel))) {
1226             Handle(StepShape_SolidModel) SM = 
1227               Handle(StepShape_SolidModel)::DownCast(SR->ItemsValue(ir));
1228             binder = TP->Find(SM);
1229           }
1230           else if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_ShellBasedSurfaceModel))) {
1231             Handle(StepShape_ShellBasedSurfaceModel) SBSM =
1232               Handle(StepShape_ShellBasedSurfaceModel)::DownCast(SR->ItemsValue(ir));
1233             binder = TP->Find(SBSM);
1234           }
1235           else if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_GeometricSet))) {
1236             Handle(StepShape_GeometricSet) GS =
1237               Handle(StepShape_GeometricSet)::DownCast(SR->ItemsValue(ir));
1238             binder = TP->Find(GS);
1239           }
1240         }
1241         if ( binder.IsNull() || ! binder->HasResult() ) continue;
1242         TopoDS_Shape S;
1243         S = TransferBRep::ShapeResult ( TP, binder );
1244         if(S.IsNull()) continue;
1245         if ( ShapeLabelMap.IsBound ( S ) )
1246           L = ShapeLabelMap.Find ( S );
1247         if ( L.IsNull() )
1248           STool->Search ( S, L, Standard_True, Standard_True, Standard_True );
1249       }
1250     }
1251
1252     if(L.IsNull()) continue;
1253       
1254     // decode validation properties
1255     Handle(StepRepr_Representation) rep = PDR->UsedRepresentation();
1256     for ( Standard_Integer j=1; j <= rep->NbItems(); j++ ) {
1257       Handle(StepRepr_RepresentationItem) ent = rep->ItemsValue(j);
1258       Standard_Boolean isArea;
1259       Standard_Real val;
1260       gp_Pnt pos;
1261       if ( Props.GetPropReal ( ent, val, isArea ) ) {
1262         if ( isArea ) XCAFDoc_Area::Set ( L, val );
1263         else XCAFDoc_Volume::Set ( L, val );
1264       }
1265       else if ( Props.GetPropPnt ( ent, rep->ContextOfItems(), pos ) ) {
1266         XCAFDoc_Centroid::Set ( L, pos );
1267       }
1268     }
1269   }
1270   return Standard_True;
1271 }
1272
1273 //=======================================================================
1274 //function : ReadLayers
1275 //purpose  : 
1276 //=======================================================================
1277
1278 Standard_Boolean STEPCAFControl_Reader::ReadLayers (const Handle(XSControl_WorkSession) &WS,
1279                                                     Handle(TDocStd_Document)& Doc) const
1280 {
1281   Handle(Interface_InterfaceModel) Model = WS->Model();
1282   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1283   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1284   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1285   if ( STool.IsNull() ) return Standard_False;
1286   Handle(XCAFDoc_LayerTool) LTool = XCAFDoc_DocumentTool::LayerTool( Doc->Main() );
1287   if ( LTool.IsNull() ) return Standard_False;
1288   
1289   Handle(Standard_Type) tSVPLA = STANDARD_TYPE(StepVisual_PresentationLayerAssignment);
1290   Standard_Integer nb = Model->NbEntities();
1291   Handle(TCollection_HAsciiString) name;
1292   
1293   for (Standard_Integer i = 1; i <= nb; i ++) {
1294     Handle(Standard_Transient) enti = Model->Value(i);
1295     if ( ! enti->IsKind ( tSVPLA ) ) continue;
1296     Handle(StepVisual_PresentationLayerAssignment) SVPLA = 
1297       Handle(StepVisual_PresentationLayerAssignment)::DownCast(enti);
1298     
1299     Handle(TCollection_HAsciiString) descr = SVPLA->Description();
1300     Handle(TCollection_HAsciiString) hName = SVPLA->Name();
1301     TCollection_ExtendedString aLayerName ( hName->String() );
1302      
1303     // find a target shape and its label in the document
1304     for (Standard_Integer j = 1; j <= SVPLA->NbAssignedItems(); j++ ) {
1305       StepVisual_LayeredItem LI = SVPLA->AssignedItemsValue(j);
1306       Handle(Transfer_Binder) binder = TP->Find( LI.Value() );
1307       if ( binder.IsNull() || ! binder->HasResult() ) continue;
1308       
1309       TopoDS_Shape S = TransferBRep::ShapeResult ( TP, binder );
1310       if ( S.IsNull() ) continue;
1311         
1312       TDF_Label shL;
1313       if ( ! STool->Search ( S, shL, Standard_True, Standard_True, Standard_True ) ) continue;
1314       LTool->SetLayer ( shL, aLayerName );
1315     }
1316     
1317     // check invisibility
1318     Interface_EntityIterator subs = WS->Graph().Sharings(SVPLA);
1319     for (subs.Start(); subs.More(); subs.Next()) {
1320       if ( ! subs.Value()->IsKind(STANDARD_TYPE(StepVisual_Invisibility)) ) continue;
1321 #ifdef OCCT_DEBUG
1322       cout<< "\tLayer \"" << aLayerName << "\" is invisible"<<endl;
1323 #endif
1324       //TDF_Label InvLayerLab = LTool->FindLayer(aLayerName);
1325       TDF_Label InvLayerLab = LTool->AddLayer(aLayerName); //skl for OCC3926
1326       Handle(TDataStd_UAttribute) aUAttr;
1327       aUAttr->Set( InvLayerLab, XCAFDoc::InvisibleGUID() );
1328     }
1329   }
1330   return Standard_True;
1331 }
1332
1333 //=======================================================================
1334 //function : ReadSHUOs
1335 //purpose  : 
1336 //=======================================================================
1337
1338 static Standard_Boolean findNextSHUOlevel (const Handle(XSControl_WorkSession) &WS,
1339                                            const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1340                                            const Handle(XCAFDoc_ShapeTool)& STool,
1341                                            const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1342                                            const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap,
1343                                            TDF_LabelSequence& aLabels)
1344 {
1345   Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings(SHUO);
1346   Handle(StepRepr_SpecifiedHigherUsageOccurrence) subSHUO;
1347   for (subs.Start(); subs.More(); subs.Next()) {
1348     if (subs.Value()->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
1349       subSHUO = Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(subs.Value());
1350       break;
1351     }
1352   }
1353   if (subSHUO.IsNull())
1354     return Standard_False;
1355   
1356   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO =
1357     Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subSHUO->NextUsage());
1358   if (NUNAUO.IsNull())
1359     return Standard_False;
1360 //   Handle(Interface_InterfaceModel) Model = WS->Model();
1361 //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1362 //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1363 //   Handle(Transfer_Binder) binder = TP->Find(NUNAUO);
1364 //   if ( binder.IsNull() || ! binder->HasResult() )
1365 //     return Standard_False;
1366 //   TopoDS_Shape NUSh = TransferBRep::ShapeResult ( TP, binder );
1367   // get label of NAUO next level
1368   TDF_Label NULab;
1369   STEPConstruct_Tool Tool( WS );
1370   NULab = STEPCAFControl_Reader::FindInstance ( NUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1371 //   STool->Search(NUSh, NUlab);
1372   if (NULab.IsNull())
1373     return Standard_False;
1374   aLabels.Append( NULab );
1375   // and check by recurse.
1376   findNextSHUOlevel( WS, subSHUO, STool, PDFileMap, ShapeLabelMap, aLabels );
1377   return Standard_True;
1378 }
1379
1380
1381 //=======================================================================
1382 //function : setSHUOintoDoc
1383 //purpose  : auxilary
1384 //=======================================================================
1385 static TDF_Label setSHUOintoDoc (const Handle(XSControl_WorkSession) &WS,
1386                                  const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1387                                  const Handle(XCAFDoc_ShapeTool)& STool,
1388                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1389                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1390 {
1391   TDF_Label aMainLabel;
1392   // get upper usage NAUO from SHUO.
1393   Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO =
1394     Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(SHUO->UpperUsage());
1395   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO =
1396     Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(SHUO->NextUsage());
1397   if ( UUNAUO.IsNull() || NUNAUO.IsNull() ) {
1398 #ifdef OCCT_DEBUG
1399     cout << "Warning: " << __FILE__ <<": Upper_usage or Next_usage of styled SHUO is null. Skip it" << endl;
1400 #endif
1401     return aMainLabel;
1402   }
1403 //   Handle(Interface_InterfaceModel) Model = WS->Model();
1404 //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1405 //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1406 //   TopoDS_Shape UUSh, NUSh;
1407 //   Handle(Transfer_Binder) binder = TP->Find(UUNAUO);
1408 //   if ( binder.IsNull() || ! binder->HasResult() )
1409 //     return aMainLabel;
1410 //   UUSh = TransferBRep::ShapeResult ( TP, binder );
1411 //   binder = TP->Find(NUNAUO);
1412 //   if ( binder.IsNull() || ! binder->HasResult() )
1413 //     return aMainLabel;
1414 //   NUSh = TransferBRep::ShapeResult ( TP, binder );
1415
1416   // get first labels for first SHUO attribute
1417   TDF_Label UULab, NULab;
1418   STEPConstruct_Tool Tool( WS );
1419   UULab = STEPCAFControl_Reader::FindInstance ( UUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1420   NULab = STEPCAFControl_Reader::FindInstance ( NUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1421   
1422 //   STool->Search(UUSh, UULab);
1423 //   STool->Search(NUSh, NULab);
1424   if (UULab.IsNull() || NULab.IsNull()) return aMainLabel;
1425   //create sequence fo labels to set SHUO structure into the document
1426   TDF_LabelSequence ShuoLabels;
1427   ShuoLabels.Append( UULab );
1428   ShuoLabels.Append( NULab );
1429   // add all other labels of sub SHUO entities
1430   findNextSHUOlevel( WS, SHUO, STool, PDFileMap, ShapeLabelMap, ShuoLabels );
1431   // last accord for SHUO
1432   Handle(XCAFDoc_GraphNode) anSHUOAttr;
1433   if ( STool->SetSHUO( ShuoLabels, anSHUOAttr ) )
1434     aMainLabel = anSHUOAttr->Label();
1435   
1436   return aMainLabel;
1437 }
1438
1439
1440 //=======================================================================
1441 //function : ReadSHUOs
1442 //purpose  : 
1443 //=======================================================================
1444
1445 Standard_Boolean STEPCAFControl_Reader::ReadSHUOs (const Handle(XSControl_WorkSession) &WS,
1446                                                    Handle(TDocStd_Document)& Doc,
1447                                                    const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1448                                                    const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1449 {
1450   // the big part code duplication from ReadColors.
1451   // It is possible to share this code functionality, just to decide how ???
1452   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( Doc->Main() );
1453   Handle(XCAFDoc_ShapeTool) STool = CTool->ShapeTool();
1454   
1455   STEPConstruct_Styles Styles ( WS );
1456   if ( ! Styles.LoadStyles() ) {
1457 #ifdef OCCT_DEBUG
1458     cout << "Warning: no styles are found in the model" << endl;
1459 #endif
1460     return Standard_False;
1461   }
1462   // searching for invisible items in the model
1463   Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
1464   Styles.LoadInvisStyles( aHSeqOfInvisStyle );
1465   // parse and search for color attributes
1466   Standard_Integer nb = Styles.NbStyles();
1467   for ( Standard_Integer i=1; i <= nb; i++ ) {
1468     Handle(StepVisual_StyledItem) style = Styles.Style ( i );
1469     if ( style.IsNull() ) continue;
1470     
1471     Standard_Boolean IsVisible = Standard_True;
1472     // check the visibility of styled item.
1473     for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++ ) {
1474       if ( style != aHSeqOfInvisStyle->Value( si ) )
1475         continue;
1476       // found that current style is invisible.
1477 #ifdef OCCT_DEBUG
1478       cout << "Warning: item No " << i << "(" << style->Item()->DynamicType()->Name() << ") is invisible" << endl;
1479 #endif
1480       IsVisible = Standard_False;
1481       break;
1482     }
1483
1484     Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol;
1485     // check if it is component style
1486     Standard_Boolean IsComponent = Standard_False;
1487     if ( ! Styles.GetColors ( style, SurfCol, BoundCol, CurveCol, IsComponent ) && IsVisible )
1488       continue;
1489     if (!IsComponent)
1490       continue;
1491     Handle(StepShape_ShapeRepresentation) aSR;
1492     findStyledSR( style, aSR );
1493     // search for SR along model
1494     if ( aSR.IsNull() )
1495       continue;
1496     Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings( aSR );
1497     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
1498     for (subs.Start(); subs.More(); subs.Next()) {
1499       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
1500       if ( aSDR.IsNull() )
1501         continue;
1502       StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
1503       Handle(StepRepr_ProductDefinitionShape) PDS = 
1504         Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
1505       if ( PDS.IsNull() )
1506         continue;
1507       StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
1508       Handle(StepRepr_SpecifiedHigherUsageOccurrence) SHUO =
1509         Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(aCharDef.ProductDefinitionRelationship());
1510       if ( SHUO.IsNull() )
1511         continue;
1512       
1513       // set the SHUO structure to the document
1514       TDF_Label aLabelForStyle = setSHUOintoDoc( WS, SHUO, STool, PDFileMap, ShapeLabelMap );
1515       if ( aLabelForStyle.IsNull() ) {
1516 #ifdef OCCT_DEBUG
1517         cout << "Warning: " << __FILE__ <<": coudnot create SHUO structure in the document" << endl;
1518 #endif
1519         continue;
1520       }
1521       // now set the style to the SHUO main label.
1522       if ( ! SurfCol.IsNull() ) {
1523         Quantity_Color col;
1524         Styles.DecodeColor ( SurfCol, col );
1525         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorSurf );
1526       }
1527       if ( ! BoundCol.IsNull() ) {
1528         Quantity_Color col;
1529         Styles.DecodeColor ( BoundCol, col );
1530         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorCurv );
1531       }
1532       if ( ! CurveCol.IsNull() ) {
1533         Quantity_Color col;
1534         Styles.DecodeColor ( CurveCol, col );
1535         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorCurv );
1536       }
1537       if ( !IsVisible )
1538         // sets the invisibility for shape.
1539         CTool->SetVisibility( aLabelForStyle, Standard_False );
1540       
1541     } // end search SHUO by SDR
1542   } // end iterates on styles
1543       
1544   return Standard_True;
1545 }
1546
1547
1548 //=======================================================================
1549 //function : GetLengthConversionFactor
1550 //purpose  : 
1551 //=======================================================================
1552 static Standard_Boolean GetLengthConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1553                                                   Standard_Real& afact)
1554 {
1555   afact=1.;
1556   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndLengthUnit)) ) return Standard_False;
1557   Handle(StepBasic_ConversionBasedUnitAndLengthUnit) CBULU =
1558     Handle(StepBasic_ConversionBasedUnitAndLengthUnit)::DownCast(NU);
1559   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBULU->ConversionFactor();
1560   afact = MWUCBU->ValueComponent();
1561   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1562   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1563     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1564     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1565       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1566       if(SU->Name()==StepBasic_sunMetre) {
1567         if(SU->HasPrefix()) 
1568           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1569         // convert m to mm
1570         afact *= 1000.;
1571       }
1572     }
1573   }
1574   return Standard_True;
1575 }
1576
1577
1578 //=======================================================================
1579 //function : GetMassConversionFactor
1580 //purpose  : 
1581 //=======================================================================
1582 static Standard_Boolean GetMassConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1583                                                 Standard_Real& afact)
1584 {
1585   afact=1.;
1586   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndMassUnit)) ) return Standard_False;
1587   Handle(StepBasic_ConversionBasedUnitAndMassUnit) CBUMU =
1588     Handle(StepBasic_ConversionBasedUnitAndMassUnit)::DownCast(NU);
1589   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBUMU->ConversionFactor();
1590   afact = MWUCBU->ValueComponent();
1591   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1592   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1593     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1594     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1595       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1596       if(SU->Name()==StepBasic_sunGram) {
1597         if(SU->HasPrefix())
1598           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1599       }
1600     }
1601   }
1602   return Standard_True;
1603 }
1604
1605
1606 //=======================================================================
1607 //function : ReadDatums
1608 //purpose  : auxilary
1609 //=======================================================================
1610 static Standard_Boolean ReadDatums(const Handle(XCAFDoc_ShapeTool) &STool,
1611                                    const Handle(XCAFDoc_DimTolTool) &DGTTool,
1612                                    const Interface_Graph &graph,
1613                                    Handle(Transfer_TransientProcess) &TP,
1614                                    const TDF_Label TolerL,
1615                                    const Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR)
1616 {
1617   if(GTWDR.IsNull()) return Standard_False;
1618   Handle(StepDimTol_HArray1OfDatumReference) HADR = GTWDR->DatumSystem();
1619   if(HADR.IsNull()) return Standard_False;
1620   for(Standard_Integer idr=1; idr<=HADR->Length(); idr++) {
1621     Handle(StepDimTol_DatumReference) DR = HADR->Value(idr);
1622     Handle(StepDimTol_Datum) aDatum = DR->ReferencedDatum();
1623     if(aDatum.IsNull()) continue;
1624     Interface_EntityIterator subs4 = graph.Sharings(aDatum);
1625     for(subs4.Start(); subs4.More(); subs4.Next()) {
1626       Handle(StepRepr_ShapeAspectRelationship) SAR = 
1627         Handle(StepRepr_ShapeAspectRelationship)::DownCast(subs4.Value());
1628       if(SAR.IsNull()) continue;
1629       Handle(StepDimTol_DatumFeature) DF = 
1630         Handle(StepDimTol_DatumFeature)::DownCast(SAR->RelatingShapeAspect());
1631       if(DF.IsNull()) continue;
1632       Interface_EntityIterator subs5 = graph.Sharings(DF);
1633       Handle(StepRepr_PropertyDefinition) PropDef;
1634       for(subs5.Start(); subs5.More() && PropDef.IsNull(); subs5.Next()) {
1635         PropDef = Handle(StepRepr_PropertyDefinition)::DownCast(subs5.Value());
1636       }
1637       if(PropDef.IsNull()) continue;
1638       Handle(StepShape_AdvancedFace) AF;
1639       subs5 = graph.Sharings(PropDef);
1640       for(subs5.Start(); subs5.More(); subs5.Next()) {
1641         Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
1642           Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs5.Value());
1643         if(!SDR.IsNull()) {
1644           Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
1645           if( !Repr.IsNull() && Repr->NbItems()>0 ) {
1646             Handle(StepRepr_RepresentationItem) RI = Repr->ItemsValue(1);
1647             AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
1648           }
1649         }
1650       }
1651       if(AF.IsNull()) return Standard_False;
1652       Standard_Integer index = TP->MapIndex(AF);
1653       TopoDS_Shape aSh;
1654       if(index >0) {
1655         Handle(Transfer_Binder) binder = TP->MapItem(index);
1656         aSh = TransferBRep::ShapeResult(binder);
1657       }
1658       if(aSh.IsNull()) continue; 
1659       TDF_Label shL;
1660       if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
1661       DGTTool->SetDatum(shL,TolerL,PropDef->Name(),PropDef->Description(),aDatum->Identification());
1662     }
1663   }
1664   return Standard_True;
1665 }
1666
1667
1668 //=======================================================================
1669 //function : ReadGDTs
1670 //purpose  : 
1671 //=======================================================================
1672
1673 Standard_Boolean STEPCAFControl_Reader::ReadGDTs(const Handle(XSControl_WorkSession) &WS,
1674                                                  Handle(TDocStd_Document)& Doc) const
1675 {
1676   Handle(Interface_InterfaceModel) Model = WS->Model();
1677   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1678   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1679   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1680   Handle(XCAFDoc_DimTolTool) DGTTool = XCAFDoc_DocumentTool::DimTolTool( Doc->Main() );
1681   if ( DGTTool.IsNull() ) return Standard_False;
1682   
1683   Standard_Integer nb = Model->NbEntities();
1684   const Interface_Graph& graph = TP->Graph();
1685   for(Standard_Integer i=1; i<=nb; i++) {
1686     Handle(Standard_Transient) ent = Model->Value(i);
1687     if(ent->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect))) {
1688       Handle(StepRepr_ShapeAspect) SA = Handle(StepRepr_ShapeAspect)::DownCast(ent);
1689       // find RepresentationItem for current ShapeAspect
1690       Handle(StepRepr_RepresentationItem) RI;
1691       Handle(StepRepr_PropertyDefinition) PropD;
1692       Interface_EntityIterator subs3 = graph.Sharings(SA);
1693       for(subs3.Start(); subs3.More() && PropD.IsNull(); subs3.Next()) {
1694         PropD = Handle(StepRepr_PropertyDefinition)::DownCast(subs3.Value());
1695       }
1696       if(PropD.IsNull()) continue;
1697       Interface_EntityIterator subs4 = graph.Sharings(PropD);
1698       for(subs4.Start(); subs4.More(); subs4.Next()) {
1699         Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
1700           Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs4.Value());
1701         if(!SDR.IsNull()) {
1702           Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
1703           if( !Repr.IsNull() && Repr->NbItems()>0 ) {
1704             RI = Repr->ItemsValue(1);
1705           }
1706         }
1707       }
1708       if(RI.IsNull()) continue;
1709       // read DGT entities:
1710       subs3 = graph.Sharings(SA);
1711       for(subs3.Start(); subs3.More(); subs3.Next()) {
1712         if(subs3.Value()->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
1713           // read dimensions
1714           Handle(StepShape_EdgeCurve) EC = Handle(StepShape_EdgeCurve)::DownCast(RI);
1715           if(EC.IsNull()) continue;
1716           Handle(TCollection_HAsciiString) aName;
1717           Handle(StepShape_DimensionalSize) DimSize = 
1718             Handle(StepShape_DimensionalSize)::DownCast(subs3.Value());
1719           Standard_Real dim1=-1.,dim2=-1.;
1720           subs4 = graph.Sharings(DimSize);
1721           for(subs4.Start(); subs4.More(); subs4.Next()) {
1722             Handle(StepShape_DimensionalCharacteristicRepresentation) DimCharR = 
1723               Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(subs4.Value());
1724             if(!DimCharR.IsNull()) {
1725               Handle(StepShape_ShapeDimensionRepresentation) SDimR = DimCharR->Representation();
1726               if(!SDimR.IsNull() && SDimR->NbItems()>0) {
1727                 Handle(StepRepr_RepresentationItem) RI = SDimR->ItemsValue(1);
1728                 Handle(StepRepr_ValueRange) VR = Handle(StepRepr_ValueRange)::DownCast(RI);
1729                 if(!VR.IsNull()) {
1730                   aName = VR->Name();
1731                   //StepRepr_CompoundItemDefinition CID = VR->ItemElement();
1732                   //if(CID.IsNull()) continue;
1733                   //Handle(StepRepr_CompoundItemDefinitionMember) CIDM = 
1734                   //  Handle(StepRepr_CompoundItemDefinitionMember)::DownCast(CID.Value());
1735                   //if(CIDM.IsNull()) continue;
1736                   //if(CIDM->ArrTransient().IsNull()) continue;
1737                   //Handle(StepRepr_HArray1OfRepresentationItem) HARI;
1738                   //if(CID.CaseMem(CIDM)==1)
1739                   //  HARI = CID.ListRepresentationItem();
1740                   //if(CID.CaseMem(CIDM)==2)
1741                   //  HARI = CID.SetRepresentationItem();
1742                   Handle(StepRepr_HArray1OfRepresentationItem) HARI = VR->ItemElement();
1743                   if(HARI.IsNull()) continue;
1744                   if(HARI->Length()>0) {
1745                     Handle(StepRepr_RepresentationItem) RI1 =
1746                       Handle(StepRepr_RepresentationItem)::DownCast(HARI->Value(1));
1747                     if(RI1.IsNull()) continue;
1748                     if(RI1->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
1749                       Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
1750                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI1);
1751                       dim1 = RILMWU->GetMeasureWithUnit()->ValueComponent();
1752                       StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
1753                       Standard_Real afact=1.;
1754                       if(anUnit.IsNull()) continue;
1755                       if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
1756                       Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
1757                       if(GetLengthConversionFactor(NU,afact)) dim1=dim1*afact;
1758                     }
1759                   }
1760                   if(HARI->Length()>1) {
1761                     Handle(StepRepr_RepresentationItem) RI2 =
1762                       Handle(StepRepr_RepresentationItem)::DownCast(HARI->Value(2));
1763                     if(RI2.IsNull()) continue;
1764                     if(RI2->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
1765                       Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
1766                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI2);
1767                       dim2 = RILMWU->GetMeasureWithUnit()->ValueComponent();
1768                       StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
1769                       Standard_Real afact=1.;
1770                       if(anUnit.IsNull()) continue;
1771                       if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
1772                       Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
1773                       if(GetLengthConversionFactor(NU,afact)) dim2 = dim2*afact;
1774                     }
1775                   }
1776                 }
1777               }
1778             }
1779           }
1780           if(dim1<0) continue;
1781           if(dim2<0) dim2=dim1;
1782           //cout<<"DimensionalSize: dim1="<<dim1<<"  dim2="<<dim2<<endl;
1783           // now we know edge_curve and value range therefore
1784           // we can create corresponding D&GT labels
1785           Standard_Integer index = TP->MapIndex(EC);
1786           TopoDS_Shape aSh;
1787           if(index >0) {
1788             Handle(Transfer_Binder) binder = TP->MapItem(index);
1789             aSh = TransferBRep::ShapeResult(binder);
1790           }
1791           if(aSh.IsNull()) continue; 
1792           TDF_Label shL;
1793           if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
1794           Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1,2);
1795           arr->SetValue(1,dim1);
1796           arr->SetValue(2,dim2);
1797           DGTTool->SetDimTol(shL,1,arr,aName,DimSize->Name());
1798         }
1799         // read tolerances and datums
1800         else if(subs3.Value()->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
1801           Handle(StepDimTol_GeometricTolerance) GT =
1802             Handle(StepDimTol_GeometricTolerance)::DownCast(subs3.Value());
1803           // read common data for tolerance
1804           //Standard_Real dim = GT->Magnitude()->ValueComponent();
1805           Handle (StepBasic_MeasureWithUnit) dim3 = GT->Magnitude();
1806           if(dim3.IsNull()) continue;
1807           Standard_Real dim = dim3->ValueComponent();
1808           StepBasic_Unit anUnit = GT->Magnitude()->UnitComponent();
1809           Standard_Real afact=1.;
1810           if(anUnit.IsNull()) continue;
1811           if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
1812           Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
1813           if(GetLengthConversionFactor(NU,afact)) dim = dim*afact;
1814           //cout<<"GeometricTolerance: Magnitude = "<<dim<<endl;
1815           Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1,1);
1816           arr->SetValue(1,dim);
1817           Handle(TCollection_HAsciiString) aName = GT->Name();
1818           Handle(TCollection_HAsciiString) aDescription = GT->Description();
1819           Handle(StepShape_AdvancedFace) AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
1820           if(AF.IsNull()) continue;
1821           Standard_Integer index = TP->MapIndex(AF);
1822           TopoDS_Shape aSh;
1823           if(index >0) {
1824             Handle(Transfer_Binder) binder = TP->MapItem(index);
1825             aSh = TransferBRep::ShapeResult(binder);
1826           }
1827           if(aSh.IsNull()) continue; 
1828           TDF_Label shL;
1829           if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
1830           // read specific data for tolerance
1831           if(GT->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol))) {
1832             Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol) GTComplex =
1833               Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol)::DownCast(subs3.Value());
1834             Standard_Integer kind=20;
1835             Handle(StepDimTol_ModifiedGeometricTolerance) MGT = 
1836               GTComplex->GetModifiedGeometricTolerance();
1837             if(!MGT.IsNull()) {
1838               kind = kind + MGT->Modifier()+1;
1839             }
1840             TDF_Label TolerL = DGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
1841             // translate datums connected with this tolerance
1842             Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
1843               GTComplex->GetGeometricToleranceWithDatumReference();
1844             if(!GTWDR.IsNull()) {
1845               ReadDatums(STool,DGTTool,graph,TP,TolerL,GTWDR);
1846             }
1847           }
1848           else if(GT->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithDatumReference))) {
1849             Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
1850               Handle(StepDimTol_GeometricToleranceWithDatumReference)::DownCast(subs3.Value());
1851             if(GTWDR.IsNull()) continue;
1852             Standard_Integer kind = 0;
1853             if     (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_AngularityTolerance)))       kind = 24;
1854             else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CircularRunoutTolerance)))   kind = 25;
1855             else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CoaxialityTolerance)))       kind = 26;
1856             else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ConcentricityTolerance)))    kind = 27;
1857             else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ParallelismTolerance)))      kind = 28;
1858             else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_PerpendicularityTolerance))) kind = 29;
1859             else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_SymmetryTolerance)))         kind = 30;
1860             else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_TotalRunoutTolerance)))      kind = 31;
1861             //cout<<"GTWDR: kind="<<kind<<endl;
1862             TDF_Label TolerL = DGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
1863             ReadDatums(STool,DGTTool,graph,TP,TolerL,GTWDR);
1864           }
1865           else if(GT->IsKind(STANDARD_TYPE(StepDimTol_ModifiedGeometricTolerance))) {
1866             Handle(StepDimTol_ModifiedGeometricTolerance) MGT =
1867               Handle(StepDimTol_ModifiedGeometricTolerance)::DownCast(subs3.Value());
1868             Standard_Integer kind = 35 + MGT->Modifier();
1869             DGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
1870           }
1871           else if(GT->IsKind(STANDARD_TYPE(StepDimTol_CylindricityTolerance))) {
1872             DGTTool->SetDimTol(shL,38,arr,aName,aDescription);
1873           }
1874           else if(GT->IsKind(STANDARD_TYPE(StepDimTol_FlatnessTolerance))) {
1875             DGTTool->SetDimTol(shL,39,arr,aName,aDescription);
1876           }
1877           else if(GT->IsKind(STANDARD_TYPE(StepDimTol_LineProfileTolerance))) {
1878             DGTTool->SetDimTol(shL,40,arr,aName,aDescription);
1879           }
1880           else if(GT->IsKind(STANDARD_TYPE(StepDimTol_PositionTolerance))) {
1881             DGTTool->SetDimTol(shL,41,arr,aName,aDescription);
1882           }
1883           else if(GT->IsKind(STANDARD_TYPE(StepDimTol_RoundnessTolerance))) {
1884             DGTTool->SetDimTol(shL,42,arr,aName,aDescription);
1885           }
1886           else if(GT->IsKind(STANDARD_TYPE(StepDimTol_StraightnessTolerance))) {
1887             DGTTool->SetDimTol(shL,43,arr,aName,aDescription);
1888           }
1889           else if(GT->IsKind(STANDARD_TYPE(StepDimTol_SurfaceProfileTolerance))) {
1890             DGTTool->SetDimTol(shL,44,arr,aName,aDescription);
1891           }
1892         }
1893       }
1894     }
1895   }
1896
1897   return Standard_True;
1898 }
1899
1900
1901 //=======================================================================
1902 //function : FindSolidForPDS
1903 //purpose  : auxilary
1904 //=======================================================================
1905
1906 static Handle(StepShape_SolidModel) FindSolidForPDS(const Handle(StepRepr_ProductDefinitionShape) &PDS,
1907                                                     const Interface_Graph &graph)
1908 {
1909   Handle(StepShape_SolidModel) SM;
1910   Interface_EntityIterator subs = graph.Sharings(PDS);
1911   Handle(StepShape_ShapeRepresentation) SR;
1912   for(subs.Start(); subs.More() && SM.IsNull(); subs.Next()) {
1913     Handle(StepShape_ShapeDefinitionRepresentation) SDR =
1914       Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
1915     if(SDR.IsNull()) continue;
1916     SR = Handle(StepShape_ShapeRepresentation)::DownCast(SDR->UsedRepresentation());
1917     if(SR.IsNull()) continue;
1918     for(Standard_Integer i=1; i<=SR->NbItems() && SM.IsNull(); i++) {
1919       SM = Handle(StepShape_SolidModel)::DownCast(SR->ItemsValue(i));
1920     }
1921     if(SM.IsNull()) {
1922       Interface_EntityIterator subs1 = graph.Sharings(SR);
1923       for(subs1.Start(); subs1.More() && SM.IsNull(); subs1.Next()) {
1924         Handle(StepRepr_RepresentationRelationship) RR =
1925           Handle(StepRepr_RepresentationRelationship)::DownCast(subs1.Value());
1926         if(RR.IsNull()) continue;
1927         Handle(StepShape_ShapeRepresentation) SR2;
1928         if(RR->Rep1()==SR) SR2 = Handle(StepShape_ShapeRepresentation)::DownCast(RR->Rep2());
1929         else SR2 = Handle(StepShape_ShapeRepresentation)::DownCast(RR->Rep1());
1930         if(SR2.IsNull()) continue;
1931         for(Standard_Integer i2=1; i2<=SR2->NbItems() && SM.IsNull(); i2++) {
1932           SM = Handle(StepShape_SolidModel)::DownCast(SR2->ItemsValue(i2));
1933         }
1934       }
1935     }
1936   }
1937   return SM;
1938 }
1939
1940
1941 //=======================================================================
1942 //function : ReadMaterials
1943 //purpose  : 
1944 //=======================================================================
1945
1946 Standard_Boolean STEPCAFControl_Reader::ReadMaterials(const Handle(XSControl_WorkSession) &WS,
1947                                                       Handle(TDocStd_Document)& Doc,
1948                                                       const Handle(TColStd_HSequenceOfTransient) &SeqPDS) const
1949 {
1950   Handle(Interface_InterfaceModel) Model = WS->Model();
1951   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1952   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1953   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1954   Handle(XCAFDoc_MaterialTool) MatTool = XCAFDoc_DocumentTool::MaterialTool( Doc->Main() );
1955   if(MatTool.IsNull()) return Standard_False;
1956   
1957   const Interface_Graph& graph = TP->Graph();
1958   for(Standard_Integer i=1; i<=SeqPDS->Length(); i++) {
1959     Handle(StepRepr_ProductDefinitionShape) PDS =
1960       Handle(StepRepr_ProductDefinitionShape)::DownCast(SeqPDS->Value(i));
1961     if(PDS.IsNull()) 
1962       continue;
1963     Handle(StepBasic_ProductDefinition) aProdDef = PDS->Definition().ProductDefinition();
1964     if(aProdDef.IsNull())
1965       continue;
1966     Handle(TCollection_HAsciiString) aName = new TCollection_HAsciiString("");
1967     Handle(TCollection_HAsciiString) aDescription = new TCollection_HAsciiString("");
1968     Handle(TCollection_HAsciiString) aDensName = new TCollection_HAsciiString("");
1969     Handle(TCollection_HAsciiString) aDensValType = new TCollection_HAsciiString("");
1970     Standard_Real aDensity=0;
1971     Interface_EntityIterator subs = graph.Sharings( aProdDef);
1972     for(subs.Start(); subs.More(); subs.Next()) {
1973       Handle(StepRepr_PropertyDefinition) PropD =
1974         Handle(StepRepr_PropertyDefinition)::DownCast(subs.Value());
1975       if(PropD.IsNull()) continue;
1976       Interface_EntityIterator subs1 = graph.Sharings(PropD);
1977       for(subs1.Start(); subs1.More(); subs1.Next()) {
1978         Handle(StepRepr_PropertyDefinitionRepresentation) PDR =
1979           Handle(StepRepr_PropertyDefinitionRepresentation)::DownCast(subs1.Value());
1980         if(PDR.IsNull()) continue;
1981         Handle(StepRepr_Representation) Repr = PDR->UsedRepresentation();
1982         if(Repr.IsNull()) continue;
1983         Standard_Integer ir;
1984         for(ir=1; ir<=Repr->NbItems(); ir++) {
1985           Handle(StepRepr_RepresentationItem) RI = Repr->ItemsValue(ir);
1986           if(RI.IsNull()) continue;
1987           if(RI->IsKind(STANDARD_TYPE(StepRepr_DescriptiveRepresentationItem))) {
1988             // find name and description for material
1989             Handle(StepRepr_DescriptiveRepresentationItem) DRI =
1990               Handle(StepRepr_DescriptiveRepresentationItem)::DownCast(RI);
1991             aName = DRI->Name();
1992             
1993             aDescription = DRI->Description();
1994             if(aName.IsNull())
1995               aName = aDescription;
1996           }
1997           if(RI->IsKind(STANDARD_TYPE(StepRepr_MeasureRepresentationItem))) {
1998             // try to find density for material
1999             Handle(StepRepr_MeasureRepresentationItem) MRI =
2000               Handle(StepRepr_MeasureRepresentationItem)::DownCast(RI);
2001             aDensity = MRI->Measure()->ValueComponent();
2002             aDensName = MRI->Name();
2003             aDensValType = new TCollection_HAsciiString(MRI->Measure()->ValueComponentMember()->Name());
2004             StepBasic_Unit aUnit = MRI->Measure()->UnitComponent();
2005             if(!aUnit.IsNull()) {
2006               Handle(StepBasic_DerivedUnit) DU = aUnit.DerivedUnit();
2007               if(DU.IsNull()) continue;
2008               for(Standard_Integer idu=1; idu<=DU->NbElements(); idu++) {
2009                 Handle(StepBasic_DerivedUnitElement) DUE = DU->ElementsValue(idu);
2010                 Handle(StepBasic_NamedUnit) NU = DUE->Unit();
2011                 Standard_Real afact=1.;
2012                 if(NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndLengthUnit))) {
2013                   if(GetLengthConversionFactor(NU,afact)) aDensity = aDensity/(afact*afact*afact);
2014                   // transfer length value for Density from millimeter to santimeter
2015                   // in order to result density has dimension gram/(sm*sm*sm)
2016                   aDensity = aDensity*1000.;
2017                 }
2018                 if(NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndMassUnit))) {
2019                   if(GetMassConversionFactor(NU,afact)) aDensity=aDensity*afact;
2020                 }
2021               }
2022             }
2023           }
2024         }
2025       }
2026     }
2027    
2028     if( aName.IsNull() || aName->Length()==0 ) 
2029       continue;
2030     // find shape label amd create Material link
2031     TopoDS_Shape aSh;
2032     Handle(StepShape_SolidModel) SM = FindSolidForPDS(PDS,graph);
2033     if(!SM.IsNull()) {
2034       Standard_Integer index = TP->MapIndex(SM);
2035       if(index >0) {
2036         Handle(Transfer_Binder) binder = TP->MapItem(index);
2037         if(!binder.IsNull())
2038           aSh = TransferBRep::ShapeResult(binder);
2039       }
2040     }
2041     if(aSh.IsNull()) continue; 
2042     TDF_Label shL;
2043     if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2044     MatTool->SetMaterial(shL,aName,aDescription,aDensity,aDensName,aDensValType);
2045   }
2046
2047   return Standard_True;
2048 }
2049
2050 //=======================================================================
2051 //function : SettleShapeData
2052 //purpose  :
2053 //=======================================================================
2054
2055 TDF_Label STEPCAFControl_Reader::SettleShapeData(const Handle(StepRepr_RepresentationItem)& theItem,
2056                                                  TDF_Label& theLab,
2057                                                  const Handle(XCAFDoc_ShapeTool)& theShapeTool,
2058                                                  const Handle(Transfer_TransientProcess)& TP) const
2059 {
2060   TDF_Label aResult = theLab;
2061
2062   Handle(TCollection_HAsciiString) hName = theItem->Name();
2063   if ( hName.IsNull() || hName->IsEmpty() )
2064     return aResult;
2065
2066   Handle(Transfer_Binder) aBinder = TP->Find(theItem);
2067   if ( aBinder.IsNull() )
2068     return aResult;
2069
2070   TopoDS_Shape aShape = TransferBRep::ShapeResult(aBinder);
2071   if ( aShape.IsNull() )
2072     return aResult;
2073
2074   // Allocate sub-Label
2075   aResult = AllocateSubLabel(theLab);
2076
2077   TCollection_AsciiString aName = hName->String();
2078   TDataStd_Name::Set(aResult, aName);
2079   theShapeTool->SetShape(aResult, aShape);
2080
2081   return aResult;
2082 }
2083
2084 //=======================================================================
2085 //function : ExpandSubShapes
2086 //purpose  :
2087 //=======================================================================
2088
2089 void STEPCAFControl_Reader::ExpandSubShapes(const Handle(XCAFDoc_ShapeTool)& ShapeTool,
2090                                             const XCAFDoc_DataMapOfShapeLabel& ShapeLabelMap,
2091                                             const STEPCAFControl_DataMapOfShapePD& ShapePDMap) const
2092 {
2093   const Handle(Transfer_TransientProcess)& TP = Reader().WS()->TransferReader()->TransientProcess();
2094   NCollection_DataMap<TopoDS_Shape, Handle(TCollection_HAsciiString)> ShapeNameMap;
2095   TColStd_MapOfTransient aRepItems;
2096
2097   // Read translation control variables
2098   Standard_Boolean doReadSNames = (Interface_Static::IVal("read.stepcaf.subshapes.name") > 0);
2099
2100   if ( !doReadSNames )
2101     return;
2102
2103   const Interface_Graph& Graph = Reader().WS()->Graph();
2104
2105   for ( STEPCAFControl_DataMapIteratorOfDataMapOfShapePD it(ShapePDMap); it.More(); it.Next() )
2106   {
2107     const TopoDS_Shape& aRootShape = it.Key();
2108     const Handle(StepBasic_ProductDefinition)& aPDef = it.Value();
2109     if ( aPDef.IsNull() )
2110       continue;
2111
2112     // Find SDR by Product
2113     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
2114     Interface_EntityIterator entIt = Graph.TypedSharings( aPDef, STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation) );
2115     for ( entIt.Start(); entIt.More(); entIt.Next() )
2116     {
2117       const Handle(Standard_Transient)& aReferer = entIt.Value();
2118       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(aReferer);
2119       if ( !aSDR.IsNull() )
2120         break;
2121     }
2122
2123     if ( aSDR.IsNull() )
2124       continue;
2125
2126     // Access shape representation
2127     Handle(StepShape_ShapeRepresentation)
2128       aShapeRepr = Handle(StepShape_ShapeRepresentation)::DownCast( aSDR->UsedRepresentation() );
2129
2130     if ( aShapeRepr.IsNull() )
2131       continue;
2132
2133     // Access representation items
2134     Handle(StepRepr_HArray1OfRepresentationItem) aReprItems = aShapeRepr->Items();
2135
2136     if ( aReprItems.IsNull() )
2137       continue;
2138
2139     if ( !ShapeLabelMap.IsBound(aRootShape) )
2140       continue;
2141
2142     TDF_Label aRootLab = ShapeLabelMap.Find(aRootShape);
2143
2144     StepRepr_SequenceOfRepresentationItem aMSBSeq;
2145     StepRepr_SequenceOfRepresentationItem aSBSMSeq;
2146
2147     // Iterate over the top level representation items collecting the
2148     // topological containers to expand
2149     for ( Standard_Integer i = aReprItems->Lower(); i <= aReprItems->Upper(); ++i )
2150     {
2151       Handle(StepRepr_RepresentationItem) aTRepr = aReprItems->Value(i);
2152       if ( aTRepr->IsKind( STANDARD_TYPE(StepShape_ManifoldSolidBrep) ) )
2153         aMSBSeq.Append(aTRepr);
2154       else if ( aTRepr->IsKind( STANDARD_TYPE(StepShape_ShellBasedSurfaceModel) ) )
2155         aSBSMSeq.Append(aTRepr);
2156     }
2157
2158     // Insert intermediate OCAF Labels for SOLIDs in case there are more
2159     // than one Manifold Solid BRep in the Shape Representation
2160     Standard_Boolean doInsertSolidLab = (aMSBSeq.Length() > 1);
2161
2162     // Expand Manifold Solid BReps
2163     for ( Standard_Integer i = 1; i <= aMSBSeq.Length(); ++i )
2164     {
2165       const Handle(StepRepr_RepresentationItem)& aManiRepr = aMSBSeq.Value(i);
2166
2167       // Put additional Label for SOLID
2168       TDF_Label aManiLab;
2169       if ( doInsertSolidLab )
2170         aManiLab = SettleShapeData(aManiRepr, aRootLab, ShapeTool, TP);
2171       else
2172         aManiLab = aRootLab;
2173
2174       ExpandManifoldSolidBrep(aManiLab, aMSBSeq.Value(i), TP, ShapeTool);
2175     }
2176
2177     // Expand Shell-Based Surface Models
2178     for ( Standard_Integer i = 1; i <= aSBSMSeq.Length(); ++i )
2179       ExpandSBSM(aRootLab, aSBSMSeq.Value(i), TP, ShapeTool);
2180   }
2181 }
2182
2183 //=======================================================================
2184 //function : ExpandManifoldSolidBrep
2185 //purpose  :
2186 //=======================================================================
2187
2188 void STEPCAFControl_Reader::ExpandManifoldSolidBrep(TDF_Label& ShapeLab,
2189                                                     const Handle(StepRepr_RepresentationItem)& Repr,
2190                                                     const Handle(Transfer_TransientProcess)& TP,
2191                                                     const Handle(XCAFDoc_ShapeTool)& ShapeTool) const
2192 {
2193   // Access outer shell
2194   Handle(StepShape_ManifoldSolidBrep) aMSB = Handle(StepShape_ManifoldSolidBrep)::DownCast(Repr);
2195   Handle(StepShape_ConnectedFaceSet) aShell = aMSB->Outer();
2196
2197   // Expand shell contents to CAF tree
2198   ExpandShell(aShell, ShapeLab, TP, ShapeTool);
2199 }
2200
2201 //=======================================================================
2202 //function : ExpandSBSM
2203 //purpose  :
2204 //=======================================================================
2205
2206 void STEPCAFControl_Reader::ExpandSBSM(TDF_Label& ShapeLab,
2207                                        const Handle(StepRepr_RepresentationItem)& Repr,
2208                                        const Handle(Transfer_TransientProcess)& TP,
2209                                        const Handle(XCAFDoc_ShapeTool)& ShapeTool) const
2210 {
2211   Handle(StepShape_ShellBasedSurfaceModel) aSBSM = Handle(StepShape_ShellBasedSurfaceModel)::DownCast(Repr);
2212
2213   // Access boundary shells
2214   Handle(StepShape_HArray1OfShell) aShells = aSBSM->SbsmBoundary();
2215   for ( Standard_Integer s = aShells->Lower(); s <= aShells->Upper(); ++s )
2216   {
2217     const StepShape_Shell& aShell = aShells->Value(s);
2218     Handle(StepShape_ConnectedFaceSet) aCFS;
2219     Handle(StepShape_OpenShell) anOpenShell = aShell.OpenShell();
2220     Handle(StepShape_ClosedShell) aClosedShell = aShell.ClosedShell();
2221
2222     if ( !anOpenShell.IsNull() )
2223       aCFS = anOpenShell;
2224     else
2225       aCFS = aClosedShell;
2226
2227     ExpandShell(aCFS, ShapeLab, TP, ShapeTool);
2228   }
2229 }
2230
2231 //=======================================================================
2232 //function : ExpandShell
2233 //purpose  :
2234 //=======================================================================
2235
2236 void STEPCAFControl_Reader::ExpandShell(const Handle(StepShape_ConnectedFaceSet)& Shell,
2237                                         TDF_Label& RootLab,
2238                                         const Handle(Transfer_TransientProcess)& TP,
2239                                         const Handle(XCAFDoc_ShapeTool)& ShapeTool) const
2240 {
2241   // Record CAF data
2242   TDF_Label aShellLab = SettleShapeData(Shell, RootLab, ShapeTool, TP);
2243
2244   // Access faces
2245   Handle(StepShape_HArray1OfFace) aFaces = Shell->CfsFaces();
2246   for ( Standard_Integer f = aFaces->Lower(); f <= aFaces->Upper(); ++f )
2247   {
2248     const Handle(StepShape_Face)& aFace = aFaces->Value(f);
2249
2250     // Record CAF data
2251     TDF_Label aFaceLab = SettleShapeData(aFace, aShellLab, ShapeTool, TP);
2252
2253     // Access face bounds
2254     Handle(StepShape_HArray1OfFaceBound) aWires = aFace->Bounds();
2255     for ( Standard_Integer w = aWires->Lower(); w <= aWires->Upper(); ++w )
2256     {
2257       const Handle(StepShape_Loop)& aWire = aWires->Value(w)->Bound();
2258
2259       // Record CAF data
2260       TDF_Label aWireLab = SettleShapeData(aWire, aFaceLab, ShapeTool, TP);
2261
2262       // Access wire edges
2263       // Currently only EDGE LOOPs are considered (!)
2264       if ( !aWire->IsInstance( STANDARD_TYPE(StepShape_EdgeLoop) ) )
2265         continue;
2266
2267       // Access edges
2268       Handle(StepShape_EdgeLoop) anEdgeLoop = Handle(StepShape_EdgeLoop)::DownCast(aWire);
2269       Handle(StepShape_HArray1OfOrientedEdge) anEdges = anEdgeLoop->EdgeList();
2270       for ( Standard_Integer e = anEdges->Lower(); e <= anEdges->Upper(); ++e )
2271       {
2272         Handle(StepShape_Edge) anEdge = anEdges->Value(e)->EdgeElement();
2273
2274         // Record CAF data
2275         TDF_Label anEdgeLab = SettleShapeData(anEdge, aWireLab, ShapeTool, TP);
2276
2277         // Access vertices
2278         Handle(StepShape_Vertex) aV1 = anEdge->EdgeStart();
2279         Handle(StepShape_Vertex) aV2 = anEdge->EdgeEnd();
2280
2281         // Record CAF data
2282         SettleShapeData(aV1, anEdgeLab, ShapeTool, TP);
2283         SettleShapeData(aV2, anEdgeLab, ShapeTool, TP);
2284       }
2285     }
2286   }
2287 }
2288
2289 //=======================================================================
2290 //function : SetColorMode
2291 //purpose  : 
2292 //=======================================================================
2293
2294 void STEPCAFControl_Reader::SetColorMode (const Standard_Boolean colormode)
2295 {
2296   myColorMode = colormode;
2297 }
2298
2299 //=======================================================================
2300 //function : GetColorMode
2301 //purpose  : 
2302 //=======================================================================
2303
2304 Standard_Boolean STEPCAFControl_Reader::GetColorMode () const
2305 {
2306   return myColorMode;
2307 }
2308
2309 //=======================================================================
2310 //function : SetNameMode
2311 //purpose  : 
2312 //=======================================================================
2313
2314 void STEPCAFControl_Reader::SetNameMode (const Standard_Boolean namemode)
2315 {
2316   myNameMode = namemode;
2317 }
2318
2319 //=======================================================================
2320 //function : GetNameMode
2321 //purpose  : 
2322 //=======================================================================
2323
2324 Standard_Boolean STEPCAFControl_Reader::GetNameMode () const
2325 {
2326   return myNameMode;
2327 }
2328
2329 //=======================================================================
2330 //function : SetLayerMode
2331 //purpose  : 
2332 //=======================================================================
2333
2334 void STEPCAFControl_Reader::SetLayerMode (const Standard_Boolean layermode)
2335 {
2336   myLayerMode = layermode;
2337 }
2338
2339 //=======================================================================
2340 //function : GetLayerMode
2341 //purpose  : 
2342 //=======================================================================
2343
2344 Standard_Boolean STEPCAFControl_Reader::GetLayerMode () const
2345 {
2346   return myLayerMode;
2347 }
2348
2349 //=======================================================================
2350 //function : SetPropsMode
2351 //purpose  : 
2352 //=======================================================================
2353
2354 void STEPCAFControl_Reader::SetPropsMode (const Standard_Boolean propsmode)
2355 {
2356   myPropsMode = propsmode;
2357 }
2358
2359 //=======================================================================
2360 //function : GetPropsMode
2361 //purpose  : 
2362 //=======================================================================
2363
2364 Standard_Boolean STEPCAFControl_Reader::GetPropsMode () const
2365 {
2366   return myPropsMode;
2367 }
2368
2369 //=======================================================================
2370 //function : SetSHUOMode
2371 //purpose  : 
2372 //=======================================================================
2373
2374 void STEPCAFControl_Reader::SetSHUOMode (const Standard_Boolean mode)
2375 {
2376   mySHUOMode = mode;
2377 }
2378
2379 //=======================================================================
2380 //function : GetSHUOMode
2381 //purpose  : 
2382 //=======================================================================
2383
2384 Standard_Boolean STEPCAFControl_Reader::GetSHUOMode () const
2385 {
2386   return mySHUOMode;
2387 }
2388
2389 //=======================================================================
2390 //function : SetGDTMode
2391 //purpose  : 
2392 //=======================================================================
2393
2394 void STEPCAFControl_Reader::SetGDTMode (const Standard_Boolean gdtmode)
2395 {
2396   myGDTMode = gdtmode;
2397 }
2398
2399 //=======================================================================
2400 //function : GetGDTMode
2401 //purpose  : 
2402 //=======================================================================
2403
2404 Standard_Boolean STEPCAFControl_Reader::GetGDTMode () const
2405 {
2406   return myGDTMode;
2407 }
2408
2409
2410 //=======================================================================
2411 //function : SetMatMode
2412 //purpose  : 
2413 //=======================================================================
2414
2415 void STEPCAFControl_Reader::SetMatMode (const Standard_Boolean matmode)
2416 {
2417   myMatMode = matmode;
2418 }
2419
2420 //=======================================================================
2421 //function : GetMatMode
2422 //purpose  : 
2423 //=======================================================================
2424
2425 Standard_Boolean STEPCAFControl_Reader::GetMatMode () const
2426 {
2427   return myMatMode;
2428 }