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