0027372: Import/Export dimension text position
[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
17 #include <BRep_Builder.hxx>
18 #include <Interface_EntityIterator.hxx>
19 #include <Interface_InterfaceModel.hxx>
20 #include <StepData_StepModel.hxx>
21 #include <HeaderSection_FileSchema.hxx>
22 #include <Interface_Static.hxx>
23 #include <NCollection_DataMap.hxx>
24 #include <OSD_Path.hxx>
25 #include <Quantity_Color.hxx>
26 #include <StepAP214_AppliedExternalIdentificationAssignment.hxx>
27 #include <StepBasic_ConversionBasedUnitAndLengthUnit.hxx>
28 #include <StepBasic_ConversionBasedUnitAndPlaneAngleUnit.hxx>
29 #include <StepBasic_ConversionBasedUnitAndMassUnit.hxx>
30 #include <StepBasic_DerivedUnit.hxx>
31 #include <StepBasic_DerivedUnitElement.hxx>
32 #include <StepBasic_MeasureValueMember.hxx>
33 #include <StepBasic_MeasureWithUnit.hxx>
34 #include <StepBasic_NamedUnit.hxx>
35 #include <StepBasic_Product.hxx>
36 #include <StepBasic_ProductDefinition.hxx>
37 #include <StepBasic_ProductDefinitionFormation.hxx>
38 #include <StepBasic_ProductDefinitionRelationship.hxx>
39 #include <StepBasic_SiUnit.hxx>
40 #include <StepBasic_Unit.hxx>
41 #include <STEPCAFControl_Controller.hxx>
42 #include <STEPCAFControl_DataMapIteratorOfDataMapOfShapePD.hxx>
43 #include <STEPCAFControl_DataMapOfPDExternFile.hxx>
44 #include <STEPCAFControl_DataMapOfSDRExternFile.hxx>
45 #include <STEPCAFControl_DataMapOfShapePD.hxx>
46 #include <STEPCAFControl_DictionaryOfExternFile.hxx>
47 #include <STEPCAFControl_ExternFile.hxx>
48 #include <STEPCAFControl_Reader.hxx>
49 #include <STEPConstruct.hxx>
50 #include <STEPConstruct_Assembly.hxx>
51 #include <STEPConstruct_ExternRefs.hxx>
52 #include <STEPConstruct_Styles.hxx>
53 #include <STEPConstruct_Tool.hxx>
54 #include <STEPConstruct_UnitContext.hxx>
55 #include <STEPConstruct_ValidationProps.hxx>
56 #include <STEPControl_Reader.hxx>
57 #include <StepGeom_GeometricRepresentationItem.hxx>
58 #include <StepGeom_Axis2Placement3d.hxx>
59 #include <StepGeom_Direction.hxx>
60 #include <StepDimTol_AngularityTolerance.hxx>
61 #include <StepDimTol_CircularRunoutTolerance.hxx>
62 #include <StepDimTol_CoaxialityTolerance.hxx>
63 #include <StepDimTol_ConcentricityTolerance.hxx>
64 #include <StepDimTol_CylindricityTolerance.hxx>
65 #include <StepDimTol_Datum.hxx>
66 #include <StepDimTol_DatumFeature.hxx>
67 #include <StepDimTol_DatumReference.hxx>
68 #include <StepDimTol_DatumReferenceElement.hxx>
69 #include <StepDimTol_DatumReferenceCompartment.hxx>
70 #include <StepDimTol_DatumSystem.hxx>
71 #include <StepDimTol_FlatnessTolerance.hxx>
72 #include <StepDimTol_GeometricTolerance.hxx>
73 #include <StepDimTol_GeometricToleranceWithDatumReference.hxx>
74 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol.hxx>
75 #include <StepDimTol_GeoTolAndGeoTolWthDatRef.hxx>
76 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol.hxx>
77 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndUneqDisGeoTol.hxx>
78 #include <StepDimTol_GeoTolAndGeoTolWthMaxTol.hxx>
79 #include <StepDimTol_HArray1OfDatumReference.hxx>
80 #include <StepDimTol_LineProfileTolerance.hxx>
81 #include <StepDimTol_ModifiedGeometricTolerance.hxx>
82 #include <StepDimTol_ParallelismTolerance.hxx>
83 #include <StepDimTol_PerpendicularityTolerance.hxx>
84 #include <StepDimTol_PositionTolerance.hxx>
85 #include <StepDimTol_ProjectedZoneDefinition.hxx>
86 #include <StepDimTol_RoundnessTolerance.hxx>
87 #include <StepDimTol_RunoutZoneDefinition.hxx>
88 #include <StepDimTol_StraightnessTolerance.hxx>
89 #include <StepDimTol_SurfaceProfileTolerance.hxx>
90 #include <StepDimTol_SymmetryTolerance.hxx>
91 #include <StepDimTol_ToleranceZone.hxx>
92 #include <StepDimTol_ToleranceZoneForm.hxx>
93 #include <StepDimTol_TotalRunoutTolerance.hxx>
94 #include <StepDimTol_GeometricToleranceWithModifiers.hxx>
95 #include <StepDimTol_HArray1OfGeometricToleranceModifier.hxx>
96 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod.hxx>
97 #include <StepDimTol_GeoTolAndGeoTolWthMod.hxx>
98 #include <StepDimTol_GeometricToleranceWithMaximumTolerance.hxx>
99 #include <StepGeom_Axis2Placement3d.hxx>
100 #include <StepGeom_Plane.hxx>
101 #include <StepGeom_Polyline.hxx>
102 #include <StepDimTol_PlacedDatumTargetFeature.hxx>
103 #include <StepRepr_AssemblyComponentUsage.hxx>
104 #include <StepRepr_CharacterizedDefinition.hxx>
105 #include <StepRepr_CompoundRepresentationItem.hxx>
106 #include <StepRepr_DescriptiveRepresentationItem.hxx>
107 #include <StepRepr_HArray1OfRepresentationItem.hxx>
108 #include <StepRepr_MeasureRepresentationItem.hxx>
109 #include <StepRepr_NextAssemblyUsageOccurrence.hxx>
110 #include <StepRepr_ProductDefinitionShape.hxx>
111 #include <StepRepr_PropertyDefinition.hxx>
112 #include <StepRepr_PropertyDefinitionRepresentation.hxx>
113 #include <StepRepr_Representation.hxx>
114 #include <StepRepr_RepresentationItem.hxx>
115 #include <StepRepr_HArray1OfRepresentationItem.hxx>
116 #include <StepRepr_RepresentationRelationship.hxx>
117 #include <StepRepr_RepresentedDefinition.hxx>
118 #include <StepRepr_ReprItemAndLengthMeasureWithUnit.hxx>
119 #include <StepRepr_ReprItemAndPlaneAngleMeasureWithUnit.hxx>
120 #include <StepRepr_SequenceOfRepresentationItem.hxx>
121 #include <StepRepr_ShapeAspect.hxx>
122 #include <StepRepr_CompositeShapeAspect.hxx>
123 #include <StepRepr_AllAroundShapeAspect.hxx>
124 #include <StepRepr_CompShAspAndDatumFeatAndShAsp.hxx>
125 #include <StepRepr_ShapeAspectRelationship.hxx>
126 #include <StepRepr_ShapeRepresentationRelationship.hxx>
127 #include <StepRepr_SpecifiedHigherUsageOccurrence.hxx>
128 #include <StepRepr_ValueRange.hxx>
129 #include <StepRepr_FeatureForDatumTargetRelationship.hxx>
130 #include <StepShape_AdvancedFace.hxx>
131 #include <StepShape_AdvancedBrepShapeRepresentation.hxx>
132 #include <StepShape_AngleRelator.hxx>
133 #include <StepShape_AngularSize.hxx>
134 #include <StepShape_AngularLocation.hxx>
135 #include <StepShape_ClosedShell.hxx>
136 #include <StepShape_ConnectedFaceSet.hxx>
137 #include <StepShape_ContextDependentShapeRepresentation.hxx>
138 #include <StepRepr_CompGroupShAspAndCompShAspAndDatumFeatAndShAsp.hxx>
139 #include <StepRepr_CompShAspAndDatumFeatAndShAsp.hxx>
140 #include <StepShape_DimensionalCharacteristicRepresentation.hxx>
141 #include <StepShape_DimensionalSizeWithPath.hxx>
142 #include <StepShape_DimensionalLocationWithPath.hxx>
143 #include <StepShape_ShapeDimensionRepresentationItem.hxx>
144 #include <StepShape_ShapeRepresentationWithParameters.hxx>
145 #include <StepShape_HArray1OfShapeDimensionRepresentationItem.hxx>
146 #include <StepShape_DimensionalSize.hxx>
147 #include <StepShape_DimensionalLocation.hxx>
148 #include <StepShape_EdgeCurve.hxx>
149 #include <StepShape_EdgeLoop.hxx>
150 #include <StepShape_GeometricCurveSet.hxx>
151 #include <StepShape_GeometricSet.hxx>
152 #include <StepShape_HArray1OfFace.hxx>
153 #include <StepShape_HArray1OfFaceBound.hxx>
154 #include <StepShape_HArray1OfOrientedEdge.hxx>
155 #include <StepShape_HArray1OfShell.hxx>
156 #include <StepShape_LimitsAndFits.hxx>
157 #include <StepShape_Loop.hxx>
158 #include <StepShape_ManifoldSolidBrep.hxx>
159 #include <StepShape_PlusMinusTolerance.hxx>
160 #include <StepShape_QualifiedRepresentationItem.hxx>
161 #include <StepShape_OpenShell.hxx>
162 #include <StepShape_ShapeDefinitionRepresentation.hxx>
163 #include <StepShape_ShapeDimensionRepresentation.hxx>
164 #include <StepShape_ShapeRepresentation.hxx>
165 #include <StepShape_ShellBasedSurfaceModel.hxx>
166 #include <StepShape_SolidModel.hxx>
167 #include <StepShape_ToleranceMethodDefinition.hxx>
168 #include <StepShape_ToleranceValue.hxx>
169 #include <StepShape_ValueFormatTypeQualifier.hxx>
170 #include <StepShape_Vertex.hxx>
171 #include <StepVisual_AnnotationCurveOccurrence.hxx>
172 #include <StepVisual_AnnotationPlane.hxx>
173 #include <StepVisual_DraughtingCallout.hxx>
174 #include <StepVisual_DraughtingCalloutElement.hxx>
175 #include <StepVisual_Invisibility.hxx>
176 #include <StepVisual_LayeredItem.hxx>
177 #include <StepVisual_PlanarBox.hxx>
178 #include <StepVisual_PresentationLayerAssignment.hxx>
179 #include <StepVisual_PresentationStyleByContext.hxx>
180 #include <StepVisual_StyleContextSelect.hxx>
181 #include <StepVisual_StyledItem.hxx>
182 #include <StepShape_TypeQualifier.hxx>
183 #include <TCollection_AsciiString.hxx>
184 #include <TCollection_HAsciiString.hxx>
185 #include <TColStd_HArray1OfReal.hxx>
186 #include <TColStd_HArray1OfTransient.hxx>
187 #include <TColStd_HSequenceOfTransient.hxx>
188 #include <TColStd_IndexedDataMapOfTransientTransient.hxx>
189 #include <TColStd_MapIteratorOfMapOfTransient.hxx>
190 #include <TColStd_MapOfTransient.hxx>
191 #include <TColStd_SequenceOfHAsciiString.hxx>
192 #include <TDataStd_Name.hxx>
193 #include <TDataStd_TreeNode.hxx>
194 #include <TDataStd_UAttribute.hxx>
195 #include <TDF_Label.hxx>
196 #include <TDF_Tool.hxx>
197 #include <TDocStd_Document.hxx>
198 #include <TNaming_NamedShape.hxx>
199 #include <TopExp_Explorer.hxx>
200 #include <TopoDS.hxx>
201 #include <TopoDS_Compound.hxx>
202 #include <TopoDS_Iterator.hxx>
203 #include <TopoDS_Shape.hxx>
204 #include <TopTools_ListIteratorOfListOfShape.hxx>
205 #include <TopTools_ListOfShape.hxx>
206 #include <TopTools_MapOfShape.hxx>
207 #include <Transfer_Binder.hxx>
208 #include <Transfer_TransientProcess.hxx>
209 #include <TransferBRep.hxx>
210 #include <XCAFDoc.hxx>
211 #include <XCAFDoc_Area.hxx>
212 #include <XCAFDoc_Centroid.hxx>
213 #include <XCAFDoc_ColorTool.hxx>
214 #include <XCAFDoc_DataMapOfShapeLabel.hxx>
215 #include <XCAFDoc_DimTolTool.hxx>
216 #include <XCAFDoc_Dimension.hxx>
217 #include <XCAFDoc_Datum.hxx>
218 #include <XCAFDoc_GeomTolerance.hxx>
219 #include <XCAFDoc_DocumentTool.hxx>
220 #include <XCAFDoc_GraphNode.hxx>
221 #include <XCAFDoc_LayerTool.hxx>
222 #include <XCAFDoc_MaterialTool.hxx>
223 #include <XCAFDoc_ShapeTool.hxx>
224 #include <XCAFDoc_Volume.hxx>
225 #include <XCAFDimTolObjects_DimensionModifiersSequence.hxx>
226 #include <XCAFDimTolObjects_GeomToleranceType.hxx>
227 #include <XCAFDimTolObjects_DimensionObject.hxx>
228 #include <XCAFDimTolObjects_GeomToleranceObject.hxx>
229 #include <XCAFDimTolObjects_DatumObject.hxx>
230 #include <XSControl_TransferReader.hxx>
231 #include <XSControl_WorkSession.hxx>
232 #include <StepAP242_DraughtingModelItemAssociation.hxx>
233 #include <StepAP242_GeometricItemSpecificUsage.hxx>
234 #include <StepGeom_CartesianPoint.hxx>
235 #include <STEPCAFControl_GDTProperty.hxx>
236 #include <StepVisual_TessellatedAnnotationOccurrence.hxx>
237 #include <StepVisual_TessellatedAnnotationOccurrence.hxx>
238 #include <StepVisual_TessellatedItem.hxx>
239 #include <StepVisual_TessellatedGeometricSet.hxx>
240 #include <StepVisual_TessellatedCurveSet.hxx>
241 #include <StepVisual_CoordinatesList.hxx>
242 #include <NCollection_Vector.hxx>
243
244 #include <TColgp_HArray1OfXYZ.hxx>
245 #include <BRepBuilderAPI_MakeEdge.hxx>
246 #include <BRepTools.hxx>
247 #include <Transfer_ActorOfTransientProcess.hxx>
248 #include <Bnd_Box.hxx>
249 #include <BRepBndLib.hxx>
250
251 // skl 21.08.2003 for reading G&DT
252 //#include <StepRepr_CompoundItemDefinition.hxx>
253 //#include <StepRepr_CompoundItemDefinitionMember.hxx>
254 //#include <StepBasic_ConversionBasedUnit.hxx>
255 //#include <TDataStd_Real.hxx>
256 //#include <TDataStd_Constraint.hxx>
257 //#include <TDataStd_ConstraintEnum.hxx>
258 //#include <TNaming_Tool.hxx>
259 //#include <AIS_InteractiveObject.hxx>
260 //#include <TPrsStd_ConstraintTools.hxx>
261 //#include <AIS_DiameterDimension.hxx>
262 //#include <TPrsStd_Position.hxx>
263 //#include <TPrsStd_AISPresentation.hxx>
264 //#include <TNaming_Builder.hxx>
265 #ifdef OCCT_DEBUG
266 //! Converts address of the passed shape (TShape) to string.
267 //! \param theShape [in] Shape to dump.
268 //! \return corresponding string.
269 TCollection_AsciiString AddrToString(const TopoDS_Shape& theShape)
270 {
271   std::string anAddrStr;
272   std::ostringstream ost;
273   ost << theShape.TShape().get();
274   anAddrStr = ost.str();
275
276   TCollection_AsciiString aStr =
277     TCollection_AsciiString("[").Cat( anAddrStr.c_str() ).Cat("]");
278
279   return aStr;
280 }
281 #endif
282
283 //=======================================================================
284 //function : IsEqual
285 //purpose  : global function to check equality of topological shapes
286 //=======================================================================
287
288 inline Standard_Boolean IsEqual(const TopoDS_Shape& theShape1,
289                                 const TopoDS_Shape& theShape2) 
290 {
291   return theShape1.IsEqual(theShape2);
292 }
293
294 //=======================================================================
295 //function : AllocateSubLabel
296 //purpose  :
297 //=======================================================================
298
299 static TDF_Label AllocateSubLabel(TDF_Label& theRoot)
300 {
301   return TDF_TagSource::NewChild(theRoot);
302 }
303
304 //=======================================================================
305 //function : STEPCAFControl_Reader
306 //purpose  : 
307 //=======================================================================
308
309 STEPCAFControl_Reader::STEPCAFControl_Reader ():
310        myColorMode( Standard_True ),
311        myNameMode ( Standard_True ),
312        myLayerMode( Standard_True ),
313        myPropsMode( Standard_True ),
314            mySHUOMode ( Standard_False ),
315        myGDTMode  ( Standard_True ),
316        myMatMode  ( Standard_True )
317 {
318   STEPCAFControl_Controller::Init();
319   myFiles = new STEPCAFControl_DictionaryOfExternFile;
320 }
321
322
323 //=======================================================================
324 //function : STEPCAFControl_Reader
325 //purpose  : 
326 //=======================================================================
327
328 STEPCAFControl_Reader::STEPCAFControl_Reader (const Handle(XSControl_WorkSession)& WS,
329                                               const Standard_Boolean scratch) :
330        myColorMode( Standard_True ),
331        myNameMode ( Standard_True ),
332        myLayerMode( Standard_True ),
333        myPropsMode( Standard_True ),
334            mySHUOMode ( Standard_False ),
335        myGDTMode  ( Standard_True ),
336        myMatMode  ( Standard_True )
337 {
338   STEPCAFControl_Controller::Init();
339   Init ( WS, scratch );
340 }
341
342
343 //=======================================================================
344 //function : Init
345 //purpose  : 
346 //=======================================================================
347
348 void STEPCAFControl_Reader::Init (const Handle(XSControl_WorkSession)& WS,
349                                   const Standard_Boolean scratch)
350 {
351 // necessary only in Writer, to set good actor:  WS->SelectNorm ( "STEP" );
352   myReader.SetWS (WS,scratch);
353   myFiles = new STEPCAFControl_DictionaryOfExternFile;
354 }
355
356
357 //=======================================================================
358 //function : ReadFile
359 //purpose  : 
360 //=======================================================================
361
362 IFSelect_ReturnStatus STEPCAFControl_Reader::ReadFile (const Standard_CString filename)
363 {
364   return myReader.ReadFile ( filename );
365 }
366
367
368 //=======================================================================
369 //function : NbRootsForTransfer
370 //purpose  : 
371 //=======================================================================
372
373 Standard_Integer STEPCAFControl_Reader::NbRootsForTransfer () 
374 {
375   return myReader.NbRootsForTransfer();
376 }
377
378
379 //=======================================================================
380 //function : TransferOneRoot
381 //purpose  : 
382 //=======================================================================
383
384 Standard_Boolean STEPCAFControl_Reader::TransferOneRoot (const Standard_Integer num,
385                                                          Handle(TDocStd_Document) &doc) 
386 {
387   TDF_LabelSequence Lseq;
388   return Transfer ( myReader, num, doc, Lseq );
389 }
390
391
392 //=======================================================================
393 //function : Transfer
394 //purpose  : 
395 //=======================================================================
396
397 Standard_Boolean STEPCAFControl_Reader::Transfer (Handle(TDocStd_Document) &doc)
398 {
399   TDF_LabelSequence Lseq;
400   return Transfer ( myReader, 0, doc, Lseq );
401 }
402
403
404 //=======================================================================
405 //function : Perform
406 //purpose  : 
407 //=======================================================================
408
409 Standard_Boolean STEPCAFControl_Reader::Perform (const Standard_CString filename,
410                                                  Handle(TDocStd_Document) &doc)
411 {
412   if ( ReadFile ( filename ) != IFSelect_RetDone ) return Standard_False;
413   return Transfer ( doc );
414 }
415   
416
417 //=======================================================================
418 //function : Perform
419 //purpose  : 
420 //=======================================================================
421
422 Standard_Boolean STEPCAFControl_Reader::Perform (const TCollection_AsciiString &filename,
423                                                  Handle(TDocStd_Document) &doc)
424 {
425   if ( ReadFile ( filename.ToCString() ) != IFSelect_RetDone ) return Standard_False;
426   return Transfer ( doc );
427 }
428   
429
430 //=======================================================================
431 //function : ExternFiles
432 //purpose  : 
433 //=======================================================================
434
435 const Handle(STEPCAFControl_DictionaryOfExternFile) &STEPCAFControl_Reader::ExternFiles () const
436 {
437   return myFiles;
438 }
439         
440
441 //=======================================================================
442 //function : ExternFile
443 //purpose  : 
444 //=======================================================================
445
446 Standard_Boolean STEPCAFControl_Reader::ExternFile (const Standard_CString name,
447                                                     Handle(STEPCAFControl_ExternFile) &ef) const
448 {
449   ef.Nullify();
450   if ( myFiles.IsNull() || ! myFiles->HasItem ( name ) ) 
451     return Standard_False;
452   ef = myFiles->Item ( name );
453   return Standard_True;
454 }
455
456
457 //=======================================================================
458 //function : Reader
459 //purpose  : 
460 //=======================================================================
461
462 STEPControl_Reader &STEPCAFControl_Reader::ChangeReader () 
463 {
464   return myReader;
465 }
466   
467
468 //=======================================================================
469 //function : Reader
470 //purpose  : 
471 //=======================================================================
472
473 const STEPControl_Reader &STEPCAFControl_Reader::Reader () const
474 {
475   return myReader;
476 }
477   
478
479 //=======================================================================
480 //function : FillShapesMap
481 //purpose  : auxiliary: fill a map by all compounds and their components
482 //=======================================================================
483
484 static void FillShapesMap (const TopoDS_Shape &S, TopTools_MapOfShape &map)
485 {
486   TopoDS_Shape S0 = S;
487   TopLoc_Location loc;
488   S0.Location ( loc );
489   map.Add ( S0 );
490   if ( S.ShapeType() != TopAbs_COMPOUND ) return;
491   for ( TopoDS_Iterator it(S); it.More(); it.Next() ) 
492     FillShapesMap ( it.Value(), map );
493 }
494
495
496 //=======================================================================
497 //function : Transfer
498 //purpose  : basic working method
499 //=======================================================================
500
501 Standard_Boolean STEPCAFControl_Reader::Transfer (STEPControl_Reader &reader,
502                                                   const Standard_Integer nroot,
503                                                   Handle(TDocStd_Document) &doc,
504                                                   TDF_LabelSequence &Lseq,
505                                                   const Standard_Boolean asOne)
506 {
507   reader.ClearShapes();
508   Standard_Integer i;
509   
510   // Read all shapes
511   Standard_Integer num = reader.NbRootsForTransfer();
512   if ( num <=0 ) return Standard_False;
513   if ( nroot ) {
514     if ( nroot > num ) return Standard_False;
515     reader.TransferOneRoot ( nroot );
516   }
517   else {
518     for ( i=1; i <= num; i++ ) reader.TransferOneRoot ( i );
519   }
520   num = reader.NbShapes();
521   if ( num <=0 ) return Standard_False;
522
523   // Fill a map of (top-level) shapes resulting from that transfer
524   // Only these shapes will be considered further
525   TopTools_MapOfShape ShapesMap, NewShapesMap;
526   for ( i=1; i <= num; i++ ) FillShapesMap ( reader.Shape(i), ShapesMap );
527   
528   // Collect information on shapes originating from SDRs
529   // this will be used to distinguish compounds representing assemblies
530   // from the ones representing hybrid models and shape sets
531   STEPCAFControl_DataMapOfShapePD ShapePDMap;
532   STEPCAFControl_DataMapOfPDExternFile PDFileMap;
533   Handle(Interface_InterfaceModel) Model = reader.Model();
534   Handle(Transfer_TransientProcess) TP = reader.WS()->TransferReader()->TransientProcess();
535   Standard_Integer nb = Model->NbEntities();
536
537   Handle(TColStd_HSequenceOfTransient) SeqPDS = new TColStd_HSequenceOfTransient;
538
539   for (i = 1; i <= nb; i ++) {
540     Handle(Standard_Transient) enti = Model->Value(i);
541     if(enti->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape))) {
542       // sequence for acceleration ReadMaterials
543       SeqPDS->Append(enti);
544     }
545     if ( enti->IsKind ( STANDARD_TYPE(StepBasic_ProductDefinition ) ) ) {
546       Handle(StepBasic_ProductDefinition) PD = 
547         Handle(StepBasic_ProductDefinition)::DownCast(enti);
548       Standard_Integer index = TP->MapIndex(PD);
549       if ( index >0 ) {
550         Handle(Transfer_Binder) binder = TP->MapItem (index);
551         TopoDS_Shape S = TransferBRep::ShapeResult(binder);
552         if ( ! S.IsNull() && ShapesMap.Contains(S) ) {
553           NewShapesMap.Add(S);
554           ShapePDMap.Bind ( S, PD ); 
555           Handle(STEPCAFControl_ExternFile) EF;
556           PDFileMap.Bind ( PD, EF );
557         }
558       }
559     }
560     if ( enti->IsKind ( STANDARD_TYPE(StepShape_ShapeRepresentation) ) ) {
561       Standard_Integer index = TP->MapIndex(enti);
562       if ( index >0 ) {
563         Handle(Transfer_Binder) binder = TP->MapItem (index);
564         TopoDS_Shape S = TransferBRep::ShapeResult(binder);
565         if ( ! S.IsNull() && ShapesMap.Contains(S) )
566           NewShapesMap.Add(S);
567       }
568     }
569   }
570
571   // get directory name of the main file
572   OSD_Path mainfile ( reader.WS()->LoadedFile() );
573   mainfile.SetName ( "" );
574   mainfile.SetExtension ( "" );
575   TCollection_AsciiString dpath;
576   mainfile.SystemName ( dpath );
577
578   // Load external references (only for relevant SDRs)
579   // and fill map SDR -> extern file
580   STEPConstruct_ExternRefs ExtRefs ( reader.WS() );
581   ExtRefs.LoadExternRefs();
582   for ( i=1; i <= ExtRefs.NbExternRefs(); i++ ) {
583     // check extern ref format
584     Handle(TCollection_HAsciiString) format = ExtRefs.Format(i);
585     if ( ! format.IsNull() ) {
586       static Handle(TCollection_HAsciiString) ap203 = new TCollection_HAsciiString ( "STEP AP203" );
587       static Handle(TCollection_HAsciiString) ap214 = new TCollection_HAsciiString ( "STEP AP214" );
588       if ( ! format->IsSameString ( ap203, Standard_False ) && 
589            ! format->IsSameString ( ap214, Standard_False ) ) {
590 #ifdef OCCT_DEBUG
591         cout << "Warning: STEPCAFControl_Reader::Transfer: Extern document is neither STEP AP203 nor AP214" << endl;
592 #else
593         continue;
594 #endif
595       }
596     }
597 #ifdef OCCT_DEBUG
598     else cout << "Warning: STEPCAFControl_Reader::Transfer: Extern document format not defined" << endl;
599 #endif
600     
601     // get and check filename of the current extern ref
602     const Standard_CString filename = ExtRefs.FileName(i);
603
604 #ifdef OCCT_DEBUG
605     cout<<"filename="<<filename<<endl;
606 #endif
607
608     if ( ! filename || ! filename[0] ) {
609 #ifdef OCCT_DEBUG
610       cout << "Warning: STEPCAFControl_Reader::Transfer: Extern reference file name is empty" << endl;
611 #endif
612       continue; // not a valid extern ref
613     }
614
615     // compute true path to the extern file
616     TCollection_AsciiString fullname = OSD_Path::AbsolutePath ( dpath, filename );
617     if ( fullname.Length() <= 0 ) fullname = filename;
618
619 /*    
620     char fullname[1024];
621     char *mainfile = reader.WS()->LoadedFile();
622     if ( ! mainfile ) mainfile = "";
623     Standard_Integer slash = 0;
624     for ( Standard_Integer k=0; mainfile[k]; k++ )
625       if ( mainfile[k] == '/' ) slash = k;
626     strncpy ( fullname, mainfile, slash );
627     sprintf ( &fullname[slash], "%s%s", ( mainfile[0] ? "/" : "" ), filename );
628 */
629     
630     // get and check PD associated with the current extern ref
631     Handle(StepBasic_ProductDefinition) PD = ExtRefs.ProdDef(i);
632     if ( PD.IsNull() ) continue; // not a valid extern ref
633     if ( ! PDFileMap.IsBound ( PD ) ) continue; // this PD is not concerned by current transfer
634     
635     // read extern file (or use existing data) and record its data
636     Handle(STEPCAFControl_ExternFile) EF = 
637       ReadExternFile ( filename, fullname.ToCString(), doc );
638     PDFileMap.Bind ( PD, EF );
639   }
640   
641   // and insert them to the document
642   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( doc->Main() );
643   if ( STool.IsNull() ) return Standard_False;
644   XCAFDoc_DataMapOfShapeLabel map;
645   if ( asOne )
646     Lseq.Append ( AddShape ( reader.OneShape(), STool, NewShapesMap, ShapePDMap, PDFileMap, map ) );
647   else {
648     for ( i=1; i <= num; i++ ) {
649       Lseq.Append ( AddShape ( reader.Shape(i), STool, NewShapesMap, ShapePDMap, PDFileMap, map ) );
650     }
651   }
652   
653   // read colors
654   if ( GetColorMode() )
655     ReadColors ( reader.WS(), doc, PDFileMap, map );
656   
657   // read names
658   if ( GetNameMode() )
659     ReadNames ( reader.WS(), doc, PDFileMap, map );
660
661   // read validation props
662   if ( GetPropsMode() )
663     ReadValProps ( reader.WS(), doc, PDFileMap, map );
664
665   // read layers
666   if ( GetLayerMode() )
667     ReadLayers ( reader.WS(), doc );
668   
669   // read SHUO entities from STEP model
670   if ( GetSHUOMode() )
671     ReadSHUOs ( reader.WS(), doc, PDFileMap, map );
672
673   // read GDT entities from STEP model
674   if(GetGDTMode())
675     ReadGDTs(reader.WS(),doc);
676
677   // read Material entities from STEP model
678   if(GetMatMode())
679     ReadMaterials(reader.WS(),doc,SeqPDS);
680
681   // Expand resulting CAF structure for sub-shapes (optionally with their
682   // names) if requested
683   ExpandSubShapes(STool, map, ShapePDMap);
684
685   return Standard_True;
686 }
687
688 //=======================================================================
689 //function : AddShape
690 //purpose  : 
691 //=======================================================================
692
693 TDF_Label STEPCAFControl_Reader::AddShape (const TopoDS_Shape &S, 
694                                            const Handle(XCAFDoc_ShapeTool) &STool,
695                                            const TopTools_MapOfShape &NewShapesMap,
696                                            const STEPCAFControl_DataMapOfShapePD &ShapePDMap,
697                                            const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
698                                            XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
699 {
700   // if shape has already been mapped, just return corresponding label
701   if ( ShapeLabelMap.IsBound ( S ) ) {
702     return ShapeLabelMap.Find ( S );
703   }
704   
705   // if shape is located, create instance
706   if ( ! S.Location().IsIdentity() ) {
707     TopoDS_Shape S0 = S;
708     TopLoc_Location loc;
709     S0.Location ( loc );
710     AddShape ( S0, STool, NewShapesMap, ShapePDMap, PDFileMap, ShapeLabelMap );
711     TDF_Label L = STool->AddShape ( S, Standard_False ); // should create reference
712     ShapeLabelMap.Bind ( S, L );
713     return L;
714   }
715   
716   // if shape is not compound, simple add it
717   if ( S.ShapeType() != TopAbs_COMPOUND ) {
718     TDF_Label L = STool->AddShape ( S, Standard_False );
719     ShapeLabelMap.Bind ( S, L );
720     return L;
721   }
722   
723   // for compounds, compute number of subshapes and check whether this is assembly
724   Standard_Boolean isAssembly = Standard_False;
725   Standard_Integer nbComponents = 0;
726   TopoDS_Iterator it;
727   for ( it.Initialize(S); it.More(); it.Next(), nbComponents++ ) {
728     TopoDS_Shape Sub0 = it.Value();
729     TopLoc_Location loc;
730     Sub0.Location ( loc );
731     if ( NewShapesMap.Contains ( Sub0 ) ) isAssembly = Standard_True;
732   }
733
734 //  if(nbComponents>0) isAssembly = Standard_True;
735   
736   // check whether it has associated external ref
737   TColStd_SequenceOfHAsciiString SHAS;
738   if ( ShapePDMap.IsBound ( S ) && PDFileMap.IsBound ( ShapePDMap.Find(S) ) ) {
739     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( ShapePDMap.Find(S) );
740     if ( ! EF.IsNull() ) {
741       // (store information on extern refs in the document)
742       SHAS.Append(EF->GetName());
743       // if yes, just return corresponding label
744       if ( ! EF->GetLabel().IsNull() ) {
745         // but if components >0, ignore extern ref!
746         if ( nbComponents <=0 ) {
747           ShapeLabelMap.Bind ( S, EF->GetLabel() );
748           STool->SetExternRefs(EF->GetLabel(),SHAS);
749           return EF->GetLabel();
750         }
751       }
752 #ifdef OCCT_DEBUG
753       if ( ! EF->GetLabel().IsNull() )
754         cout << "Warning: STEPCAFControl_Reader::AddShape: Non-empty shape with external ref; ref is ignored" << endl;
755       else if ( nbComponents <=0 ) 
756         cout << "Warning: STEPCAFControl_Reader::AddShape: Result of reading extern ref is Null" << endl;
757 #endif
758     }
759   }
760   
761   // add compound either as a whole,
762   if ( ! isAssembly ) {
763     TDF_Label L = STool->AddShape ( S, Standard_False );
764     if ( SHAS.Length() >0 ) STool->SetExternRefs(L,SHAS);
765     ShapeLabelMap.Bind ( S, L );
766     return L;
767   }
768   
769   // or as assembly, component-by-component
770   TDF_Label L = STool->NewShape();
771   for ( it.Initialize(S); it.More(); it.Next(), nbComponents++ ) {
772     TopoDS_Shape Sub0 = it.Value();
773     TopLoc_Location loc;
774     Sub0.Location ( loc );
775     TDF_Label subL = AddShape ( Sub0, STool, NewShapesMap, ShapePDMap, PDFileMap, ShapeLabelMap );
776     if ( ! subL.IsNull() ) {
777       STool->AddComponent ( L, subL, it.Value().Location() );
778     }
779   }
780   if ( SHAS.Length() >0 ) STool->SetExternRefs(L,SHAS);
781   ShapeLabelMap.Bind ( S, L );
782   //STool->SetShape ( L, S ); // it is necessary for assemblies OCC1747 // commemted by skl for OCC2941
783
784   return L;
785 }
786
787 //=======================================================================
788 //function : ReadExternFile
789 //purpose  : 
790 //=======================================================================
791
792 Handle(STEPCAFControl_ExternFile) STEPCAFControl_Reader::ReadExternFile (const Standard_CString file, 
793                                                                          const Standard_CString fullname, 
794                                                                          Handle(TDocStd_Document)& doc) 
795 {
796   // if the file is already read, associate it with SDR
797   if ( myFiles->HasItem ( file, Standard_True ) ) {
798     return myFiles->Item ( file );
799   }
800
801 #ifdef OCCT_DEBUG
802   cout << "Reading extern file: " << fullname << endl;
803 #endif
804  
805   // create new WorkSession and Reader
806   Handle(XSControl_WorkSession) newWS = new XSControl_WorkSession;
807   newWS->SelectNorm ( "STEP" );
808   STEPControl_Reader sr ( newWS, Standard_False );
809   
810   // start to fill the resulting ExternFile structure
811   Handle(STEPCAFControl_ExternFile) EF = new STEPCAFControl_ExternFile;
812   EF->SetWS ( newWS );
813   EF->SetName ( new TCollection_HAsciiString ( file ) );
814   
815   // read file
816   EF->SetLoadStatus ( sr.ReadFile ( fullname ) );
817   
818   // transfer in single-result mode
819   if ( EF->GetLoadStatus() == IFSelect_RetDone ) {
820     TDF_LabelSequence labels;
821     EF->SetTransferStatus ( Transfer ( sr, 0, doc, labels, Standard_True ) );
822     if ( labels.Length() >0 ) EF->SetLabel ( labels.Value(1) );
823   }
824   
825   // add read file to dictionary
826   myFiles->SetItem ( file, EF );
827   
828   return EF;
829 }
830
831
832 //=======================================================================
833 //function : SetColorToSubshape
834 //purpose  : auxilary
835 //=======================================================================
836 static void SetColorToSubshape(const Handle(XCAFDoc_ColorTool) & CTool,
837                                const TopoDS_Shape & S,
838                                const Quantity_Color& col,
839                                const XCAFDoc_ColorType type)
840 {
841   for (TopoDS_Iterator it(S); it.More(); it.Next())
842     if (! CTool->SetColor( it.Value(), col, type)) break;
843 }
844
845
846 //=======================================================================
847 //function : findStyledSR
848 //purpose  : auxilary
849 //=======================================================================
850 static void findStyledSR (const Handle(StepVisual_StyledItem) &style,
851                           Handle(StepShape_ShapeRepresentation)& aSR)
852 {
853   // search Shape Represenatation for component styled item
854   for ( Standard_Integer j=1; j <= style->NbStyles(); j++ ) {
855     Handle(StepVisual_PresentationStyleByContext) PSA = 
856       Handle(StepVisual_PresentationStyleByContext)::DownCast(style->StylesValue ( j ));
857     if ( PSA.IsNull() )
858       continue;
859     StepVisual_StyleContextSelect aStyleCntxSlct = PSA->StyleContext();
860     Handle(StepShape_ShapeRepresentation) aCurrentSR = 
861       Handle(StepShape_ShapeRepresentation)::DownCast(aStyleCntxSlct.Representation());
862     if ( aCurrentSR.IsNull() )
863       continue;
864     aSR = aCurrentSR;
865       break;
866   }
867 }
868
869
870 //=======================================================================
871 //function : ReadColors
872 //purpose  : 
873 //=======================================================================
874
875 Standard_Boolean STEPCAFControl_Reader::ReadColors (const Handle(XSControl_WorkSession) &WS,
876                                                     Handle(TDocStd_Document)& Doc,
877                                                     const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
878                                                     const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
879 {
880   STEPConstruct_Styles Styles ( WS );
881   if ( ! Styles.LoadStyles() ) {
882 #ifdef OCCT_DEBUG
883     cout << "Warning: no styles are found in the model" << endl;
884 #endif
885     return Standard_False;
886   }
887   // searching for invisible items in the model
888   Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
889   Styles.LoadInvisStyles( aHSeqOfInvisStyle );
890   
891   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( Doc->Main() );
892   if ( CTool.IsNull() ) return Standard_False;
893
894   // parse and search for color attributes
895   Standard_Integer nb = Styles.NbStyles();
896   for ( Standard_Integer i=1; i <= nb; i++ ) {
897     Handle(StepVisual_StyledItem) style = Styles.Style ( i );
898     if ( style.IsNull() ) continue;
899     
900     Standard_Boolean IsVisible = Standard_True;
901     // check the visibility of styled item.
902     for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++ ) {
903       if ( style != aHSeqOfInvisStyle->Value( si ) )
904         continue;
905       // found that current style is invisible.
906       IsVisible = Standard_False;
907       break;
908     }
909
910     Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol;
911     // check if it is component style
912     Standard_Boolean IsComponent = Standard_False;
913     if ( ! Styles.GetColors ( style, SurfCol, BoundCol, CurveCol, IsComponent ) && IsVisible )
914       continue;
915     
916     // find shape
917     NCollection_Vector<Handle(MMgt_TShared)> anItems;
918     if (!style->Item().IsNull()) {
919       anItems.Append(style->Item());
920     }
921     else if (!style->ItemAP242().Representation().IsNull()){
922       //special case for AP242: item can be Reprsentation
923       Handle(StepRepr_Representation) aRepr = style->ItemAP242().Representation();
924       for (Standard_Integer i = 1; i <= aRepr->Items()->Length(); i++)
925         anItems.Append(aRepr->Items()->Value(i));
926     }
927     for (Standard_Integer itemIt = 0; itemIt < anItems.Length(); itemIt++) {
928       TopoDS_Shape S = STEPConstruct::FindShape ( Styles.TransientProcess(),
929         Handle(StepRepr_RepresentationItem)::DownCast(anItems.Value(itemIt)) );
930       Standard_Boolean isSkipSHUOstyle = Standard_False;
931       // take shape with real location.
932       while ( IsComponent ) {
933         // take SR of NAUO
934         Handle(StepShape_ShapeRepresentation) aSR;
935         findStyledSR( style, aSR );
936         // search for SR along model
937         if (aSR.IsNull())
938           break;
939         Handle(XSControl_TransferReader) TR = WS->TransferReader();
940         Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
941         Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings( aSR );
942         Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
943         for (subs.Start(); subs.More(); subs.Next()) {
944           aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
945           if ( aSDR.IsNull() )
946             continue;
947           StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
948           Handle(StepRepr_ProductDefinitionShape) PDS = 
949             Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
950           if ( PDS.IsNull() )
951             continue;
952           StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
953           
954           Handle(StepRepr_AssemblyComponentUsage) ACU = 
955             Handle(StepRepr_AssemblyComponentUsage)::DownCast(aCharDef.ProductDefinitionRelationship());
956           // PTV 10.02.2003 skip styled item that refer to SHUO
957           if (ACU->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
958             isSkipSHUOstyle = Standard_True;
959             break;
960           }
961           Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO =
962             Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(ACU);
963           if ( NAUO.IsNull() )
964             continue;
965           
966           TopoDS_Shape aSh;
967           // PTV 10.02.2003 to find component of assembly CORRECTLY
968           STEPConstruct_Tool Tool( WS );
969           TDF_Label aShLab = FindInstance ( NAUO, CTool->ShapeTool(), Tool, PDFileMap, ShapeLabelMap );
970           aSh = CTool->ShapeTool()->GetShape(aShLab);
971           if (!aSh.IsNull()) {
972             S = aSh;
973             break;
974           }
975         }
976         break;
977       }
978       if (isSkipSHUOstyle)
979         continue; // skip styled item which refer to SHUO
980       
981       if ( S.IsNull() )
982         continue;
983       
984       if ( ! SurfCol.IsNull() ) {
985         Quantity_Color col;
986         Styles.DecodeColor ( SurfCol, col );
987         if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorSurf ))
988           SetColorToSubshape( CTool, S, col, XCAFDoc_ColorSurf );
989       }
990       if ( ! BoundCol.IsNull() ) {
991         Quantity_Color col;
992         Styles.DecodeColor ( BoundCol, col );
993         if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorCurv ))
994           SetColorToSubshape(  CTool, S, col, XCAFDoc_ColorCurv );
995       }
996       if ( ! CurveCol.IsNull() ) {
997         Quantity_Color col;
998         Styles.DecodeColor ( CurveCol, col );
999         if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorCurv ))
1000           SetColorToSubshape(  CTool, S, col, XCAFDoc_ColorCurv );
1001       }
1002       if ( !IsVisible ) {
1003         // sets the invisibility for shape.
1004         TDF_Label aInvL;
1005         if ( CTool->ShapeTool()->Search( S, aInvL ) )
1006           CTool->SetVisibility( aInvL, Standard_False );
1007       }
1008     }
1009   }
1010   CTool->ReverseChainsOfTreeNodes();
1011   return Standard_True;
1012 }
1013
1014 //=======================================================================
1015 //function : GetLabelFromPD
1016 //purpose  : 
1017 //=======================================================================
1018
1019 static TDF_Label GetLabelFromPD (const Handle(StepBasic_ProductDefinition) &PD,
1020                                  const Handle(XCAFDoc_ShapeTool) &STool,
1021                                  const Handle(Transfer_TransientProcess) &TP,
1022                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1023                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1024 {
1025   TDF_Label L;
1026   if ( PDFileMap.IsBound ( PD ) ) {
1027     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( PD );
1028     if ( ! EF.IsNull() ) {
1029       L = EF->GetLabel();
1030       if ( ! L.IsNull() ) return L;
1031     }
1032   }
1033
1034   TopoDS_Shape S;
1035   Handle(Transfer_Binder) binder = TP->Find(PD);
1036   if ( binder.IsNull() || ! binder->HasResult() ) return L;
1037   S = TransferBRep::ShapeResult ( TP, binder );
1038   if ( S.IsNull() ) return L;
1039
1040   if ( S.IsNull() ) return L;
1041   if ( ShapeLabelMap.IsBound ( S ) )
1042     L = ShapeLabelMap.Find ( S );
1043   if ( L.IsNull() )
1044     STool->Search ( S, L, Standard_True, Standard_True, Standard_False );
1045   return L;
1046 }
1047
1048 //=======================================================================
1049 //function : FindInstance
1050 //purpose  : 
1051 //=======================================================================
1052
1053 TDF_Label STEPCAFControl_Reader::FindInstance (const Handle(StepRepr_NextAssemblyUsageOccurrence) &NAUO,
1054                                                const Handle(XCAFDoc_ShapeTool) &STool,
1055                                                const STEPConstruct_Tool &Tool,
1056                                                const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1057                                                const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1058 {
1059   TDF_Label L;
1060   
1061   // get shape resulting from CDSR (in fact, only location is interesting)
1062   Handle(Transfer_TransientProcess) TP = Tool.TransientProcess();
1063   Handle(Transfer_Binder) binder = TP->Find(NAUO);
1064   if ( binder.IsNull() || ! binder->HasResult() ) {
1065 #ifdef OCCT_DEBUG
1066     cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << endl;
1067 #endif
1068     return L;
1069   }
1070   
1071   TopoDS_Shape S = TransferBRep::ShapeResult ( TP, binder );
1072   if ( S.IsNull() ) {
1073 #ifdef OCCT_DEBUG
1074     cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << endl;
1075 #endif
1076     return L;
1077   }
1078
1079   // find component`s original label
1080   Handle(StepBasic_ProductDefinition) PD = NAUO->RelatedProductDefinition();
1081   if ( PD.IsNull() ) return L;
1082   TDF_Label Lref = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
1083   if ( Lref.IsNull() ) return L;
1084   
1085   // find main shape (assembly) label
1086   PD.Nullify();
1087   PD = NAUO->RelatingProductDefinition();
1088   if ( PD.IsNull() ) return L;
1089   TDF_Label L0 = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
1090   if ( L0.IsNull() ) return L;
1091   
1092   // if CDSR and NAUO are reversed, swap labels
1093   Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1094   Interface_EntityIterator subs1 = Tool.Graph().Sharings(NAUO);
1095   for (subs1.Start(); subs1.More(); subs1.Next()) {
1096     Handle(StepRepr_ProductDefinitionShape) PDS = 
1097       Handle(StepRepr_ProductDefinitionShape)::DownCast(subs1.Value());
1098     if(PDS.IsNull()) continue;
1099     Interface_EntityIterator subs2 = Tool.Graph().Sharings(PDS);
1100     for (subs2.Start(); subs2.More(); subs2.Next()) {
1101       Handle(StepShape_ContextDependentShapeRepresentation) CDSRtmp = 
1102         Handle(StepShape_ContextDependentShapeRepresentation)::DownCast(subs2.Value());
1103       if (CDSRtmp.IsNull()) continue;
1104       CDSR = CDSRtmp;
1105     }
1106   }
1107   if (CDSR.IsNull()) return L;
1108 //  if ( STEPConstruct_Assembly::CheckSRRReversesNAUO ( Tool.Model(), CDSR ) ) {
1109 //    TDF_Label Lsw = L0; L0 = Lref; Lref = Lsw;
1110 //  }
1111   
1112   // iterate on components to find proper one
1113   TDF_LabelSequence seq;
1114   XCAFDoc_ShapeTool::GetComponents ( L0, seq );
1115   for ( Standard_Integer k=1; L.IsNull() && k <= seq.Length(); k++ ) {
1116     TDF_Label Lcomp = seq(k), Lref2;
1117     if ( XCAFDoc_ShapeTool::GetReferredShape ( Lcomp, Lref2 ) && 
1118         Lref2 == Lref &&
1119         S.Location() == XCAFDoc_ShapeTool::GetLocation ( Lcomp ) ) 
1120       L = Lcomp;
1121   }
1122   
1123   return L;
1124 }
1125
1126 //=======================================================================
1127 //function : ReadNames
1128 //purpose  : 
1129 //=======================================================================
1130
1131 Standard_Boolean STEPCAFControl_Reader::ReadNames (const Handle(XSControl_WorkSession) &WS,
1132                                                    Handle(TDocStd_Document)& Doc,
1133                                                    const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1134                                                    const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1135 {
1136   // get starting data
1137   Handle(Interface_InterfaceModel) Model = WS->Model();
1138   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1139   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1140   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1141   if ( STool.IsNull() ) return Standard_False;
1142   STEPConstruct_Tool Tool ( WS );
1143
1144   // iterate on model to find all SDRs and CDSRs
1145   Standard_Integer nb = Model->NbEntities();
1146   Handle(Standard_Type) tNAUO = STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence);
1147   Handle(Standard_Type) tPD  = STANDARD_TYPE(StepBasic_ProductDefinition);
1148   Handle(TCollection_HAsciiString) name;
1149   TDF_Label L;
1150   for (Standard_Integer i = 1; i <= nb; i++) {
1151     Handle(Standard_Transient) enti = Model->Value(i);
1152
1153     // get description of NAUO
1154     if ( enti->DynamicType() == tNAUO ) {
1155       L.Nullify();
1156       Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO = 
1157         Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(enti);
1158       if(NAUO.IsNull()) continue;
1159       Interface_EntityIterator subs = WS->Graph().Sharings(NAUO);
1160       for (subs.Start(); subs.More(); subs.Next()) {
1161         Handle(StepRepr_ProductDefinitionShape) PDS = 
1162           Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
1163         if(PDS.IsNull()) continue;
1164         Handle(StepBasic_ProductDefinitionRelationship) PDR = PDS->Definition().ProductDefinitionRelationship();
1165         if ( PDR.IsNull() ) continue;
1166         if ( PDR->HasDescription() && 
1167             PDR->Description()->Length() >0 ) name = PDR->Description();
1168         else if ( !PDR->Name().IsNull() && PDR->Name()->Length() >0 ) name = PDR->Name();
1169         else if ( !PDR->Id().IsNull()) name = PDR->Id();
1170         else name = new TCollection_HAsciiString;
1171       }
1172       // find proper label
1173       L = FindInstance ( NAUO, STool, Tool, PDFileMap, ShapeLabelMap );
1174       if ( L.IsNull() ) continue;
1175       TCollection_ExtendedString str ( name->String() );
1176       TDataStd_Name::Set ( L, str );
1177     }
1178
1179     // for PD get name of associated product
1180     if ( enti->DynamicType() == tPD ) {
1181       L.Nullify();
1182       Handle(StepBasic_ProductDefinition) PD = 
1183         Handle(StepBasic_ProductDefinition)::DownCast(enti);
1184       if(PD.IsNull()) continue;
1185       Handle(StepBasic_Product) Prod = (!PD->Formation().IsNull() ? PD->Formation()->OfProduct() : NULL);
1186       if (Prod.IsNull())
1187         name = new TCollection_HAsciiString;
1188       else if (!Prod->Name().IsNull() && Prod->Name()->UsefullLength() > 0) 
1189         name = Prod->Name();
1190       else if (!Prod->Id().IsNull()) 
1191         name = Prod->Id();
1192       else 
1193         name = new TCollection_HAsciiString;
1194       L = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
1195       if ( L.IsNull() ) continue;
1196       TCollection_ExtendedString str ( name->String() );
1197       TDataStd_Name::Set ( L, str );
1198     }
1199     // set a name to the document
1200     //TCollection_ExtendedString str ( name->String() );
1201     //TDataStd_Name::Set ( L, str );
1202   }
1203
1204   return Standard_True;
1205 }
1206
1207 //=======================================================================
1208 //function : GetLabelFromPD
1209 //purpose  : 
1210 //=======================================================================
1211
1212 static TDF_Label GetLabelFromPD (const Handle(StepBasic_ProductDefinition) &PD,
1213                                  const Handle(XCAFDoc_ShapeTool) &STool,
1214                                  const STEPConstruct_ValidationProps &Props,
1215                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1216                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1217 {
1218   TDF_Label L;
1219   if ( PDFileMap.IsBound ( PD ) ) {
1220     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( PD );
1221     if ( ! EF.IsNull() ) {
1222       L = EF->GetLabel();
1223       if ( ! L.IsNull() ) return L;
1224     }
1225   }
1226   TopoDS_Shape S = Props.GetPropShape ( PD );
1227   if ( S.IsNull() ) return L;
1228   if ( ShapeLabelMap.IsBound ( S ) )
1229     L = ShapeLabelMap.Find ( S );
1230   if ( L.IsNull() )
1231     STool->Search ( S, L, Standard_True, Standard_True, Standard_False );
1232   return L;
1233 }
1234
1235 //=======================================================================
1236 //function : ReadValProps
1237 //purpose  : 
1238 //=======================================================================
1239
1240 Standard_Boolean STEPCAFControl_Reader::ReadValProps (const Handle(XSControl_WorkSession) &WS,
1241                                                       Handle(TDocStd_Document)& Doc,
1242                                                       const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1243                                                       const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1244 {
1245   // get starting data
1246   Handle(Interface_InterfaceModel) Model = WS->Model();
1247   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1248   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1249   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1250   if ( STool.IsNull() ) return Standard_False;
1251
1252   // load props from the STEP model
1253   TColStd_SequenceOfTransient props;
1254   STEPConstruct_ValidationProps Props ( WS );
1255   if ( ! Props.LoadProps ( props ) ) {
1256 #ifdef OCCT_DEBUG
1257     cout << "Warning: no validation props found in the model" << endl;
1258 #endif
1259     return Standard_False;
1260   }
1261
1262   // interpret props one by one
1263   for (Standard_Integer i = 1; i <= props.Length(); i ++) {
1264     Handle(StepRepr_PropertyDefinitionRepresentation) PDR = 
1265       Handle(StepRepr_PropertyDefinitionRepresentation)::DownCast ( props.Value(i) );
1266     if ( PDR.IsNull() ) continue;
1267
1268     TDF_Label L;
1269
1270     Handle(StepRepr_PropertyDefinition) PD = PDR->Definition().PropertyDefinition();
1271     Interface_EntityIterator subs = Props.Graph().Shareds(PD);
1272     for (subs.Start(); L.IsNull() && subs.More(); subs.Next()) {
1273       if ( subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape)) ) {
1274         Handle(StepRepr_ProductDefinitionShape) PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
1275         if(PDS.IsNull()) continue;
1276         // find corresponding NAUO
1277         Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO;
1278         Interface_EntityIterator subs1 = Props.Graph().Shareds(PDS);
1279         for (subs1.Start(); NAUO.IsNull() && subs1.More(); subs1.Next()) {
1280           if ( subs1.Value()->IsKind(STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence)) ) 
1281             NAUO = Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subs1.Value());
1282         }
1283         if ( !NAUO.IsNull() ) {
1284           L = FindInstance ( NAUO, STool, WS, PDFileMap, ShapeLabelMap );
1285           if ( L.IsNull() ) continue;
1286         }
1287         else {
1288           // find corresponding ProductDefinition:
1289           Handle(StepBasic_ProductDefinition) ProdDef;
1290           Interface_EntityIterator subsPDS = Props.Graph().Shareds(PDS);
1291           for (subsPDS.Start(); ProdDef.IsNull() && subsPDS.More(); subsPDS.Next()) {
1292             if ( subsPDS.Value()->IsKind(STANDARD_TYPE(StepBasic_ProductDefinition)) ) 
1293               ProdDef = Handle(StepBasic_ProductDefinition)::DownCast(subsPDS.Value());
1294           }
1295           if ( ProdDef.IsNull() ) continue;
1296           L = GetLabelFromPD ( ProdDef, STool, Props, PDFileMap, ShapeLabelMap );
1297         }
1298       }
1299
1300       if ( subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)) ) {
1301         Handle(StepRepr_ShapeAspect) SA = Handle(StepRepr_ShapeAspect)::DownCast(subs.Value());
1302         if(SA.IsNull()) continue;
1303         // find ShapeRepresentation
1304         Handle(StepShape_ShapeRepresentation) SR;
1305         Interface_EntityIterator subs1 = Props.Graph().Sharings(SA);
1306         for(subs1.Start(); subs1.More() && SR.IsNull(); subs1.Next()) {
1307           Handle(StepRepr_PropertyDefinition) PropD1 = 
1308             Handle(StepRepr_PropertyDefinition)::DownCast(subs1.Value());
1309           if(PropD1.IsNull()) continue;
1310           Interface_EntityIterator subs2 = Props.Graph().Sharings(PropD1);
1311           for(subs2.Start(); subs2.More() && SR.IsNull(); subs2.Next()) {
1312             Handle(StepShape_ShapeDefinitionRepresentation) SDR =
1313               Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs2.Value());
1314             if(SDR.IsNull()) continue;
1315             SR = Handle(StepShape_ShapeRepresentation)::DownCast(SDR->UsedRepresentation());
1316           }
1317         }
1318         if(SR.IsNull()) continue;
1319         Handle(Transfer_Binder) binder;
1320         for(Standard_Integer ir=1; ir<=SR->NbItems() && binder.IsNull(); ir++) {
1321           if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_SolidModel))) {
1322             Handle(StepShape_SolidModel) SM = 
1323               Handle(StepShape_SolidModel)::DownCast(SR->ItemsValue(ir));
1324             binder = TP->Find(SM);
1325           }
1326           else if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_ShellBasedSurfaceModel))) {
1327             Handle(StepShape_ShellBasedSurfaceModel) SBSM =
1328               Handle(StepShape_ShellBasedSurfaceModel)::DownCast(SR->ItemsValue(ir));
1329             binder = TP->Find(SBSM);
1330           }
1331           else if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_GeometricSet))) {
1332             Handle(StepShape_GeometricSet) GS =
1333               Handle(StepShape_GeometricSet)::DownCast(SR->ItemsValue(ir));
1334             binder = TP->Find(GS);
1335           }
1336         }
1337         if ( binder.IsNull() || ! binder->HasResult() ) continue;
1338         TopoDS_Shape S;
1339         S = TransferBRep::ShapeResult ( TP, binder );
1340         if(S.IsNull()) continue;
1341         if ( ShapeLabelMap.IsBound ( S ) )
1342           L = ShapeLabelMap.Find ( S );
1343         if ( L.IsNull() )
1344           STool->Search ( S, L, Standard_True, Standard_True, Standard_True );
1345       }
1346     }
1347
1348     if(L.IsNull()) continue;
1349       
1350     // decode validation properties
1351     Handle(StepRepr_Representation) rep = PDR->UsedRepresentation();
1352     for ( Standard_Integer j=1; j <= rep->NbItems(); j++ ) {
1353       Handle(StepRepr_RepresentationItem) ent = rep->ItemsValue(j);
1354       Standard_Boolean isArea;
1355       Standard_Real val;
1356       gp_Pnt pos;
1357       if ( Props.GetPropReal ( ent, val, isArea ) ) {
1358         if ( isArea ) XCAFDoc_Area::Set ( L, val );
1359         else XCAFDoc_Volume::Set ( L, val );
1360       }
1361       else if ( Props.GetPropPnt ( ent, rep->ContextOfItems(), pos ) ) {
1362         XCAFDoc_Centroid::Set ( L, pos );
1363       }
1364     }
1365   }
1366   return Standard_True;
1367 }
1368
1369 //=======================================================================
1370 //function : ReadLayers
1371 //purpose  : 
1372 //=======================================================================
1373
1374 Standard_Boolean STEPCAFControl_Reader::ReadLayers (const Handle(XSControl_WorkSession) &WS,
1375                                                     Handle(TDocStd_Document)& Doc) const
1376 {
1377   Handle(Interface_InterfaceModel) Model = WS->Model();
1378   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1379   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1380   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1381   if ( STool.IsNull() ) return Standard_False;
1382   Handle(XCAFDoc_LayerTool) LTool = XCAFDoc_DocumentTool::LayerTool( Doc->Main() );
1383   if ( LTool.IsNull() ) return Standard_False;
1384   
1385   Handle(Standard_Type) tSVPLA = STANDARD_TYPE(StepVisual_PresentationLayerAssignment);
1386   Standard_Integer nb = Model->NbEntities();
1387   Handle(TCollection_HAsciiString) name;
1388   
1389   for (Standard_Integer i = 1; i <= nb; i ++) {
1390     Handle(Standard_Transient) enti = Model->Value(i);
1391     if ( ! enti->IsKind ( tSVPLA ) ) continue;
1392     Handle(StepVisual_PresentationLayerAssignment) SVPLA = 
1393       Handle(StepVisual_PresentationLayerAssignment)::DownCast(enti);
1394     
1395     Handle(TCollection_HAsciiString) descr = SVPLA->Description();
1396     Handle(TCollection_HAsciiString) hName = SVPLA->Name();
1397     TCollection_ExtendedString aLayerName ( hName->String() );
1398      
1399     // find a target shape and its label in the document
1400     for (Standard_Integer j = 1; j <= SVPLA->NbAssignedItems(); j++ ) {
1401       StepVisual_LayeredItem LI = SVPLA->AssignedItemsValue(j);
1402       Handle(Transfer_Binder) binder = TP->Find( LI.Value() );
1403       if ( binder.IsNull() || ! binder->HasResult() ) continue;
1404       
1405       TopoDS_Shape S = TransferBRep::ShapeResult ( TP, binder );
1406       if ( S.IsNull() ) continue;
1407         
1408       TDF_Label shL;
1409       if ( ! STool->Search ( S, shL, Standard_True, Standard_True, Standard_True ) ) continue;
1410       LTool->SetLayer ( shL, aLayerName );
1411     }
1412     
1413     // check invisibility
1414     Interface_EntityIterator subs = WS->Graph().Sharings(SVPLA);
1415     for (subs.Start(); subs.More(); subs.Next()) {
1416       if ( ! subs.Value()->IsKind(STANDARD_TYPE(StepVisual_Invisibility)) ) continue;
1417 #ifdef OCCT_DEBUG
1418       cout<< "\tLayer \"" << aLayerName << "\" is invisible"<<endl;
1419 #endif
1420       //TDF_Label InvLayerLab = LTool->FindLayer(aLayerName);
1421       TDF_Label InvLayerLab = LTool->AddLayer(aLayerName); //skl for OCC3926
1422       Handle(TDataStd_UAttribute) aUAttr;
1423       aUAttr->Set( InvLayerLab, XCAFDoc::InvisibleGUID() );
1424     }
1425   }
1426   return Standard_True;
1427 }
1428
1429 //=======================================================================
1430 //function : ReadSHUOs
1431 //purpose  : 
1432 //=======================================================================
1433
1434 static Standard_Boolean findNextSHUOlevel (const Handle(XSControl_WorkSession) &WS,
1435                                            const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1436                                            const Handle(XCAFDoc_ShapeTool)& STool,
1437                                            const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1438                                            const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap,
1439                                            TDF_LabelSequence& aLabels)
1440 {
1441   Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings(SHUO);
1442   Handle(StepRepr_SpecifiedHigherUsageOccurrence) subSHUO;
1443   for (subs.Start(); subs.More(); subs.Next()) {
1444     if (subs.Value()->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
1445       subSHUO = Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(subs.Value());
1446       break;
1447     }
1448   }
1449   if (subSHUO.IsNull())
1450     return Standard_False;
1451   
1452   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO = subSHUO->NextUsage();
1453   if (NUNAUO.IsNull())
1454     return Standard_False;
1455 //   Handle(Interface_InterfaceModel) Model = WS->Model();
1456 //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1457 //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1458 //   Handle(Transfer_Binder) binder = TP->Find(NUNAUO);
1459 //   if ( binder.IsNull() || ! binder->HasResult() )
1460 //     return Standard_False;
1461 //   TopoDS_Shape NUSh = TransferBRep::ShapeResult ( TP, binder );
1462   // get label of NAUO next level
1463   TDF_Label NULab;
1464   STEPConstruct_Tool Tool( WS );
1465   NULab = STEPCAFControl_Reader::FindInstance ( NUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1466 //   STool->Search(NUSh, NUlab);
1467   if (NULab.IsNull())
1468     return Standard_False;
1469   aLabels.Append( NULab );
1470   // and check by recurse.
1471   findNextSHUOlevel( WS, subSHUO, STool, PDFileMap, ShapeLabelMap, aLabels );
1472   return Standard_True;
1473 }
1474
1475
1476 //=======================================================================
1477 //function : setSHUOintoDoc
1478 //purpose  : auxilary
1479 //=======================================================================
1480 static TDF_Label setSHUOintoDoc (const Handle(XSControl_WorkSession) &WS,
1481                                  const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1482                                  const Handle(XCAFDoc_ShapeTool)& STool,
1483                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1484                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1485 {
1486   TDF_Label aMainLabel;
1487   // get upper usage NAUO from SHUO.
1488   Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO =
1489     Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(SHUO->UpperUsage());
1490   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO = SHUO->NextUsage();
1491   if ( UUNAUO.IsNull() || NUNAUO.IsNull() ) {
1492 #ifdef OCCT_DEBUG
1493     cout << "Warning: " << __FILE__ <<": Upper_usage or Next_usage of styled SHUO is null. Skip it" << endl;
1494 #endif
1495     return aMainLabel;
1496   }
1497 //   Handle(Interface_InterfaceModel) Model = WS->Model();
1498 //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1499 //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1500 //   TopoDS_Shape UUSh, NUSh;
1501 //   Handle(Transfer_Binder) binder = TP->Find(UUNAUO);
1502 //   if ( binder.IsNull() || ! binder->HasResult() )
1503 //     return aMainLabel;
1504 //   UUSh = TransferBRep::ShapeResult ( TP, binder );
1505 //   binder = TP->Find(NUNAUO);
1506 //   if ( binder.IsNull() || ! binder->HasResult() )
1507 //     return aMainLabel;
1508 //   NUSh = TransferBRep::ShapeResult ( TP, binder );
1509
1510   // get first labels for first SHUO attribute
1511   TDF_Label UULab, NULab;
1512   STEPConstruct_Tool Tool( WS );
1513   UULab = STEPCAFControl_Reader::FindInstance ( UUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1514   NULab = STEPCAFControl_Reader::FindInstance ( NUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1515   
1516 //   STool->Search(UUSh, UULab);
1517 //   STool->Search(NUSh, NULab);
1518   if (UULab.IsNull() || NULab.IsNull()) return aMainLabel;
1519   //create sequence fo labels to set SHUO structure into the document
1520   TDF_LabelSequence ShuoLabels;
1521   ShuoLabels.Append( UULab );
1522   ShuoLabels.Append( NULab );
1523   // add all other labels of sub SHUO entities
1524   findNextSHUOlevel( WS, SHUO, STool, PDFileMap, ShapeLabelMap, ShuoLabels );
1525   // last accord for SHUO
1526   Handle(XCAFDoc_GraphNode) anSHUOAttr;
1527   if ( STool->SetSHUO( ShuoLabels, anSHUOAttr ) )
1528     aMainLabel = anSHUOAttr->Label();
1529   
1530   return aMainLabel;
1531 }
1532
1533
1534 //=======================================================================
1535 //function : ReadSHUOs
1536 //purpose  : 
1537 //=======================================================================
1538
1539 Standard_Boolean STEPCAFControl_Reader::ReadSHUOs (const Handle(XSControl_WorkSession) &WS,
1540                                                    Handle(TDocStd_Document)& Doc,
1541                                                    const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1542                                                    const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1543 {
1544   // the big part code duplication from ReadColors.
1545   // It is possible to share this code functionality, just to decide how ???
1546   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( Doc->Main() );
1547   Handle(XCAFDoc_ShapeTool) STool = CTool->ShapeTool();
1548   
1549   STEPConstruct_Styles Styles ( WS );
1550   if ( ! Styles.LoadStyles() ) {
1551 #ifdef OCCT_DEBUG
1552     cout << "Warning: no styles are found in the model" << endl;
1553 #endif
1554     return Standard_False;
1555   }
1556   // searching for invisible items in the model
1557   Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
1558   Styles.LoadInvisStyles( aHSeqOfInvisStyle );
1559   // parse and search for color attributes
1560   Standard_Integer nb = Styles.NbStyles();
1561   for ( Standard_Integer i=1; i <= nb; i++ ) {
1562     Handle(StepVisual_StyledItem) style = Styles.Style ( i );
1563     if ( style.IsNull() ) continue;
1564     
1565     Standard_Boolean IsVisible = Standard_True;
1566     // check the visibility of styled item.
1567     for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++ ) {
1568       if ( style != aHSeqOfInvisStyle->Value( si ) )
1569         continue;
1570       // found that current style is invisible.
1571 #ifdef OCCT_DEBUG
1572       cout << "Warning: item No " << i << "(" << style->Item()->DynamicType()->Name() << ") is invisible" << endl;
1573 #endif
1574       IsVisible = Standard_False;
1575       break;
1576     }
1577
1578     Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol;
1579     // check if it is component style
1580     Standard_Boolean IsComponent = Standard_False;
1581     if ( ! Styles.GetColors ( style, SurfCol, BoundCol, CurveCol, IsComponent ) && IsVisible )
1582       continue;
1583     if (!IsComponent)
1584       continue;
1585     Handle(StepShape_ShapeRepresentation) aSR;
1586     findStyledSR( style, aSR );
1587     // search for SR along model
1588     if ( aSR.IsNull() )
1589       continue;
1590     Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings( aSR );
1591     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
1592     for (subs.Start(); subs.More(); subs.Next()) {
1593       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
1594       if ( aSDR.IsNull() )
1595         continue;
1596       StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
1597       Handle(StepRepr_ProductDefinitionShape) PDS = 
1598         Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
1599       if ( PDS.IsNull() )
1600         continue;
1601       StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
1602       Handle(StepRepr_SpecifiedHigherUsageOccurrence) SHUO =
1603         Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(aCharDef.ProductDefinitionRelationship());
1604       if ( SHUO.IsNull() )
1605         continue;
1606       
1607       // set the SHUO structure to the document
1608       TDF_Label aLabelForStyle = setSHUOintoDoc( WS, SHUO, STool, PDFileMap, ShapeLabelMap );
1609       if ( aLabelForStyle.IsNull() ) {
1610 #ifdef OCCT_DEBUG
1611         cout << "Warning: " << __FILE__ <<": coudnot create SHUO structure in the document" << endl;
1612 #endif
1613         continue;
1614       }
1615       // now set the style to the SHUO main label.
1616       if ( ! SurfCol.IsNull() ) {
1617         Quantity_Color col;
1618         Styles.DecodeColor ( SurfCol, col );
1619         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorSurf );
1620       }
1621       if ( ! BoundCol.IsNull() ) {
1622         Quantity_Color col;
1623         Styles.DecodeColor ( BoundCol, col );
1624         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorCurv );
1625       }
1626       if ( ! CurveCol.IsNull() ) {
1627         Quantity_Color col;
1628         Styles.DecodeColor ( CurveCol, col );
1629         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorCurv );
1630       }
1631       if ( !IsVisible )
1632         // sets the invisibility for shape.
1633         CTool->SetVisibility( aLabelForStyle, Standard_False );
1634       
1635     } // end search SHUO by SDR
1636   } // end iterates on styles
1637       
1638   return Standard_True;
1639 }
1640
1641
1642 //=======================================================================
1643 //function : GetLengthConversionFactor
1644 //purpose  : 
1645 //=======================================================================
1646 static Standard_Boolean GetLengthConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1647                                                   Standard_Real& afact)
1648 {
1649   afact=1.;
1650   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndLengthUnit)) ) return Standard_False;
1651   Handle(StepBasic_ConversionBasedUnitAndLengthUnit) CBULU =
1652     Handle(StepBasic_ConversionBasedUnitAndLengthUnit)::DownCast(NU);
1653   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBULU->ConversionFactor();
1654   afact = MWUCBU->ValueComponent();
1655   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1656   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1657     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1658     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1659       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1660       if(SU->Name()==StepBasic_sunMetre) {
1661         if(SU->HasPrefix()) 
1662           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1663         // convert m to mm
1664         afact *= 1000.;
1665       }
1666     }
1667   }
1668   return Standard_True;
1669 }
1670
1671
1672 //=======================================================================
1673 //function : GetAngleConversionFactor
1674 //purpose  : 
1675 //=======================================================================
1676 static Standard_Boolean GetAngleConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1677                                                   Standard_Real& afact)
1678 {
1679   afact=1.;
1680   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndPlaneAngleUnit)) ) return Standard_False;
1681   Handle(StepBasic_ConversionBasedUnitAndPlaneAngleUnit) CBULU =
1682     Handle(StepBasic_ConversionBasedUnitAndPlaneAngleUnit)::DownCast(NU);
1683   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBULU->ConversionFactor();
1684   afact = MWUCBU->ValueComponent();
1685   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1686   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1687     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1688     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1689       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1690       if(SU->Name()==StepBasic_sunRadian) {
1691         if(SU->HasPrefix()) 
1692           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1693         // convert radian to deg
1694         afact *= 180/M_PI;
1695       }
1696     }
1697   }
1698   return Standard_True;
1699 }
1700
1701 //=======================================================================
1702 //function : GetMassConversionFactor
1703 //purpose  : 
1704 //=======================================================================
1705 static Standard_Boolean GetMassConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1706                                                 Standard_Real& afact)
1707 {
1708   afact=1.;
1709   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndMassUnit)) ) return Standard_False;
1710   Handle(StepBasic_ConversionBasedUnitAndMassUnit) CBUMU =
1711     Handle(StepBasic_ConversionBasedUnitAndMassUnit)::DownCast(NU);
1712   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBUMU->ConversionFactor();
1713   afact = MWUCBU->ValueComponent();
1714   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1715   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1716     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1717     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1718       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1719       if(SU->Name()==StepBasic_sunGram) {
1720         if(SU->HasPrefix())
1721           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1722       }
1723     }
1724   }
1725   return Standard_True;
1726 }
1727
1728 //=======================================================================
1729 //function : readAnnotation
1730 //purpose  : return annotation plane and position for given GDT
1731 // (Dimension, Geometric_Tolerance, Datum_Feature or Placed_Datum_Target_Feature)
1732 //=======================================================================
1733 void readAnnotation(const Handle(XSControl_TransferReader)& theTR, 
1734   const Handle(Standard_Transient) theGDT,
1735   const Handle(Standard_Transient)& theDimObject)
1736 {
1737   Handle(TCollection_HAsciiString) aPresentName;
1738   TopoDS_Compound aResAnnotation;
1739   Handle(Transfer_TransientProcess) aTP = theTR->TransientProcess();
1740   const Interface_Graph& aGraph = aTP->Graph();
1741   // find the proper DraughtingModelItemAssociation
1742   Interface_EntityIterator subs = aGraph.Sharings(theGDT);
1743   Handle(StepAP242_DraughtingModelItemAssociation) aDMIA;
1744   for (subs.Start(); subs.More() && aDMIA.IsNull(); subs.Next()) {
1745     if (!subs.Value()->IsKind(STANDARD_TYPE(StepAP242_DraughtingModelItemAssociation)))
1746       continue;
1747     aDMIA = Handle(StepAP242_DraughtingModelItemAssociation)::DownCast(subs.Value());
1748     Handle(TCollection_HAsciiString) aName = aDMIA->Name();
1749     aName->LowerCase();
1750     if (!aName->Search(new TCollection_HAsciiString("pmi representation to presentation link"))) {
1751       aDMIA = NULL;
1752     }
1753   }
1754   if (aDMIA.IsNull() || aDMIA->NbIdentifiedItem() == 0)
1755     return;
1756
1757   // retrieve AnnotationPlane
1758   Standard_Boolean isHasPlane = Standard_False;
1759   gp_Ax2 aPlaneAxes;
1760   Handle(StepRepr_RepresentationItem) aDMIAE = aDMIA->IdentifiedItemValue(1);
1761   if (aDMIAE.IsNull())
1762     return;
1763   subs = aGraph.Sharings(aDMIAE);
1764   Handle(StepVisual_AnnotationPlane) anAnPlane;
1765   for (subs.Start(); subs.More() && anAnPlane.IsNull(); subs.Next()) {
1766     anAnPlane = Handle(StepVisual_AnnotationPlane)::DownCast(subs.Value());
1767   }
1768   if (!anAnPlane.IsNull()) {
1769     Handle(StepRepr_RepresentationItem) aPlaneItem = anAnPlane->Item();
1770     Handle(StepGeom_Axis2Placement3d) aA2P3D;
1771     //retrieve axes from AnnotationPlane
1772     if (aPlaneItem->IsKind(STANDARD_TYPE(StepGeom_Plane))) {
1773       Handle(StepGeom_Plane) aPlane = Handle(StepGeom_Plane)::DownCast(aPlaneItem);
1774       aA2P3D = aPlane->Position();
1775     }
1776     else if (aPlaneItem->IsKind(STANDARD_TYPE(StepVisual_PlanarBox))) {
1777       Handle(StepVisual_PlanarBox) aBox = Handle(StepVisual_PlanarBox)::DownCast(aPlaneItem);
1778       aA2P3D = aBox->Placement().Axis2Placement3d();
1779     }
1780     // build gp_Ax2 from axes
1781     if (!aA2P3D.IsNull())
1782     {
1783       Handle(StepGeom_Direction) anAxis = aA2P3D->Axis(), 
1784         aRefDir = aA2P3D->RefDirection();
1785       if (!anAxis.IsNull() && !aRefDir.IsNull()) {
1786         Handle(TColStd_HArray1OfReal) aCoords;
1787         aCoords = anAxis->DirectionRatios();
1788         gp_Dir aXDir(aCoords->Value(1), aCoords->Value(2), aCoords->Value(3));
1789         aCoords = aRefDir->DirectionRatios();
1790         gp_Dir aYDir(aCoords->Value(1), aCoords->Value(2), aCoords->Value(3));
1791         aPlaneAxes.SetDirection(aXDir.Crossed(aYDir));
1792         aPlaneAxes.SetYDirection(aYDir);
1793         //set location of the annotation plane
1794         Handle(TColStd_HArray1OfReal) aLocCoords;
1795         Handle(StepGeom_CartesianPoint) aLoc = aA2P3D->Location();
1796         gp_Pnt aLocPos( aLoc->CoordinatesValue (1), aLoc->CoordinatesValue (2), aLoc->CoordinatesValue (3));
1797         aPlaneAxes.SetLocation(aLocPos);
1798         isHasPlane = Standard_True;
1799       }
1800     }
1801   }
1802
1803   // set plane axes to XCAF
1804   if (isHasPlane) {
1805     if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DimensionObject))) {
1806       Handle(XCAFDimTolObjects_DimensionObject) anObj = 
1807         Handle(XCAFDimTolObjects_DimensionObject)::DownCast(theDimObject);
1808       Handle(TColgp_HArray1OfPnt) aPnts = new TColgp_HArray1OfPnt(1, 1);
1809       anObj->SetPlane(aPlaneAxes);
1810     }
1811     else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DatumObject))) {
1812       Handle(XCAFDimTolObjects_DatumObject) anObj =
1813         Handle(XCAFDimTolObjects_DatumObject)::DownCast(theDimObject);
1814       anObj->SetPlane(aPlaneAxes);
1815     }
1816     else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_GeomToleranceObject))) {
1817       Handle(XCAFDimTolObjects_GeomToleranceObject) anObj =
1818         Handle(XCAFDimTolObjects_GeomToleranceObject)::DownCast(theDimObject);
1819       anObj->SetPlane(aPlaneAxes);
1820     }
1821   }
1822
1823   // Retrieve presentation
1824   Handle(StepVisual_AnnotationCurveOccurrence) anACO;
1825   NCollection_Vector<Handle(StepVisual_TessellatedAnnotationOccurrence)> aTesselations;
1826   NCollection_Vector<Handle(StepVisual_StyledItem)> anAnnotations;
1827   if (aDMIAE->IsKind(STANDARD_TYPE(StepVisual_AnnotationCurveOccurrence))) 
1828   {
1829     anACO = Handle(StepVisual_AnnotationCurveOccurrence)::DownCast(aDMIAE);
1830     if( !anACO.IsNull())
1831       anAnnotations.Append(anACO);
1832   }
1833
1834   else if (aDMIAE->IsKind(STANDARD_TYPE(StepVisual_DraughtingCallout))) 
1835   {
1836     Handle(StepVisual_DraughtingCallout) aDCallout =
1837       Handle(StepVisual_DraughtingCallout)::DownCast(aDMIAE);
1838     for (Standard_Integer i = 1; i <= aDCallout->NbContents() && anACO.IsNull(); i++) {
1839       anACO = aDCallout->ContentsValue(i).AnnotationCurveOccurrence();
1840       if(!anACO.IsNull())
1841       {
1842         anAnnotations.Append(anACO);
1843         continue;
1844       }
1845       Handle(StepVisual_TessellatedAnnotationOccurrence) aTesselation = 
1846         aDCallout->ContentsValue(i).TessellatedAnnotationOccurrence();
1847       if( !aTesselation.IsNull())
1848         anAnnotations.Append(aTesselation);
1849     }
1850   }
1851
1852   if (!anAnnotations.Length())
1853     return;
1854
1855
1856   BRep_Builder aB;
1857   aB.MakeCompound(aResAnnotation);
1858
1859   Standard_Integer i =0;
1860   Bnd_Box aBox;
1861   Standard_Integer nbShapes =0;
1862   for( ; i < anAnnotations.Length(); i++)
1863   {
1864     Handle(StepVisual_StyledItem) anItem = anAnnotations(i);
1865   
1866     aPresentName = anItem->Name();
1867
1868     anACO = Handle(StepVisual_AnnotationCurveOccurrence)::DownCast(anItem);
1869     TopoDS_Shape anAnnotationShape;
1870     if(!anACO.IsNull())
1871     {
1872       Handle(StepRepr_RepresentationItem) aCurveItem = anACO->Item();
1873       anAnnotationShape = STEPConstruct::FindShape (aTP,aCurveItem);
1874       if( anAnnotationShape.IsNull())
1875       {
1876         Handle(Transfer_Binder) binder = theTR->Actor()->Transfer(aCurveItem, aTP);
1877         if ( ! binder.IsNull() && binder->HasResult() ) {
1878           anAnnotationShape = TransferBRep::ShapeResult ( aTP, binder );
1879         }
1880       }
1881     }
1882     //case of tesselated entities
1883     else
1884     {
1885       Handle(StepRepr_RepresentationItem) aTessItem = anItem->Item();
1886       if(aTessItem.IsNull())
1887         continue;
1888       Handle(StepVisual_TessellatedGeometricSet) aTessSet = Handle(StepVisual_TessellatedGeometricSet)::DownCast(aTessItem);
1889       if( aTessSet.IsNull())
1890         continue;
1891       NCollection_Handle<StepVisual_Array1OfTessellatedItem> aListItems = aTessSet->Items();
1892       Standard_Integer nb = aListItems.IsNull() ? 0 : aListItems->Length();
1893       Handle(StepVisual_TessellatedCurveSet) aTessCurve;
1894       for (Standard_Integer n = 1; n <= nb && aTessCurve.IsNull(); n++)
1895       {
1896         aTessCurve = Handle(StepVisual_TessellatedCurveSet)::DownCast(aListItems->Value(n));
1897       }
1898       if( aTessCurve.IsNull())
1899         continue;
1900       Handle(StepVisual_CoordinatesList) aCoordList = aTessCurve->CoordList();
1901       if( aCoordList.IsNull())
1902         continue;
1903       Handle(TColgp_HArray1OfXYZ)  aPoints = aCoordList->Points();
1904
1905       if (aPoints.IsNull() || aPoints->Length() == 0)
1906         continue;
1907       NCollection_Handle<StepVisual_VectorOfHSequenceOfInteger> aCurves = aTessCurve->Curves();
1908       Standard_Integer aNbC = (aCurves.IsNull() ? 0 : aCurves->Length());
1909       TopoDS_Compound aComp;
1910       aB.MakeCompound(aComp);
1911       
1912       Standard_Integer k = 0;
1913       for( ; k < aNbC; k++)
1914       {
1915         Handle(TColStd_HSequenceOfInteger) anIndexes = aCurves->Value(k);
1916         TopoDS_Wire aCurW;
1917         aB.MakeWire(aCurW);
1918
1919         for(Standard_Integer n = 1; n < anIndexes->Length(); n++)
1920         {
1921           Standard_Integer ind = anIndexes->Value(n);
1922           Standard_Integer indnext = anIndexes->Value(n + 1);
1923           if( ind > aPoints->Length() || indnext > aPoints->Length())
1924             continue;
1925           gp_Pnt aP1(aPoints->Value(ind));
1926           gp_Pnt aP2(aPoints->Value(indnext));
1927           BRepBuilderAPI_MakeEdge aMaker(aP1, aP2);
1928           if( aMaker.IsDone())
1929           {
1930             TopoDS_Edge aCurE = aMaker.Edge();
1931             aB.Add(aCurW, aCurE);
1932           }
1933         }
1934         aB.Add(aComp, aCurW);
1935       }
1936       anAnnotationShape = aComp;
1937     }
1938     if(!anAnnotationShape.IsNull())
1939     {
1940       nbShapes++;
1941       aB.Add(aResAnnotation, anAnnotationShape);
1942       if( i == anAnnotations.Length() - 1)
1943         BRepBndLib::AddClose(anAnnotationShape, aBox);
1944     }
1945   }
1946   
1947   if(!nbShapes)
1948     return;
1949   gp_Pnt aPtext(0., 0., 0.);
1950   // if Annotation plane location inside bounding box set it to text position
1951   // else set the center of bounding box to text position
1952   if(!aBox.IsVoid())
1953   {
1954     Standard_Real aXmin, aYmin, aZmin,aXmax, aYmax, aZmax; 
1955     aBox.Get(aXmin, aYmin, aZmin,aXmax, aYmax, aZmax);
1956     if (isHasPlane && !aBox.IsOut(aPlaneAxes.Location())) {
1957       aPtext = aPlaneAxes.Location();
1958     }
1959     else {
1960       aPtext = gp_Pnt((aXmin + aXmax) * 0.5, (aYmin + aYmax) * 0.5, (aZmin + aZmax) * 0.5);
1961     }
1962   }
1963   else {
1964     aPtext = aPlaneAxes.Location();
1965   }
1966
1967   // set point to XCAF
1968   if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DimensionObject))) {
1969     Handle(XCAFDimTolObjects_DimensionObject) anObj = 
1970       Handle(XCAFDimTolObjects_DimensionObject)::DownCast(theDimObject);
1971     anObj->SetPointTextAttach(aPtext);
1972     anObj->SetPresentation(aResAnnotation, aPresentName);
1973   }
1974   else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DatumObject))) {
1975     Handle(XCAFDimTolObjects_DatumObject) anObj =
1976       Handle(XCAFDimTolObjects_DatumObject)::DownCast(theDimObject);
1977       anObj->SetPointTextAttach(aPtext);
1978       anObj->SetPresentation(aResAnnotation, aPresentName);
1979   }
1980   else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_GeomToleranceObject))) {
1981     Handle(XCAFDimTolObjects_GeomToleranceObject) anObj =
1982       Handle(XCAFDimTolObjects_GeomToleranceObject)::DownCast(theDimObject);
1983     anObj->SetPointTextAttach(aPtext);
1984     anObj->SetPresentation(aResAnnotation, aPresentName);
1985   }
1986   return;
1987 }
1988
1989 //=======================================================================
1990 //function : ReadDatums
1991 //purpose  : auxilary
1992 //=======================================================================
1993 static Standard_Boolean ReadDatums(const Handle(XCAFDoc_ShapeTool) &STool,
1994                                    const Handle(XCAFDoc_DimTolTool) &DGTTool,
1995                                    const Interface_Graph &graph,
1996                                    const Handle(Transfer_TransientProcess) &TP,
1997                                    const TDF_Label TolerL,
1998                                    const Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR)
1999 {
2000   if(GTWDR.IsNull()) return Standard_False;
2001   Handle(StepDimTol_HArray1OfDatumReference) HADR = GTWDR->DatumSystem();
2002   if(HADR.IsNull()) return Standard_False;
2003   for(Standard_Integer idr=1; idr<=HADR->Length(); idr++) {
2004     Handle(StepDimTol_DatumReference) DR = HADR->Value(idr);
2005     Handle(StepDimTol_Datum) aDatum = DR->ReferencedDatum();
2006     if(aDatum.IsNull()) continue;
2007     Interface_EntityIterator subs4 = graph.Sharings(aDatum);
2008     for(subs4.Start(); subs4.More(); subs4.Next()) {
2009       Handle(StepRepr_ShapeAspectRelationship) SAR = 
2010         Handle(StepRepr_ShapeAspectRelationship)::DownCast(subs4.Value());
2011       if(SAR.IsNull()) continue;
2012       Handle(StepDimTol_DatumFeature) DF = 
2013         Handle(StepDimTol_DatumFeature)::DownCast(SAR->RelatingShapeAspect());
2014       if(DF.IsNull()) continue;
2015       Interface_EntityIterator subs5 = graph.Sharings(DF);
2016       Handle(StepRepr_PropertyDefinition) PropDef;
2017       for(subs5.Start(); subs5.More() && PropDef.IsNull(); subs5.Next()) {
2018         PropDef = Handle(StepRepr_PropertyDefinition)::DownCast(subs5.Value());
2019       }
2020       if(PropDef.IsNull()) continue;
2021       Handle(StepShape_AdvancedFace) AF;
2022       subs5 = graph.Sharings(PropDef);
2023       for(subs5.Start(); subs5.More(); subs5.Next()) {
2024         Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
2025           Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs5.Value());
2026         if(!SDR.IsNull()) {
2027           Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
2028           if( !Repr.IsNull() && Repr->NbItems()>0 ) {
2029             Handle(StepRepr_RepresentationItem) RI = Repr->ItemsValue(1);
2030             AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
2031           }
2032         }
2033       }
2034       if(AF.IsNull()) return Standard_False;
2035       Standard_Integer index = TP->MapIndex(AF);
2036       TopoDS_Shape aSh;
2037       if(index >0) {
2038         Handle(Transfer_Binder) binder = TP->MapItem(index);
2039         aSh = TransferBRep::ShapeResult(binder);
2040       }
2041       if(aSh.IsNull()) continue; 
2042       TDF_Label shL;
2043       if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2044       DGTTool->SetDatum(shL,TolerL,PropDef->Name(),PropDef->Description(),aDatum->Identification());
2045     }
2046   }
2047   return Standard_True;
2048 }
2049
2050
2051 //=======================================================================
2052 //function : setDatumToXCAF
2053 //purpose  : 
2054 //=======================================================================
2055 static Standard_Boolean setDatumToXCAF(const Handle(StepDimTol_Datum)& theDat,
2056                                         const TDF_Label theGDTL,
2057                                         const Standard_Integer thePositionCounter,
2058                                         const XCAFDimTolObjects_DatumModifiersSequence& aXCAFModifiers,
2059                                         const XCAFDimTolObjects_DatumModifWithValue aXCAFModifWithVal,
2060                                         const Standard_Real aModifValue,
2061                                         const Handle(TDocStd_Document)& theDoc,
2062                                         const Handle(XSControl_WorkSession)& theWS)
2063 {
2064   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
2065   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
2066   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
2067   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
2068   const Interface_Graph& aGraph = aTP->Graph();
2069   Handle(XCAFDoc_Datum) aDat;
2070   TDF_Label aShL;
2071   Standard_Boolean aRefShapeIsFound = Standard_False;
2072   Standard_Boolean aFirstStep = Standard_True;
2073   Interface_EntityIterator anIterD = aGraph.Sharings(theDat);
2074   for(anIterD.Start(); anIterD.More(); anIterD.Next()) {
2075     Handle(StepRepr_ShapeAspectRelationship) aSAR = 
2076       Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIterD.Value());
2077     if(aSAR.IsNull()) continue;
2078
2079     Handle(StepRepr_ShapeAspect) aSA = aSAR->RelatingShapeAspect();
2080     if (aSA.IsNull()) continue;
2081     Handle(StepAP242_GeometricItemSpecificUsage) aPGISU;
2082     if(aSA->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp)))
2083     {
2084       //processing for complex entity
2085       Interface_EntityIterator anIterC = aGraph.Sharings(aSA);
2086       for(anIterC.Start(); anIterC.More(); anIterC.Next()) {
2087         Handle(StepRepr_ShapeAspectRelationship) SAR = 
2088           Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIterC.Value());
2089         if(SAR.IsNull()) continue;
2090         Handle(StepRepr_ShapeAspect) aS = SAR->RelatedShapeAspect();
2091         if(aS.IsNull()) continue;
2092         Interface_EntityIterator anIterSA = aGraph.Sharings(aS);
2093         for(anIterSA.Start(); anIterSA.More() && aPGISU.IsNull(); anIterSA.Next()) {
2094           aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterSA.Value());
2095         }
2096         if(!aPGISU.IsNull()){
2097           aSA = aS;
2098           break;
2099         }
2100       }
2101     }
2102     else if(aSA->IsKind(STANDARD_TYPE(StepDimTol_PlacedDatumTargetFeature)))
2103     {
2104       //processing for datum target
2105       Interface_EntityIterator anIterDTF = aGraph.Sharings(aSA);
2106       for(anIterDTF.Start(); anIterDTF.More(); anIterDTF.Next()) {
2107         if(anIterDTF.Value()->IsKind(STANDARD_TYPE(StepRepr_FeatureForDatumTargetRelationship)))
2108         {
2109           Handle(StepRepr_FeatureForDatumTargetRelationship) aFFDTR =
2110             Handle(StepRepr_FeatureForDatumTargetRelationship)::DownCast(anIterDTF.Value());
2111           Handle(StepRepr_ShapeAspect) aTmpSA = aFFDTR->RelatedShapeAspect();
2112           Interface_EntityIterator anIterDSWP = aGraph.Sharings(aTmpSA);
2113           for(anIterDSWP.Start(); anIterDSWP.More() && aPGISU.IsNull(); anIterDSWP.Next()) {
2114             aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
2115     }
2116         }
2117       }
2118     }
2119     if (aSA.IsNull()) continue;
2120     Interface_EntityIterator anIterDSWP = aGraph.Sharings(aSA);
2121     for(anIterDSWP.Start(); anIterDSWP.More() && aPGISU.IsNull(); anIterDSWP.Next()) {
2122       aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
2123     }
2124     if(aPGISU.IsNull()) continue;
2125     // get representation item
2126     Handle(StepRepr_RepresentationItem) aRI;
2127     for(Standard_Integer i = 1 ; i <= aPGISU->NbIdentifiedItem() && aRI.IsNull(); i++)
2128     {
2129       aRI = aPGISU->IdentifiedItemValue(i);
2130     }
2131     if(aRI.IsNull()) continue;
2132     Standard_Integer index = aTP->MapIndex(aRI);
2133     TopoDS_Shape aSh;
2134     if(index >0) {
2135       Handle(Transfer_Binder) binder = aTP->MapItem(index);
2136       aSh = TransferBRep::ShapeResult(binder);
2137     }
2138     if(aSh.IsNull()) continue; 
2139     if( !aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True) ) continue;
2140     Handle(TDataStd_TreeNode) aNode;
2141     if(aFirstStep && aShL.FindAttribute(XCAFDoc::DatumRefGUID(),aNode) && aNode->HasFirst() &&
2142        aNode->First()->Label().FindAttribute(XCAFDoc_Datum::GetID(),aDat))
2143     {
2144       //if datums already attached, not need add datum target
2145       aRefShapeIsFound = Standard_True;
2146     }
2147     aFirstStep = Standard_False;
2148     Handle(XCAFDimTolObjects_DatumObject) aDatObj;
2149     if(aSA->IsKind(STANDARD_TYPE(StepDimTol_PlacedDatumTargetFeature)))
2150     {
2151       if(!aRefShapeIsFound)
2152       {
2153         //if datum targers not yet added
2154         TDF_Label aDatL = aDGTTool->AddDatum();
2155         aDat = XCAFDoc_Datum::Set(aDatL);
2156         aDGTTool->SetDatum(aShL, aDatL);
2157         aDatObj = aDat->GetObject();
2158         aDatObj->SetName(theDat->Identification());
2159         aDatObj->SetPosition (thePositionCounter);
2160         if(!aXCAFModifiers.IsEmpty())
2161           aDatObj->SetModifiers(aXCAFModifiers);
2162         if (aXCAFModifWithVal != XCAFDimTolObjects_DatumModifWithValue_None) 
2163           aDatObj->SetModifierWithValue(aXCAFModifWithVal, aModifValue);
2164         aDGTTool->SetDatumToGeomTol(aDatL, theGDTL);
2165         Handle(StepDimTol_PlacedDatumTargetFeature) aPDTF = Handle(StepDimTol_PlacedDatumTargetFeature)::DownCast(aSA);
2166         if (aPDTF->TargetId()->IsIntegerValue())
2167           aDatObj->SetDatumTargetNumber(aPDTF->TargetId()->IntegerValue());
2168         else
2169           aDatObj->SetDatumTargetNumber(0);
2170         aDatObj->IsDatumTarget(Standard_True);
2171         XCAFDimTolObjects_DatumTargetType aType;
2172         if(STEPCAFControl_GDTProperty::GetDatumTargetType(aSA->Description(),aType))
2173         {
2174           aDatObj->SetDatumTargetType(aType);
2175           if(aType == XCAFDimTolObjects_DatumTargetType_Area)
2176           {
2177             Interface_EntityIterator anIterDTF = aGraph.Shareds(aSA);
2178             for(anIterDTF.Start(); anIterDTF.More(); anIterDTF.Next()) {
2179               if(anIterDTF.Value()->IsKind(STANDARD_TYPE(StepAP242_GeometricItemSpecificUsage)))
2180               {
2181                 Handle(StepAP242_GeometricItemSpecificUsage) aGISU
2182                   = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
2183                 Handle(StepRepr_RepresentationItem) anItem;
2184                 if(aPGISU->NbIdentifiedItem() > 0) {
2185                   anItem = aPGISU->IdentifiedItemValue(1);
2186                 }
2187                 if(anItem.IsNull()) continue;
2188                 Standard_Integer anItemIndex = aTP->MapIndex(anItem);
2189                 if(anItemIndex >0) {
2190                   Handle(Transfer_Binder) binder = aTP->MapItem(anItemIndex);
2191                   TopoDS_Shape anItemShape = TransferBRep::ShapeResult(binder);
2192                   aDatObj->SetDatumTarget(anItemShape);
2193                 }
2194               }
2195             }
2196           }
2197           else
2198           {
2199             Interface_EntityIterator anIterDTF = aGraph.Shareds(aSA);
2200             for(anIterDTF.Start(); anIterDTF.More(); anIterDTF.Next()) {
2201               if(anIterDTF.Value()->IsKind(STANDARD_TYPE(StepRepr_PropertyDefinition)))
2202               {
2203                 Interface_EntityIterator anIterPD = aGraph.Shareds(anIterDTF.Value());
2204                 for(anIterPD.Start(); anIterPD.More(); anIterPD.Next()) {
2205                   if(anIterPD.Value()->IsKind(STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation)))
2206                   {
2207                     Interface_EntityIterator anIterSDR = aGraph.Sharings(anIterPD.Value());
2208                     for(anIterSDR.Start(); anIterSDR.More(); anIterSDR.Next()) {
2209                       if(anIterSDR.Value()->IsKind(STANDARD_TYPE(StepShape_ShapeRepresentationWithParameters)))
2210                       {
2211                         Handle(StepShape_ShapeRepresentationWithParameters) aSRWP
2212                           = Handle(StepShape_ShapeRepresentationWithParameters)::DownCast(anIterSDR.Value());
2213                         for(Standard_Integer r = aSRWP->Items()->Lower(); r <= aSRWP->Items()->Upper(); r++)
2214                         {
2215                           if(aSRWP->ItemsValue(r)->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
2216                           {
2217                             Handle(StepGeom_Axis2Placement3d) anAx
2218                               = Handle(StepGeom_Axis2Placement3d)::DownCast(aSRWP->ItemsValue(r));
2219                             Handle(TColStd_HArray1OfReal) aDirArr = anAx->Axis()->DirectionRatios();
2220                             Handle(TColStd_HArray1OfReal) aDirRArr = anAx->RefDirection()->DirectionRatios();
2221                             Handle(TColStd_HArray1OfReal) aLocArr = anAx->Location()->Coordinates();
2222                             gp_Dir aDir;
2223                             gp_Dir aDirR;
2224                             gp_Pnt aPnt;
2225                             if(!aDirArr.IsNull() && aDirArr->Length() > 2 &&
2226                               !aDirRArr.IsNull() && aDirRArr->Length() > 2 && 
2227                               !aLocArr.IsNull() && aLocArr->Length() > 2)
2228                             {
2229                               aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, aDirArr->Lower()+2);
2230                               aDirR.SetCoord(aDirRArr->Lower(), aDirRArr->Lower()+1, aDirRArr->Lower()+2);
2231                               aPnt.SetCoord(aLocArr->Lower(), aLocArr->Lower()+1, aLocArr->Lower()+2);
2232                               gp_Ax2 anA(aPnt, aDir, aDirR);
2233                               aDatObj->SetDatumTargetAxis(anA);
2234                             }
2235                           }
2236                           else if(aSRWP->ItemsValue(r)->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit)))
2237                           {
2238                             Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) aM =
2239                               Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(aSRWP->ItemsValue(r)); 
2240                             Standard_Real aVal = aM->GetMeasureWithUnit()->ValueComponent();
2241                             StepBasic_Unit anUnit = aM->GetMeasureWithUnit()->UnitComponent();
2242                             Standard_Real aFact=1.;
2243                             if(anUnit.IsNull()) continue;
2244                             if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2245                             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2246                             if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2247                             if(aM->Name()->String().IsEqual("target length") ||
2248                               aM->Name()->String().IsEqual("target diameter"))
2249                               aDatObj->SetDatumTargetLength(aVal);
2250                             else
2251                               aDatObj->SetDatumTargetWidth(aVal);
2252                           }
2253                         }
2254                       }
2255                     }
2256                   }
2257                 }
2258               }
2259             }
2260           }
2261         }
2262       }
2263     }
2264     else
2265     {
2266       //processing for darum feature
2267       TDF_Label aDatL = aDGTTool->AddDatum();
2268       aDat = XCAFDoc_Datum::Set(aDatL);
2269       aDGTTool->SetDatum(aShL, aDatL);
2270       aDatObj = aDat->GetObject();
2271       aDatObj->SetName(theDat->Identification());
2272       aDatObj->SetPosition (thePositionCounter);
2273       if(!aXCAFModifiers.IsEmpty())
2274         aDatObj->SetModifiers(aXCAFModifiers);
2275       if (aXCAFModifWithVal != XCAFDimTolObjects_DatumModifWithValue_None) 
2276         aDatObj->SetModifierWithValue(aXCAFModifWithVal, aModifValue);
2277       aDGTTool->SetDatumToGeomTol(aDatL, theGDTL);
2278     }
2279     if(!aDatObj.IsNull()) {
2280       readAnnotation(aTR, aSAR->RelatingShapeAspect(), aDatObj);
2281       aDat->SetObject(aDatObj);
2282     }
2283   }
2284   return !aDat.IsNull();
2285 }
2286
2287
2288 //=======================================================================
2289 //function : ReadDatums
2290 //purpose  : auxilary
2291 //=======================================================================
2292 static Standard_Boolean readDatumsAP242(const Handle(Standard_Transient)& theEnt,
2293                                         const TDF_Label theGDTL,
2294                                         const Handle(TDocStd_Document)& theDoc,
2295                                         const Handle(XSControl_WorkSession)& theWS)
2296 {
2297   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
2298   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
2299   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
2300   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
2301   const Interface_Graph& aGraph = aTP->Graph();
2302
2303   Interface_EntityIterator anIter = aGraph.Shareds(theEnt);
2304   for(anIter.Start(); anIter.More(); anIter.Next()) {
2305     Handle(Standard_Transient) anAtr = anIter.Value();
2306     if(anAtr->IsKind(STANDARD_TYPE(StepDimTol_DatumSystem)))
2307     {
2308       Standard_Integer aPositionCounter = 0;//position on frame 
2309       Handle(StepDimTol_DatumSystem) aDS = Handle(StepDimTol_DatumSystem)::DownCast(anAtr);
2310       Interface_EntityIterator anIterDS = aGraph.Sharings(aDS);
2311       for(anIterDS.Start(); anIterDS.More(); anIterDS.Next()) {
2312         Handle(Standard_Transient) anAtrDS = anIterDS.Value();
2313         if(anAtrDS->IsKind(STANDARD_TYPE(StepAP242_GeometricItemSpecificUsage)))
2314         {
2315           //get axis
2316           Handle(StepAP242_GeometricItemSpecificUsage)aAxGISUI
2317             = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anAtrDS);
2318           if (aAxGISUI->IdentifiedItemValue(1)->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
2319           {
2320             Handle(StepGeom_Axis2Placement3d) anAx
2321               = Handle(StepGeom_Axis2Placement3d)::DownCast(aAxGISUI->IdentifiedItemValue(1));
2322             Handle(XCAFDoc_GeomTolerance) aTol;
2323             if(theGDTL.FindAttribute(XCAFDoc_GeomTolerance::GetID(), aTol))
2324             {
2325               Handle(XCAFDimTolObjects_GeomToleranceObject) anObj = aTol->GetObject();
2326               Handle(TColStd_HArray1OfReal) aDirArr = anAx->Axis()->DirectionRatios();
2327               Handle(TColStd_HArray1OfReal) aDirRArr = anAx->RefDirection()->DirectionRatios();
2328               Handle(TColStd_HArray1OfReal) aLocArr = anAx->Location()->Coordinates();
2329               gp_Dir aDir;
2330               gp_Dir aDirR;
2331               gp_Pnt aPnt;
2332               if(!aDirArr.IsNull() && aDirArr->Length() > 2 &&
2333                 !aDirRArr.IsNull() && aDirRArr->Length() > 2 && 
2334                 !aLocArr.IsNull() && aLocArr->Length() > 2)
2335               {
2336                 aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, aDirArr->Lower()+2);
2337                 aDirR.SetCoord(aDirRArr->Lower(), aDirRArr->Lower()+1, aDirRArr->Lower()+2);
2338                 aPnt.SetCoord(aLocArr->Lower(), aLocArr->Lower()+1, aLocArr->Lower()+2);
2339                 gp_Ax2 anA(aPnt, aDir, aDirR);
2340                 anObj->SetAxis(anA);
2341                 aTol->SetObject(anObj);
2342               }
2343             }
2344           }
2345         }
2346       }
2347       if (aDS->NbConstituents() > 0)
2348       {
2349         //get datum feature and datum target from datum system
2350         Handle(StepDimTol_HArray1OfDatumReferenceCompartment) aDRCA = aDS->Constituents();
2351         if(!aDRCA.IsNull())
2352         {
2353           for(Standard_Integer i = aDRCA->Lower(); i <= aDRCA->Upper(); i++)
2354           {
2355             Handle(StepDimTol_DatumReferenceCompartment) aDRC = aDRCA->Value(i);
2356             //gete modifiers
2357             Handle(StepDimTol_HArray1OfDatumReferenceModifier) aModif = aDRC->Modifiers();
2358             XCAFDimTolObjects_DatumModifiersSequence aXCAFModifiers;
2359             XCAFDimTolObjects_DatumModifWithValue aXCAFModifWithVal = XCAFDimTolObjects_DatumModifWithValue_None;
2360             Standard_Real aModifValue = 0;
2361             if(!aModif.IsNull())
2362             {
2363               for(Standard_Integer m = aModif->Lower(); m <= aModif->Upper(); m++)
2364               {
2365                 if(aModif->Value(m).CaseNumber() == 2)
2366                   aXCAFModifiers.Append(
2367                   (XCAFDimTolObjects_DatumSingleModif)aModif->Value(m).
2368                   SimpleDatumReferenceModifierMember()->Value());
2369                 else if (aModif->Value(m).CaseNumber() == 1)
2370                 {
2371                   aXCAFModifWithVal = (XCAFDimTolObjects_DatumModifWithValue)(aModif->Value(m).DatumReferenceModifierWithValue()->ModifierType() + 1);
2372                   Standard_Real aVal = aModif->Value(m).DatumReferenceModifierWithValue()->ModifierValue()->ValueComponent();
2373                   StepBasic_Unit anUnit = aModif->Value(m).DatumReferenceModifierWithValue()->ModifierValue()->UnitComponent();
2374                   Standard_Real aFact=1.;
2375                   if(anUnit.IsNull()) continue;
2376                   if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2377                   Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2378                   if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2379                   aModifValue = aVal;
2380                 }
2381               }
2382             }
2383             aPositionCounter++;
2384             Interface_EntityIterator anIterDRC = aGraph.Shareds(aDRC);
2385             for(anIterDRC.Start(); anIterDRC.More(); anIterDRC.Next()) {
2386               
2387               if(anIterDRC.Value()->IsKind(STANDARD_TYPE(StepDimTol_Datum)))
2388               {
2389                 Handle(StepDimTol_Datum) aD = Handle(StepDimTol_Datum)::DownCast(anIterDRC.Value());
2390                 setDatumToXCAF(aD, theGDTL, aPositionCounter, aXCAFModifiers, aXCAFModifWithVal, aModifValue,theDoc, theWS);
2391               }
2392               else if(anIterDRC.Value()->IsKind(STANDARD_TYPE(StepDimTol_DatumReferenceElement)))
2393               {
2394                 Handle(StepDimTol_DatumReferenceElement) aDRE 
2395                   = Handle(StepDimTol_DatumReferenceElement)::DownCast(anIterDRC.Value());
2396                 //get modifiers from group of datums
2397                 Handle(StepDimTol_HArray1OfDatumReferenceModifier) aModifE = aDRE->Modifiers();
2398                 if(!aModifE.IsNull())
2399                 {
2400                   for(Standard_Integer k = aModifE->Lower(); k <= aModifE->Upper(); k++)
2401                   {
2402                     if(aModifE->Value(k).CaseNumber() == 1)
2403                       aXCAFModifiers.Append(
2404                       (XCAFDimTolObjects_DatumSingleModif)aModifE->Value(k).
2405                       SimpleDatumReferenceModifierMember()->Value());
2406                     else if (aModifE->Value(k).CaseNumber() == 2)
2407                     {
2408                       aXCAFModifWithVal = (XCAFDimTolObjects_DatumModifWithValue)(aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierType() + 1);
2409                       Standard_Real aVal = aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierValue()->ValueComponent();
2410                       StepBasic_Unit anUnit = aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierValue()->UnitComponent();
2411                       Standard_Real aFact=1.;
2412                       if(anUnit.IsNull()) continue;
2413                       if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2414                       Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2415                       if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2416                       aModifValue = aVal;
2417                     }
2418                   }
2419                 }
2420                 Interface_EntityIterator anIterDRE = aGraph.Shareds(aDRE);
2421                 for(anIterDRE.Start(); anIterDRE.More(); anIterDRE.Next()) {
2422                   if(anIterDRE.Value()->IsKind(STANDARD_TYPE(StepDimTol_Datum)))
2423                   {
2424                     Handle(StepDimTol_Datum) aD = Handle(StepDimTol_Datum)::DownCast(anIterDRE.Value());
2425                     setDatumToXCAF(aD, theGDTL, aPositionCounter, aXCAFModifiers, aXCAFModifWithVal, aModifValue,theDoc, theWS);
2426                   }
2427                 }
2428               }
2429             }
2430           }
2431         }
2432       }
2433     }
2434   }
2435   return Standard_True;
2436 }
2437
2438 //=======================================================================
2439 //function : craeteGeomTolObjectInXCAF
2440 //purpose  : 
2441 //=======================================================================
2442 static TDF_Label createGDTObjectInXCAF(const Handle(Standard_Transient)& theEnt,
2443                                                const Handle(TDocStd_Document)& theDoc,
2444                                                const Handle(XSControl_WorkSession)& theWS)
2445 {
2446   TDF_Label aGDTL;
2447   if(!theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) &&
2448      !theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) && 
2449      !theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
2450   {
2451     return aGDTL;
2452   }
2453
2454   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
2455   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
2456   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
2457   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
2458   const Interface_Graph& aGraph = aTP->Graph();
2459   Standard_Boolean isAllAround = Standard_False;
2460   Standard_Boolean isAllOver = Standard_False;
2461   
2462   // find RepresentationItem for current Ent
2463   NCollection_Sequence<Handle(Standard_Transient)> aSeqRI1, aSeqRI2;
2464
2465   Interface_EntityIterator anIter = aGraph.Shareds(theEnt);
2466   for(anIter.Start(); anIter.More(); anIter.Next()) {
2467     Handle(Standard_Transient) anAtr = anIter.Value();
2468     NCollection_Sequence<Handle(StepRepr_ShapeAspect)> aSAs;
2469     if(anAtr->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape)))
2470     {
2471       //if associating tolerances with part (All-Over)
2472       Interface_EntityIterator anIterSDR = aGraph.Sharings(anAtr);
2473       for(anIterSDR.Start(); anIterSDR.More(); anIterSDR.Next()) 
2474       {
2475         Handle(Standard_Transient) anAtrSDR = anIterSDR.Value();
2476         if(anAtrSDR->IsKind(STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation)))
2477         {
2478           isAllOver = Standard_True;
2479           Interface_EntityIterator anIterABSR = aGraph.Shareds(anAtrSDR);
2480           for(anIterABSR.Start(); anIterABSR.More(); anIterABSR.Next()) 
2481           {
2482             Handle(Standard_Transient) anAtrABSR = anIterABSR.Value();
2483             if(anAtrABSR->IsKind(STANDARD_TYPE(StepShape_AdvancedBrepShapeRepresentation)))
2484             {
2485               aSeqRI1.Append(anAtrABSR);
2486             }
2487           }
2488         }
2489       }
2490     }
2491     else if(anAtr->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) || 
2492       anAtr->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)))
2493     {
2494       //if tolerance attached to dimension
2495       Interface_EntityIterator anIterDim = aGraph.Shareds(anAtr);
2496       for(anIterDim.Start(); anIterDim.More(); anIterDim.Next()) 
2497       {
2498         Handle(Standard_Transient) anAtrDim = anIterDim.Value();
2499         if(anAtrDim->IsKind(STANDARD_TYPE(StepRepr_CompositeShapeAspect)) || 
2500           anAtrDim->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp)))
2501         {
2502           Interface_EntityIterator anIterCSA = aGraph.Sharings(anAtrDim);
2503           for(anIterCSA.Start(); anIterCSA.More(); anIterCSA.Next()) {
2504             if (anIterCSA.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspectRelationship))){
2505               Interface_EntityIterator anIterSAR = aGraph.Shareds(anIterCSA.Value());
2506               for(anIterSAR.Start(); anIterSAR.More(); anIterSAR.Next()) {
2507                 if (anIterSAR.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect))){
2508                   aSAs.Append(Handle(StepRepr_ShapeAspect)::DownCast(anIterSAR.Value()));
2509                 }
2510               }
2511             }
2512           }
2513         }
2514         else if(anAtrDim->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)))
2515         {
2516           aSAs.Append( Handle(StepRepr_ShapeAspect)::DownCast(anAtrDim));
2517         }
2518       }
2519     }
2520     else if(anAtr->IsKind(STANDARD_TYPE(StepRepr_CompositeShapeAspect)) || 
2521       anAtr->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp)))
2522     {
2523       //processing for composite entity
2524       Handle(Standard_Transient) anAtrTmp = anAtr;
2525       if(anAtr->IsKind(STANDARD_TYPE(StepRepr_AllAroundShapeAspect)))
2526       {
2527         // if applyed AllAround Modifier
2528         isAllAround = Standard_True;
2529         Interface_EntityIterator anIterAASA = aGraph.Sharings(anAtrTmp);
2530         for(anIterAASA.Start(); anIterAASA.More(); anIterAASA.Next()) {
2531           if (anIterAASA.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspectRelationship))){
2532             Interface_EntityIterator anIterSAR = aGraph.Shareds(anIterAASA.Value());
2533             for(anIterSAR.Start(); anIterSAR.More(); anIterSAR.Next()) {
2534               if ((anIterSAR.Value()->IsKind(STANDARD_TYPE(StepRepr_CompositeShapeAspect)) || 
2535                 anIterSAR.Value()->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp))) &&
2536                 anAtrTmp != anIterSAR.Value()){
2537                   anAtrTmp = anIterSAR.Value();
2538                   break;
2539               }
2540             }
2541           }
2542         }
2543       }
2544       Interface_EntityIterator anIterCSA = aGraph.Sharings(anAtrTmp);
2545       for(anIterCSA.Start(); anIterCSA.More(); anIterCSA.Next()) {
2546         if (anIterCSA.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspectRelationship))){
2547           Interface_EntityIterator anIterSAR = aGraph.Shareds(anIterCSA.Value());
2548           for(anIterSAR.Start(); anIterSAR.More(); anIterSAR.Next()) {
2549             if (anIterSAR.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect))){
2550               aSAs.Append(Handle(StepRepr_ShapeAspect)::DownCast(anIterSAR.Value()));
2551             }
2552           }
2553         }
2554       }
2555     }
2556     else if(anAtr->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)))
2557     {
2558       //default
2559       aSAs.Append( Handle(StepRepr_ShapeAspect)::DownCast(anAtr));
2560     }
2561     if(!aSAs.IsEmpty())
2562     {
2563       //get representation items
2564       NCollection_Sequence<Handle(Standard_Transient)> aSeqRI;
2565       for(Standard_Integer i = aSAs.Lower(); i <= aSAs.Upper(); i++)
2566       {
2567         Interface_EntityIterator anIterSA = aGraph.Sharings(aSAs.Value(i));
2568         Handle(StepAP242_GeometricItemSpecificUsage) aGISU;
2569         Handle(StepRepr_PropertyDefinition) PropD;
2570         for(anIterSA.Start(); anIterSA.More() && aGISU.IsNull() && PropD.IsNull(); anIterSA.Next()) {
2571           aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterSA.Value());
2572           PropD = Handle(StepRepr_PropertyDefinition)::DownCast(anIterSA.Value());
2573         }
2574         if(!PropD.IsNull())//for old version
2575         {
2576           Handle(StepRepr_RepresentationItem) RI;
2577           Interface_EntityIterator subs4 = aGraph.Sharings(PropD);
2578           for(subs4.Start(); subs4.More(); subs4.Next()) {
2579             Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
2580               Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs4.Value());
2581             if(!SDR.IsNull()) {
2582               Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
2583               if( !Repr.IsNull() && Repr->NbItems()>0 ) {
2584                 RI = Repr->ItemsValue(1);
2585               }
2586             }
2587           }
2588           if(RI.IsNull()) continue;
2589
2590           if(theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
2591             // read dimensions
2592             Handle(StepShape_EdgeCurve) EC = Handle(StepShape_EdgeCurve)::DownCast(RI);
2593             if(EC.IsNull()) continue;
2594             Handle(TCollection_HAsciiString) aName;
2595             Handle(StepShape_DimensionalSize) DimSize = 
2596               Handle(StepShape_DimensionalSize)::DownCast(theEnt);
2597             Standard_Real dim1=-1.,dim2=-1.;
2598             subs4 = aGraph.Sharings(DimSize);
2599             for(subs4.Start(); subs4.More(); subs4.Next()) {
2600               Handle(StepShape_DimensionalCharacteristicRepresentation) DimCharR = 
2601                 Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(subs4.Value());
2602               if(!DimCharR.IsNull()) {
2603                 Handle(StepShape_ShapeDimensionRepresentation) SDimR = DimCharR->Representation();
2604                 if(!SDimR.IsNull() && SDimR->NbItems()>0) {
2605                   Handle(StepRepr_RepresentationItem) anItem = SDimR->ItemsValue(1);
2606                   Handle(StepRepr_ValueRange) VR = Handle(StepRepr_ValueRange)::DownCast(anItem);
2607                   if(!VR.IsNull()) {
2608                     aName = VR->Name();
2609                     //StepRepr_CompoundItemDefinition CID = VR->ItemElement();
2610                     //if(CID.IsNull()) continue;
2611                     //Handle(StepRepr_CompoundItemDefinitionMember) CIDM = 
2612                     //  Handle(StepRepr_CompoundItemDefinitionMember)::DownCast(CID.Value());
2613                     //if(CIDM.IsNull()) continue;
2614                     //if(CIDM->ArrTransient().IsNull()) continue;
2615                     //Handle(StepRepr_HArray1OfRepresentationItem) HARI;
2616                     //if(CID.CaseMem(CIDM)==1)
2617                     //  HARI = CID.ListRepresentationItem();
2618                     //if(CID.CaseMem(CIDM)==2)
2619                     //  HARI = CID.SetRepresentationItem();
2620                     Handle(StepRepr_HArray1OfRepresentationItem) HARI = VR->ItemElement();
2621                     if(HARI.IsNull()) continue;
2622                     if(HARI->Length()>0) {
2623                       Handle(StepRepr_RepresentationItem) RI1 = HARI->Value(1);
2624                       if(RI1.IsNull()) continue;
2625                       if(RI1->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2626                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
2627                           Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI1);
2628                         dim1 = RILMWU->GetMeasureWithUnit()->ValueComponent();
2629                         StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
2630                         Standard_Real afact=1.;
2631                         if(anUnit.IsNull()) continue;
2632                         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2633                         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2634                         if(GetLengthConversionFactor(NU,afact)) dim1=dim1*afact;
2635                       }
2636                     }
2637                     if(HARI->Length()>1) {
2638                       Handle(StepRepr_RepresentationItem) RI2 = HARI->Value(2);
2639                       if(RI2.IsNull()) continue;
2640                       if(RI2->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2641                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
2642                           Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI2);
2643                         dim2 = RILMWU->GetMeasureWithUnit()->ValueComponent();
2644                         StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
2645                         Standard_Real afact=1.;
2646                         if(anUnit.IsNull()) continue;
2647                         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2648                         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2649                         if(GetLengthConversionFactor(NU,afact)) dim2 = dim2*afact;
2650                       }
2651                     }
2652                   }
2653                 }
2654               }
2655             }
2656             if(dim1<0) continue;
2657             if(dim2<0) dim2=dim1;
2658             //cout<<"DimensionalSize: dim1="<<dim1<<"  dim2="<<dim2<<endl;
2659             // now we know edge_curve and value range therefore
2660             // we can create corresponding D&GT labels
2661             Standard_Integer index = aTP->MapIndex(EC);
2662             TopoDS_Shape aSh;
2663             if(index >0) {
2664               Handle(Transfer_Binder) binder = aTP->MapItem(index);
2665               aSh = TransferBRep::ShapeResult(binder);
2666             }
2667             if(aSh.IsNull()) continue; 
2668             TDF_Label shL;
2669             if( !aSTool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2670             Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1,2);
2671             arr->SetValue(1,dim1);
2672             arr->SetValue(2,dim2);
2673             aDGTTool->SetDimTol(shL,1,arr,aName,DimSize->Name());
2674           }
2675           // read tolerances and datums
2676           else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
2677             Handle(StepDimTol_GeometricTolerance) GT =
2678               Handle(StepDimTol_GeometricTolerance)::DownCast(theEnt);
2679             // read common data for tolerance
2680             //Standard_Real dim = GT->Magnitude()->ValueComponent();
2681             Handle (StepBasic_MeasureWithUnit) dim3 = GT->Magnitude();
2682             if(dim3.IsNull()) continue;
2683             Standard_Real dim = dim3->ValueComponent();
2684             StepBasic_Unit anUnit = GT->Magnitude()->UnitComponent();
2685             Standard_Real afact=1.;
2686             if(anUnit.IsNull()) continue;
2687             if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2688             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2689             if(GetLengthConversionFactor(NU,afact)) dim = dim*afact;
2690             //cout<<"GeometricTolerance: Magnitude = "<<dim<<endl;
2691             Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1,1);
2692             arr->SetValue(1,dim);
2693             Handle(TCollection_HAsciiString) aName = GT->Name();
2694             Handle(TCollection_HAsciiString) aDescription = GT->Description();
2695             Handle(StepShape_AdvancedFace) AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
2696             if(AF.IsNull()) continue;
2697             Standard_Integer index = aTP->MapIndex(AF);
2698             TopoDS_Shape aSh;
2699             if(index >0) {
2700               Handle(Transfer_Binder) binder = aTP->MapItem(index);
2701               aSh = TransferBRep::ShapeResult(binder);
2702             }
2703             if(aSh.IsNull()) continue; 
2704             TDF_Label shL;
2705             if( !aSTool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2706             // read specific data for tolerance
2707             if(GT->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol))) {
2708               Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol) GTComplex =
2709                 Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol)::DownCast(theEnt);
2710               Standard_Integer kind=20;
2711               Handle(StepDimTol_ModifiedGeometricTolerance) MGT = 
2712                 GTComplex->GetModifiedGeometricTolerance();
2713               if(!MGT.IsNull()) {
2714                 kind = kind + MGT->Modifier()+1;
2715               }
2716               TDF_Label TolerL = aDGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
2717               // translate datums connected with this tolerance
2718               Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
2719                 GTComplex->GetGeometricToleranceWithDatumReference();
2720               if(!GTWDR.IsNull()) {
2721                 ReadDatums(aSTool,aDGTTool,aGraph,aTP,TolerL,GTWDR);
2722               }
2723             }
2724             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithDatumReference))) {
2725               Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
2726                 Handle(StepDimTol_GeometricToleranceWithDatumReference)::DownCast(theEnt);
2727               if(GTWDR.IsNull()) continue;
2728               Standard_Integer kind = 0;
2729               if     (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_AngularityTolerance)))       kind = 24;
2730               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CircularRunoutTolerance)))   kind = 25;
2731               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CoaxialityTolerance)))       kind = 26;
2732               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ConcentricityTolerance)))    kind = 27;
2733               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ParallelismTolerance)))      kind = 28;
2734               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_PerpendicularityTolerance))) kind = 29;
2735               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_SymmetryTolerance)))         kind = 30;
2736               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_TotalRunoutTolerance)))      kind = 31;
2737               //cout<<"GTWDR: kind="<<kind<<endl;
2738               TDF_Label TolerL = aDGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
2739               ReadDatums(aSTool,aDGTTool,aGraph,aTP,TolerL,GTWDR);
2740             }
2741             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_ModifiedGeometricTolerance))) {
2742               Handle(StepDimTol_ModifiedGeometricTolerance) MGT =
2743                 Handle(StepDimTol_ModifiedGeometricTolerance)::DownCast(theEnt);
2744               Standard_Integer kind = 35 + MGT->Modifier();
2745               aDGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
2746             }
2747             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_CylindricityTolerance))) {
2748               aDGTTool->SetDimTol(shL,38,arr,aName,aDescription);
2749             }
2750             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_FlatnessTolerance))) {
2751               aDGTTool->SetDimTol(shL,39,arr,aName,aDescription);
2752             }
2753             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_LineProfileTolerance))) {
2754               aDGTTool->SetDimTol(shL,40,arr,aName,aDescription);
2755             }
2756             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_PositionTolerance))) {
2757               aDGTTool->SetDimTol(shL,41,arr,aName,aDescription);
2758             }
2759             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_RoundnessTolerance))) {
2760               aDGTTool->SetDimTol(shL,42,arr,aName,aDescription);
2761             }
2762             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_StraightnessTolerance))) {
2763               aDGTTool->SetDimTol(shL,43,arr,aName,aDescription);
2764             }
2765             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_SurfaceProfileTolerance))) {
2766               aDGTTool->SetDimTol(shL,44,arr,aName,aDescription);
2767             }
2768           }
2769         }
2770         else
2771         {
2772           if(aGISU.IsNull()) continue;
2773           if(aGISU->NbIdentifiedItem() > 0) {
2774             aSeqRI.Append(aGISU->IdentifiedItemValue(1));
2775           }
2776         }
2777       }
2778       if(!aSeqRI.IsEmpty())
2779       {
2780         if(aSeqRI1.IsEmpty())
2781           aSeqRI1 = aSeqRI;
2782         else 
2783           aSeqRI2 = aSeqRI;
2784       }
2785     }
2786   }
2787   if(aSeqRI1.IsEmpty()) return aGDTL;
2788
2789   TDF_LabelSequence aShLS1, aShLS2;
2790
2791   for(Standard_Integer i = aSeqRI1.Lower(); i <= aSeqRI1.Upper() ;i++)
2792   {
2793     Standard_Integer anIndex = aTP->MapIndex(aSeqRI1.Value(i));
2794     TopoDS_Shape aSh;
2795     if(anIndex >0) {
2796       Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
2797       aSh = TransferBRep::ShapeResult(aBinder);
2798     }
2799     if(!aSh.IsNull())
2800     {
2801       TDF_Label aShL;
2802       aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True);
2803       aShLS1.Append(aShL);
2804     }
2805   }
2806   if (!aSeqRI2.IsEmpty())
2807   {
2808     //for dimensional location
2809     for(Standard_Integer i = aSeqRI2.Lower(); i <= aSeqRI2.Upper() ;i++)
2810     {
2811       Standard_Integer anIndex = aTP->MapIndex(aSeqRI2.Value(i));
2812       TopoDS_Shape aSh;
2813       if(anIndex >0) {
2814         Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
2815         aSh = TransferBRep::ShapeResult(aBinder);
2816       }
2817       if(!aSh.IsNull())
2818       {
2819         TDF_Label aShL;
2820         aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True);
2821         aShLS2.Append(aShL);
2822       }
2823     }
2824   }
2825
2826   if(!aShLS1.IsEmpty())
2827   {
2828     // add to XCAF
2829     if(!theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
2830     {
2831       aGDTL = aDGTTool->AddDimension();
2832       Handle(XCAFDoc_Dimension) aDim = XCAFDoc_Dimension::Set(aGDTL);
2833       TCollection_AsciiString aStr("DGT:Dimensional_");
2834       if(theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)))
2835       {
2836         aStr.AssignCat("Size");
2837       }
2838       else if(theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)))
2839       {
2840         aStr.AssignCat("Location");
2841       }
2842       TDataStd_Name::Set(aGDTL, aStr);
2843
2844       if(!aShLS2.IsEmpty())
2845       {
2846         aDGTTool->SetDimension(aShLS1, aShLS2, aGDTL);
2847       }
2848       else
2849       {
2850         TDF_LabelSequence aEmptySeq;
2851         aDGTTool->SetDimension(aShLS1, aEmptySeq, aGDTL);
2852       }
2853     }
2854     else
2855     {
2856       aGDTL = aDGTTool->AddGeomTolerance();
2857       Handle(XCAFDoc_GeomTolerance) aGTol = XCAFDoc_GeomTolerance::Set(aGDTL);
2858       TCollection_AsciiString aStr("DGT:GeomTolerance");
2859       TDataStd_Name::Set(aGDTL, aStr);
2860       aDGTTool->SetGeomTolerance(aShLS1, aGDTL);
2861       Handle(XCAFDimTolObjects_GeomToleranceObject) anObj = aGTol->GetObject();
2862       if(isAllAround)
2863         anObj->AddModifier(XCAFDimTolObjects_GeomToleranceModif_All_Around);
2864       else if(isAllOver)
2865         anObj->AddModifier(XCAFDimTolObjects_GeomToleranceModif_All_Over);
2866       aGTol->SetObject(anObj);
2867     }
2868     readDatumsAP242(theEnt, aGDTL, theDoc, theWS);
2869   }
2870   return aGDTL;
2871 }
2872
2873 //=======================================================================
2874 //function : setDimObjectToXCAF
2875 //purpose  : 
2876 //=======================================================================
2877 static void setDimObjectToXCAF(const Handle(Standard_Transient)& theEnt,
2878                                            const TDF_Label& aDimL,
2879                                            const Handle(TDocStd_Document)& theDoc,
2880                                            const Handle(XSControl_WorkSession)& theWS)
2881 {
2882   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
2883   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
2884   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
2885   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
2886   const Interface_Graph& aGraph = aTP->Graph();
2887   Handle(XCAFDimTolObjects_DimensionObject) aDimObj;
2888   if(!theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) &&
2889     !theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation))) 
2890     return;
2891
2892   Handle(StepShape_DimensionalSize) aDimSize = 
2893     Handle(StepShape_DimensionalSize)::DownCast(theEnt);
2894   Handle(StepShape_DimensionalLocation) aDimLocation = 
2895     Handle(StepShape_DimensionalLocation)::DownCast(theEnt);
2896
2897   aDimObj = new XCAFDimTolObjects_DimensionObject();
2898   Standard_Real aDim1=-1.,aDim2=-1.,aDim3=-1.;
2899   Handle(StepShape_TypeQualifier) aTQ;
2900   Handle(StepShape_ValueFormatTypeQualifier) aVFTQ;
2901   Handle(StepShape_ToleranceValue) aTV;
2902   Handle(StepShape_LimitsAndFits) aLAF;
2903   Handle(StepRepr_CompoundRepresentationItem) aCRI;
2904   Handle(StepGeom_Axis2Placement3d) anAP;
2905
2906   Interface_EntityIterator anIterDim;
2907   if(!aDimSize.IsNull())
2908   {
2909     anIterDim = aGraph.Sharings(aDimSize);
2910   }
2911   else
2912   {
2913     anIterDim = aGraph.Sharings(aDimLocation);
2914   }
2915   for(anIterDim.Start(); anIterDim.More(); anIterDim.Next()) {
2916     Handle(StepShape_DimensionalCharacteristicRepresentation) aDCR = 
2917       Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(anIterDim.Value());
2918     Handle(StepShape_PlusMinusTolerance) aPMT = 
2919       Handle(StepShape_PlusMinusTolerance)::DownCast(anIterDim.Value());
2920     if(!aDCR.IsNull()) {
2921       Handle(StepShape_ShapeDimensionRepresentation) aSDR = aDCR->Representation();
2922       if(!aSDR.IsNull()) {
2923         Handle(StepRepr_HArray1OfRepresentationItem) aHARI = aSDR->Items();
2924
2925         if(!aHARI.IsNull())
2926         {
2927           for(Standard_Integer nr = aHARI->Lower(); nr <= aHARI->Upper(); nr++)
2928           {
2929             Handle(StepRepr_RepresentationItem) aDRI = aHARI->Value(nr);
2930             if(aDRI.IsNull()) continue;
2931
2932             if(aDRI->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2933               //get values
2934               Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) aRILMWU =
2935                 Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(aDRI);
2936               Standard_Real aVal = aRILMWU->GetMeasureWithUnit()->ValueComponent();
2937               StepBasic_Unit anUnit = aRILMWU->GetMeasureWithUnit()->UnitComponent();
2938               Standard_Real aFact=1.;
2939               if(anUnit.IsNull()) continue;
2940               if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2941               Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2942               if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2943               if(aDim2 > 0)
2944               {
2945                 if(aDim1 > aDim2)
2946                 {
2947                   Standard_Real aTmp = aDim1;
2948                   aDim1 = aDim2;
2949                   aDim2 = aTmp;
2950                 }
2951                 if(aVal < aDim1)
2952                   aDim1 = aVal;
2953                 else if(aVal > aDim2)
2954                   aDim2 = aVal;
2955               }
2956               else if(aDim1 > 0)
2957               {
2958                 if (aVal > aDim1)
2959                   aDim2 = aVal;
2960                 else
2961                 {
2962                   aDim2 = aDim1;
2963                   aDim1 = aVal;
2964                 }
2965               }
2966               else
2967                 aDim1 = aVal;
2968             }
2969             else if(aDRI->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit))) {
2970               //get values
2971               Handle(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit) aRIPAMWU =
2972                 Handle(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit)::DownCast(aDRI);
2973               Standard_Real aVal = aRIPAMWU->GetMeasureWithUnit()->ValueComponent();
2974               StepBasic_Unit anUnit = aRIPAMWU->GetMeasureWithUnit()->UnitComponent();
2975               Standard_Real aFact=1.;
2976               if(anUnit.IsNull()) continue;
2977               if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2978               Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2979               if(GetAngleConversionFactor(NU,aFact)) aVal=aVal*aFact;
2980               if(aDim2 > 0)
2981               {
2982                 if(aDim1 > aDim2)
2983                 {
2984                   Standard_Real aTmp = aDim1;
2985                   aDim1 = aDim2;
2986                   aDim2 = aTmp;
2987                 }
2988                 if(aVal < aDim1)
2989                   aDim1 = aVal;
2990                 else if(aVal > aDim2)
2991                   aDim2 = aVal;
2992               }
2993               else if(aDim1 > 0)
2994               {
2995                 if (aVal > aDim1)
2996                   aDim2 = aVal;
2997                 else
2998                 {
2999                   aDim2 = aDim1;
3000                   aDim1 = aVal;
3001                 }
3002               }
3003               else
3004                 aDim1 = aVal;
3005             }
3006             else if(aDRI->IsKind(STANDARD_TYPE(StepShape_QualifiedRepresentationItem))) {
3007               //get qualifier
3008               Handle(StepShape_QualifiedRepresentationItem) aQRI =
3009                 Handle(StepShape_QualifiedRepresentationItem)::DownCast(aDRI);
3010               for(Standard_Integer l = 1; l <= aQRI->NbQualifiers(); l++)
3011               {
3012                 aTQ = aQRI->Qualifiers()->Value(l).TypeQualifier();
3013                 aVFTQ = aQRI->Qualifiers()->Value(l).ValueFormatTypeQualifier();
3014               }
3015             }
3016             else if (aDRI->IsKind(STANDARD_TYPE(StepRepr_DescriptiveRepresentationItem))) {
3017               Handle(StepRepr_DescriptiveRepresentationItem) aDescription =
3018                 Handle(StepRepr_DescriptiveRepresentationItem)::DownCast(aDRI);
3019               aDimObj->AddDescription(aDescription->Description(), aDescription->Name());
3020             }
3021             else if(aDRI->IsKind(STANDARD_TYPE(StepRepr_CompoundRepresentationItem))) {
3022               aCRI = Handle(StepRepr_CompoundRepresentationItem)::DownCast(aDRI);
3023             }
3024             else if(aDRI->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
3025             {
3026               anAP = Handle(StepGeom_Axis2Placement3d)::DownCast(aDRI);
3027             }
3028           }
3029         }
3030       }
3031     }
3032     else if (!aPMT.IsNull())
3033     {
3034       StepShape_ToleranceMethodDefinition aTMD = aPMT->Range();
3035       if(aPMT.IsNull()) continue;
3036       if(aTMD.CaseNumber() == 1)
3037         //! 1 -> ToleranceValue from StepShape
3038         //! 2 -> LimitsAndFits from StepShape
3039       {
3040         //plus minus tolerance 
3041         aTV = aTMD.ToleranceValue();
3042         if (aTV.IsNull()) continue;
3043
3044         Standard_Real aVal = aTV->UpperBound()->ValueComponent();
3045         StepBasic_Unit anUnit = aTV->UpperBound()->UnitComponent();
3046         Standard_Real aFact=1.;
3047         if(anUnit.IsNull()) continue;
3048         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
3049         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3050         if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
3051         aDim3 = aVal;
3052
3053         aVal = aTV->LowerBound()->ValueComponent();
3054         anUnit = aTV->LowerBound()->UnitComponent();
3055         aFact=1.;
3056         if(anUnit.IsNull()) continue;
3057         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
3058         NU = anUnit.NamedUnit();
3059         if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
3060         aDim2 = Abs(aVal);
3061       }
3062       else
3063       {
3064         // calss of tolerance
3065         aLAF = aTMD.LimitsAndFits();
3066       }
3067     }
3068   }
3069
3070   if(aDim1<0) return;
3071
3072   if(aDim2 < 0)
3073     aDimObj->SetValue(aDim1);
3074   else if (aDim3 < 0)
3075   {
3076     Handle(TColStd_HArray1OfReal) anArr = new TColStd_HArray1OfReal(1,2);
3077     anArr->SetValue(1,aDim1);
3078     anArr->SetValue(2,aDim2);
3079     aDimObj->SetValues(anArr);
3080   }
3081   else
3082   {
3083     Handle(TColStd_HArray1OfReal) anArr = new TColStd_HArray1OfReal(1,3);
3084     anArr->SetValue(1,aDim1);
3085     anArr->SetValue(2,aDim2);
3086     anArr->SetValue(3,aDim3);
3087     aDimObj->SetValues(anArr);
3088   }
3089   if(!aTQ.IsNull()) 
3090   {
3091     XCAFDimTolObjects_DimensionQualifier aQ;
3092     if (STEPCAFControl_GDTProperty::GetDimQualifierType(aTQ->Name(), aQ))
3093     {
3094         aDimObj->SetQualifier(aQ);
3095     }
3096   }
3097
3098   if (!aVFTQ.IsNull())
3099   {
3100     //A typical value would be 'NR2 2.2'
3101     TCollection_HAsciiString aFormat = aVFTQ->FormatType();
3102     Standard_Integer i = aFormat.Location(1,' ',1,aFormat.Length());
3103     aFormat.SubString(i+1,i+1)->IntegerValue();
3104     aDimObj->SetNbOfDecimalPlaces(aFormat.SubString(i+1,i+1)->IntegerValue(),
3105       aFormat.SubString(i+3,i+3)->IntegerValue());
3106   }
3107
3108   if (!aLAF.IsNull())
3109   { 
3110     //get class of tolerance
3111     Standard_Boolean aHolle = Standard_False;
3112     XCAFDimTolObjects_DimensionFormVariance aFV = XCAFDimTolObjects_DimensionFormVariance_None;
3113     XCAFDimTolObjects_DimensionGrade aG = XCAFDimTolObjects_DimensionGrade_IT01;
3114     STEPCAFControl_GDTProperty::GetDimClassOfTolerance(aLAF, aHolle, aFV, aG);
3115     aDimObj->SetClassOfTolerance(aHolle, aFV, aG);
3116   }
3117
3118   if (!aCRI.IsNull() && aCRI->ItemElement()->Length() > 0)
3119   {
3120     //get modifiers
3121     XCAFDimTolObjects_DimensionModifiersSequence aModifiers;
3122     STEPCAFControl_GDTProperty::GetDimModifiers(aCRI, aModifiers);
3123     if(aModifiers.Length() > 0)
3124       aDimObj->SetModifiers(aModifiers);
3125   }
3126
3127   Handle(TCollection_HAsciiString) aName;
3128   if(!aDimSize.IsNull())
3129   {
3130     aName = aDimSize->Name();
3131   }
3132   else
3133   {
3134     aName = aDimLocation->Name();
3135   }
3136   XCAFDimTolObjects_DimensionType aType = XCAFDimTolObjects_DimensionType_Location_None;
3137   if (!STEPCAFControl_GDTProperty::GetDimType(aName, aType))
3138   {
3139     if(!aDimSize.IsNull())
3140     {
3141       Handle(StepShape_AngularSize) anAngSize= 
3142         Handle(StepShape_AngularSize)::DownCast(aDimSize);
3143       if(!anAngSize.IsNull())
3144       {
3145         //get qualifier for angular value
3146         aType = XCAFDimTolObjects_DimensionType_Size_Angular;
3147         if(anAngSize->AngleSelection() == StepShape_Equal)
3148           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Avg);
3149         else if (anAngSize->AngleSelection() == StepShape_Large)
3150           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Max);
3151         else if (anAngSize->AngleSelection() == StepShape_Small)
3152           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Min);
3153       }
3154     }
3155     else
3156     {
3157       Handle(StepShape_AngularLocation) anAngLoc= 
3158         Handle(StepShape_AngularLocation)::DownCast(aDimLocation);
3159       if(!anAngLoc.IsNull())
3160       {
3161         //get qualifier for angular value
3162         aType = XCAFDimTolObjects_DimensionType_Location_Angular;
3163         if(anAngLoc->AngleSelection() == StepShape_Equal)
3164           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Avg);
3165         else if (anAngLoc->AngleSelection() == StepShape_Large)
3166           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Max);
3167         else if (anAngLoc->AngleSelection() == StepShape_Small)
3168           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Min);
3169       }
3170     }
3171     if(aType == XCAFDimTolObjects_DimensionType_Location_None)
3172     {
3173       Handle(StepRepr_ShapeAspect) aPSA;
3174       if(!aDimSize.IsNull())
3175       {
3176         Handle(StepShape_DimensionalSizeWithPath) aDimSizeWithPath= 
3177           Handle(StepShape_DimensionalSizeWithPath)::DownCast(aDimSize);
3178         if (!aDimSizeWithPath.IsNull())
3179         {
3180           aType = XCAFDimTolObjects_DimensionType_Size_WithPath;
3181           aPSA = aDimSizeWithPath->Path();
3182         }
3183       }
3184       else
3185       {
3186         Handle(StepShape_DimensionalLocationWithPath) aDimLocWithPath= 
3187           Handle(StepShape_DimensionalLocationWithPath)::DownCast(aDimLocation);
3188         if (!aDimLocWithPath.IsNull())
3189         {
3190           aType = XCAFDimTolObjects_DimensionType_Location_WithPath;
3191           aPSA = aDimLocWithPath->Path();
3192         }
3193       }
3194
3195       if(!aPSA.IsNull())
3196       {
3197         //for DimensionalLocationWithPath
3198         Handle(StepGeom_GeometricRepresentationItem) aGRI;
3199         Handle(StepAP242_GeometricItemSpecificUsage) aPGISU;
3200         Interface_EntityIterator anIterDSWP = aGraph.Sharings(aPSA);
3201         for(anIterDSWP.Start(); anIterDSWP.More() && aPGISU.IsNull(); anIterDSWP.Next()) {
3202           aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
3203         }
3204         if(aPGISU.IsNull()) return;
3205         if(aPGISU->NbIdentifiedItem() > 0) {
3206           aGRI = Handle(StepGeom_GeometricRepresentationItem)::DownCast(aPGISU->IdentifiedItemValue(1));
3207         }
3208         if(aGRI.IsNull()) return;
3209         Handle(StepRepr_RepresentationItem) aPRI;
3210         Interface_EntityIterator anIterGRI = aGraph.Sharings(aGRI);
3211         for(anIterGRI.Start(); anIterGRI.More() && aPGISU.IsNull(); anIterGRI.Next()) {
3212           aPRI = Handle(StepRepr_RepresentationItem)::DownCast(anIterGRI.Value());
3213         }
3214         Standard_Integer anIndex = aTP->MapIndex(aPRI);
3215         TopoDS_Edge aSh;
3216         if(anIndex >0) {
3217           Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
3218           aSh = TopoDS::Edge(TransferBRep::ShapeResult(aBinder));
3219         }
3220         if(aSh.IsNull()) return; 
3221         aDimObj->SetPath(aSh);
3222       }
3223       else if(!anAP.IsNull())
3224       {
3225         if(anAP->Name()->String().IsEqual("orientation") && !anAP->Axis().IsNull())
3226         {
3227           //for Oriented Dimensional Location
3228           Handle(TColStd_HArray1OfReal) aDirArr = anAP->RefDirection()->DirectionRatios();
3229           gp_Dir aDir;
3230           if(!aDirArr.IsNull() && aDirArr->Length() > 2)
3231           {
3232             aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, aDirArr->Lower()+2);
3233             aDimObj->SetDirection(aDir);
3234           }
3235           else if(aDirArr->Length() > 1)
3236           {
3237             aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, 0);
3238             aDimObj->SetDirection(aDir);
3239           }
3240         }
3241       }
3242     }
3243   }
3244   aDimObj->SetType(aType);
3245
3246   
3247   if(!aDimObj.IsNull())
3248   {
3249
3250     Handle(XCAFDoc_Dimension) aDim;
3251
3252     if(aDimL.FindAttribute(XCAFDoc_Dimension::GetID(),aDim))
3253     {
3254       readAnnotation(aTR, theEnt, aDimObj);
3255       aDim->SetObject(aDimObj);
3256     }
3257   }
3258 }
3259
3260 //=======================================================================
3261 //function : getTolType
3262 //purpose  : 
3263 //=======================================================================
3264 static Standard_Boolean getTolType(const Handle(Standard_Transient)& theEnt,
3265                        XCAFDimTolObjects_GeomToleranceType& theType)
3266 {
3267   if(!theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) 
3268     return Standard_False;
3269   theType = XCAFDimTolObjects_GeomToleranceType_None;
3270   if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRef)))
3271   {
3272     Handle(StepDimTol_GeoTolAndGeoTolWthDatRef) anE = Handle(StepDimTol_GeoTolAndGeoTolWthDatRef)::DownCast(theEnt);
3273     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3274   }
3275   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)))
3276   {
3277     Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol) anE = 
3278       Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)::DownCast(theEnt);
3279     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3280   }
3281   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod)))
3282   {
3283     Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod) anE = 
3284       Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod)::DownCast(theEnt);
3285     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3286   }
3287   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMaxTol)))
3288   {
3289     Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol) anE = 
3290       Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol)::DownCast(theEnt);
3291     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3292   }
3293   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMod)))
3294   {
3295     Handle(StepDimTol_GeoTolAndGeoTolWthMod) anE = 
3296       Handle(StepDimTol_GeoTolAndGeoTolWthMod)::DownCast(theEnt);
3297     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3298   }
3299   else if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndUneqDisGeoTol)))
3300   {
3301     Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndUneqDisGeoTol) anE = 
3302       Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndUneqDisGeoTol)::DownCast(theEnt);
3303     theType = STEPCAFControl_GDTProperty::GetGeomToleranceType(anE->GetToleranceType());
3304   }
3305   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_AngularityTolerance)))
3306   {
3307     theType = XCAFDimTolObjects_GeomToleranceType_Angularity;
3308   }
3309   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_CircularRunoutTolerance)))
3310   {
3311     theType = XCAFDimTolObjects_GeomToleranceType_CircularRunout;
3312   }
3313   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_RoundnessTolerance)))
3314   {
3315     theType = XCAFDimTolObjects_GeomToleranceType_CircularityOrRoundness;
3316   }
3317   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_CoaxialityTolerance)))
3318   {
3319     theType = XCAFDimTolObjects_GeomToleranceType_Coaxiality;
3320   }
3321   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_ConcentricityTolerance)))
3322   {
3323     theType = XCAFDimTolObjects_GeomToleranceType_Concentricity;
3324   }
3325   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_CylindricityTolerance)))
3326   {
3327     theType = XCAFDimTolObjects_GeomToleranceType_Cylindricity;
3328   }
3329   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_FlatnessTolerance)))
3330   {
3331     theType = XCAFDimTolObjects_GeomToleranceType_Flatness;
3332   }
3333   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_ParallelismTolerance)))
3334   {
3335     theType = XCAFDimTolObjects_GeomToleranceType_Parallelism;
3336   }
3337   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_PerpendicularityTolerance)))
3338   {
3339     theType = XCAFDimTolObjects_GeomToleranceType_Perpendicularity;
3340   }
3341   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_PositionTolerance)) || 
3342      theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol)))
3343   {
3344     theType = XCAFDimTolObjects_GeomToleranceType_Position;
3345   }
3346   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_LineProfileTolerance)))
3347   {
3348     theType = XCAFDimTolObjects_GeomToleranceType_ProfileOfLine;
3349   }
3350   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_SurfaceProfileTolerance)))
3351   {
3352     theType = XCAFDimTolObjects_GeomToleranceType_ProfileOfSurface;
3353   }
3354   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_StraightnessTolerance)))
3355   {
3356     theType = XCAFDimTolObjects_GeomToleranceType_Straightness;
3357   }
3358   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_SymmetryTolerance)))
3359   {
3360     theType = XCAFDimTolObjects_GeomToleranceType_Symmetry;
3361   }
3362   else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_TotalRunoutTolerance)))
3363   {
3364     theType = XCAFDimTolObjects_GeomToleranceType_TotalRunout;
3365   }
3366   return Standard_True;
3367 }
3368 //=======================================================================
3369 //function : setGeomTolObjectToXCAF
3370 //purpose  : 
3371 //=======================================================================
3372 static void setGeomTolObjectToXCAF(const Handle(Standard_Transient)& theEnt,
3373                                            const TDF_Label& theTolL,
3374                                            const Handle(TDocStd_Document)& theDoc,
3375                                            const Handle(XSControl_WorkSession)& theWS)
3376 {
3377   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
3378   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
3379   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
3380   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
3381   const Interface_Graph& aGraph = aTP->Graph();
3382   Handle(XCAFDoc_GeomTolerance) aGTol;
3383   if(!theTolL.FindAttribute(XCAFDoc_GeomTolerance::GetID(), aGTol))
3384   {
3385     return;
3386   }
3387   Handle(XCAFDimTolObjects_GeomToleranceObject) aTolObj = aGTol->GetObject();
3388   Handle(StepDimTol_GeometricTolerance) aTolEnt = Handle(StepDimTol_GeometricTolerance)::DownCast(theEnt);
3389
3390   XCAFDimTolObjects_GeomToleranceType aType = XCAFDimTolObjects_GeomToleranceType_None;
3391   getTolType(theEnt, aType);
3392   aTolObj->SetType(aType);
3393   if(!aTolEnt->Magnitude().IsNull()){
3394     //get value
3395     Standard_Real aVal = aTolEnt->Magnitude()->ValueComponent();
3396     StepBasic_Unit anUnit = aTolEnt->Magnitude()->UnitComponent();
3397     Standard_Real aFact=1.;
3398     if(anUnit.IsNull()) return;
3399     if( !(anUnit.CaseNum(anUnit.Value())==1) ) return;
3400     Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3401     if(GetLengthConversionFactor(NU,aFact))
3402       aVal=aVal*aFact;
3403     aTolObj->SetValue(aVal);
3404   }
3405   //get modifiers
3406   XCAFDimTolObjects_GeomToleranceTypeValue aTypeV = XCAFDimTolObjects_GeomToleranceTypeValue_None;
3407   Interface_EntityIterator anIter = aGraph.Sharings(aTolEnt);
3408   for(anIter.Start(); anIter.More(); anIter.Next()) {
3409     if(anIter.Value()->IsKind(STANDARD_TYPE(StepDimTol_ToleranceZone))){
3410       Handle(StepDimTol_ToleranceZoneForm) aForm 
3411                             = Handle(StepDimTol_ToleranceZone)::DownCast(anIter.Value())->Form();
3412       STEPCAFControl_GDTProperty::GetTolValueType(aForm->Name(), aTypeV);
3413       Interface_EntityIterator anIt = aGraph.Sharings(anIter.Value());
3414       for(anIt.Start(); anIt.More(); anIt.Next()) {
3415         if(anIt.Value()->IsKind(STANDARD_TYPE(StepDimTol_ProjectedZoneDefinition))){
3416           Handle(StepDimTol_ProjectedZoneDefinition) aPZone
3417                               = Handle(StepDimTol_ProjectedZoneDefinition)::DownCast(anIt.Value());
3418           if(!aPZone->ProjectionLength().IsNull())
3419           {
3420             Standard_Real aVal = aPZone->ProjectionLength()->ValueComponent();
3421             StepBasic_Unit anUnit = aPZone->ProjectionLength()->UnitComponent();
3422             Standard_Real aFact=1.;
3423             if(anUnit.IsNull()) return;
3424             if( !(anUnit.CaseNum(anUnit.Value())==1) ) return;
3425             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3426             if(GetLengthConversionFactor(NU,aFact))
3427               aVal=aVal*aFact;
3428             aTolObj->SetValueOfZoneModifier(aVal);
3429             aTolObj->SetZoneModifier(XCAFDimTolObjects_GeomToleranceZoneModif_Projected);
3430           }
3431         }
3432         else if (anIt.Value()->IsKind(STANDARD_TYPE(StepDimTol_RunoutZoneDefinition)))
3433         {
3434           Handle(StepDimTol_RunoutZoneDefinition) aRZone
3435                                 = Handle(StepDimTol_RunoutZoneDefinition)::DownCast(anIt.Value());
3436           if(!aRZone->Orientation().IsNull())
3437           {
3438             Standard_Real aVal = aRZone->Orientation()->Angle()->ValueComponent();
3439             StepBasic_Unit anUnit = aRZone->Orientation()->Angle()->UnitComponent();
3440             Standard_Real aFact=1.;
3441             if(anUnit.IsNull()) continue;
3442             if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
3443             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3444             if(GetAngleConversionFactor(NU,aFact)) aVal=aVal*aFact;
3445             aTolObj->SetValueOfZoneModifier(aVal);
3446             aTolObj->SetZoneModifier(XCAFDimTolObjects_GeomToleranceZoneModif_Runout);
3447           }
3448         }
3449       }
3450       aTolObj->SetTypeOfValue(aTypeV);
3451     }
3452   }
3453   Handle(StepDimTol_HArray1OfGeometricToleranceModifier) aModifiers;
3454   if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithModifiers)))
3455   {
3456     aModifiers = Handle(StepDimTol_GeometricToleranceWithModifiers)::DownCast(aTolEnt)->Modifiers();
3457   }
3458   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod)))
3459   {
3460     aModifiers = Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod)
3461                             ::DownCast(aTolEnt)->GetGeometricToleranceWithModifiers()->Modifiers();
3462   }
3463   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMod)))
3464   {
3465     aModifiers = Handle(StepDimTol_GeoTolAndGeoTolWthMod)
3466                              ::DownCast(aTolEnt)->GetGeometricToleranceWithModifiers()->Modifiers();
3467   }
3468   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMaxTol)))
3469   {
3470     aModifiers = Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol)
3471                              ::DownCast(aTolEnt)->GetGeometricToleranceWithModifiers()->Modifiers();
3472   }
3473   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)))
3474   {
3475     aModifiers = Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)
3476                              ::DownCast(aTolEnt)->GetGeometricToleranceWithModifiers()->Modifiers();
3477   }
3478   if(!aModifiers.IsNull())
3479   {
3480     for(Standard_Integer i = aModifiers->Lower(); i <= aModifiers->Upper(); i++)
3481     {
3482       if(aModifiers->Value(i) == StepDimTol_GTMLeastMaterialRequirement)
3483         aTolObj->SetMaterialRequirementModifier(XCAFDimTolObjects_GeomToleranceMatReqModif_L);
3484       else if (aModifiers->Value(i) == StepDimTol_GTMMaximumMaterialRequirement)
3485         aTolObj->SetMaterialRequirementModifier(XCAFDimTolObjects_GeomToleranceMatReqModif_M);
3486       else
3487         aTolObj->AddModifier((XCAFDimTolObjects_GeomToleranceModif)aModifiers->Value(i));
3488     }
3489   }
3490   Standard_Real aVal = 0;
3491   StepBasic_Unit anUnit;
3492   if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithMaximumTolerance)))
3493   {
3494     Handle(StepDimTol_GeometricToleranceWithMaximumTolerance) aMax = Handle(StepDimTol_GeometricToleranceWithMaximumTolerance)::DownCast(aTolEnt);
3495     aVal = aMax->MaximumUpperTolerance()->ValueComponent();
3496     anUnit = aMax->MaximumUpperTolerance()->UnitComponent();
3497   }
3498   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthMaxTol)))
3499   {
3500     Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol) aMax = 
3501       Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol)::DownCast(aTolEnt);
3502     aVal = aMax->GetMaxTolerance()->ValueComponent();
3503     anUnit = aMax->GetMaxTolerance()->UnitComponent();
3504   }
3505   else if (aTolEnt->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)))
3506   {
3507     Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol) aMax = 
3508       Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol)::DownCast(aTolEnt);
3509     aVal = aMax->GetMaxTolerance()->ValueComponent();
3510     anUnit = aMax->GetMaxTolerance()->UnitComponent();
3511   }
3512   if (!anUnit.IsNull() && (anUnit.CaseNum(anUnit.Value()) == 1))
3513   {
3514     Standard_Real aFact=1.;
3515     Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3516     if(GetAngleConversionFactor(NU,aFact)) aVal=aVal*aFact;
3517     aTolObj->SetMaxValueModifier(aVal);
3518   }
3519   
3520   readAnnotation(aTR, theEnt, aTolObj);
3521   aGTol->SetObject(aTolObj);
3522 }
3523
3524 //=======================================================================
3525 //function : ReadGDTs
3526 //purpose  : 
3527 //=======================================================================
3528
3529 Standard_Boolean STEPCAFControl_Reader::ReadGDTs(const Handle(XSControl_WorkSession)& theWS,
3530                                                  Handle(TDocStd_Document)& theDoc) const
3531 {
3532   Handle(Interface_InterfaceModel) aModel = theWS->Model();
3533   Handle(StepData_StepModel) aSM = Handle(StepData_StepModel)::DownCast(aModel);
3534   Interface_EntityIterator anI = aSM->Header();
3535   Handle(HeaderSection_FileSchema) aH;
3536   for(anI.Start(); anI.More() && aH.IsNull();anI.Next())
3537     aH = Handle(HeaderSection_FileSchema)::DownCast(anI.Value());
3538   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
3539   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
3540   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
3541   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
3542   if ( aDGTTool.IsNull() ) return Standard_False;
3543
3544   Standard_Integer nb = aModel->NbEntities();
3545   for(Standard_Integer i=1; i<=nb; i++) {
3546     Handle(Standard_Transient) anEnt = aModel->Value(i);
3547     if(anEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) || 
3548        anEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) ||
3549        anEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
3550       TDF_Label aGDTL = createGDTObjectInXCAF(anEnt,theDoc,theWS);
3551       if(!aGDTL.IsNull()){
3552         if(anEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))){
3553           setGeomTolObjectToXCAF(anEnt, aGDTL,theDoc,theWS);
3554         }
3555         else {
3556           setDimObjectToXCAF(anEnt, aGDTL,theDoc,theWS);
3557         }
3558       }
3559     }
3560   }
3561   return Standard_True;
3562 }
3563
3564
3565 //=======================================================================
3566 //function : FindSolidForPDS
3567 //purpose  : auxilary
3568 //=======================================================================
3569
3570 static Handle(StepShape_SolidModel) FindSolidForPDS(const Handle(StepRepr_ProductDefinitionShape) &PDS,
3571                                                     const Interface_Graph &graph)
3572 {
3573   Handle(StepShape_SolidModel) SM;
3574   Interface_EntityIterator subs = graph.Sharings(PDS);
3575   Handle(StepShape_ShapeRepresentation) SR;
3576   for(subs.Start(); subs.More() && SM.IsNull(); subs.Next()) {
3577     Handle(StepShape_ShapeDefinitionRepresentation) SDR =
3578       Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
3579     if(SDR.IsNull()) continue;
3580     SR = Handle(StepShape_ShapeRepresentation)::DownCast(SDR->UsedRepresentation());
3581     if(SR.IsNull()) continue;
3582     for(Standard_Integer i=1; i<=SR->NbItems() && SM.IsNull(); i++) {
3583       SM = Handle(StepShape_SolidModel)::DownCast(SR->ItemsValue(i));
3584     }
3585     if(SM.IsNull()) {
3586       Interface_EntityIterator subs1 = graph.Sharings(SR);
3587       for(subs1.Start(); subs1.More() && SM.IsNull(); subs1.Next()) {
3588         Handle(StepRepr_RepresentationRelationship) RR =
3589           Handle(StepRepr_RepresentationRelationship)::DownCast(subs1.Value());
3590         if(RR.IsNull()) continue;
3591         Handle(StepShape_ShapeRepresentation) SR2;
3592         if(RR->Rep1()==SR) SR2 = Handle(StepShape_ShapeRepresentation)::DownCast(RR->Rep2());
3593         else SR2 = Handle(StepShape_ShapeRepresentation)::DownCast(RR->Rep1());
3594         if(SR2.IsNull()) continue;
3595         for(Standard_Integer i2=1; i2<=SR2->NbItems() && SM.IsNull(); i2++) {
3596           SM = Handle(StepShape_SolidModel)::DownCast(SR2->ItemsValue(i2));
3597         }
3598       }
3599     }
3600   }
3601   return SM;
3602 }
3603
3604
3605 //=======================================================================
3606 //function : ReadMaterials
3607 //purpose  : 
3608 //=======================================================================
3609
3610 Standard_Boolean STEPCAFControl_Reader::ReadMaterials(const Handle(XSControl_WorkSession) &WS,
3611                                                       Handle(TDocStd_Document)& Doc,
3612                                                       const Handle(TColStd_HSequenceOfTransient) &SeqPDS) const
3613 {
3614   Handle(Interface_InterfaceModel) Model = WS->Model();
3615   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
3616   Handle(XSControl_TransferReader) TR = WS->TransferReader();
3617   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
3618   Handle(XCAFDoc_MaterialTool) MatTool = XCAFDoc_DocumentTool::MaterialTool( Doc->Main() );
3619   if(MatTool.IsNull()) return Standard_False;
3620   
3621   const Interface_Graph& graph = TP->Graph();
3622   for(Standard_Integer i=1; i<=SeqPDS->Length(); i++) {
3623     Handle(StepRepr_ProductDefinitionShape) PDS =
3624       Handle(StepRepr_ProductDefinitionShape)::DownCast(SeqPDS->Value(i));
3625     if(PDS.IsNull()) 
3626       continue;
3627     Handle(StepBasic_ProductDefinition) aProdDef = PDS->Definition().ProductDefinition();
3628     if(aProdDef.IsNull())
3629       continue;
3630     Handle(TCollection_HAsciiString) aName = new TCollection_HAsciiString("");
3631     Handle(TCollection_HAsciiString) aDescription = new TCollection_HAsciiString("");
3632     Handle(TCollection_HAsciiString) aDensName = new TCollection_HAsciiString("");
3633     Handle(TCollection_HAsciiString) aDensValType = new TCollection_HAsciiString("");
3634     Standard_Real aDensity=0;
3635     Interface_EntityIterator subs = graph.Sharings( aProdDef);
3636     for(subs.Start(); subs.More(); subs.Next()) {
3637       Handle(StepRepr_PropertyDefinition) PropD =
3638         Handle(StepRepr_PropertyDefinition)::DownCast(subs.Value());
3639       if(PropD.IsNull()) continue;
3640       Interface_EntityIterator subs1 = graph.Sharings(PropD);
3641       for(subs1.Start(); subs1.More(); subs1.Next()) {
3642         Handle(StepRepr_PropertyDefinitionRepresentation) PDR =
3643           Handle(StepRepr_PropertyDefinitionRepresentation)::DownCast(subs1.Value());
3644         if(PDR.IsNull()) continue;
3645         Handle(StepRepr_Representation) Repr = PDR->UsedRepresentation();
3646         if(Repr.IsNull()) continue;
3647         Standard_Integer ir;
3648         for(ir=1; ir<=Repr->NbItems(); ir++) {
3649           Handle(StepRepr_RepresentationItem) RI = Repr->ItemsValue(ir);
3650           if(RI.IsNull()) continue;
3651           if(RI->IsKind(STANDARD_TYPE(StepRepr_DescriptiveRepresentationItem))) {
3652             // find name and description for material
3653             Handle(StepRepr_DescriptiveRepresentationItem) DRI =
3654               Handle(StepRepr_DescriptiveRepresentationItem)::DownCast(RI);
3655             aName = DRI->Name();
3656             
3657             aDescription = DRI->Description();
3658             if(aName.IsNull())
3659               aName = aDescription;
3660           }
3661           if(RI->IsKind(STANDARD_TYPE(StepRepr_MeasureRepresentationItem))) {
3662             // try to find density for material
3663             Handle(StepRepr_MeasureRepresentationItem) MRI =
3664               Handle(StepRepr_MeasureRepresentationItem)::DownCast(RI);
3665             aDensity = MRI->Measure()->ValueComponent();
3666             aDensName = MRI->Name();
3667             aDensValType = new TCollection_HAsciiString(MRI->Measure()->ValueComponentMember()->Name());
3668             StepBasic_Unit aUnit = MRI->Measure()->UnitComponent();
3669             if(!aUnit.IsNull()) {
3670               Handle(StepBasic_DerivedUnit) DU = aUnit.DerivedUnit();
3671               if(DU.IsNull()) continue;
3672               for(Standard_Integer idu=1; idu<=DU->NbElements(); idu++) {
3673                 Handle(StepBasic_DerivedUnitElement) DUE = DU->ElementsValue(idu);
3674                 Handle(StepBasic_NamedUnit) NU = DUE->Unit();
3675                 Standard_Real afact=1.;
3676                 if(NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndLengthUnit))) {
3677                   if(GetLengthConversionFactor(NU,afact)) aDensity = aDensity/(afact*afact*afact);
3678                   // transfer length value for Density from millimeter to santimeter
3679                   // in order to result density has dimension gram/(sm*sm*sm)
3680                   aDensity = aDensity*1000.;
3681                 }
3682                 if(NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndMassUnit))) {
3683                   if(GetMassConversionFactor(NU,afact)) aDensity=aDensity*afact;
3684                 }
3685               }
3686             }
3687           }
3688         }
3689       }
3690     }
3691    
3692     if( aName.IsNull() || aName->Length()==0 ) 
3693       continue;
3694     // find shape label amd create Material link
3695     TopoDS_Shape aSh;
3696     Handle(StepShape_SolidModel) SM = FindSolidForPDS(PDS,graph);
3697     if(!SM.IsNull()) {
3698       Standard_Integer index = TP->MapIndex(SM);
3699       if(index >0) {
3700         Handle(Transfer_Binder) binder = TP->MapItem(index);
3701         if(!binder.IsNull())
3702           aSh = TransferBRep::ShapeResult(binder);
3703       }
3704     }
3705     if(aSh.IsNull()) continue; 
3706     TDF_Label shL;
3707     if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
3708     MatTool->SetMaterial(shL,aName,aDescription,aDensity,aDensName,aDensValType);
3709   }
3710
3711   return Standard_True;
3712 }
3713
3714 //=======================================================================
3715 //function : SettleShapeData
3716 //purpose  :
3717 //=======================================================================
3718
3719 TDF_Label STEPCAFControl_Reader::SettleShapeData(const Handle(StepRepr_RepresentationItem)& theItem,
3720                                                  TDF_Label& theLab,
3721                                                  const Handle(XCAFDoc_ShapeTool)& theShapeTool,
3722                                                  const Handle(Transfer_TransientProcess)& TP) const
3723 {
3724   TDF_Label aResult = theLab;
3725
3726   Handle(TCollection_HAsciiString) hName = theItem->Name();
3727   if ( hName.IsNull() || hName->IsEmpty() )
3728     return aResult;
3729
3730   Handle(Transfer_Binder) aBinder = TP->Find(theItem);
3731   if ( aBinder.IsNull() )
3732     return aResult;
3733
3734   TopoDS_Shape aShape = TransferBRep::ShapeResult(aBinder);
3735   if ( aShape.IsNull() )
3736     return aResult;
3737
3738   // Allocate sub-Label
3739   aResult = AllocateSubLabel(theLab);
3740
3741   TCollection_AsciiString aName = hName->String();
3742   TDataStd_Name::Set(aResult, aName);
3743   theShapeTool->SetShape(aResult, aShape);
3744
3745   return aResult;
3746 }
3747
3748 //=======================================================================
3749 //function : ExpandSubShapes
3750 //purpose  :
3751 //=======================================================================
3752
3753 void STEPCAFControl_Reader::ExpandSubShapes(const Handle(XCAFDoc_ShapeTool)& ShapeTool,
3754                                             const XCAFDoc_DataMapOfShapeLabel& ShapeLabelMap,
3755                                             const STEPCAFControl_DataMapOfShapePD& ShapePDMap) const
3756 {
3757   const Handle(Transfer_TransientProcess)& TP = Reader().WS()->TransferReader()->TransientProcess();
3758   NCollection_DataMap<TopoDS_Shape, Handle(TCollection_HAsciiString)> ShapeNameMap;
3759   TColStd_MapOfTransient aRepItems;
3760
3761   // Read translation control variables
3762   Standard_Boolean doReadSNames = (Interface_Static::IVal("read.stepcaf.subshapes.name") > 0);
3763
3764   if ( !doReadSNames )
3765     return;
3766
3767   const Interface_Graph& Graph = Reader().WS()->Graph();
3768
3769   for ( STEPCAFControl_DataMapIteratorOfDataMapOfShapePD it(ShapePDMap); it.More(); it.Next() )
3770   {
3771     const TopoDS_Shape& aRootShape = it.Key();
3772     const Handle(StepBasic_ProductDefinition)& aPDef = it.Value();
3773     if ( aPDef.IsNull() )
3774       continue;
3775
3776     // Find SDR by Product
3777     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
3778     Interface_EntityIterator entIt = Graph.TypedSharings( aPDef, STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation) );
3779     for ( entIt.Start(); entIt.More(); entIt.Next() )
3780     {
3781       const Handle(Standard_Transient)& aReferer = entIt.Value();
3782       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(aReferer);
3783       if ( !aSDR.IsNull() )
3784         break;
3785     }
3786
3787     if ( aSDR.IsNull() )
3788       continue;
3789
3790     // Access shape representation
3791     Handle(StepShape_ShapeRepresentation)
3792       aShapeRepr = Handle(StepShape_ShapeRepresentation)::DownCast( aSDR->UsedRepresentation() );
3793
3794     if ( aShapeRepr.IsNull() )
3795       continue;
3796
3797     // Access representation items
3798     Handle(StepRepr_HArray1OfRepresentationItem) aReprItems = aShapeRepr->Items();
3799
3800     if ( aReprItems.IsNull() )
3801       continue;
3802
3803     if ( !ShapeLabelMap.IsBound(aRootShape) )
3804       continue;
3805
3806     TDF_Label aRootLab = ShapeLabelMap.Find(aRootShape);
3807
3808     StepRepr_SequenceOfRepresentationItem aMSBSeq;
3809     StepRepr_SequenceOfRepresentationItem aSBSMSeq;
3810
3811     // Iterate over the top level representation items collecting the
3812     // topological containers to expand
3813     for ( Standard_Integer i = aReprItems->Lower(); i <= aReprItems->Upper(); ++i )
3814     {
3815       Handle(StepRepr_RepresentationItem) aTRepr = aReprItems->Value(i);
3816       if ( aTRepr->IsKind( STANDARD_TYPE(StepShape_ManifoldSolidBrep) ) )
3817         aMSBSeq.Append(aTRepr);
3818       else if ( aTRepr->IsKind( STANDARD_TYPE(StepShape_ShellBasedSurfaceModel) ) )
3819         aSBSMSeq.Append(aTRepr);
3820     }
3821
3822     // Insert intermediate OCAF Labels for SOLIDs in case there are more
3823     // than one Manifold Solid BRep in the Shape Representation
3824     Standard_Boolean doInsertSolidLab = (aMSBSeq.Length() > 1);
3825
3826     // Expand Manifold Solid BReps
3827     for ( Standard_Integer i = 1; i <= aMSBSeq.Length(); ++i )
3828     {
3829       const Handle(StepRepr_RepresentationItem)& aManiRepr = aMSBSeq.Value(i);
3830
3831       // Put additional Label for SOLID
3832       TDF_Label aManiLab;
3833       if ( doInsertSolidLab )
3834         aManiLab = SettleShapeData(aManiRepr, aRootLab, ShapeTool, TP);
3835       else
3836         aManiLab = aRootLab;
3837
3838       ExpandManifoldSolidBrep(aManiLab, aMSBSeq.Value(i), TP, ShapeTool);
3839     }
3840
3841     // Expand Shell-Based Surface Models
3842     for ( Standard_Integer i = 1; i <= aSBSMSeq.Length(); ++i )
3843       ExpandSBSM(aRootLab, aSBSMSeq.Value(i), TP, ShapeTool);
3844   }
3845 }
3846
3847 //=======================================================================
3848 //function : ExpandManifoldSolidBrep
3849 //purpose  :
3850 //=======================================================================
3851
3852 void STEPCAFControl_Reader::ExpandManifoldSolidBrep(TDF_Label& ShapeLab,
3853                                                     const Handle(StepRepr_RepresentationItem)& Repr,
3854                                                     const Handle(Transfer_TransientProcess)& TP,
3855                                                     const Handle(XCAFDoc_ShapeTool)& ShapeTool) const
3856 {
3857   // Access outer shell
3858   Handle(StepShape_ManifoldSolidBrep) aMSB = Handle(StepShape_ManifoldSolidBrep)::DownCast(Repr);
3859   Handle(StepShape_ConnectedFaceSet) aShell = aMSB->Outer();
3860
3861   // Expand shell contents to CAF tree
3862   ExpandShell(aShell, ShapeLab, TP, ShapeTool);
3863 }
3864
3865 //=======================================================================
3866 //function : ExpandSBSM
3867 //purpose  :
3868 //=======================================================================
3869
3870 void STEPCAFControl_Reader::ExpandSBSM(TDF_Label& ShapeLab,
3871                                        const Handle(StepRepr_RepresentationItem)& Repr,
3872                                        const Handle(Transfer_TransientProcess)& TP,
3873                                        const Handle(XCAFDoc_ShapeTool)& ShapeTool) const
3874 {
3875   Handle(StepShape_ShellBasedSurfaceModel) aSBSM = Handle(StepShape_ShellBasedSurfaceModel)::DownCast(Repr);
3876
3877   // Access boundary shells
3878   Handle(StepShape_HArray1OfShell) aShells = aSBSM->SbsmBoundary();
3879   for ( Standard_Integer s = aShells->Lower(); s <= aShells->Upper(); ++s )
3880   {
3881     const StepShape_Shell& aShell = aShells->Value(s);
3882     Handle(StepShape_ConnectedFaceSet) aCFS;
3883     Handle(StepShape_OpenShell) anOpenShell = aShell.OpenShell();
3884     Handle(StepShape_ClosedShell) aClosedShell = aShell.ClosedShell();
3885
3886     if ( !anOpenShell.IsNull() )
3887       aCFS = anOpenShell;
3888     else
3889       aCFS = aClosedShell;
3890
3891     ExpandShell(aCFS, ShapeLab, TP, ShapeTool);
3892   }
3893 }
3894
3895 //=======================================================================
3896 //function : ExpandShell
3897 //purpose  :
3898 //=======================================================================
3899
3900 void STEPCAFControl_Reader::ExpandShell(const Handle(StepShape_ConnectedFaceSet)& Shell,
3901                                         TDF_Label& RootLab,
3902                                         const Handle(Transfer_TransientProcess)& TP,
3903                                         const Handle(XCAFDoc_ShapeTool)& ShapeTool) const
3904 {
3905   // Record CAF data
3906   TDF_Label aShellLab = SettleShapeData(Shell, RootLab, ShapeTool, TP);
3907
3908   // Access faces
3909   Handle(StepShape_HArray1OfFace) aFaces = Shell->CfsFaces();
3910   for ( Standard_Integer f = aFaces->Lower(); f <= aFaces->Upper(); ++f )
3911   {
3912     const Handle(StepShape_Face)& aFace = aFaces->Value(f);
3913
3914     // Record CAF data
3915     TDF_Label aFaceLab = SettleShapeData(aFace, aShellLab, ShapeTool, TP);
3916
3917     // Access face bounds
3918     Handle(StepShape_HArray1OfFaceBound) aWires = aFace->Bounds();
3919     for ( Standard_Integer w = aWires->Lower(); w <= aWires->Upper(); ++w )
3920     {
3921       const Handle(StepShape_Loop)& aWire = aWires->Value(w)->Bound();
3922
3923       // Record CAF data
3924       TDF_Label aWireLab = SettleShapeData(aWire, aFaceLab, ShapeTool, TP);
3925
3926       // Access wire edges
3927       // Currently only EDGE LOOPs are considered (!)
3928       if ( !aWire->IsInstance( STANDARD_TYPE(StepShape_EdgeLoop) ) )
3929         continue;
3930
3931       // Access edges
3932       Handle(StepShape_EdgeLoop) anEdgeLoop = Handle(StepShape_EdgeLoop)::DownCast(aWire);
3933       Handle(StepShape_HArray1OfOrientedEdge) anEdges = anEdgeLoop->EdgeList();
3934       for ( Standard_Integer e = anEdges->Lower(); e <= anEdges->Upper(); ++e )
3935       {
3936         Handle(StepShape_Edge) anEdge = anEdges->Value(e)->EdgeElement();
3937
3938         // Record CAF data
3939         TDF_Label anEdgeLab = SettleShapeData(anEdge, aWireLab, ShapeTool, TP);
3940
3941         // Access vertices
3942         Handle(StepShape_Vertex) aV1 = anEdge->EdgeStart();
3943         Handle(StepShape_Vertex) aV2 = anEdge->EdgeEnd();
3944
3945         // Record CAF data
3946         SettleShapeData(aV1, anEdgeLab, ShapeTool, TP);
3947         SettleShapeData(aV2, anEdgeLab, ShapeTool, TP);
3948       }
3949     }
3950   }
3951 }
3952
3953 //=======================================================================
3954 //function : SetColorMode
3955 //purpose  : 
3956 //=======================================================================
3957
3958 void STEPCAFControl_Reader::SetColorMode (const Standard_Boolean colormode)
3959 {
3960   myColorMode = colormode;
3961 }
3962
3963 //=======================================================================
3964 //function : GetColorMode
3965 //purpose  : 
3966 //=======================================================================
3967
3968 Standard_Boolean STEPCAFControl_Reader::GetColorMode () const
3969 {
3970   return myColorMode;
3971 }
3972
3973 //=======================================================================
3974 //function : SetNameMode
3975 //purpose  : 
3976 //=======================================================================
3977
3978 void STEPCAFControl_Reader::SetNameMode (const Standard_Boolean namemode)
3979 {
3980   myNameMode = namemode;
3981 }
3982
3983 //=======================================================================
3984 //function : GetNameMode
3985 //purpose  : 
3986 //=======================================================================
3987
3988 Standard_Boolean STEPCAFControl_Reader::GetNameMode () const
3989 {
3990   return myNameMode;
3991 }
3992
3993 //=======================================================================
3994 //function : SetLayerMode
3995 //purpose  : 
3996 //=======================================================================
3997
3998 void STEPCAFControl_Reader::SetLayerMode (const Standard_Boolean layermode)
3999 {
4000   myLayerMode = layermode;
4001 }
4002
4003 //=======================================================================
4004 //function : GetLayerMode
4005 //purpose  : 
4006 //=======================================================================
4007
4008 Standard_Boolean STEPCAFControl_Reader::GetLayerMode () const
4009 {
4010   return myLayerMode;
4011 }
4012
4013 //=======================================================================
4014 //function : SetPropsMode
4015 //purpose  : 
4016 //=======================================================================
4017
4018 void STEPCAFControl_Reader::SetPropsMode (const Standard_Boolean propsmode)
4019 {
4020   myPropsMode = propsmode;
4021 }
4022
4023 //=======================================================================
4024 //function : GetPropsMode
4025 //purpose  : 
4026 //=======================================================================
4027
4028 Standard_Boolean STEPCAFControl_Reader::GetPropsMode () const
4029 {
4030   return myPropsMode;
4031 }
4032
4033 //=======================================================================
4034 //function : SetSHUOMode
4035 //purpose  : 
4036 //=======================================================================
4037
4038 void STEPCAFControl_Reader::SetSHUOMode (const Standard_Boolean mode)
4039 {
4040   mySHUOMode = mode;
4041 }
4042
4043 //=======================================================================
4044 //function : GetSHUOMode
4045 //purpose  : 
4046 //=======================================================================
4047
4048 Standard_Boolean STEPCAFControl_Reader::GetSHUOMode () const
4049 {
4050   return mySHUOMode;
4051 }
4052
4053 //=======================================================================
4054 //function : SetGDTMode
4055 //purpose  : 
4056 //=======================================================================
4057
4058 void STEPCAFControl_Reader::SetGDTMode (const Standard_Boolean gdtmode)
4059 {
4060   myGDTMode = gdtmode;
4061 }
4062
4063 //=======================================================================
4064 //function : GetGDTMode
4065 //purpose  : 
4066 //=======================================================================
4067
4068 Standard_Boolean STEPCAFControl_Reader::GetGDTMode () const
4069 {
4070   return myGDTMode;
4071 }
4072
4073
4074 //=======================================================================
4075 //function : SetMatMode
4076 //purpose  : 
4077 //=======================================================================
4078
4079 void STEPCAFControl_Reader::SetMatMode (const Standard_Boolean matmode)
4080 {
4081   myMatMode = matmode;
4082 }
4083
4084 //=======================================================================
4085 //function : GetMatMode
4086 //purpose  : 
4087 //=======================================================================
4088
4089 Standard_Boolean STEPCAFControl_Reader::GetMatMode () const
4090 {
4091   return myMatMode;
4092 }