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