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