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