0026827: Position and orientation for GD&T frames
[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   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     TopoDS_Shape S = STEPConstruct::FindShape ( Styles.TransientProcess(), style->Item() );
918     Standard_Boolean isSkipSHUOstyle = Standard_False;
919     // take shape with real location.
920     while ( IsComponent ) {
921       // take SR of NAUO
922       Handle(StepShape_ShapeRepresentation) aSR;
923       findStyledSR( style, aSR );
924       // search for SR along model
925       if (aSR.IsNull())
926         break;
927 //       Handle(Interface_InterfaceModel) Model = WS->Model();
928       Handle(XSControl_TransferReader) TR = WS->TransferReader();
929       Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
930       Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings( aSR );
931       Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
932       for (subs.Start(); subs.More(); subs.Next()) {
933         aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
934         if ( aSDR.IsNull() )
935           continue;
936         StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
937         Handle(StepRepr_ProductDefinitionShape) PDS = 
938           Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
939         if ( PDS.IsNull() )
940           continue;
941         StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
942         
943         Handle(StepRepr_AssemblyComponentUsage) ACU = 
944           Handle(StepRepr_AssemblyComponentUsage)::DownCast(aCharDef.ProductDefinitionRelationship());
945         // PTV 10.02.2003 skip styled item that refer to SHUO
946         if (ACU->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
947           isSkipSHUOstyle = Standard_True;
948           break;
949         }
950         Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO =
951           Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(ACU);
952         if ( NAUO.IsNull() )
953           continue;
954         
955         TopoDS_Shape aSh;
956         // PTV 10.02.2003 to find component of assembly CORRECTLY
957         STEPConstruct_Tool Tool( WS );
958         TDF_Label aShLab = FindInstance ( NAUO, CTool->ShapeTool(), Tool, PDFileMap, ShapeLabelMap );
959         aSh = CTool->ShapeTool()->GetShape(aShLab);
960 //         Handle(Transfer_Binder) binder = TP->Find(NAUO);
961 //         if ( binder.IsNull() || ! binder->HasResult() )
962 //           continue;
963 //         aSh = TransferBRep::ShapeResult ( TP, binder );
964         if (!aSh.IsNull()) {
965           S = aSh;
966           break;
967         }
968       }
969       break;
970     }
971     if (isSkipSHUOstyle)
972       continue; // skip styled item which refer to SHUO
973     
974     if ( S.IsNull() )
975       continue;
976     
977     if ( ! SurfCol.IsNull() ) {
978       Quantity_Color col;
979       Styles.DecodeColor ( SurfCol, col );
980       if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorSurf ))
981         SetColorToSubshape( CTool, S, col, XCAFDoc_ColorSurf );
982     }
983     if ( ! BoundCol.IsNull() ) {
984       Quantity_Color col;
985       Styles.DecodeColor ( BoundCol, col );
986       if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorCurv ))
987         SetColorToSubshape(  CTool, S, col, XCAFDoc_ColorCurv );
988     }
989     if ( ! CurveCol.IsNull() ) {
990       Quantity_Color col;
991       Styles.DecodeColor ( CurveCol, col );
992       if ( ! CTool->SetColor ( S, col, XCAFDoc_ColorCurv ))
993         SetColorToSubshape(  CTool, S, col, XCAFDoc_ColorCurv );
994     }
995     if ( !IsVisible ) {
996       // sets the invisibility for shape.
997       TDF_Label aInvL;
998       if ( CTool->ShapeTool()->Search( S, aInvL ) )
999         CTool->SetVisibility( aInvL, Standard_False );
1000     }
1001   }
1002   CTool->ReverseChainsOfTreeNodes();
1003   return Standard_True;
1004 }
1005
1006 //=======================================================================
1007 //function : GetLabelFromPD
1008 //purpose  : 
1009 //=======================================================================
1010
1011 static TDF_Label GetLabelFromPD (const Handle(StepBasic_ProductDefinition) &PD,
1012                                  const Handle(XCAFDoc_ShapeTool) &STool,
1013                                  const Handle(Transfer_TransientProcess) &TP,
1014                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1015                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1016 {
1017   TDF_Label L;
1018   if ( PDFileMap.IsBound ( PD ) ) {
1019     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( PD );
1020     if ( ! EF.IsNull() ) {
1021       L = EF->GetLabel();
1022       if ( ! L.IsNull() ) return L;
1023     }
1024   }
1025
1026   TopoDS_Shape S;
1027   Handle(Transfer_Binder) binder = TP->Find(PD);
1028   if ( binder.IsNull() || ! binder->HasResult() ) return L;
1029   S = TransferBRep::ShapeResult ( TP, binder );
1030   if ( S.IsNull() ) return L;
1031
1032   if ( S.IsNull() ) return L;
1033   if ( ShapeLabelMap.IsBound ( S ) )
1034     L = ShapeLabelMap.Find ( S );
1035   if ( L.IsNull() )
1036     STool->Search ( S, L, Standard_True, Standard_True, Standard_False );
1037   return L;
1038 }
1039
1040 //=======================================================================
1041 //function : FindInstance
1042 //purpose  : 
1043 //=======================================================================
1044
1045 TDF_Label STEPCAFControl_Reader::FindInstance (const Handle(StepRepr_NextAssemblyUsageOccurrence) &NAUO,
1046                                                const Handle(XCAFDoc_ShapeTool) &STool,
1047                                                const STEPConstruct_Tool &Tool,
1048                                                const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1049                                                const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1050 {
1051   TDF_Label L;
1052   
1053   // get shape resulting from CDSR (in fact, only location is interesting)
1054   Handle(Transfer_TransientProcess) TP = Tool.TransientProcess();
1055   Handle(Transfer_Binder) binder = TP->Find(NAUO);
1056   if ( binder.IsNull() || ! binder->HasResult() ) {
1057 #ifdef OCCT_DEBUG
1058     cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << endl;
1059 #endif
1060     return L;
1061   }
1062   
1063   TopoDS_Shape S = TransferBRep::ShapeResult ( TP, binder );
1064   if ( S.IsNull() ) {
1065 #ifdef OCCT_DEBUG
1066     cout << "Error: STEPCAFControl_Reader::FindInstance: NAUO is not mapped to shape" << endl;
1067 #endif
1068     return L;
1069   }
1070
1071   // find component`s original label
1072   Handle(StepBasic_ProductDefinition) PD = NAUO->RelatedProductDefinition();
1073   if ( PD.IsNull() ) return L;
1074   TDF_Label Lref = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
1075   if ( Lref.IsNull() ) return L;
1076   
1077   // find main shape (assembly) label
1078   PD.Nullify();
1079   PD = NAUO->RelatingProductDefinition();
1080   if ( PD.IsNull() ) return L;
1081   TDF_Label L0 = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
1082   if ( L0.IsNull() ) return L;
1083   
1084   // if CDSR and NAUO are reversed, swap labels
1085   Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1086   Interface_EntityIterator subs1 = Tool.Graph().Sharings(NAUO);
1087   for (subs1.Start(); subs1.More(); subs1.Next()) {
1088     Handle(StepRepr_ProductDefinitionShape) PDS = 
1089       Handle(StepRepr_ProductDefinitionShape)::DownCast(subs1.Value());
1090     if(PDS.IsNull()) continue;
1091     Interface_EntityIterator subs2 = Tool.Graph().Sharings(PDS);
1092     for (subs2.Start(); subs2.More(); subs2.Next()) {
1093       Handle(StepShape_ContextDependentShapeRepresentation) CDSRtmp = 
1094         Handle(StepShape_ContextDependentShapeRepresentation)::DownCast(subs2.Value());
1095       if (CDSRtmp.IsNull()) continue;
1096       CDSR = CDSRtmp;
1097     }
1098   }
1099   if (CDSR.IsNull()) return L;
1100 //  if ( STEPConstruct_Assembly::CheckSRRReversesNAUO ( Tool.Model(), CDSR ) ) {
1101 //    TDF_Label Lsw = L0; L0 = Lref; Lref = Lsw;
1102 //  }
1103   
1104   // iterate on components to find proper one
1105   TDF_LabelSequence seq;
1106   XCAFDoc_ShapeTool::GetComponents ( L0, seq );
1107   for ( Standard_Integer k=1; L.IsNull() && k <= seq.Length(); k++ ) {
1108     TDF_Label Lcomp = seq(k), Lref2;
1109     if ( XCAFDoc_ShapeTool::GetReferredShape ( Lcomp, Lref2 ) && 
1110         Lref2 == Lref &&
1111         S.Location() == XCAFDoc_ShapeTool::GetLocation ( Lcomp ) ) 
1112       L = Lcomp;
1113   }
1114   
1115   return L;
1116 }
1117
1118 //=======================================================================
1119 //function : ReadNames
1120 //purpose  : 
1121 //=======================================================================
1122
1123 Standard_Boolean STEPCAFControl_Reader::ReadNames (const Handle(XSControl_WorkSession) &WS,
1124                                                    Handle(TDocStd_Document)& Doc,
1125                                                    const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1126                                                    const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1127 {
1128   // get starting data
1129   Handle(Interface_InterfaceModel) Model = WS->Model();
1130   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1131   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1132   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1133   if ( STool.IsNull() ) return Standard_False;
1134   STEPConstruct_Tool Tool ( WS );
1135
1136   // iterate on model to find all SDRs and CDSRs
1137   Standard_Integer nb = Model->NbEntities();
1138   Handle(Standard_Type) tNAUO = STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence);
1139   Handle(Standard_Type) tPD  = STANDARD_TYPE(StepBasic_ProductDefinition);
1140   Handle(TCollection_HAsciiString) name;
1141   TDF_Label L;
1142   for (Standard_Integer i = 1; i <= nb; i++) {
1143     Handle(Standard_Transient) enti = Model->Value(i);
1144
1145     // get description of NAUO
1146     if ( enti->DynamicType() == tNAUO ) {
1147       L.Nullify();
1148       Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO = 
1149         Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(enti);
1150       if(NAUO.IsNull()) continue;
1151       Interface_EntityIterator subs = WS->Graph().Sharings(NAUO);
1152       for (subs.Start(); subs.More(); subs.Next()) {
1153         Handle(StepRepr_ProductDefinitionShape) PDS = 
1154           Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
1155         if(PDS.IsNull()) continue;
1156         Handle(StepBasic_ProductDefinitionRelationship) PDR = PDS->Definition().ProductDefinitionRelationship();
1157         if ( PDR.IsNull() ) continue;
1158         if ( PDR->HasDescription() && 
1159             PDR->Description()->Length() >0 ) name = PDR->Description();
1160         else if ( !PDR->Name().IsNull() && PDR->Name()->Length() >0 ) name = PDR->Name();
1161         else if ( !PDR->Id().IsNull()) name = PDR->Id();
1162         else name = new TCollection_HAsciiString;
1163       }
1164       // find proper label
1165       L = FindInstance ( NAUO, STool, Tool, PDFileMap, ShapeLabelMap );
1166       if ( L.IsNull() ) continue;
1167       TCollection_ExtendedString str ( name->String() );
1168       TDataStd_Name::Set ( L, str );
1169     }
1170
1171     // for PD get name of associated product
1172     if ( enti->DynamicType() == tPD ) {
1173       L.Nullify();
1174       Handle(StepBasic_ProductDefinition) PD = 
1175         Handle(StepBasic_ProductDefinition)::DownCast(enti);
1176       if(PD.IsNull()) continue;
1177       Handle(StepBasic_Product) Prod = (!PD->Formation().IsNull() ? PD->Formation()->OfProduct() : NULL);
1178       if (Prod.IsNull())
1179         name = new TCollection_HAsciiString;
1180       else if (!Prod->Name().IsNull() && Prod->Name()->UsefullLength() > 0) 
1181         name = Prod->Name();
1182       else if (!Prod->Id().IsNull()) 
1183         name = Prod->Id();
1184       else 
1185         name = new TCollection_HAsciiString;
1186       L = GetLabelFromPD ( PD, STool, TP, PDFileMap, ShapeLabelMap );
1187       if ( L.IsNull() ) continue;
1188       TCollection_ExtendedString str ( name->String() );
1189       TDataStd_Name::Set ( L, str );
1190     }
1191     // set a name to the document
1192     //TCollection_ExtendedString str ( name->String() );
1193     //TDataStd_Name::Set ( L, str );
1194   }
1195
1196   return Standard_True;
1197 }
1198
1199 //=======================================================================
1200 //function : GetLabelFromPD
1201 //purpose  : 
1202 //=======================================================================
1203
1204 static TDF_Label GetLabelFromPD (const Handle(StepBasic_ProductDefinition) &PD,
1205                                  const Handle(XCAFDoc_ShapeTool) &STool,
1206                                  const STEPConstruct_ValidationProps &Props,
1207                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1208                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1209 {
1210   TDF_Label L;
1211   if ( PDFileMap.IsBound ( PD ) ) {
1212     Handle(STEPCAFControl_ExternFile) EF = PDFileMap.Find ( PD );
1213     if ( ! EF.IsNull() ) {
1214       L = EF->GetLabel();
1215       if ( ! L.IsNull() ) return L;
1216     }
1217   }
1218   TopoDS_Shape S = Props.GetPropShape ( PD );
1219   if ( S.IsNull() ) return L;
1220   if ( ShapeLabelMap.IsBound ( S ) )
1221     L = ShapeLabelMap.Find ( S );
1222   if ( L.IsNull() )
1223     STool->Search ( S, L, Standard_True, Standard_True, Standard_False );
1224   return L;
1225 }
1226
1227 //=======================================================================
1228 //function : ReadValProps
1229 //purpose  : 
1230 //=======================================================================
1231
1232 Standard_Boolean STEPCAFControl_Reader::ReadValProps (const Handle(XSControl_WorkSession) &WS,
1233                                                       Handle(TDocStd_Document)& Doc,
1234                                                       const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1235                                                       const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1236 {
1237   // get starting data
1238   Handle(Interface_InterfaceModel) Model = WS->Model();
1239   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1240   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1241   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1242   if ( STool.IsNull() ) return Standard_False;
1243
1244   // load props from the STEP model
1245   TColStd_SequenceOfTransient props;
1246   STEPConstruct_ValidationProps Props ( WS );
1247   if ( ! Props.LoadProps ( props ) ) {
1248 #ifdef OCCT_DEBUG
1249     cout << "Warning: no validation props found in the model" << endl;
1250 #endif
1251     return Standard_False;
1252   }
1253
1254   // interpret props one by one
1255   for (Standard_Integer i = 1; i <= props.Length(); i ++) {
1256     Handle(StepRepr_PropertyDefinitionRepresentation) PDR = 
1257       Handle(StepRepr_PropertyDefinitionRepresentation)::DownCast ( props.Value(i) );
1258     if ( PDR.IsNull() ) continue;
1259
1260     TDF_Label L;
1261
1262     Handle(StepRepr_PropertyDefinition) PD = PDR->Definition().PropertyDefinition();
1263     Interface_EntityIterator subs = Props.Graph().Shareds(PD);
1264     for (subs.Start(); L.IsNull() && subs.More(); subs.Next()) {
1265       if ( subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape)) ) {
1266         Handle(StepRepr_ProductDefinitionShape) PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(subs.Value());
1267         if(PDS.IsNull()) continue;
1268         // find corresponding NAUO
1269         Handle(StepRepr_NextAssemblyUsageOccurrence) NAUO;
1270         Interface_EntityIterator subs1 = Props.Graph().Shareds(PDS);
1271         for (subs1.Start(); NAUO.IsNull() && subs1.More(); subs1.Next()) {
1272           if ( subs1.Value()->IsKind(STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence)) ) 
1273             NAUO = Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subs1.Value());
1274         }
1275         if ( !NAUO.IsNull() ) {
1276           L = FindInstance ( NAUO, STool, WS, PDFileMap, ShapeLabelMap );
1277           if ( L.IsNull() ) continue;
1278         }
1279         else {
1280           // find corresponding ProductDefinition:
1281           Handle(StepBasic_ProductDefinition) ProdDef;
1282           Interface_EntityIterator subsPDS = Props.Graph().Shareds(PDS);
1283           for (subsPDS.Start(); ProdDef.IsNull() && subsPDS.More(); subsPDS.Next()) {
1284             if ( subsPDS.Value()->IsKind(STANDARD_TYPE(StepBasic_ProductDefinition)) ) 
1285               ProdDef = Handle(StepBasic_ProductDefinition)::DownCast(subsPDS.Value());
1286           }
1287           if ( ProdDef.IsNull() ) continue;
1288           L = GetLabelFromPD ( ProdDef, STool, Props, PDFileMap, ShapeLabelMap );
1289         }
1290       }
1291
1292       if ( subs.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)) ) {
1293         Handle(StepRepr_ShapeAspect) SA = Handle(StepRepr_ShapeAspect)::DownCast(subs.Value());
1294         if(SA.IsNull()) continue;
1295         // find ShapeRepresentation
1296         Handle(StepShape_ShapeRepresentation) SR;
1297         Interface_EntityIterator subs1 = Props.Graph().Sharings(SA);
1298         for(subs1.Start(); subs1.More() && SR.IsNull(); subs1.Next()) {
1299           Handle(StepRepr_PropertyDefinition) PropD1 = 
1300             Handle(StepRepr_PropertyDefinition)::DownCast(subs1.Value());
1301           if(PropD1.IsNull()) continue;
1302           Interface_EntityIterator subs2 = Props.Graph().Sharings(PropD1);
1303           for(subs2.Start(); subs2.More() && SR.IsNull(); subs2.Next()) {
1304             Handle(StepShape_ShapeDefinitionRepresentation) SDR =
1305               Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs2.Value());
1306             if(SDR.IsNull()) continue;
1307             SR = Handle(StepShape_ShapeRepresentation)::DownCast(SDR->UsedRepresentation());
1308           }
1309         }
1310         if(SR.IsNull()) continue;
1311         Handle(Transfer_Binder) binder;
1312         for(Standard_Integer ir=1; ir<=SR->NbItems() && binder.IsNull(); ir++) {
1313           if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_SolidModel))) {
1314             Handle(StepShape_SolidModel) SM = 
1315               Handle(StepShape_SolidModel)::DownCast(SR->ItemsValue(ir));
1316             binder = TP->Find(SM);
1317           }
1318           else if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_ShellBasedSurfaceModel))) {
1319             Handle(StepShape_ShellBasedSurfaceModel) SBSM =
1320               Handle(StepShape_ShellBasedSurfaceModel)::DownCast(SR->ItemsValue(ir));
1321             binder = TP->Find(SBSM);
1322           }
1323           else if(SR->ItemsValue(ir)->IsKind(STANDARD_TYPE(StepShape_GeometricSet))) {
1324             Handle(StepShape_GeometricSet) GS =
1325               Handle(StepShape_GeometricSet)::DownCast(SR->ItemsValue(ir));
1326             binder = TP->Find(GS);
1327           }
1328         }
1329         if ( binder.IsNull() || ! binder->HasResult() ) continue;
1330         TopoDS_Shape S;
1331         S = TransferBRep::ShapeResult ( TP, binder );
1332         if(S.IsNull()) continue;
1333         if ( ShapeLabelMap.IsBound ( S ) )
1334           L = ShapeLabelMap.Find ( S );
1335         if ( L.IsNull() )
1336           STool->Search ( S, L, Standard_True, Standard_True, Standard_True );
1337       }
1338     }
1339
1340     if(L.IsNull()) continue;
1341       
1342     // decode validation properties
1343     Handle(StepRepr_Representation) rep = PDR->UsedRepresentation();
1344     for ( Standard_Integer j=1; j <= rep->NbItems(); j++ ) {
1345       Handle(StepRepr_RepresentationItem) ent = rep->ItemsValue(j);
1346       Standard_Boolean isArea;
1347       Standard_Real val;
1348       gp_Pnt pos;
1349       if ( Props.GetPropReal ( ent, val, isArea ) ) {
1350         if ( isArea ) XCAFDoc_Area::Set ( L, val );
1351         else XCAFDoc_Volume::Set ( L, val );
1352       }
1353       else if ( Props.GetPropPnt ( ent, rep->ContextOfItems(), pos ) ) {
1354         XCAFDoc_Centroid::Set ( L, pos );
1355       }
1356     }
1357   }
1358   return Standard_True;
1359 }
1360
1361 //=======================================================================
1362 //function : ReadLayers
1363 //purpose  : 
1364 //=======================================================================
1365
1366 Standard_Boolean STEPCAFControl_Reader::ReadLayers (const Handle(XSControl_WorkSession) &WS,
1367                                                     Handle(TDocStd_Document)& Doc) const
1368 {
1369   Handle(Interface_InterfaceModel) Model = WS->Model();
1370   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1371   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1372   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( Doc->Main() );
1373   if ( STool.IsNull() ) return Standard_False;
1374   Handle(XCAFDoc_LayerTool) LTool = XCAFDoc_DocumentTool::LayerTool( Doc->Main() );
1375   if ( LTool.IsNull() ) return Standard_False;
1376   
1377   Handle(Standard_Type) tSVPLA = STANDARD_TYPE(StepVisual_PresentationLayerAssignment);
1378   Standard_Integer nb = Model->NbEntities();
1379   Handle(TCollection_HAsciiString) name;
1380   
1381   for (Standard_Integer i = 1; i <= nb; i ++) {
1382     Handle(Standard_Transient) enti = Model->Value(i);
1383     if ( ! enti->IsKind ( tSVPLA ) ) continue;
1384     Handle(StepVisual_PresentationLayerAssignment) SVPLA = 
1385       Handle(StepVisual_PresentationLayerAssignment)::DownCast(enti);
1386     
1387     Handle(TCollection_HAsciiString) descr = SVPLA->Description();
1388     Handle(TCollection_HAsciiString) hName = SVPLA->Name();
1389     TCollection_ExtendedString aLayerName ( hName->String() );
1390      
1391     // find a target shape and its label in the document
1392     for (Standard_Integer j = 1; j <= SVPLA->NbAssignedItems(); j++ ) {
1393       StepVisual_LayeredItem LI = SVPLA->AssignedItemsValue(j);
1394       Handle(Transfer_Binder) binder = TP->Find( LI.Value() );
1395       if ( binder.IsNull() || ! binder->HasResult() ) continue;
1396       
1397       TopoDS_Shape S = TransferBRep::ShapeResult ( TP, binder );
1398       if ( S.IsNull() ) continue;
1399         
1400       TDF_Label shL;
1401       if ( ! STool->Search ( S, shL, Standard_True, Standard_True, Standard_True ) ) continue;
1402       LTool->SetLayer ( shL, aLayerName );
1403     }
1404     
1405     // check invisibility
1406     Interface_EntityIterator subs = WS->Graph().Sharings(SVPLA);
1407     for (subs.Start(); subs.More(); subs.Next()) {
1408       if ( ! subs.Value()->IsKind(STANDARD_TYPE(StepVisual_Invisibility)) ) continue;
1409 #ifdef OCCT_DEBUG
1410       cout<< "\tLayer \"" << aLayerName << "\" is invisible"<<endl;
1411 #endif
1412       //TDF_Label InvLayerLab = LTool->FindLayer(aLayerName);
1413       TDF_Label InvLayerLab = LTool->AddLayer(aLayerName); //skl for OCC3926
1414       Handle(TDataStd_UAttribute) aUAttr;
1415       aUAttr->Set( InvLayerLab, XCAFDoc::InvisibleGUID() );
1416     }
1417   }
1418   return Standard_True;
1419 }
1420
1421 //=======================================================================
1422 //function : ReadSHUOs
1423 //purpose  : 
1424 //=======================================================================
1425
1426 static Standard_Boolean findNextSHUOlevel (const Handle(XSControl_WorkSession) &WS,
1427                                            const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1428                                            const Handle(XCAFDoc_ShapeTool)& STool,
1429                                            const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1430                                            const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap,
1431                                            TDF_LabelSequence& aLabels)
1432 {
1433   Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings(SHUO);
1434   Handle(StepRepr_SpecifiedHigherUsageOccurrence) subSHUO;
1435   for (subs.Start(); subs.More(); subs.Next()) {
1436     if (subs.Value()->IsKind(STANDARD_TYPE(StepRepr_SpecifiedHigherUsageOccurrence))) {
1437       subSHUO = Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(subs.Value());
1438       break;
1439     }
1440   }
1441   if (subSHUO.IsNull())
1442     return Standard_False;
1443   
1444   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO = subSHUO->NextUsage();
1445   if (NUNAUO.IsNull())
1446     return Standard_False;
1447 //   Handle(Interface_InterfaceModel) Model = WS->Model();
1448 //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1449 //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1450 //   Handle(Transfer_Binder) binder = TP->Find(NUNAUO);
1451 //   if ( binder.IsNull() || ! binder->HasResult() )
1452 //     return Standard_False;
1453 //   TopoDS_Shape NUSh = TransferBRep::ShapeResult ( TP, binder );
1454   // get label of NAUO next level
1455   TDF_Label NULab;
1456   STEPConstruct_Tool Tool( WS );
1457   NULab = STEPCAFControl_Reader::FindInstance ( NUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1458 //   STool->Search(NUSh, NUlab);
1459   if (NULab.IsNull())
1460     return Standard_False;
1461   aLabels.Append( NULab );
1462   // and check by recurse.
1463   findNextSHUOlevel( WS, subSHUO, STool, PDFileMap, ShapeLabelMap, aLabels );
1464   return Standard_True;
1465 }
1466
1467
1468 //=======================================================================
1469 //function : setSHUOintoDoc
1470 //purpose  : auxilary
1471 //=======================================================================
1472 static TDF_Label setSHUOintoDoc (const Handle(XSControl_WorkSession) &WS,
1473                                  const Handle(StepRepr_SpecifiedHigherUsageOccurrence)& SHUO,
1474                                  const Handle(XCAFDoc_ShapeTool)& STool,
1475                                  const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1476                                  const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap)
1477 {
1478   TDF_Label aMainLabel;
1479   // get upper usage NAUO from SHUO.
1480   Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO =
1481     Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(SHUO->UpperUsage());
1482   Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO = SHUO->NextUsage();
1483   if ( UUNAUO.IsNull() || NUNAUO.IsNull() ) {
1484 #ifdef OCCT_DEBUG
1485     cout << "Warning: " << __FILE__ <<": Upper_usage or Next_usage of styled SHUO is null. Skip it" << endl;
1486 #endif
1487     return aMainLabel;
1488   }
1489 //   Handle(Interface_InterfaceModel) Model = WS->Model();
1490 //   Handle(XSControl_TransferReader) TR = WS->TransferReader();
1491 //   Handle(Transfer_TransientProcess) TP = TR->TransientProcess();
1492 //   TopoDS_Shape UUSh, NUSh;
1493 //   Handle(Transfer_Binder) binder = TP->Find(UUNAUO);
1494 //   if ( binder.IsNull() || ! binder->HasResult() )
1495 //     return aMainLabel;
1496 //   UUSh = TransferBRep::ShapeResult ( TP, binder );
1497 //   binder = TP->Find(NUNAUO);
1498 //   if ( binder.IsNull() || ! binder->HasResult() )
1499 //     return aMainLabel;
1500 //   NUSh = TransferBRep::ShapeResult ( TP, binder );
1501
1502   // get first labels for first SHUO attribute
1503   TDF_Label UULab, NULab;
1504   STEPConstruct_Tool Tool( WS );
1505   UULab = STEPCAFControl_Reader::FindInstance ( UUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1506   NULab = STEPCAFControl_Reader::FindInstance ( NUNAUO, STool, Tool, PDFileMap, ShapeLabelMap ); 
1507   
1508 //   STool->Search(UUSh, UULab);
1509 //   STool->Search(NUSh, NULab);
1510   if (UULab.IsNull() || NULab.IsNull()) return aMainLabel;
1511   //create sequence fo labels to set SHUO structure into the document
1512   TDF_LabelSequence ShuoLabels;
1513   ShuoLabels.Append( UULab );
1514   ShuoLabels.Append( NULab );
1515   // add all other labels of sub SHUO entities
1516   findNextSHUOlevel( WS, SHUO, STool, PDFileMap, ShapeLabelMap, ShuoLabels );
1517   // last accord for SHUO
1518   Handle(XCAFDoc_GraphNode) anSHUOAttr;
1519   if ( STool->SetSHUO( ShuoLabels, anSHUOAttr ) )
1520     aMainLabel = anSHUOAttr->Label();
1521   
1522   return aMainLabel;
1523 }
1524
1525
1526 //=======================================================================
1527 //function : ReadSHUOs
1528 //purpose  : 
1529 //=======================================================================
1530
1531 Standard_Boolean STEPCAFControl_Reader::ReadSHUOs (const Handle(XSControl_WorkSession) &WS,
1532                                                    Handle(TDocStd_Document)& Doc,
1533                                                    const STEPCAFControl_DataMapOfPDExternFile &PDFileMap,
1534                                                    const XCAFDoc_DataMapOfShapeLabel &ShapeLabelMap) const
1535 {
1536   // the big part code duplication from ReadColors.
1537   // It is possible to share this code functionality, just to decide how ???
1538   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( Doc->Main() );
1539   Handle(XCAFDoc_ShapeTool) STool = CTool->ShapeTool();
1540   
1541   STEPConstruct_Styles Styles ( WS );
1542   if ( ! Styles.LoadStyles() ) {
1543 #ifdef OCCT_DEBUG
1544     cout << "Warning: no styles are found in the model" << endl;
1545 #endif
1546     return Standard_False;
1547   }
1548   // searching for invisible items in the model
1549   Handle(TColStd_HSequenceOfTransient) aHSeqOfInvisStyle = new TColStd_HSequenceOfTransient;
1550   Styles.LoadInvisStyles( aHSeqOfInvisStyle );
1551   // parse and search for color attributes
1552   Standard_Integer nb = Styles.NbStyles();
1553   for ( Standard_Integer i=1; i <= nb; i++ ) {
1554     Handle(StepVisual_StyledItem) style = Styles.Style ( i );
1555     if ( style.IsNull() ) continue;
1556     
1557     Standard_Boolean IsVisible = Standard_True;
1558     // check the visibility of styled item.
1559     for (Standard_Integer si = 1; si <= aHSeqOfInvisStyle->Length(); si++ ) {
1560       if ( style != aHSeqOfInvisStyle->Value( si ) )
1561         continue;
1562       // found that current style is invisible.
1563 #ifdef OCCT_DEBUG
1564       cout << "Warning: item No " << i << "(" << style->Item()->DynamicType()->Name() << ") is invisible" << endl;
1565 #endif
1566       IsVisible = Standard_False;
1567       break;
1568     }
1569
1570     Handle(StepVisual_Colour) SurfCol, BoundCol, CurveCol;
1571     // check if it is component style
1572     Standard_Boolean IsComponent = Standard_False;
1573     if ( ! Styles.GetColors ( style, SurfCol, BoundCol, CurveCol, IsComponent ) && IsVisible )
1574       continue;
1575     if (!IsComponent)
1576       continue;
1577     Handle(StepShape_ShapeRepresentation) aSR;
1578     findStyledSR( style, aSR );
1579     // search for SR along model
1580     if ( aSR.IsNull() )
1581       continue;
1582     Interface_EntityIterator subs = WS->HGraph()->Graph().Sharings( aSR );
1583     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
1584     for (subs.Start(); subs.More(); subs.Next()) {
1585       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs.Value());
1586       if ( aSDR.IsNull() )
1587         continue;
1588       StepRepr_RepresentedDefinition aPDSselect = aSDR->Definition();
1589       Handle(StepRepr_ProductDefinitionShape) PDS = 
1590         Handle(StepRepr_ProductDefinitionShape)::DownCast(aPDSselect.PropertyDefinition());
1591       if ( PDS.IsNull() )
1592         continue;
1593       StepRepr_CharacterizedDefinition aCharDef = PDS->Definition();
1594       Handle(StepRepr_SpecifiedHigherUsageOccurrence) SHUO =
1595         Handle(StepRepr_SpecifiedHigherUsageOccurrence)::DownCast(aCharDef.ProductDefinitionRelationship());
1596       if ( SHUO.IsNull() )
1597         continue;
1598       
1599       // set the SHUO structure to the document
1600       TDF_Label aLabelForStyle = setSHUOintoDoc( WS, SHUO, STool, PDFileMap, ShapeLabelMap );
1601       if ( aLabelForStyle.IsNull() ) {
1602 #ifdef OCCT_DEBUG
1603         cout << "Warning: " << __FILE__ <<": coudnot create SHUO structure in the document" << endl;
1604 #endif
1605         continue;
1606       }
1607       // now set the style to the SHUO main label.
1608       if ( ! SurfCol.IsNull() ) {
1609         Quantity_Color col;
1610         Styles.DecodeColor ( SurfCol, col );
1611         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorSurf );
1612       }
1613       if ( ! BoundCol.IsNull() ) {
1614         Quantity_Color col;
1615         Styles.DecodeColor ( BoundCol, col );
1616         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorCurv );
1617       }
1618       if ( ! CurveCol.IsNull() ) {
1619         Quantity_Color col;
1620         Styles.DecodeColor ( CurveCol, col );
1621         CTool->SetColor ( aLabelForStyle, col, XCAFDoc_ColorCurv );
1622       }
1623       if ( !IsVisible )
1624         // sets the invisibility for shape.
1625         CTool->SetVisibility( aLabelForStyle, Standard_False );
1626       
1627     } // end search SHUO by SDR
1628   } // end iterates on styles
1629       
1630   return Standard_True;
1631 }
1632
1633
1634 //=======================================================================
1635 //function : GetLengthConversionFactor
1636 //purpose  : 
1637 //=======================================================================
1638 static Standard_Boolean GetLengthConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1639                                                   Standard_Real& afact)
1640 {
1641   afact=1.;
1642   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndLengthUnit)) ) return Standard_False;
1643   Handle(StepBasic_ConversionBasedUnitAndLengthUnit) CBULU =
1644     Handle(StepBasic_ConversionBasedUnitAndLengthUnit)::DownCast(NU);
1645   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBULU->ConversionFactor();
1646   afact = MWUCBU->ValueComponent();
1647   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1648   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1649     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1650     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1651       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1652       if(SU->Name()==StepBasic_sunMetre) {
1653         if(SU->HasPrefix()) 
1654           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1655         // convert m to mm
1656         afact *= 1000.;
1657       }
1658     }
1659   }
1660   return Standard_True;
1661 }
1662
1663
1664 //=======================================================================
1665 //function : GetAngleConversionFactor
1666 //purpose  : 
1667 //=======================================================================
1668 static Standard_Boolean GetAngleConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1669                                                   Standard_Real& afact)
1670 {
1671   afact=1.;
1672   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndPlaneAngleUnit)) ) return Standard_False;
1673   Handle(StepBasic_ConversionBasedUnitAndPlaneAngleUnit) CBULU =
1674     Handle(StepBasic_ConversionBasedUnitAndPlaneAngleUnit)::DownCast(NU);
1675   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBULU->ConversionFactor();
1676   afact = MWUCBU->ValueComponent();
1677   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1678   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1679     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1680     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1681       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1682       if(SU->Name()==StepBasic_sunRadian) {
1683         if(SU->HasPrefix()) 
1684           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1685         // convert radian to deg
1686         afact *= 180/M_PI;
1687       }
1688     }
1689   }
1690   return Standard_True;
1691 }
1692
1693 //=======================================================================
1694 //function : GetMassConversionFactor
1695 //purpose  : 
1696 //=======================================================================
1697 static Standard_Boolean GetMassConversionFactor(Handle(StepBasic_NamedUnit)& NU,
1698                                                 Standard_Real& afact)
1699 {
1700   afact=1.;
1701   if( !NU->IsKind(STANDARD_TYPE(StepBasic_ConversionBasedUnitAndMassUnit)) ) return Standard_False;
1702   Handle(StepBasic_ConversionBasedUnitAndMassUnit) CBUMU =
1703     Handle(StepBasic_ConversionBasedUnitAndMassUnit)::DownCast(NU);
1704   Handle(StepBasic_MeasureWithUnit) MWUCBU = CBUMU->ConversionFactor();
1705   afact = MWUCBU->ValueComponent();
1706   StepBasic_Unit anUnit2 = MWUCBU->UnitComponent();
1707   if(anUnit2.CaseNum(anUnit2.Value())==1) {
1708     Handle(StepBasic_NamedUnit) NU2 = anUnit2.NamedUnit();
1709     if(NU2->IsKind(STANDARD_TYPE(StepBasic_SiUnit))) {
1710       Handle(StepBasic_SiUnit) SU = Handle(StepBasic_SiUnit)::DownCast(NU2);
1711       if(SU->Name()==StepBasic_sunGram) {
1712         if(SU->HasPrefix())
1713           afact *= STEPConstruct_UnitContext::ConvertSiPrefix (SU->Prefix());
1714       }
1715     }
1716   }
1717   return Standard_True;
1718 }
1719
1720 //=======================================================================
1721 //function : readAnnotation
1722 //purpose  : return annotation plane and position for given GDT
1723 // (Dimension, Geometric_Tolerance, Datum_Feature or Placed_Datum_Target_Feature)
1724 //=======================================================================
1725 void readAnnotation(const Handle(XSControl_TransferReader)& theTR, 
1726   const Handle(Standard_Transient) theGDT,
1727   const Handle(Standard_Transient)& theDimObject)
1728 {
1729   Handle(TCollection_HAsciiString) aPresentName;
1730   TopoDS_Compound aResAnnotation;
1731   Handle(Transfer_TransientProcess) aTP = theTR->TransientProcess();
1732   const Interface_Graph& aGraph = aTP->Graph();
1733   // find the proper DraughtingModelItemAssociation
1734   Interface_EntityIterator subs = aGraph.Sharings(theGDT);
1735   Handle(StepAP242_DraughtingModelItemAssociation) aDMIA;
1736   for (subs.Start(); subs.More() && aDMIA.IsNull(); subs.Next()) {
1737     if (!subs.Value()->IsKind(STANDARD_TYPE(StepAP242_DraughtingModelItemAssociation)))
1738       continue;
1739     aDMIA = Handle(StepAP242_DraughtingModelItemAssociation)::DownCast(subs.Value());
1740     Handle(TCollection_HAsciiString) aName = aDMIA->Name();
1741     aName->LowerCase();
1742     if (!aName->Search(new TCollection_HAsciiString("pmi representation to presentation link"))) {
1743       aDMIA = NULL;
1744     }
1745   }
1746   if (aDMIA.IsNull() || aDMIA->NbIdentifiedItem() == 0)
1747     return;
1748
1749   // retrieve AnnotationPlane
1750   Standard_Boolean isHasPlane = Standard_False;
1751   gp_Ax2 aPlaneAxes;
1752   Handle(StepRepr_RepresentationItem) aDMIAE = aDMIA->IdentifiedItemValue(1);
1753   if (aDMIAE.IsNull())
1754     return;
1755   subs = aGraph.Sharings(aDMIAE);
1756   Handle(StepVisual_AnnotationPlane) anAnPlane;
1757   for (subs.Start(); subs.More() && anAnPlane.IsNull(); subs.Next()) {
1758     anAnPlane = Handle(StepVisual_AnnotationPlane)::DownCast(subs.Value());
1759   }
1760   if (!anAnPlane.IsNull()) {
1761     Handle(StepRepr_RepresentationItem) aPlaneItem = anAnPlane->Item();
1762     Handle(StepGeom_Axis2Placement3d) aA2P3D;
1763     //retrieve axes from AnnotationPlane
1764     if (aPlaneItem->IsKind(STANDARD_TYPE(StepGeom_Plane))) {
1765       Handle(StepGeom_Plane) aPlane = Handle(StepGeom_Plane)::DownCast(aPlaneItem);
1766       aA2P3D = aPlane->Position();
1767     }
1768     else if (aPlaneItem->IsKind(STANDARD_TYPE(StepVisual_PlanarBox))) {
1769       Handle(StepVisual_PlanarBox) aBox = Handle(StepVisual_PlanarBox)::DownCast(aPlaneItem);
1770       aA2P3D = aBox->Placement().Axis2Placement3d();
1771     }
1772     // build gp_Ax2 from axes
1773     if (!aA2P3D.IsNull())
1774     {
1775       Handle(StepGeom_Direction) anAxis = aA2P3D->Axis(), 
1776         aRefDir = aA2P3D->RefDirection();
1777       if (!anAxis.IsNull() && !aRefDir.IsNull()) {
1778         Handle(TColStd_HArray1OfReal) aCoords;
1779         aCoords = anAxis->DirectionRatios();
1780         gp_Dir aXDir(aCoords->Value(1), aCoords->Value(2), aCoords->Value(3));
1781         aCoords = aRefDir->DirectionRatios();
1782         gp_Dir aYDir(aCoords->Value(1), aCoords->Value(2), aCoords->Value(3));
1783         aPlaneAxes.SetDirection(aXDir.Crossed(aYDir));
1784         aPlaneAxes.SetYDirection(aYDir);
1785         //set location of the annotation plane
1786         Handle(TColStd_HArray1OfReal) aLocCoords;
1787         Handle(StepGeom_CartesianPoint) aLoc = aA2P3D->Location();
1788         gp_Pnt aLocPos( aLoc->CoordinatesValue (1), aLoc->CoordinatesValue (2), aLoc->CoordinatesValue (3));
1789         aPlaneAxes.SetLocation(aLocPos);
1790         isHasPlane = Standard_True;
1791       }
1792     }
1793   }
1794
1795   // set plane axes to XCAF
1796   if (isHasPlane) {
1797     if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DimensionObject))) {
1798       Handle(XCAFDimTolObjects_DimensionObject) anObj = 
1799         Handle(XCAFDimTolObjects_DimensionObject)::DownCast(theDimObject);
1800
1801       Handle(TColgp_HArray1OfPnt) aPnts = new TColgp_HArray1OfPnt(1, 1);
1802       anObj->SetPlane(aPlaneAxes);
1803     
1804
1805     }
1806     else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DatumObject))) {
1807       Handle(XCAFDimTolObjects_DatumObject) anObj =
1808         Handle(XCAFDimTolObjects_DatumObject)::DownCast(theDimObject);
1809       anObj->SetPlane(aPlaneAxes);
1810       
1811     }
1812     else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_GeomToleranceObject))) {
1813       Handle(XCAFDimTolObjects_GeomToleranceObject) anObj =
1814         Handle(XCAFDimTolObjects_GeomToleranceObject)::DownCast(theDimObject);
1815       anObj->SetPlane(aPlaneAxes);
1816      
1817     }
1818   }
1819
1820
1821   // Retrieve presentation
1822   Handle(StepVisual_AnnotationCurveOccurrence) anACO;
1823   NCollection_Vector<Handle(StepVisual_TessellatedAnnotationOccurrence)> aTesselations;
1824   NCollection_Vector<Handle(StepVisual_StyledItem)> anAnnotations;
1825   if (aDMIAE->IsKind(STANDARD_TYPE(StepVisual_AnnotationCurveOccurrence))) 
1826   {
1827     anACO = Handle(StepVisual_AnnotationCurveOccurrence)::DownCast(aDMIAE);
1828     if( !anACO.IsNull())
1829       anAnnotations.Append(anACO);
1830   }
1831
1832   else if (aDMIAE->IsKind(STANDARD_TYPE(StepVisual_DraughtingCallout))) 
1833   {
1834     Handle(StepVisual_DraughtingCallout) aDCallout =
1835       Handle(StepVisual_DraughtingCallout)::DownCast(aDMIAE);
1836     for (Standard_Integer i = 1; i <= aDCallout->NbContents() && anACO.IsNull(); i++) {
1837       anACO = aDCallout->ContentsValue(i).AnnotationCurveOccurrence();
1838       if(!anACO.IsNull())
1839       {
1840         anAnnotations.Append(anACO);
1841         continue;
1842       }
1843       Handle(StepVisual_TessellatedAnnotationOccurrence) aTesselation = 
1844         aDCallout->ContentsValue(i).TessellatedAnnotationOccurrence();
1845       if( !aTesselation.IsNull())
1846         anAnnotations.Append(aTesselation);
1847     }
1848   }
1849
1850   if (!anAnnotations.Length())
1851     return;
1852
1853
1854   BRep_Builder aB;
1855   aB.MakeCompound(aResAnnotation);
1856
1857   Standard_Integer i =0;
1858   Bnd_Box aBox;
1859   Standard_Integer nbShapes =0;
1860   for( ; i < anAnnotations.Length(); i++)
1861   {
1862     Handle(StepVisual_StyledItem) anItem = anAnnotations(i);
1863   
1864     aPresentName = anItem->Name();
1865
1866     anACO = Handle(StepVisual_AnnotationCurveOccurrence)::DownCast(anItem);
1867     TopoDS_Shape anAnnotationShape;
1868     if(!anACO.IsNull())
1869     {
1870       Handle(StepRepr_RepresentationItem) aCurveItem = anACO->Item();
1871       anAnnotationShape = STEPConstruct::FindShape (aTP,aCurveItem);
1872       if( anAnnotationShape.IsNull())
1873       {
1874         Handle(Transfer_Binder) binder = theTR->Actor()->Transfer(aCurveItem, aTP);
1875         if ( ! binder.IsNull() && binder->HasResult() ) {
1876           anAnnotationShape = TransferBRep::ShapeResult ( aTP, binder );
1877         }
1878       }
1879     }
1880     //case of tesselated entities
1881     else
1882     {
1883       Handle(StepRepr_RepresentationItem) aTessItem = anItem->Item();
1884       if(aTessItem.IsNull())
1885         continue;
1886       Handle(StepVisual_TessellatedGeometricSet) aTessSet = Handle(StepVisual_TessellatedGeometricSet)::DownCast(aTessItem);
1887       if( aTessSet.IsNull())
1888         continue;
1889       NCollection_Handle<StepVisual_Array1OfTessellaltedItem> aListItems = aTessSet->Items();
1890       Standard_Integer nb = aListItems.IsNull() ? 0 : aListItems->Length();
1891       Handle(StepVisual_TessellatedCurveSet) aTessCurve;
1892       for (Standard_Integer n = 1; n <= nb && aTessCurve.IsNull(); n++)
1893       {
1894         aTessCurve = Handle(StepVisual_TessellatedCurveSet)::DownCast(aListItems->Value(n));
1895       }
1896       if( aTessCurve.IsNull())
1897         continue;
1898       Handle(StepVisual_CoordinatesList) aCoordList = aTessCurve->CoordList();
1899       if( aCoordList.IsNull())
1900         continue;
1901       Handle(TColgp_HArray1OfXYZ)  aPoints = aCoordList->Points();
1902
1903       if (aPoints.IsNull() || aPoints->Length() == 0)
1904         continue;
1905       NCollection_Handle<StepVisual_VectorOfHSequenceOfInteger> aCurves = aTessCurve->Curves();
1906       Standard_Integer aNbC = (aCurves.IsNull() ? 0 : aCurves->Length());
1907       TopoDS_Compound aComp;
1908       aB.MakeCompound(aComp);
1909       
1910       Standard_Integer k = 0;
1911       for( ; k < aNbC; k++)
1912       {
1913         Handle(TColStd_HSequenceOfInteger) anIndexes = aCurves->Value(k);
1914         TopoDS_Wire aCurW;
1915         aB.MakeWire(aCurW);
1916
1917         for(Standard_Integer n = 1; n < anIndexes->Length(); n++)
1918         {
1919           Standard_Integer ind = anIndexes->Value(n);
1920           Standard_Integer indnext = anIndexes->Value(n + 1);
1921           if( ind > aPoints->Length() || indnext > aPoints->Length())
1922             continue;
1923           gp_Pnt aP1(aPoints->Value(ind));
1924           gp_Pnt aP2(aPoints->Value(indnext));
1925           BRepBuilderAPI_MakeEdge aMaker(aP1, aP2);
1926           if( aMaker.IsDone())
1927           {
1928             TopoDS_Edge aCurE = aMaker.Edge();
1929             aB.Add(aCurW, aCurE);
1930           }
1931         }
1932         aB.Add(aComp, aCurW);
1933       }
1934       anAnnotationShape = aComp;
1935     }
1936     if(!anAnnotationShape.IsNull())
1937     {
1938       nbShapes++;
1939       aB.Add(aResAnnotation, anAnnotationShape);
1940       if( i == anAnnotations.Length() - 1)
1941         BRepBndLib::AddClose(anAnnotationShape, aBox);
1942     }
1943   }
1944   
1945   if(!nbShapes)
1946     return;
1947   gp_Pnt aPtext(0., 0., 0.);
1948   if(!aBox.IsVoid())
1949   {
1950     Standard_Real aXmin, aYmin, aZmin,aXmax, aYmax, aZmax; 
1951     aBox.Get(aXmin, aYmin, aZmin,aXmax, aYmax, aZmax);
1952     aPtext = gp_Pnt((aXmin + aXmax) * 0.5, (aYmin + aYmax) * 0.5, (aZmin + aZmax) * 0.5);
1953   }
1954
1955   // set point to XCAF
1956   if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DimensionObject))) {
1957     Handle(XCAFDimTolObjects_DimensionObject) anObj = 
1958       Handle(XCAFDimTolObjects_DimensionObject)::DownCast(theDimObject);
1959     anObj->SetPointTextAttach(aPtext);
1960     anObj->SetPresentation(aResAnnotation, aPresentName);
1961   }
1962   else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_DatumObject))) {
1963     Handle(XCAFDimTolObjects_DatumObject) anObj =
1964       Handle(XCAFDimTolObjects_DatumObject)::DownCast(theDimObject);
1965       anObj->SetPointTextAttach(aPtext);
1966       anObj->SetPresentation(aResAnnotation, aPresentName);
1967   }
1968   else if (theDimObject->IsKind(STANDARD_TYPE(XCAFDimTolObjects_GeomToleranceObject))) {
1969     Handle(XCAFDimTolObjects_GeomToleranceObject) anObj =
1970       Handle(XCAFDimTolObjects_GeomToleranceObject)::DownCast(theDimObject);
1971     anObj->SetPointTextAttach(aPtext);
1972     anObj->SetPresentation(aResAnnotation, aPresentName);
1973   }
1974   return;
1975 }
1976
1977 //=======================================================================
1978 //function : ReadDatums
1979 //purpose  : auxilary
1980 //=======================================================================
1981 static Standard_Boolean ReadDatums(const Handle(XCAFDoc_ShapeTool) &STool,
1982                                    const Handle(XCAFDoc_DimTolTool) &DGTTool,
1983                                    const Interface_Graph &graph,
1984                                    const Handle(Transfer_TransientProcess) &TP,
1985                                    const TDF_Label TolerL,
1986                                    const Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR)
1987 {
1988   if(GTWDR.IsNull()) return Standard_False;
1989   Handle(StepDimTol_HArray1OfDatumReference) HADR = GTWDR->DatumSystem();
1990   if(HADR.IsNull()) return Standard_False;
1991   for(Standard_Integer idr=1; idr<=HADR->Length(); idr++) {
1992     Handle(StepDimTol_DatumReference) DR = HADR->Value(idr);
1993     Handle(StepDimTol_Datum) aDatum = DR->ReferencedDatum();
1994     if(aDatum.IsNull()) continue;
1995     Interface_EntityIterator subs4 = graph.Sharings(aDatum);
1996     for(subs4.Start(); subs4.More(); subs4.Next()) {
1997       Handle(StepRepr_ShapeAspectRelationship) SAR = 
1998         Handle(StepRepr_ShapeAspectRelationship)::DownCast(subs4.Value());
1999       if(SAR.IsNull()) continue;
2000       Handle(StepDimTol_DatumFeature) DF = 
2001         Handle(StepDimTol_DatumFeature)::DownCast(SAR->RelatingShapeAspect());
2002       if(DF.IsNull()) continue;
2003       Interface_EntityIterator subs5 = graph.Sharings(DF);
2004       Handle(StepRepr_PropertyDefinition) PropDef;
2005       for(subs5.Start(); subs5.More() && PropDef.IsNull(); subs5.Next()) {
2006         PropDef = Handle(StepRepr_PropertyDefinition)::DownCast(subs5.Value());
2007       }
2008       if(PropDef.IsNull()) continue;
2009       Handle(StepShape_AdvancedFace) AF;
2010       subs5 = graph.Sharings(PropDef);
2011       for(subs5.Start(); subs5.More(); subs5.Next()) {
2012         Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
2013           Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs5.Value());
2014         if(!SDR.IsNull()) {
2015           Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
2016           if( !Repr.IsNull() && Repr->NbItems()>0 ) {
2017             Handle(StepRepr_RepresentationItem) RI = Repr->ItemsValue(1);
2018             AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
2019           }
2020         }
2021       }
2022       if(AF.IsNull()) return Standard_False;
2023       Standard_Integer index = TP->MapIndex(AF);
2024       TopoDS_Shape aSh;
2025       if(index >0) {
2026         Handle(Transfer_Binder) binder = TP->MapItem(index);
2027         aSh = TransferBRep::ShapeResult(binder);
2028       }
2029       if(aSh.IsNull()) continue; 
2030       TDF_Label shL;
2031       if( !STool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2032       DGTTool->SetDatum(shL,TolerL,PropDef->Name(),PropDef->Description(),aDatum->Identification());
2033     }
2034   }
2035   return Standard_True;
2036 }
2037
2038
2039 //=======================================================================
2040 //function : setDatumToXCAF
2041 //purpose  : 
2042 //=======================================================================
2043 static Standard_Boolean setDatumToXCAF(const Handle(StepDimTol_Datum)& theDat,
2044                                         const TDF_Label theGDTL,
2045                                         const Standard_Integer thePositionCounter,
2046                                         const XCAFDimTolObjects_DatumModifiersSequence& aXCAFModifiers,
2047                                         const XCAFDimTolObjects_DatumModifWithValue aXCAFModifWithVal,
2048                                         const Standard_Real aModifValue,
2049                                         const Handle(TDocStd_Document)& theDoc,
2050                                         const Handle(XSControl_WorkSession)& theWS)
2051 {
2052   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
2053   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
2054   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
2055   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
2056   const Interface_Graph& aGraph = aTP->Graph();
2057   Handle(XCAFDoc_Datum) aDat;
2058   TDF_Label aShL;
2059   Standard_Boolean aRefShapeIsFound = Standard_False;
2060   Standard_Boolean aFirstStep = Standard_True;
2061   Interface_EntityIterator anIterD = aGraph.Sharings(theDat);
2062   for(anIterD.Start(); anIterD.More(); anIterD.Next()) {
2063     Handle(StepRepr_ShapeAspectRelationship) aSAR = 
2064       Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIterD.Value());
2065     if(aSAR.IsNull()) continue;
2066
2067     Handle(StepRepr_ShapeAspect) aSA = aSAR->RelatingShapeAspect();
2068     if (aSA.IsNull()) continue;
2069     Handle(StepAP242_GeometricItemSpecificUsage) aPGISU;
2070     if(aSA->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp)))
2071     {
2072       //processing for complex entity
2073       Interface_EntityIterator anIterC = aGraph.Sharings(aSA);
2074       for(anIterC.Start(); anIterC.More(); anIterC.Next()) {
2075         Handle(StepRepr_ShapeAspectRelationship) SAR = 
2076           Handle(StepRepr_ShapeAspectRelationship)::DownCast(anIterC.Value());
2077         if(SAR.IsNull()) continue;
2078         Handle(StepRepr_ShapeAspect) aS = SAR->RelatedShapeAspect();
2079         if(aS.IsNull()) continue;
2080         Interface_EntityIterator anIterSA = aGraph.Sharings(aS);
2081         for(anIterSA.Start(); anIterSA.More() && aPGISU.IsNull(); anIterSA.Next()) {
2082           aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterSA.Value());
2083         }
2084         if(!aPGISU.IsNull()){
2085           aSA = aS;
2086           break;
2087         }
2088       }
2089     }
2090     else if(aSA->IsKind(STANDARD_TYPE(StepDimTol_PlacedDatumTargetFeature)))
2091     {
2092       //processing for datum target
2093       Interface_EntityIterator anIterDTF = aGraph.Sharings(aSA);
2094       for(anIterDTF.Start(); anIterDTF.More(); anIterDTF.Next()) {
2095         if(anIterDTF.Value()->IsKind(STANDARD_TYPE(StepRepr_FeatureForDatumTargetRelationship)))
2096         {
2097           Handle(StepRepr_FeatureForDatumTargetRelationship) aFFDTR =
2098             Handle(StepRepr_FeatureForDatumTargetRelationship)::DownCast(anIterDTF.Value());
2099           Handle(StepRepr_ShapeAspect) aTmpSA = aFFDTR->RelatedShapeAspect();
2100           Interface_EntityIterator anIterDSWP = aGraph.Sharings(aTmpSA);
2101           for(anIterDSWP.Start(); anIterDSWP.More() && aPGISU.IsNull(); anIterDSWP.Next()) {
2102             aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
2103     }
2104         }
2105       }
2106     }
2107     if (aSA.IsNull()) continue;
2108     Interface_EntityIterator anIterDSWP = aGraph.Sharings(aSA);
2109     for(anIterDSWP.Start(); anIterDSWP.More() && aPGISU.IsNull(); anIterDSWP.Next()) {
2110       aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
2111     }
2112     if(aPGISU.IsNull()) continue;
2113     // get representation item
2114     Handle(StepRepr_RepresentationItem) aRI;
2115     for(Standard_Integer i = 1 ; i <= aPGISU->NbIdentifiedItem() && aRI.IsNull(); i++)
2116     {
2117       aRI = aPGISU->IdentifiedItemValue(i);
2118     }
2119     if(aRI.IsNull()) continue;
2120     Standard_Integer index = aTP->MapIndex(aRI);
2121     TopoDS_Shape aSh;
2122     if(index >0) {
2123       Handle(Transfer_Binder) binder = aTP->MapItem(index);
2124       aSh = TransferBRep::ShapeResult(binder);
2125     }
2126     if(aSh.IsNull()) continue; 
2127     if( !aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True) ) continue;
2128     Handle(TDataStd_TreeNode) aNode;
2129     if(aFirstStep && aShL.FindAttribute(XCAFDoc::DatumRefGUID(),aNode) && aNode->HasFirst() &&
2130        aNode->First()->Label().FindAttribute(XCAFDoc_Datum::GetID(),aDat))
2131     {
2132       //if datums already attached, not need add datum target
2133       aRefShapeIsFound = Standard_True;
2134     }
2135     aFirstStep = Standard_False;
2136     Handle(XCAFDimTolObjects_DatumObject) aDatObj;
2137     if(aSA->IsKind(STANDARD_TYPE(StepDimTol_PlacedDatumTargetFeature)))
2138     {
2139       if(!aRefShapeIsFound)
2140       {
2141         //if datum targers not yet added
2142         TDF_Label aDatL = aDGTTool->AddDatum();
2143         aDat = XCAFDoc_Datum::Set(aDatL);
2144         aDGTTool->SetDatum(aShL, aDatL);
2145         aDatObj = aDat->GetObject();
2146         aDatObj->SetName(theDat->Identification());
2147         aDatObj->SetPosition (thePositionCounter);
2148         if(!aXCAFModifiers.IsEmpty())
2149           aDatObj->SetModifiers(aXCAFModifiers);
2150         if (aXCAFModifWithVal != XCAFDimTolObjects_DatumModifWithValue_None) 
2151           aDatObj->SetModifierWithValue(aXCAFModifWithVal, aModifValue);
2152         aDGTTool->SetDatumToGeomTol(aDatL, theGDTL);
2153         Handle(StepDimTol_PlacedDatumTargetFeature) aPDTF = Handle(StepDimTol_PlacedDatumTargetFeature)::DownCast(aSA);
2154         if (aPDTF->TargetId()->IsIntegerValue())
2155           aDatObj->SetDatumTargetNumber(aPDTF->TargetId()->IntegerValue());
2156         else
2157           aDatObj->SetDatumTargetNumber(0);
2158         aDatObj->IsDatumTarget(Standard_True);
2159         XCAFDimTolObjects_DatumTargetType aType;
2160         if(STEPCAFControl_GDTProperty::GetDatumTargetType(aSA->Description(),aType))
2161         {
2162           aDatObj->SetDatumTargetType(aType);
2163           if(aType == XCAFDimTolObjects_DatumTargetType_Area)
2164           {
2165             Interface_EntityIterator anIterDTF = aGraph.Shareds(aSA);
2166             for(anIterDTF.Start(); anIterDTF.More(); anIterDTF.Next()) {
2167               if(anIterDTF.Value()->IsKind(STANDARD_TYPE(StepAP242_GeometricItemSpecificUsage)))
2168               {
2169                 Handle(StepAP242_GeometricItemSpecificUsage) aGISU
2170                   = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
2171                 Handle(StepRepr_RepresentationItem) anItem;
2172                 if(aPGISU->NbIdentifiedItem() > 0) {
2173                   anItem = aPGISU->IdentifiedItemValue(1);
2174                 }
2175                 if(anItem.IsNull()) continue;
2176                 Standard_Integer anItemIndex = aTP->MapIndex(anItem);
2177                 if(anItemIndex >0) {
2178                   Handle(Transfer_Binder) binder = aTP->MapItem(anItemIndex);
2179                   TopoDS_Shape anItemShape = TransferBRep::ShapeResult(binder);
2180                   aDatObj->SetDatumTarget(anItemShape);
2181                 }
2182               }
2183             }
2184           }
2185           else
2186           {
2187             Interface_EntityIterator anIterDTF = aGraph.Shareds(aSA);
2188             for(anIterDTF.Start(); anIterDTF.More(); anIterDTF.Next()) {
2189               if(anIterDTF.Value()->IsKind(STANDARD_TYPE(StepRepr_PropertyDefinition)))
2190               {
2191                 Interface_EntityIterator anIterPD = aGraph.Shareds(anIterDTF.Value());
2192                 for(anIterPD.Start(); anIterPD.More(); anIterPD.Next()) {
2193                   if(anIterPD.Value()->IsKind(STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation)))
2194                   {
2195                     Interface_EntityIterator anIterSDR = aGraph.Sharings(anIterPD.Value());
2196                     for(anIterSDR.Start(); anIterSDR.More(); anIterSDR.Next()) {
2197                       if(anIterSDR.Value()->IsKind(STANDARD_TYPE(StepShape_ShapeRepresentationWithParameters)))
2198                       {
2199                         Handle(StepShape_ShapeRepresentationWithParameters) aSRWP
2200                           = Handle(StepShape_ShapeRepresentationWithParameters)::DownCast(anIterSDR.Value());
2201                         for(Standard_Integer r = aSRWP->Items()->Lower(); r <= aSRWP->Items()->Upper(); r++)
2202                         {
2203                           if(aSRWP->ItemsValue(r)->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
2204                           {
2205                             Handle(StepGeom_Axis2Placement3d) anAx
2206                               = Handle(StepGeom_Axis2Placement3d)::DownCast(aSRWP->ItemsValue(r));
2207                             Handle(TColStd_HArray1OfReal) aDirArr = anAx->Axis()->DirectionRatios();
2208                             Handle(TColStd_HArray1OfReal) aDirRArr = anAx->RefDirection()->DirectionRatios();
2209                             Handle(TColStd_HArray1OfReal) aLocArr = anAx->Location()->Coordinates();
2210                             gp_Dir aDir;
2211                             gp_Dir aDirR;
2212                             gp_Pnt aPnt;
2213                             if(!aDirArr.IsNull() && aDirArr->Length() > 2 &&
2214                               !aDirRArr.IsNull() && aDirRArr->Length() > 2 && 
2215                               !aLocArr.IsNull() && aLocArr->Length() > 2)
2216                             {
2217                               aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, aDirArr->Lower()+2);
2218                               aDirR.SetCoord(aDirRArr->Lower(), aDirRArr->Lower()+1, aDirRArr->Lower()+2);
2219                               aPnt.SetCoord(aLocArr->Lower(), aLocArr->Lower()+1, aLocArr->Lower()+2);
2220                               gp_Ax2 anA(aPnt, aDir, aDirR);
2221                               aDatObj->SetDatumTargetAxis(anA);
2222                             }
2223                           }
2224                           else if(aSRWP->ItemsValue(r)->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit)))
2225                           {
2226                             Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) aM =
2227                               Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(aSRWP->ItemsValue(r)); 
2228                             Standard_Real aVal = aM->GetMeasureWithUnit()->ValueComponent();
2229                             StepBasic_Unit anUnit = aM->GetMeasureWithUnit()->UnitComponent();
2230                             Standard_Real aFact=1.;
2231                             if(anUnit.IsNull()) continue;
2232                             if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2233                             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2234                             if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2235                             if(aM->Name()->String().IsEqual("target length") ||
2236                               aM->Name()->String().IsEqual("target diameter"))
2237                               aDatObj->SetDatumTargetLength(aVal);
2238                             else
2239                               aDatObj->SetDatumTargetWidth(aVal);
2240                           }
2241                         }
2242                       }
2243                     }
2244                   }
2245                 }
2246               }
2247             }
2248           }
2249         }
2250       }
2251     }
2252     else
2253     {
2254       //processing for darum feature
2255       TDF_Label aDatL = aDGTTool->AddDatum();
2256       aDat = XCAFDoc_Datum::Set(aDatL);
2257       aDGTTool->SetDatum(aShL, aDatL);
2258       aDatObj = aDat->GetObject();
2259       aDatObj->SetName(theDat->Identification());
2260       aDatObj->SetPosition (thePositionCounter);
2261       if(!aXCAFModifiers.IsEmpty())
2262         aDatObj->SetModifiers(aXCAFModifiers);
2263       if (aXCAFModifWithVal != XCAFDimTolObjects_DatumModifWithValue_None) 
2264         aDatObj->SetModifierWithValue(aXCAFModifWithVal, aModifValue);
2265       aDGTTool->SetDatumToGeomTol(aDatL, theGDTL);
2266     }
2267     if(!aDatObj.IsNull()) {
2268       readAnnotation(aTR, aSAR->RelatingShapeAspect(), aDatObj);
2269       aDat->SetObject(aDatObj);
2270     }
2271   }
2272   return !aDat.IsNull();
2273 }
2274
2275
2276 //=======================================================================
2277 //function : ReadDatums
2278 //purpose  : auxilary
2279 //=======================================================================
2280 static Standard_Boolean readDatumsAP242(const Handle(Standard_Transient)& theEnt,
2281                                         const TDF_Label theGDTL,
2282                                         const Handle(TDocStd_Document)& theDoc,
2283                                         const Handle(XSControl_WorkSession)& theWS)
2284 {
2285   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
2286   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
2287   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
2288   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
2289   const Interface_Graph& aGraph = aTP->Graph();
2290
2291   Interface_EntityIterator anIter = aGraph.Shareds(theEnt);
2292   for(anIter.Start(); anIter.More(); anIter.Next()) {
2293     Handle(Standard_Transient) anAtr = anIter.Value();
2294     if(anAtr->IsKind(STANDARD_TYPE(StepDimTol_DatumSystem)))
2295     {
2296       Standard_Integer aPositionCounter = 0;//position on frame 
2297       Handle(StepDimTol_DatumSystem) aDS = Handle(StepDimTol_DatumSystem)::DownCast(anAtr);
2298       Interface_EntityIterator anIterDS = aGraph.Sharings(aDS);
2299       for(anIterDS.Start(); anIterDS.More(); anIterDS.Next()) {
2300         Handle(Standard_Transient) anAtrDS = anIterDS.Value();
2301         if(anAtrDS->IsKind(STANDARD_TYPE(StepAP242_GeometricItemSpecificUsage)))
2302         {
2303           //get axis
2304           Handle(StepAP242_GeometricItemSpecificUsage)aAxGISUI
2305             = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anAtrDS);
2306           if (aAxGISUI->IdentifiedItemValue(1)->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
2307           {
2308             Handle(StepGeom_Axis2Placement3d) anAx
2309               = Handle(StepGeom_Axis2Placement3d)::DownCast(aAxGISUI->IdentifiedItemValue(1));
2310             Handle(XCAFDoc_GeomTolerance) aTol;
2311             if(theGDTL.FindAttribute(XCAFDoc_GeomTolerance::GetID(), aTol))
2312             {
2313               Handle(XCAFDimTolObjects_GeomToleranceObject) anObj = aTol->GetObject();
2314               Handle(TColStd_HArray1OfReal) aDirArr = anAx->Axis()->DirectionRatios();
2315               Handle(TColStd_HArray1OfReal) aDirRArr = anAx->RefDirection()->DirectionRatios();
2316               Handle(TColStd_HArray1OfReal) aLocArr = anAx->Location()->Coordinates();
2317               gp_Dir aDir;
2318               gp_Dir aDirR;
2319               gp_Pnt aPnt;
2320               if(!aDirArr.IsNull() && aDirArr->Length() > 2 &&
2321                 !aDirRArr.IsNull() && aDirRArr->Length() > 2 && 
2322                 !aLocArr.IsNull() && aLocArr->Length() > 2)
2323               {
2324                 aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, aDirArr->Lower()+2);
2325                 aDirR.SetCoord(aDirRArr->Lower(), aDirRArr->Lower()+1, aDirRArr->Lower()+2);
2326                 aPnt.SetCoord(aLocArr->Lower(), aLocArr->Lower()+1, aLocArr->Lower()+2);
2327                 gp_Ax2 anA(aPnt, aDir, aDirR);
2328                 anObj->SetAxis(anA);
2329                 aTol->SetObject(anObj);
2330               }
2331             }
2332           }
2333         }
2334       }
2335       if (aDS->NbConstituents() > 0)
2336       {
2337         //get datum feature and datum target from datum system
2338         Handle(StepDimTol_HArray1OfDatumReferenceCompartment) aDRCA = aDS->Constituents();
2339         if(!aDRCA.IsNull())
2340         {
2341           for(Standard_Integer i = aDRCA->Lower(); i <= aDRCA->Upper(); i++)
2342           {
2343             Handle(StepDimTol_DatumReferenceCompartment) aDRC = aDRCA->Value(i);
2344             //gete modifiers
2345             Handle(StepDimTol_HArray1OfDatumReferenceModifier) aModif = aDRC->Modifiers();
2346             XCAFDimTolObjects_DatumModifiersSequence aXCAFModifiers;
2347             XCAFDimTolObjects_DatumModifWithValue aXCAFModifWithVal = XCAFDimTolObjects_DatumModifWithValue_None;
2348             Standard_Real aModifValue = 0;
2349             if(!aModif.IsNull())
2350             {
2351               for(Standard_Integer m = aModif->Lower(); m <= aModif->Upper(); m++)
2352               {
2353                 if(aModif->Value(m).CaseNumber() == 2)
2354                   aXCAFModifiers.Append(
2355                   (XCAFDimTolObjects_DatumSingleModif)aModif->Value(m).
2356                   SimpleDatumReferenceModifierMember()->Value());
2357                 else if (aModif->Value(m).CaseNumber() == 1)
2358                 {
2359                   aXCAFModifWithVal = (XCAFDimTolObjects_DatumModifWithValue)(aModif->Value(m).DatumReferenceModifierWithValue()->ModifierType() + 1);
2360                   Standard_Real aVal = aModif->Value(m).DatumReferenceModifierWithValue()->ModifierValue()->ValueComponent();
2361                   StepBasic_Unit anUnit = aModif->Value(m).DatumReferenceModifierWithValue()->ModifierValue()->UnitComponent();
2362                   Standard_Real aFact=1.;
2363                   if(anUnit.IsNull()) continue;
2364                   if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2365                   Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2366                   if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2367                   aModifValue = aVal;
2368                 }
2369               }
2370             }
2371             aPositionCounter++;
2372             Interface_EntityIterator anIterDRC = aGraph.Shareds(aDRC);
2373             for(anIterDRC.Start(); anIterDRC.More(); anIterDRC.Next()) {
2374               
2375               if(anIterDRC.Value()->IsKind(STANDARD_TYPE(StepDimTol_Datum)))
2376               {
2377                 Handle(StepDimTol_Datum) aD = Handle(StepDimTol_Datum)::DownCast(anIterDRC.Value());
2378                 setDatumToXCAF(aD, theGDTL, aPositionCounter, aXCAFModifiers, aXCAFModifWithVal, aModifValue,theDoc, theWS);
2379               }
2380               else if(anIterDRC.Value()->IsKind(STANDARD_TYPE(StepDimTol_DatumReferenceElement)))
2381               {
2382                 Handle(StepDimTol_DatumReferenceElement) aDRE 
2383                   = Handle(StepDimTol_DatumReferenceElement)::DownCast(anIterDRC.Value());
2384                 //get modifiers from group of datums
2385                 Handle(StepDimTol_HArray1OfDatumReferenceModifier) aModifE = aDRE->Modifiers();
2386                 if(!aModifE.IsNull())
2387                 {
2388                   for(Standard_Integer k = aModifE->Lower(); k <= aModifE->Upper(); k++)
2389                   {
2390                     if(aModifE->Value(k).CaseNumber() == 1)
2391                       aXCAFModifiers.Append(
2392                       (XCAFDimTolObjects_DatumSingleModif)aModifE->Value(k).
2393                       SimpleDatumReferenceModifierMember()->Value());
2394                     else if (aModifE->Value(k).CaseNumber() == 2)
2395                     {
2396                       aXCAFModifWithVal = (XCAFDimTolObjects_DatumModifWithValue)(aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierType() + 1);
2397                       Standard_Real aVal = aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierValue()->ValueComponent();
2398                       StepBasic_Unit anUnit = aModifE->Value(k).DatumReferenceModifierWithValue()->ModifierValue()->UnitComponent();
2399                       Standard_Real aFact=1.;
2400                       if(anUnit.IsNull()) continue;
2401                       if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2402                       Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2403                       if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2404                       aModifValue = aVal;
2405                     }
2406                   }
2407                 }
2408                 Interface_EntityIterator anIterDRE = aGraph.Shareds(aDRE);
2409                 for(anIterDRE.Start(); anIterDRE.More(); anIterDRE.Next()) {
2410                   if(anIterDRE.Value()->IsKind(STANDARD_TYPE(StepDimTol_Datum)))
2411                   {
2412                     Handle(StepDimTol_Datum) aD = Handle(StepDimTol_Datum)::DownCast(anIterDRE.Value());
2413                     setDatumToXCAF(aD, theGDTL, aPositionCounter, aXCAFModifiers, aXCAFModifWithVal, aModifValue,theDoc, theWS);
2414                   }
2415                 }
2416               }
2417             }
2418           }
2419         }
2420       }
2421     }
2422   }
2423   return Standard_True;
2424 }
2425
2426 //=======================================================================
2427 //function : craeteGeomTolObjectInXCAF
2428 //purpose  : 
2429 //=======================================================================
2430 static TDF_Label createGDTObjectInXCAF(const Handle(Standard_Transient)& theEnt,
2431                                                const Handle(TDocStd_Document)& theDoc,
2432                                                const Handle(XSControl_WorkSession)& theWS)
2433 {
2434   TDF_Label aGDTL;
2435   if(!theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) &&
2436      !theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) && 
2437      !theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
2438   {
2439     return aGDTL;
2440   }
2441
2442   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
2443   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
2444   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
2445   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
2446   const Interface_Graph& aGraph = aTP->Graph();
2447   Standard_Boolean isAllAround = Standard_False;
2448   Standard_Boolean isAllOver = Standard_False;
2449   
2450   // find RepresentationItem for current Ent
2451   NCollection_Sequence<Handle(Standard_Transient)> aSeqRI1, aSeqRI2;
2452
2453   Interface_EntityIterator anIter = aGraph.Shareds(theEnt);
2454   for(anIter.Start(); anIter.More(); anIter.Next()) {
2455     Handle(Standard_Transient) anAtr = anIter.Value();
2456     NCollection_Sequence<Handle(StepRepr_ShapeAspect)> aSAs;
2457     if(anAtr->IsKind(STANDARD_TYPE(StepRepr_ProductDefinitionShape)))
2458     {
2459       //if associating tolerances with part (All-Over)
2460       Interface_EntityIterator anIterSDR = aGraph.Sharings(anAtr);
2461       for(anIterSDR.Start(); anIterSDR.More(); anIterSDR.Next()) 
2462       {
2463         Handle(Standard_Transient) anAtrSDR = anIterSDR.Value();
2464         if(anAtrSDR->IsKind(STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation)))
2465         {
2466           isAllOver = Standard_True;
2467           Interface_EntityIterator anIterABSR = aGraph.Shareds(anAtrSDR);
2468           for(anIterABSR.Start(); anIterABSR.More(); anIterABSR.Next()) 
2469           {
2470             Handle(Standard_Transient) anAtrABSR = anIterABSR.Value();
2471             if(anAtrABSR->IsKind(STANDARD_TYPE(StepShape_AdvancedBrepShapeRepresentation)))
2472             {
2473               aSeqRI1.Append(anAtrABSR);
2474             }
2475           }
2476         }
2477       }
2478     }
2479     else if(anAtr->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)) || 
2480       anAtr->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)))
2481     {
2482       //if tolerance attached to dimension
2483       Interface_EntityIterator anIterDim = aGraph.Shareds(anAtr);
2484       for(anIterDim.Start(); anIterDim.More(); anIterDim.Next()) 
2485       {
2486         Handle(Standard_Transient) anAtrDim = anIterDim.Value();
2487         if(anAtrDim->IsKind(STANDARD_TYPE(StepRepr_CompositeShapeAspect)) || 
2488           anAtrDim->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp)))
2489         {
2490           Interface_EntityIterator anIterCSA = aGraph.Sharings(anAtrDim);
2491           for(anIterCSA.Start(); anIterCSA.More(); anIterCSA.Next()) {
2492             if (anIterCSA.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspectRelationship))){
2493               Interface_EntityIterator anIterSAR = aGraph.Shareds(anIterCSA.Value());
2494               for(anIterSAR.Start(); anIterSAR.More(); anIterSAR.Next()) {
2495                 if (anIterSAR.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect))){
2496                   aSAs.Append(Handle(StepRepr_ShapeAspect)::DownCast(anIterSAR.Value()));
2497                 }
2498               }
2499             }
2500           }
2501         }
2502         else if(anAtrDim->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)))
2503         {
2504           aSAs.Append( Handle(StepRepr_ShapeAspect)::DownCast(anAtrDim));
2505         }
2506       }
2507     }
2508     else if(anAtr->IsKind(STANDARD_TYPE(StepRepr_CompositeShapeAspect)) || 
2509       anAtr->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp)))
2510     {
2511       //processing for composite entity
2512       Handle(Standard_Transient) anAtrTmp = anAtr;
2513       if(anAtr->IsKind(STANDARD_TYPE(StepRepr_AllAroundShapeAspect)))
2514       {
2515         // if applyed AllAround Modifier
2516         isAllAround = Standard_True;
2517         Interface_EntityIterator anIterAASA = aGraph.Sharings(anAtrTmp);
2518         for(anIterAASA.Start(); anIterAASA.More(); anIterAASA.Next()) {
2519           if (anIterAASA.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspectRelationship))){
2520             Interface_EntityIterator anIterSAR = aGraph.Shareds(anIterAASA.Value());
2521             for(anIterSAR.Start(); anIterSAR.More(); anIterSAR.Next()) {
2522               if ((anIterSAR.Value()->IsKind(STANDARD_TYPE(StepRepr_CompositeShapeAspect)) || 
2523                 anIterSAR.Value()->IsKind(STANDARD_TYPE(StepRepr_CompShAspAndDatumFeatAndShAsp))) &&
2524                 anAtrTmp != anIterSAR.Value()){
2525                   anAtrTmp = anIterSAR.Value();
2526                   break;
2527               }
2528             }
2529           }
2530         }
2531       }
2532       Interface_EntityIterator anIterCSA = aGraph.Sharings(anAtrTmp);
2533       for(anIterCSA.Start(); anIterCSA.More(); anIterCSA.Next()) {
2534         if (anIterCSA.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspectRelationship))){
2535           Interface_EntityIterator anIterSAR = aGraph.Shareds(anIterCSA.Value());
2536           for(anIterSAR.Start(); anIterSAR.More(); anIterSAR.Next()) {
2537             if (anIterSAR.Value()->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect))){
2538               aSAs.Append(Handle(StepRepr_ShapeAspect)::DownCast(anIterSAR.Value()));
2539             }
2540           }
2541         }
2542       }
2543     }
2544     else if(anAtr->IsKind(STANDARD_TYPE(StepRepr_ShapeAspect)))
2545     {
2546       //default
2547       aSAs.Append( Handle(StepRepr_ShapeAspect)::DownCast(anAtr));
2548     }
2549     if(!aSAs.IsEmpty())
2550     {
2551       //get representation items
2552       NCollection_Sequence<Handle(Standard_Transient)> aSeqRI;
2553       for(Standard_Integer i = aSAs.Lower(); i <= aSAs.Upper(); i++)
2554       {
2555         Interface_EntityIterator anIterSA = aGraph.Sharings(aSAs.Value(i));
2556         Handle(StepAP242_GeometricItemSpecificUsage) aGISU;
2557         Handle(StepRepr_PropertyDefinition) PropD;
2558         for(anIterSA.Start(); anIterSA.More() && aGISU.IsNull() && PropD.IsNull(); anIterSA.Next()) {
2559           aGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterSA.Value());
2560           PropD = Handle(StepRepr_PropertyDefinition)::DownCast(anIterSA.Value());
2561         }
2562         if(!PropD.IsNull())//for old version
2563         {
2564           Handle(StepRepr_RepresentationItem) RI;
2565           Interface_EntityIterator subs4 = aGraph.Sharings(PropD);
2566           for(subs4.Start(); subs4.More(); subs4.Next()) {
2567             Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
2568               Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs4.Value());
2569             if(!SDR.IsNull()) {
2570               Handle(StepRepr_Representation) Repr = SDR->UsedRepresentation();
2571               if( !Repr.IsNull() && Repr->NbItems()>0 ) {
2572                 RI = Repr->ItemsValue(1);
2573               }
2574             }
2575           }
2576           if(RI.IsNull()) continue;
2577
2578           if(theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize))) {
2579             // read dimensions
2580             Handle(StepShape_EdgeCurve) EC = Handle(StepShape_EdgeCurve)::DownCast(RI);
2581             if(EC.IsNull()) continue;
2582             Handle(TCollection_HAsciiString) aName;
2583             Handle(StepShape_DimensionalSize) DimSize = 
2584               Handle(StepShape_DimensionalSize)::DownCast(theEnt);
2585             Standard_Real dim1=-1.,dim2=-1.;
2586             subs4 = aGraph.Sharings(DimSize);
2587             for(subs4.Start(); subs4.More(); subs4.Next()) {
2588               Handle(StepShape_DimensionalCharacteristicRepresentation) DimCharR = 
2589                 Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(subs4.Value());
2590               if(!DimCharR.IsNull()) {
2591                 Handle(StepShape_ShapeDimensionRepresentation) SDimR = DimCharR->Representation();
2592                 if(!SDimR.IsNull() && SDimR->NbItems()>0) {
2593                   Handle(StepRepr_RepresentationItem) anItem = SDimR->ItemsValue(1);
2594                   Handle(StepRepr_ValueRange) VR = Handle(StepRepr_ValueRange)::DownCast(anItem);
2595                   if(!VR.IsNull()) {
2596                     aName = VR->Name();
2597                     //StepRepr_CompoundItemDefinition CID = VR->ItemElement();
2598                     //if(CID.IsNull()) continue;
2599                     //Handle(StepRepr_CompoundItemDefinitionMember) CIDM = 
2600                     //  Handle(StepRepr_CompoundItemDefinitionMember)::DownCast(CID.Value());
2601                     //if(CIDM.IsNull()) continue;
2602                     //if(CIDM->ArrTransient().IsNull()) continue;
2603                     //Handle(StepRepr_HArray1OfRepresentationItem) HARI;
2604                     //if(CID.CaseMem(CIDM)==1)
2605                     //  HARI = CID.ListRepresentationItem();
2606                     //if(CID.CaseMem(CIDM)==2)
2607                     //  HARI = CID.SetRepresentationItem();
2608                     Handle(StepRepr_HArray1OfRepresentationItem) HARI = VR->ItemElement();
2609                     if(HARI.IsNull()) continue;
2610                     if(HARI->Length()>0) {
2611                       Handle(StepRepr_RepresentationItem) RI1 = HARI->Value(1);
2612                       if(RI1.IsNull()) continue;
2613                       if(RI1->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2614                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
2615                           Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI1);
2616                         dim1 = RILMWU->GetMeasureWithUnit()->ValueComponent();
2617                         StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
2618                         Standard_Real afact=1.;
2619                         if(anUnit.IsNull()) continue;
2620                         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2621                         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2622                         if(GetLengthConversionFactor(NU,afact)) dim1=dim1*afact;
2623                       }
2624                     }
2625                     if(HARI->Length()>1) {
2626                       Handle(StepRepr_RepresentationItem) RI2 = HARI->Value(2);
2627                       if(RI2.IsNull()) continue;
2628                       if(RI2->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2629                         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMWU =
2630                           Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(RI2);
2631                         dim2 = RILMWU->GetMeasureWithUnit()->ValueComponent();
2632                         StepBasic_Unit anUnit = RILMWU->GetMeasureWithUnit()->UnitComponent();
2633                         Standard_Real afact=1.;
2634                         if(anUnit.IsNull()) continue;
2635                         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2636                         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2637                         if(GetLengthConversionFactor(NU,afact)) dim2 = dim2*afact;
2638                       }
2639                     }
2640                   }
2641                 }
2642               }
2643             }
2644             if(dim1<0) continue;
2645             if(dim2<0) dim2=dim1;
2646             //cout<<"DimensionalSize: dim1="<<dim1<<"  dim2="<<dim2<<endl;
2647             // now we know edge_curve and value range therefore
2648             // we can create corresponding D&GT labels
2649             Standard_Integer index = aTP->MapIndex(EC);
2650             TopoDS_Shape aSh;
2651             if(index >0) {
2652               Handle(Transfer_Binder) binder = aTP->MapItem(index);
2653               aSh = TransferBRep::ShapeResult(binder);
2654             }
2655             if(aSh.IsNull()) continue; 
2656             TDF_Label shL;
2657             if( !aSTool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2658             Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1,2);
2659             arr->SetValue(1,dim1);
2660             arr->SetValue(2,dim2);
2661             aDGTTool->SetDimTol(shL,1,arr,aName,DimSize->Name());
2662           }
2663           // read tolerances and datums
2664           else if(theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance))) {
2665             Handle(StepDimTol_GeometricTolerance) GT =
2666               Handle(StepDimTol_GeometricTolerance)::DownCast(theEnt);
2667             // read common data for tolerance
2668             //Standard_Real dim = GT->Magnitude()->ValueComponent();
2669             Handle (StepBasic_MeasureWithUnit) dim3 = GT->Magnitude();
2670             if(dim3.IsNull()) continue;
2671             Standard_Real dim = dim3->ValueComponent();
2672             StepBasic_Unit anUnit = GT->Magnitude()->UnitComponent();
2673             Standard_Real afact=1.;
2674             if(anUnit.IsNull()) continue;
2675             if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2676             Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2677             if(GetLengthConversionFactor(NU,afact)) dim = dim*afact;
2678             //cout<<"GeometricTolerance: Magnitude = "<<dim<<endl;
2679             Handle(TColStd_HArray1OfReal) arr = new TColStd_HArray1OfReal(1,1);
2680             arr->SetValue(1,dim);
2681             Handle(TCollection_HAsciiString) aName = GT->Name();
2682             Handle(TCollection_HAsciiString) aDescription = GT->Description();
2683             Handle(StepShape_AdvancedFace) AF = Handle(StepShape_AdvancedFace)::DownCast(RI);
2684             if(AF.IsNull()) continue;
2685             Standard_Integer index = aTP->MapIndex(AF);
2686             TopoDS_Shape aSh;
2687             if(index >0) {
2688               Handle(Transfer_Binder) binder = aTP->MapItem(index);
2689               aSh = TransferBRep::ShapeResult(binder);
2690             }
2691             if(aSh.IsNull()) continue; 
2692             TDF_Label shL;
2693             if( !aSTool->Search(aSh, shL, Standard_True, Standard_True, Standard_True) ) continue;
2694             // read specific data for tolerance
2695             if(GT->IsKind(STANDARD_TYPE(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol))) {
2696               Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol) GTComplex =
2697                 Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol)::DownCast(theEnt);
2698               Standard_Integer kind=20;
2699               Handle(StepDimTol_ModifiedGeometricTolerance) MGT = 
2700                 GTComplex->GetModifiedGeometricTolerance();
2701               if(!MGT.IsNull()) {
2702                 kind = kind + MGT->Modifier()+1;
2703               }
2704               TDF_Label TolerL = aDGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
2705               // translate datums connected with this tolerance
2706               Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
2707                 GTComplex->GetGeometricToleranceWithDatumReference();
2708               if(!GTWDR.IsNull()) {
2709                 ReadDatums(aSTool,aDGTTool,aGraph,aTP,TolerL,GTWDR);
2710               }
2711             }
2712             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_GeometricToleranceWithDatumReference))) {
2713               Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
2714                 Handle(StepDimTol_GeometricToleranceWithDatumReference)::DownCast(theEnt);
2715               if(GTWDR.IsNull()) continue;
2716               Standard_Integer kind = 0;
2717               if     (GTWDR->IsKind(STANDARD_TYPE(StepDimTol_AngularityTolerance)))       kind = 24;
2718               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CircularRunoutTolerance)))   kind = 25;
2719               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_CoaxialityTolerance)))       kind = 26;
2720               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ConcentricityTolerance)))    kind = 27;
2721               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_ParallelismTolerance)))      kind = 28;
2722               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_PerpendicularityTolerance))) kind = 29;
2723               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_SymmetryTolerance)))         kind = 30;
2724               else if(GTWDR->IsKind(STANDARD_TYPE(StepDimTol_TotalRunoutTolerance)))      kind = 31;
2725               //cout<<"GTWDR: kind="<<kind<<endl;
2726               TDF_Label TolerL = aDGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
2727               ReadDatums(aSTool,aDGTTool,aGraph,aTP,TolerL,GTWDR);
2728             }
2729             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_ModifiedGeometricTolerance))) {
2730               Handle(StepDimTol_ModifiedGeometricTolerance) MGT =
2731                 Handle(StepDimTol_ModifiedGeometricTolerance)::DownCast(theEnt);
2732               Standard_Integer kind = 35 + MGT->Modifier();
2733               aDGTTool->SetDimTol(shL,kind,arr,aName,aDescription);
2734             }
2735             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_CylindricityTolerance))) {
2736               aDGTTool->SetDimTol(shL,38,arr,aName,aDescription);
2737             }
2738             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_FlatnessTolerance))) {
2739               aDGTTool->SetDimTol(shL,39,arr,aName,aDescription);
2740             }
2741             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_LineProfileTolerance))) {
2742               aDGTTool->SetDimTol(shL,40,arr,aName,aDescription);
2743             }
2744             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_PositionTolerance))) {
2745               aDGTTool->SetDimTol(shL,41,arr,aName,aDescription);
2746             }
2747             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_RoundnessTolerance))) {
2748               aDGTTool->SetDimTol(shL,42,arr,aName,aDescription);
2749             }
2750             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_StraightnessTolerance))) {
2751               aDGTTool->SetDimTol(shL,43,arr,aName,aDescription);
2752             }
2753             else if(GT->IsKind(STANDARD_TYPE(StepDimTol_SurfaceProfileTolerance))) {
2754               aDGTTool->SetDimTol(shL,44,arr,aName,aDescription);
2755             }
2756           }
2757         }
2758         else
2759         {
2760           if(aGISU.IsNull()) continue;
2761           if(aGISU->NbIdentifiedItem() > 0) {
2762             aSeqRI.Append(aGISU->IdentifiedItemValue(1));
2763           }
2764         }
2765       }
2766       if(!aSeqRI.IsEmpty())
2767       {
2768         if(aSeqRI1.IsEmpty())
2769           aSeqRI1 = aSeqRI;
2770         else 
2771           aSeqRI2 = aSeqRI;
2772       }
2773     }
2774   }
2775   if(aSeqRI1.IsEmpty()) return aGDTL;
2776
2777   TDF_LabelSequence aShLS1, aShLS2;
2778
2779   for(Standard_Integer i = aSeqRI1.Lower(); i <= aSeqRI1.Upper() ;i++)
2780   {
2781     Standard_Integer anIndex = aTP->MapIndex(aSeqRI1.Value(i));
2782     TopoDS_Shape aSh;
2783     if(anIndex >0) {
2784       Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
2785       aSh = TransferBRep::ShapeResult(aBinder);
2786     }
2787     if(!aSh.IsNull())
2788     {
2789       TDF_Label aShL;
2790       aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True);
2791       aShLS1.Append(aShL);
2792     }
2793   }
2794   if (!aSeqRI2.IsEmpty())
2795   {
2796     //for dimensional location
2797     for(Standard_Integer i = aSeqRI2.Lower(); i <= aSeqRI2.Upper() ;i++)
2798     {
2799       Standard_Integer anIndex = aTP->MapIndex(aSeqRI2.Value(i));
2800       TopoDS_Shape aSh;
2801       if(anIndex >0) {
2802         Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
2803         aSh = TransferBRep::ShapeResult(aBinder);
2804       }
2805       if(!aSh.IsNull())
2806       {
2807         TDF_Label aShL;
2808         aSTool->Search(aSh, aShL, Standard_True, Standard_True, Standard_True);
2809         aShLS2.Append(aShL);
2810       }
2811     }
2812   }
2813
2814   if(!aShLS1.IsEmpty())
2815   {
2816     // add to XCAF
2817     if(!theEnt->IsKind(STANDARD_TYPE(StepDimTol_GeometricTolerance)))
2818     {
2819       aGDTL = aDGTTool->AddDimension();
2820       Handle(XCAFDoc_Dimension) aDim = XCAFDoc_Dimension::Set(aGDTL);
2821       TCollection_AsciiString aStr("DGT:Dimensional_");
2822       if(theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)))
2823       {
2824         aStr.AssignCat("Size");
2825       }
2826       else if(theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation)))
2827       {
2828         aStr.AssignCat("Location");
2829       }
2830       TDataStd_Name::Set(aGDTL, aStr);
2831
2832       if(!aShLS2.IsEmpty())
2833       {
2834         aDGTTool->SetDimension(aShLS1, aShLS2, aGDTL);
2835       }
2836       else
2837       {
2838         TDF_LabelSequence aEmptySeq;
2839         aDGTTool->SetDimension(aShLS1, aEmptySeq, aGDTL);
2840       }
2841     }
2842     else
2843     {
2844       aGDTL = aDGTTool->AddGeomTolerance();
2845       Handle(XCAFDoc_GeomTolerance) aGTol = XCAFDoc_GeomTolerance::Set(aGDTL);
2846       TCollection_AsciiString aStr("DGT:GeomTolerance");
2847       TDataStd_Name::Set(aGDTL, aStr);
2848       aDGTTool->SetGeomTolerance(aShLS1, aGDTL);
2849       Handle(XCAFDimTolObjects_GeomToleranceObject) anObj = aGTol->GetObject();
2850       if(isAllAround)
2851         anObj->AddModifier(XCAFDimTolObjects_GeomToleranceModif_All_Around);
2852       else if(isAllOver)
2853         anObj->AddModifier(XCAFDimTolObjects_GeomToleranceModif_All_Over);
2854       aGTol->SetObject(anObj);
2855     }
2856     readDatumsAP242(theEnt, aGDTL, theDoc, theWS);
2857   }
2858   return aGDTL;
2859 }
2860
2861 //=======================================================================
2862 //function : setDimObjectToXCAF
2863 //purpose  : 
2864 //=======================================================================
2865 static void setDimObjectToXCAF(const Handle(Standard_Transient)& theEnt,
2866                                            const TDF_Label& aDimL,
2867                                            const Handle(TDocStd_Document)& theDoc,
2868                                            const Handle(XSControl_WorkSession)& theWS)
2869 {
2870   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( theDoc->Main() );
2871   Handle(XCAFDoc_DimTolTool) aDGTTool = XCAFDoc_DocumentTool::DimTolTool( theDoc->Main() );
2872   Handle(XSControl_TransferReader) aTR = theWS->TransferReader();
2873   Handle(Transfer_TransientProcess) aTP = aTR->TransientProcess();
2874   const Interface_Graph& aGraph = aTP->Graph();
2875   Handle(XCAFDimTolObjects_DimensionObject) aDimObj;
2876   if(!theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalSize)) &&
2877     !theEnt->IsKind(STANDARD_TYPE(StepShape_DimensionalLocation))) 
2878     return;
2879
2880   Handle(StepShape_DimensionalSize) aDimSize = 
2881     Handle(StepShape_DimensionalSize)::DownCast(theEnt);
2882   Handle(StepShape_DimensionalLocation) aDimLocation = 
2883     Handle(StepShape_DimensionalLocation)::DownCast(theEnt);
2884
2885   Standard_Real aDim1=-1.,aDim2=-1.,aDim3=-1.;
2886   Handle(StepShape_TypeQualifier) aTQ;
2887   Handle(StepShape_ValueFormatTypeQualifier) aVFTQ;
2888   Handle(StepShape_ToleranceValue) aTV;
2889   Handle(StepShape_LimitsAndFits) aLAF;
2890   Handle(StepRepr_CompoundRepresentationItem) aCRI;
2891   Handle(StepGeom_Axis2Placement3d) anAP;
2892
2893   Interface_EntityIterator anIterDim;
2894   if(!aDimSize.IsNull())
2895   {
2896     anIterDim = aGraph.Sharings(aDimSize);
2897   }
2898   else
2899   {
2900     anIterDim = aGraph.Sharings(aDimLocation);
2901   }
2902   for(anIterDim.Start(); anIterDim.More(); anIterDim.Next()) {
2903     Handle(StepShape_DimensionalCharacteristicRepresentation) aDCR = 
2904       Handle(StepShape_DimensionalCharacteristicRepresentation)::DownCast(anIterDim.Value());
2905     Handle(StepShape_PlusMinusTolerance) aPMT = 
2906       Handle(StepShape_PlusMinusTolerance)::DownCast(anIterDim.Value());
2907     if(!aDCR.IsNull()) {
2908       Handle(StepShape_ShapeDimensionRepresentation) aSDR = aDCR->Representation();
2909       if(!aSDR.IsNull()) {
2910         Handle(StepRepr_HArray1OfRepresentationItem) aHARI = aSDR->Items();
2911
2912         if(!aHARI.IsNull())
2913         {
2914           for(Standard_Integer nr = aHARI->Lower(); nr <= aHARI->Upper(); nr++)
2915           {
2916             Handle(StepRepr_RepresentationItem) aDRI = aHARI->Value(nr);
2917             if(aDRI.IsNull()) continue;
2918
2919             if(aDRI->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndLengthMeasureWithUnit))) {
2920               //get values
2921               Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) aRILMWU =
2922                 Handle(StepRepr_ReprItemAndLengthMeasureWithUnit)::DownCast(aDRI);
2923               Standard_Real aVal = aRILMWU->GetMeasureWithUnit()->ValueComponent();
2924               StepBasic_Unit anUnit = aRILMWU->GetMeasureWithUnit()->UnitComponent();
2925               Standard_Real aFact=1.;
2926               if(anUnit.IsNull()) continue;
2927               if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2928               Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2929               if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
2930               if(aDim2 > 0)
2931               {
2932                 if(aDim1 > aDim2)
2933                 {
2934                   Standard_Real aTmp = aDim1;
2935                   aDim1 = aDim2;
2936                   aDim2 = aTmp;
2937                 }
2938                 if(aVal < aDim1)
2939                   aDim1 = aVal;
2940                 else if(aVal > aDim2)
2941                   aDim2 = aVal;
2942               }
2943               else if(aDim1 > 0)
2944               {
2945                 if (aVal > aDim1)
2946                   aDim2 = aVal;
2947                 else
2948                 {
2949                   aDim2 = aDim1;
2950                   aDim1 = aVal;
2951                 }
2952               }
2953               else
2954                 aDim1 = aVal;
2955             }
2956             else if(aDRI->IsKind(STANDARD_TYPE(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit))) {
2957               //get values
2958               Handle(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit) aRIPAMWU =
2959                 Handle(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit)::DownCast(aDRI);
2960               Standard_Real aVal = aRIPAMWU->GetMeasureWithUnit()->ValueComponent();
2961               StepBasic_Unit anUnit = aRIPAMWU->GetMeasureWithUnit()->UnitComponent();
2962               Standard_Real aFact=1.;
2963               if(anUnit.IsNull()) continue;
2964               if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
2965               Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
2966               if(GetAngleConversionFactor(NU,aFact)) aVal=aVal*aFact;
2967               if(aDim2 > 0)
2968               {
2969                 if(aDim1 > aDim2)
2970                 {
2971                   Standard_Real aTmp = aDim1;
2972                   aDim1 = aDim2;
2973                   aDim2 = aTmp;
2974                 }
2975                 if(aVal < aDim1)
2976                   aDim1 = aVal;
2977                 else if(aVal > aDim2)
2978                   aDim2 = aVal;
2979               }
2980               else if(aDim1 > 0)
2981               {
2982                 if (aVal > aDim1)
2983                   aDim2 = aVal;
2984                 else
2985                 {
2986                   aDim2 = aDim1;
2987                   aDim1 = aVal;
2988                 }
2989               }
2990               else
2991                 aDim1 = aVal;
2992             }
2993             else if(aDRI->IsKind(STANDARD_TYPE(StepShape_QualifiedRepresentationItem))) {
2994               //get qualifier
2995               Handle(StepShape_QualifiedRepresentationItem) aQRI =
2996                 Handle(StepShape_QualifiedRepresentationItem)::DownCast(aDRI);
2997               for(Standard_Integer l = 1; l <= aQRI->NbQualifiers(); l++)
2998               {
2999                 aTQ = aQRI->Qualifiers()->Value(l).TypeQualifier();
3000                 aVFTQ = aQRI->Qualifiers()->Value(l).ValueFormatTypeQualifier();
3001               }
3002             }
3003             else if(aDRI->IsKind(STANDARD_TYPE(StepRepr_CompoundRepresentationItem))) {
3004               aCRI = Handle(StepRepr_CompoundRepresentationItem)::DownCast(aDRI);
3005             }
3006             else if(aDRI->IsKind(STANDARD_TYPE(StepGeom_Axis2Placement3d)))
3007             {
3008               anAP = Handle(StepGeom_Axis2Placement3d)::DownCast(aDRI);
3009             }
3010           }
3011         }
3012       }
3013     }
3014     else if (!aPMT.IsNull())
3015     {
3016       StepShape_ToleranceMethodDefinition aTMD = aPMT->Range();
3017       if(aPMT.IsNull()) continue;
3018       if(aTMD.CaseNumber() == 1)
3019         //! 1 -> ToleranceValue from StepShape
3020         //! 2 -> LimitsAndFits from StepShape
3021       {
3022         //plus minus tolerance 
3023         aTV = aTMD.ToleranceValue();
3024         if (aTV.IsNull()) continue;
3025
3026         Standard_Real aVal = aTV->UpperBound()->ValueComponent();
3027         StepBasic_Unit anUnit = aTV->UpperBound()->UnitComponent();
3028         Standard_Real aFact=1.;
3029         if(anUnit.IsNull()) continue;
3030         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
3031         Handle(StepBasic_NamedUnit) NU = anUnit.NamedUnit();
3032         if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
3033         aDim3 = aVal;
3034
3035         aVal = aTV->LowerBound()->ValueComponent();
3036         anUnit = aTV->LowerBound()->UnitComponent();
3037         aFact=1.;
3038         if(anUnit.IsNull()) continue;
3039         if( !(anUnit.CaseNum(anUnit.Value())==1) ) continue;
3040         NU = anUnit.NamedUnit();
3041         if(GetLengthConversionFactor(NU,aFact)) aVal=aVal*aFact;
3042         aDim2 = Abs(aVal);
3043       }
3044       else
3045       {
3046         // calss of tolerance
3047         aLAF = aTMD.LimitsAndFits();
3048       }
3049     }
3050   }
3051
3052   if(aDim1<0) return;
3053
3054   aDimObj = new XCAFDimTolObjects_DimensionObject();
3055   if(aDim2 < 0)
3056     aDimObj->SetValue(aDim1);
3057   else if (aDim3 < 0)
3058   {
3059     Handle(TColStd_HArray1OfReal) anArr = new TColStd_HArray1OfReal(1,2);
3060     anArr->SetValue(1,aDim1);
3061     anArr->SetValue(2,aDim2);
3062     aDimObj->SetValues(anArr);
3063   }
3064   else
3065   {
3066     Handle(TColStd_HArray1OfReal) anArr = new TColStd_HArray1OfReal(1,3);
3067     anArr->SetValue(1,aDim1);
3068     anArr->SetValue(2,aDim2);
3069     anArr->SetValue(3,aDim3);
3070     aDimObj->SetValues(anArr);
3071   }
3072   if(!aTQ.IsNull()) 
3073   {
3074     XCAFDimTolObjects_DimensionQualifier aQ;
3075     if (STEPCAFControl_GDTProperty::GetDimQualifierType(aTQ->Name(), aQ))
3076     {
3077         aDimObj->SetQualifier(aQ);
3078     }
3079   }
3080
3081   if (!aVFTQ.IsNull())
3082   {
3083     //A typical value would be 'NR2 2.2'
3084     TCollection_HAsciiString aFormat = aVFTQ->FormatType();
3085     Standard_Integer i = aFormat.Location(1,' ',1,aFormat.Length());
3086     aFormat.SubString(i+1,i+1)->IntegerValue();
3087     aDimObj->SetNbOfDecimalPlaces(aFormat.SubString(i+1,i+1)->IntegerValue(),
3088       aFormat.SubString(i+3,i+3)->IntegerValue());
3089   }
3090
3091   if (!aLAF.IsNull())
3092   { 
3093     //get class of tolerance
3094     Standard_Boolean aHolle = Standard_False;
3095     XCAFDimTolObjects_DimensionFormVariance aFV = XCAFDimTolObjects_DimensionFormVariance_None;
3096     XCAFDimTolObjects_DimensionGrade aG = XCAFDimTolObjects_DimensionGrade_IT01;
3097     STEPCAFControl_GDTProperty::GetDimClassOfTolerance(aLAF, aHolle, aFV, aG);
3098     aDimObj->SetClassOfTolerance(aHolle, aFV, aG);
3099   }
3100
3101   if (!aCRI.IsNull() && aCRI->ItemElement()->Length() > 0)
3102   {
3103     //get modifiers
3104     XCAFDimTolObjects_DimensionModifiersSequence aModifiers;
3105     STEPCAFControl_GDTProperty::GetDimModifiers(aCRI, aModifiers);
3106     if(aModifiers.Length() > 0)
3107       aDimObj->SetModifiers(aModifiers);
3108   }
3109
3110   Handle(TCollection_HAsciiString) aName;
3111   if(!aDimSize.IsNull())
3112   {
3113     aName = aDimSize->Name();
3114   }
3115   else
3116   {
3117     aName = aDimLocation->Name();
3118   }
3119   XCAFDimTolObjects_DimensionType aType = XCAFDimTolObjects_DimensionType_Location_None;
3120   if (!STEPCAFControl_GDTProperty::GetDimType(aName, aType))
3121   {
3122     if(!aDimSize.IsNull())
3123     {
3124       Handle(StepShape_AngularSize) anAngSize= 
3125         Handle(StepShape_AngularSize)::DownCast(aDimSize);
3126       if(!anAngSize.IsNull())
3127       {
3128         //get qualifier for angular value
3129         aType = XCAFDimTolObjects_DimensionType_Size_Angular;
3130         if(anAngSize->AngleSelection() == StepShape_Equal)
3131           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Avg);
3132         else if (anAngSize->AngleSelection() == StepShape_Large)
3133           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Max);
3134         else if (anAngSize->AngleSelection() == StepShape_Small)
3135           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Min);
3136       }
3137     }
3138     else
3139     {
3140       Handle(StepShape_AngularLocation) anAngLoc= 
3141         Handle(StepShape_AngularLocation)::DownCast(aDimLocation);
3142       if(!anAngLoc.IsNull())
3143       {
3144         //get qualifier for angular value
3145         aType = XCAFDimTolObjects_DimensionType_Location_Angular;
3146         if(anAngLoc->AngleSelection() == StepShape_Equal)
3147           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Avg);
3148         else if (anAngLoc->AngleSelection() == StepShape_Large)
3149           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Max);
3150         else if (anAngLoc->AngleSelection() == StepShape_Small)
3151           aDimObj->SetQualifier(XCAFDimTolObjects_DimensionQualifier_Min);
3152       }
3153     }
3154     if(aType == XCAFDimTolObjects_DimensionType_Location_None)
3155     {
3156       Handle(StepRepr_ShapeAspect) aPSA;
3157       if(!aDimSize.IsNull())
3158       {
3159         Handle(StepShape_DimensionalSizeWithPath) aDimSizeWithPath= 
3160           Handle(StepShape_DimensionalSizeWithPath)::DownCast(aDimSize);
3161         if (!aDimSizeWithPath.IsNull())
3162         {
3163           aType = XCAFDimTolObjects_DimensionType_Size_WithPath;
3164           aPSA = aDimSizeWithPath->Path();
3165         }
3166       }
3167       else
3168       {
3169         Handle(StepShape_DimensionalLocationWithPath) aDimLocWithPath= 
3170           Handle(StepShape_DimensionalLocationWithPath)::DownCast(aDimLocation);
3171         if (!aDimLocWithPath.IsNull())
3172         {
3173           aType = XCAFDimTolObjects_DimensionType_Location_WithPath;
3174           aPSA = aDimLocWithPath->Path();
3175         }
3176       }
3177
3178       if(!aPSA.IsNull())
3179       {
3180         //for DimensionalLocationWithPath
3181         Handle(StepGeom_GeometricRepresentationItem) aGRI;
3182         Handle(StepAP242_GeometricItemSpecificUsage) aPGISU;
3183         Interface_EntityIterator anIterDSWP = aGraph.Sharings(aPSA);
3184         for(anIterDSWP.Start(); anIterDSWP.More() && aPGISU.IsNull(); anIterDSWP.Next()) {
3185           aPGISU = Handle(StepAP242_GeometricItemSpecificUsage)::DownCast(anIterDSWP.Value());
3186         }
3187         if(aPGISU.IsNull()) return;
3188         if(aPGISU->NbIdentifiedItem() > 0) {
3189           aGRI = Handle(StepGeom_GeometricRepresentationItem)::DownCast(aPGISU->IdentifiedItemValue(1));
3190         }
3191         if(aGRI.IsNull()) return;
3192         Handle(StepRepr_RepresentationItem) aPRI;
3193         Interface_EntityIterator anIterGRI = aGraph.Sharings(aGRI);
3194         for(anIterGRI.Start(); anIterGRI.More() && aPGISU.IsNull(); anIterGRI.Next()) {
3195           aPRI = Handle(StepRepr_RepresentationItem)::DownCast(anIterGRI.Value());
3196         }
3197         Standard_Integer anIndex = aTP->MapIndex(aPRI);
3198         TopoDS_Edge aSh;
3199         if(anIndex >0) {
3200           Handle(Transfer_Binder) aBinder = aTP->MapItem(anIndex);
3201           aSh = TopoDS::Edge(TransferBRep::ShapeResult(aBinder));
3202         }
3203         if(aSh.IsNull()) return; 
3204         aDimObj->SetPath(aSh);
3205       }
3206       else if(!anAP.IsNull())
3207       {
3208         if(anAP->Name()->String().IsEqual("orientation") && !anAP->Axis().IsNull())
3209         {
3210           //for Oriented Dimensional Location
3211           Handle(TColStd_HArray1OfReal) aDirArr = anAP->RefDirection()->DirectionRatios();
3212           gp_Dir aDir;
3213           if(!aDirArr.IsNull() && aDirArr->Length() > 2)
3214           {
3215             aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, aDirArr->Lower()+2);
3216             aDimObj->SetDirection(aDir);
3217           }
3218           else if(aDirArr->Length() > 1)
3219           {
3220             aDir.SetCoord(aDirArr->Lower(), aDirArr->Lower()+1, 0);
3221             aDimObj->SetDirection(aDir);
3222           }
3223         }
3224       }
3225     }
3226   }
3227   aDimObj->SetType(aType);
3228
3229   
3230   if(!aDimObj.IsNull())
3231   {
3232
3233     Handle(XCAFDoc_Dimension) aDim;
3234
3235     if(aDimL.FindAttribute(XCAFDoc_Dimension::GetID(),aDim))
3236     {
3237       readAnnotation(aTR, theEnt, aDimObj);
3238       aDim->SetObject(aDimObj);
3239     }
3240   }
3241 }
3242
3243 //=======================================================================
3244 //function : getTolType
3245 //purpose  : 
3246 //=======================================================================
3247 static Standard_Boolean getTolType(const Handle(Standard_Transient)& theEnt,
3248                        XCAFDimTolObjects_GeomToleranceType& theType)
3249 {