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