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