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