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