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