0027934: Data Exchange - implement STEP common labels
[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_SiUnitAndLengthUnit.hxx>
41 #include <StepBasic_Unit.hxx>
42 #include <STEPCAFControl_Controller.hxx>
43 #include <STEPCAFControl_DataMapIteratorOfDataMapOfShapePD.hxx>
44 #include <STEPCAFControl_DataMapOfPDExternFile.hxx>
45 #include <STEPCAFControl_DataMapOfSDRExternFile.hxx>
46 #include <STEPCAFControl_DataMapOfShapePD.hxx>
47 #include <STEPCAFControl_DictionaryOfExternFile.hxx>
48 #include <STEPCAFControl_ExternFile.hxx>
49 #include <STEPCAFControl_Reader.hxx>
50 #include <STEPConstruct.hxx>
51 #include <STEPConstruct_Assembly.hxx>
52 #include <STEPConstruct_ExternRefs.hxx>
53 #include <STEPConstruct_Styles.hxx>
54 #include <STEPConstruct_Tool.hxx>
55 #include <STEPConstruct_UnitContext.hxx>
56 #include <STEPConstruct_ValidationProps.hxx>
57 #include <STEPControl_Reader.hxx>
58 #include <StepGeom_GeometricRepresentationItem.hxx>
59 #include <StepGeom_Axis2Placement3d.hxx>
60 #include <StepGeom_Direction.hxx>
61 #include <StepDimTol_AngularityTolerance.hxx>
62 #include <StepDimTol_CircularRunoutTolerance.hxx>
63 #include <StepDimTol_CoaxialityTolerance.hxx>
64 #include <StepDimTol_ConcentricityTolerance.hxx>
65 #include <StepDimTol_CylindricityTolerance.hxx>
66 #include <StepDimTol_Datum.hxx>
67 #include <StepDimTol_DatumFeature.hxx>
68 #include <StepDimTol_DatumReference.hxx>
69 #include <StepDimTol_DatumReferenceElement.hxx>
70 #include <StepDimTol_DatumReferenceCompartment.hxx>
71 #include <StepDimTol_DatumSystem.hxx>
72 #include <StepDimTol_FlatnessTolerance.hxx>
73 #include <StepDimTol_GeometricTolerance.hxx>
74 #include <StepDimTol_GeometricToleranceWithDatumReference.hxx>
75 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol.hxx>
76 #include <StepDimTol_GeoTolAndGeoTolWthDatRef.hxx>
77 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol.hxx>
78 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndUneqDisGeoTol.hxx>
79 #include <StepDimTol_GeoTolAndGeoTolWthMaxTol.hxx>
80 #include <StepDimTol_HArray1OfDatumReference.hxx>
81 #include <StepDimTol_LineProfileTolerance.hxx>
82 #include <StepDimTol_ModifiedGeometricTolerance.hxx>
83 #include <StepDimTol_ParallelismTolerance.hxx>
84 #include <StepDimTol_PerpendicularityTolerance.hxx>
85 #include <StepDimTol_PositionTolerance.hxx>
86 #include <StepDimTol_ProjectedZoneDefinition.hxx>
87 #include <StepDimTol_RoundnessTolerance.hxx>
88 #include <StepDimTol_RunoutZoneDefinition.hxx>
89 #include <StepDimTol_StraightnessTolerance.hxx>
90 #include <StepDimTol_SurfaceProfileTolerance.hxx>
91 #include <StepDimTol_SymmetryTolerance.hxx>
92 #include <StepDimTol_ToleranceZone.hxx>
93 #include <StepDimTol_ToleranceZoneForm.hxx>
94 #include <StepDimTol_TotalRunoutTolerance.hxx>
95 #include <StepDimTol_GeometricToleranceWithModifiers.hxx>
96 #include <StepDimTol_HArray1OfGeometricToleranceModifier.hxx>
97 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod.hxx>
98 #include <StepDimTol_GeoTolAndGeoTolWthMod.hxx>
99 #include <StepDimTol_GeometricToleranceWithMaximumTolerance.hxx>
100 #include <StepGeom_Axis2Placement3d.hxx>
101 #include <StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext.hxx>
102 #include <StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx.hxx>
103 #include <StepGeom_Plane.hxx>
104 #include <StepGeom_Polyline.hxx>
105 #include <StepDimTol_PlacedDatumTargetFeature.hxx>
106 #include <StepRepr_AssemblyComponentUsage.hxx>
107 #include <StepRepr_CharacterizedDefinition.hxx>
108 #include <StepRepr_CompoundRepresentationItem.hxx>
109 #include <StepRepr_DerivedShapeAspect.hxx>
110 #include <StepRepr_DescriptiveRepresentationItem.hxx>
111 #include <StepRepr_HArray1OfRepresentationItem.hxx>
112 #include <StepRepr_MeasureRepresentationItem.hxx>
113 #include <StepRepr_NextAssemblyUsageOccurrence.hxx>
114 #include <StepRepr_ProductDefinitionShape.hxx>
115 #include <StepRepr_PropertyDefinition.hxx>
116 #include <StepRepr_PropertyDefinitionRepresentation.hxx>
117 #include <StepRepr_Representation.hxx>
118 #include <StepRepr_RepresentationItem.hxx>
119 #include <StepRepr_HArray1OfRepresentationItem.hxx>
120 #include <StepRepr_RepresentationRelationship.hxx>
121 #include <StepRepr_RepresentedDefinition.hxx>
122 #include <StepRepr_ReprItemAndLengthMeasureWithUnit.hxx>
123 #include <StepRepr_ReprItemAndPlaneAngleMeasureWithUnit.hxx>
124 #include <StepRepr_SequenceOfRepresentationItem.hxx>
125 #include <StepRepr_ShapeAspect.hxx>
126 #include <StepRepr_ShapeAspectDerivingRelationship.hxx>
127 #include <StepRepr_CompositeShapeAspect.hxx>
128 #include <StepRepr_AllAroundShapeAspect.hxx>
129 #include <StepRepr_CompShAspAndDatumFeatAndShAsp.hxx>
130 #include <StepRepr_ShapeAspectRelationship.hxx>
131 #include <StepRepr_ShapeRepresentationRelationship.hxx>
132 #include <StepRepr_SpecifiedHigherUsageOccurrence.hxx>
133 #include <StepRepr_ValueRange.hxx>
134 #include <StepRepr_FeatureForDatumTargetRelationship.hxx>
135 #include <StepShape_AdvancedFace.hxx>
136 #include <StepShape_AdvancedBrepShapeRepresentation.hxx>
137 #include <StepShape_AngleRelator.hxx>
138 #include <StepShape_AngularSize.hxx>
139 #include <StepShape_AngularLocation.hxx>
140 #include <StepShape_ClosedShell.hxx>
141 #include <StepShape_ConnectedFaceSet.hxx>
142 #include <StepShape_ContextDependentShapeRepresentation.hxx>
143 #include <StepRepr_CompGroupShAspAndCompShAspAndDatumFeatAndShAsp.hxx>
144 #include <StepRepr_CompShAspAndDatumFeatAndShAsp.hxx>
145 #include <StepShape_DimensionalCharacteristicRepresentation.hxx>
146 #include <StepShape_DimensionalSizeWithPath.hxx>
147 #include <StepShape_DimensionalLocationWithPath.hxx>
148 #include <StepShape_ShapeDimensionRepresentationItem.hxx>
149 #include <StepShape_ShapeRepresentationWithParameters.hxx>
150 #include <StepShape_HArray1OfShapeDimensionRepresentationItem.hxx>
151 #include <StepShape_DimensionalSize.hxx>
152 #include <StepShape_DimensionalLocation.hxx>
153 #include <StepShape_EdgeCurve.hxx>
154 #include <StepShape_EdgeLoop.hxx>
155 #include <StepShape_GeometricCurveSet.hxx>
156 #include <StepShape_GeometricSet.hxx>
157 #include <StepShape_HArray1OfFace.hxx>
158 #include <StepShape_HArray1OfFaceBound.hxx>
159 #include <StepShape_HArray1OfOrientedEdge.hxx>
160 #include <StepShape_HArray1OfShell.hxx>
161 #include <StepShape_LimitsAndFits.hxx>
162 #include <StepShape_Loop.hxx>
163 #include <StepShape_ManifoldSolidBrep.hxx>
164 #include <StepShape_PlusMinusTolerance.hxx>
165 #include <StepShape_QualifiedRepresentationItem.hxx>
166 #include <StepShape_OpenShell.hxx>
167 #include <StepShape_ShapeDefinitionRepresentation.hxx>
168 #include <StepShape_ShapeDimensionRepresentation.hxx>
169 #include <StepShape_ShapeRepresentation.hxx>
170 #include <StepShape_ShellBasedSurfaceModel.hxx>
171 #include <StepShape_SolidModel.hxx>
172 #include <StepShape_ToleranceMethodDefinition.hxx>
173 #include <StepShape_ToleranceValue.hxx>
174 #include <StepShape_ValueFormatTypeQualifier.hxx>
175 #include <StepShape_Vertex.hxx>
176 #include <StepVisual_AnnotationCurveOccurrence.hxx>
177 #include <StepVisual_AnnotationPlane.hxx>
178 #include <StepVisual_DraughtingCallout.hxx>
179 #include <StepVisual_DraughtingCalloutElement.hxx>
180 #include <StepVisual_DraughtingModel.hxx>
181 #include <StepVisual_Invisibility.hxx>
182 #include <StepVisual_LayeredItem.hxx>
183 #include <StepVisual_PlanarBox.hxx>
184 #include <StepVisual_PresentationLayerAssignment.hxx>
185 #include <StepVisual_PresentationStyleByContext.hxx>
186 #include <StepVisual_StyleContextSelect.hxx>
187 #include <StepVisual_StyledItem.hxx>
188 #include <StepShape_TypeQualifier.hxx>
189 #include <TCollection_AsciiString.hxx>
190 #include <TCollection_HAsciiString.hxx>
191 #include <TColStd_HArray1OfReal.hxx>
192 #include <TColStd_HArray1OfTransient.hxx>
193 #include <TColStd_HSequenceOfTransient.hxx>
194 #include <TColStd_IndexedDataMapOfTransientTransient.hxx>
195 #include <TColStd_MapIteratorOfMapOfTransient.hxx>
196 #include <TColStd_MapOfTransient.hxx>
197 #include <TColStd_SequenceOfHAsciiString.hxx>
198 #include <TDataStd_Name.hxx>
199 #include <TDataStd_TreeNode.hxx>
200 #include <TDataStd_UAttribute.hxx>
201 #include <TDF_Label.hxx>
202 #include <TDF_Tool.hxx>
203 #include <TDocStd_Document.hxx>
204 #include <TNaming_NamedShape.hxx>
205 #include <TopExp_Explorer.hxx>
206 #include <TopoDS.hxx>
207 #include <TopoDS_Compound.hxx>
208 #include <TopoDS_Iterator.hxx>
209 #include <TopoDS_Shape.hxx>
210 #include <TopTools_ListIteratorOfListOfShape.hxx>
211 #include <TopTools_ListOfShape.hxx>
212 #include <TopTools_MapOfShape.hxx>
213 #include <Transfer_Binder.hxx>
214 #include <Transfer_TransientProcess.hxx>
215 #include <TransferBRep.hxx>
216 #include <XCAFDoc.hxx>
217 #include <XCAFDoc_Area.hxx>
218 #include <XCAFDoc_Centroid.hxx>
219 #include <XCAFDoc_ColorTool.hxx>
220 #include <XCAFDoc_DataMapOfShapeLabel.hxx>
221 #include <XCAFDoc_DimTolTool.hxx>
222 #include <XCAFDoc_Dimension.hxx>
223 #include <XCAFDoc_Datum.hxx>
224 #include <XCAFDoc_GeomTolerance.hxx>
225 #include <XCAFDoc_DocumentTool.hxx>
226 #include <XCAFDoc_GraphNode.hxx>
227 #include <XCAFDoc_LayerTool.hxx>
228 #include <XCAFDoc_MaterialTool.hxx>
229 #include <XCAFDoc_ShapeTool.hxx>
230 #include <XCAFDoc_Volume.hxx>
231 #include <XCAFDimTolObjects_DimensionModifiersSequence.hxx>
232 #include <XCAFDimTolObjects_GeomToleranceType.hxx>
233 #include <XCAFDimTolObjects_DimensionObject.hxx>
234 #include <XCAFDimTolObjects_GeomToleranceObject.hxx>
235 #include <XCAFDimTolObjects_DatumObject.hxx>
236 #include <XSControl_TransferReader.hxx>
237 #include <XSControl_WorkSession.hxx>
238 #include <StepAP242_DraughtingModelItemAssociation.hxx>
239 #include <StepAP242_GeometricItemSpecificUsage.hxx>
240 #include <StepGeom_CartesianPoint.hxx>
241 #include <STEPCAFControl_GDTProperty.hxx>
242 #include <StepVisual_TessellatedAnnotationOccurrence.hxx>
243 #include <StepVisual_TessellatedAnnotationOccurrence.hxx>
244 #include <StepVisual_TessellatedItem.hxx>
245 #include <StepVisual_TessellatedGeometricSet.hxx>
246 #include <StepVisual_TessellatedCurveSet.hxx>
247 #include <StepVisual_CoordinatesList.hxx>
248 #include <NCollection_Vector.hxx>
249
250 #include <TColgp_HArray1OfXYZ.hxx>
251 #include <BRepBuilderAPI_MakeEdge.hxx>
252 #include <BRepTools.hxx>
253 #include <Transfer_ActorOfTransientProcess.hxx>
254 #include <Bnd_Box.hxx>
255 #include <BRepBndLib.hxx>
256
257 // skl 21.08.2003 for reading G&DT
258 //#include <StepRepr_CompoundItemDefinition.hxx>
259 //#include <StepRepr_CompoundItemDefinitionMember.hxx>
260 //#include <StepBasic_ConversionBasedUnit.hxx>
261 //#include <TDataStd_Real.hxx>
262 //#include <TDataStd_Constraint.hxx>
263 //#include <TDataStd_ConstraintEnum.hxx>
264 //#include <TNaming_Tool.hxx>
265 //#include <AIS_InteractiveObject.hxx>
266 //#include <TPrsStd_ConstraintTools.hxx>
267 //#include <AIS_DiameterDimension.hxx>
268 //#include <TPrsStd_Position.hxx>
269 //#include <TPrsStd_AISPresentation.hxx>
270 //#include <TNaming_Builder.hxx>
271 #ifdef OCCT_DEBUG
272 //! Converts address of the passed shape (TShape) to string.
273 //! \param theShape [in] Shape to dump.
274 //! \return corresponding string.
275 TCollection_AsciiString AddrToString(const TopoDS_Shape& theShape)
276 {
277   std::string anAddrStr;
278   std::ostringstream ost;
279   ost << theShape.TShape().get();
280   anAddrStr = ost.str();
281
282   TCollection_AsciiString aStr =
283     TCollection_AsciiString("[").Cat( anAddrStr.c_str() ).Cat("]");
284
285   return aStr;
286 }
287 #endif
288
289 //=======================================================================
290 //function : IsEqual
291 //purpose  : global function to check equality of topological shapes
292 //=======================================================================
293
294 inline Standard_Boolean IsEqual(const TopoDS_Shape& theShape1,
295                                 const TopoDS_Shape& theShape2) 
296 {
297   return theShape1.IsEqual(theShape2);
298 }
299
300 //=======================================================================
301 //function : AllocateSubLabel
302 //purpose  :
303 //=======================================================================
304
305 static TDF_Label AllocateSubLabel(TDF_Label& theRoot)
306 {
307   return TDF_TagSource::NewChild(theRoot);
308 }
309
310 //=======================================================================
311 //function : STEPCAFControl_Reader
312 //purpose  : 
313 //=======================================================================
314
315 STEPCAFControl_Reader::STEPCAFControl_Reader ():
316        myColorMode( Standard_True ),
317        myNameMode ( Standard_True ),
318        myLayerMode( Standard_True ),
319        myPropsMode( Standard_True ),
320            mySHUOMode ( Standard_False ),
321        myGDTMode  ( Standard_True ),
322        myMatMode  ( Standard_True )
323 {
324   STEPCAFControl_Controller::Init();
325   myFiles = new STEPCAFControl_DictionaryOfExternFile;
326 }
327
328
329 //=======================================================================
330 //function : STEPCAFControl_Reader
331 //purpose  : 
332 //=======================================================================
333
334 STEPCAFControl_Reader::STEPCAFControl_Reader (const Handle(XSControl_WorkSession)& WS,
335                                               const Standard_Boolean scratch) :
336        myColorMode( Standard_True ),
337        myNameMode ( Standard_True ),
338        myLayerMode( Standard_True ),
339        myPropsMode( Standard_True ),
340            mySHUOMode ( Standard_False ),
341        myGDTMode  ( Standard_True ),
342        myMatMode  ( Standard_True )
343 {
344   STEPCAFControl_Controller::Init();
345   Init ( WS, scratch );
346 }
347
348
349 //=======================================================================
350 //function : Init
351 //purpose  : 
352 //=======================================================================
353
354 void STEPCAFControl_Reader::Init (const Handle(XSControl_WorkSession)& WS,
355                                   const Standard_Boolean scratch)
356 {
357 // necessary only in Writer, to set good actor:  WS->SelectNorm ( "STEP" );
358   myReader.SetWS (WS,scratch);
359   myFiles = new STEPCAFControl_DictionaryOfExternFile;
360 }
361
362
363 //=======================================================================
364 //function : ReadFile
365 //purpose  : 
366 //=======================================================================
367
368 IFSelect_ReturnStatus STEPCAFControl_Reader::ReadFile (const Standard_CString filename)
369 {
370   return myReader.ReadFile ( filename );
371 }
372
373
374 //=======================================================================
375 //function : NbRootsForTransfer
376 //purpose  : 
377 //=======================================================================
378
379 Standard_Integer STEPCAFControl_Reader::NbRootsForTransfer () 
380 {
381   return myReader.NbRootsForTransfer();
382 }
383
384
385 //=======================================================================
386 //function : TransferOneRoot
387 //purpose  : 
388 //=======================================================================
389
390 Standard_Boolean STEPCAFControl_Reader::TransferOneRoot (const Standard_Integer num,
391                                                          Handle(TDocStd_Document) &doc) 
392 {
393   TDF_LabelSequence Lseq;
394   return Transfer ( myReader, num, doc, Lseq );
395 }
396
397
398 //=======================================================================
399 //function : Transfer
400 //purpose  : 
401 //=======================================================================
402
403 Standard_Boolean STEPCAFControl_Reader::Transfer (Handle(TDocStd_Document) &doc)
404 {
405   TDF_LabelSequence Lseq;
406   return Transfer ( myReader, 0, doc, Lseq );
407 }
408
409
410 //=======================================================================
411 //function : Perform
412 //purpose  : 
413 //=======================================================================
414
415 Standard_Boolean STEPCAFControl_Reader::Perform (const Standard_CString filename,
416                                                  Handle(TDocStd_Document) &doc)
417 {
418   if ( ReadFile ( filename ) != IFSelect_RetDone ) return Standard_False;
419   return Transfer ( doc );
420 }
421   
422
423 //=======================================================================
424 //function : Perform
425 //purpose  : 
426 //=======================================================================
427
428 Standard_Boolean STEPCAFControl_Reader::Perform (const TCollection_AsciiString &filename,
429                                                  Handle(TDocStd_Document) &doc)
430 {
431   if ( ReadFile ( filename.ToCString() ) != IFSelect_RetDone ) return Standard_False;
432   return Transfer ( doc );
433 }
434   
435
436 //=======================================================================
437 //function : ExternFiles
438 //purpose  : 
439 //=======================================================================
440
441 const Handle(STEPCAFControl_DictionaryOfExternFile) &STEPCAFControl_Reader::ExternFiles () const
442 {
443   return myFiles;
444 }
445         
446
447 //=======================================================================
448 //function : ExternFile
449 //purpose  : 
450 //=======================================================================
451
452 Standard_Boolean STEPCAFControl_Reader::ExternFile (const Standard_CString name,
453                                                     Handle(STEPCAFControl_ExternFile) &ef) const
454 {
455   ef.Nullify();
456   if ( myFiles.IsNull() || ! myFiles->HasItem ( name ) ) 
457     return Standard_False;
458   ef = myFiles->Item ( name );
459   return Standard_True;
460 }
461
462
463 //=======================================================================
464 //function : Reader
465 //purpose  : 
466 //=======================================================================
467
468 STEPControl_Reader &STEPCAFControl_Reader::ChangeReader () 
469 {
470   return myReader;
471 }
472   
473
474 //=======================================================================
475 //function : Reader
476 //purpose  : 
477 //=======================================================================
478
479 const STEPControl_Reader &STEPCAFControl_Reader::Reader () const
480 {
481   return myReader;
482 }
483   
484
485 //=======================================================================
486 //function : FillShapesMap
487 //purpose  : auxiliary: fill a map by all compounds and their components
488 //=======================================================================
489
490 static void FillShapesMap (const TopoDS_Shape &S, TopTools_MapOfShape &map)
491 {
492   TopoDS_Shape S0 = S;
493   TopLoc_Location loc;
494   S0.Location ( loc );
495   map.Add ( S0 );
496   if ( S.ShapeType() != TopAbs_COMPOUND ) return;
497   for ( TopoDS_Iterator it(S); it.More(); it.Next() ) 
498     FillShapesMap ( it.Value(), map );
499 }
500
501
502 //=======================================================================
503 //function : Transfer
504 //purpose  : basic working method
505 //=======================================================================
506
507 Standard_Boolean STEPCAFControl_Reader::Transfer (STEPControl_Reader &reader,
508                                                   const Standard_Integer nroot,
509                                                   Handle(TDocStd_Document) &doc,
510                                                   TDF_LabelSequence &Lseq,
511                                                   const Standard_Boolean asOne)
512 {
513   reader.ClearShapes();
514   Standard_Integer i;
515   
516   // Read all shapes
517   Standard_Integer num = reader.NbRootsForTransfer();
518   if ( num <=0 ) return Standard_False;
519   if ( nroot ) {
520     if ( nroot > num ) return Standard_False;
521     reader.TransferOneRoot ( nroot );
522   }
523   else {
524     for ( i=1; i <= num; i++ ) reader.TransferOneRoot ( i );
525   }
526   num = reader.NbShapes();
527   if ( num <=0 ) return Standard_False;
528
529   // Fill a map of (top-level) shapes resulting from that transfer
530   // Only these shapes will be considered further
531   TopTools_MapOfShape ShapesMap, NewShapesMap;
532   for ( i=1; i <= num; i++ ) FillShapesMap ( reader.Shape(i), ShapesMap );
533   
534   // Collect information on shapes originating from SDRs
535   // this will be used to distinguish compounds representing assemblies
536   // from the ones representing hybrid models and shape sets
537   STEPCAFControl_DataMapOfShapePD ShapePDMap;
538   STEPCAFControl_DataMapOfPDExternFile PDFileMap;
539   Handle(Interface_InterfaceModel) Model = reader.Model();
540   const Handle(Transfer_TransientProcess) &TP = reader.WS()->TransferReader()->TransientProcess();
541   Standard_Integer nb = Model->NbEntities();
542
543   Handle(TColStd_HSequenceOfTransient) SeqPDS = new TColStd_HSequenceOfTransient;
544
545   for (i = 1; i <= nb; i ++) {
546     Handle(Standard_Transient) enti = Model->Value(i);
547     if(enti->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape))) {
548       // sequence for acceleration ReadMaterials
549       SeqPDS->Append(enti);
550     }
551     if ( enti->IsKind ( STANDARD_TYPE(StepBasic_ProductDefinition ) ) ) {
552       Handle(StepBasic_ProductDefinition) PD = 
553         Handle(StepBasic_ProductDefinition)::DownCast(enti);
554       Standard_Integer index = TP->MapIndex(PD);
555       if ( index >0 ) {
556         Handle(Transfer_Binder) binder = TP->MapItem (index);
557         TopoDS_Shape S = TransferBRep::ShapeResult(binder);
558         if ( ! S.IsNull() && ShapesMap.Contains(S) ) {
559           NewShapesMap.Add(S);
560           ShapePDMap.Bind ( S, PD ); 
561           Handle(STEPCAFControl_ExternFile) EF;
562           PDFileMap.Bind ( PD, EF );
563         }
564       }
565     }
566     if ( enti->IsKind ( STANDARD_TYPE(StepShape_ShapeRepresentation) ) ) {
567       Standard_Integer index = TP->MapIndex(enti);
568       if ( index >0 ) {
569         Handle(Transfer_Binder) binder = TP->MapItem (index);
570         TopoDS_Shape S = TransferBRep::ShapeResult(binder);
571         if ( ! S.IsNull() && ShapesMap.Contains(S) )
572           NewShapesMap.Add(S);
573       }
574     }
575   }
576
577   // get directory name of the main file
578   OSD_Path mainfile ( reader.WS()->LoadedFile() );
579   mainfile.SetName ( "" );
580   mainfile.SetExtension ( "" );
581   TCollection_AsciiString dpath;
582   mainfile.SystemName ( dpath );
583
584   // Load external references (only for relevant SDRs)
585   // and fill map SDR -> extern file
586   STEPConstruct_ExternRefs ExtRefs ( reader.WS() );
587   ExtRefs.LoadExternRefs();
588   for ( i=1; i <= ExtRefs.NbExternRefs(); i++ ) {
589     // check extern ref format
590     Handle(TCollection_HAsciiString) format = ExtRefs.Format(i);
591     if ( ! format.IsNull() ) {
592       static Handle(TCollection_HAsciiString) ap203 = new TCollection_HAsciiString ( "STEP AP203" );
593       static Handle(TCollection_HAsciiString) ap214 = new TCollection_HAsciiString ( "STEP AP214" );
594       if ( ! format->IsSameString ( ap203, Standard_False ) && 
595            ! format->IsSameString ( ap214, Standard_False ) ) {
596 #ifdef OCCT_DEBUG
597         cout << "Warning: STEPCAFControl_Reader::Transfer: Extern document is neither STEP AP203 nor AP214" << endl;
598 #else
599         continue;
600 #endif
601       }
602     }
603 #ifdef OCCT_DEBUG
604     else cout << "Warning: STEPCAFControl_Reader::Transfer: Extern document format not defined" << endl;
605 #endif
606     
607     // get and check filename of the current extern ref
608     const Standard_CString filename = ExtRefs.FileName(i);
609
610 #ifdef OCCT_DEBUG
611     cout<<"filename="<<filename<<endl;
612 #endif
613
614     if ( ! filename || ! filename[0] ) {
615 #ifdef OCCT_DEBUG
616       cout << "Warning: STEPCAFControl_Reader::Transfer: Extern reference file name is empty" << endl;
617 #endif
618       continue; // not a valid extern ref
619     }
620
621     // compute true path to the extern file
622     TCollection_AsciiString fullname = OSD_Path::AbsolutePath ( dpath, filename );
623     if ( fullname.Length() <= 0 ) fullname = filename;
624
625 /*    
626     char fullname[1024];
627     char *mainfile = reader.WS()->LoadedFile();
628     if ( ! mainfile ) mainfile = "";
629     Standard_Integer slash = 0;
630     for ( Standard_Integer k=0; mainfile[k]; k++ )
631       if ( mainfile[k] == '/' ) slash = k;
632     strncpy ( fullname, mainfile, slash );
633     sprintf ( &fullname[slash], "%s%s", ( mainfile[0] ? "/" : "" ), filename );
634 */
635     
636     // get and check PD associated with the current extern ref
637     Handle(StepBasic_ProductDefinition) PD = ExtRefs.ProdDef(i);
638     if ( PD.IsNull() ) continue; // not a valid extern ref
639     if ( ! PDFileMap.IsBound ( PD ) ) continue; // this PD is not concerned by current transfer
640     
641     // read extern file (or use existing data) and record its data
642     Handle(STEPCAFControl_ExternFile) EF = 
643       ReadExternFile ( filename, fullname.ToCString(), doc );
644     PDFileMap.Bind ( PD, EF );
645   }
646   
647   // and insert them to the document
648   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( doc->Main() );
649   if ( STool.IsNull() ) return Standard_False;
650   XCAFDoc_DataMapOfShapeLabel map;
651   if ( asOne )
652     Lseq.Append ( AddShape ( reader.OneShape(), STool, NewShapesMap, ShapePDMap, PDFileMap, map ) );
653   else {
654     for ( i=1; i <= num; i++ ) {
655       Lseq.Append ( AddShape ( reader.Shape(i), STool, NewShapesMap, ShapePDMap, PDFileMap, map ) );
656     }
657   }
658   
659   // read colors
660   if ( GetColorMode() )
661     ReadColors ( reader.WS(), doc, PDFileMap, map );
662   
663   // read names
664   if ( GetNameMode() )
665     ReadNames ( reader.WS(), doc, PDFileMap, map );
666
667   // read validation props
668   if ( GetPropsMode() )
669     ReadValProps ( reader.WS(), doc, PDFileMap, map );
670
671   // read layers
672   if ( GetLayerMode() )
673     ReadLayers ( reader.WS(), doc );
674   
675   // read SHUO entities from STEP model
676   if ( GetSHUOMode() )
677     ReadSHUOs ( reader.WS(), doc, PDFileMap, map );
678
679   // read GDT entities from STEP model
680   if(GetGDTMode())
681     ReadGDTs(reader.WS(),doc);
682
683   // read Material entities from STEP model
684   if(GetMatMode())
685     ReadMaterials(reader.WS(),doc,SeqPDS);
686
687   // Expand resulting CAF structure for sub-shapes (optionally with their
688   // names) if requested
689   ExpandSubShapes(STool, map, ShapePDMap);
690
691   return Standard_True;
692 }
693
694 //=======================================================================
695 //function : AddShape
696 //purpose  : 
697 //=======================================================================
698
699 TDF_Label STEPCAFControl_Reader::AddShape (const TopoDS_Shape &S, 
700                                            const Handle(XCAFDoc_ShapeTool) &STool,
701                                            const TopTools_MapOfShape &NewShapesMap,
702                                            const STEPCAFControl_DataMapOfShapePD &ShapePDMap,
703                                            const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
704                                            XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
705 {
706   // if shape has already been mapped, just return corresponding label
707   if ( ShapeLabelMap.IsBound ( S ) ) {
708     return ShapeLabelMap.Find ( S );
709   }
710   
711   // if shape is located, create instance
712   if ( ! S.Location().IsIdentity() ) {
713     TopoDS_Shape S0 = S;
714     TopLoc_Location loc;
715     S0.Location ( loc );
716     AddShape ( S0, STool, NewShapesMap, ShapePDMap, PDFileMap, ShapeLabelMap );
717     TDF_Label L = STool->AddShape ( S, Standard_False ); // should create reference
718     ShapeLabelMap.Bind ( S, L );
719     return L;
720   }
721   
722   // if shape is not compound, simple add it
723   if ( S.ShapeType() != TopAbs_COMPOUND ) {
724     TDF_Label L = STool->AddShape ( S, Standard_False );
725     ShapeLabelMap.Bind ( S, L );
726     return L;
727   }
728   
729   // for compounds, compute number of subshapes and check whether this is assembly
730   Standard_Boolean isAssembly = Standard_False;
731   Standard_Integer nbComponents = 0;
732   TopoDS_Iterator it;
733   for ( it.Initialize(S); it.More(); it.Next(), nbComponents++ ) {
734     TopoDS_Shape Sub0 = it.Value();
735     TopLoc_Location loc;
736     Sub0.Location ( loc );
737     if ( NewShapesMap.Contains ( Sub0 ) ) isAssembly = Standard_True;
738   }
739
740 //  if(nbComponents>0) isAssembly = Standard_True;
741   
742   // check whether it has associated external ref
743   TColStd_SequenceOfHAsciiString SHAS;
744   if ( ShapePDMap.IsBound ( S ) && PDFileMap.IsBound ( ShapePDMap.Find(S) ) ) {
745     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( ShapePDMap.Find(S) );
746     if ( ! EF.IsNull() ) {
747       // (store information on extern refs in the document)
748       SHAS.Append(EF->GetName());
749       // if yes, just return corresponding label
750       if ( ! EF->GetLabel().IsNull() ) {
751         // but if components >0, ignore extern ref!
752         if ( nbComponents <=0 ) {
753           ShapeLabelMap.Bind ( S, EF->GetLabel() );
754           STool->SetExternRefs(EF->GetLabel(),SHAS);
755           return EF->GetLabel();
756         }
757       }
758 #ifdef OCCT_DEBUG
759       if ( ! EF->GetLabel().IsNull() )
760         cout << "Warning: STEPCAFControl_Reader::AddShape: Non-empty shape with external ref; ref is ignored" << endl;
761       else if ( nbComponents <=0 ) 
762         cout << "Warning: STEPCAFControl_Reader::AddShape: Result of reading extern ref is Null" << endl;
763 #endif
764     }
765   }
766   
767   // add compound either as a whole,
768   if ( ! isAssembly ) {
769     TDF_Label L = STool->AddShape ( S, Standard_False );
770     if ( SHAS.Length() >0 ) STool->SetExternRefs(L,SHAS);
771     ShapeLabelMap.Bind ( S, L );
772     return L;
773   }
774   
775   // or as assembly, component-by-component
776   TDF_Label L = STool->NewShape();
777   for ( it.Initialize(S); it.More(); it.Next(), nbComponents++ ) {
778     TopoDS_Shape Sub0 = it.Value();
779     TopLoc_Location loc;
780     Sub0.Location ( loc );
781     TDF_Label subL = AddShape ( Sub0, STool, NewShapesMap, ShapePDMap, PDFileMap, ShapeLabelMap );
782     if ( ! subL.IsNull() ) {
783       STool->AddComponent ( L, subL, it.Value().Location() );
784     }
785   }
786   if ( SHAS.Length() >0 ) STool->SetExternRefs(L,SHAS);
787   ShapeLabelMap.Bind ( S, L );
788   //STool->SetShape ( L, S ); // it is necessary for assemblies OCC1747 // commemted by skl for OCC2941
789
790   return L;
791 }
792
793 //=======================================================================
794 //function : ReadExternFile
795 //purpose  : 
796 //=======================================================================
797
798 Handle(STEPCAFControl_ExternFile) STEPCAFControl_Reader::ReadExternFile (const Standard_CString file, 
799                                                                          const Standard_CString fullname, 
800                                                                          Handle(TDocStd_Document)& doc) 
801 {
802   // if the file is already read, associate it with SDR
803   if ( myFiles->HasItem ( file, Standard_True ) ) {
804     return myFiles->Item ( file );
805   }
806
807 #ifdef OCCT_DEBUG
808   cout << "Reading extern file: " << fullname << endl;
809 #endif
810  
811   // create new WorkSession and Reader
812   Handle(XSControl_WorkSession) newWS = new XSControl_WorkSession;
813   newWS->SelectNorm ( "STEP" );
814   STEPControl_Reader sr ( newWS, Standard_False );
815   
816   // start to fill the resulting ExternFile structure
817   Handle(STEPCAFControl_ExternFile) EF = new STEPCAFControl_ExternFile;
818   EF->SetWS ( newWS );
819   EF->SetName ( new TCollection_HAsciiString ( file ) );
820   
821   // read file
822   EF->SetLoadStatus ( sr.ReadFile ( fullname ) );
823   
824   // transfer in single-result mode
825   if ( EF->GetLoadStatus() == IFSelect_RetDone ) {
826     TDF_LabelSequence labels;
827     EF->SetTransferStatus ( Transfer ( sr, 0, doc, labels, Standard_True ) );
828     if ( labels.Length() >0 ) EF->SetLabel ( labels.Value(1) );
829   }
830   
831   // add read file to dictionary
832   myFiles->SetItem ( file, EF );
833   
834   return EF;
835 }
836
837
838 //=======================================================================
839 //function : SetColorToSubshape
840 //purpose  : auxilary
841 //=======================================================================
842 static void SetColorToSubshape(const Handle(XCAFDoc_ColorTool) & CTool,
843                                const TopoDS_Shape & S,
844                                const Quantity_Color& col,
845                                const XCAFDoc_ColorType type)
846 {
847   for (TopoDS_Iterator it(S); it.More(); it.Next())
848     if (! CTool->SetColor( it.Value(), col, type)) break;
849 }
850
851
852 //=======================================================================
853 //function : findStyledSR
854 //purpose  : auxilary
855 //=======================================================================
856 static void findStyledSR (const Handle(StepVisual_StyledItem) &style,
857                           Handle(StepShape_ShapeRepresentation)& aSR)
858 {
859   // search Shape Represenatation for component styled item
860   for ( Standard_Integer j=1; j <= style->NbStyles(); j++ ) {
861     Handle(StepVisual_PresentationStyleByContext) PSA = 
862       Handle(StepVisual_PresentationStyleByContext)::DownCast(style->StylesValue ( j ));
863     if ( PSA.IsNull() )
864       continue;
865     StepVisual_StyleContextSelect aStyleCntxSlct = PSA->StyleContext();
866     Handle(StepShape_ShapeRepresentation) aCurrentSR = 
867       Handle(StepShape_ShapeRepresentation)::DownCast(aStyleCntxSlct.Representation());
868     if ( aCurrentSR.IsNull() )
869       continue;
870     aSR = aCurrentSR;
871       break;
872   }
873 }
874
875
876 //=======================================================================
877 //function : ReadColors
878 //purpose  : 
879 //=======================================================================
880
881 Standard_Boolean STEPCAFControl_Reader::ReadColors (const Handle(XSControl_WorkSession) &WS,
882                                                     Handle(TDocStd_Document)& Doc,
883                                                     const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
884                                                     const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
885 {
886   STEPConstruct_Styles Styles ( WS );
887   if ( ! Styles.LoadStyles() ) {
888 #ifdef OCCT_DEBUG
889     cout << "Warning: no styles are found in the model" << endl;
890 #endif
891     return Standard_False;
892   }
893   // searching for invisible items in the model
894   Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
895   Styles.LoadInvisStyles( aHSeqOfInvisStyle );
896   
897   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( Doc->Main() );
898   if ( CTool.IsNull() ) return Standard_False;
899
900   // parse and search for color attributes
901   Standard_Integer nb = Styles.NbStyles();
902   for ( Standard_Integer i=1; i <= nb; i++ ) {
903     Handle(StepVisual_StyledItem) style = Styles.Style ( i );
904     if ( style.IsNull() ) continue;
905     
906     Standard_Boolean IsVisible = Standard_True;
907     // check the visibility of styled item.
908     for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++ ) {
909       if ( style != aHSeqOfInvisStyle->Value( si ) )
910         continue;
911       // found that current style is invisible.
912       IsVisible = Standard_False;
913       break;
914     }
915
916     Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol;
917     // check if it is component style
918     Standard_Boolean IsComponent = Standard_False;
919     if ( ! Styles.GetColors ( style, SurfCol, BoundCol, CurveCol, IsComponent ) && IsVisible )
920       continue;
921     
922     // find shape
923     NCollection_Vector<Handle(MMgt_TShared)> anItems;
924     if (!style->Item().IsNull()) {
925       anItems.Append(style->Item());
926     }
927     else if (!style->ItemAP242().Representation().IsNull()){
928       //special case for AP242: item can be Reprsentation
929       Handle(StepRepr_Representation) aRepr = style->ItemAP242().Representation();
930       for (Standard_Integer j = 1; j <= aRepr->Items()->Length(); j++)
931         anItems.Append(aRepr->Items()->Value(j));
932     }
933     for (Standard_Integer itemIt = 0; itemIt < anItems.Length(); itemIt++) {
934       TopoDS_Shape S = STEPConstruct::FindShape ( Styles.TransientProcess(),
935         Handle(StepRepr_RepresentationItem)::DownCast(anItems.Value(itemIt)) );
936       Standard_Boolean isSkipSHUOstyle = Standard_False;
937       // take shape with real location.
938       while ( IsComponent ) {
939         // take SR of NAUO
940         Handle(StepShape_ShapeRepresentation) aSR;
941         findStyledSR( style, aSR );
942         // search for SR along model
943         if (aSR.IsNull())
944           break;
945         Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings( aSR );
946         Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
947         for (subs.Start(); subs.More(); subs.Next()) {
948           aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
949           if ( aSDR.IsNull() )
950             continue;
951           StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
952           Handle(StepRepr_ProductDefinitionShape) PDS = 
953             Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
954           if ( PDS.IsNull() )
955             continue;
956           StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
957           
958           Handle(StepRepr_AssemblyComponentUsage) ACU = 
959             Handle(StepRepr_AssemblyComponentUsage)::DownCast(aCharDef.ProductDefinitionRelationship());
960           // PTV 10.02.2003 skip styled item that refer to SHUO
961           if (ACU->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
962             isSkipSHUOstyle = Standard_True;
963             break;
964           }
965           Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO =
966             Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(ACU);
967           if ( NAUO.IsNull() )
968             continue;
969           
970           TopoDS_Shape aSh;
971           // PTV 10.02.2003 to find component of assembly CORRECTLY
972           STEPConstruct_Tool Tool( WS );
973           TDF_Label aShLab = FindInstance ( NAUO, CTool->ShapeTool(), Tool, PDFileMap, ShapeLabelMap );
974           aSh = CTool->ShapeTool()->GetShape(aShLab);
975           if (!aSh.IsNull()) {
976             S = aSh;
977             break;
978           }
979         }
980         break;
981       }
982       if (isSkipSHUOstyle)
983         continue; // skip styled item which refer to SHUO
984       
985       if ( S.IsNull() )
986         continue;
987       
988       if ( ! SurfCol.IsNull() ) {
989         Quantity_Color col;
990         Styles.DecodeColor ( SurfCol, col );
991         if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorSurf ))
992           SetColorToSubshape( CTool, S, col, XCAFDoc_ColorSurf );
993       }
994       if ( ! BoundCol.IsNull() ) {
995         Quantity_Color col;
996         Styles.DecodeColor ( BoundCol, col );
997         if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorCurv ))
998           SetColorToSubshape(  CTool, S, col, XCAFDoc_ColorCurv );
999       }
1000       if ( ! CurveCol.IsNull() ) {
1001         Quantity_Color col;
1002         Styles.DecodeColor ( CurveCol, col );
1003         if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorCurv ))
1004           SetColorToSubshape(  CTool, S, col, XCAFDoc_ColorCurv );
1005       }
1006       if ( !IsVisible ) {
1007         // sets the invisibility for shape.
1008         TDF_Label aInvL;
1009         if ( CTool->ShapeTool()->Search( S, aInvL ) )
1010           CTool->SetVisibility( aInvL, Standard_False );
1011       }
1012     }
1013   }
1014   CTool->ReverseChainsOfTreeNodes();
1015   return Standard_True;
1016 }
1017
1018 //=======================================================================
1019 //function : GetLabelFromPD
1020 //purpose  : 
1021 //=======================================================================
1022
1023 static TDF_Label GetLabelFromPD (const Handle(StepBasic_ProductDefinition) &PD,
1024                                  const Handle(XCAFDoc_ShapeTool) &STool,
1025                                  const Handle(Transfer_TransientProcess) &TP,
1026                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1027                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1028 {
1029   TDF_Label L;
1030   if ( PDFileMap.IsBound ( PD ) ) {
1031     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( PD );
1032     if ( ! EF.IsNull() ) {
1033       L = EF->GetLabel();
1034       if ( ! L.IsNull() ) return L;
1035     }
1036   }
1037
1038   TopoDS_Shape S;
1039   Handle(Transfer_Binder) binder = TP->Find(PD);
1040   if ( binder.IsNull() || ! binder->HasResult() ) return L;
1041   S = TransferBRep::ShapeResult ( TP, binder );
1042   if ( S.IsNull() ) return L;
1043
1044   if ( S.IsNull() ) return L;
1045   if ( ShapeLabelMap.IsBound ( S ) )
1046     L = ShapeLabelMap.Find ( S );
1047   if ( L.IsNull() )
1048     STool->Search ( S, L, Standard_True, Standard_True, Standard_False );
1049   return L;
1050 }
1051
1052 //=======================================================================
1053 //function : FindInstance
1054 //purpose  : 
1055 //=======================================================================
1056
1057 TDF_Label STEPCAFControl_Reader::FindInstance (const Handle(StepRepr_NextAssemblyUsageOccurrence) &NAUO,
1058                                                const Handle(XCAFDoc_ShapeTool) &STool,
1059                                                const STEPConstruct_Tool &Tool,
1060                                                const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1061                                                const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1062 {
1063   TDF_Label L;
1064   
1065   // get shape resulting from CDSR (in fact, only location is interesting)
1066   Handle(Transfer_TransientProcess) TP = Tool.TransientProcess();
1067   Handle(Transfer_Binder) binder = TP->Find(NAUO);
1068   if ( binder.IsNull() || ! binder->HasResult() ) {
1069 #ifdef OCCT_DEBUG
1070     cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << endl;
1071 #endif
1072     return L;
1073   }
1074   
1075   TopoDS_Shape S = TransferBRep::ShapeResult ( TP, binder );
1076   if ( S.IsNull() ) {
1077 #ifdef OCCT_DEBUG
1078     cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << endl;
1079 #endif
1080     return L;
1081   }
1082
1083   // find component`s original label
1084   Handle(StepBasic_ProductDefinition) PD = NAUO->RelatedProductDefinition();
1085   if ( PD.IsNull() ) return L;
1086   TDF_Label Lref = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
1087   if ( Lref.IsNull() ) return L;
1088   
1089   // find main shape (assembly) label
1090   PD.Nullify();
1091   PD = NAUO->RelatingProductDefinition();
1092   if ( PD.IsNull() ) return L;
1093   TDF_Label L0 = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
1094   if ( L0.IsNull() ) return L;
1095   
1096   // if CDSR and NAUO are reversed, swap labels
1097   Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1098   Interface_EntityIterator subs1 = Tool.Graph().Sharings(NAUO);
1099   for (subs1.Start(); subs1.More(); subs1.Next()) {
1100     Handle(StepRepr_ProductDefinitionShape) PDS = 
1101       Handle(StepRepr_ProductDefinitionShape)::DownCast(subs1.Value());
1102     if(PDS.IsNull()) continue;
1103     Interface_EntityIterator subs2 = Tool.Graph().Sharings(PDS);
1104     for (subs2.Start(); subs2.More(); subs2.Next()) {
1105       Handle(StepShape_ContextDependentShapeRepresentation) CDSRtmp = 
1106         Handle(StepShape_ContextDependentShapeRepresentation)::DownCast(subs2.Value());
1107       if (CDSRtmp.IsNull()) continue;
1108       CDSR = CDSRtmp;
1109     }
1110   }
1111   if (CDSR.IsNull()) return L;
1112 //  if ( STEPConstruct_Assembly::CheckSRRReversesNAUO ( Tool.Model(), CDSR ) ) {
1113 //    TDF_Label Lsw = L0; L0 = Lref; Lref = Lsw;
1114 //  }
1115   
1116   // iterate on components to find proper one
1117   TDF_LabelSequence seq;
1118   XCAFDoc_ShapeTool::GetComponents ( L0, seq );
1119   for ( Standard_Integer k=1; L.IsNull() && k <= seq.Length(); k++ ) {
1120     TDF_Label Lcomp = seq(k), Lref2;
1121     if ( XCAFDoc_ShapeTool::GetReferredShape ( Lcomp, Lref2 ) && 
1122         Lref2 == Lref &&
1123         S.Location() == XCAFDoc_ShapeTool::GetLocation ( Lcomp ) ) 
1124       L = Lcomp;
1125   }
1126   
1127   return L;
1128 }
1129
1130 //=======================================================================
1131 //function : ReadNames
1132 //purpose  : 
1133 //=======================================================================
1134
1135 Standard_Boolean STEPCAFControl_Reader::ReadNames (const Handle(XSControl_WorkSession) &WS,
1136                                                    Handle(TDocStd_Document)& Doc,
1137                                                    const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1138                                                    const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1139 {
1140   // get starting data
1141   const Handle(Interface_InterfaceModel) &Model = WS->Model();
1142   const Handle(XSControl_TransferReader) &TR = WS->TransferReader();
1143   const Handle(Transfer_TransientProcess) &TP = TR->TransientProcess();
1144   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1145   if ( STool.IsNull() ) return Standard_False;
1146   STEPConstruct_Tool Tool ( WS );
1147
1148   // iterate on model to find all SDRs and CDSRs
1149   Standard_Integer nb = Model->NbEntities();
1150   Handle(Standard_Type) tNAUO = STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence);
1151   Handle(Standard_Type) tPD  = STANDARD_TYPE(StepBasic_ProductDefinition);
1152   Handle(TCollection_HAsciiString) name;
1153   TDF_Label L;
1154   for (Standard_Integer i = 1; i <= nb; i++) {
1155     Handle(Standard_Transient) enti = Model->Value(i);
1156
1157     // get description of NAUO
1158     if ( enti->DynamicType() == tNAUO ) {
1159       L.Nullify();
1160       Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO = 
1161         Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(enti);
1162       if(NAUO.IsNull()) continue;
1163       Interface_EntityIterator subs = WS->Graph().Sharings(NAUO);
1164       for (subs.Start(); subs.More(); subs.Next()) {
1165         Handle(StepRepr_ProductDefinitionShape) PDS = 
1166           Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
1167         if(PDS.IsNull()) continue;
1168         Handle(StepBasic_ProductDefinitionRelationship) PDR = PDS->Definition().ProductDefinitionRelationship();
1169         if ( PDR.IsNull() ) continue;
1170         if ( PDR->HasDescription() && 
1171             PDR->Description()->UsefullLength() >0 ) name = PDR->Description();
1172         else if ( !PDR->Name().IsNull() && PDR->Name()->UsefullLength() >0 ) name = PDR->Name();
1173         else if ( !PDR->Id().IsNull()) name = PDR->Id();
1174         else name = new TCollection_HAsciiString;
1175       }
1176       // find proper label
1177       L = FindInstance ( NAUO, STool, Tool, PDFileMap, ShapeLabelMap );
1178       if ( L.IsNull() ) continue;
1179       TCollection_ExtendedString str ( name->String() );
1180       TDataStd_Name::Set ( L, str );
1181     }
1182
1183     // for PD get name of associated product
1184     if ( enti->DynamicType() == tPD ) {
1185       L.Nullify();
1186       Handle(StepBasic_ProductDefinition) PD = 
1187         Handle(StepBasic_ProductDefinition)::DownCast(enti);
1188       if(PD.IsNull()) continue;
1189       Handle(StepBasic_Product) Prod = (!PD->Formation().IsNull() ? PD->Formation()->OfProduct() : NULL);
1190       if (Prod.IsNull())
1191         name = new TCollection_HAsciiString;
1192       else if (!Prod->Name().IsNull() && Prod->Name()->UsefullLength() > 0) 
1193         name = Prod->Name();
1194       else if (!Prod->Id().IsNull()) 
1195         name = Prod->Id();
1196       else 
1197         name = new TCollection_HAsciiString;
1198       L = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
1199       if ( L.IsNull() ) continue;
1200       TCollection_ExtendedString str ( name->String() );
1201       TDataStd_Name::Set ( L, str );
1202     }
1203     // set a name to the document
1204     //TCollection_ExtendedString str ( name->String() );
1205     //TDataStd_Name::Set ( L, str );
1206   }
1207
1208   return Standard_True;
1209 }
1210
1211 //=======================================================================
1212 //function : GetLabelFromPD
1213 //purpose  : 
1214 //=======================================================================
1215
1216 static TDF_Label GetLabelFromPD (const Handle(StepBasic_ProductDefinition) &PD,
1217                                  const Handle(XCAFDoc_ShapeTool) &STool,
1218                                  const STEPConstruct_ValidationProps &Props,
1219                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1220                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1221 {
1222   TDF_Label L;
1223   if ( PDFileMap.IsBound ( PD ) ) {
1224     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( PD );
1225     if ( ! EF.IsNull() ) {
1226       L = EF->GetLabel();
1227       if ( ! L.IsNull() ) return L;
1228     }
1229   }
1230   TopoDS_Shape S = Props.GetPropShape ( PD );
1231   if ( S.IsNull() ) return L;
1232   if ( ShapeLabelMap.IsBound ( S ) )
1233     L = ShapeLabelMap.Find ( S );
1234   if ( L.IsNull() )
1235     STool->Search ( S, L, Standard_True, Standard_True, Standard_False );
1236   return L;
1237 }
1238
1239 //=======================================================================
1240 //function : ReadValProps
1241 //purpose  : 
1242 //=======================================================================
1243
1244 Standard_Boolean STEPCAFControl_Reader::ReadValProps (const Handle(XSControl_WorkSession) &WS,
1245                                                       Handle(TDocStd_Document)& Doc,
1246                                                       const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1247                                                       const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1248 {
1249   // get starting data
1250   const Handle(XSControl_TransferReader) &TR = WS->TransferReader();
1251   const Handle(Transfer_TransientProcess) &TP = TR->TransientProcess();
1252   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1253   if ( STool.IsNull() ) return Standard_False;
1254
1255   // load props from the STEP model
1256   TColStd_SequenceOfTransient props;
1257   STEPConstruct_ValidationProps Props ( WS );
1258   if ( ! Props.LoadProps ( props ) ) {
1259 #ifdef OCCT_DEBUG
1260     cout << "Warning: no validation props found in the model" << endl;
1261 #endif
1262     return Standard_False;
1263   }
1264
1265   // interpret props one by one
1266   for (Standard_Integer i = 1; i <= props.Length(); i ++) {
1267     Handle(StepRepr_PropertyDefinitionRepresentation) PDR = 
1268       Handle(StepRepr_PropertyDefinitionRepresentation)::DownCast ( props.Value(i) );
1269     if ( PDR.IsNull() ) continue;
1270
1271     TDF_Label L;
1272
1273     Handle(StepRepr_PropertyDefinition) PD = PDR->Definition().PropertyDefinition();
1274     Interface_EntityIterator subs = Props.Graph().Shareds(PD);
1275     for (subs.Start(); L.IsNull() && subs.More(); subs.Next()) {
1276       if ( subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape)) ) {
1277         Handle(StepRepr_ProductDefinitionShape) PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
1278         if(PDS.IsNull()) continue;
1279         // find corresponding NAUO
1280         Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO;
1281         Interface_EntityIterator subs1 = Props.Graph().Shareds(PDS);
1282         for (subs1.Start(); NAUO.IsNull() && subs1.More(); subs1.Next()) {
1283           if ( subs1.Value()->IsKind(STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence)) ) 
1284             NAUO = Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subs1.Value());
1285         }
1286         if ( !NAUO.IsNull() ) {
1287           L = FindInstance ( NAUO, STool, WS, PDFileMap, ShapeLabelMap );
1288           if ( L.IsNull() ) continue;
1289         }
1290         else {
1291           // find corresponding ProductDefinition:
1292           Handle(StepBasic_ProductDefinition) ProdDef;
1293           Interface_EntityIterator subsPDS = Props.Graph().Shareds(PDS);
1294           for (subsPDS.Start(); ProdDef.IsNull() && subsPDS.More(); subsPDS.Next()) {
1295             if ( subsPDS.Value()->IsKind(STANDARD_TYPE(StepBasic_ProductDefinition)) ) 
1296               ProdDef = Handle(StepBasic_ProductDefinition)::DownCast(subsPDS.Value());
1297           }
1298           if ( ProdDef.IsNull() ) continue;
1299           L = GetLabelFromPD ( ProdDef, STool, Props, PDFileMap, ShapeLabelMap );
1300         }
1301       }
1302
1303       if ( subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)) ) {
1304         Handle(StepRepr_ShapeAspect) SA = Handle(StepRepr_ShapeAspect)::DownCast(subs.Value());
1305         if(SA.IsNull()) continue;
1306         // find ShapeRepresentation
1307         Handle(StepShape_ShapeRepresentation) SR;
1308         Interface_EntityIterator subs1 = Props.Graph().Sharings(SA);
1309         for(subs1.Start(); subs1.More() && SR.IsNull(); subs1.Next()) {
1310           Handle(StepRepr_PropertyDefinition) PropD1 = 
1311             Handle(StepRepr_PropertyDefinition)::DownCast(subs1.Value());
1312           if(PropD1.IsNull()) continue;
1313           Interface_EntityIterator subs2 = Props.Graph().Sharings(PropD1);
1314           for(subs2.Start(); subs2.More() && SR.IsNull(); subs2.Next()) {
1315             Handle(StepShape_ShapeDefinitionRepresentation) SDR =
1316               Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs2.Value());
1317             if(SDR.IsNull()) continue;
1318             SR = Handle(StepShape_ShapeRepresentation)::DownCast(SDR->UsedRepresentation());
1319           }
1320         }
1321         if(SR.IsNull()) continue;
1322         Handle(Transfer_Binder) binder;
1323         for(Standard_Integer ir=1; ir<=SR->NbItems() && binder.IsNull(); ir++) {
1324           if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_SolidModel))) {
1325             Handle(StepShape_SolidModel) SM = 
1326               Handle(StepShape_SolidModel)::DownCast(SR->ItemsValue(ir));
1327             binder = TP->Find(SM);
1328           }
1329           else if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_ShellBasedSurfaceModel))) {
1330             Handle(StepShape_ShellBasedSurfaceModel) SBSM =
1331               Handle(StepShape_ShellBasedSurfaceModel)::DownCast(SR->ItemsValue(ir));
1332             binder = TP->Find(SBSM);
1333           }
1334           else if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_GeometricSet))) {
1335             Handle(StepShape_GeometricSet) GS =
1336               Handle(StepShape_GeometricSet)::DownCast(SR->ItemsValue(ir));
1337             binder = TP->Find(GS);
1338           }
1339         }
1340         if ( binder.IsNull() || ! binder->HasResult() ) continue;
1341         TopoDS_Shape S;
1342         S = TransferBRep::ShapeResult ( TP, binder );
1343         if(S.IsNull()) continue;
1344         if ( ShapeLabelMap.IsBound ( S ) )
1345           L = ShapeLabelMap.Find ( S );
1346         if ( L.IsNull() )
1347           STool->Search ( S, L, Standard_True, Standard_True, Standard_True );
1348       }
1349     }
1350
1351     if(L.IsNull()) continue;
1352       
1353     // decode validation properties
1354     Handle(StepRepr_Representation) rep = PDR->UsedRepresentation();
1355     for ( Standard_Integer j=1; j <= rep->NbItems(); j++ ) {
1356       Handle(StepRepr_RepresentationItem) ent = rep->ItemsValue(j);
1357       Standard_Boolean isArea;
1358       Standard_Real val;
1359       gp_Pnt pos;
1360       if ( Props.GetPropReal ( ent, val, isArea ) ) {
1361         if ( isArea ) XCAFDoc_Area::Set ( L, val );
1362         else XCAFDoc_Volume::Set ( L, val );
1363       }
1364       else if ( Props.GetPropPnt ( ent, rep->ContextOfItems(), pos ) ) {
1365         XCAFDoc_Centroid::Set ( L, pos );
1366       }
1367     }
1368   }
1369   return Standard_True;
1370 }
1371
1372 //=======================================================================
1373 //function : ReadLayers
1374 //purpose  : 
1375 //=======================================================================
1376
1377 Standard_Boolean STEPCAFControl_Reader::ReadLayers (const Handle(XSControl_WorkSession) &WS,
1378                                                     Handle(TDocStd_Document)& Doc) const
1379 {
1380   const Handle(Interface_InterfaceModel) &Model = WS->Model();
1381   const Handle(XSControl_TransferReader) &TR = WS->TransferReader();
1382   const Handle(Transfer_TransientProcess) &TP = TR->TransientProcess();
1383   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1384   if ( STool.IsNull() ) return Standard_False;
1385   Handle(XCAFDoc_LayerTool) LTool = XCAFDoc_DocumentTool::LayerTool( Doc->Main() );
1386   if ( LTool.IsNull() ) return Standard_False;
1387   
1388   Handle(Standard_Type) tSVPLA = STANDARD_TYPE(StepVisual_PresentationLayerAssignment);
1389   Standard_Integer nb = Model->NbEntities();
1390   Handle(TCollection_HAsciiString) name;
1391   
1392   for (Standard_Integer i = 1; i <= nb; i ++) {
1393     Handle(Standard_Transient) enti = Model->Value(i);
1394     if ( ! enti->IsKind ( tSVPLA ) ) continue;
1395     Handle(StepVisual_PresentationLayerAssignment) SVPLA = 
1396       Handle(StepVisual_PresentationLayerAssignment)::DownCast(enti);
1397     
1398     Handle(TCollection_HAsciiString) descr = SVPLA->Description();
1399     Handle(TCollection_HAsciiString) hName = SVPLA->Name();
1400     TCollection_ExtendedString aLayerName ( hName->String() );
1401      
1402     // find a target shape and its label in the document
1403     for (Standard_Integer j = 1; j <= SVPLA->NbAssignedItems(); j++ ) {
1404       StepVisual_LayeredItem LI = SVPLA->AssignedItemsValue(j);
1405       Handle(Transfer_Binder) binder = TP->Find( LI.Value() );
1406       if ( binder.IsNull() || ! binder->HasResult() ) continue;
1407       
1408       TopoDS_Shape S = TransferBRep::ShapeResult ( TP, binder );
1409       if ( S.IsNull() ) continue;
1410         
1411       TDF_Label shL;
1412       if ( ! STool->Search ( S, shL, Standard_True, Standard_True, Standard_True ) ) continue;
1413       LTool->SetLayer ( shL, aLayerName );
1414     }
1415     
1416     // check invisibility
1417     Interface_EntityIterator subs = WS->Graph().Sharings(SVPLA);
1418     for (subs.Start(); subs.More(); subs.Next()) {
1419       if ( ! subs.Value()->IsKind(STANDARD_TYPE(StepVisual_Invisibility)) ) continue;
1420 #ifdef OCCT_DEBUG
1421       cout<< "\tLayer \"" << aLayerName << "\" is invisible"<<endl;
1422 #endif
1423       //TDF_Label InvLayerLab = LTool->FindLayer(aLayerName);
1424       TDF_Label InvLayerLab = LTool->AddLayer(aLayerName); //skl for OCC3926
1425       Handle(TDataStd_UAttribute) aUAttr;
1426       aUAttr->Set( InvLayerLab, XCAFDoc::InvisibleGUID() );
1427     }
1428   }
1429   return Standard_True;
1430 }
1431
1432 //=======================================================================
1433 //function : ReadSHUOs
1434 //purpose  : 
1435 //=======================================================================
1436
1437 static Standard_Boolean findNextSHUOlevel (const Handle(XSControl_WorkSession) &WS,
1438                                            const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1439                                            const Handle(XCAFDoc_ShapeTool)& STool,
1440                                            const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1441                                            const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap,
1442                                            TDF_LabelSequence& aLabels)
1443 {
1444   Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings(SHUO);
1445   Handle(StepRepr_SpecifiedHigherUsageOccurrence) subSHUO;
1446   for (subs.Start(); subs.More(); subs.Next()) {
1447     if (subs.Value()->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
1448       subSHUO = Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(subs.Value());
1449       break;
1450     }
1451   }
1452   if (subSHUO.IsNull())
1453     return Standard_False;
1454   
1455   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO = subSHUO->NextUsage();
1456   if (NUNAUO.IsNull())
1457     return Standard_False;
1458 //   Handle(Interface_InterfaceModel) Model = WS->Model();
1459 //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1460 //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1461 //   Handle(Transfer_Binder) binder = TP->Find(NUNAUO);
1462 //   if ( binder.IsNull() || ! binder->HasResult() )
1463 //     return Standard_False;
1464 //   TopoDS_Shape NUSh = TransferBRep::ShapeResult ( TP, binder );
1465   // get label of NAUO next level
1466   TDF_Label NULab;
1467   STEPConstruct_Tool Tool( WS );
1468   NULab = STEPCAFControl_Reader::FindInstance ( NUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1469 //   STool->Search(NUSh, NUlab);
1470   if (NULab.IsNull())
1471     return Standard_False;
1472   aLabels.Append( NULab );
1473   // and check by recurse.
1474   findNextSHUOlevel( WS, subSHUO, STool, PDFileMap, ShapeLabelMap, aLabels );
1475   return Standard_True;
1476 }
1477
1478
1479 //=======================================================================
1480 //function : setSHUOintoDoc
1481 //purpose  : auxilary
1482 //=======================================================================
1483 static TDF_Label setSHUOintoDoc (const Handle(XSControl_WorkSession) &WS,
1484                                  const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1485                                  const Handle(XCAFDoc_ShapeTool)& STool,
1486                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1487                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1488 {
1489   TDF_Label aMainLabel;
1490   // get upper usage NAUO from SHUO.
1491   Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO =
1492     Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(SHUO->UpperUsage());
1493   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO = SHUO->NextUsage();
1494   if ( UUNAUO.IsNull() || NUNAUO.IsNull() ) {
1495 #ifdef OCCT_DEBUG
1496     cout << "Warning: " << __FILE__ <<": Upper_usage or Next_usage of styled SHUO is null. Skip it" << endl;
1497 #endif
1498     return aMainLabel;
1499   }
1500 //   Handle(Interface_InterfaceModel) Model = WS->Model();
1501 //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1502 //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1503 //   TopoDS_Shape UUSh, NUSh;
1504 //   Handle(Transfer_Binder) binder = TP->Find(UUNAUO);
1505 //   if ( binder.IsNull() || ! binder->HasResult() )
1506 //     return aMainLabel;
1507 //   UUSh = TransferBRep::ShapeResult ( TP, binder );
1508 //   binder = TP->Find(NUNAUO);
1509 //   if ( binder.IsNull() || ! binder->HasResult() )
1510 //     return aMainLabel;
1511 //   NUSh = TransferBRep::ShapeResult ( TP, binder );
1512
1513   // get first labels for first SHUO attribute
1514   TDF_Label UULab, NULab;
1515   STEPConstruct_Tool Tool( WS );
1516   UULab = STEPCAFControl_Reader::FindInstance ( UUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1517   NULab = STEPCAFControl_Reader::FindInstance ( NUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1518   
1519 //   STool->Search(UUSh, UULab);
1520 //   STool->Search(NUSh, NULab);
1521   if (UULab.IsNull() || NULab.IsNull()) return aMainLabel;
1522   //create sequence fo labels to set SHUO structure into the document
1523   TDF_LabelSequence ShuoLabels;
1524   ShuoLabels.Append( UULab );
1525   ShuoLabels.Append( NULab );
1526   // add all other labels of sub SHUO entities
1527   findNextSHUOlevel( WS, SHUO, STool, PDFileMap, ShapeLabelMap, ShuoLabels );
1528   // last accord for SHUO
1529   Handle(XCAFDoc_GraphNode) anSHUOAttr;
1530   if ( STool->SetSHUO( ShuoLabels, anSHUOAttr ) )
1531     aMainLabel = anSHUOAttr->Label();
1532   
1533   return aMainLabel;
1534 }
1535
1536
1537 //=======================================================================
1538 //function : ReadSHUOs
1539 //purpose  : 
1540 //=======================================================================
1541
1542 Standard_Boolean STEPCAFControl_Reader::ReadSHUOs (const Handle(XSControl_WorkSession) &WS,
1543                                                    Handle(TDocStd_Document)& Doc,
1544                                                    const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1545                                                    const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1546 {
1547   // the big part code duplication from ReadColors.
1548   // It is possible to share this code functionality, just to decide how ???
1549   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( Doc->Main() );
1550   Handle(XCAFDoc_ShapeTool) STool = CTool->ShapeTool();
1551   
1552   STEPConstruct_Styles Styles ( WS );
1553   if ( ! Styles.LoadStyles() ) {
1554 #ifdef OCCT_DEBUG
1555     cout << "Warning: no styles are found in the model" << endl;
1556 #endif
1557     return Standard_False;
1558   }
1559   // searching for invisible items in the model
1560   Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
1561   Styles.LoadInvisStyles( aHSeqOfInvisStyle );
1562   // parse and search for color attributes
1563   Standard_Integer nb = Styles.NbStyles();
1564   for ( Standard_Integer i=1; i <= nb; i++ ) {
1565     Handle(StepVisual_StyledItem) style = Styles.Style ( i );
1566     if ( style.IsNull() ) continue;
1567     
1568     Standard_Boolean IsVisible = Standard_True;
1569     // check the visibility of styled item.
1570     for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++ ) {
1571       if ( style != aHSeqOfInvisStyle->Value( si ) )
1572         continue;
1573       // found that current style is invisible.
1574 #ifdef OCCT_DEBUG
1575       cout << "Warning: item No " << i << "(" << style->Item()->DynamicType()->Name() << ") is invisible" << endl;
1576 #endif
1577       IsVisible = Standard_False;
1578       break;
1579     }
1580
1581     Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol;
1582     // check if it is component style
1583     Standard_Boolean IsComponent = Standard_False;
1584     if ( ! Styles.GetColors ( style, SurfCol, BoundCol, CurveCol, IsComponent ) && IsVisible )
1585       continue;
1586     if (!IsComponent)
1587       continue;
1588     Handle(StepShape_ShapeRepresentation) aSR;
1589     findStyledSR( style, aSR );
1590     // search for SR along model
1591     if ( aSR.IsNull() )
1592       continue;
1593     Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings( aSR );
1594     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
1595     for (subs.Start(); subs.More(); subs.Next()) {
1596       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
1597       if ( aSDR.IsNull() )
1598         continue;
1599       StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
1600       Handle(StepRepr_ProductDefinitionShape) PDS = 
1601         Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
1602       if ( PDS.IsNull() )
1603         continue;
1604       StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
1605       Handle(StepRepr_SpecifiedHigherUsageOccurrence) SHUO =
1606         Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(aCharDef.ProductDefinitionRelationship());
1607       if ( SHUO.IsNull() )
1608         continue;
1609       
1610       // set the SHUO structure to the document
1611       TDF_Label aLabelForStyle = setSHUOintoDoc( WS, SHUO, STool, PDFileMap, ShapeLabelMap );
1612       if ( aLabelForStyle.IsNull() ) {
1613 #ifdef OCCT_DEBUG
1614         cout << "Warning: " << __FILE__ <<": coudnot create SHUO structure in the document" << endl;
1615 #endif
1616         continue;
1617       }
1618       // now set the style to the SHUO main label.
1619       if ( ! SurfCol.IsNull() ) {
1620         Quantity_Color col;
1621         Styles.DecodeColor ( SurfCol, col );
1622         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorSurf );
1623       }
1624       if ( ! BoundCol.IsNull() ) {
1625         Quantity_Color col;
1626         Styles.DecodeColor ( BoundCol, col );
1627         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorCurv );
1628       }
1629       if ( ! CurveCol.IsNull() ) {
1630         Quantity_Color col;
1631         Styles.DecodeColor ( CurveCol, col );
1632         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorCurv );
1633       }
1634       if ( !IsVisible )
1635         // sets the invisibility for shape.
1636         CTool->SetVisibility( aLabelForStyle, Standard_False );
1637       
1638     } // end search SHUO by SDR
1639   } // end iterates on styles
1640       
1641   return Standard_True;
1642 }
1643
1644
1645 //=======================================================================
1646 //function : GetLengthConversionFactor
1647 //purpose  : 
1648 //=======================================================================
1649 static Standard_Boolean GetLengthConversionFactor(const Handle(StepBasic_NamedUnit)& NU,
1650                                                   Standard_Real& afact)
1651 {
1652   afact=1.;
1653   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndLengthUnit)) ) return Standard_False;
1654   Handle(StepBasic_ConversionBasedUnitAndLengthUnit) CBULU =
1655     Handle(StepBasic_ConversionBasedUnitAndLengthUnit)::DownCast(NU);
1656   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBULU->ConversionFactor();
1657   afact = MWUCBU->ValueComponent();
1658   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1659   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1660     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1661     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1662       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1663       if(SU->Name()==StepBasic_sunMetre) {
1664         if(SU->HasPrefix()) 
1665           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1666         // convert m to mm
1667         afact *= 1000.;
1668       }
1669     }
1670   }
1671   return Standard_True;
1672 }
1673
1674 //=======================================================================
1675 //function : GetLengthConversionFactorFromContext
1676 //purpose  : 
1677 //=======================================================================
1678 static Standard_Boolean GetLengthConversionFactorFromContext(const Handle(StepRepr_RepresentationContext)& theRC,
1679                                                              Standard_Real& theFact)
1680 {
1681   theFact = 1;
1682   if (theRC.IsNull())
1683     return Standard_False;
1684   Handle(StepBasic_ConversionBasedUnitAndLengthUnit) aSiLU;
1685   Handle(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext) aCtx =
1686     Handle(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext)::DownCast(theRC);
1687   if (!aCtx.IsNull()) {
1688     for (Standard_Integer j = 1; j <= aCtx->NbUnits(); j++) {
1689       if (aCtx->UnitsValue(j)->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndLengthUnit))) {
1690         aSiLU = Handle(StepBasic_ConversionBasedUnitAndLengthUnit)::DownCast(aCtx->UnitsValue(j));
1691         break;
1692       }
1693     }
1694   }
1695   if (aSiLU.IsNull()) {
1696     Handle(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx) aCtx1 =
1697       Handle(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx)::DownCast(theRC);
1698     if (!aCtx1.IsNull()) {
1699       for (Standard_Integer j = 1; j <= aCtx1->NbUnits(); j++) {
1700         if (aCtx1->UnitsValue(j)->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndLengthUnit))) {
1701           aSiLU = Handle(StepBasic_ConversionBasedUnitAndLengthUnit)::DownCast(aCtx1->UnitsValue(j));
1702           break;
1703         }
1704       }
1705     }
1706   }
1707   if (aSiLU.IsNull())
1708     return Standard_False;
1709   return GetLengthConversionFactor(aSiLU, theFact);
1710   
1711 }
1712
1713 //=======================================================================
1714 //function : GetAngleConversionFactor
1715 //purpose  : 
1716 //=======================================================================
1717 static Standard_Boolean GetAngleConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1718                                                   Standard_Real& afact)
1719 {
1720   afact=1.;
1721   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndPlaneAngleUnit)) ) return Standard_False;
1722   Handle(StepBasic_ConversionBasedUnitAndPlaneAngleUnit) CBULU =
1723     Handle(StepBasic_ConversionBasedUnitAndPlaneAngleUnit)::DownCast(NU);
1724   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBULU->ConversionFactor();
1725   afact = MWUCBU->ValueComponent();
1726   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1727   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1728     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1729     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1730       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1731       if(SU->Name()==StepBasic_sunRadian) {
1732         if(SU->HasPrefix()) 
1733           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1734         // convert radian to deg
1735         afact *= 180/M_PI;
1736       }
1737     }
1738   }
1739   return Standard_True;
1740 }
1741
1742 //=======================================================================
1743 //function : GetMassConversionFactor
1744 //purpose  : 
1745 //=======================================================================
1746 static Standard_Boolean GetMassConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1747                                                 Standard_Real& afact)
1748 {
1749   afact=1.;
1750   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndMassUnit)) ) return Standard_False;
1751   Handle(StepBasic_ConversionBasedUnitAndMassUnit) CBUMU =
1752     Handle(StepBasic_ConversionBasedUnitAndMassUnit)::DownCast(NU);
1753   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBUMU->ConversionFactor();
1754   afact = MWUCBU->ValueComponent();
1755   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1756   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1757     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1758     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1759       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1760       if(SU->Name()==StepBasic_sunGram) {
1761         if(SU->HasPrefix())
1762           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1763       }
1764     }
1765   }
1766   return Standard_True;
1767 }
1768 //=======================================================================
1769 //function : readPMIPresentation
1770 //purpose  : read polyline or tessellated presentation for 
1771 // (Annotation_Curve_Occurrence or Draughting_Callout)
1772 //=======================================================================
1773 Standard_Boolean readPMIPresentation(const Handle(Standard_Transient)& thePresentEntity,
1774                                      const Handle(XSControl_TransferReader)& theTR,
1775                                      const Standard_Real theFact,
1776                                      TopoDS_Shape& thePresentation, 
1777                                      Handle(TCollection_HAsciiString)& thePresentName, 
1778                                      Bnd_Box& theBox)
1779 {
1780   Handle(Transfer_TransientProcess) aTP = theTR->TransientProcess();
1781   Handle(StepVisual_AnnotationCurveOccurrence) anACO;
1782   NCollection_Vector<Handle(StepVisual_StyledItem)> anAnnotations;
1783   if (thePresentEntity->IsKind(STANDARD_TYPE(StepVisual_AnnotationCurveOccurrence)))
1784   {
1785     anACO = Handle(StepVisual_AnnotationCurveOccurrence)::DownCast(thePresentEntity);
1786     thePresentName = anACO->Name();
1787     if (!anACO.IsNull())
1788       anAnnotations.Append(anACO);
1789   }
1790   else if (thePresentEntity->IsKind(STANDARD_TYPE(StepVisual_DraughtingCallout)))
1791   {
1792     Handle(StepVisual_DraughtingCallout) aDCallout =
1793       Handle(StepVisual_DraughtingCallout)::DownCast(thePresentEntity);
1794     thePresentName = aDCallout->Name();
1795     for (Standard_Integer i = 1; i <= aDCallout->NbContents() && anACO.IsNull(); i++) {
1796       anACO = aDCallout->ContentsValue(i).AnnotationCurveOccurrence();
1797       if (!anACO.IsNull())
1798       {
1799         anAnnotations.Append(anACO);
1800         continue;
1801       }
1802       Handle(StepVisual_TessellatedAnnotationOccurrence) aTesselation =
1803         aDCallout->ContentsValue(i).TessellatedAnnotationOccurrence();
1804       if (!aTesselation.IsNull())
1805         anAnnotations.Append(aTesselation);
1806     }
1807   }
1808
1809   if (!anAnnotations.Length())
1810     return Standard_False;
1811
1812
1813   BRep_Builder aB;
1814   TopoDS_Compound aResAnnotation;
1815   aB.MakeCompound(aResAnnotation);
1816
1817   Standard_Integer i = 0;
1818   Bnd_Box aBox;
1819   Standard_Integer nbShapes = 0;
1820   for (; i < anAnnotations.Length(); i++)
1821   {
1822     Handle(StepVisual_StyledItem) anItem = anAnnotations(i);
1823     anACO = Handle(StepVisual_AnnotationCurveOccurrence)::DownCast(anItem);
1824     TopoDS_Shape anAnnotationShape;
1825     if (!anACO.IsNull())
1826     {
1827       Handle(StepRepr_RepresentationItem) aCurveItem = anACO->Item();
1828       anAnnotationShape = STEPConstruct::FindShape(aTP, aCurveItem);
1829       if (anAnnotationShape.IsNull())
1830       {
1831         Handle(Transfer_Binder) binder = theTR->Actor()->Transfer(aCurveItem, aTP);
1832         if (!binder.IsNull() && binder->HasResult()) {
1833           anAnnotationShape = TransferBRep::ShapeResult(aTP, binder);
1834         }
1835       }
1836     }
1837     //case of tessellated entities
1838     else
1839     {
1840       Handle(StepRepr_RepresentationItem) aTessItem = anItem->Item();
1841       if (aTessItem.IsNull())
1842         continue;
1843       Handle(StepVisual_TessellatedGeometricSet) aTessSet = Handle(StepVisual_TessellatedGeometricSet)::DownCast(aTessItem);
1844       if (aTessSet.IsNull())
1845         continue;
1846       NCollection_Handle<StepVisual_Array1OfTessellatedItem> aListItems = aTessSet->Items();
1847       Standard_Integer nb = aListItems.IsNull() ? 0 : aListItems->Length();
1848       Handle(StepVisual_TessellatedCurveSet) aTessCurve;
1849       for (Standard_Integer n = 1; n <= nb && aTessCurve.IsNull(); n++)
1850       {
1851         aTessCurve = Handle(StepVisual_TessellatedCurveSet)::DownCast(aListItems->Value(n));
1852       }
1853       if (aTessCurve.IsNull())
1854         continue;
1855       Handle(StepVisual_CoordinatesList) aCoordList = aTessCurve->CoordList();
1856       if (aCoordList.IsNull())
1857         continue;
1858       Handle(TColgp_HArray1OfXYZ)  aPoints = aCoordList->Points();
1859
1860       if (aPoints.IsNull() || aPoints->Length() == 0)
1861         continue;
1862       NCollection_Handle<StepVisual_VectorOfHSequenceOfInteger> aCurves = aTessCurve->Curves();
1863       Standard_Integer aNbC = (aCurves.IsNull() ? 0 : aCurves->Length());
1864       TopoDS_Compound aComp;
1865       aB.MakeCompound(aComp);
1866
1867       Standard_Integer k = 0;
1868       for (; k < aNbC; k++)
1869       {
1870         Handle(TColStd_HSequenceOfInteger) anIndexes = aCurves->Value(k);
1871         TopoDS_Wire aCurW;
1872         aB.MakeWire(aCurW);
1873
1874         for (Standard_Integer n = 1; n < anIndexes->Length(); n++)
1875         {
1876           Standard_Integer ind = anIndexes->Value(n);
1877           Standard_Integer indnext = anIndexes->Value(n + 1);
1878           if (ind > aPoints->Length() || indnext > aPoints->Length())
1879             continue;
1880           gp_Pnt aP1(aPoints->Value(ind) * theFact);
1881           gp_Pnt aP2(aPoints->Value(indnext) * theFact);
1882           BRepBuilderAPI_MakeEdge aMaker(aP1, aP2);
1883           if (aMaker.IsDone())
1884           {
1885             TopoDS_Edge aCurE = aMaker.Edge();
1886             aB.Add(aCurW, aCurE);
1887           }
1888         }
1889         aB.Add(aComp, aCurW);
1890       }
1891       anAnnotationShape = aComp;
1892     }
1893     if (!anAnnotationShape.IsNull())
1894     {
1895       nbShapes++;
1896       aB.Add(aResAnnotation, anAnnotationShape);
1897       if (i == anAnnotations.Length() - 1)
1898         BRepBndLib::AddClose(anAnnotationShape, aBox);
1899     }
1900   }
1901
1902   thePresentation = aResAnnotation;
1903   theBox = aBox;
1904   return (nbShapes > 0);
1905 }
1906
1907 //=======================================================================
1908 //function : readAnnotationPlane
1909 //purpose  : read annotation plane
1910 //=======================================================================
1911 Standard_Boolean readAnnotationPlane(const Handle(StepVisual_AnnotationPlane) theAnnotationPlane,
1912                                      const Standard_Real theFact,
1913                                      gp_Ax2& thePlane)
1914 {
1915   if (theAnnotationPlane.IsNull())
1916     return Standard_False;
1917   gp_Ax2 aPlaneAxes;
1918   Handle(StepRepr_RepresentationItem) aPlaneItem = theAnnotationPlane->Item();
1919   Handle(StepGeom_Axis2Placement3d) aA2P3D;
1920   //retrieve axes from AnnotationPlane
1921   if (aPlaneItem->IsKind(STANDARD_TYPE(StepGeom_Plane))) {
1922     Handle(StepGeom_Plane) aPlane = Handle(StepGeom_Plane)::DownCast(aPlaneItem);
1923     aA2P3D = aPlane->Position();
1924   }
1925   else if (aPlaneItem->IsKind(STANDARD_TYPE(StepVisual_PlanarBox))) {
1926     Handle(StepVisual_PlanarBox) aBox = Handle(StepVisual_PlanarBox)::DownCast(aPlaneItem);
1927     aA2P3D = aBox->Placement().Axis2Placement3d();
1928   }
1929   if (aA2P3D.IsNull())
1930     return Standard_False;
1931
1932   // build gp_Ax2 from axes
1933   Handle(StepGeom_Direction) anAxis = aA2P3D->Axis(),
1934     aRefDir = aA2P3D->RefDirection();
1935   if (anAxis.IsNull() || aRefDir.IsNull())
1936     return Standard_False;
1937
1938   Handle(TColStd_HArray1OfReal) aCoords;
1939   aCoords = anAxis->DirectionRatios();
1940   gp_Dir aXDir(aCoords->Value(1), aCoords->Value(2), aCoords->Value(3));
1941   aCoords = aRefDir->DirectionRatios();
1942   gp_Dir aYDir(aCoords->Value(1), aCoords->Value(2), aCoords->Value(3));
1943   aPlaneAxes.SetDirection(aXDir.Crossed(aYDir));
1944   aPlaneAxes.SetYDirection(aYDir);
1945   //set location of the annotation plane
1946   Handle(TColStd_HArray1OfReal) aLocCoords;
1947   Handle(StepGeom_CartesianPoint) aLoc = aA2P3D->Location();
1948   gp_Pnt aLocPos(aLoc->CoordinatesValue(1) * theFact, aLoc->CoordinatesValue(2) * theFact, aLoc->CoordinatesValue(3) * theFact);
1949   aPlaneAxes.SetLocation(aLocPos);
1950   thePlane = aPlaneAxes;
1951   return Standard_True;
1952 }
1953
1954 //=======================================================================
1955 //function : readAnnotation
1956 //purpose  : read annotation plane and position for given GDT
1957 // (Dimension, Geometric_Tolerance, Datum_Feature or Placed_Datum_Target_Feature)
1958 //=======================================================================
1959 void readAnnotation(const Handle(XSControl_TransferReader)& theTR, 
1960   const Handle(Standard_Transient) theGDT,
1961   const Handle(Standard_Transient)& theDimObject)
1962 {
1963   Handle(TCollection_HAsciiString) aPresentName;
1964   TopoDS_Compound aResAnnotation;
1965   Handle(Transfer_TransientProcess) aTP = theTR->TransientProcess();
1966   const Interface_Graph& aGraph = aTP->Graph();
1967   // find the proper DraughtingModelItemAssociation
1968   Interface_EntityIterator subs = aGraph.Sharings(theGDT);
1969   Handle(StepAP242_DraughtingModelItemAssociation) aDMIA;
1970   for (subs.Start(); subs.More() && aDMIA.IsNull(); subs.Next()) {
1971     if (!subs.Value()->IsKind(STANDARD_TYPE(StepAP242_DraughtingModelItemAssociation)))
1972       continue;
1973     aDMIA = Handle(StepAP242_DraughtingModelItemAssociation)::DownCast(subs.Value());
1974     Handle(TCollection_HAsciiString) aName = aDMIA->Name();
1975     aName->LowerCase();
1976     if (!aName->Search(new TCollection_HAsciiString("pmi representation to presentation link"))) {
1977       aDMIA = NULL;
1978     }
1979   }
1980   if (aDMIA.IsNull() || aDMIA->NbIdentifiedItem() == 0)
1981     return;
1982
1983   // calculate units
1984   Handle(StepVisual_DraughtingModel) aDModel = 
1985     Handle(StepVisual_DraughtingModel)::DownCast(aDMIA->UsedRepresentation());
1986   Standard_Real aFact = 1;
1987   if (!aDModel.IsNull())
1988     GetLengthConversionFactorFromContext(aDModel->ContextOfItems(), aFact);
1989
1990   // retrieve AnnotationPlane
1991   Handle(StepRepr_RepresentationItem) aDMIAE = aDMIA->IdentifiedItemValue(1);
1992   if (aDMIAE.IsNull())
1993     return;
1994   gp_Ax2 aPlaneAxes;
1995   subs = aGraph.Sharings(aDMIAE);
1996   Handle(StepVisual_AnnotationPlane) anAnPlane;
1997   for (subs.Start(); subs.More() && anAnPlane.IsNull(); subs.Next()) {
1998     anAnPlane = Handle(StepVisual_AnnotationPlane)::DownCast(subs.Value());
1999   }
2000   Standard_Boolean isHasPlane = readAnnotationPlane(anAnPlane, aFact, aPlaneAxes);
2001
2002   // set plane axes to XCAF
2003   if (isHasPlane) {
2004     if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DimensionObject))) {
2005       Handle(XCAFDimTolObjects_DimensionObject) anObj = 
2006         Handle(XCAFDimTolObjects_DimensionObject)::DownCast(theDimObject);
2007       Handle(TColgp_HArray1OfPnt) aPnts = new TColgp_HArray1OfPnt(1, 1);
2008       anObj->SetPlane(aPlaneAxes);
2009     }
2010     else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DatumObject))) {
2011       Handle(XCAFDimTolObjects_DatumObject) anObj =
2012         Handle(XCAFDimTolObjects_DatumObject)::DownCast(theDimObject);
2013       anObj->SetPlane(aPlaneAxes);
2014     }
2015     else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_GeomToleranceObject))) {
2016       Handle(XCAFDimTolObjects_GeomToleranceObject) anObj =
2017         Handle(XCAFDimTolObjects_GeomToleranceObject)::DownCast(theDimObject);
2018       anObj->SetPlane(aPlaneAxes);
2019     }
2020   }
2021
2022   // Retrieve presentation
2023   Bnd_Box aBox;
2024   if (!readPMIPresentation(aDMIAE, theTR, aFact, aResAnnotation, aPresentName, aBox))
2025     return;
2026   gp_Pnt aPtext(0., 0., 0.);
2027   // if Annotation plane location inside bounding box set it to text position
2028   // else set the center of bounding box to text position
2029   if (!aBox.IsVoid())
2030   {
2031     Standard_Real aXmin, aYmin, aZmin, aXmax, aYmax, aZmax;
2032     aBox.Get(aXmin, aYmin, aZmin, aXmax, aYmax, aZmax);
2033     if (isHasPlane && !aBox.IsOut(aPlaneAxes.Location())) {
2034       aPtext = aPlaneAxes.Location();
2035     }
2036     else {
2037       aPtext = gp_Pnt((aXmin + aXmax) * 0.5, (aYmin + aYmax) * 0.5, (aZmin + aZmax) * 0.5);
2038     }
2039   }
2040   else {
2041     aPtext = aPlaneAxes.Location();
2042   }
2043
2044   // set point to XCAF
2045   if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DimensionObject))) {
2046     Handle(XCAFDimTolObjects_DimensionObject) anObj = 
2047       Handle(XCAFDimTolObjects_DimensionObject)::DownCast(theDimObject);
2048     anObj->SetPointTextAttach(aPtext);
2049     anObj->SetPresentation(aResAnnotation, aPresentName);
2050   }
2051   else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DatumObject))) {
2052     Handle(XCAFDimTolObjects_DatumObject) anObj =
2053       Handle(XCAFDimTolObjects_DatumObject)::DownCast(theDimObject);
2054       anObj->SetPointTextAttach(aPtext);
2055       anObj->SetPresentation(aResAnnotation, aPresentName);
2056   }
2057   else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_GeomToleranceObject))) {
2058     Handle(XCAFDimTolObjects_GeomToleranceObject) anObj =
2059       Handle(XCAFDimTolObjects_GeomToleranceObject)::DownCast(theDimObject);
2060     anObj->SetPointTextAttach(aPtext);
2061     anObj->SetPresentation(aResAnnotation, aPresentName);
2062   }
2063   return;
2064 }
2065
2066 //=======================================================================
2067 //function : readConnectionPoints
2068 //purpose  : read connection points for given dimension
2069 //=======================================================================
2070 void readConnectionPoints(const Handle(XSControl_TransferReader)& theTR, 
2071   const Handle(Standard_Transient) theGDT,
2072   const Handle(XCAFDimTolObjects_DimensionObject)& theDimObject)
2073 {
2074   Handle(Transfer_TransientProcess) aTP = theTR->TransientProcess();
2075   const Interface_Graph& aGraph = aTP->Graph();
2076
2077   //calculate units
2078   Standard_Real aFact = 1;
2079   Handle(StepShape_ShapeDimensionRepresentation) aSDR = NULL;
2080   for (Interface_EntityIterator anIt = aGraph.Sharings(theGDT); aSDR.IsNull() && anIt.More(); anIt.Next()) {
2081     aSDR = Handle(StepShape_ShapeDimensionRepresentation)::DownCast(anIt.Value());
2082   }
2083   if (!aSDR.IsNull())
2084     GetLengthConversionFactorFromContext(aSDR->ContextOfItems(), aFact);
2085   
2086   if (theGDT->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
2087     // retrieve derived geometry
2088     Handle(StepShape_DimensionalSize) aDim = Handle(StepShape_DimensionalSize)::DownCast(theGDT);
2089     Handle(StepRepr_DerivedShapeAspect) aDSA = Handle(StepRepr_DerivedShapeAspect)::DownCast(aDim->AppliesTo());
2090     if (aDSA.IsNull())
2091       return;
2092     Handle(StepAP242_GeometricItemSpecificUsage) aGISU = NULL;
2093     for (Interface_EntityIterator anIt = aGraph.Sharings(aDSA); aGISU.IsNull() && anIt.More(); anIt.Next()) {
2094       aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIt.Value());
2095     }
2096     if (aGISU.IsNull() || aGISU->NbIdentifiedItem() == 0)
2097       return;
2098     Handle(StepGeom_CartesianPoint) aPoint = Handle(StepGeom_CartesianPoint)::DownCast(aGISU->IdentifiedItem()->Value(1));
2099     if (aPoint.IsNull()) {
2100       // try Axis2Placement3d.location instead of CartesianPoint
2101       Handle(StepGeom_Axis2Placement3d) anA2P3D =
2102         Handle(StepGeom_Axis2Placement3d)::DownCast(aGISU->IdentifiedItem()->Value(1));
2103       if (anA2P3D.IsNull())
2104         return;
2105       aPoint = anA2P3D->Location();
2106     }
2107   
2108     // set connection point to object
2109     gp_Pnt aPnt(aPoint->CoordinatesValue(1) * aFact, aPoint->CoordinatesValue(2) * aFact, aPoint->CoordinatesValue(3) * aFact);
2110     theDimObject->SetPoint(aPnt);
2111   }
2112   else if (theGDT->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation))) {
2113     // retrieve derived geometry
2114     Handle(StepShape_DimensionalLocation) aDim = Handle(StepShape_DimensionalLocation)::DownCast(theGDT);
2115     Handle(StepRepr_DerivedShapeAspect) aDSA1 = Handle(StepRepr_DerivedShapeAspect)::DownCast(aDim->RelatingShapeAspect());
2116     Handle(StepRepr_DerivedShapeAspect) aDSA2 = Handle(StepRepr_DerivedShapeAspect)::DownCast(aDim->RelatedShapeAspect());
2117     if (aDSA1.IsNull() && aDSA2.IsNull())
2118       return;
2119     Handle(StepAP242_GeometricItemSpecificUsage) aGISU1 = NULL;
2120     Handle(StepAP242_GeometricItemSpecificUsage) aGISU2 = NULL;
2121     if (!aDSA1.IsNull()) {
2122       for (Interface_EntityIterator anIt = aGraph.Sharings(aDSA1); aGISU1.IsNull() && anIt.More(); anIt.Next()) {
2123         aGISU1 = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIt.Value());
2124       }
2125     }
2126     if (!aDSA2.IsNull()) {
2127       for (Interface_EntityIterator anIt = aGraph.Sharings(aDSA2); aGISU2.IsNull() && anIt.More(); anIt.Next()) {
2128         aGISU2 = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIt.Value());
2129       }
2130     }
2131     // first point
2132     if (!aGISU1.IsNull() && aGISU1->NbIdentifiedItem() > 0) {
2133       Handle(StepGeom_CartesianPoint) aPoint = Handle(StepGeom_CartesianPoint)::DownCast(aGISU1->IdentifiedItem()->Value(1));
2134       if (aPoint.IsNull()) {
2135         // try Axis2Placement3d.location instead of CartesianPoint
2136         Handle(StepGeom_Axis2Placement3d) anA2P3D =
2137           Handle(StepGeom_Axis2Placement3d)::DownCast(aGISU1->IdentifiedItem()->Value(1));
2138         if (!anA2P3D.IsNull())
2139           aPoint = anA2P3D->Location();
2140       }
2141       if (!aPoint.IsNull()) {
2142         // set connection point to object
2143         gp_Pnt aPnt(aPoint->CoordinatesValue(1) * aFact, aPoint->CoordinatesValue(2) * aFact, aPoint->CoordinatesValue(3) * aFact);
2144         theDimObject->SetPoint(aPnt);
2145       }
2146     }
2147     // second point
2148     if (!aGISU2.IsNull() && aGISU2->NbIdentifiedItem() > 0) {
2149       Handle(StepGeom_CartesianPoint) aPoint = Handle(StepGeom_CartesianPoint)::DownCast(aGISU2->IdentifiedItem()->Value(1));
2150       if (aPoint.IsNull()) {
2151         // try Axis2Placement3d.location instead of CartesianPoint
2152         Handle(StepGeom_Axis2Placement3d) anA2P3D =
2153           Handle(StepGeom_Axis2Placement3d)::DownCast(aGISU2->IdentifiedItem()->Value(1));
2154         if (!anA2P3D.IsNull())
2155           aPoint = anA2P3D->Location();
2156       }
2157       if (!aPoint.IsNull()) {
2158         // set connection point to object
2159         gp_Pnt aPnt(aPoint->CoordinatesValue(1) * aFact, aPoint->CoordinatesValue(2) * aFact, aPoint->CoordinatesValue(3) * aFact);
2160         theDimObject->SetPoint2(aPnt);
2161       }
2162     }
2163   }
2164 }
2165
2166 //=======================================================================
2167 //function : ReadDatums
2168 //purpose  : auxilary
2169 //=======================================================================
2170 static Standard_Boolean ReadDatums(const Handle(XCAFDoc_ShapeTool) &STool,
2171                                    const Handle(XCAFDoc_DimTolTool) &DGTTool,
2172                                    const Interface_Graph &graph,
2173                                    const Handle(Transfer_TransientProcess) &TP,
2174                                    const TDF_Label TolerL,
2175                                    const Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR)
2176 {
2177   if(GTWDR.IsNull()) return Standard_False;
2178   Handle(StepDimTol_HArray1OfDatumReference) HADR = GTWDR->DatumSystem();
2179   if(HADR.IsNull()) return Standard_False;
2180   for(Standard_Integer idr=1; idr<=HADR->Length(); idr++) {
2181     Handle(StepDimTol_DatumReference) DR = HADR->Value(idr);
2182     Handle(StepDimTol_Datum) aDatum = DR->ReferencedDatum();
2183     if(aDatum.IsNull()) continue;
2184     Interface_EntityIterator subs4 = graph.Sharings(aDatum);
2185     for(subs4.Start(); subs4.More(); subs4.Next()) {
2186       Handle(StepRepr_ShapeAspectRelationship) SAR = 
2187         Handle(StepRepr_ShapeAspectRelationship)::DownCast(subs4.Value());
2188       if(SAR.IsNull()) continue;
2189       Handle(StepDimTol_DatumFeature) DF = 
2190         Handle(StepDimTol_DatumFeature)::DownCast(SAR->RelatingShapeAspect());
2191       if(DF.IsNull()) continue;
2192       Interface_EntityIterator subs5 = graph.Sharings(DF);
2193       Handle(StepRepr_PropertyDefinition) PropDef;
2194       for(subs5.Start(); subs5.More() && PropDef.IsNull(); subs5.Next()) {
2195         PropDef = Handle(StepRepr_PropertyDefinition)::DownCast(subs5.Value());
2196       }
2197       if(PropDef.IsNull()) continue;
2198       Handle(StepShape_AdvancedFace) AF;
2199       subs5 = graph.Sharings(PropDef);
2200       for(subs5.Start(); subs5.More(); subs5.Next()) {
2201         Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
2202           Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs5.Value());
2203         if(!SDR.IsNull()) {
2204           Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
2205           if( !Repr.IsNull() && Repr->NbItems()>0 ) {
2206             Handle(StepRepr_RepresentationItem) RI = Repr->ItemsValue(1);
2207             AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
2208           }
2209         }
2210       }
2211       if(AF.IsNull()) return Standard_False;
2212       Standard_Integer index = TP->MapIndex(AF);
2213       TopoDS_Shape aSh;
2214       if(index >0) {
2215         Handle(Transfer_Binder) binder = TP->MapItem(index);
2216         aSh = TransferBRep::ShapeResult(binder);
2217       }
2218       if(aSh.IsNull()) continue; 
2219       TDF_Label shL;
2220       if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2221       DGTTool->SetDatum(shL,TolerL,PropDef->Name(),PropDef->Description(),aDatum->Identification());
2222     }
2223   }
2224   return Standard_True;
2225 }
2226
2227
2228 //=======================================================================
2229 //function : setDatumToXCAF
2230 //purpose  : 
2231 //=======================================================================
2232 static Standard_Boolean setDatumToXCAF(const Handle(StepDimTol_Datum)& theDat,
2233                                         const TDF_Label theGDTL,
2234                                         const Standard_Integer thePositionCounter,
2235                                         const XCAFDimTolObjects_DatumModifiersSequence& aXCAFModifiers,
2236                                         const XCAFDimTolObjects_DatumModifWithValue aXCAFModifWithVal,
2237                                         const Standard_Real aModifValue,
2238                                         const Handle(TDocStd_Document)& theDoc,
2239                                         const Handle(XSControl_WorkSession)& theWS)
2240 {
2241   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
2242   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
2243   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
2244   const Handle(Transfer_TransientProcess) &aTP = aTR->TransientProcess();
2245   const Interface_Graph& aGraph = aTP->Graph();
2246   Handle(XCAFDoc_Datum) aDat;
2247   TDF_Label aShL;
2248   Standard_Boolean aRefShapeIsFound = Standard_False;
2249   Standard_Boolean aFirstStep = Standard_True;
2250   Interface_EntityIterator anIterD = aGraph.Sharings(theDat);
2251   for(anIterD.Start(); anIterD.More(); anIterD.Next()) {
2252     Handle(StepRepr_ShapeAspectRelationship) aSAR = 
2253       Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIterD.Value());
2254     if(aSAR.IsNull()) continue;
2255
2256     Handle(StepRepr_ShapeAspect) aSA = aSAR->RelatingShapeAspect();
2257     if (aSA.IsNull()) continue;
2258     Handle(StepAP242_GeometricItemSpecificUsage) aPGISU;
2259     if(aSA->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp)))
2260     {
2261       //processing for complex entity
2262       Interface_EntityIterator anIterC = aGraph.Sharings(aSA);
2263       for(anIterC.Start(); anIterC.More(); anIterC.Next()) {
2264         Handle(StepRepr_ShapeAspectRelationship) SAR = 
2265           Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIterC.Value());
2266         if(SAR.IsNull()) continue;
2267         Handle(StepRepr_ShapeAspect) aS = SAR->RelatedShapeAspect();
2268         if(aS.IsNull()) continue;
2269         Interface_EntityIterator anIterSA = aGraph.Sharings(aS);
2270         for(anIterSA.Start(); anIterSA.More() && aPGISU.IsNull(); anIterSA.Next()) {
2271           aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterSA.Value());
2272         }
2273         if(!aPGISU.IsNull()){
2274           aSA = aS;
2275           break;
2276         }
2277       }
2278     }
2279     else if(aSA->IsKind(STANDARD_TYPE(StepDimTol_PlacedDatumTargetFeature)))
2280     {
2281       //processing for datum target
2282       Interface_EntityIterator anIterDTF = aGraph.Sharings(aSA);
2283       for(anIterDTF.Start(); anIterDTF.More(); anIterDTF.Next()) {
2284         if(anIterDTF.Value()->IsKind(STANDARD_TYPE(StepRepr_FeatureForDatumTargetRelationship)))
2285         {
2286           Handle(StepRepr_FeatureForDatumTargetRelationship) aFFDTR =
2287             Handle(StepRepr_FeatureForDatumTargetRelationship)::DownCast(anIterDTF.Value());
2288           Handle(StepRepr_ShapeAspect) aTmpSA = aFFDTR->RelatedShapeAspect();
2289           Interface_EntityIterator anIterDSWP = aGraph.Sharings(aTmpSA);
2290           for(anIterDSWP.Start(); anIterDSWP.More() && aPGISU.IsNull(); anIterDSWP.Next()) {
2291             aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
2292     }
2293         }
2294       }
2295     }
2296     if (aSA.IsNull()) continue;
2297     Interface_EntityIterator anIterDSWP = aGraph.Sharings(aSA);
2298     for(anIterDSWP.Start(); anIterDSWP.More() && aPGISU.IsNull(); anIterDSWP.Next()) {
2299       aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
2300     }
2301     if(aPGISU.IsNull()) continue;
2302     // get representation item
2303     Handle(StepRepr_RepresentationItem) aRI;
2304     for(Standard_Integer i = 1 ; i <= aPGISU->NbIdentifiedItem() && aRI.IsNull(); i++)
2305     {
2306       aRI = aPGISU->IdentifiedItemValue(i);
2307     }
2308     if(aRI.IsNull()) continue;
2309     Standard_Integer index = aTP->MapIndex(aRI);
2310     TopoDS_Shape aSh;
2311     if(index >0) {
2312       Handle(Transfer_Binder) binder = aTP->MapItem(index);
2313       aSh = TransferBRep::ShapeResult(binder);
2314     }
2315     if(aSh.IsNull()) continue; 
2316     if( !aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True) ) continue;
2317     Handle(TDataStd_TreeNode) aNode;
2318     if(aFirstStep && aShL.FindAttribute(XCAFDoc::DatumRefGUID(),aNode) && aNode->HasFirst() &&
2319        aNode->First()->Label().FindAttribute(XCAFDoc_Datum::GetID(),aDat))
2320     {
2321       //if datums already attached, not need add datum target
2322       aRefShapeIsFound = Standard_True;
2323     }
2324     aFirstStep = Standard_False;
2325     Handle(XCAFDimTolObjects_DatumObject) aDatObj;
2326     if(aSA->IsKind(STANDARD_TYPE(StepDimTol_PlacedDatumTargetFeature)))
2327     {
2328       if(!aRefShapeIsFound)
2329       {
2330         //if datum targers not yet added
2331         TDF_Label aDatL = aDGTTool->AddDatum();
2332         aDat = XCAFDoc_Datum::Set(aDatL);
2333         aDGTTool->SetDatum(aShL, aDatL);
2334         aDatObj = aDat->GetObject();
2335         aDatObj->SetName(theDat->Identification());
2336         aDatObj->SetPosition (thePositionCounter);
2337         if(!aXCAFModifiers.IsEmpty())
2338           aDatObj->SetModifiers(aXCAFModifiers);
2339         if (aXCAFModifWithVal != XCAFDimTolObjects_DatumModifWithValue_None) 
2340           aDatObj->SetModifierWithValue(aXCAFModifWithVal, aModifValue);
2341         aDGTTool->SetDatumToGeomTol(aDatL, theGDTL);
2342         Handle(StepDimTol_PlacedDatumTargetFeature) aPDTF = Handle(StepDimTol_PlacedDatumTargetFeature)::DownCast(aSA);
2343         if (aPDTF->TargetId()->IsIntegerValue())
2344           aDatObj->SetDatumTargetNumber(aPDTF->TargetId()->IntegerValue());
2345         else
2346           aDatObj->SetDatumTargetNumber(0);
2347         aDatObj->IsDatumTarget(Standard_True);
2348         XCAFDimTolObjects_DatumTargetType aType;
2349         if(STEPCAFControl_GDTProperty::GetDatumTargetType(aSA->Description(),aType))
2350         {
2351           aDatObj->SetDatumTargetType(aType);
2352           if(aType == XCAFDimTolObjects_DatumTargetType_Area)
2353           {
2354             Interface_EntityIterator anIterDTF = aGraph.Shareds(aSA);
2355             for(anIterDTF.Start(); anIterDTF.More(); anIterDTF.Next()) {
2356               if(anIterDTF.Value()->IsKind(STANDARD_TYPE(StepAP242_GeometricItemSpecificUsage)))
2357               {
2358                 Handle(StepAP242_GeometricItemSpecificUsage) aGISU
2359                   = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
2360                 Handle(StepRepr_RepresentationItem) anItem;
2361                 if(aPGISU->NbIdentifiedItem() > 0) {
2362                   anItem = aPGISU->IdentifiedItemValue(1);
2363                 }
2364                 if(anItem.IsNull()) continue;
2365                 Standard_Integer anItemIndex = aTP->MapIndex(anItem);
2366                 if(anItemIndex >0) {
2367                   Handle(Transfer_Binder) binder = aTP->MapItem(anItemIndex);
2368                   TopoDS_Shape anItemShape = TransferBRep::ShapeResult(binder);
2369                   aDatObj->SetDatumTarget(anItemShape);
2370                 }
2371               }
2372             }
2373           }
2374           else
2375           {
2376             Interface_EntityIterator anIterDTF = aGraph.Shareds(aSA);
2377             for(anIterDTF.Start(); anIterDTF.More(); anIterDTF.Next()) {
2378               if(anIterDTF.Value()->IsKind(STANDARD_TYPE(StepRepr_PropertyDefinition)))
2379               {
2380                 Interface_EntityIterator anIterPD = aGraph.Shareds(anIterDTF.Value());
2381                 for(anIterPD.Start(); anIterPD.More(); anIterPD.Next()) {
2382                   if(anIterPD.Value()->IsKind(STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation)))
2383                   {
2384                     Interface_EntityIterator anIterSDR = aGraph.Sharings(anIterPD.Value());
2385                     for(anIterSDR.Start(); anIterSDR.More(); anIterSDR.Next()) {
2386                       if(anIterSDR.Value()->IsKind(STANDARD_TYPE(StepShape_ShapeRepresentationWithParameters)))
2387                       {
2388                         Handle(StepShape_ShapeRepresentationWithParameters) aSRWP
2389                           = Handle(StepShape_ShapeRepresentationWithParameters)::DownCast(anIterSDR.Value());
2390                         for(Standard_Integer r = aSRWP->Items()->Lower(); r <= aSRWP->Items()->Upper(); r++)
2391                         {
2392                           if(aSRWP->ItemsValue(r)->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
2393                           {
2394                             Handle(StepGeom_Axis2Placement3d) anAx
2395                               = Handle(StepGeom_Axis2Placement3d)::DownCast(aSRWP->ItemsValue(r));
2396                             Handle(TColStd_HArray1OfReal) aDirArr = anAx->Axis()->DirectionRatios();
2397                             Handle(TColStd_HArray1OfReal) aDirRArr = anAx->RefDirection()->DirectionRatios();
2398                             Handle(TColStd_HArray1OfReal) aLocArr = anAx->Location()->Coordinates();
2399                             gp_Dir aDir;
2400                             gp_Dir aDirR;
2401                             gp_Pnt aPnt;
2402                             if(!aDirArr.IsNull() && aDirArr->Length() > 2 &&
2403                               !aDirRArr.IsNull() && aDirRArr->Length() > 2 && 
2404                               !aLocArr.IsNull() && aLocArr->Length() > 2)
2405                             {
2406                               aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, aDirArr->Lower()+2);
2407                               aDirR.SetCoord(aDirRArr->Lower(), aDirRArr->Lower()+1, aDirRArr->Lower()+2);
2408                               aPnt.SetCoord(aLocArr->Lower(), aLocArr->Lower()+1, aLocArr->Lower()+2);
2409                               gp_Ax2 anA(aPnt, aDir, aDirR);
2410                               aDatObj->SetDatumTargetAxis(anA);
2411                             }
2412                           }
2413                           else if(aSRWP->ItemsValue(r)->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit)))
2414                           {
2415                             Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) aM =
2416                               Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(aSRWP->ItemsValue(r)); 
2417                             Standard_Real aVal = aM->GetMeasureWithUnit()->ValueComponent();
2418                             StepBasic_Unit anUnit = aM->GetMeasureWithUnit()->UnitComponent();
2419                             Standard_Real aFact=1.;
2420                             if(anUnit.IsNull()) continue;
2421                             if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2422                             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2423                             if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2424                             if(aM->Name()->String().IsEqual("target length") ||
2425                               aM->Name()->String().IsEqual("target diameter"))
2426                               aDatObj->SetDatumTargetLength(aVal);
2427                             else
2428                               aDatObj->SetDatumTargetWidth(aVal);
2429                           }
2430                         }
2431                       }
2432                     }
2433                   }
2434                 }
2435               }
2436             }
2437           }
2438         }
2439       }
2440     }
2441     else
2442     {
2443       //processing for darum feature
2444       TDF_Label aDatL = aDGTTool->AddDatum();
2445       aDat = XCAFDoc_Datum::Set(aDatL);
2446       aDGTTool->SetDatum(aShL, aDatL);
2447       aDatObj = aDat->GetObject();
2448       aDatObj->SetName(theDat->Identification());
2449       aDatObj->SetPosition (thePositionCounter);
2450       if(!aXCAFModifiers.IsEmpty())
2451         aDatObj->SetModifiers(aXCAFModifiers);
2452       if (aXCAFModifWithVal != XCAFDimTolObjects_DatumModifWithValue_None) 
2453         aDatObj->SetModifierWithValue(aXCAFModifWithVal, aModifValue);
2454       aDGTTool->SetDatumToGeomTol(aDatL, theGDTL);
2455     }
2456     if(!aDatObj.IsNull()) {
2457       readAnnotation(aTR, aSAR->RelatingShapeAspect(), aDatObj);
2458       aDat->SetObject(aDatObj);
2459     }
2460   }
2461   return !aDat.IsNull();
2462 }
2463
2464
2465 //=======================================================================
2466 //function : ReadDatums
2467 //purpose  : auxilary
2468 //=======================================================================
2469 static Standard_Boolean readDatumsAP242(const Handle(Standard_Transient)& theEnt,
2470                                         const TDF_Label theGDTL,
2471                                         const Handle(TDocStd_Document)& theDoc,
2472                                         const Handle(XSControl_WorkSession)& theWS)
2473 {
2474   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
2475   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
2476   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
2477   const Handle(Transfer_TransientProcess) &aTP = aTR->TransientProcess();
2478   const Interface_Graph& aGraph = aTP->Graph();
2479
2480   Interface_EntityIterator anIter = aGraph.Shareds(theEnt);
2481   for(anIter.Start(); anIter.More(); anIter.Next()) {
2482     Handle(Standard_Transient) anAtr = anIter.Value();
2483     if(anAtr->IsKind(STANDARD_TYPE(StepDimTol_DatumSystem)))
2484     {
2485       Standard_Integer aPositionCounter = 0;//position on frame 
2486       Handle(StepDimTol_DatumSystem) aDS = Handle(StepDimTol_DatumSystem)::DownCast(anAtr);
2487       Interface_EntityIterator anIterDS = aGraph.Sharings(aDS);
2488       for(anIterDS.Start(); anIterDS.More(); anIterDS.Next()) {
2489         Handle(Standard_Transient) anAtrDS = anIterDS.Value();
2490         if(anAtrDS->IsKind(STANDARD_TYPE(StepAP242_GeometricItemSpecificUsage)))
2491         {
2492           //get axis
2493           Handle(StepAP242_GeometricItemSpecificUsage)aAxGISUI
2494             = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anAtrDS);
2495           if (aAxGISUI->IdentifiedItemValue(1)->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
2496           {
2497             Handle(StepGeom_Axis2Placement3d) anAx
2498               = Handle(StepGeom_Axis2Placement3d)::DownCast(aAxGISUI->IdentifiedItemValue(1));
2499             Handle(XCAFDoc_GeomTolerance) aTol;
2500             if(theGDTL.FindAttribute(XCAFDoc_GeomTolerance::GetID(), aTol))
2501             {
2502               Handle(XCAFDimTolObjects_GeomToleranceObject) anObj = aTol->GetObject();
2503               Handle(TColStd_HArray1OfReal) aDirArr = anAx->Axis()->DirectionRatios();
2504               Handle(TColStd_HArray1OfReal) aDirRArr = anAx->RefDirection()->DirectionRatios();
2505               Handle(TColStd_HArray1OfReal) aLocArr = anAx->Location()->Coordinates();
2506               gp_Dir aDir;
2507               gp_Dir aDirR;
2508               gp_Pnt aPnt;
2509               if(!aDirArr.IsNull() && aDirArr->Length() > 2 &&
2510                 !aDirRArr.IsNull() && aDirRArr->Length() > 2 && 
2511                 !aLocArr.IsNull() && aLocArr->Length() > 2)
2512               {
2513                 aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, aDirArr->Lower()+2);
2514                 aDirR.SetCoord(aDirRArr->Lower(), aDirRArr->Lower()+1, aDirRArr->Lower()+2);
2515                 aPnt.SetCoord(aLocArr->Lower(), aLocArr->Lower()+1, aLocArr->Lower()+2);
2516                 gp_Ax2 anA(aPnt, aDir, aDirR);
2517                 anObj->SetAxis(anA);
2518                 aTol->SetObject(anObj);
2519               }
2520             }
2521           }
2522         }
2523       }
2524       if (aDS->NbConstituents() > 0)
2525       {
2526         //get datum feature and datum target from datum system
2527         Handle(StepDimTol_HArray1OfDatumReferenceCompartment) aDRCA = aDS->Constituents();
2528         if(!aDRCA.IsNull())
2529         {
2530           for(Standard_Integer i = aDRCA->Lower(); i <= aDRCA->Upper(); i++)
2531           {
2532             Handle(StepDimTol_DatumReferenceCompartment) aDRC = aDRCA->Value(i);
2533             //gete modifiers
2534             Handle(StepDimTol_HArray1OfDatumReferenceModifier) aModif = aDRC->Modifiers();
2535             XCAFDimTolObjects_DatumModifiersSequence aXCAFModifiers;
2536             XCAFDimTolObjects_DatumModifWithValue aXCAFModifWithVal = XCAFDimTolObjects_DatumModifWithValue_None;
2537             Standard_Real aModifValue = 0;
2538             if(!aModif.IsNull())
2539             {
2540               for(Standard_Integer m = aModif->Lower(); m <= aModif->Upper(); m++)
2541               {
2542                 if(aModif->Value(m).CaseNumber() == 2)
2543                   aXCAFModifiers.Append(
2544                   (XCAFDimTolObjects_DatumSingleModif)aModif->Value(m).
2545                   SimpleDatumReferenceModifierMember()->Value());
2546                 else if (aModif->Value(m).CaseNumber() == 1)
2547                 {
2548                   aXCAFModifWithVal = (XCAFDimTolObjects_DatumModifWithValue)(aModif->Value(m).DatumReferenceModifierWithValue()->ModifierType() + 1);
2549                   Standard_Real aVal = aModif->Value(m).DatumReferenceModifierWithValue()->ModifierValue()->ValueComponent();
2550                   StepBasic_Unit anUnit = aModif->Value(m).DatumReferenceModifierWithValue()->ModifierValue()->UnitComponent();
2551                   Standard_Real aFact=1.;
2552                   if(anUnit.IsNull()) continue;
2553                   if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2554                   Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2555                   if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2556                   aModifValue = aVal;
2557                 }
2558               }
2559             }
2560             aPositionCounter++;
2561             Interface_EntityIterator anIterDRC = aGraph.Shareds(aDRC);
2562             for(anIterDRC.Start(); anIterDRC.More(); anIterDRC.Next()) {
2563               
2564               if(anIterDRC.Value()->IsKind(STANDARD_TYPE(StepDimTol_Datum)))
2565               {
2566                 Handle(StepDimTol_Datum) aD = Handle(StepDimTol_Datum)::DownCast(anIterDRC.Value());
2567                 setDatumToXCAF(aD, theGDTL, aPositionCounter, aXCAFModifiers, aXCAFModifWithVal, aModifValue,theDoc, theWS);
2568               }
2569               else if(anIterDRC.Value()->IsKind(STANDARD_TYPE(StepDimTol_DatumReferenceElement)))
2570               {
2571                 Handle(StepDimTol_DatumReferenceElement) aDRE 
2572                   = Handle(StepDimTol_DatumReferenceElement)::DownCast(anIterDRC.Value());
2573                 //get modifiers from group of datums
2574                 Handle(StepDimTol_HArray1OfDatumReferenceModifier) aModifE = aDRE->Modifiers();
2575                 if(!aModifE.IsNull())
2576                 {
2577                   for(Standard_Integer k = aModifE->Lower(); k <= aModifE->Upper(); k++)
2578                   {
2579                     if(aModifE->Value(k).CaseNumber() == 2)
2580                       aXCAFModifiers.Append(
2581                       (XCAFDimTolObjects_DatumSingleModif)aModifE->Value(k).
2582                       SimpleDatumReferenceModifierMember()->Value());
2583                     else if (aModifE->Value(k).CaseNumber() == 1)
2584                     {
2585                       aXCAFModifWithVal = (XCAFDimTolObjects_DatumModifWithValue)(aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierType() + 1);
2586                       Standard_Real aVal = aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierValue()->ValueComponent();
2587                       StepBasic_Unit anUnit = aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierValue()->UnitComponent();
2588                       Standard_Real aFact=1.;
2589                       if(anUnit.IsNull()) continue;
2590                       if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2591                       Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2592                       if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2593                       aModifValue = aVal;
2594                     }
2595                   }
2596                 }
2597                 Interface_EntityIterator anIterDRE = aGraph.Shareds(aDRE);
2598                 for(anIterDRE.Start(); anIterDRE.More(); anIterDRE.Next()) {
2599                   if(anIterDRE.Value()->IsKind(STANDARD_TYPE(StepDimTol_Datum)))
2600                   {
2601                     Handle(StepDimTol_Datum) aD = Handle(StepDimTol_Datum)::DownCast(anIterDRE.Value());
2602                     setDatumToXCAF(aD, theGDTL, aPositionCounter, aXCAFModifiers, aXCAFModifWithVal, aModifValue,theDoc, theWS);
2603                   }
2604                 }
2605               }
2606             }
2607           }
2608         }
2609       }
2610     }
2611   }
2612   return Standard_True;
2613 }
2614
2615 //=======================================================================
2616 //function : collectShapeAspect
2617 //purpose  : 
2618 //=======================================================================
2619 static void collectShapeAspect(const Handle(StepRepr_ShapeAspect)& theSA,
2620                                const Handle(XSControl_WorkSession)& theWS,
2621                                NCollection_Sequence<Handle(StepRepr_ShapeAspect)>& theSAs)
2622 {
2623   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
2624   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
2625   const Interface_Graph& aGraph = aTP->Graph();
2626   // Retrieve Shape_Aspect, connected to Representation_Item from Derived_Shape_Aspect
2627   if (theSA->IsKind(STANDARD_TYPE(StepRepr_DerivedShapeAspect))) {
2628     Interface_EntityIterator anIter = aGraph.Sharings(theSA);
2629     Handle(StepRepr_ShapeAspectDerivingRelationship) aSADR = NULL;
2630     for (; aSADR.IsNull() && anIter.More(); anIter.Next()) {
2631       aSADR = Handle(StepRepr_ShapeAspectDerivingRelationship)::DownCast(anIter.Value());
2632     }
2633     if (!aSADR.IsNull())
2634       collectShapeAspect(aSADR->RelatedShapeAspect(), theWS, theSAs);
2635   }
2636   else if (theSA->IsKind(STANDARD_TYPE(StepDimTol_DatumFeature))) {
2637     theSAs.Append(theSA);
2638     return;
2639   }
2640   else {
2641     // Find all children Shape_Aspect
2642     Standard_Boolean isSimple = Standard_True;
2643     Interface_EntityIterator anIter = aGraph.Sharings(theSA);
2644     for (; anIter.More(); anIter.Next()) {
2645       if (anIter.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspectRelationship)) &&
2646           !anIter.Value()->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation))) {
2647         Handle(StepRepr_ShapeAspectRelationship) aSAR =
2648           Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIter.Value());
2649         if (aSAR->RelatingShapeAspect() == theSA) {
2650           collectShapeAspect(aSAR->RelatedShapeAspect(), theWS, theSAs);
2651           isSimple = Standard_False;
2652         }
2653       }
2654     }
2655     // If not Composite_Shape_Aspect (or subtype) append to sequence.
2656     if (isSimple)
2657       theSAs.Append(theSA);
2658   }
2659 }
2660
2661 //=======================================================================
2662 //function : createGeomTolObjectInXCAF
2663 //purpose  : 
2664 //=======================================================================
2665 static TDF_Label createGDTObjectInXCAF(const Handle(Standard_Transient)& theEnt,
2666                                                const Handle(TDocStd_Document)& theDoc,
2667                                                const Handle(XSControl_WorkSession)& theWS)
2668 {
2669   TDF_Label aGDTL;
2670   if(!theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) &&
2671      !theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) && 
2672      !theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
2673   {
2674     return aGDTL;
2675   }
2676   // protection against invalid input
2677   if (theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
2678     Handle(StepDimTol_GeometricTolerance) aGeomTol = Handle(StepDimTol_GeometricTolerance)::DownCast(theEnt);
2679     if (aGeomTol->TolerancedShapeAspect().IsNull())
2680       return aGDTL;
2681   }
2682   if (theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
2683     Handle(StepShape_DimensionalSize) aDim = Handle(StepShape_DimensionalSize)::DownCast(theEnt);
2684     if (aDim->AppliesTo().IsNull())
2685       return aGDTL;
2686   }
2687   if (theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation))) {
2688     Handle(StepShape_DimensionalLocation) aDim = Handle(StepShape_DimensionalLocation)::DownCast(theEnt);
2689     if (aDim->RelatedShapeAspect().IsNull() || aDim->RelatingShapeAspect().IsNull())
2690       return aGDTL;
2691   }
2692
2693   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
2694   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
2695   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
2696   const Handle(Transfer_TransientProcess) &aTP = aTR->TransientProcess();
2697   const Interface_Graph& aGraph = aTP->Graph();
2698   Standard_Boolean isAllAround = Standard_False;
2699   Standard_Boolean isAllOver = Standard_False;
2700   
2701   // find RepresentationItem for current Ent
2702   NCollection_Sequence<Handle(Standard_Transient)> aSeqRI1, aSeqRI2;
2703
2704   // Collect all Shape_Aspect entities
2705   Interface_EntityIterator anIter = aGraph.Shareds(theEnt);
2706   for(anIter.Start(); anIter.More(); anIter.Next()) {
2707     Handle(Standard_Transient) anAtr = anIter.Value();
2708     NCollection_Sequence<Handle(StepRepr_ShapeAspect)> aSAs;
2709     if(anAtr->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape)))
2710     {
2711       //if associating tolerances with part (All-Over)
2712       Interface_EntityIterator anIterSDR = aGraph.Sharings(anAtr);
2713       for(anIterSDR.Start(); anIterSDR.More(); anIterSDR.Next()) 
2714       {
2715         Handle(Standard_Transient) anAtrSDR = anIterSDR.Value();
2716         if(anAtrSDR->IsKind(STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation)))
2717         {
2718           isAllOver = Standard_True;
2719           Interface_EntityIterator anIterABSR = aGraph.Shareds(anAtrSDR);
2720           for(anIterABSR.Start(); anIterABSR.More(); anIterABSR.Next()) 
2721           {
2722             Handle(Standard_Transient) anAtrABSR = anIterABSR.Value();
2723             if(anAtrABSR->IsKind(STANDARD_TYPE(StepShape_AdvancedBrepShapeRepresentation)))
2724             {
2725               aSeqRI1.Append(anAtrABSR);
2726             }
2727           }
2728         }
2729       }
2730     }
2731     else if(anAtr->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) || 
2732       anAtr->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)))
2733     {
2734       //if tolerance attached to dimension
2735       Interface_EntityIterator anIterDim = aGraph.Shareds(anAtr);
2736       for(anIterDim.Start(); anIterDim.More(); anIterDim.Next()) 
2737       {
2738         Handle(StepRepr_ShapeAspect) aSA = Handle(StepRepr_ShapeAspect)::DownCast(anIterDim.Value());
2739         if(!aSA.IsNull()) {
2740           collectShapeAspect(aSA, theWS, aSAs);
2741         }
2742       }
2743     }
2744     else if(anAtr->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)))
2745     {
2746       if(anAtr->IsKind(STANDARD_TYPE(StepRepr_AllAroundShapeAspect)))
2747       {
2748         // if applyed AllAround Modifier
2749         isAllAround = Standard_True;
2750       }
2751       // dimensions and default tolerances
2752       Handle(StepRepr_ShapeAspect) aSA = Handle(StepRepr_ShapeAspect)::DownCast(anAtr);
2753       if(!aSA.IsNull()) {
2754         collectShapeAspect(aSA, theWS, aSAs);
2755       }
2756     }
2757
2758     // Collect all representation items
2759     if(!aSAs.IsEmpty())
2760     {
2761       //get representation items
2762       NCollection_Sequence<Handle(Standard_Transient)> aSeqRI;
2763       for(Standard_Integer i = aSAs.Lower(); i <= aSAs.Upper(); i++)
2764       {
2765         Interface_EntityIterator anIterSA = aGraph.Sharings(aSAs.Value(i));
2766         Handle(StepAP242_GeometricItemSpecificUsage) aGISU;
2767         Handle(StepRepr_PropertyDefinition) PropD;
2768         for(anIterSA.Start(); anIterSA.More() && aGISU.IsNull() && PropD.IsNull(); anIterSA.Next()) {
2769           aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterSA.Value());
2770           PropD = Handle(StepRepr_PropertyDefinition)::DownCast(anIterSA.Value());
2771         }
2772         if(!PropD.IsNull())//for old version
2773         {
2774           Handle(StepRepr_RepresentationItem) RI;
2775           Interface_EntityIterator subs4 = aGraph.Sharings(PropD);
2776           for(subs4.Start(); subs4.More(); subs4.Next()) {
2777             Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
2778               Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs4.Value());
2779             if(!SDR.IsNull()) {
2780               Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
2781               if( !Repr.IsNull() && Repr->NbItems()>0 ) {
2782                 RI = Repr->ItemsValue(1);
2783               }
2784             }
2785           }
2786           if(RI.IsNull()) continue;
2787
2788           if(theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
2789             // read dimensions
2790             Handle(StepShape_EdgeCurve) EC = Handle(StepShape_EdgeCurve)::DownCast(RI);
2791             if(EC.IsNull()) continue;
2792             Handle(TCollection_HAsciiString) aName;
2793             Handle(StepShape_DimensionalSize) DimSize = 
2794               Handle(StepShape_DimensionalSize)::DownCast(theEnt);
2795             Standard_Real dim1=-1.,dim2=-1.;
2796             subs4 = aGraph.Sharings(DimSize);
2797             for(subs4.Start(); subs4.More(); subs4.Next()) {
2798               Handle(StepShape_DimensionalCharacteristicRepresentation) DimCharR = 
2799                 Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(subs4.Value());
2800               if(!DimCharR.IsNull()) {
2801                 Handle(StepShape_ShapeDimensionRepresentation) SDimR = DimCharR->Representation();
2802                 if(!SDimR.IsNull() && SDimR->NbItems()>0) {
2803                   Handle(StepRepr_RepresentationItem) anItem = SDimR->ItemsValue(1);
2804                   Handle(StepRepr_ValueRange) VR = Handle(StepRepr_ValueRange)::DownCast(anItem);
2805                   if(!VR.IsNull()) {
2806                     aName = VR->Name();
2807                     //StepRepr_CompoundItemDefinition CID = VR->ItemElement();
2808                     //if(CID.IsNull()) continue;
2809                     //Handle(StepRepr_CompoundItemDefinitionMember) CIDM = 
2810                     //  Handle(StepRepr_CompoundItemDefinitionMember)::DownCast(CID.Value());
2811                     //if(CIDM.IsNull()) continue;
2812                     //if(CIDM->ArrTransient().IsNull()) continue;
2813                     //Handle(StepRepr_HArray1OfRepresentationItem) HARI;
2814                     //if(CID.CaseMem(CIDM)==1)
2815                     //  HARI = CID.ListRepresentationItem();
2816                     //if(CID.CaseMem(CIDM)==2)
2817                     //  HARI = CID.SetRepresentationItem();
2818                     Handle(StepRepr_HArray1OfRepresentationItem) HARI = VR->ItemElement();
2819                     if(HARI.IsNull()) continue;
2820                     if(HARI->Length()>0) {
2821                       Handle(StepRepr_RepresentationItem) RI1 = HARI->Value(1);
2822                       if(RI1.IsNull()) continue;
2823                       if(RI1->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2824                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
2825                           Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI1);
2826                         dim1 = RILMWU->GetMeasureWithUnit()->ValueComponent();
2827                         StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
2828                         Standard_Real afact=1.;
2829                         if(anUnit.IsNull()) continue;
2830                         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2831                         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2832                         if(GetLengthConversionFactor(NU,afact)) dim1=dim1*afact;
2833                       }
2834                     }
2835                     if(HARI->Length()>1) {
2836                       Handle(StepRepr_RepresentationItem) RI2 = HARI->Value(2);
2837                       if(RI2.IsNull()) continue;
2838                       if(RI2->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2839                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
2840                           Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI2);
2841                         dim2 = RILMWU->GetMeasureWithUnit()->ValueComponent();
2842                         StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
2843                         Standard_Real afact=1.;
2844                         if(anUnit.IsNull()) continue;
2845                         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2846                         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2847                         if(GetLengthConversionFactor(NU,afact)) dim2 = dim2*afact;
2848                       }
2849                     }
2850                   }
2851                 }
2852               }
2853             }
2854             if(dim1<0) continue;
2855             if(dim2<0) dim2=dim1;
2856             //cout<<"DimensionalSize: dim1="<<dim1<<"  dim2="<<dim2<<endl;
2857             // now we know edge_curve and value range therefore
2858             // we can create corresponding D&GT labels
2859             Standard_Integer index = aTP->MapIndex(EC);
2860             TopoDS_Shape aSh;
2861             if(index >0) {
2862               Handle(Transfer_Binder) binder = aTP->MapItem(index);
2863               aSh = TransferBRep::ShapeResult(binder);
2864             }
2865             if(aSh.IsNull()) continue; 
2866             TDF_Label shL;
2867             if( !aSTool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2868             Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1,2);
2869             arr->SetValue(1,dim1);
2870             arr->SetValue(2,dim2);
2871             aDGTTool->SetDimTol(shL,1,arr,aName,DimSize->Name());
2872           }
2873           // read tolerances and datums
2874           else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
2875             Handle(StepDimTol_GeometricTolerance) GT =
2876               Handle(StepDimTol_GeometricTolerance)::DownCast(theEnt);
2877             // read common data for tolerance
2878             //Standard_Real dim = GT->Magnitude()->ValueComponent();
2879             Handle (StepBasic_MeasureWithUnit) dim3 = GT->Magnitude();
2880             if(dim3.IsNull()) continue;
2881             Standard_Real dim = dim3->ValueComponent();
2882             StepBasic_Unit anUnit = GT->Magnitude()->UnitComponent();
2883             Standard_Real afact=1.;
2884             if(anUnit.IsNull()) continue;
2885             if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2886             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2887             if(GetLengthConversionFactor(NU,afact)) dim = dim*afact;
2888             //cout<<"GeometricTolerance: Magnitude = "<<dim<<endl;
2889             Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1,1);
2890             arr->SetValue(1,dim);
2891             Handle(TCollection_HAsciiString) aName = GT->Name();
2892             Handle(TCollection_HAsciiString) aDescription = GT->Description();
2893             Handle(StepShape_AdvancedFace) AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
2894             if(AF.IsNull()) continue;
2895             Standard_Integer index = aTP->MapIndex(AF);
2896             TopoDS_Shape aSh;
2897             if(index >0) {
2898               Handle(Transfer_Binder) binder = aTP->MapItem(index);
2899               aSh = TransferBRep::ShapeResult(binder);
2900             }
2901             if(aSh.IsNull()) continue; 
2902             TDF_Label shL;
2903             if( !aSTool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2904             // read specific data for tolerance
2905             if(GT->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol))) {
2906               Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol) GTComplex =
2907                 Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol)::DownCast(theEnt);
2908               Standard_Integer kind=20;
2909               Handle(StepDimTol_ModifiedGeometricTolerance) MGT = 
2910                 GTComplex->GetModifiedGeometricTolerance();
2911               if(!MGT.IsNull()) {
2912                 kind = kind + MGT->Modifier()+1;
2913               }
2914               TDF_Label TolerL = aDGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
2915               // translate datums connected with this tolerance
2916               Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
2917                 GTComplex->GetGeometricToleranceWithDatumReference();
2918               if(!GTWDR.IsNull()) {
2919                 ReadDatums(aSTool,aDGTTool,aGraph,aTP,TolerL,GTWDR);
2920               }
2921             }
2922             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithDatumReference))) {
2923               Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
2924                 Handle(StepDimTol_GeometricToleranceWithDatumReference)::DownCast(theEnt);
2925               if(GTWDR.IsNull()) continue;
2926               Standard_Integer kind = 0;
2927               if     (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_AngularityTolerance)))       kind = 24;
2928               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CircularRunoutTolerance)))   kind = 25;
2929               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CoaxialityTolerance)))       kind = 26;
2930               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ConcentricityTolerance)))    kind = 27;
2931               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ParallelismTolerance)))      kind = 28;
2932               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_PerpendicularityTolerance))) kind = 29;
2933               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_SymmetryTolerance)))         kind = 30;
2934               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_TotalRunoutTolerance)))      kind = 31;
2935               //cout<<"GTWDR: kind="<<kind<<endl;
2936               TDF_Label TolerL = aDGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
2937               ReadDatums(aSTool,aDGTTool,aGraph,aTP,TolerL,GTWDR);
2938             }
2939             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_ModifiedGeometricTolerance))) {
2940               Handle(StepDimTol_ModifiedGeometricTolerance) MGT =
2941                 Handle(StepDimTol_ModifiedGeometricTolerance)::DownCast(theEnt);
2942               Standard_Integer kind = 35 + MGT->Modifier();
2943               aDGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
2944             }
2945             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_CylindricityTolerance))) {
2946               aDGTTool->SetDimTol(shL,38,arr,aName,aDescription);
2947             }
2948             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_FlatnessTolerance))) {
2949               aDGTTool->SetDimTol(shL,39,arr,aName,aDescription);
2950             }
2951             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_LineProfileTolerance))) {
2952               aDGTTool->SetDimTol(shL,40,arr,aName,aDescription);
2953             }
2954             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_PositionTolerance))) {
2955               aDGTTool->SetDimTol(shL,41,arr,aName,aDescription);
2956             }
2957             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_RoundnessTolerance))) {
2958               aDGTTool->SetDimTol(shL,42,arr,aName,aDescription);
2959             }
2960             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_StraightnessTolerance))) {
2961               aDGTTool->SetDimTol(shL,43,arr,aName,aDescription);
2962             }
2963             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_SurfaceProfileTolerance))) {
2964               aDGTTool->SetDimTol(shL,44,arr,aName,aDescription);
2965             }
2966           }
2967         }
2968         else
2969         {
2970           if(aGISU.IsNull()) continue;
2971           Standard_Integer j =1;
2972           for ( ; j <= aGISU->NbIdentifiedItem(); j++) {
2973             aSeqRI.Append(aGISU->IdentifiedItemValue(j));
2974           }
2975         }
2976       }
2977       if(!aSeqRI.IsEmpty())
2978       {
2979         if(aSeqRI1.IsEmpty())
2980           aSeqRI1 = aSeqRI;
2981         else 
2982           aSeqRI2 = aSeqRI;
2983       }
2984     }
2985   }
2986   if(aSeqRI1.IsEmpty()) 
2987     return aGDTL;
2988
2989   TDF_LabelSequence aShLS1, aShLS2;
2990
2991   // Collect shapes
2992   for(Standard_Integer i = aSeqRI1.Lower(); i <= aSeqRI1.Upper() ;i++)
2993   {
2994     Standard_Integer anIndex = aTP->MapIndex(aSeqRI1.Value(i));
2995     TopoDS_Shape aSh;
2996     if(anIndex >0) {
2997       Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
2998       aSh = TransferBRep::ShapeResult(aBinder);
2999     }
3000     if(!aSh.IsNull())
3001     {
3002       TDF_Label aShL;
3003       aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True);
3004       aShLS1.Append(aShL);
3005     }
3006   }
3007   if (!aSeqRI2.IsEmpty())
3008   {
3009     //for dimensional location
3010     for(Standard_Integer i = aSeqRI2.Lower(); i <= aSeqRI2.Upper() ;i++)
3011     {
3012       Standard_Integer anIndex = aTP->MapIndex(aSeqRI2.Value(i));
3013       TopoDS_Shape aSh;
3014       if(anIndex >0) {
3015         Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
3016         aSh = TransferBRep::ShapeResult(aBinder);
3017       }
3018       if(!aSh.IsNull())
3019       {
3020         TDF_Label aShL;
3021         aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True);
3022         aShLS2.Append(aShL);
3023       }
3024     }
3025   }
3026
3027   if(!aShLS1.IsEmpty())
3028   {
3029     // add to XCAF
3030     if(!theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
3031     {
3032       aGDTL = aDGTTool->AddDimension();
3033       Handle(XCAFDoc_Dimension) aDim = XCAFDoc_Dimension::Set(aGDTL);
3034       TCollection_AsciiString aStr("DGT:Dimensional_");
3035       if(theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)))
3036       {
3037         aStr.AssignCat("Size");
3038       }
3039       else if(theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)))
3040       {
3041         aStr.AssignCat("Location");
3042       }
3043       TDataStd_Name::Set(aGDTL, aStr);
3044
3045       if(!aShLS2.IsEmpty())
3046       {
3047         aDGTTool->SetDimension(aShLS1, aShLS2, aGDTL);
3048       }
3049       else
3050       {
3051         TDF_LabelSequence aEmptySeq;
3052         aDGTTool->SetDimension(aShLS1, aEmptySeq, aGDTL);
3053       }
3054     }
3055     else
3056     {
3057       aGDTL = aDGTTool->AddGeomTolerance();
3058       Handle(XCAFDoc_GeomTolerance) aGTol = XCAFDoc_GeomTolerance::Set(aGDTL);
3059       TCollection_AsciiString aStr("DGT:GeomTolerance");
3060       TDataStd_Name::Set(aGDTL, aStr);
3061       aDGTTool->SetGeomTolerance(aShLS1, aGDTL);
3062       Handle(XCAFDimTolObjects_GeomToleranceObject) anObj = aGTol->GetObject();
3063       if(isAllAround)
3064         anObj->AddModifier(XCAFDimTolObjects_GeomToleranceModif_All_Around);
3065       else if(isAllOver)
3066         anObj->AddModifier(XCAFDimTolObjects_GeomToleranceModif_All_Over);
3067       aGTol->SetObject(anObj);
3068     }
3069     readDatumsAP242(theEnt, aGDTL, theDoc, theWS);
3070   }
3071   return aGDTL;
3072 }
3073
3074 //=======================================================================
3075 //function : setDimObjectToXCAF
3076 //purpose  : 
3077 //=======================================================================
3078 static void setDimObjectToXCAF(const Handle(Standard_Transient)& theEnt,
3079                                            const TDF_Label& aDimL,
3080                                            const Handle(TDocStd_Document)& theDoc,
3081                                            const Handle(XSControl_WorkSession)& theWS)
3082 {
3083   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
3084   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
3085   const Handle(XSControl_TransferReader) &aTR = theWS->TransferReader();
3086   const Handle(Transfer_TransientProcess) &aTP = aTR->TransientProcess();
3087   const Interface_Graph& aGraph = aTP->Graph();
3088   Handle(XCAFDimTolObjects_DimensionObject) aDimObj;
3089   if(!theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) &&
3090     !theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation))) 
3091     return;
3092
3093   Handle(StepShape_DimensionalSize) aDimSize = 
3094     Handle(StepShape_DimensionalSize)::DownCast(theEnt);
3095   Handle(StepShape_DimensionalLocation) aDimLocation = 
3096     Handle(StepShape_DimensionalLocation)::DownCast(theEnt);
3097
3098   aDimObj = new XCAFDimTolObjects_DimensionObject();
3099   Standard_Real aDim1=-1.,aDim2=-1.,aDim3=-1.;
3100   Handle(StepShape_TypeQualifier) aTQ;
3101   Handle(StepShape_ValueFormatTypeQualifier) aVFTQ;
3102   Handle(StepShape_ToleranceValue) aTV;
3103   Handle(StepShape_LimitsAndFits) aLAF;
3104   Handle(StepRepr_CompoundRepresentationItem) aCRI;
3105   Handle(StepGeom_Axis2Placement3d) anAP;
3106
3107   Interface_EntityIterator anIterDim;
3108   if(!aDimSize.IsNull())
3109   {
3110     anIterDim = aGraph.Sharings(aDimSize);
3111   }
3112   else
3113   {
3114     anIterDim = aGraph.Sharings(aDimLocation);
3115   }
3116   for(anIterDim.Start(); anIterDim.More(); anIterDim.Next()) {
3117     Handle(StepShape_DimensionalCharacteristicRepresentation) aDCR = 
3118       Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(anIterDim.Value());
3119     Handle(StepShape_PlusMinusTolerance) aPMT = 
3120       Handle(StepShape_PlusMinusTolerance)::DownCast(anIterDim.Value());
3121     if(!aDCR.IsNull()) {
3122       Handle(StepShape_ShapeDimensionRepresentation) aSDR = aDCR->Representation();
3123       if(!aSDR.IsNull()) {
3124         Handle(StepRepr_HArray1OfRepresentationItem) aHARI = aSDR->Items();
3125
3126         if(!aHARI.IsNull())
3127         {
3128           for(Standard_Integer nr = aHARI->Lower(); nr <= aHARI->Upper(); nr++)
3129           {
3130             Handle(StepRepr_RepresentationItem) aDRI = aHARI->Value(nr);
3131             if(aDRI.IsNull()) continue;
3132
3133             if(aDRI->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
3134               //get values
3135               Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) aRILMWU =
3136                 Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(aDRI);
3137               Standard_Real aVal = aRILMWU->GetMeasureWithUnit()->ValueComponent();
3138               StepBasic_Unit anUnit = aRILMWU->GetMeasureWithUnit()->UnitComponent();
3139               Standard_Real aFact=1.;
3140               if(anUnit.IsNull()) continue;
3141               if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
3142               Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3143               if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
3144               if(aDim2 > 0)
3145               {
3146                 if(aDim1 > aDim2)
3147                 {
3148                   Standard_Real aTmp = aDim1;
3149                   aDim1 = aDim2;
3150                   aDim2 = aTmp;
3151                 }
3152                 if(aVal < aDim1)
3153                   aDim1 = aVal;
3154                 else if(aVal > aDim2)
3155                   aDim2 = aVal;
3156               }
3157               else if(aDim1 > 0)
3158               {
3159                 if (aVal > aDim1)
3160                   aDim2 = aVal;
3161                 else
3162                 {
3163                   aDim2 = aDim1;
3164                   aDim1 = aVal;
3165                 }
3166               }
3167               else
3168                 aDim1 = aVal;
3169             }
3170             else if(aDRI->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit))) {
3171               //get values
3172               Handle(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit) aRIPAMWU =
3173                 Handle(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit)::DownCast(aDRI);
3174               Standard_Real aVal = aRIPAMWU->GetMeasureWithUnit()->ValueComponent();
3175               StepBasic_Unit anUnit = aRIPAMWU->GetMeasureWithUnit()->UnitComponent();
3176               Standard_Real aFact=1.;
3177               if(anUnit.IsNull()) continue;
3178               if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
3179               Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3180               if(GetAngleConversionFactor(NU,aFact)) aVal=aVal*aFact;
3181               if(aDim2 > 0)
3182               {
3183                 if(aDim1 > aDim2)
3184                 {
3185                   Standard_Real aTmp = aDim1;
3186                   aDim1 = aDim2;
3187                   aDim2 = aTmp;
3188                 }
3189                 if(aVal < aDim1)
3190                   aDim1 = aVal;
3191                 else if(aVal > aDim2)
3192                   aDim2 = aVal;
3193               }
3194               else if(aDim1 > 0)
3195               {
3196                 if (aVal > aDim1)
3197                   aDim2 = aVal;
3198                 else
3199                 {
3200                   aDim2 = aDim1;
3201                   aDim1 = aVal;
3202                 }
3203               }
3204               else
3205                 aDim1 = aVal;
3206             }
3207             else if(aDRI->IsKind(STANDARD_TYPE(StepShape_QualifiedRepresentationItem))) {
3208               //get qualifier
3209               Handle(StepShape_QualifiedRepresentationItem) aQRI =
3210                 Handle(StepShape_QualifiedRepresentationItem)::DownCast(aDRI);
3211               for(Standard_Integer l = 1; l <= aQRI->NbQualifiers(); l++)
3212               {
3213                 aTQ = aQRI->Qualifiers()->Value(l).TypeQualifier();
3214                 aVFTQ = aQRI->Qualifiers()->Value(l).ValueFormatTypeQualifier();
3215               }
3216             }
3217             else if (aDRI->IsKind(STANDARD_TYPE(StepRepr_DescriptiveRepresentationItem))) {
3218               Handle(StepRepr_DescriptiveRepresentationItem) aDescription =
3219                 Handle(StepRepr_DescriptiveRepresentationItem)::DownCast(aDRI);
3220               aDimObj->AddDescription(aDescription->Description(), aDescription->Name());
3221             }
3222             else if(aDRI->IsKind(STANDARD_TYPE(StepRepr_CompoundRepresentationItem))) {
3223               aCRI = Handle(StepRepr_CompoundRepresentationItem)::DownCast(aDRI);
3224             }
3225             else if(aDRI->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
3226             {
3227               anAP = Handle(StepGeom_Axis2Placement3d)::DownCast(aDRI);
3228             }
3229           }
3230         }
3231       }
3232     }
3233     else if (!aPMT.IsNull())
3234     {
3235       StepShape_ToleranceMethodDefinition aTMD = aPMT->Range();
3236       if(aPMT.IsNull()) continue;
3237       if(aTMD.CaseNumber() == 1)
3238         //! 1 -> ToleranceValue from StepShape
3239         //! 2 -> LimitsAndFits from StepShape