5cf87cc385bf85186723a4fdebe7e787052887bd
[occt.git] / src / STEPCAFControl / STEPCAFControl_Writer.cxx
1 // Created on: 2000-08-15
2 // Created by: Andrey BETENEV
3 // Copyright (c) 2000-2014 OPEN CASCADE SAS
4 //
5 // This file is part of Open CASCADE Technology software library.
6 //
7 // This library is free software; you can redistribute it and/or modify it under
8 // the terms of the GNU Lesser General Public License version 2.1 as published
9 // by the Free Software Foundation, with special exception defined in the file
10 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
11 // distribution for complete text of the license and disclaimer of any warranty.
12 //
13 // Alternatively, this file may be used under the terms of Open CASCADE
14 // commercial license or contractual agreement.
15
16 // CURRENT LIMITATIONS: 
17 // when val props and names assigned to instance of 
18 // component in assembly, it is in fact supposed that only one CDSR corresponds
19 // to such shape. This can be wrong and should be handled more carefully
20 // (analysis of SDRs which the CDSR links should be done)
21 // Names and validation props are supported for top-level shapes only
22
23 #include <BRep_Builder.hxx>
24 #include <GeomToStep_MakeCartesianPoint.hxx>
25 #include <HeaderSection_FileSchema.hxx>
26 #include <Interface_EntityIterator.hxx>
27 #include <Interface_Static.hxx>
28 #include <Message_Messenger.hxx>
29 #include <MoniTool_DataMapIteratorOfDataMapOfShapeTransient.hxx>
30 #include <NCollection_Vector.hxx>
31 #include <OSD_Path.hxx>
32 #include <Quantity_TypeOfColor.hxx>
33 #include <StepAP214_Protocol.hxx>
34 #include <StepAP242_DraughtingModelItemAssociation.hxx>
35 #include <StepAP242_GeometricItemSpecificUsage.hxx>
36 #include <StepBasic_DerivedUnit.hxx>
37 #include <StepBasic_DerivedUnitElement.hxx>
38 #include <StepBasic_HArray1OfDerivedUnitElement.hxx>
39 #include <StepBasic_LengthMeasureWithUnit.hxx>
40 #include <StepBasic_MeasureValueMember.hxx>
41 #include <StepBasic_Product.hxx>
42 #include <StepBasic_ProductDefinition.hxx>
43 #include <StepBasic_ProductDefinitionFormation.hxx>
44 #include <StepBasic_ProductDefinitionRelationship.hxx>
45 #include <StepBasic_SiUnitAndLengthUnit.hxx>
46 #include <StepBasic_SiUnitAndMassUnit.hxx>
47 #include <StepBasic_SiUnitAndPlaneAngleUnit.hxx>
48 #include <STEPCAFControl_ActorWrite.hxx>
49 #include <STEPCAFControl_Controller.hxx>
50 #include <STEPCAFControl_ExternFile.hxx>
51 #include <STEPCAFControl_Writer.hxx>
52 #include <STEPConstruct.hxx>
53 #include <STEPConstruct_DataMapOfAsciiStringTransient.hxx>
54 #include <STEPConstruct_DataMapOfPointTransient.hxx>
55 #include <STEPConstruct_ExternRefs.hxx>
56 #include <STEPCAFControl_GDTProperty.hxx>
57 #include <STEPConstruct_Styles.hxx>
58 #include <STEPConstruct_ValidationProps.hxx>
59 #include <STEPControl_StepModelType.hxx>
60 #include <STEPControl_Writer.hxx>
61 #include <StepData_Logical.hxx>
62 #include <StepData_StepModel.hxx>
63 #include <StepDimTol_AngularityTolerance.hxx>
64 #include <StepDimTol_CircularRunoutTolerance.hxx>
65 #include <StepDimTol_CoaxialityTolerance.hxx>
66 #include <StepDimTol_ConcentricityTolerance.hxx>
67 #include <StepDimTol_CylindricityTolerance.hxx>
68 #include <StepDimTol_Datum.hxx>
69 #include <StepDimTol_DatumFeature.hxx>
70 #include <StepDimTol_DatumReference.hxx>
71 #include <StepDimTol_DatumReferenceElement.hxx>
72 #include <StepDimTol_DatumSystem.hxx>
73 #include <StepDimTol_DatumSystemOrReference.hxx>
74 #include <StepDimTol_DatumTarget.hxx>
75 #include <StepDimTol_FlatnessTolerance.hxx>
76 #include <StepDimTol_GeometricToleranceType.hxx>
77 #include <StepDimTol_GeometricToleranceWithDatumReference.hxx>
78 #include <StepDimTol_GeometricToleranceWithModifiers.hxx>
79 #include <StepDimTol_GeoTolAndGeoTolWthDatRef.hxx>
80 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol.hxx>
81 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod.hxx>
82 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol.hxx>
83 #include <StepDimTol_GeoTolAndGeoTolWthMaxTol.hxx>
84 #include <StepDimTol_GeoTolAndGeoTolWthMod.hxx>
85 #include <StepDimTol_HArray1OfDatumReference.hxx>
86 #include <StepDimTol_HArray1OfDatumReferenceElement.hxx>
87 #include <StepDimTol_HArray1OfDatumReferenceModifier.hxx>
88 #include <StepDimTol_HArray1OfDatumSystemOrReference.hxx>
89 #include <StepDimTol_LineProfileTolerance.hxx>
90 #include <StepDimTol_ModifiedGeometricTolerance.hxx>
91 #include <StepDimTol_ParallelismTolerance.hxx>
92 #include <StepDimTol_PerpendicularityTolerance.hxx>
93 #include <StepDimTol_PlacedDatumTargetFeature.hxx>
94 #include <StepDimTol_PositionTolerance.hxx>
95 #include <StepDimTol_RoundnessTolerance.hxx>
96 #include <StepDimTol_RunoutZoneDefinition.hxx>
97 #include <StepDimTol_RunoutZoneOrientation.hxx>
98 #include <StepDimTol_StraightnessTolerance.hxx>
99 #include <StepDimTol_SurfaceProfileTolerance.hxx>
100 #include <StepDimTol_SymmetryTolerance.hxx>
101 #include <StepDimTol_ToleranceZone.hxx>
102 #include <StepDimTol_ToleranceZoneForm.hxx>
103 #include <StepDimTol_TotalRunoutTolerance.hxx>
104 #include <StepGeom_Axis2Placement3d.hxx>
105 #include <StepGeom_CartesianPoint.hxx>
106 #include <StepGeom_Direction.hxx>
107 #include <StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext.hxx>
108 #include <StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx.hxx>
109 #include <StepGeom_Plane.hxx>
110 #include <StepGeom_Surface.hxx>
111 #include <StepRepr_CompGroupShAspAndCompShAspAndDatumFeatAndShAsp.hxx>
112 #include <StepRepr_CompositeShapeAspect.hxx>
113 #include <StepRepr_ConstructiveGeometryRepresentation.hxx>
114 #include <StepRepr_ConstructiveGeometryRepresentationRelationship.hxx>
115 #include <StepRepr_DerivedShapeAspect.hxx>
116 #include <StepRepr_DescriptiveRepresentationItem.hxx>
117 #include <StepRepr_FeatureForDatumTargetRelationship.hxx>
118 #include <StepRepr_HArray1OfRepresentationItem.hxx>
119 #include <StepRepr_MeasureRepresentationItem.hxx>
120 #include <StepRepr_NextAssemblyUsageOccurrence.hxx>
121 #include <StepRepr_ProductDefinitionShape.hxx>
122 #include <StepRepr_PropertyDefinition.hxx>
123 #include <StepRepr_RepresentedDefinition.hxx>
124 #include <StepRepr_Representation.hxx>
125 #include <StepRepr_RepresentationItem.hxx>
126 #include <StepRepr_ReprItemAndLengthMeasureWithUnit.hxx>
127 #include <StepRepr_ReprItemAndLengthMeasureWithUnitAndQRI.hxx>
128 #include <StepRepr_ReprItemAndPlaneAngleMeasureWithUnit.hxx>
129 #include <StepRepr_ReprItemAndPlaneAngleMeasureWithUnitAndQRI.hxx>
130 #include <StepRepr_ShapeAspect.hxx>
131 #include <StepRepr_ShapeAspectDerivingRelationship.hxx>
132 #include <StepRepr_ShapeAspectRelationship.hxx>
133 #include <StepRepr_SpecifiedHigherUsageOccurrence.hxx>
134 #include <StepRepr_ValueRange.hxx>
135 #include <StepShape_AdvancedFace.hxx>
136 #include <StepShape_AngleRelator.hxx>
137 #include <StepShape_AngularLocation.hxx>
138 #include <StepShape_AngularSize.hxx>
139 #include <StepShape_ConnectedFaceSet.hxx>
140 #include <StepShape_ContextDependentShapeRepresentation.hxx>
141 #include <StepShape_DimensionalCharacteristic.hxx>
142 #include <StepShape_DimensionalCharacteristicRepresentation.hxx>
143 #include <StepShape_DimensionalLocation.hxx>
144 #include <StepShape_DimensionalLocationWithPath.hxx>
145 #include <StepShape_DimensionalSize.hxx>
146 #include <StepShape_DimensionalSizeWithPath.hxx>
147 #include <StepShape_EdgeCurve.hxx>
148 #include <StepShape_EdgeLoop.hxx>
149 #include <StepShape_FaceBound.hxx>
150 #include <StepShape_LimitsAndFits.hxx>
151 #include <StepShape_OrientedEdge.hxx>
152 #include <StepShape_PlusMinusTolerance.hxx>
153 #include <StepShape_QualifiedRepresentationItem.hxx>
154 #include <StepShape_ShapeDefinitionRepresentation.hxx>
155 #include <StepShape_ShapeDimensionRepresentation.hxx>
156 #include <StepShape_ShapeRepresentation.hxx>
157 #include <StepShape_ShapeRepresentationWithParameters.hxx>
158 #include <StepShape_ToleranceValue.hxx>
159 #include <StepShape_TypeQualifier.hxx>
160 #include <StepShape_ValueFormatTypeQualifier.hxx>
161 #include <StepVisual_AnnotationPlane.hxx>
162 #include <StepVisual_CurveStyle.hxx>
163 #include <StepVisual_DraughtingCallout.hxx>
164 #include <StepVisual_DraughtingModel.hxx>
165 #include <StepVisual_HArray1OfInvisibleItem.hxx>
166 #include <StepVisual_HArray1OfLayeredItem.hxx>
167 #include <StepVisual_HArray1OfPresentationStyleAssignment.hxx>
168 #include <StepVisual_HArray1OfPresentationStyleSelect.hxx>
169 #include <StepVisual_Invisibility.hxx>
170 #include <StepVisual_InvisibleItem.hxx>
171 #include <StepVisual_MechanicalDesignGeometricPresentationRepresentation.hxx>
172 #include <StepVisual_NullStyleMember.hxx>
173 #include <StepVisual_PointStyle.hxx>
174 #include <StepVisual_PresentationLayerAssignment.hxx>
175 #include <StepVisual_PresentationRepresentation.hxx>
176 #include <StepVisual_PresentationStyleAssignment.hxx>
177 #include <StepVisual_PresentationStyleByContext.hxx>
178 #include <StepVisual_StyledItem.hxx>
179 #include <StepVisual_SurfaceStyleUsage.hxx>
180 #include <StepVisual_TessellatedAnnotationOccurrence.hxx>
181 #include <StepVisual_TessellatedGeometricSet.hxx>
182 #include <TCollection_AsciiString.hxx>
183 #include <TCollection_HAsciiString.hxx>
184 #include <TColStd_HArray1OfReal.hxx>
185 #include <TColStd_HArray1OfTransient.hxx>
186 #include <TColStd_HSequenceOfTransient.hxx>
187 #include <TColStd_MapOfAsciiString.hxx>
188 #include <TColStd_MapOfTransient.hxx>
189 #include <TDataStd_Name.hxx>
190 #include <TDataStd_TreeNode.hxx>
191 #include <TDataStd_UAttribute.hxx>
192 #include <TDF_AttributeSequence.hxx>
193 #include <TDF_ChildIterator.hxx>
194 #include <TDF_Label.hxx>
195 #include <TDF_LabelSequence.hxx>
196 #include <TDF_Tool.hxx>
197 #include <TDocStd_Document.hxx>
198 #include <TopoDS_Compound.hxx>
199 #include <TopoDS_Iterator.hxx>
200 #include <TopoDS_Shape.hxx>
201 #include <TopTools_MapOfShape.hxx>
202 #include <TopTools_SequenceOfShape.hxx>
203 #include <Transfer_ActorOfFinderProcess.hxx>
204 #include <Transfer_Binder.hxx>
205 #include <Transfer_FinderProcess.hxx>
206 #include <Transfer_TransientListBinder.hxx>
207 #include <TransferBRep.hxx>
208 #include <TransferBRep_ShapeMapper.hxx>
209 #include <XCAFDimTolObjects_DatumObject.hxx>
210 #include <XCAFDimTolObjects_DimensionFormVariance.hxx>
211 #include <XCAFDimTolObjects_DimensionGrade.hxx>
212 #include <XCAFDimTolObjects_DimensionObject.hxx>
213 #include <XCAFDimTolObjects_DimensionModif.hxx>
214 #include <XCAFDimTolObjects_DimensionModifiersSequence.hxx>
215 #include <XCAFDimTolObjects_DimensionQualifier.hxx>
216 #include <XCAFDimTolObjects_GeomToleranceObject.hxx>
217 #include <XCAFDoc.hxx>
218 #include <XCAFDoc_Area.hxx>
219 #include <XCAFDoc_Centroid.hxx>
220 #include <XCAFDoc_ColorTool.hxx>
221 #include <XCAFDoc_Datum.hxx>
222 #include <XCAFDoc_Dimension.hxx>
223 #include <XCAFDoc_DimTol.hxx>
224 #include <XCAFDoc_DimTolTool.hxx>
225 #include <XCAFDoc_DocumentTool.hxx>
226 #include <XCAFDoc_GeomTolerance.hxx>
227 #include <XCAFDoc_GraphNode.hxx>
228 #include <XCAFDoc_LayerTool.hxx>
229 #include <XCAFDoc_Material.hxx>
230 #include <XCAFDoc_MaterialTool.hxx>
231 #include <XCAFDoc_ShapeTool.hxx>
232 #include <XCAFDoc_Volume.hxx>
233 #include <XCAFPrs.hxx>
234 #include <XCAFPrs_DataMapIteratorOfDataMapOfStyleShape.hxx>
235 #include <XCAFPrs_DataMapOfShapeStyle.hxx>
236 #include <XCAFPrs_DataMapOfStyleShape.hxx>
237 #include <XCAFPrs_Style.hxx>
238 #include <XSControl_TransferWriter.hxx>
239 #include <XSControl_WorkSession.hxx>
240
241 // added by skl 15.01.2004 for D&GT writing
242 //#include <StepRepr_CompoundItemDefinition.hxx>
243 //#include <StepRepr_CompoundItemDefinitionMember.hxx>
244 // added by skl 12.02.2004 for writing materials
245 //=======================================================================
246 //function : GetLabelName
247 //purpose  : auxilary function: take name of label and append it to str
248 //=======================================================================
249 static Standard_Boolean GetLabelName (const TDF_Label &L, Handle(TCollection_HAsciiString) &str)
250 {
251   Handle(TDataStd_Name) N;
252   if ( ! L.FindAttribute ( TDataStd_Name::GetID(), N ) ) return Standard_False;
253   TCollection_ExtendedString name = N->Get();
254   if ( name.Length() <=0 ) return Standard_False;
255
256   // set name, converting it to Ascii and removing spaces
257   TCollection_AsciiString buf ( name, '?' );
258   buf.LeftAdjust();
259   buf.RightAdjust();
260   buf.ChangeAll(' ','_');
261   str->AssignCat ( buf.ToCString() );
262   return Standard_True;
263 }
264
265
266 //=======================================================================
267 //function : STEPCAFControl_Writer
268 //purpose  :
269 //=======================================================================
270
271 STEPCAFControl_Writer::STEPCAFControl_Writer () :
272        myColorMode( Standard_True ),
273        myNameMode ( Standard_True ),
274        myLayerMode( Standard_True ),
275        myPropsMode( Standard_True ),
276        mySHUOMode ( Standard_True ),
277        myDGTMode  ( Standard_True ),
278        myMatMode  ( Standard_True )
279 {
280   STEPCAFControl_Controller::Init();
281   Handle(XSControl_WorkSession) WS = new XSControl_WorkSession;
282   Init ( WS );
283 }
284
285
286 //=======================================================================
287 //function : STEPCAFControl_Writer
288 //purpose  :
289 //=======================================================================
290
291 STEPCAFControl_Writer::STEPCAFControl_Writer (const Handle(XSControl_WorkSession)& WS,
292                                               const Standard_Boolean scratch)
293 {
294   STEPCAFControl_Controller::Init();
295   Init ( WS, scratch );
296   myColorMode = Standard_True;
297   myNameMode = Standard_True;
298   myLayerMode = Standard_True;
299   myPropsMode = Standard_True;
300   mySHUOMode = Standard_True;
301 }
302
303
304 //=======================================================================
305 //function : Init
306 //purpose  :
307 //=======================================================================
308
309 void STEPCAFControl_Writer::Init (const Handle(XSControl_WorkSession)& WS,
310                                   const Standard_Boolean scratch)
311 {
312   WS->SelectNorm ( "STEP" );
313   myWriter.SetWS (WS,scratch);
314   myFiles.Clear();
315   myLabEF.Clear();
316   myLabels.Clear();
317   myGDTPresentationDM = new StepVisual_DraughtingModel();
318   myGDTPrsCurveStyle = new StepVisual_HArray1OfPresentationStyleAssignment(1, 1);
319 }
320
321
322 //=======================================================================
323 //function : Write
324 //purpose  :
325 //=======================================================================
326
327 IFSelect_ReturnStatus STEPCAFControl_Writer::Write (const Standard_CString filename)
328 {
329   IFSelect_ReturnStatus status = myWriter.Write ( filename );
330
331   // get directory name of the main file
332   OSD_Path mainfile ( filename );
333   mainfile.SetName ( "" );
334   mainfile.SetExtension ( "" );
335   TCollection_AsciiString dpath;
336   mainfile.SystemName ( dpath );
337
338   NCollection_DataMap<TCollection_AsciiString, Handle(STEPCAFControl_ExternFile)>::Iterator it(myFiles);
339   for ( ; it.More(); it.Next() ) {
340     Handle(STEPCAFControl_ExternFile) EF = it.Value();
341     if ( EF->GetWriteStatus() != IFSelect_RetVoid ) continue;
342
343     // construct extern file name
344     TCollection_AsciiString fname = OSD_Path::AbsolutePath ( dpath, EF->GetName()->String() );
345     if ( fname.Length() <= 0 ) fname = EF->GetName()->String();
346 #ifdef OCCT_DEBUG
347     cout << "Writing external file: " << fname.ToCString() << endl;
348 #endif
349     
350     EF->SetWriteStatus ( EF->GetWS()->SendAll ( fname.ToCString() ) );
351   }
352
353   return status;
354 }
355
356
357 //=======================================================================
358 //function : Transfer
359 //purpose  :
360 //=======================================================================
361
362 Standard_Boolean STEPCAFControl_Writer::Transfer( const Handle(TDocStd_Document) &doc,
363                                                   const STEPControl_StepModelType mode,
364                                                   const Standard_CString multi )
365 {
366   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( doc->Main() );
367   if ( STool.IsNull() ) return Standard_False;
368
369   TDF_LabelSequence labels;
370   STool->GetFreeShapes ( labels );
371   return Transfer ( myWriter, labels, mode, multi );
372 }
373
374
375 //=======================================================================
376 //function : Transfer
377 //purpose  :
378 //=======================================================================
379
380 Standard_Boolean STEPCAFControl_Writer::Transfer( const TDF_Label& L,
381                                                   const STEPControl_StepModelType mode,
382                                                   const Standard_CString multi )
383 {
384   TDF_LabelSequence labels;
385   labels.Append ( L );
386   return Transfer ( myWriter, labels, mode, multi );
387 }
388
389 //=======================================================================
390 //function : Transfer
391 //purpose  :
392 //=======================================================================
393
394 Standard_Boolean STEPCAFControl_Writer::Transfer( const TDF_LabelSequence& labels,
395                                                   const STEPControl_StepModelType mode,
396                                                   const Standard_CString multi )
397 {
398   return Transfer( myWriter, labels, mode, multi );
399 }
400
401 //=======================================================================
402 //function : Perform
403 //purpose  :
404 //=======================================================================
405
406 Standard_Boolean STEPCAFControl_Writer::Perform (const Handle(TDocStd_Document) &doc,
407                                                  const Standard_CString filename)
408 {
409   if ( ! Transfer ( doc ) ) return Standard_False;
410   return Write ( filename ) == IFSelect_RetDone;
411 }
412
413
414 //=======================================================================
415 //function : Perform
416 //purpose  :
417 //=======================================================================
418
419 Standard_Boolean STEPCAFControl_Writer::Perform (const Handle(TDocStd_Document) &doc,
420                                                  const TCollection_AsciiString &filename)
421 {
422   if ( ! Transfer ( doc ) ) return Standard_False;
423   return Write ( filename.ToCString() ) == IFSelect_RetDone;
424 }
425
426
427 //=======================================================================
428 //function : ExternFiles
429 //purpose  :
430 //=======================================================================
431
432 const NCollection_DataMap<TCollection_AsciiString, Handle(STEPCAFControl_ExternFile)>& STEPCAFControl_Writer::ExternFiles () const
433 {
434   return myFiles;
435 }
436
437
438 //=======================================================================
439 //function : ExternFile
440 //purpose  :
441 //=======================================================================
442
443 Standard_Boolean STEPCAFControl_Writer::ExternFile (const TDF_Label &L,
444                                                     Handle(STEPCAFControl_ExternFile) &ef) const
445 {
446   ef.Nullify();
447   if ( ! myLabEF.IsBound ( L ) ) return Standard_False;
448   ef = myLabEF.Find ( L );
449   return Standard_True;
450 }
451
452
453 //=======================================================================
454 //function : ExternFile
455 //purpose  :
456 //=======================================================================
457
458 Standard_Boolean STEPCAFControl_Writer::ExternFile (const Standard_CString name,
459                                                     Handle(STEPCAFControl_ExternFile) &ef) const
460 {
461   ef.Nullify();
462   if ( ! myFiles.IsEmpty() || ! myFiles.IsBound ( name ) )
463     return Standard_False;
464   ef = myFiles.Find( name );
465   return Standard_True;
466 }
467
468
469 //=======================================================================
470 //function : Writer
471 //purpose  :
472 //=======================================================================
473
474 STEPControl_Writer &STEPCAFControl_Writer::ChangeWriter ()
475 {
476   return myWriter;
477 }
478
479
480 //=======================================================================
481 //function : Writer
482 //purpose  :
483 //=======================================================================
484
485 const STEPControl_Writer &STEPCAFControl_Writer::Writer () const
486 {
487   return myWriter;
488 }
489
490
491 //=======================================================================
492 //function : Transfer
493 //purpose  :
494 //=======================================================================
495
496 Standard_Boolean STEPCAFControl_Writer::Transfer (STEPControl_Writer &writer,
497                                                   const TDF_LabelSequence &labels,
498                                                   const STEPControl_StepModelType mode,
499                                                   const Standard_CString multi,
500                                                   const Standard_Boolean isExternFile)
501 {
502   if ( labels.Length() <=0 ) return Standard_False;
503
504   Handle(STEPCAFControl_ActorWrite) Actor =
505     Handle(STEPCAFControl_ActorWrite)::DownCast ( writer.WS()->NormAdaptor()->ActorWrite() );
506
507   // translate free top-level shapes of the DECAF document
508   Standard_Integer ap = Interface_Static::IVal ("write.step.schema");
509   TDF_LabelSequence sublabels;
510   for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
511     TDF_Label L = labels.Value(i);
512     TopoDS_Shape dummy;
513     if ( myLabels.IsBound ( L ) ) continue; // already processed
514
515     TopoDS_Shape shape = XCAFDoc_ShapeTool::GetShape ( L );
516     if ( shape.IsNull() ) continue;
517     
518     // write shape either as a whole, or as multifile (with extern refs)
519     if ( ! multi  ) {
520       Actor->SetStdMode ( Standard_False );
521
522       TDF_LabelSequence comp;
523
524       //for case when only part of assemby structure should be written in the document
525       //if specified label is component of the assembly then
526       //in order to save location of this component in the high-level assembly
527       //and save name of high-level assembly it is necessary to represent structure of high-level assembly 
528       //as assembly with one component specified by current label. 
529       //For that compound containing only specified component is binded to the label of the high-level assembly.
530       //The such way full structure of high-level assembly was replaced on the assembly contaning one component.
531       if ( XCAFDoc_ShapeTool::IsComponent ( L ) )
532       {
533         TopoDS_Compound aComp;
534         BRep_Builder aB;
535         aB.MakeCompound(aComp);
536         aB.Add(aComp, shape);
537         shape = aComp; 
538         comp.Append(L);
539         TDF_Label ref;
540         if ( XCAFDoc_ShapeTool::GetReferredShape ( L, ref ) )
541         {
542           if(XCAFDoc_ShapeTool::IsAssembly ( ref))
543             XCAFDoc_ShapeTool::GetComponents ( ref, comp, Standard_True );
544         }
545         L = L.Father();
546       }
547       else
548       {
549         // fill sequence of (sub) shapes for which attributes should be written
550         // and set actor to handle assemblies in a proper way
551         if(XCAFDoc_ShapeTool::IsAssembly ( L ))
552           XCAFDoc_ShapeTool::GetComponents ( L, comp, Standard_True );
553       }
554       
555       for ( Standard_Integer k=1; k <= comp.Length(); k++ ) {
556         TDF_Label ref;
557         if ( ! XCAFDoc_ShapeTool::GetReferredShape ( comp(k), ref ) ) continue;
558         if ( ! myLabels.IsBound ( ref ) ) {
559           TopoDS_Shape refS = XCAFDoc_ShapeTool::GetShape ( ref );
560           myLabels.Bind ( ref, refS );
561           sublabels.Append ( ref );
562           if ( XCAFDoc_ShapeTool::IsAssembly ( ref ) )
563             Actor->RegisterAssembly ( refS );
564         }
565       }
566       myLabels.Bind ( L, shape );
567       sublabels.Append ( L );
568       if ( XCAFDoc_ShapeTool::IsAssembly ( L ) )
569         Actor->RegisterAssembly ( shape );
570
571       writer.Transfer(shape,mode,Standard_False);
572       Actor->SetStdMode ( Standard_True ); // restore default behaviour
573     }
574     else {
575       // translate final solids
576       TopoDS_Shape Sass = TransferExternFiles ( L, mode, sublabels, multi );
577
578       // translate main assembly structure
579 /*
580       if ( ap == 3 ) { // if AP203, switch to AP214
581         Interface_Static::SetCVal ("write.step.schema", "AP214DIS");
582         Handle(StepData_StepModel) model = 
583           Handle(StepData_StepModel)::DownCast ( writer.WS()->Model() );
584         if ( model->HasHeaderEntity(STANDARD_TYPE(HeaderSection_FileSchema)) ) {
585           Handle(HeaderSection_FileSchema) fs = 
586             Handle(HeaderSection_FileSchema)::DownCast ( model->HeaderEntity(STANDARD_TYPE(HeaderSection_FileSchema)) );
587           Handle(TCollection_HAsciiString) str = fs->SchemaIdentifiersValue ( 1 );
588           Handle(TCollection_HAsciiString) ap214 = new TCollection_HAsciiString ( "AUTOMOTIVE_DESIGN" );
589           if ( str->Search ( ap214 ) <0 ) {
590             str->Clear();
591             str->AssignCat ( ap214 );
592           }
593         }
594       }
595 */      
596       Standard_Integer assemblymode = Interface_Static::IVal ("write.step.assembly");
597       Interface_Static::SetCVal ("write.step.assembly", "On");
598       writer.Transfer ( Sass, STEPControl_AsIs );
599       Interface_Static::SetIVal ("write.step.assembly", assemblymode);
600       Interface_Static::SetIVal ("write.step.schema", ap);
601     }
602   }
603
604   writer.WS()->ComputeGraph(Standard_True );// added by skl 03.11.2003 since we use
605                                             // writer.Transfer() wihtout compute graph
606
607   // write names
608   if ( GetNameMode() )
609     WriteNames ( writer.WS(), sublabels );
610
611   if ( !multi ) {
612     // write colors
613     if ( GetColorMode() )
614       WriteColors ( writer.WS(), sublabels );
615     
616     // write layers
617     if ( GetLayerMode() )
618       WriteLayers ( writer.WS(), sublabels );
619
620     // write SHUO entities
621     if ( GetSHUOMode() && !isExternFile ) 
622       // do not store SHUO for extern reference for the moment
623       WriteSHUOs (  writer.WS(), sublabels );
624     
625     // write G&DTs
626     if(GetDimTolMode()) {
627       if (ap == 5) {
628         WriteDGTsAP242(writer.WS(), sublabels);
629       }
630       else {
631         WriteDGTs(writer.WS(), sublabels);
632       }
633     }
634
635     // write Materials
636     if(GetMaterialMode())
637       WriteMaterials(writer.WS(),sublabels);
638
639     // register all MDGPRs in model
640     const Handle(Interface_InterfaceModel) &Model = writer.WS()->Model();
641     MoniTool_DataMapIteratorOfDataMapOfShapeTransient anItr(myMapCompMDGPR);
642     for (; anItr.More(); anItr.Next())
643       Model->AddWithRefs( anItr.Value() );
644   }
645   
646   if ( multi ) { // external refs
647     WriteExternRefs ( writer.WS(), sublabels );
648   }
649
650   // write validation props
651 //  if ( multi && ap ==3 ) {
652 //      Interface_Static::SetCVal ("write.step.schema", "AP214DIS");
653 //  }
654   if ( GetPropsMode() ) 
655     WriteValProps ( writer.WS(), sublabels, multi );
656
657   Interface_Static::SetIVal ("write.step.schema", ap);
658
659   // refresh graph
660   writer.WS()->ComputeGraph ( Standard_True );
661
662   /* ================================
663     *  Write names for the sub-shapes
664     * ================================ */
665
666   if (Interface_Static::IVal("write.stepcaf.subshapes.name") != 0)
667   {
668     const Handle(XSControl_TransferWriter) &TW = this->ChangeWriter().WS()->TransferWriter();
669     const Handle(Transfer_FinderProcess) &FP = TW->FinderProcess();
670
671     for ( int i = 1; i <= labels.Length(); i++ )
672     {
673       TDF_Label L = labels.Value(i);
674
675       for ( TDF_ChildIterator it(L, Standard_True); it.More(); it.Next() )
676       {
677         TDF_Label SubL = it.Value();
678
679         // Access name recorded in OCAF TDataStd_Name attribute
680         Handle(TCollection_HAsciiString) hSubName = new TCollection_HAsciiString;
681         if ( !GetLabelName(SubL, hSubName) )
682           continue;
683
684         // Access topological data
685         TopoDS_Shape SubS = XCAFDoc_ShapeTool::GetShape(SubL);
686         if ( SubS.IsNull() )
687           continue;
688
689         // Access the correspondent STEP Representation Item
690         Handle(StepRepr_RepresentationItem) RI;
691         Handle(TransferBRep_ShapeMapper) aShMapper = TransferBRep::ShapeMapper(FP, SubS);
692         if ( !FP->FindTypedTransient(aShMapper, STANDARD_TYPE(StepRepr_RepresentationItem), RI) )
693           continue;
694
695         // Record the name
696         RI->SetName(hSubName);
697       }
698     }
699   }
700
701   return Standard_True;
702 }
703
704
705 //=======================================================================
706 //function : TransferExternFiles
707 //purpose  :
708 //=======================================================================
709
710 TopoDS_Shape STEPCAFControl_Writer::TransferExternFiles (const TDF_Label &L,
711                                                          const STEPControl_StepModelType mode,
712                                                          TDF_LabelSequence &labels,
713                                                          const Standard_CString prefix)
714 {
715   // if label already translated, just return the shape
716   if ( myLabels.IsBound ( L ) ) {
717     return myLabels.Find ( L );
718   }
719
720   TopoDS_Compound C;
721   BRep_Builder B;
722   B.MakeCompound ( C );
723   //labels.Append ( L ); 
724   // if not assembly, write to separate file
725   if ( ! XCAFDoc_ShapeTool::IsAssembly ( L ) && !XCAFDoc_ShapeTool::IsComponent ( L )) {
726     labels.Append ( L );
727     // prepare for transfer
728     Handle(XSControl_WorkSession) newWS = new XSControl_WorkSession;
729     newWS->SelectNorm ( "STEP" );
730     STEPControl_Writer sw ( newWS, Standard_True );
731     TDF_LabelSequence Lseq;
732     Lseq.Append ( L );
733
734     // construct the name for extern file
735     Handle(TCollection_HAsciiString) basename = new TCollection_HAsciiString;
736     if ( prefix && prefix[0] ) basename->AssignCat ( prefix );
737     GetLabelName ( L, basename );
738     Handle(TCollection_HAsciiString) name = new TCollection_HAsciiString ( basename );
739     name->AssignCat ( ".stp" );
740     if ( myFiles.IsBound( name->ToCString() ) ) { // avoid confusions
741       for ( Standard_Integer k=1; k < 32000; k++ ) {
742         name = new TCollection_HAsciiString ( basename );
743         name->AssignCat ( "_" );
744         name->AssignCat ( TCollection_AsciiString ( k ).ToCString() );
745         name->AssignCat ( ".stp" );
746         if ( ! myFiles.IsBound ( name->ToCString() ) ) break;
747       }
748     }
749
750     // translate and record extern file
751     Handle(STEPCAFControl_ExternFile) EF = new STEPCAFControl_ExternFile;
752     EF->SetWS ( newWS );
753     EF->SetName ( name );
754     EF->SetLabel ( L );
755     Standard_Integer assemblymode = Interface_Static::IVal ("write.step.assembly");
756     Interface_Static::SetCVal ("write.step.assembly", "Off");
757     const Standard_CString multi = 0;
758     EF->SetTransferStatus ( Transfer ( sw, Lseq, mode, multi, Standard_True ) );
759     Interface_Static::SetIVal ("write.step.assembly", assemblymode);
760     myLabEF.Bind ( L, EF );
761     myFiles.Bind ( name->ToCString(), EF );
762
763     // return empty compound as replacement for the shape
764     myLabels.Bind ( L, C );
765     return C;
766   }
767   TDF_LabelSequence comp;
768   TDF_Label aCurL = L;
769   //if specified shape is component then high-level assembly is considered
770   //to get valid structure with location
771   if ( XCAFDoc_ShapeTool::IsComponent ( L ) )
772   {
773     comp.Append(L);
774     aCurL = L.Father();
775   }
776   // else iterate on components add create structure of empty compounds
777   // representing the assembly
778   else if (XCAFDoc_ShapeTool::IsAssembly ( L ))
779     XCAFDoc_ShapeTool::GetComponents ( L, comp, Standard_False );
780
781   labels.Append ( aCurL );
782   for ( Standard_Integer k=1; k <= comp.Length(); k++ ) {
783     TDF_Label lab = comp(k);
784     TDF_Label ref;
785     if ( ! XCAFDoc_ShapeTool::GetReferredShape ( lab, ref ) ) continue;
786     TopoDS_Shape Scomp = TransferExternFiles ( ref, mode, labels, prefix );
787     Scomp.Location ( XCAFDoc_ShapeTool::GetLocation ( lab ) );
788     B.Add ( C, Scomp );
789   }
790   myLabels.Bind ( aCurL, C );
791   return C;
792 }
793
794
795 //=======================================================================
796 //function : WriteExternRefs
797 //purpose  :
798 //=======================================================================
799
800 Standard_Boolean STEPCAFControl_Writer::WriteExternRefs (const Handle(XSControl_WorkSession) &WS,
801                                                          const TDF_LabelSequence &labels) const
802 {
803   if ( labels.Length() <=0 ) return Standard_False;
804
805   const Handle(XSControl_TransferWriter) &TW = WS->TransferWriter();
806   const Handle(Transfer_FinderProcess) &FP = TW->FinderProcess();
807   STEPConstruct_ExternRefs EFTool ( WS );
808   Standard_Integer schema = Interface_Static::IVal("write.step.schema");
809   for ( Standard_Integer k=1; k <= labels.Length(); k++ ) {
810     TDF_Label lab = labels(k);
811     if ( XCAFDoc_ShapeTool::IsAssembly ( lab ) ) continue; // skip assemblies
812
813     // get extern file
814     Handle(STEPCAFControl_ExternFile) EF;
815     if ( ! ExternFile ( lab, EF ) ) continue; // should never be
816
817     // find SDR
818     if ( ! myLabels.IsBound ( lab ) ) continue; // not recorded as translated, skip
819     TopoDS_Shape S = myLabels.Find ( lab );
820
821     Handle(StepShape_ShapeDefinitionRepresentation) SDR;
822     Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, S );
823     if ( ! FP->FindTypedTransient ( mapper, STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation), SDR ) ) {
824 #ifdef OCCT_DEBUG
825       cout << "Warning: Cannot find SDR for " << S.TShape()->DynamicType()->Name() << endl;
826 #endif
827       continue;
828     }
829
830     // add extern ref
831     const Standard_CString format = (const Standard_CString) ( schema == 3 ? "STEP AP203" : "STEP AP214" );
832     // try to get PD from SDR
833     StepRepr_RepresentedDefinition RD = SDR->Definition();
834     Handle(StepRepr_PropertyDefinition) aPropDef = RD.PropertyDefinition();
835     if (aPropDef.IsNull()) {
836 #ifdef OCCT_DEBUG
837       cout << "Warning: STEPCAFControl_Writer::WriteExternRefs StepRepr_PropertyDefinition is null for " << S.TShape()->DynamicType()->Name() << endl;
838 #endif
839       continue;
840     }
841     StepRepr_CharacterizedDefinition CharDef = aPropDef->Definition();
842     Handle(StepBasic_ProductDefinition) PD = CharDef.ProductDefinition();
843     if (PD.IsNull()) {
844 #ifdef OCCT_DEBUG
845       cout << "Warning: STEPCAFControl_Writer::WriteExternRefs StepBasic_ProductDefinition is null for " << S.TShape()->DynamicType()->Name() << endl;
846 #endif
847       continue;
848     }
849     EFTool.AddExternRef ( EF->GetName()->ToCString(), PD, format );
850   }
851   EFTool.WriteExternRefs(schema);
852   return Standard_True;
853 }
854
855
856 //=======================================================================
857 //function : FindEntities
858 //purpose  : auxilary
859 //=======================================================================
860 static Standard_Integer FindEntities (const Handle(Transfer_FinderProcess) &FP,
861                                       const TopoDS_Shape &S,
862                                       TopLoc_Location &L,
863                                       TColStd_SequenceOfTransient &seqRI)
864 {
865   Handle(StepRepr_RepresentationItem) item = STEPConstruct::FindEntity ( FP, S, L );
866
867   if ( ! item.IsNull() ) {
868     seqRI.Append ( item );
869     return 1;
870   }
871       
872   // may be S was splited during shape processing
873   Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, S );
874   Handle(Transfer_Binder) bnd = FP->Find ( mapper );
875   if ( bnd.IsNull() ) return 0;
876   
877   Handle(Transfer_TransientListBinder) TransientListBinder =
878     //Handle(Transfer_TransientListBinder)::DownCast( bnd->Next(Standard_True) );
879     Handle(Transfer_TransientListBinder)::DownCast( bnd );
880   Standard_Integer nres=0;
881   if ( TransientListBinder.IsNull() && S.ShapeType() == TopAbs_COMPOUND) 
882   {
883     for ( TopoDS_Iterator it(S); it.More(); it.Next() ) {
884       Handle(StepRepr_RepresentationItem) aLocalItem = STEPConstruct::FindEntity ( FP, it.Value(), L );
885       if (aLocalItem.IsNull() ) continue;
886       nres++;
887       seqRI.Append (aLocalItem);
888     }
889   }
890   else if(!TransientListBinder.IsNull())
891   {
892
893     const Standard_Integer nb = TransientListBinder->NbTransients();
894     for (Standard_Integer i=1; i<=nb; i++) {
895       Handle(Standard_Transient) t = TransientListBinder->Transient(i);
896       item = Handle(StepRepr_RepresentationItem)::DownCast(t);
897       if ( item.IsNull() ) continue;
898       nres++;
899       seqRI.Append ( item );
900     }
901   }
902 /*  works but is obsolete: another approach
903   if (i<=nb) {
904     TopoDS_Shape comp = TransferBRep::ShapeResult(bnd);
905     if ( ! comp.IsNull() && comp.ShapeType() < S.ShapeType() ) {
906       for ( TopoDS_Iterator it(comp); it.More(); it.Next() ) {
907         MakeSTEPStyles(Styles, it.Value(), settings, STEPstyle, 
908                        Map, ( hasOwn ? &style : 0 ) );
909       }
910     }
911   }
912 */
913   return nres;
914 }
915
916
917 //=======================================================================
918 //function : getStyledItem
919 //purpose  : auxilary
920 //=======================================================================
921 static Standard_Boolean getStyledItem(const TopoDS_Shape& S,
922                                       const Handle(XCAFDoc_ShapeTool)& STool,
923                                       const STEPConstruct_Styles &Styles, 
924                                       Handle(StepVisual_StyledItem) &resSelItem,
925                                       const MoniTool_DataMapOfShapeTransient& myMapCompMDGPR)
926 {
927   TDF_Label aTopShL = STool->FindShape(S, Standard_False);
928   TopoDS_Shape aTopLevSh = STool->GetShape( aTopShL );
929   Standard_Boolean found = Standard_False;
930   if ( !aTopLevSh.IsNull() &&  myMapCompMDGPR.IsBound( aTopLevSh ) ) {
931     Handle(StepVisual_PresentationRepresentation) aMDGPR = 
932       Handle(StepVisual_PresentationRepresentation)::DownCast( myMapCompMDGPR.Find( aTopLevSh ) );
933     Handle(StepRepr_HArray1OfRepresentationItem) anSelItmHArr = aMDGPR->Items();
934     // search for PSA of Monifold solid
935     if ( !anSelItmHArr.IsNull() )
936     {
937       for (Standard_Integer si = 1; si <= anSelItmHArr->Length(); si++) {
938         Handle(StepVisual_StyledItem) aSelItm =
939           Handle(StepVisual_StyledItem)::DownCast(anSelItmHArr->Value(si));
940
941         if ( aSelItm.IsNull() ) 
942           continue;
943
944         // check that it is a stiled item for monifold solid brep
945         TopLoc_Location Loc;
946         TColStd_SequenceOfTransient aNewseqRI;
947         FindEntities ( Styles.FinderProcess(), aTopLevSh, Loc, aNewseqRI );
948         if ( aNewseqRI.Length() > 0 )
949         {
950           
951           Handle(StepRepr_RepresentationItem) anItem = aSelItm->Item();
952           Standard_Boolean isSameMonSolBR = Standard_False;
953           for (Standard_Integer mi = 1; mi <= aNewseqRI.Length(); mi++) {
954             if ( !anItem.IsNull() && anItem == aNewseqRI.Value( mi ) ) {
955               isSameMonSolBR = Standard_True;
956               break;
957             }
958           }
959           if (!isSameMonSolBR)
960             continue;
961         }
962         
963         
964         for (Standard_Integer jsi = 1; jsi <= aSelItm->NbStyles() && !found; jsi++) {
965           Handle(StepVisual_PresentationStyleAssignment) aFatherPSA = aSelItm->StylesValue(jsi);
966           // check for PSA for top-level (not Presentation style by contex for NAUO)
967           if (aFatherPSA.IsNull() || aFatherPSA->IsKind(STANDARD_TYPE(StepVisual_PresentationStyleByContext)))
968             continue;
969           resSelItem = aSelItm;
970           found = Standard_True;
971         }
972       }
973     }
974   }
975   return found;
976 }
977
978
979 //=======================================================================
980 //function : setDefaultInstanceColor
981 //purpose  : auxilary
982 //=======================================================================
983 static Standard_Boolean setDefaultInstanceColor (const Handle(StepVisual_StyledItem) &aSelItm,
984                                                  Handle(StepVisual_PresentationStyleAssignment)& PSA)
985 {
986    Standard_Boolean found = Standard_False;
987   for (Standard_Integer jsi = 1; jsi <= aSelItm->NbStyles() && !found; jsi++) {
988     Handle(StepVisual_PresentationStyleAssignment) aFatherPSA = aSelItm->StylesValue(jsi);
989   // check for PSA for top-level (not Presentation style by contex for NAUO)
990   if (aFatherPSA.IsNull() || aFatherPSA->IsKind(STANDARD_TYPE(StepVisual_PresentationStyleByContext))) 
991     return Standard_False;
992           
993   // get style select from father PSA
994   if (aFatherPSA->NbStyles() > 0) {
995     Handle(StepVisual_HArray1OfPresentationStyleSelect) aFatherStyles =
996       new StepVisual_HArray1OfPresentationStyleSelect(1, aFatherPSA->NbStyles());
997     for (Standard_Integer k = 1; k <= aFatherPSA->NbStyles(); k++) {
998       StepVisual_PresentationStyleSelect PSS;
999       StepVisual_PresentationStyleSelect olDPSS = aFatherPSA->StylesValue(k);
1000       if (!olDPSS.PointStyle().IsNull())
1001         PSS.SetValue (olDPSS.PointStyle());
1002       else if (!olDPSS.CurveStyle().IsNull())
1003         PSS.SetValue (olDPSS.CurveStyle());
1004       else if (!olDPSS.SurfaceStyleUsage().IsNull())
1005         PSS.SetValue (olDPSS.SurfaceStyleUsage());
1006       else {
1007         found = Standard_False;
1008         break;
1009       }
1010       //aFatherStyles->SetValue( k, PSS );
1011       aFatherStyles->SetValue( k, olDPSS );
1012       found = Standard_True;
1013     }
1014             // init PSA of NAUO
1015     if (found) {
1016       PSA->Init( aFatherStyles );
1017     }
1018   }
1019     
1020   }
1021   return found;
1022 }
1023
1024
1025 //=======================================================================
1026 //function : MakeSTEPStyles
1027 //purpose  : auxilary
1028 //=======================================================================
1029 static void MakeSTEPStyles (STEPConstruct_Styles &Styles,
1030                             const TopoDS_Shape &S,
1031                             const XCAFPrs_DataMapOfShapeStyle &settings,
1032                             Handle(StepVisual_StyledItem) &override,
1033                             TopTools_MapOfShape &Map,
1034                             const MoniTool_DataMapOfShapeTransient& myMapCompMDGPR,
1035                             STEPConstruct_DataMapOfAsciiStringTransient &DPDCs,
1036                             STEPConstruct_DataMapOfPointTransient &ColRGBs,
1037                             const Handle(XCAFDoc_ColorTool)& CTool,
1038                             const XCAFPrs_Style *inherit = 0,
1039                             const Standard_Boolean isComponent = Standard_False)
1040 {
1041   // skip already processed shapes
1042   if ( ! Map.Add ( S ) ) return;
1043
1044   // check if shape has its own style (r inherits from ancestor)
1045   XCAFPrs_Style style;
1046   if ( inherit ) style = *inherit;
1047   if ( settings.IsBound(S) ) {
1048     XCAFPrs_Style own = settings.Find(S);
1049     if ( !own.IsVisible() ) style.SetVisibility ( Standard_False );
1050     if ( own.IsSetColorCurv() ) style.SetColorCurv ( own.GetColorCurv() );
1051     if ( own.IsSetColorSurf() ) style.SetColorSurf ( own.GetColorSurf() );
1052   }
1053
1054   // translate colors to STEP
1055   Handle(StepVisual_Colour) surfColor, curvColor;
1056   if ( style.IsSetColorSurf() )
1057     surfColor = Styles.EncodeColor(style.GetColorSurf(),DPDCs,ColRGBs);
1058   if ( style.IsSetColorCurv() )
1059     curvColor = Styles.EncodeColor(style.GetColorCurv(),DPDCs,ColRGBs);
1060   
1061   Standard_Boolean hasOwn = ( ! surfColor.IsNull() || 
1062                               ! curvColor.IsNull() ||
1063                               ! style.IsVisible() );
1064
1065   // find target item and assign style to it
1066   Handle(StepVisual_StyledItem) STEPstyle = override;
1067   if ( hasOwn ) {
1068     if ( S.ShapeType() != TopAbs_COMPOUND || isComponent ) { // skip compounds, let subshapes inherit its colors
1069       TopLoc_Location L;
1070       TColStd_SequenceOfTransient seqRI;
1071       Standard_Integer nb = FindEntities ( Styles.FinderProcess(), S, L, seqRI );
1072 #ifdef OCCT_DEBUG
1073       if ( nb <=0 ) cout << "Warning: Cannot find RI for " << S.TShape()->DynamicType()->Name() << endl;
1074 #endif
1075       //Get overridden style gka 10.06.03
1076       if ( isComponent && nb) 
1077         getStyledItem(S, CTool->ShapeTool(), Styles, override,myMapCompMDGPR);
1078        
1079            
1080       for ( Standard_Integer i=1; i <= nb; i++ ) {
1081         Handle(StepRepr_RepresentationItem) item = 
1082           Handle(StepRepr_RepresentationItem)::DownCast(seqRI(i));
1083         Handle(StepVisual_PresentationStyleAssignment) PSA;
1084         if ( style.IsVisible() || !surfColor.IsNull() || !curvColor.IsNull() ) {
1085           PSA = Styles.MakeColorPSA ( item, surfColor, curvColor, isComponent );
1086         }
1087         else {
1088           // default white color
1089           surfColor = Styles.EncodeColor(Quantity_Color(1,1,1,Quantity_TOC_RGB),DPDCs,ColRGBs);
1090           PSA = Styles.MakeColorPSA ( item, surfColor, curvColor, isComponent );
1091           if ( isComponent ) 
1092             setDefaultInstanceColor( override, PSA);
1093           
1094         } // end of component case
1095         
1096         STEPstyle = Styles.AddStyle ( item, PSA, override );
1097         hasOwn = Standard_False;
1098       }
1099     }
1100   }
1101
1102   // iterate on subshapes (except vertices :)
1103   if ( S.ShapeType() == TopAbs_EDGE ) return;
1104   if ( !isComponent ) // PTV 10.02.2003
1105     for ( TopoDS_Iterator it(S); it.More(); it.Next() ) {
1106       MakeSTEPStyles ( Styles, it.Value(), settings, STEPstyle,
1107                       Map, myMapCompMDGPR, DPDCs, ColRGBs, CTool,
1108                       ( hasOwn ? &style : 0 ) );
1109     }
1110 }
1111
1112 /*
1113 static Standard_Boolean getFatherColor (const TDF_Label& L,
1114                                         const Handle(XCAFDoc_ColorTool)& CTool,
1115                                         XCAFPrs_Style& style)
1116 {
1117   Standard_Boolean done = Standard_False;
1118   TopoDS_Shape aSh = CTool->ShapeTool()->GetShape( L );
1119   TDF_Label aFL = CTool->ShapeTool()->FindShape( aSh );
1120   if (aFL.IsNull() || aFL == L)
1121     return done;
1122   Quantity_Color C;
1123   if ( CTool->GetColor ( aFL, XCAFDoc_ColorGen, C ) ) {
1124     style.SetColorCurv ( C );
1125     style.SetColorSurf ( C );
1126     done = Standard_True;
1127   }
1128   if ( CTool->GetColor ( aFL, XCAFDoc_ColorSurf, C ) ) {
1129     style.SetColorSurf ( C );
1130     done = Standard_True;
1131   }
1132   if ( CTool->GetColor ( aFL, XCAFDoc_ColorCurv, C ) ) {
1133     style.SetColorCurv ( C );
1134     done = Standard_True;
1135   }
1136   
1137   return done;
1138 }
1139 */
1140
1141
1142 //=======================================================================
1143 //function : WriteColors
1144 //purpose  : 
1145 //=======================================================================
1146
1147 Standard_Boolean STEPCAFControl_Writer::WriteColors (const Handle(XSControl_WorkSession) &WS,
1148                                                      const TDF_LabelSequence &labels)
1149 {
1150   if ( labels.Length() <=0 ) return Standard_False;
1151
1152   // Iterate on shapes in the document
1153   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( labels(1) );
1154   if ( CTool.IsNull() ) return Standard_False;
1155
1156   STEPConstruct_Styles Styles ( WS );
1157   STEPConstruct_DataMapOfAsciiStringTransient DPDCs;
1158   STEPConstruct_DataMapOfPointTransient ColRGBs;
1159   for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
1160     TDF_Label L = labels.Value(i);
1161
1162     Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( labels(1) );
1163     // Skip assemblies: colors assigned to assemblies and their instances
1164     // are not supported (it is not clear how to encode that in STEP)
1165     if ( XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1166 #ifdef OCCT_DEBUG
1167       cout << "Warning: Cannot write color  for Assembly" << endl;
1168       cout << "Info: Check for colors assigned to components in assembly" << endl;
1169 #endif
1170       // PTV 22.01.2003 Write color for instances.
1171       TDF_LabelSequence compLabels;
1172       if ( aSTool.IsNull() )
1173         continue;
1174       if (!aSTool->GetComponents(L, compLabels))
1175         continue;
1176       WriteColors(WS, compLabels);
1177       continue;
1178     }
1179     Styles.ClearStyles();
1180
1181     // get a target shape and try to find corresponding context
1182     // (all the colors set under that label will be put into that context)
1183     TopoDS_Shape S;
1184     if ( ! XCAFDoc_ShapeTool::GetShape ( L, S ) ) continue;
1185     Standard_Boolean isComponent = aSTool->IsComponent( L );
1186     TopoDS_Shape aTopSh = S;
1187     Handle(StepRepr_RepresentationContext) Context = Styles.FindContext ( S );
1188     if ( isComponent ) {
1189       TDF_Label aTopShL = aSTool->FindShape(S, Standard_False);
1190       if (aTopShL.IsNull())
1191         continue;
1192       aTopSh = aSTool->GetShape( aTopShL );
1193       Context = Styles.FindContext ( aTopSh );
1194     }
1195     if ( Context.IsNull() )
1196         continue;
1197     
1198     // collect settings set on that label
1199     XCAFPrs_DataMapOfShapeStyle settings;
1200     TDF_LabelSequence seq;
1201     seq.Append ( L );
1202     XCAFDoc_ShapeTool::GetSubShapes ( L, seq );
1203     Standard_Boolean isVisible = Standard_True;
1204     for ( Standard_Integer j = 1; j <= seq.Length(); j++ ) {
1205       TDF_Label lab = seq.Value(j);
1206       XCAFPrs_Style style;
1207       Quantity_Color C;
1208       if ( lab == L ) {
1209         // check for invisible status of object on label
1210         if ( !CTool->IsVisible( lab ) ) {
1211           isVisible = Standard_False;
1212           style.SetVisibility( Standard_False );
1213         }
1214       }
1215       if ( CTool->GetColor ( lab, XCAFDoc_ColorGen, C ) ) {
1216         style.SetColorCurv ( C );
1217         style.SetColorSurf ( C );
1218       }
1219       if ( CTool->GetColor ( lab, XCAFDoc_ColorSurf, C ) )
1220         style.SetColorSurf ( C );
1221       if ( CTool->GetColor ( lab, XCAFDoc_ColorCurv, C ) )
1222         style.SetColorCurv ( C );
1223       
1224       // commented, cause we are need to take reference from 
1225 //       if ( isComponent && lab == L && !isVisible)
1226 //         if ( !style.IsSetColorSurf() && !style.IsSetColorCurv() ) {
1227 //           getFatherColor ( L, CTool, style);
1228 //         }
1229       if ( ! style.IsSetColorCurv() && ! style.IsSetColorSurf() && isVisible ) continue;
1230
1231       TopoDS_Shape sub = XCAFDoc_ShapeTool::GetShape ( lab );
1232       settings.Bind ( sub, style );
1233     }
1234     
1235     if ( settings.Extent() <=0 ) continue;
1236
1237     // iterate on subshapes and create STEP styles
1238     Handle(StepVisual_StyledItem) override;
1239     TopTools_MapOfShape Map;
1240     
1241     MakeSTEPStyles(Styles,S,settings,override,Map,myMapCompMDGPR,DPDCs,ColRGBs,CTool,0,isComponent);
1242     
1243     // create MDGPR and record it in model
1244     Handle(StepVisual_MechanicalDesignGeometricPresentationRepresentation) aMDGPR;
1245
1246     if (!isComponent) {
1247       if ( myMapCompMDGPR.IsBound( aTopSh )) {
1248 #ifdef OCCT_DEBUG
1249         cerr << "Error: Current Top-Level shape have MDGPR already " << endl;
1250 #endif
1251       }
1252       Styles.CreateMDGPR ( Context, aMDGPR );
1253       if (!aMDGPR.IsNull())
1254         myMapCompMDGPR.Bind( aTopSh, aMDGPR );
1255     }
1256     else {
1257       // create SDR and add to model.
1258       const Handle(XSControl_TransferWriter) &TW = WS->TransferWriter();
1259       const Handle(Transfer_FinderProcess) &FP = TW->FinderProcess();
1260       Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, S );
1261       Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1262       if ( FP->FindTypedTransient(mapper, 
1263                                   STANDARD_TYPE(StepShape_ContextDependentShapeRepresentation),
1264                                   CDSR) ) {
1265         // create SDR for NAUO
1266         Handle(StepRepr_ProductDefinitionShape) nullPDS; // important to be NULL
1267         Styles.CreateNAUOSRD( Context, CDSR, nullPDS );
1268         
1269         // search for MDGPR of the component top-level shape
1270         if ( myMapCompMDGPR.IsBound( aTopSh )) {
1271           aMDGPR = Handle(StepVisual_MechanicalDesignGeometricPresentationRepresentation)::DownCast( myMapCompMDGPR.Find( aTopSh ) );
1272         } else {
1273           aMDGPR = new StepVisual_MechanicalDesignGeometricPresentationRepresentation;
1274           Handle(TCollection_HAsciiString) ReprName = new TCollection_HAsciiString ( "" );
1275           aMDGPR->SetName( ReprName );
1276           aMDGPR->SetContextOfItems( Context );
1277           myMapCompMDGPR.Bind ( aTopSh, aMDGPR );
1278         }
1279         Handle(StepRepr_HArray1OfRepresentationItem) oldItems = aMDGPR->Items();
1280         Standard_Integer oldLengthlen = 0;
1281         if (!oldItems.IsNull())
1282           oldLengthlen = oldItems->Length();
1283         const Standard_Integer nbIt = oldLengthlen + Styles.NbStyles();
1284         if(!nbIt)
1285           continue;
1286         Handle(StepRepr_HArray1OfRepresentationItem) newItems =
1287           new StepRepr_HArray1OfRepresentationItem(1, nbIt);
1288         Standard_Integer si;
1289         Standard_Integer el = 1;
1290         for ( si=1; si <= oldLengthlen; si++ )
1291           newItems->SetValue( el++, oldItems->Value( si ) );
1292         for ( si=1; si <= Styles.NbStyles(); si++ ) {
1293           newItems->SetValue( el++, Styles.Style(si));
1294         }
1295        
1296         if (newItems->Length() > 0)
1297           aMDGPR->SetItems( newItems );
1298       } //end of work with CDSR
1299     }
1300     if ( !isVisible ) {
1301     // create invisibility item and refer for stiledItem
1302       Handle(StepVisual_Invisibility) Invsblt = new StepVisual_Invisibility();
1303       Handle(StepVisual_HArray1OfInvisibleItem) HInvsblItm = 
1304         new StepVisual_HArray1OfInvisibleItem (1,Styles.NbStyles());
1305       // put all style item into the harray
1306       for ( Standard_Integer si=1; si <= Styles.NbStyles(); si++ ) {
1307         Handle(StepRepr_RepresentationItem) styledItm = Styles.Style(si);
1308         StepVisual_InvisibleItem anInvItem;
1309         anInvItem.SetValue( styledItm );
1310         HInvsblItm->SetValue( si, anInvItem );
1311       }
1312       // set the invisibility of items
1313       Invsblt->Init( HInvsblItm );
1314       WS->Model()->AddWithRefs( Invsblt );
1315     }
1316   }
1317
1318   return Standard_True;
1319 }
1320
1321
1322 //=======================================================================
1323 //function : WriteNames
1324 //purpose  :
1325 //=======================================================================
1326
1327 Standard_Boolean STEPCAFControl_Writer::WriteNames (const Handle(XSControl_WorkSession) &WS,
1328                                                     const TDF_LabelSequence &labels) const
1329 {
1330   if ( labels.Length() <=0 ) return Standard_False;
1331
1332   // get working data
1333   const Handle(XSControl_TransferWriter) &TW = WS->TransferWriter();
1334   const Handle(Transfer_FinderProcess) &FP = TW->FinderProcess();
1335
1336   // Iterate on requested shapes
1337   for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
1338     TDF_Label L = labels.Value(i);
1339
1340     // get name
1341     Handle(TCollection_HAsciiString) hName = new TCollection_HAsciiString;
1342     if ( ! GetLabelName (L, hName) ) continue;
1343 //    Handle(TDataStd_Name) N;
1344 //    if ( ! L.FindAttribute ( TDataStd_Name::GetID(), N ) ) continue;
1345 //    TCollection_ExtendedString name = N->Get();
1346 //    if ( name.Length() <=0 ) continue;
1347
1348     // find target STEP entity for the current shape
1349 //    TopoDS_Shape S;
1350 //    if ( ! XCAFDoc_ShapeTool::GetShape ( L, S ) ) continue;
1351     if ( ! myLabels.IsBound ( L ) ) continue; // not recorded as translated, skip
1352     TopoDS_Shape S = myLabels.Find ( L );
1353
1354     Handle(StepShape_ShapeDefinitionRepresentation) SDR;
1355     Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, S );
1356     if ( ! FP->FindTypedTransient ( mapper, STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation), SDR ) ) {
1357 #ifdef OCCT_DEBUG
1358       cout << "Warning: Cannot find SDR for " << S.TShape()->DynamicType()->Name() << endl;
1359 #endif
1360       continue;
1361     }
1362
1363     // set the name to the PRODUCT
1364     Handle(StepRepr_PropertyDefinition) PropD = SDR->Definition().PropertyDefinition();
1365     if ( PropD.IsNull() ) continue;
1366     Handle(StepBasic_ProductDefinition) PD = PropD->Definition().ProductDefinition();
1367     if ( PD.IsNull() ) continue;
1368     Handle(StepBasic_Product) Prod = PD->Formation()->OfProduct();
1369
1370     Prod->SetId ( hName );
1371     Prod->SetName ( hName );
1372
1373     // write names for components of assemblies
1374     if ( XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1375       TDF_LabelSequence seq;
1376       XCAFDoc_ShapeTool::GetComponents ( L, seq );
1377       for (Standard_Integer k=1; k <= seq.Length(); k++) {
1378         TDF_Label lab = seq(k);
1379
1380         // get shape with correct location
1381         TDF_Label Lref;
1382         if ( ! XCAFDoc_ShapeTool::GetReferredShape ( lab, Lref ) || 
1383              ! myLabels.IsBound ( Lref ) ) continue;
1384         S = myLabels.Find ( Lref );
1385         S.Move ( XCAFDoc_ShapeTool::GetLocation ( lab ) );
1386         
1387         hName = new TCollection_HAsciiString;
1388         if ( ! GetLabelName (lab, hName) ) continue;
1389         
1390         // find the target CDSR corresponding to a shape
1391         mapper = TransferBRep::ShapeMapper ( FP, S );
1392         Handle(Transfer_Binder) binder = FP->Find ( mapper );
1393         Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1394         if ( ! FP->FindTypedTransient (mapper,STANDARD_TYPE(StepShape_ContextDependentShapeRepresentation), CDSR) ) 
1395           continue;
1396         Handle(StepRepr_ProductDefinitionShape) PDS = CDSR->RepresentedProductRelation();
1397         Handle(StepBasic_ProductDefinitionRelationship) NAUO = PDS->Definition().ProductDefinitionRelationship();
1398         if ( ! NAUO.IsNull() ) NAUO->SetName ( hName );
1399       }
1400     }
1401   }
1402
1403   return Standard_True;
1404 }
1405
1406
1407 //=======================================================================
1408 //function : WritePropsForLabel
1409 //purpose  :
1410 //=======================================================================
1411 static Standard_Boolean WritePropsForLabel(const Handle(XSControl_WorkSession) &WS,
1412                                            const Handle(XCAFDoc_ShapeTool) &aSTool,
1413                                            const STEPCAFControl_DataMapOfLabelShape &myLabels,
1414                                            const TDF_Label &L,
1415                                            const Standard_CString multi)
1416 {
1417   if(L.IsNull()) return Standard_False;
1418
1419   STEPConstruct_ValidationProps Props ( WS );
1420
1421   TopoDS_Shape S = aSTool->GetShape(L);
1422   if(S.IsNull()) return Standard_False;
1423
1424   if ( ! multi || XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1425     // write area
1426     Handle(XCAFDoc_Area) A;
1427     L.FindAttribute ( XCAFDoc_Area::GetID(), A );
1428     if ( ! A.IsNull() ) {
1429       Props.AddArea ( S, A->Get() );
1430     }
1431     // write volume
1432     Handle(XCAFDoc_Volume) V;
1433     L.FindAttribute ( XCAFDoc_Volume::GetID(), V );
1434     if ( ! V.IsNull() ) {
1435       Props.AddVolume ( S, V->Get() );
1436     }
1437   }
1438   // write centroid
1439   Handle(XCAFDoc_Centroid) C;
1440   L.FindAttribute ( XCAFDoc_Centroid::GetID(), C );
1441   if ( ! C.IsNull() ) {
1442     Props.AddCentroid ( S, C->Get() );
1443   }
1444
1445   if( XCAFDoc_ShapeTool::IsCompound(L) || XCAFDoc_ShapeTool::IsAssembly(L) ) {
1446     if(L.HasChild()) {
1447       for(Standard_Integer ich=1; ich<=L.NbChildren(); ich++) {
1448         WritePropsForLabel(WS,aSTool,myLabels,L.FindChild(ich),multi);
1449       }
1450     }
1451   }
1452
1453   return Standard_True;
1454 }
1455
1456
1457 //=======================================================================
1458 //function : WriteValProps
1459 //purpose  :
1460 //=======================================================================
1461
1462 Standard_Boolean STEPCAFControl_Writer::WriteValProps (const Handle(XSControl_WorkSession) &WS,
1463                                                        const TDF_LabelSequence &labels,
1464                                                        const Standard_CString multi) const
1465 {
1466   if ( labels.Length() <=0 ) return Standard_False;
1467
1468   // get working data
1469 //  STEPConstruct_ValidationProps Props ( WS );
1470   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( labels(1) );
1471
1472   // Iterate on requested shapes
1473   for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
1474     TDF_Label L = labels.Value(i);
1475
1476     WritePropsForLabel(WS,aSTool,myLabels,L,multi);
1477 /*    
1478     // find target STEP entity for the current shape
1479     if ( ! myLabels.IsBound ( L ) ) continue; // not recorded as translated, skip
1480     TopoDS_Shape S = myLabels.Find ( L );
1481
1482     // write area and volume (except for components in multifile mode)
1483     if ( ! multi || XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1484       Handle(XCAFDoc_Area) A;
1485       L.FindAttribute ( XCAFDoc_Area::GetID(), A );
1486       if ( ! A.IsNull() ) Props.AddArea ( S, A->Get() );
1487
1488       Handle(XCAFDoc_Volume) V;
1489       L.FindAttribute ( XCAFDoc_Volume::GetID(), V );
1490       if ( ! V.IsNull() ) Props.AddVolume ( S, V->Get() );
1491     }
1492
1493     // write centroid
1494     Handle(XCAFDoc_Centroid) C;
1495     L.FindAttribute ( XCAFDoc_Centroid::GetID(), C );
1496     if ( ! C.IsNull() ) Props.AddCentroid ( S, C->Get() );
1497
1498     // write centroid for components of assemblies
1499     if ( XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1500       TDF_LabelSequence seq;
1501       XCAFDoc_ShapeTool::GetComponents ( L, seq );
1502       for (Standard_Integer k=1; k <= seq.Length(); k++) {
1503         TDF_Label lab = seq(k);
1504
1505         // get shape with correct location
1506         TDF_Label Lref;
1507         if ( ! XCAFDoc_ShapeTool::GetReferredShape ( lab, Lref ) || 
1508              ! myLabels.IsBound ( Lref ) ) continue;
1509         TopLoc_Location Loc = XCAFDoc_ShapeTool::GetLocation ( lab );
1510         S = myLabels.Find ( Lref );
1511         S.Move ( Loc );
1512                 
1513         C.Nullify();
1514         lab.FindAttribute ( XCAFDoc_Centroid::GetID(), C );
1515         // if centroid is not assigned to an instance, 
1516         // use (shifted) centroid of original shape
1517         gp_Pnt center;
1518         if ( C.IsNull() ) {
1519           Lref.FindAttribute ( XCAFDoc_Centroid::GetID(), C );
1520           if ( C.IsNull() ) continue;
1521           center = C->Get().Transformed ( Loc.Transformation() );
1522         }
1523         else center = C->Get();
1524
1525         Props.AddCentroid ( S, center, Standard_True );
1526       }
1527     }
1528 */
1529   }
1530
1531   return Standard_True;
1532 }
1533
1534
1535 //=======================================================================
1536 //function : WriteLayers
1537 //purpose  : 
1538 //=======================================================================
1539
1540 Standard_Boolean STEPCAFControl_Writer::WriteLayers (const Handle(XSControl_WorkSession) &WS,
1541                                                      const TDF_LabelSequence  &labels ) const
1542 {
1543   
1544   if ( labels.Length() <=0 ) return Standard_False;
1545
1546   // get working data
1547   const Handle(Interface_InterfaceModel) &Model = WS->Model();
1548   const Handle(XSControl_TransferWriter) &TW = WS->TransferWriter();
1549   const Handle(Transfer_FinderProcess) &FP = TW->FinderProcess();
1550   Handle(XCAFDoc_LayerTool) LTool = XCAFDoc_DocumentTool::LayerTool( labels(1) );
1551   if (LTool.IsNull() ) return Standard_False;
1552
1553   TDF_LabelSequence LayerLS;
1554   LTool->GetLayerLabels(LayerLS);
1555   if ( LayerLS.Length() <=0 ) return Standard_False;
1556
1557   // Iterate on requested layers and for each layer take set of shapes.
1558   for ( Standard_Integer i=1; i <= LayerLS.Length(); i++ ) {
1559     TDF_Label L = LayerLS.Value(i);
1560     
1561     // get labels of shapes in that layer
1562     TDF_LabelSequence ShapeLs;
1563     LTool->GetShapesOfLayer(L, ShapeLs);
1564     if ( ShapeLs.Length() <=0 ) continue;
1565     
1566     // name of layer: if not set, is considered as being empty
1567     Handle(TCollection_HAsciiString) hName = new TCollection_HAsciiString;
1568     GetLabelName ( L, hName );
1569
1570     // Find target STEP entity for each shape and add to StepVisual_PresentationLayerAssignment items.
1571     TColStd_SequenceOfTransient seqRI;
1572     for ( Standard_Integer j=1; j <= ShapeLs.Length(); j++) {
1573       TDF_Label shLabel = ShapeLs.Value(j);
1574       if ( shLabel.IsNull() ) continue;
1575       
1576       // there is no way to assign layer to instance in STEP
1577       if ( XCAFDoc_ShapeTool::IsAssembly ( shLabel ) ||
1578            XCAFDoc_ShapeTool::IsReference ( shLabel ) )
1579         continue;
1580       
1581       // check that the shape is one of (uub)labels written during current transfer
1582       Standard_Integer k = 1;
1583       for ( ; k <= labels.Length(); k++ )
1584         if ( shLabel.IsDescendant ( labels(k) ) ) break;
1585       if ( k > labels.Length() ) continue;
1586
1587       // get target STEP entity
1588       TopoDS_Shape oneShape = XCAFDoc_ShapeTool::GetShape(shLabel);
1589       
1590       TopLoc_Location Loc;
1591       Standard_Integer nb = 
1592         FindEntities ( FP, oneShape, Loc, seqRI );
1593       if ( nb <=0 ) 
1594         FP->Messenger() << "Warning: Cannot find RI for " << oneShape.TShape()->DynamicType()->Name() << endl;
1595     }
1596     if ( seqRI.Length() <= 0 ) continue;
1597
1598     // analyze visibility
1599     Handle(StepVisual_PresentationLayerAssignment) StepLayerAs = new StepVisual_PresentationLayerAssignment;
1600     Handle(TCollection_HAsciiString) descr;
1601     Handle(TDataStd_UAttribute) aUAttr;
1602     Standard_Boolean isLinv = Standard_False;
1603     if (L.FindAttribute(XCAFDoc::InvisibleGUID(), aUAttr)) {
1604       descr = new TCollection_HAsciiString ("invisible");
1605 #ifdef OCCT_DEBUG
1606       FP->Messenger() << "\tLayer \"" << hName->String().ToCString() << "\" is invisible"<<endl;
1607 #endif
1608       isLinv = Standard_True;
1609     }
1610     else descr = new TCollection_HAsciiString ("visible");
1611     
1612     // create layer entity
1613     Handle(StepVisual_HArray1OfLayeredItem) HArrayOfLItem = 
1614       new StepVisual_HArray1OfLayeredItem ( 1, seqRI.Length() );
1615     for (Standard_Integer i1 = 1; i1<=seqRI.Length(); i1++) {
1616       StepVisual_LayeredItem LI;
1617       LI.SetValue ( seqRI.Value(i1) );
1618       HArrayOfLItem->SetValue( i1, LI );
1619     }
1620     StepLayerAs->Init(hName, descr, HArrayOfLItem);
1621     Model->AddWithRefs( StepLayerAs );
1622     // PTV 23.01.2003 add the invisibility AFTER adding layer into the model.
1623     // add the invisibility for the layer
1624     if (isLinv) {
1625       // Invisibility Item for containig invisible layers.
1626       Handle(StepVisual_HArray1OfInvisibleItem) HInvsblItm = new StepVisual_HArray1OfInvisibleItem (1,1);
1627       StepVisual_InvisibleItem InvIt;
1628       InvIt.SetValue( StepLayerAs );
1629       HInvsblItm->SetValue( 1, InvIt);
1630       
1631       Handle(StepVisual_Invisibility) Invsblt = new StepVisual_Invisibility();
1632       Invsblt->Init( HInvsblItm );
1633       Model->AddWithRefs( Invsblt );
1634     }
1635   }
1636   return Standard_True;
1637 }
1638
1639
1640 //=======================================================================
1641 //function : getSHUOstyle
1642 //purpose  : auxilary
1643 //=======================================================================
1644 static Standard_Boolean getSHUOstyle(const TDF_Label& aSHUOlab,
1645                                      const Handle(XCAFDoc_ColorTool)& CTool,
1646                                      XCAFPrs_Style& SHUOstyle)
1647 {
1648   Quantity_Color C;
1649   if (!CTool->IsVisible( aSHUOlab ) )
1650     SHUOstyle.SetVisibility(Standard_False);
1651   else {
1652     if ( CTool->GetColor ( aSHUOlab, XCAFDoc_ColorGen, C ) ) {
1653       SHUOstyle.SetColorCurv ( C );
1654       SHUOstyle.SetColorSurf ( C );
1655     }
1656     if ( CTool->GetColor ( aSHUOlab, XCAFDoc_ColorSurf, C ) )
1657       SHUOstyle.SetColorSurf ( C );
1658     if ( CTool->GetColor ( aSHUOlab, XCAFDoc_ColorCurv, C ) )
1659       SHUOstyle.SetColorCurv ( C );
1660   }
1661   if ( !SHUOstyle.IsSetColorCurv() && 
1662       !SHUOstyle.IsSetColorSurf() &&
1663       SHUOstyle.IsVisible() )
1664     return Standard_False;
1665   return Standard_True;
1666 }
1667
1668
1669 //=======================================================================
1670 //function : getProDefinitionOfNAUO
1671 //purpose  : auxilary
1672 //=======================================================================
1673 static Standard_Boolean getProDefinitionOfNAUO(const Handle(XSControl_WorkSession)& WS,
1674                                                const TopoDS_Shape& theShape,
1675                                                Handle(StepBasic_ProductDefinition)& PD,
1676                                                Handle(StepRepr_NextAssemblyUsageOccurrence)& NAUO,
1677                                                Standard_Boolean IsRelating)
1678 {
1679   if ( theShape.IsNull() )
1680     return Standard_False;
1681   // get CDSR
1682   const Handle(XSControl_TransferWriter) &TW = WS->TransferWriter();
1683   const Handle(Transfer_FinderProcess) &FP = TW->FinderProcess();
1684   Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1685   Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, theShape );
1686   if (!FP->FindTypedTransient(mapper, 
1687                               STANDARD_TYPE(StepShape_ContextDependentShapeRepresentation),
1688                               CDSR))
1689     return Standard_False;
1690   // get PDS of NAUO
1691   Handle(StepRepr_ProductDefinitionShape) PDS = CDSR->RepresentedProductRelation();
1692   if (PDS.IsNull())
1693     return Standard_False;
1694   // get the NAUO entity
1695   Interface_Graph aGraph = WS->HGraph()->Graph();
1696   Interface_EntityIterator subs = aGraph.Shareds(PDS);
1697   for ( subs.Start(); subs.More(); subs.Next() ) {
1698     if (!subs.Value()->IsKind(STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence)))
1699       continue;
1700     NAUO = Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subs.Value());
1701     break;
1702   }
1703   if ( NAUO.IsNull() )
1704     return Standard_False;
1705   // get Relatinf or Related product definition
1706   if ( !IsRelating )
1707     PD = NAUO->RelatedProductDefinition();
1708   else
1709     PD = NAUO->RelatingProductDefinition();
1710   if ( PD.IsNull() )
1711     return Standard_False;
1712   return Standard_True;
1713 }
1714
1715
1716 //=======================================================================
1717 //function : writeSHUO
1718 //purpose  : auxilary
1719 //=======================================================================
1720 static Standard_Boolean writeSHUO (const Handle(XCAFDoc_GraphNode)& theSHUO,
1721                                    const Handle(XCAFDoc_ShapeTool)& theSTool,
1722                                    const Handle(XSControl_WorkSession)& WS,
1723                                    Handle(StepRepr_SpecifiedHigherUsageOccurrence)& theTopSHUO,
1724                                    TopoDS_Shape& NAUOShape,
1725                                    Handle(StepBasic_ProductDefinition)& theRelatingPD,
1726                                    Standard_Boolean& isDeepest)
1727 {
1728   // set the ProductDefinitionRelationship descriptin information as empty strings.
1729   Handle(TCollection_HAsciiString) EmptyString = new TCollection_HAsciiString("");
1730   
1731   TDF_LabelSequence aNextUsageLabs;
1732   theSTool->GetSHUONextUsage( theSHUO->Label(), aNextUsageLabs );
1733   Handle(XCAFDoc_GraphNode) NuSHUO;
1734   if ( theTopSHUO.IsNull() ) {
1735     // the top SHUO
1736     if (aNextUsageLabs.Length() < 1)
1737       return Standard_False;
1738     theSTool->GetSHUO( aNextUsageLabs.Value(1), NuSHUO );
1739     if (NuSHUO.IsNull())
1740       return Standard_False;
1741     // get relating product definition
1742     TopoDS_Shape aTopCompShape = theSTool->GetShape( theSHUO->Label().Father() ); 
1743     Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO;
1744     if (!getProDefinitionOfNAUO( WS, aTopCompShape,
1745                                  theRelatingPD, UUNAUO, Standard_True ))
1746       return Standard_False;
1747     // get related product definition
1748     TopoDS_Shape aNUShape = theSTool->GetShape( NuSHUO->Label().Father() );
1749     Handle(StepBasic_ProductDefinition) aRelatedPD;
1750     Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO;
1751     if (!getProDefinitionOfNAUO( WS, aNUShape,
1752                                  aRelatedPD, NUNAUO, Standard_False ))
1753       return Standard_False;
1754     
1755     theTopSHUO = new StepRepr_SpecifiedHigherUsageOccurrence;
1756     // create deepest shuo EmptyString
1757     theTopSHUO->Init(/*id*/EmptyString, /*name*/EmptyString,
1758                      /*no description*/Standard_False,/*description*/EmptyString,
1759                      theRelatingPD, aRelatedPD,
1760                      /*no ACURefDesignator*/Standard_False,/*ACURefDesignator*/EmptyString,
1761                      /*upper_usage*/UUNAUO, /*next_usage*/NUNAUO);
1762     // write the other SHUO.
1763     if(!writeSHUO( NuSHUO, theSTool, WS, theTopSHUO, NAUOShape, theRelatingPD, isDeepest )) {
1764       theTopSHUO.Nullify();
1765       return Standard_False;
1766     }
1767     
1768     return Standard_True;
1769   }
1770 //   Handle(XCAFDoc_GraphNode) NuSHUO;
1771   if ( aNextUsageLabs.Length() > 0) {
1772     // store SHUO recursive
1773 #ifdef OCCT_DEBUG
1774     if ( aNextUsageLabs.Length() > 1 )
1775       cout << "Warning: store only one next_usage of current SHUO"  << endl;
1776 #endif    
1777     theSTool->GetSHUO( aNextUsageLabs.Value(1), NuSHUO );
1778     Handle(StepRepr_SpecifiedHigherUsageOccurrence) aNUEntSHUO =
1779       new StepRepr_SpecifiedHigherUsageOccurrence;
1780     if (!writeSHUO( NuSHUO, theSTool, WS, aNUEntSHUO, NAUOShape, theRelatingPD, isDeepest ))
1781       return Standard_False;
1782     
1783     // store the deepest SHUO to the dociment
1784     TopoDS_Shape aNUSh, aUUSh;
1785     aNUSh = theSTool->GetShape( NuSHUO->Label().Father() );
1786     aUUSh = theSTool->GetShape( theSHUO->Label().Father() );
1787     // get relating PD with upper_usage and related PD with next_usage
1788     Handle(StepBasic_ProductDefinition) nullPD;// no need to use,case have shared <theRelatingPD>
1789     Handle(StepBasic_ProductDefinition) aRelatedPD;
1790     Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO, NUNAUO;
1791     if (!getProDefinitionOfNAUO( WS, aUUSh, nullPD, UUNAUO, Standard_True ) ||
1792         !getProDefinitionOfNAUO( WS, aNUSh, aRelatedPD, NUNAUO, Standard_False )) {
1793 #ifdef OCCT_DEBUG
1794       cout << "Warning: cannot get related or relating PD" << endl;
1795 #endif
1796       return Standard_False;
1797     }
1798     aNUEntSHUO->Init(/*id*/EmptyString, /*name*/EmptyString,
1799                      /*no description*/Standard_False,/*description*/EmptyString,
1800                      theRelatingPD, aRelatedPD,
1801                      /*no ACURefDesignator*/Standard_False,/*ACURefDesignator*/EmptyString,
1802                      /*upper_usage*/theTopSHUO, /*next_usage*/NUNAUO);
1803     if ( isDeepest ) {
1804       isDeepest = Standard_False;
1805     }
1806     WS->Model()->AddWithRefs ( aNUEntSHUO );
1807     return Standard_True;
1808   } // end of recurse storing
1809     
1810   // get shape 
1811   TDF_Label aShapeL = theSHUO->Label().Father();
1812   NAUOShape = theSTool->GetShape( aShapeL );
1813   // return to the deepest level from SHUO shape level
1814   // it is because SHUO is attribute on deep level and shape level.
1815   isDeepest = Standard_True;
1816   return Standard_True;
1817 }
1818
1819
1820 //=======================================================================
1821 //function : createSHUOStyledItem
1822 //purpose  : auxilary
1823 //=======================================================================
1824 static Standard_Boolean createSHUOStyledItem (const XCAFPrs_Style& style,
1825                                               const Handle(StepRepr_ProductDefinitionShape)& PDS,
1826                                               const Handle(XSControl_WorkSession) &WS,
1827                                               const TopoDS_Shape& Sh,
1828                                               const Handle(XCAFDoc_ShapeTool)& STool,
1829                                               MoniTool_DataMapOfShapeTransient& myMapCompMDGPR)
1830 {
1831   // create styled item for the indicated SHUO and store to the model
1832   STEPConstruct_Styles Styles( WS );
1833   // translate colors to STEP
1834   Handle(StepVisual_Colour) surfColor, curvColor;
1835   if ( style.IsSetColorSurf() )
1836     surfColor = Styles.EncodeColor ( style.GetColorSurf() );
1837   if ( style.IsSetColorCurv() )
1838     curvColor = Styles.EncodeColor ( style.GetColorCurv() );
1839   Standard_Boolean isComponent = Standard_True;// cause need to get PSBC
1840   Handle(StepRepr_RepresentationItem) item;
1841   // set default color for invisible SHUO.
1842   Standard_Boolean isSetDefaultColor = Standard_False;
1843   if (surfColor.IsNull() && curvColor.IsNull() && !style.IsVisible() ) {
1844     surfColor = Styles.EncodeColor ( Quantity_Color( 1, 1, 1, Quantity_TOC_RGB ) );
1845     isSetDefaultColor = Standard_True;
1846   }
1847   Handle(StepVisual_PresentationStyleAssignment) PSA =
1848     Styles.MakeColorPSA ( item, surfColor, curvColor, isComponent );
1849   Handle(StepVisual_StyledItem) override; //null styled item
1850   
1851   // find the repr item of the shape
1852   const Handle(XSControl_TransferWriter) &TW = WS->TransferWriter();
1853   const Handle(Transfer_FinderProcess) &FP = TW->FinderProcess();
1854   Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, Sh );
1855   Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1856   FP->FindTypedTransient(mapper, 
1857                          STANDARD_TYPE(StepShape_ContextDependentShapeRepresentation),
1858                          CDSR);
1859   if ( CDSR.IsNull() )
1860     return Standard_False;
1861   // find context
1862   Handle(StepRepr_RepresentationContext) Context = Styles.FindContext( Sh );
1863   TopoDS_Shape aTopSh = Sh;
1864   if (Context.IsNull()) {
1865     TDF_Label aTopShL = STool->FindShape(Sh, Standard_False);
1866     if (aTopShL.IsNull())
1867       return Standard_False;
1868     aTopSh = STool->GetShape( aTopShL );
1869     Context = Styles.FindContext ( aTopSh );
1870   }
1871   if (Context.IsNull())
1872     return Standard_False;
1873   // get representation item of the shape
1874   TopLoc_Location L;
1875   TColStd_SequenceOfTransient seqRI;
1876   FindEntities ( FP, Sh, L, seqRI );
1877 #ifdef OCCT_DEBUG
1878   if ( seqRI.Length() <=0 ) 
1879     FP->Messenger() << "Warning: Cannot find RI for " << Sh.TShape()->DynamicType()->Name() << endl;
1880 #endif
1881   item = Handle(StepRepr_RepresentationItem)::DownCast(seqRI(1));
1882   //get overridden styled item
1883   getStyledItem(Sh,STool, Styles, override,myMapCompMDGPR);
1884   
1885   // get STEP STYLED ITEM
1886   Handle(StepVisual_StyledItem) STEPstyle = Styles.AddStyle ( item, PSA, override );
1887   // create SR, SDR and all necessary references between them and ST, PDS, PSBC, GRC
1888   Styles.CreateNAUOSRD( Context, CDSR, PDS );
1889   
1890   // add step styled item of SHUO to the model
1891   // do it by additing styled item to the MDGPR
1892   if ( !aTopSh.IsNull() &&  !myMapCompMDGPR.IsBound( aTopSh ) ) {
1893     // create MDGPR and record it in model
1894 #ifdef OCCT_DEBUG
1895     cout << "Warning: " << __FILE__ << ": Create new MDGPR for SHUO instance"  << endl;
1896 #endif
1897     Handle(StepVisual_MechanicalDesignGeometricPresentationRepresentation) aMDGPR;
1898     Styles.CreateMDGPR ( Context, aMDGPR );
1899     if (!aMDGPR.IsNull())
1900       myMapCompMDGPR.Bind( aTopSh, aMDGPR );
1901   }
1902   else if ( !aTopSh.IsNull() &&  myMapCompMDGPR.IsBound( aTopSh ) ) {
1903     // get MDGPR of the top-level shape
1904     Handle(StepVisual_PresentationRepresentation) aMDGPR = 
1905       Handle(StepVisual_PresentationRepresentation)::DownCast( myMapCompMDGPR.Find( aTopSh ) );
1906     // get old styled items to not lose it
1907     Handle(StepRepr_HArray1OfRepresentationItem) oldItems = aMDGPR->Items();
1908     Standard_Integer oldLengthlen = 0;
1909     if (!oldItems.IsNull())
1910       oldLengthlen = oldItems->Length();
1911     // create new array of styled items by an olds and new one
1912     Handle(StepRepr_HArray1OfRepresentationItem) newItems =
1913       new StepRepr_HArray1OfRepresentationItem(1, oldLengthlen + 1);
1914     Standard_Integer si;
1915     Standard_Integer el = 1;
1916     for ( si=1; si <= oldLengthlen; si++ )
1917       newItems->SetValue( el++, oldItems->Value( si ) );
1918     newItems->SetValue (el++, STEPstyle);
1919     // init MDGPR be new array of styled items
1920     if (newItems->Length() > 0)
1921       aMDGPR->SetItems( newItems );
1922   }
1923   else {
1924     WS->Model()->AddWithRefs ( STEPstyle ); // add as root to the model, but it is not good
1925 #ifdef OCCT_DEBUG
1926     cout << "Warning: " << __FILE__ << ": adds styled item of SHUO as root, casue cannot find MDGPR" << endl;
1927 #endif
1928   }
1929   // create invisibility item for the styled item
1930   if ( !style.IsVisible() ) {
1931     if (isSetDefaultColor) {
1932       // try to set default color from top-level shape
1933       
1934       setDefaultInstanceColor(override, PSA);
1935     }
1936     // create invisibility item and refer for stiledItem
1937     Handle(StepVisual_Invisibility) Invsblt = new StepVisual_Invisibility();
1938     Handle(StepVisual_HArray1OfInvisibleItem) HInvsblItm = 
1939       new StepVisual_HArray1OfInvisibleItem (1,1);
1940     // put all style item into the harray
1941     StepVisual_InvisibleItem anInvItem;
1942     anInvItem.SetValue( STEPstyle );
1943     HInvsblItm->SetValue( 1, anInvItem );
1944     Invsblt->Init( HInvsblItm );
1945     WS->Model()->AddWithRefs( Invsblt );
1946   }
1947   
1948   return Standard_True;
1949 }
1950
1951
1952 //=======================================================================
1953 //function : WriteSHUOs
1954 //purpose  : 
1955 //=======================================================================
1956
1957 Standard_Boolean STEPCAFControl_Writer::WriteSHUOs (const Handle(XSControl_WorkSession) &WS,
1958                                                     const TDF_LabelSequence  &labels )
1959 {
1960   if ( labels.Length() <=0 ) return Standard_False;
1961
1962   // get working data
1963   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( labels(1) );
1964   if (CTool.IsNull() )
1965     return Standard_False;
1966   // map of transfered SHUO
1967   TColStd_MapOfTransient aMapOfMainSHUO;
1968   // Iterate on requested shapes
1969   for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
1970     TDF_Label L = labels.Value(i);
1971     if ( ! myLabels.IsBound ( L ) ) continue; // not recorded as translated, skip
1972     if ( XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1973       TDF_LabelSequence seq;
1974       XCAFDoc_ShapeTool::GetComponents ( L, seq );
1975       // iterates on components of assembly
1976       for (Standard_Integer k=1; k <= seq.Length(); k++) {
1977         TDF_Label lab = seq(k);
1978         TDF_AttributeSequence anAttrSeq;
1979         CTool->ShapeTool()->GetAllComponentSHUO( lab, anAttrSeq );
1980         // work with SHUO
1981         for (Standard_Integer j = 1; j <= anAttrSeq.Length(); j++) {
1982           Handle(XCAFDoc_GraphNode) aSHUO = 
1983             Handle(XCAFDoc_GraphNode)::DownCast(anAttrSeq.Value( j ));
1984           // take label of SHUO
1985           TDF_Label aSHUOlab = aSHUO->Label();
1986           TDF_LabelSequence aUpLabels;
1987           // check is it SHUO of upper_usage
1988           CTool->ShapeTool()->GetSHUOUpperUsage( aSHUOlab, aUpLabels );
1989           if ( aUpLabels.Length() > 0 )
1990             continue; // transfer only main SHUO
1991           if ( aMapOfMainSHUO.Contains( aSHUO ) )
1992             continue; // do not try to transfer SHUO twice
1993           aMapOfMainSHUO.Add( aSHUO );
1994           // check if it is styled SHUO
1995           XCAFPrs_Style SHUOstyle;
1996           if ( !getSHUOstyle ( aSHUOlab, CTool, SHUOstyle ) ) {
1997 #ifdef OCCT_DEBUG
1998             cout << "Warning: " << __FILE__ << ": do not store SHUO without any style to the STEP model" << endl;
1999 #endif
2000             continue;
2001           }
2002           // write SHUO to the model amd then add structure type.
2003           TopoDS_Shape NAUOShape; // shape of the deepest NAUO in the SHUO structure
2004           Standard_Boolean isDeepest = Standard_False;
2005           Handle(StepRepr_SpecifiedHigherUsageOccurrence) anEntOfSHUO;
2006           Handle(StepBasic_ProductDefinition) aRelatingPD;
2007           // create the top SHUO and all other.
2008           writeSHUO( aSHUO, CTool->ShapeTool(), WS, anEntOfSHUO, NAUOShape, aRelatingPD, isDeepest );
2009           if ( anEntOfSHUO.IsNull() || NAUOShape.IsNull() ) {
2010 #ifdef OCCT_DEBUG
2011             cout << "Warning: " << __FILE__ << ": Cannot store SHUO" << endl;
2012 #endif
2013             continue;
2014           }
2015           // create new Product Definition Shape for TOP SHUO
2016 #ifdef OCCT_DEBUG
2017             cout << "Info: " << __FILE__ << ": Create NEW PDS for current SHUO " << endl;
2018 #endif
2019           Handle(StepRepr_ProductDefinitionShape) PDS = new StepRepr_ProductDefinitionShape;
2020           Handle(TCollection_HAsciiString) aPDSname = new TCollection_HAsciiString("SHUO");
2021           Handle(TCollection_HAsciiString) descrStr = new TCollection_HAsciiString("");
2022           StepRepr_CharacterizedDefinition aCharDef;
2023           aCharDef.SetValue( anEntOfSHUO );
2024           PDS->Init( aPDSname, Standard_False, descrStr, aCharDef );
2025           
2026           // create styled item for SHUO and add to the model
2027           createSHUOStyledItem ( SHUOstyle, PDS, WS, NAUOShape, CTool->ShapeTool(), myMapCompMDGPR );
2028           
2029         } // end work with SHUO
2030       } // end of an assembly components
2031     } // end of IsAssembly case
2032     // nothing to do if it is not assembly
2033     continue;
2034   } // end of iterates on indicated labels
2035   return Standard_True;
2036 }
2037
2038
2039 //=======================================================================
2040 //function : FindPDSforDGT
2041 //purpose  : auxilary: find PDS for AdvancedFace or EdgeCurve for creation
2042 //                     needed ShapeAspect in D&GT structure
2043 //=======================================================================
2044 static Standard_Boolean FindPDSforDGT(const Interface_Graph &aGraph,
2045                                       const Handle(Standard_Transient) &ent,
2046                                       Handle(StepRepr_ProductDefinitionShape) &PDS,
2047                                       Handle(StepRepr_RepresentationContext) &RC,
2048                                       Handle(StepShape_AdvancedFace) &AF,
2049                                       Handle(StepShape_EdgeCurve) &EC)
2050 {
2051   if (ent.IsNull())
2052     return Standard_False;
2053   if( !ent->IsKind(STANDARD_TYPE(StepShape_EdgeCurve)) && 
2054       !ent->IsKind(STANDARD_TYPE(StepShape_AdvancedFace)) ) 
2055     return Standard_False;
2056
2057   AF = Handle(StepShape_AdvancedFace)::DownCast(ent);
2058   if( AF.IsNull() ) {
2059     EC = Handle(StepShape_EdgeCurve)::DownCast(ent);
2060     Interface_EntityIterator subs = aGraph.Sharings(EC);
2061     for(subs.Start(); subs.More() && AF.IsNull(); subs.Next()) {
2062       Handle(StepShape_OrientedEdge) OE = Handle(StepShape_OrientedEdge)::DownCast(subs.Value());
2063       if(OE.IsNull()) continue;
2064       Interface_EntityIterator subs1 = aGraph.Sharings(OE);
2065       for(subs1.Start(); subs1.More() && AF.IsNull(); subs1.Next()) {
2066         Handle(StepShape_EdgeLoop) EL = Handle(StepShape_EdgeLoop)::DownCast(subs1.Value());
2067         if(EL.IsNull()) continue;
2068         Interface_EntityIterator subs2 = aGraph.Sharings(EL);
2069         for(subs2.Start(); subs2.More() && AF.IsNull(); subs2.Next()) {
2070           Handle(StepShape_FaceBound) FB = Handle(StepShape_FaceBound)::DownCast(subs2.Value());
2071           if(FB.IsNull()) continue;
2072           Interface_EntityIterator subs3 = aGraph.Sharings(FB);
2073           for(subs3.Start(); subs3.More() && AF.IsNull(); subs3.Next()) {
2074             AF = Handle(StepShape_AdvancedFace)::DownCast(subs3.Value());
2075           }
2076         }
2077       }
2078     }
2079   }
2080   if(AF.IsNull()) return Standard_False;
2081
2082   Interface_EntityIterator subs = aGraph.Sharings(AF);
2083   for(subs.Start(); subs.More() && PDS.IsNull(); subs.Next()) {
2084     Handle(StepShape_ConnectedFaceSet) CFS =
2085       Handle(StepShape_ConnectedFaceSet)::DownCast(subs.Value());
2086     if(CFS.IsNull()) continue;
2087     Interface_EntityIterator subs1 = aGraph.Sharings(CFS);
2088     for(subs1.Start(); subs1.More() && PDS.IsNull(); subs1.Next()) {
2089       Handle(StepRepr_RepresentationItem) RI = 
2090         Handle(StepRepr_RepresentationItem)::DownCast(subs1.Value());
2091       if(RI.IsNull()) continue;
2092       Interface_EntityIterator subs2 = aGraph.Sharings(RI);
2093       for(subs2.Start(); subs2.More() && PDS.IsNull(); subs2.Next()) {
2094         Handle(StepShape_ShapeRepresentation) SR = 
2095           Handle(StepShape_ShapeRepresentation)::DownCast(subs2.Value());
2096         if(SR.IsNull()) continue;
2097         RC = SR->ContextOfItems();
2098         Interface_EntityIterator subs3 = aGraph.Sharings(SR);
2099         for(subs3.Start(); subs3.More() && PDS.IsNull(); subs3.Next()) {
2100           Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
2101             Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs3.Value());
2102           if(SDR.IsNull()) continue;
2103           Handle(StepRepr_PropertyDefinition) PropD = SDR->Definition().PropertyDefinition();
2104           if(PropD.IsNull()) continue;
2105           PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(PropD);
2106         }
2107       }
2108     }
2109   }
2110   
2111   return Standard_True;
2112 }
2113
2114 //=======================================================================
2115 //function : FindPDS
2116 //purpose  : auxilary: find Product_definition_shape entity for given entity
2117 //=======================================================================
2118 static Handle(StepRepr_ProductDefinitionShape) FindPDS(const Interface_Graph &theGraph,
2119                                                        const Handle(Standard_Transient) &theEnt,
2120                                                        Handle(StepRepr_RepresentationContext) &theRC)
2121 {
2122   if (theEnt.IsNull())
2123     return NULL;
2124   Handle(StepRepr_ProductDefinitionShape) aPDS;
2125
2126   // try to find shape_representation in sharings
2127   Interface_EntityIterator anIter = theGraph.Sharings(theEnt);
2128   for (anIter.Start(); anIter.More() && aPDS.IsNull(); anIter.Next()) {
2129     Handle(StepShape_ShapeRepresentation) aSR = Handle(StepShape_ShapeRepresentation)::DownCast(anIter.Value());
2130     if (aSR.IsNull())
2131       continue;
2132     theRC = aSR->ContextOfItems();
2133     Interface_EntityIterator aSDRIt = theGraph.Sharings(aSR);
2134     for (aSDRIt.Start(); aSDRIt.More() && aPDS.IsNull(); aSDRIt.Next()) {
2135       Handle(StepShape_ShapeDefinitionRepresentation) aSDR =
2136         Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(aSDRIt.Value());
2137       if (aSDR.IsNull()) continue;
2138       Handle(StepRepr_PropertyDefinition) aPropD = aSDR->Definition().PropertyDefinition();
2139       if (aPropD.IsNull()) continue;
2140       aPDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(aPropD);
2141     }
2142   }
2143   if (!aPDS.IsNull())
2144     return aPDS;
2145
2146   anIter = theGraph.Sharings(theEnt);
2147   for (anIter.Start(); anIter.More(); anIter.Next()) {
2148     if (anIter.Value()->IsKind(STANDARD_TYPE(StepShape_TopologicalRepresentationItem)) ||
2149       anIter.Value()->IsKind(STANDARD_TYPE(StepGeom_GeometricRepresentationItem)))
2150     {
2151       aPDS = FindPDS(theGraph, anIter.Value(), theRC);
2152       if (!aPDS.IsNull())
2153         return aPDS;
2154     }
2155   }
2156
2157   return aPDS;
2158 }
2159
2160 //=======================================================================
2161 //function : GetUnit
2162 //purpose  : auxiliary
2163 //=======================================================================
2164 static StepBasic_Unit GetUnit(const Handle(StepRepr_RepresentationContext)& theRC,
2165                               const Standard_Boolean isAngle = Standard_False)
2166 {
2167   StepBasic_Unit aUnit;
2168   if (isAngle) {
2169     Handle(StepBasic_SiUnitAndPlaneAngleUnit) aSiPAU;
2170     Handle(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext) aCtx =
2171       Handle(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext)::DownCast(theRC);
2172     if(!aCtx.IsNull()) {
2173       for(Standard_Integer j = 1; j <= aCtx->NbUnits(); j++) {
2174         if(aCtx->UnitsValue(j)->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndPlaneAngleUnit))) {
2175           aSiPAU = Handle(StepBasic_SiUnitAndPlaneAngleUnit)::DownCast(aCtx->UnitsValue(j));
2176           break;
2177         }
2178       }
2179     }
2180     if(aSiPAU.IsNull()) {
2181       Handle(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx) aCtx1 =
2182         Handle(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx)::DownCast(theRC);
2183       if(!aCtx1.IsNull()) {
2184         for(Standard_Integer j = 1; j <= aCtx1->NbUnits(); j++) {
2185           if(aCtx1->UnitsValue(j)->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndPlaneAngleUnit))) {
2186             aSiPAU = Handle(StepBasic_SiUnitAndPlaneAngleUnit)::DownCast(aCtx1->UnitsValue(j));
2187             break;
2188           }
2189         }
2190       }
2191     }
2192     if(aSiPAU.IsNull())
2193       aSiPAU = new StepBasic_SiUnitAndPlaneAngleUnit;
2194     aUnit.SetValue(aSiPAU);
2195   }
2196   else {
2197     Handle(StepBasic_SiUnitAndLengthUnit) aSiLU;
2198     Handle(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext) aCtx =
2199       Handle(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext)::DownCast(theRC);
2200     if(!aCtx.IsNull()) {
2201       for(Standard_Integer j = 1; j <= aCtx->NbUnits(); j++) {
2202         if(aCtx->UnitsValue(j)->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndLengthUnit))) {
2203           aSiLU = Handle(StepBasic_SiUnitAndLengthUnit)::DownCast(aCtx->UnitsValue(j));
2204           break;
2205         }
2206       }
2207     }
2208     if(aSiLU.IsNull()) {
2209       Handle(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx) aCtx1 =
2210         Handle(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx)::DownCast(theRC);
2211       if(!aCtx1.IsNull()) {
2212         for(Standard_Integer j = 1; j <= aCtx1->NbUnits(); j++) {
2213           if(aCtx1->UnitsValue(j)->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndLengthUnit))) {
2214             aSiLU = Handle(StepBasic_SiUnitAndLengthUnit)::DownCast(aCtx1->UnitsValue(j));
2215             break;
2216           }
2217         }
2218       }
2219     }
2220     if(aSiLU.IsNull())
2221       aSiLU = new StepBasic_SiUnitAndLengthUnit;
2222     aUnit.SetValue(aSiLU);
2223   }
2224   return aUnit;
2225 }
2226
2227 //=======================================================================
2228 //function : CreateDimValue
2229 //purpose  : auxiliary
2230 //======================================================================
2231 static Handle(StepRepr_ReprItemAndMeasureWithUnit) CreateDimValue(const Standard_Real theValue,
2232                                                                   const StepBasic_Unit theUnit,
2233                                                                   const Handle(TCollection_HAsciiString)& theName,
2234                                                                   const Standard_CString theMeasureName,
2235                                                                   const Standard_Boolean isAngle,
2236                                                                   const Standard_Boolean isQualified = Standard_False,
2237                                                                   const Handle(StepShape_QualifiedRepresentationItem)& theQRI = NULL)
2238 {
2239   Handle(StepRepr_RepresentationItem) aReprItem = new StepRepr_RepresentationItem();
2240   aReprItem->Init(new TCollection_HAsciiString(theName));
2241   Handle(StepBasic_MeasureWithUnit) aMWU = new StepBasic_MeasureWithUnit();
2242   Handle(StepBasic_MeasureValueMember) aValueMember = new StepBasic_MeasureValueMember();
2243   aValueMember->SetName(theMeasureName);
2244   aValueMember->SetReal(theValue);
2245   aMWU->Init(aValueMember, theUnit);
2246   if (isQualified) {
2247     if (isAngle) {
2248       // Angle & with qualifiers
2249       Handle(StepRepr_ReprItemAndPlaneAngleMeasureWithUnitAndQRI) anItem = 
2250         new StepRepr_ReprItemAndPlaneAngleMeasureWithUnitAndQRI();
2251       anItem->Init(aMWU, aReprItem, theQRI);
2252       return anItem;
2253     }
2254     else {
2255       // Length & with qualifiers
2256       Handle(StepRepr_ReprItemAndLengthMeasureWithUnitAndQRI) anItem = 
2257         new StepRepr_ReprItemAndLengthMeasureWithUnitAndQRI();
2258       anItem->Init(aMWU, aReprItem, theQRI);
2259       return anItem;
2260     }
2261   }
2262   else {
2263     if (isAngle) {
2264       // Angle & without qualifiers
2265       Handle(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit) anItem = 
2266         new StepRepr_ReprItemAndPlaneAngleMeasureWithUnit();
2267       anItem->Init(aMWU, aReprItem);
2268       return anItem;
2269     }
2270     else {
2271       // Length & without qualifiers
2272       Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) anItem = 
2273         new StepRepr_ReprItemAndLengthMeasureWithUnit();
2274       anItem->Init(aMWU, aReprItem);
2275       return anItem;
2276     }
2277   }
2278 }
2279
2280 //=======================================================================
2281 //function : WriteShapeAspect
2282 //purpose  : auxiliary (write Shape_Aspect entity for given shape)
2283 //=======================================================================
2284
2285 Handle(StepRepr_ShapeAspect) STEPCAFControl_Writer::WriteShapeAspect (const Handle(XSControl_WorkSession) &WS,
2286                                                                       const TDF_Label theLabel,
2287                                                                       const TopoDS_Shape theShape,
2288                                                                       Handle(StepRepr_RepresentationContext)& theRC,
2289                                                                       Handle(StepAP242_GeometricItemSpecificUsage)& theGISU)
2290 {
2291   // Get working data
2292   const Handle(Interface_InterfaceModel) &Model = WS->Model();
2293   const Handle(XSControl_TransferWriter) &TW = WS->TransferWriter();
2294   const Handle(Transfer_FinderProcess) &FP = TW->FinderProcess();
2295   const Handle(Interface_HGraph) aHGraph = WS->HGraph();
2296   if (aHGraph.IsNull())
2297     return NULL;
2298   Interface_Graph aGraph = aHGraph->Graph();
2299
2300   TopLoc_Location aLoc;
2301   TColStd_SequenceOfTransient aSeqRI;
2302   FindEntities( FP, theShape, aLoc, aSeqRI );
2303   if ( aSeqRI.Length() <= 0 ) {
2304     FP->Messenger() << "Warning: Cannot find RI for "<<theShape.TShape()->DynamicType()->Name()<<endl;
2305     return NULL;
2306   }
2307
2308   Handle(StepRepr_ProductDefinitionShape) aPDS;
2309   Handle(StepRepr_RepresentationContext) aRC;
2310   Handle(Standard_Transient) anEnt = aSeqRI.Value(1);
2311   aPDS = FindPDS(aGraph, anEnt, aRC);
2312   if(aPDS.IsNull()) 
2313     return NULL;
2314
2315   theRC = aRC;
2316   // Shape_Aspect
2317   Handle(TCollection_HAsciiString) aName = new TCollection_HAsciiString();
2318   Handle(TDataStd_Name) aNameAttr;
2319   if (theLabel.FindAttribute(TDataStd_Name::GetID(), aNameAttr)) {
2320     aName = new TCollection_HAsciiString(TCollection_AsciiString(aNameAttr->Get(), '?'));
2321     Standard_Integer aFirstSpace = aName->Search(" ");
2322     if (aFirstSpace != -1)
2323       aName = aName->SubString(aFirstSpace + 1, aName->Length());
2324     else
2325       aName = new TCollection_HAsciiString();
2326   }
2327   Handle(TCollection_HAsciiString) aDescription = new TCollection_HAsciiString();
2328   Handle(StepRepr_ShapeAspect) aSA = new StepRepr_ShapeAspect;
2329   aSA->Init(aName, aDescription, aPDS, StepData_LTrue);
2330
2331   // Geometric_Item_Specific_Usage
2332   Handle(StepAP242_GeometricItemSpecificUsage) aGISU = new StepAP242_GeometricItemSpecificUsage();
2333   StepAP242_ItemIdentifiedRepresentationUsageDefinition aDefinition;
2334   aDefinition.SetValue(aSA);
2335   Handle(StepRepr_HArray1OfRepresentationItem) anReprItems = new StepRepr_HArray1OfRepresentationItem(1, 1);
2336   Handle(StepRepr_RepresentationItem) anIdentifiedItem = Handle(StepRepr_RepresentationItem)::DownCast(anEnt);
2337   anReprItems->SetValue(1, anIdentifiedItem);
2338   Interface_EntityIterator subs = aGraph.Sharings(aPDS);
2339   Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
2340   for (subs.Start(); subs.More() && aSDR.IsNull(); subs.Next()) {
2341     Handle(Standard_Transient) anEntity = subs.Value();
2342     aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(anEntity);
2343   }
2344   if (aSDR.IsNull())
2345     return NULL;
2346
2347   // Set entities to model
2348   aGISU->Init(aName, aDescription, aDefinition, aSDR->UsedRepresentation(), anReprItems);
2349   Model->AddWithRefs(aSA);
2350   Model->AddWithRefs(aGISU);
2351   theGISU = aGISU;
2352   return aSA;
2353 }
2354
2355 //=======================================================================
2356 //function : WritePresentation
2357 //purpose  : auxiliary (write annotation plane and presentation)
2358 //======================================================================
2359 void STEPCAFControl_Writer::WritePresentation(const Handle(XSControl_WorkSession) &WS,
2360                                               const TopoDS_Shape thePresentation,
2361                                               const Handle(TCollection_HAsciiString)& thePrsName,
2362                                               const Standard_Boolean hasSemantic,
2363                                               const Standard_Boolean hasPlane,
2364                                               const gp_Ax2 theAnnotationPlane,
2365                                               const gp_Pnt theTextPosition,
2366                                               const Handle(Standard_Transient) theDimension)
2367 {
2368   if (thePresentation.IsNull())
2369     return;
2370   // Get working data
2371   const Handle(Interface_InterfaceModel) &aModel = WS->Model();
2372
2373   // Presentation
2374   Handle(StepVisual_TessellatedGeometricSet) aGeomSet = STEPCAFControl_GDTProperty::GetTessellation(thePresentation);
2375   Handle(StepVisual_TessellatedAnnotationOccurrence) aTAO = new StepVisual_TessellatedAnnotationOccurrence();
2376   aTAO->Init(new TCollection_HAsciiString(), myGDTPrsCurveStyle, aGeomSet);
2377   StepVisual_DraughtingCalloutElement aDCElement;
2378   aDCElement.SetValue(aTAO);
2379   Handle(StepVisual_HArray1OfDraughtingCalloutElement) aTAOs = new StepVisual_HArray1OfDraughtingCalloutElement(1, 1);
2380   aTAOs->SetValue(1, aDCElement);
2381   Handle(StepVisual_DraughtingCallout) aDCallout = new StepVisual_DraughtingCallout();
2382   Handle(TCollection_HAsciiString) aPrsName = thePrsName.IsNull() ? new TCollection_HAsciiString() : thePrsName;
2383   aDCallout->Init(aPrsName, aTAOs);
2384   Handle(StepRepr_HArray1OfRepresentationItem) aDCsForDMIA = new StepRepr_HArray1OfRepresentationItem(1, 1);
2385   aDCsForDMIA->SetValue(1, aDCallout);
2386   myGDTAnnotations.Append(aDCallout);
2387   StepAP242_ItemIdentifiedRepresentationUsageDefinition aDimension;
2388   aDimension.SetValue(theDimension);
2389   Handle(TCollection_HAsciiString) aDMIAName;
2390   if (hasSemantic)
2391     aDMIAName = new TCollection_HAsciiString("PMI representation to presentation link");
2392   else
2393     aDMIAName = new TCollection_HAsciiString();
2394   Handle(StepAP242_DraughtingModelItemAssociation) aDMIA =
2395     new StepAP242_DraughtingModelItemAssociation();
2396   aDMIA->Init(aDMIAName, new TCollection_HAsciiString(), aDimension, myGDTPresentationDM, aDCsForDMIA);
2397   aModel->AddWithRefs(aDMIA);
2398
2399   if (!hasPlane)
2400     return;
2401
2402   // Annotation plane
2403   // Presentation Style
2404   Handle(StepVisual_NullStyleMember) aNullStyle = new StepVisual_NullStyleMember();
2405   aNullStyle->SetEnumText(0, ".NULL.");
2406   StepVisual_PresentationStyleSelect aStyleItem;
2407   aStyleItem.SetValue(aNullStyle);
2408   Handle(StepVisual_HArray1OfPresentationStyleSelect) aStyles = new StepVisual_HArray1OfPresentationStyleSelect(1, 1);
2409   aStyles->SetValue(1, aStyleItem);
2410   Handle(StepVisual_PresentationStyleAssignment) aPrsStyle = new StepVisual_PresentationStyleAssignment();
2411   aPrsStyle->Init(aStyles);
2412   Handle(StepVisual_HArray1OfPresentationStyleAssignment) aPrsStyles =
2413     new StepVisual_HArray1OfPresentationStyleAssignment(1, 1);
2414   aPrsStyles->SetValue(1, aPrsStyle);
2415   // Plane
2416   Handle(StepGeom_Plane) aPlane = new StepGeom_Plane();
2417   Handle(StepGeom_Axis2Placement3d) anAxis = STEPCAFControl_GDTProperty::GetAxis2Placement3D(theAnnotationPlane);
2418   // Set text position to plane origin
2419   Handle(StepGeom_CartesianPoint) aTextPos = new StepGeom_CartesianPoint();
2420   Handle(TColStd_HArray1OfReal) aCoords = new TColStd_HArray1OfReal(1, 3);
2421   for (Standard_Integer i = 1; i <= 3; i++)
2422     aCoords->SetValue(i, theTextPosition.Coord(i));
2423   aTextPos->Init(new TCollection_HAsciiString(), aCoords);
2424   anAxis->SetLocation(aTextPos);
2425   aPlane->Init(new TCollection_HAsciiString(), anAxis);
2426   // Annotation plane element
2427   StepVisual_AnnotationPlaneElement aPlaneElement;
2428   aPlaneElement.SetValue(aDCallout);
2429   Handle(StepVisual_HArray1OfAnnotationPlaneElement) aDCsForAnnPln = new StepVisual_HArray1OfAnnotationPlaneElement(1, 1);
2430   aDCsForAnnPln->SetValue(1, aPlaneElement);
2431   // Init AnnotationPlane entity
2432   Handle(StepVisual_AnnotationPlane) anAnnPlane = new StepVisual_AnnotationPlane();
2433   anAnnPlane->Init(new TCollection_HAsciiString(), aPrsStyles, aPlane, aDCsForAnnPln);
2434   myGDTAnnotations.Append(anAnnPlane);
2435   aModel->AddWithRefs(anAnnPlane);
2436 }
2437
2438 //=======================================================================
2439 //function : WriteDatumAP242
2440 //purpose  : auxiliary (write Datum entity for given shape or write all 
2441 //           necessary entities and link them to already written datum 
2442 //           in case of multiple features association)
2443 //=======================================================================
2444 Handle(StepDimTol_Datum) STEPCAFControl_Writer::WriteDatumAP242(const Handle(XSControl_WorkSession) &WS,
2445                                                                 const TDF_LabelSequence theShapeL,
2446                                                                 const TDF_Label theDatumL,
2447                                                                 const Standard_Boolean isFirstDTarget,
2448                                                                 const Handle(StepDimTol_Datum) theWrittenDatum)
2449 {
2450   // Get working data
2451   const Handle(Interface_InterfaceModel) &Model = WS->Model();
2452   const Handle(XSControl_TransferWriter) &TW = WS->TransferWriter();
2453   const Handle(Transfer_FinderProcess) &FP = TW->FinderProcess();
2454   const Handle(Interface_HGraph) aHGraph = WS->HGraph();
2455   if (aHGraph.IsNull())
2456     return NULL;
2457   Interface_Graph aGraph = aHGraph->Graph();
2458
2459   Handle(StepRepr_ShapeAspect) aSA;
2460   Handle(StepRepr_RepresentationContext) aRC;
2461   Handle(StepRepr_ProductDefinitionShape) aPDS;
2462   NCollection_Sequence<Handle(StepRepr_ShapeAspect)> aSASeq;
2463   Handle(StepAP242_GeometricItemSpecificUsage) aGISU;
2464   Standard_Integer aSANum = 0, aGISUNum = 0;
2465   // Link with datum feature
2466   for (Standard_Integer i = 1; i <= theShapeL.Length(); i++) {
2467     Handle(Standard_Transient) anEnt;
2468     TopoDS_Shape aShape;
2469     TopLoc_Location aLoc;
2470     TColStd_SequenceOfTransient aSeqRI;
2471
2472     aShape = XCAFDoc_ShapeTool::GetShape(theShapeL.Value(i));
2473     FindEntities(FP, aShape, aLoc, aSeqRI);
2474     if (aSeqRI.Length() <= 0) {
2475       FP->Messenger() << "Warning: Cannot find RI for " << aShape.TShape()->DynamicType()->Name() << endl;
2476       continue;
2477     }
2478     anEnt = aSeqRI.Value(1);
2479     aPDS = FindPDS(aGraph, anEnt, aRC);
2480     if (aPDS.IsNull())
2481       continue;
2482
2483     Handle(StepRepr_ShapeAspect) aCurrentSA = WriteShapeAspect(WS, theDatumL, aShape, aRC, aGISU);
2484     if (aCurrentSA.IsNull())
2485       continue;
2486     aSASeq.Append(aCurrentSA);
2487     aSANum = Model->Number(aCurrentSA);
2488     aGISUNum = Model->Number(aGISU);
2489   }
2490   if (aPDS.IsNull()) {
2491     // Workaround for datums without shape
2492     aPDS = myGDTCommonPDS;
2493     Interface_EntityIterator aSDRIt = aGraph.Sharings(aPDS);
2494     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
2495     for (aSDRIt.Start(); aSDRIt.More() && aSDR.IsNull(); aSDRIt.Next())
2496       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(aSDRIt.Value());
2497     if (!aSDR.IsNull()) {
2498       Handle(StepRepr_Representation) aRepr = aSDR->UsedRepresentation();
2499       if (!aRepr.IsNull())
2500         aRC = aRepr->ContextOfItems();
2501     }
2502   }
2503
2504
2505   // Find if datum has datum targets and get common datum attributes
2506   Handle(XCAFDoc_Datum) aDatumAttr;
2507   if (!theDatumL.FindAttribute(XCAFDoc_Datum::GetID(), aDatumAttr)) 
2508     return NULL;
2509   Handle(XCAFDimTolObjects_DatumObject) anObject = aDatumAttr->GetObject();
2510   if (anObject.IsNull())
2511     return NULL;
2512   Standard_Boolean isSimpleDatum = !anObject->IsDatumTarget();
2513   Handle(TCollection_HAsciiString) anIdentifier = anObject->GetName();
2514   Handle(TCollection_HAsciiString) aTargetId = (anObject->GetDatumTargetNumber() == 0 ? 
2515     new TCollection_HAsciiString() : new TCollection_HAsciiString(anObject->GetDatumTargetNumber()));
2516
2517   // If datum type is area, but there is no area in object, write as simple datum
2518   if (anObject->GetDatumTargetType() == XCAFDimTolObjects_DatumTargetType_Area &&
2519     anObject->GetDatumTarget().IsNull())
2520     isSimpleDatum = Standard_True;
2521
2522   // Simple datum
2523   if (isSimpleDatum) {
2524     if (aSASeq.Length() == 0) {
2525       // Create empty datum with name and presentation only
2526       Handle(StepDimTol_DatumFeature) aDF = new StepDimTol_DatumFeature();
2527       aDF->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), aPDS, StepData_LTrue);
2528       aSA = aDF;
2529       Model->AddWithRefs(aDF);
2530     }
2531     else if (aSASeq.Length() == 1) {
2532       Handle(StepDimTol_DatumFeature) aDF = new StepDimTol_DatumFeature();
2533       aDF->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), aPDS, StepData_LTrue);
2534       Model->ReplaceEntity(aSANum, aDF);
2535       aSA = aDF;
2536       StepAP242_ItemIdentifiedRepresentationUsageDefinition aDefinition;
2537       aDefinition.SetValue(aDF);
2538       aGISU->SetDefinition(aDefinition);
2539       Model->ReplaceEntity(aGISUNum, aGISU);
2540     }
2541     else if (aSASeq.Length() > 1) {
2542       Handle(StepRepr_CompShAspAndDatumFeatAndShAsp) aDF = new StepRepr_CompShAspAndDatumFeatAndShAsp();
2543       aDF->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), aPDS, StepData_LTrue);
2544       for (Standard_Integer i = 1; i <= aSASeq.Length(); i++) {
2545         Handle(StepRepr_ShapeAspectRelationship) aSAR = new StepRepr_ShapeAspectRelationship();
2546         aSAR->Init(new TCollection_HAsciiString(), Standard_False, new TCollection_HAsciiString(), aDF, aSASeq.Value(i));
2547         Model->AddWithRefs(aSAR);
2548       }
2549       aSA = aDF;
2550       Model->AddWithRefs(aDF);
2551     }
2552   }
2553   // Datum with datum targets
2554   else {
2555     XCAFDimTolObjects_DatumTargetType aDatumType = anObject->GetDatumTargetType();
2556     Handle(StepDimTol_DatumTarget) aDatumTarget;
2557     // Note: the given way to write such datum type may be incorrect (too little information)
2558     if (aDatumType == XCAFDimTolObjects_DatumTargetType_Area) {
2559       TopoDS_Shape aDTShape = anObject->GetDatumTarget();
2560       Handle(StepAP242_GeometricItemSpecificUsage) anAreaGISU;
2561       Handle(StepRepr_ShapeAspect) anAreaSA = WriteShapeAspect(WS, theDatumL, aDTShape, aRC, anAreaGISU);
2562       aSANum = Model->Number(anAreaSA);
2563       aGISUNum = Model->Number(anAreaGISU);
2564       Handle(StepDimTol_DatumTarget) aDT = new StepDimTol_DatumTarget();
2565       aDT->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString("area"), anAreaSA->OfShape(),
2566         StepData_LTrue, aTargetId);
2567       Model->ReplaceEntity(aSANum, aDT);
2568       StepAP242_ItemIdentifiedRepresentationUsageDefinition aDefinition;
2569       aDefinition.SetValue(aDT);
2570       anAreaGISU->SetDefinition(aDefinition);
2571       Model->ReplaceEntity(aGISUNum, anAreaGISU);
2572     }
2573     else {
2574       Handle(StepDimTol_PlacedDatumTargetFeature) aPDTF = new StepDimTol_PlacedDatumTargetFeature();
2575       aPDTF->Init(new TCollection_HAsciiString(), STEPCAFControl_GDTProperty::GetDatumTargetName(aDatumType),
2576         aPDS, StepData_LTrue, aTargetId);
2577       Model->AddWithRefs(aPDTF);
2578       aDatumTarget = aPDTF;
2579       // Datum targets
2580       Handle(StepRepr_PropertyDefinition) aPD = new StepRepr_PropertyDefinition();
2581       StepRepr_CharacterizedDefinition aCDefinition;
2582       aCDefinition.SetValue(aPDTF);
2583       aPD->Init(new TCollection_HAsciiString(), Standard_False, NULL, aCDefinition);
2584       if (anObject->HasDatumTargetParams()) {
2585         // write all parameters of datum target
2586         Handle(StepShape_ShapeRepresentationWithParameters) aSRWP = new StepShape_ShapeRepresentationWithParameters();
2587         // Common for all datum targets
2588         StepBasic_Unit aUnit = GetUnit(aRC);
2589         gp_Ax2 aDTAxis = anObject->GetDatumTargetAxis();
2590         Handle(StepGeom_Axis2Placement3d) anA2P3D =
2591           STEPCAFControl_GDTProperty::GetAxis2Placement3D(aDTAxis);
2592         anA2P3D->SetName(new TCollection_HAsciiString("orientation"));
2593         Handle(StepRepr_HArray1OfRepresentationItem) anItems;
2594         // Process each datum target type
2595         if (aDatumType == XCAFDimTolObjects_DatumTargetType_Point) {
2596           anItems = new StepRepr_HArray1OfRepresentationItem(1, 1);
2597         }
2598         else  {
2599           Handle(TCollection_HAsciiString) aTargetValueName;
2600           if (aDatumType == XCAFDimTolObjects_DatumTargetType_Line) {
2601             anItems = new StepRepr_HArray1OfRepresentationItem(1, 2);
2602             aTargetValueName = new TCollection_HAsciiString("target length");
2603           }
2604           else if (aDatumType == XCAFDimTolObjects_DatumTargetType_Rectangle) {
2605             anItems = new StepRepr_HArray1OfRepresentationItem(1, 3);
2606             aTargetValueName = new TCollection_HAsciiString("target length");
2607             // Additional value
2608             Handle(StepRepr_ReprItemAndMeasureWithUnit) aTargetValue = CreateDimValue(anObject->GetDatumTargetWidth(),
2609               aUnit, new TCollection_HAsciiString("target width"), "POSITIVE_LENGTH_MEASURE", Standard_False);
2610             anItems->SetValue(2, aTargetValue);
2611             Model->AddWithRefs(aTargetValue);
2612           }
2613           else if (aDatumType == XCAFDimTolObjects_DatumTargetType_Circle) {
2614             anItems = new StepRepr_HArray1OfRepresentationItem(1, 2);
2615             aTargetValueName = new TCollection_HAsciiString("target diameter");
2616           }
2617           // Value
2618           Handle(StepRepr_ReprItemAndMeasureWithUnit) aTargetValue = CreateDimValue(anObject->GetDatumTargetLength(),
2619             aUnit, aTargetValueName, "POSITIVE_LENGTH_MEASURE", Standard_False);
2620           anItems->SetValue(1, aTargetValue);
2621           Model->AddWithRefs(aTargetValue);
2622         }
2623         anItems->SetValue(anItems->Length(), anA2P3D);
2624         aSRWP->Init(new TCollection_HAsciiString(), anItems, aRC);
2625         // Create and write auxiliary entities
2626         Handle(StepShape_ShapeDefinitionRepresentation) aSDR = new StepShape_ShapeDefinitionRepresentation();
2627         StepRepr_RepresentedDefinition aRDefinition;
2628         aRDefinition.SetValue(aPD);
2629         aSDR->Init(aRDefinition, aSRWP);
2630         Model->AddWithRefs(aPD);
2631         Model->AddWithRefs(aSRWP);
2632         Model->AddWithRefs(aSDR);
2633       }
2634     }
2635     // Link datum target to datum feature
2636     // if aSASeq.Length() == 0 nothing to do
2637     if (aSASeq.Length() == 1) {
2638       Handle(StepRepr_FeatureForDatumTargetRelationship) aFFDTR = new StepRepr_FeatureForDatumTargetRelationship();
2639       aFFDTR->Init(new TCollection_HAsciiString(), Standard_False, NULL, aSASeq.Value(1), aDatumTarget);
2640       Model->AddWithRefs(aFFDTR);
2641     }
2642     else if (aSASeq.Length() > 1) {
2643       Handle(StepRepr_CompositeShapeAspect) aCompSA = new StepRepr_CompositeShapeAspect();
2644       aCompSA->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), aPDS, aSASeq.Value(1)->ProductDefinitional());
2645       for (Standard_Integer i = 1; i <= aSASeq.Length(); i++) {
2646         Handle(StepRepr_ShapeAspectRelationship) aSAR = new StepRepr_ShapeAspectRelationship();
2647         aSAR->Init(new TCollection_HAsciiString(), Standard_False, new TCollection_HAsciiString(), aCompSA, aSASeq.Value(i));
2648         Model->AddWithRefs(aSAR);
2649       }
2650       Handle(StepRepr_FeatureForDatumTargetRelationship) aFFDTR = new StepRepr_FeatureForDatumTargetRelationship();
2651       aFFDTR->Init(new TCollection_HAsciiString(), Standard_False, NULL, aCompSA, aDatumTarget);
2652       Model->AddWithRefs(aFFDTR);
2653     }
2654     aSA = aDatumTarget;
2655   }
2656
2657   // Datum
2658   Handle(StepDimTol_Datum) aDatum = theWrittenDatum;
2659   if (isFirstDTarget) {
2660     aDatum = new StepDimTol_Datum();
2661     aDatum->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), aPDS, StepData_LFalse, anIdentifier);
2662     Model->AddWithRefs(aDatum);
2663   }
2664
2665   // Shape_Aspect_Relationship
2666   if (!aSA.IsNull()) {
2667     Handle(StepRepr_ShapeAspectRelationship) aSAR = new StepRepr_ShapeAspectRelationship();
2668     aSAR->Init(new TCollection_HAsciiString(), Standard_False, NULL, aSA, aDatum);
2669     Model->AddWithRefs(aSAR);
2670   }
2671
2672   //Annotation plane and Presentation
2673   WritePresentation(WS, anObject->GetPresentation(), anObject->GetPresentationName(), Standard_True, anObject->HasPlane(),
2674     anObject->GetPlane(), anObject->GetPointTextAttach(), aSA);
2675
2676   return aDatum;
2677 }
2678
2679 //=======================================================================
2680 //function : WriteDimValues
2681 //purpose  : auxiliary (write all data for given dimension: values, 
2682 //           qualifiers, modifiers, orientation and tolerance class)
2683 //======================================================================
2684 static void WriteDimValues(const Handle(XSControl_WorkSession) &WS,
2685                            const Handle(XCAFDimTolObjects_DimensionObject) theObject,
2686                            const Handle(StepRepr_RepresentationContext) theRC,
2687                            const StepShape_DimensionalCharacteristic theDimension)
2688 {
2689   // Get working data
2690   const Handle(Interface_InterfaceModel) &aModel = WS->Model();
2691   XCAFDimTolObjects_DimensionModifiersSequence aModifiers = theObject->GetModifiers();
2692   Handle(Standard_Transient) aDim = theDimension.Value();
2693   Standard_Boolean isAngle = aDim->IsKind(STANDARD_TYPE(StepShape_AngularLocation)) ||
2694                              aDim->IsKind(STANDARD_TYPE(StepShape_AngularSize));
2695
2696   // Unit
2697   StepBasic_Unit aUnit = GetUnit(theRC, isAngle);
2698   Standard_CString aMeasureName;
2699   if (isAngle)
2700     aMeasureName = "POSITIVE_PLANE_ANGLE_MEASURE";
2701   else
2702     aMeasureName = "POSITIVE_LENGTH_MEASURE";
2703
2704   // Values
2705   Handle(StepRepr_HArray1OfRepresentationItem) aValues;
2706   Standard_Integer aNbItems = 1, aValIt = 1;
2707   if (theObject->IsDimWithRange())
2708     aNbItems += 2;
2709   if (aModifiers.Length() > 0)
2710     aNbItems++;
2711   if (theObject->GetType() == XCAFDimTolObjects_DimensionType_Location_Oriented)
2712     aNbItems++;
2713   aNbItems += theObject->NbDescriptions();
2714   aValues = new StepRepr_HArray1OfRepresentationItem(1, aNbItems);
2715
2716   // Nominal value
2717   Standard_Real aNominal = theObject->GetValue();
2718   Standard_Integer aLeftNbDigits, aRightNbDigits;
2719   theObject->GetNbOfDecimalPlaces(aLeftNbDigits, aRightNbDigits);
2720   Standard_Integer aNbQualifiers = 0;
2721   if (theObject->HasQualifier() && !isAngle)
2722     aNbQualifiers++;
2723   if (aLeftNbDigits > 0 || aRightNbDigits > 0)
2724     aNbQualifiers++;
2725   // With qualifiers
2726   if (aNbQualifiers > 0) {
2727     Handle(StepShape_QualifiedRepresentationItem) aQRI = new StepShape_QualifiedRepresentationItem();
2728     Handle(StepShape_HArray1OfValueQualifier) aQualifiers = new StepShape_HArray1OfValueQualifier(1, aNbQualifiers);
2729     // Type qualifier
2730     if (theObject->HasQualifier() && !isAngle) {
2731       StepShape_ValueQualifier anItem;
2732       Handle(StepShape_TypeQualifier) aType = new StepShape_TypeQualifier();
2733       XCAFDimTolObjects_DimensionQualifier aQualifier = theObject->GetQualifier();
2734       aType->Init(STEPCAFControl_GDTProperty::GetDimQualifierName(aQualifier));
2735       aModel->AddWithRefs(aType);
2736       anItem.SetValue(aType);
2737       aQualifiers->SetValue(1, anItem);
2738     }
2739     // Number of decimal places
2740     if (aLeftNbDigits > 0 || aRightNbDigits > 0) {
2741       StepShape_ValueQualifier anItem;
2742       Handle(StepShape_ValueFormatTypeQualifier) aType = new StepShape_ValueFormatTypeQualifier();
2743       Handle(TCollection_HAsciiString) aFormatType = new TCollection_HAsciiString("NR2 ");
2744       aFormatType->AssignCat(new TCollection_HAsciiString(aLeftNbDigits));
2745       aFormatType->AssignCat(new TCollection_HAsciiString("."));
2746       aFormatType->AssignCat(new TCollection_HAsciiString(aRightNbDigits));
2747       aType->Init(aFormatType);
2748       aModel->AddWithRefs(aType);
2749       anItem.SetValue(aType);
2750       aQualifiers->SetValue(aNbQualifiers, anItem);
2751     }
2752     // Set qualifiers
2753     aQRI->SetQualifiers(aQualifiers);
2754     Handle(StepRepr_ReprItemAndMeasureWithUnit) anItem = CreateDimValue(aNominal, aUnit,
2755       new TCollection_HAsciiString("nominal value"), aMeasureName, isAngle, Standard_True, aQRI);
2756     aValues->SetValue(aValIt, anItem);
2757     aValIt++;
2758   }
2759   // Without qualifiers
2760   else {
2761     Handle(StepRepr_ReprItemAndMeasureWithUnit) anItem = CreateDimValue(aNominal, aUnit,
2762       new TCollection_HAsciiString("nominal value"), aMeasureName, isAngle);
2763     aValues->SetValue(aValIt, anItem);
2764     aValIt++;
2765   }
2766
2767   // Ranges
2768   if (theObject->IsDimWithRange()) {
2769     Handle(StepRepr_ReprItemAndMeasureWithUnit) aLowerItem = CreateDimValue(theObject->GetLowerBound(), aUnit,
2770       new TCollection_HAsciiString("lower limit"), aMeasureName, isAngle);
2771     Handle(StepRepr_ReprItemAndMeasureWithUnit) anUpperItem = CreateDimValue(theObject->GetUpperBound(), aUnit,
2772       new TCollection_HAsciiString("upper limit"), aMeasureName, isAngle);
2773     aValues->SetValue(aValIt, aLowerItem);
2774     aValIt++;
2775     aValues->SetValue(aValIt, anUpperItem);
2776     aValIt++;
2777   }
2778
2779   // Modifiers
2780   if (aModifiers.Length() > 0) {
2781     Handle(StepRepr_CompoundRepresentationItem) aCompoundRI = new StepRepr_CompoundRepresentationItem();
2782     Handle (StepRepr_HArray1OfRepresentationItem) aModifItems = 
2783       new StepRepr_HArray1OfRepresentationItem(1, aModifiers.Length());
2784     for (Standard_Integer i = 1; i <= aModifiers.Length(); i++) {
2785       XCAFDimTolObjects_DimensionModif aModif = aModifiers.Value(i);
2786       Handle(StepRepr_DescriptiveRepresentationItem) aModifItem = 
2787         new StepRepr_DescriptiveRepresentationItem();
2788       aModifItem->Init(new TCollection_HAsciiString(), STEPCAFControl_GDTProperty::GetDimModifierName(aModif));
2789       aModel->AddWithRefs(aModifItem);
2790       aModifItems->SetValue(i, aModifItem);
2791     }
2792     aCompoundRI->Init(new TCollection_HAsciiString(), aModifItems);
2793     aValues->SetValue(aValIt, aCompoundRI);
2794     aValIt++;
2795   }
2796
2797   // Orientation
2798   if (theObject->GetType() == XCAFDimTolObjects_DimensionType_Location_Oriented) {
2799     Handle(StepGeom_Axis2Placement3d) anOrientation = new StepGeom_Axis2Placement3d();
2800     gp_Dir aDir;
2801     theObject->GetDirection(aDir);
2802     GeomToStep_MakeCartesianPoint MkPoint(gp_Pnt(0, 0, 0));
2803     Handle(StepGeom_CartesianPoint) aLoc = MkPoint.Value();
2804     Handle(StepGeom_Direction) anAxis = new StepGeom_Direction();
2805     Handle(TColStd_HArray1OfReal) aCoords = new TColStd_HArray1OfReal(1, 3);
2806     aCoords->SetValue(1, aDir.X());
2807     aCoords->SetValue(2, aDir.Y());
2808     aCoords->SetValue(3, aDir.Z());
2809     anAxis->Init(new TCollection_HAsciiString(), aCoords);
2810     anOrientation->Init(new TCollection_HAsciiString("orientation"), aLoc, Standard_True, anAxis, Standard_False, NULL);
2811     aValues->SetValue(aValIt, anOrientation);
2812     aValIt++;
2813   }
2814
2815   // Descriptions
2816   if (theObject->HasDescriptions()) {
2817     for (Standard_Integer i = 0; i < theObject->NbDescriptions(); i++) {
2818       Handle(StepRepr_DescriptiveRepresentationItem) aDRI = new StepRepr_DescriptiveRepresentationItem();
2819       aDRI->Init(theObject->GetDescriptionName(i), theObject->GetDescription(i));
2820       aValues->SetValue(aValIt, aDRI);
2821       aValIt++;
2822     }
2823   }
2824
2825   for (Standard_Integer i = 1; i <= aValues->Length(); i++)
2826     aModel->AddWithRefs(aValues->Value(i));
2827
2828   // Create resulting Shape_Dimension_Representation
2829   Handle(StepShape_ShapeDimensionRepresentation) aSDR = new StepShape_ShapeDimensionRepresentation();
2830   aSDR->Init(new TCollection_HAsciiString(), aValues, theRC);
2831   aModel->AddWithRefs(aSDR);
2832   Handle(StepShape_DimensionalCharacteristicRepresentation) aDCR = new StepShape_DimensionalCharacteristicRepresentation();
2833   aDCR->Init(theDimension, aSDR);
2834   aModel->AddWithRefs(aDCR);
2835
2836   // Plus_Minus_Tolerance
2837   if (theObject->IsDimWithPlusMinusTolerance()) {
2838     Handle(TCollection_HAsciiString) aDummyName = new TCollection_HAsciiString(aMeasureName);
2839     aDummyName = aDummyName->SubString(9, aDummyName->Length()); //delete "POSITIVE_"
2840     aMeasureName = aDummyName->ToCString();
2841     Standard_Real aLowerTolValue = -theObject->GetLowerTolValue(),
2842                   anUpperTolValue = theObject->GetUpperTolValue();
2843     // Upper
2844     Handle(StepBasic_MeasureWithUnit) anUpperMWU = new StepBasic_MeasureWithUnit();
2845     Handle(StepBasic_MeasureValueMember) anUpperValue = new StepBasic_MeasureValueMember();
2846     anUpperValue->SetName(aMeasureName);
2847     anUpperValue->SetReal(anUpperTolValue);
2848     anUpperMWU->Init(anUpperValue, aUnit);
2849     aModel->AddWithRefs(anUpperMWU);
2850     // Lower
2851     Handle(StepBasic_MeasureWithUnit) aLowerMWU = new StepBasic_MeasureWithUnit();
2852     Handle(StepBasic_MeasureValueMember) aLowerValue = new StepBasic_MeasureValueMember();
2853     aLowerValue->SetName(aMeasureName);
2854     aLowerValue->SetReal(aLowerTolValue);
2855     aLowerMWU->Init(aLowerValue, aUnit);
2856     aModel->AddWithRefs(aLowerMWU);
2857     // Tolerance
2858     Handle(StepShape_ToleranceValue) aTolValue = new StepShape_ToleranceValue();
2859     aTolValue->Init(aLowerMWU, anUpperMWU);
2860     aModel->AddWithRefs(aTolValue);
2861     StepShape_ToleranceMethodDefinition aMethod;
2862     aMethod.SetValue(aTolValue);
2863     Handle(StepShape_PlusMinusTolerance) aPlusMinusTol = new StepShape_PlusMinusTolerance();
2864     aPlusMinusTol->Init(aMethod, theDimension);
2865     aModel->AddWithRefs(aPlusMinusTol);
2866   }
2867   // Tolerance class
2868   if (theObject->IsDimWithClassOfTolerance()) {
2869     Standard_Boolean isHole;
2870     XCAFDimTolObjects_DimensionFormVariance aFormVariance;
2871     XCAFDimTolObjects_DimensionGrade aGrade;
2872     if (!theObject->GetClassOfTolerance(isHole, aFormVariance, aGrade))
2873       return;
2874     Handle(StepShape_LimitsAndFits) aLAF = STEPCAFControl_GDTProperty::GetLimitsAndFits(isHole, aFormVariance, aGrade);
2875     aModel->AddWithRefs(aLAF);
2876     StepShape_ToleranceMethodDefinition aMethod;
2877     aMethod.SetValue(aLAF);
2878     Handle(StepShape_PlusMinusTolerance) aPlusMinusTol = new StepShape_PlusMinusTolerance();
2879     aPlusMinusTol->Init(aMethod, theDimension);
2880     aModel->AddWithRefs(aPlusMinusTol);
2881   }
2882 }
2883
2884 //=======================================================================
2885 //function : WriteDerivedGeometry
2886 //purpose  : auxiliary (write connection point for dimensions)
2887 //======================================================================
2888 static void WriteDerivedGeometry (const Handle(XSControl_WorkSession) &WS,
2889                                   const Handle(XCAFDimTolObjects_DimensionObject)& theObject,
2890                                   const Handle(StepRepr_ConstructiveGeometryRepresentation) theRepr,
2891                                   Handle(StepRepr_ShapeAspect)& theFirstSA,
2892                                   Handle(StepRepr_ShapeAspect)& theSecondSA,
2893                                   NCollection_Vector<Handle(StepGeom_CartesianPoint)>& thePnts)
2894 {
2895   const Handle(Interface_InterfaceModel) &aModel = WS->Model();
2896   // First point
2897   if (theObject->HasPoint()) {
2898     GeomToStep_MakeCartesianPoint aPointMaker(theObject->GetPoint());
2899     Handle(StepGeom_CartesianPoint) aPoint = aPointMaker.Value();
2900     thePnts.Append(aPoint);
2901     Handle(StepRepr_DerivedShapeAspect) aDSA = new StepRepr_DerivedShapeAspect();
2902     aDSA->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), theFirstSA->OfShape(), StepData_LFalse);
2903     Handle(StepAP242_GeometricItemSpecificUsage) aGISU = new StepAP242_GeometricItemSpecificUsage();
2904     StepAP242_ItemIdentifiedRepresentationUsageDefinition aDefinition;
2905     aDefinition.SetValue(aDSA);
2906     Handle(StepRepr_HArray1OfRepresentationItem) anItem = new StepRepr_HArray1OfRepresentationItem(1, 1);
2907     anItem->SetValue(1, aPoint);
2908     aGISU->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), aDefinition, theRepr, anItem);
2909     Handle(StepRepr_ShapeAspectDerivingRelationship) aSADR = new StepRepr_ShapeAspectDerivingRelationship();
2910     aSADR->Init(new TCollection_HAsciiString(), Standard_False, new TCollection_HAsciiString(), aDSA, theFirstSA);
2911     theFirstSA = aDSA;
2912     aModel->AddWithRefs(aGISU);
2913     aModel->AddWithRefs(aSADR);
2914   }
2915   
2916   // Second point (for locations)
2917   if (theObject->HasPoint2()) {
2918     GeomToStep_MakeCartesianPoint aPointMaker(theObject->GetPoint2());
2919     Handle(StepGeom_CartesianPoint) aPoint = aPointMaker.Value();
2920     thePnts.Append(aPoint);
2921     Handle(StepRepr_DerivedShapeAspect) aDSA = new StepRepr_DerivedShapeAspect();
2922     aDSA->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), theFirstSA->OfShape(), StepData_LFalse);
2923     Handle(StepAP242_GeometricItemSpecificUsage) aGISU = new StepAP242_GeometricItemSpecificUsage();
2924     StepAP242_ItemIdentifiedRepresentationUsageDefinition aDefinition;
2925     aDefinition.SetValue(aDSA);
2926     Handle(StepRepr_HArray1OfRepresentationItem) anItem = new StepRepr_HArray1OfRepresentationItem(1, 1);
2927     anItem->SetValue(1, aPoint);
2928     aGISU->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), aDefinition, theRepr, anItem);
2929     Handle(StepRepr_ShapeAspectDerivingRelationship) aSADR = new StepRepr_ShapeAspectDerivingRelationship();
2930     aSADR->Init(new TCollection_HAsciiString(), Standard_False, new TCollection_HAsciiString(), aDSA, theSecondSA);
2931     theSecondSA = aDSA;
2932     aModel->AddWithRefs(aGISU);
2933     aModel->AddWithRefs(aSADR);
2934   }
2935 }
2936
2937 //=======================================================================
2938 //function : WriteDatumSystem
2939 //purpose  : auxiliary (write Write datum system for given
2940 //           geometric_tolerance)
2941 //======================================================================
2942 static Handle(StepDimTol_HArray1OfDatumSystemOrReference) WriteDatumSystem(const Handle(XSControl_WorkSession) &WS,
2943                                                                            const TDF_Label theGeomTolL,
2944                                                                            const TDF_LabelSequence theDatumSeq,
2945                                                                            const STEPConstruct_DataMapOfAsciiStringTransient theDatumMap,
2946                                                                            const Handle(StepRepr_RepresentationContext)& theRC)
2947 {
2948   // Get working data
2949   const Handle(Interface_InterfaceModel) &Model = WS->Model();
2950   const Handle(Interface_HGraph) aHGraph = WS->HGraph();
2951   if (aHGraph.IsNull())
2952     return NULL;
2953   Interface_Graph aGraph = aHGraph->Graph();
2954   Handle(XCAFDoc_GeomTolerance) aGTAttr;
2955   if (!theGeomTolL.FindAttribute(XCAFDoc_GeomTolerance::GetID(), aGTAttr)) 
2956     return NULL;
2957   Handle(XCAFDimTolObjects_GeomToleranceObject) anObject = aGTAttr->GetObject();
2958   if (anObject.IsNull())
2959     return NULL;
2960
2961   // Unit
2962   StepBasic_Unit aUnit = GetUnit(theRC);
2963
2964   XCAFDimTolObjects_DatumObjectSequence aDatums;
2965   Standard_Integer aMaxDatumNum = 0;
2966   for (Standard_Integer i = 1; i <= theDatumSeq.Length(); i++) {
2967     Handle(XCAFDoc_Datum) aDatumAttr;
2968     if (!theDatumSeq.Value(i).FindAttribute(XCAFDoc_Datum::GetID(), aDatumAttr)) 
2969       continue;
2970     Handle(XCAFDimTolObjects_DatumObject) aDatumObj = aDatumAttr->GetObject();
2971     if (aDatumObj.IsNull())
2972       continue;
2973     aDatums.Append(aDatumObj);
2974     aMaxDatumNum = Max(aMaxDatumNum, aDatumObj->GetPosition());
2975   }
2976   if (aMaxDatumNum == 0)
2977     return NULL;
2978
2979   Handle(StepDimTol_HArray1OfDatumReferenceCompartment) aConstituents =
2980     new StepDimTol_HArray1OfDatumReferenceCompartment(1, aMaxDatumNum);
2981   // Auxiliary datum to initialize attributes in Datum_System
2982   Handle(StepDimTol_Datum) aFirstDatum;
2983   Standard_Integer aConstituentsNum = 0;
2984   for (Standard_Integer i = 1; i <= aMaxDatumNum; i++) {
2985     // Collect datums with i-th position
2986     XCAFDimTolObjects_DatumObjectSequence aDatumSeqPos;
2987     for (Standard_Integer j = 1; j <= aDatums.Length(); j++)
2988       if (aDatums.Value(j)->GetPosition() == i)
2989         aDatumSeqPos.Append(aDatums.Value(j));
2990     if (aDatumSeqPos.Length() < 1)
2991       continue;
2992
2993     aConstituentsNum++;
2994     // Initialize Datum_Reference_Compartment
2995     StepDimTol_DatumOrCommonDatum aDatumRef;
2996     Handle(StepDimTol_DatumReferenceCompartment) aCompartment =
2997       new StepDimTol_DatumReferenceCompartment();
2998     Handle(StepDimTol_HArray1OfDatumReferenceModifier) aModifiers;
2999     if (aDatumSeqPos.Length() == 1) {
3000       // Datum entity
3001       Handle(Standard_Transient) aFDValue;
3002       if (theDatumMap.Find(aDatumSeqPos.Value(1)->GetName()->String(), aFDValue) && !aFDValue.IsNull())
3003         aFirstDatum = Handle(StepDimTol_Datum)::DownCast (aFDValue);
3004       aDatumRef.SetValue(aFirstDatum);
3005       // Modifiers
3006       XCAFDimTolObjects_DatumModifiersSequence aSimpleModifiers = aDatumSeqPos.Value(1)->GetModifiers();
3007       XCAFDimTolObjects_DatumModifWithValue aModifWithVal;
3008       Standard_Real aValue = 0;
3009       aDatumSeqPos.Value(1)->GetModifierWithValue(aModifWithVal, aValue);
3010       aModifiers = STEPCAFControl_GDTProperty::GetDatumRefModifiers(aSimpleModifiers, aModifWithVal, aValue, aUnit);
3011       // Add Datum_Reference_Modifier_With_Value
3012       if (!aModifiers.IsNull()) {
3013         Handle(StepDimTol_DatumReferenceModifierWithValue) aDRMWV = 
3014           aModifiers->Value(aModifiers->Length()).DatumReferenceModifierWithValue();
3015         if (!aDRMWV.IsNull()) {
3016           Model->AddWithRefs(aDRMWV);
3017         }
3018       }
3019     }
3020     else {
3021       Handle(StepDimTol_HArray1OfDatumReferenceElement) aCommonDatumList = new StepDimTol_HArray1OfDatumReferenceElement(1, aDatumSeqPos.Length());
3022       for (Standard_Integer j = 1; j <= aDatumSeqPos.Length(); j++) {
3023         // Datum entity
3024         Handle(StepDimTol_Datum) aDatum;
3025         Handle(Standard_Transient) aDValue;
3026         if (theDatumMap.Find(aDatumSeqPos.Value(j)->GetName()->String(), aDValue))
3027           aDatum = Handle(StepDimTol_Datum)::DownCast (aDValue);
3028         StepDimTol_DatumOrCommonDatum anElemDatumRef;
3029         anElemDatumRef.SetValue(aDatum);
3030         if (aFirstDatum.IsNull())
3031           aFirstDatum = aDatum;
3032         // Modifiers
3033         XCAFDimTolObjects_DatumModifiersSequence aSimpleModifiers = aDatumSeqPos.Value(j)->GetModifiers();
3034         XCAFDimTolObjects_DatumModifWithValue aModifWithVal;
3035         Standard_Real aValue = 0;
3036         aDatumSeqPos.Value(j)->GetModifierWithValue(aModifWithVal, aValue);
3037         Handle(StepDimTol_HArray1OfDatumReferenceModifier) anElemModifiers =
3038           STEPCAFControl_GDTProperty::GetDatumRefModifiers(aSimpleModifiers, aModifWithVal, aValue, aUnit);
3039         // Add Datum_Reference_Modifier_With_Value
3040         if (!anElemModifiers.IsNull()) {
3041           Handle(StepDimTol_DatumReferenceModifierWithValue) aDRMWV = 
3042             anElemModifiers->Value(anElemModifiers->Length()).DatumReferenceModifierWithValue();
3043           if (!aDRMWV.IsNull()) {
3044             Model->AddWithRefs(aDRMWV);
3045           }
3046         }
3047         // Datum_Reference_Element
3048         Handle(StepDimTol_DatumReferenceElement) anElement = new StepDimTol_DatumReferenceElement();
3049         anElement->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), aDatum->OfShape(),
3050           aDatum->ProductDefinitional(), anElemDatumRef, !anElemModifiers.IsNull(), anElemModifiers);
3051         Model->AddWithRefs(anElement);
3052         aCommonDatumList->SetValue(j, anElement);
3053       }
3054       aDatumRef.SetValue(aCommonDatumList);
3055     }
3056     aCompartment->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), aFirstDatum->OfShape(),
3057       aFirstDatum->ProductDefinitional(), aDatumRef, !aModifiers.IsNull(), aModifiers);
3058     Model->AddWithRefs(aCompartment);
3059     aConstituents->SetValue(aConstituentsNum, aCompartment);
3060   }
3061   // Remove null elements from aConstituents
3062   Standard_Integer aNbConstituents = 0;
3063   for (Standard_Integer i = 1; i <= aConstituents->Length(); i++)
3064     if (!aConstituents->Value(i).IsNull())
3065       aNbConstituents++;
3066   Handle(StepDimTol_HArray1OfDatumReferenceCompartment) aResConstituents =
3067     new StepDimTol_HArray1OfDatumReferenceCompartment(1, aNbConstituents);
3068   Standard_Integer aConstituentsIt = 0;
3069   for (Standard_Integer i = 1; i <= aConstituents->Length(); i++)
3070     if (!aConstituents->Value(i).IsNull()) {
3071       aConstituentsIt++;
3072       aResConstituents->SetValue(aConstituentsIt, aConstituents->Value(i));
3073     }
3074
3075   Handle(StepDimTol_HArray1OfDatumSystemOrReference) aDatumSystem;
3076   Handle(StepDimTol_DatumSystem) aDS = new StepDimTol_DatumSystem();
3077   aDS->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), aFirstDatum->OfShape(),
3078     aFirstDatum->ProductDefinitional(), aResConstituents);
3079   Model->AddWithRefs(aDS);
3080   StepDimTol_DatumSystemOrReference anArrayValue;
3081   anArrayValue.SetValue(aDS);
3082   aDatumSystem = new StepDimTol_HArray1OfDatumSystemOrReference(1, 1);
3083   aDatumSystem->SetValue(1, anArrayValue);
3084
3085   // Axis
3086   if (anObject->HasAxis()) {
3087     Handle(StepGeom_Axis2Placement3d) anAxis =
3088       STEPCAFControl_GDTProperty::GetAxis2Placement3D(anObject->GetAxis());
3089     anAxis->SetName(new TCollection_HAsciiString("orientation"));
3090     Handle(StepAP242_GeometricItemSpecificUsage) aGISU = new StepAP242_GeometricItemSpecificUsage();
3091     StepAP242_ItemIdentifiedRepresentationUsageDefinition aDefinition;
3092     aDefinition.SetValue(aDS);
3093     Handle(StepRepr_HArray1OfRepresentationItem) anReprItems = new StepRepr_HArray1OfRepresentationItem(1, 1);
3094     Handle(StepRepr_RepresentationItem) anIdentifiedItem = anAxis;
3095     anReprItems->SetValue(1, anIdentifiedItem);
3096     Interface_EntityIterator subs = aGraph.Sharings(aFirstDatum->OfShape());
3097     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
3098     for (subs.Start(); subs.More() && aSDR.IsNull(); subs.Next()) {
3099       Handle(Standard_Transient) anEntity = subs.Value();
3100       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(anEntity);
3101     }
3102     if (aSDR.IsNull())
3103       return aDatumSystem;
3104     
3105     aGISU->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(),
3106       aDefinition, aSDR->UsedRepresentation(), anReprItems);
3107     Model->AddWithRefs(anAxis);
3108     Model->AddWithRefs(aGISU);
3109   }
3110
3111   return aDatumSystem;
3112 }
3113
3114 //=======================================================================
3115 //function : WriteToleranceZone
3116 //purpose  : auxiliary (write tolerace zones)
3117 //=======================================================================
3118 void STEPCAFControl_Writer::WriteToleranceZone (const Handle(XSControl_WorkSession) &WS,
3119                                                 const Handle(XCAFDimTolObjects_GeomToleranceObject)& theObject,
3120                                                 const Handle(StepDimTol_GeometricTolerance)& theEntity,
3121                                                 const Handle(StepRepr_RepresentationContext)& theRC)
3122 {
3123   // Get working data
3124   const Handle(Interface_InterfaceModel) &Model = WS->Model();
3125   if (theEntity.IsNull() || theObject.IsNull())
3126     return;
3127
3128   // Return if there is no tolerance zones
3129   if (theObject->GetTypeOfValue() == XCAFDimTolObjects_GeomToleranceTypeValue_None &&
3130       theObject->GetZoneModifier() != XCAFDimTolObjects_GeomToleranceZoneModif_Runout)
3131     return;
3132
3133   // Create Tolerance_Zone
3134   Handle(StepDimTol_ToleranceZoneForm) aForm = new StepDimTol_ToleranceZoneForm();
3135   Model->AddWithRefs(aForm);
3136   aForm->Init(STEPCAFControl_GDTProperty::GetTolValueType(theObject->GetTypeOfValue()));
3137   Handle(StepDimTol_HArray1OfToleranceZoneTarget) aZoneTargetArray = new StepDimTol_HArray1OfToleranceZoneTarget(1, 1);
3138   StepDimTol_ToleranceZoneTarget aTarget;
3139   aTarget.SetValue(theEntity);
3140   aZoneTargetArray->SetValue(1, aTarget);
3141   Handle(StepDimTol_ToleranceZone) aZone = new StepDimTol_ToleranceZone();
3142   aZone->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(),
3143     theEntity->TolerancedShapeAspect().ShapeAspect()->OfShape(), StepData_LFalse,
3144     aZoneTargetArray, aForm);
3145   Model->AddWithRefs(aZone);
3146
3147   // Runout_Tolerance_Zone
3148   Handle(StepBasic_PlaneAngleMeasureWithUnit) aPAMWU = new StepBasic_PlaneAngleMeasureWithUnit();
3149   Handle(StepBasic_MeasureValueMember) aValueMember = new StepBasic_MeasureValueMember();
3150   aValueMember->SetName("PLANE_ANGLE_MEASURE");
3151   aValueMember->SetReal(theObject->GetValueOfZoneModifier());
3152   aPAMWU->Init(aValueMember, GetUnit(theRC, Standard_True));
3153   Handle(StepDimTol_RunoutZoneOrientation) anOrientation = new StepDimTol_RunoutZoneOrientation();
3154   anOrientation->Init(aPAMWU);
3155   Handle(StepDimTol_RunoutZoneDefinition) aDefinition = new StepDimTol_RunoutZoneDefinition();
3156   aDefinition->Init(aZone, NULL, anOrientation);
3157   Model->AddWithRefs(aDefinition);
3158   Model->AddWithRefs(anOrientation);
3159   Model->AddWithRefs(aPAMWU);
3160 }
3161
3162 //=======================================================================
3163 //function : WriteGeomTolerance
3164 //purpose  : auxiliary (write Geometric_Tolerance entity for given shapes,
3165 //           label and datum system)
3166 //======================================================================
3167 void STEPCAFControl_Writer::WriteGeomTolerance (const Handle(XSControl_WorkSession) &WS,
3168                                                 const TDF_LabelSequence theShapeSeqL,
3169                                                 const TDF_Label theGeomTolL,
3170                                                 const Handle(StepDimTol_HArray1OfDatumSystemOrReference)& theDatumSystem,
3171                                                 const Handle(StepRepr_RepresentationContext)& theRC)
3172 {
3173   // Get working data
3174   const Handle(Interface_InterfaceModel) &Model = WS->Model();
3175   Handle(XCAFDoc_GeomTolerance) aGTAttr;
3176   if (!theGeomTolL.FindAttribute(XCAFDoc_GeomTolerance::GetID(), aGTAttr)) 
3177     return;
3178   Handle(XCAFDimTolObjects_GeomToleranceObject) anObject = aGTAttr->GetObject();
3179   if (anObject.IsNull())
3180     return;
3181
3182   // Value
3183   Handle(StepBasic_LengthMeasureWithUnit) aLMWU = new StepBasic_LengthMeasureWithUnit();
3184   StepBasic_Unit aUnit = GetUnit(theRC);
3185   Handle(StepBasic_MeasureValueMember) aValueMember = new StepBasic_MeasureValueMember();
3186   aValueMember->SetName("LENGTH_MEASURE");
3187   aValueMember->SetReal(anObject->GetValue());
3188   aLMWU->Init(aValueMember, aUnit);
3189   Model->AddWithRefs(aLMWU);
3190
3191   // Geometric_Tolerance target
3192   Handle(StepRepr_ShapeAspect) aMainSA;
3193   Handle(StepRepr_RepresentationContext) dummyRC;
3194   Handle(StepAP242_GeometricItemSpecificUsage) dummyGISU;
3195   if (theShapeSeqL.Length() == 1) {
3196     TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(theShapeSeqL.Value(1));
3197     aMainSA = WriteShapeAspect(WS, theGeomTolL, aShape, dummyRC, dummyGISU);
3198     Model->AddWithRefs(aMainSA);
3199   }
3200   else {
3201     Handle(StepRepr_CompositeShapeAspect) aCSA;
3202     for (Standard_Integer i = 1; i <= theShapeSeqL.Length(); i++) {
3203       TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(theShapeSeqL.Value(i));
3204       Handle(StepRepr_ShapeAspect) aSA = WriteShapeAspect(WS, theGeomTolL, aShape, dummyRC, dummyGISU);
3205       if (aSA.IsNull())
3206         continue;
3207       if (aCSA.IsNull()) {
3208         aCSA = new StepRepr_CompositeShapeAspect();
3209         aCSA->Init(aSA->Name(), aSA->Description(), aSA->OfShape(), aSA->ProductDefinitional());
3210         Model->AddWithRefs(aCSA);
3211       }
3212       Handle(StepRepr_ShapeAspectRelationship) aSAR = new StepRepr_ShapeAspectRelationship();
3213       aSAR->Init(new TCollection_HAsciiString(), Standard_False, NULL, aCSA, aSA);
3214       Model->AddWithRefs(aSAR);
3215     }
3216     aMainSA = aCSA;
3217   }
3218   StepDimTol_GeometricToleranceTarget aGTTarget;
3219   aGTTarget.SetValue(aMainSA);
3220
3221   Standard_Boolean isWithModif = Standard_False,
3222                    isWithDatRef = Standard_False,
3223                    isWithMaxTol = Standard_False;
3224   // Modifiers
3225   // Simple modifiers
3226   XCAFDimTolObjects_GeomToleranceModifiersSequence aModifiers = anObject->GetModifiers();
3227   Handle(StepDimTol_HArray1OfGeometricToleranceModifier) aModifArray;
3228   Handle(StepBasic_LengthMeasureWithUnit) aMaxLMWU;
3229   Standard_Integer aModifNb = aModifiers.Length();
3230   if (anObject->GetMaterialRequirementModifier() != XCAFDimTolObjects_GeomToleranceMatReqModif_None)
3231       aModifNb++;
3232   for (Standard_Integer i = 1; i <= aModifiers.Length(); i++)
3233     if (aModifiers.Value(i) == XCAFDimTolObjects_GeomToleranceModif_All_Around ||
3234         aModifiers.Value(i) == XCAFDimTolObjects_GeomToleranceModif_All_Over)
3235         aModifNb--;
3236   if (aModifNb > 0) {
3237     isWithModif = Standard_True;
3238     aModifArray = new StepDimTol_HArray1OfGeometricToleranceModifier(1, aModifNb);
3239     Standard_Integer k = 1;
3240     for (Standard_Integer i = 1; i <= aModifiers.Length(); i++) {
3241       if (aModifiers.Value(i) == XCAFDimTolObjects_GeomToleranceModif_All_Around ||
3242         aModifiers.Value(i) == XCAFDimTolObjects_GeomToleranceModif_All_Over)
3243         continue;
3244       StepDimTol_GeometricToleranceModifier aModif = 
3245         STEPCAFControl_GDTProperty::GetGeomToleranceModifier(aModifiers.Value(i));
3246       aModifArray->SetValue(k, aModif);
3247       k++;
3248     }
3249     if (anObject->GetMaterialRequirementModifier() == XCAFDimTolObjects_GeomToleranceMatReqModif_L) {
3250       aModifArray->SetValue(aModifNb, StepDimTol_GTMLeastMaterialRequirement);
3251     }
3252     else if (anObject->GetMaterialRequirementModifier() == XCAFDimTolObjects_GeomToleranceMatReqModif_M) {
3253       aModifArray->SetValue(aModifNb, StepDimTol_GTMMaximumMaterialRequirement);
3254     }
3255     // Modifier with value
3256     if (anObject->GetMaxValueModifier() != 0) {
3257       isWithMaxTol = Standard_True;
3258       aMaxLMWU = new StepBasic_LengthMeasureWithUnit();
3259       Handle(StepBasic_MeasureValueMember) aModifierValueMember = new StepBasic_MeasureValueMember();
3260       aModifierValueMember->SetName("LENGTH_MEASURE");
3261       aModifierValueMember->SetReal(anObject->GetMaxValueModifier());
3262       aMaxLMWU->Init(aModifierValueMember, aUnit);
3263       Model->AddWithRefs(aMaxLMWU);
3264     }
3265   }
3266
3267   // Datum Reference
3268   isWithDatRef = !theDatumSystem.IsNull();
3269
3270   // Collect all attributes
3271   Handle(TCollection_HAsciiString) aName = new TCollection_HAsciiString(),
3272                                   aDescription = new TCollection_HAsciiString();
3273   Handle(StepDimTol_GeometricToleranceWithDatumReference) aGTWDR = 
3274     new StepDimTol_GeometricToleranceWithDatumReference();
3275   aGTWDR->SetDatumSystem(theDatumSystem);
3276   Handle(StepDimTol_GeometricToleranceWithModifiers) aGTWM = 
3277     new StepDimTol_GeometricToleranceWithModifiers();
3278   aGTWM->SetModifiers(aModifArray);
3279   StepDimTol_GeometricToleranceType aType = 
3280     STEPCAFControl_GDTProperty::GetGeomToleranceType(anObject->GetType());
3281
3282   // Init and write necessary subtype of Geometric_Tolerance entity
3283   Handle(StepDimTol_GeometricTolerance) aGeomTol;
3284   if (isWithModif) {
3285     if (isWithMaxTol) {
3286       if (isWithDatRef) {
3287         // Geometric_Tolerance & Geometric_Tolerance_With_Datum_Reference & 
3288         //Geometric_Tolerance_With_Maximum_Tolerance & Geometric_Tolerance_With_Modifiers
3289         Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol) aResult =
3290           new StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol();
3291         aResult->Init(aName, aDescription, aLMWU, aGTTarget, aGTWDR, aGTWM, aMaxLMWU, aType);
3292         aGeomTol = aResult;
3293       }
3294       else {
3295         // Geometric_Tolerance & Geometric_Tolerance_With_Maximum_Tolerance & Geometric_Tolerance_With_Modifiers
3296         Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol) aResult =
3297           new StepDimTol_GeoTolAndGeoTolWthMaxTol();
3298         aResult->Init(aName, aDescription, aLMWU, aGTTarget, aGTWM, aMaxLMWU, aType);
3299         aGeomTol = aResult;
3300       }
3301     }
3302     else {
3303       if (isWithDatRef) {
3304         // Geometric_Tolerance & Geometric_Tolerance_With_Datum_Reference & Geometric_Tolerance_With_Modifiers
3305         Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod) aResult =
3306           new StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod();
3307         aResult->Init(aName, aDescription, aLMWU, aGTTarget, aGTWDR, aGTWM, aType);
3308         aGeomTol = aResult;
3309       }
3310       else {
3311         // Geometric_Tolerance & Geometric_Tolerance_With_Modifiers
3312         Handle(StepDimTol_GeoTolAndGeoTolWthMod) aResult =
3313           new StepDimTol_GeoTolAndGeoTolWthMod();
3314         aResult->Init(aName, aDescription, aLMWU, aGTTarget, aGTWM, aType);
3315         aGeomTol = aResult;
3316       }
3317     }
3318   }
3319   else {
3320     if (isWithDatRef) {
3321       // Geometric_Tolerance & Geometric_Tolerance_With_Datum_Reference
3322       Handle(StepDimTol_GeoTolAndGeoTolWthDatRef) aResult =
3323           new StepDimTol_GeoTolAndGeoTolWthDatRef();
3324         aResult->Init(aName, aDescription, aLMWU, aGTTarget, aGTWDR, aType);
3325         aGeomTol = aResult;
3326     }
3327     else {
3328       // Geometric_Tolerance
3329       Handle(StepDimTol_GeometricTolerance) aResult = 
3330         STEPCAFControl_GDTProperty::GetGeomTolerance(anObject->GetType());
3331       if (!aResult.IsNull()) {
3332         aResult->Init(aName, aDescription, aLMWU, aGTTarget);
3333         aGeomTol = aResult;
3334       }
3335     }
3336   }
3337   Model->AddWithRefs(aGeomTol);
3338   WriteToleranceZone(WS, anObject, aGeomTol, theRC);
3339   //Annotation plane and Presentation
3340   WritePresentation(WS, anObject->GetPresentation(), anObject->GetPresentationName(), Standard_True, anObject->HasPlane(),
3341     anObject->GetPlane(), anObject->GetPointTextAttach(), aGeomTol);
3342 }
3343
3344 //=======================================================================
3345 //function : WriteDGTs
3346 //purpose  : 
3347 //=======================================================================
3348 Standard_Boolean STEPCAFControl_Writer::WriteDGTs (const Handle(XSControl_WorkSession) &WS,
3349                                                    const TDF_LabelSequence  &labels ) const
3350 {
3351   
3352   if ( labels.Length() <=0 ) return Standard_False;
3353   
3354   // get working data
3355   const Handle(Interface_InterfaceModel) &Model = WS->Model();
3356   const Handle(XSControl_TransferWriter) &TW = WS->TransferWriter();
3357   const Handle(Transfer_FinderProcess) &FP = TW->FinderProcess();
3358
3359   const Handle(Interface_HGraph) aHGraph = WS->HGraph();
3360   if(aHGraph.IsNull())
3361     return Standard_False;
3362
3363   Interface_Graph aGraph = aHGraph->Graph();
3364   Handle(XCAFDoc_DimTolTool) DGTTool = XCAFDoc_DocumentTool::DimTolTool( labels(1) );
3365   if(DGTTool.IsNull() ) return Standard_False;
3366
3367   TDF_LabelSequence DGTLabels;
3368
3369   STEPConstruct_DataMapOfAsciiStringTransient DatumMap;
3370
3371   // write Datums
3372   DGTLabels.Clear();
3373   DGTTool->GetDatumLabels(DGTLabels);
3374   if(DGTLabels.Length()<=0) return Standard_False;
3375   Standard_Integer i;
3376   for(i=1; i<=DGTLabels.Length(); i++) {
3377     TDF_Label DatumL = DGTLabels.Value(i);
3378     TDF_LabelSequence ShapeL;
3379     TDF_LabelSequence aNullSeq;
3380     if(!DGTTool->GetRefShapeLabel(DatumL,ShapeL,aNullSeq)) continue;
3381     // find target shape
3382     TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(ShapeL.Value(1));
3383     TopLoc_Location Loc;
3384     TColStd_SequenceOfTransient seqRI;
3385     FindEntities( FP, aShape, Loc, seqRI );
3386     if ( seqRI.Length() <= 0 ) {
3387       FP->Messenger() << "Warning: Cannot find RI for "<<aShape.TShape()->DynamicType()->Name()<<endl;
3388       continue;
3389     }
3390     Handle(StepRepr_ProductDefinitionShape) PDS;
3391     Handle(StepRepr_RepresentationContext) RC;
3392     Handle(Standard_Transient) ent = seqRI.Value(1);
3393     Handle(StepShape_AdvancedFace) AF;
3394     Handle(StepShape_EdgeCurve) EC;
3395     FindPDSforDGT(aGraph,ent,PDS,RC,AF,EC);
3396     if(PDS.IsNull()) continue;
3397     //cout<<"Model->Number(PDS)="<<Model->Number(PDS)<<endl;
3398     Handle(XCAFDoc_Datum) DatumAttr;
3399     if(!DatumL.FindAttribute(XCAFDoc_Datum::GetID(),DatumAttr)) continue;
3400     Handle(TCollection_HAsciiString) aName = DatumAttr->GetName();
3401     Handle(TCollection_HAsciiString) aDescription = DatumAttr->GetDescription();
3402     Handle(TCollection_HAsciiString) anIdentification = DatumAttr->GetIdentification();
3403     Handle(StepDimTol_DatumFeature) DF = new StepDimTol_DatumFeature;
3404     Handle(StepDimTol_Datum) aDatum = new StepDimTol_Datum;
3405     DF->Init(aName, new TCollection_HAsciiString, PDS, StepData_LTrue);
3406     Model->AddWithRefs(DF);
3407     aDatum->Init(aName, new TCollection_HAsciiString, PDS, StepData_LFalse, anIdentification);
3408     Model->AddWithRefs(aDatum);
3409     Handle(StepRepr_ShapeAspectRelationship) SAR = new StepRepr_ShapeAspectRelationship;
3410     SAR->SetName(aName);
3411     SAR->SetRelatingShapeAspect(DF);
3412     SAR->SetRelatedShapeAspect(aDatum);
3413     Model->AddWithRefs(SAR);
3414     // write chain for DatumFeature
3415     StepRepr_CharacterizedDefinition CD;
3416     CD.SetValue(DF);
3417     Handle(StepRepr_PropertyDefinition) PropD = new StepRepr_PropertyDefinition;
3418     PropD->Init(aName,Standard_True,aDescription,CD);
3419     Model->AddWithRefs(PropD);
3420     StepRepr_RepresentedDefinition RD;
3421     RD.SetValue(PropD);
3422     Handle(StepShape_ShapeRepresentation) SR = new StepShape_ShapeRepresentation;
3423     Handle(StepRepr_HArray1OfRepresentationItem) HARI =
3424       new StepRepr_HArray1OfRepresentationItem(1,1);
3425     HARI->SetValue(1,AF);
3426     SR->Init(aName,HARI,RC);
3427     Handle(StepShape_ShapeDefinitionRepresentation) SDR = new StepShape_ShapeDefinitionRepresentation;
3428     SDR->Init(RD,SR);
3429     Model->AddWithRefs(SDR);
3430     // write chain for Datum 
3431     StepRepr_CharacterizedDefinition CD1;
3432     CD1.SetValue(aDatum);
3433     Handle(StepRepr_PropertyDefinition) PropD1 = new StepRepr_PropertyDefinition;
3434     PropD1->Init(aName,Standard_True,aDescription,CD1);
3435     Model->AddWithRefs(PropD1);
3436     StepRepr_RepresentedDefinition RD1;
3437     RD1.SetValue(PropD1);
3438     Handle(StepShape_ShapeRepresentation) SR1 = new StepShape_ShapeRepresentation;
3439     Handle(StepRepr_HArray1OfRepresentationItem) HARI1 =
3440       new StepRepr_HArray1OfRepresentationItem(1,1);
3441     HARI1->SetValue(1,AF->FaceGeometry());
3442     SR1->Init(aName,HARI1,RC);
3443     Model->AddWithRefs(SR1);
3444     Handle(StepShape_ShapeDefinitionRepresentation) SDR1 = new StepShape_ShapeDefinitionRepresentation;
3445     SDR1->Init(RD1,SR1);
3446     Model->AddWithRefs(SDR1);
3447     // add created Datum into Map
3448     TCollection_AsciiString stmp(aName->ToCString());
3449     stmp.AssignCat(aDescription->ToCString());
3450     stmp.AssignCat(anIdentification->ToCString());
3451     DatumMap.Bind(stmp,aDatum);
3452   }
3453
3454   // write Tolerances and Dimensions
3455   DGTLabels.Clear();
3456   DGTTool->GetDimTolLabels(DGTLabels);
3457   if(DGTLabels.Length()<=0) return Standard_False;
3458   for(i=1; i<=DGTLabels.Length(); i++) {
3459     TDF_Label DimTolL = DGTLabels.Value(i);
3460     TDF_LabelSequence ShapeL;
3461     TDF_LabelSequence aNullSeq;
3462     if(!DGTTool->GetRefShapeLabel(DimTolL,ShapeL,aNullSeq)) continue;
3463     // find target shape
3464     TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(ShapeL.Value(1));
3465     TopLoc_Location Loc;
3466     TColStd_SequenceOfTransient seqRI;
3467     FindEntities( FP, aShape, Loc, seqRI );
3468     if ( seqRI.Length() <= 0 ) {
3469       FP->Messenger() << "Warning: Cannot find RI for "<<aShape.TShape()->DynamicType()->Name()<<endl;
3470       continue;
3471     }
3472     Handle(StepRepr_ProductDefinitionShape) PDS;
3473     Handle(StepRepr_RepresentationContext) RC;
3474     Handle(Standard_Transient) ent = seqRI.Value(1);
3475     Handle(StepShape_AdvancedFace) AF;
3476     Handle(StepShape_EdgeCurve) EC;
3477     FindPDSforDGT(aGraph,ent,PDS,RC,AF,EC);
3478     if(PDS.IsNull()) continue;
3479     //cout<<"Model->Number(PDS)="<<Model->Number(PDS)<<endl;
3480
3481     Handle(XCAFDoc_DimTol) DimTolAttr;
3482     if(!DimTolL.FindAttribute(XCAFDoc_DimTol::GetID(),DimTolAttr)) continue;
3483     Standard_Integer kind = DimTolAttr->GetKind();
3484     Handle(TColStd_HArray1OfReal) aVal = DimTolAttr->GetVal();
3485     Handle(TCollection_HAsciiString) aName = DimTolAttr->GetName();
3486     Handle(TCollection_HAsciiString) aDescription = DimTolAttr->GetDescription();
3487
3488     // common part of writing D&GT entities
3489     StepRepr_CharacterizedDefinition CD;
3490     Handle(StepRepr_ShapeAspect) SA = new StepRepr_ShapeAspect;
3491     SA->Init(aName, new TCollection_HAsciiString, PDS, StepData_LTrue);
3492     Model->AddWithRefs(SA);
3493     CD.SetValue(SA);
3494     Handle(StepRepr_PropertyDefinition) PropD = new StepRepr_PropertyDefinition;
3495     PropD->Init(aName,Standard_True,aDescription,CD);
3496     Model->AddWithRefs(PropD);
3497     StepRepr_RepresentedDefinition RD;
3498     RD.SetValue(PropD);
3499     Handle(StepShape_ShapeRepresentation) SR = new StepShape_ShapeRepresentation;
3500     Handle(StepRepr_HArray1OfRepresentationItem) HARI =
3501       new StepRepr_HArray1OfRepresentationItem(1,1);
3502     if(kind<20) 
3503       HARI->SetValue(1,EC);
3504     else
3505       HARI->SetValue(1,AF);
3506     SR->Init(aName,HARI,RC);
3507     Handle(StepShape_ShapeDefinitionRepresentation) SDR = new StepShape_ShapeDefinitionRepresentation;
3508     SDR->Init(RD,SR);
3509     Model->AddWithRefs(SDR);
3510     // define aUnit for creation LengthMeasureWithUnit (common for all)
3511     StepBasic_Unit aUnit;
3512     Handle(StepBasic_SiUnitAndLengthUnit) SLU;
3513     Handle(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext) Ctx =
3514       Handle(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext)::DownCast(RC);
3515     if(!Ctx.IsNull()) {
3516       for(Standard_Integer j=1; j<=Ctx->NbUnits(); j++) {
3517         if(Ctx->UnitsValue(j)->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndLengthUnit))) {
3518           SLU = Handle(StepBasic_SiUnitAndLengthUnit)::DownCast(Ctx->UnitsValue(j));
3519           break;
3520         }
3521       }
3522     }
3523     if(SLU.IsNull()) {
3524       Handle(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx) Ctx1 =
3525         Handle(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx)::DownCast(RC);
3526       if(!Ctx1.IsNull()) {
3527         for(Standard_Integer j=1; j<=Ctx1->NbUnits(); j++) {
3528           if(Ctx1->UnitsValue(j)->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndLengthUnit))) {
3529             SLU = Handle(StepBasic_SiUnitAndLengthUnit)::DownCast(Ctx1->UnitsValue(j));
3530             break;
3531           }
3532         }
3533       }
3534     }
3535     if(SLU.IsNull()) {
3536       SLU = new StepBasic_SiUnitAndLengthUnit;
3537     }
3538     aUnit.SetValue(SLU);
3539
3540     // specific part of writing D&GT entities
3541     if(kind<20) { //dimension
3542       Handle(StepShape_DimensionalSize) DimSize = new StepShape_DimensionalSize;
3543       DimSize->Init(SA,aDescription);
3544       Model->AddWithRefs(DimSize);
3545       if(aVal->Length()>1) {
3546         // create MeasureWithUnits
3547         Handle(StepBasic_MeasureValueMember) MVM1 = new StepBasic_MeasureValueMember;
3548         MVM1->SetName("POSITIVE_LENGTH_MEASURE");
3549         MVM1->SetReal(aVal->Value(1));
3550         Handle(StepBasic_MeasureWithUnit) MWU1 = new StepBasic_MeasureWithUnit;
3551         MWU1->Init(MVM1,aUnit);
3552         Handle(StepBasic_MeasureValueMember) MVM2 = new StepBasic_MeasureValueMember;
3553         MVM2->SetName("POSITIVE_LENGTH_MEASURE");
3554         MVM2->SetReal(aVal->Value(2));
3555         Handle(StepBasic_MeasureWithUnit) MWU2 = new StepBasic_MeasureWithUnit;
3556         MWU2->Init(MVM2,aUnit);
3557         Handle(StepRepr_RepresentationItem) RI1 = new StepRepr_RepresentationItem;
3558         RI1->Init(new TCollection_HAsciiString("lower limit"));
3559         Handle(StepRepr_RepresentationItem) RI2 = new StepRepr_RepresentationItem;
3560         RI2->Init(new TCollection_HAsciiString("upper limit"));
3561         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMU1 =
3562           new StepRepr_ReprItemAndLengthMeasureWithUnit;
3563         RILMU1->Init(MWU1,RI1);
3564         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMU2 =
3565           new StepRepr_ReprItemAndLengthMeasureWithUnit;
3566         RILMU2->Init(MWU2,RI2);
3567         Model->AddWithRefs(RILMU1);
3568         Model->AddWithRefs(RILMU2);
3569         //Handle(StepRepr_CompoundItemDefinitionMember) CIDM =
3570         //  new StepRepr_CompoundItemDefinitionMember;
3571         //Handle(TColStd_HArray1OfTransient) ArrTr = new TColStd_HArray1OfTransient(1,2);
3572         //ArrTr->SetValue(1,RILMU1);
3573         //ArrTr->SetValue(2,RILMU2);
3574         //CIDM->SetArrTransient(ArrTr);
3575         //CIDM->SetName("SET_REPRESENTATION_ITEM");
3576         //StepRepr_CompoundItemDefinition CID;
3577         //CID.SetValue(CIDM);
3578         Handle(StepRepr_HArray1OfRepresentationItem) HARIVR =
3579           new StepRepr_HArray1OfRepresentationItem(1,2);
3580         HARIVR->SetValue(1,RILMU1);
3581         HARIVR->SetValue(2,RILMU2);
3582         Handle(StepRepr_ValueRange) VR = new StepRepr_ValueRange;
3583         //VR->Init(aName,CID);
3584         VR->Init(aName,HARIVR);
3585         Model->AddEntity(VR);
3586         Handle(StepShape_ShapeDimensionRepresentation) SDimR =
3587           new StepShape_ShapeDimensionRepresentation;
3588         Handle(StepRepr_HArray1OfRepresentationItem) aHARI =
3589           new StepRepr_HArray1OfRepresentationItem(1,1);
3590         aHARI->SetValue(1,VR);
3591         SDimR->Init(aName,aHARI,RC);
3592         Model->AddWithRefs(SDimR);
3593         Handle(StepShape_DimensionalCharacteristicRepresentation) DimCharR =
3594           new StepShape_DimensionalCharacteristicRepresentation;
3595         StepShape_DimensionalCharacteristic DimChar;
3596         DimChar.SetValue(DimSize);
3597         DimCharR->Init(DimChar,SDimR);
3598         Model->AddEntity(DimCharR);
3599       }
3600     }
3601     else if(kind<50) { //tolerance
3602       if(kind<35) { // tolerance with datum system
3603         TDF_LabelSequence DatumLabels;
3604         DGTTool->GetDatumOfTolerLabels(DimTolL,DatumLabels);
3605         Standard_Integer NbDR = DatumLabels.Length();
3606         Handle(StepDimTol_HArray1OfDatumReference) HADR = new StepDimTol_HArray1OfDatumReference(1,NbDR);
3607         for(Standard_Integer j=1; j<=NbDR; j++) {
3608           Handle(XCAFDoc_Datum) DatumAttr;
3609           TDF_Label DatumL = DatumLabels.Value(j);
3610           if(!DatumL.FindAttribute(XCAFDoc_Datum::GetID(),DatumAttr)) continue;
3611           Handle(TCollection_HAsciiString) aNameD = DatumAttr->GetName();
3612           Handle(TCollection_HAsciiString) aDescriptionD = DatumAttr->GetDescription();
3613           Handle(TCollection_HAsciiString) anIdentificationD = DatumAttr->GetIdentification();
3614           TCollection_AsciiString stmp(aNameD->ToCString());
3615           stmp.AssignCat(aDescriptionD->ToCString());
3616           stmp.AssignCat(anIdentificationD->ToCString());
3617           if(DatumMap.IsBound(stmp)) {
3618             Handle(StepDimTol_Datum) aDatum = 
3619               Handle(StepDimTol_Datum)::DownCast(DatumMap.Find(stmp));
3620             Handle(StepDimTol_DatumReference) DR = new StepDimTol_DatumReference;
3621             DR->Init(j,aDatum);
3622             Model->AddWithRefs(DR);
3623             HADR->SetValue(j,DR);
3624           }
3625         }
3626         // create LengthMeasureWithUnit
3627         Handle(StepBasic_MeasureValueMember) MVM = new StepBasic_MeasureValueMember;
3628         MVM->SetName("LENGTH_MEASURE");
3629         MVM->SetReal(aVal->Value(1));
3630         Handle(StepBasic_LengthMeasureWithUnit) LMWU = new StepBasic_LengthMeasureWithUnit;
3631         LMWU->Init(MVM,aUnit);
3632         // create tolerance by it's type
3633         if(kind<24) {
3634           Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
3635             new StepDimTol_GeometricToleranceWithDatumReference;
3636           GTWDR->SetDatumSystem(HADR);
3637           Handle(StepDimTol_ModifiedGeometricTolerance) MGT =
3638             new StepDimTol_ModifiedGeometricTolerance;
3639           if(kind==21) MGT->SetModifier(StepDimTol_MaximumMaterialCondition);
3640           else if(kind==22) MGT->SetModifier(StepDimTol_LeastMaterialCondition);
3641           else if(kind==23) MGT->SetModifier(StepDimTol_RegardlessOfFeatureSize);
3642           Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol) GTComplex =
3643             new StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol;
3644           GTComplex->Init(aName,aDescription,LMWU,SA,GTWDR,MGT);
3645           Model->AddWithRefs(GTComplex);
3646         }
3647         else if(kind==24) {
3648           Handle(StepDimTol_AngularityTolerance) aToler =
3649             new StepDimTol_AngularityTolerance;
3650           aToler->Init(aName,aDescription,LMWU,SA,HADR);
3651           Model->AddWithRefs(aToler);
3652         }
3653         else if(kind==25) {
3654           Handle(StepDimTol_CircularRunoutTolerance) aToler =
3655             new StepDimTol_CircularRunoutTolerance;
3656           aToler->Init(aName,aDescription,LMWU,SA,HADR);
3657           Model->AddWithRefs(aToler);
3658         }
3659         else if(kind==26) {
3660           Handle(StepDimTol_CoaxialityTolerance) aToler =
3661             new StepDimTol_CoaxialityTolerance;
3662           aToler->Init(aName,aDescription,LMWU,SA,HADR);
3663           Model->AddWithRefs(aToler);
3664         }
3665         else if(kind==27) {
3666           Handle(StepDimTol_ConcentricityTolerance) aToler =
3667             new StepDimTol_ConcentricityTolerance;
3668           aToler->Init(aName,aDescription,LMWU,SA,HADR);
3669           Model->AddWithRefs(aToler);
3670         }
3671         else if(kind==28) {
3672           Handle(StepDimTol_ParallelismTolerance) aToler =
3673             new StepDimTol_ParallelismTolerance;
3674           aToler->Init(aName,aDescription,LMWU,SA,HADR);
3675           Model->AddWithRefs(aToler);
3676         }
3677         else if(kind==29) {
3678           Handle(StepDimTol_PerpendicularityTolerance) aToler =
3679             new StepDimTol_PerpendicularityTolerance;
3680           aToler->Init(aName,aDescription,LMWU,SA,HADR);
3681           Model->AddWithRefs(aToler);
3682         }
3683         else if(kind==30) {
3684           Handle(StepDimTol_SymmetryTolerance) aToler =
3685             new StepDimTol_SymmetryTolerance;
3686           aToler->Init(aName,aDescription,LMWU,SA,HADR);
3687           Model->AddWithRefs(aToler);
3688         }
3689         else if(kind==31) {
3690           Handle(StepDimTol_TotalRunoutTolerance) aToler =
3691             new StepDimTol_TotalRunoutTolerance;
3692           aToler->Init(aName,aDescription,LMWU,SA,HADR);
3693           Model->AddWithRefs(aToler);
3694         }
3695       }
3696     }
3697   }
3698
3699   return Standard_True;
3700 }
3701
3702 //=======================================================================
3703 //function : WriteDGTsAP242
3704 //purpose  : 
3705 //=======================================================================
3706
3707 Standard_Boolean STEPCAFControl_Writer::WriteDGTsAP242 (const Handle(XSControl_WorkSession) &WS,
3708                                                         const TDF_LabelSequence  &labels )
3709 {
3710   // Get working data
3711   const Handle(Interface_InterfaceModel) &aModel = WS->Model();
3712
3713   const Handle(Interface_HGraph) aHGraph = WS->HGraph();
3714   if(aHGraph.IsNull())
3715     return Standard_False;
3716
3717   Interface_Graph aGraph = aHGraph->Graph();
3718   Handle(XCAFDoc_DimTolTool) DGTTool = XCAFDoc_DocumentTool::DimTolTool(labels(1));
3719   if(DGTTool.IsNull())
3720     return Standard_False;
3721
3722   // Common entities for presentation
3723   STEPConstruct_Styles aStyles (WS);
3724   Handle(StepVisual_Colour) aCurvColor = aStyles.EncodeColor(Quantity_NOC_WHITE);
3725   Handle(StepRepr_RepresentationItem) anItem = NULL;
3726   myGDTPrsCurveStyle->SetValue(1, aStyles.MakeColorPSA(anItem, aCurvColor, aCurvColor));
3727   Interface_EntityIterator aModelIter = aModel->Entities();
3728   for (; aModelIter.More() && myGDTCommonPDS.IsNull(); aModelIter.Next())
3729     myGDTCommonPDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(aModelIter.Value());
3730
3731   TDF_LabelSequence aDGTLabels;
3732   STEPConstruct_DataMapOfAsciiStringTransient aDatumMap;
3733   Handle(StepRepr_RepresentationContext) aRC;
3734
3735   //------------- //
3736   // write Datums //
3737   //--------------//
3738   DGTTool->GetDatumLabels(aDGTLabels);
3739   // Find all shapes with datums
3740   TColStd_MapOfAsciiString aNameIdMap;
3741   for(Standard_Integer i = 1; i <= aDGTLabels.Length(); i++) {
3742     TDF_Label aDatumL = aDGTLabels.Value(i);
3743     TDF_LabelSequence aShapeL, aNullSeq;
3744     DGTTool->GetRefShapeLabel(aDatumL, aShapeL, aNullSeq);
3745     Handle(XCAFDoc_Datum) aDatumAttr;
3746     aDatumL.FindAttribute(XCAFDoc_Datum::GetID(), aDatumAttr);
3747     Handle(XCAFDimTolObjects_DatumObject) anObject = aDatumAttr->GetObject();
3748     TCollection_AsciiString aDatumName = anObject->GetName()->String();
3749     TCollection_AsciiString aDatumTargetId = TCollection_AsciiString(anObject->GetDatumTargetNumber());
3750     if (!aNameIdMap.Add(aDatumName.Cat(aDatumTargetId)))
3751       continue;
3752     Handle(Standard_Transient) aWrittenDatum;
3753     Standard_Boolean isFirstDT = !aDatumMap.Find(aDatumName, aWrittenDatum);
3754     Handle(StepDimTol_Datum) aDatum = WriteDatumAP242(WS, aShapeL, aDatumL, isFirstDT, 
3755                                                       Handle(StepDimTol_Datum)::DownCast (aWrittenDatum));
3756     // Add created Datum into Map
3757     aDatumMap.Bind(aDatumName, aDatum);
3758   }
3759
3760   //----------------- //
3761   // write Dimensions //
3762   //------------------//
3763   aDGTLabels.Clear();
3764   DGTTool->GetDimensionLabels(aDGTLabels);
3765   // Auxiliary entities for derived geometry
3766   Handle(StepRepr_ConstructiveGeometryRepresentation) aCGRepr =
3767     new StepRepr_ConstructiveGeometryRepresentation();
3768   Handle(StepRepr_ConstructiveGeometryRepresentationRelationship) aCGReprRel =
3769     new StepRepr_ConstructiveGeometryRepresentationRelationship();
3770   NCollection_Vector<Handle(StepGeom_CartesianPoint)> aConnectionPnts;
3771   Handle(StepRepr_RepresentationContext) dummyRC;
3772   Handle(StepAP242_GeometricItemSpecificUsage) dummyGISU;
3773   for (Standard_Integer i = 1; i <= aDGTLabels.Length(); i++) {
3774     TDF_Label aDimensionL = aDGTLabels.Value(i);
3775     TDF_LabelSequence aFirstShapeL, aSecondShapeL;
3776     Handle(XCAFDoc_Dimension) aDimAttr;
3777     if (!aDimensionL.FindAttribute(XCAFDoc_Dimension::GetID(),aDimAttr)) 
3778       continue;
3779     Handle(XCAFDimTolObjects_DimensionObject) anObject = aDimAttr->GetObject();
3780     if (anObject.IsNull())
3781       continue;
3782     if (anObject->GetType() == XCAFDimTolObjects_DimensionType_CommonLabel)
3783     {
3784       Handle(StepRepr_ShapeAspect) aSA = new StepRepr_ShapeAspect();
3785       aSA->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), myGDTCommonPDS, StepData_LTrue);
3786       aModel->AddWithRefs(aSA);
3787       WritePresentation(WS, anObject->GetPresentation(), anObject->GetPresentationName(), anObject->HasPlane(),
3788         Standard_False, anObject->GetPlane(), anObject->GetPointTextAttach(), aSA);
3789     }
3790
3791     if (!DGTTool->GetRefShapeLabel(aDimensionL, aFirstShapeL, aSecondShapeL))
3792       continue;
3793
3794     // Write links with shapes
3795     Handle(StepRepr_ShapeAspect) aFirstSA, aSecondSA;
3796     if (aFirstShapeL.Length() == 1) {
3797       TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(aFirstShapeL.Value(1));
3798       aFirstSA = WriteShapeAspect(WS, aDimensionL, aShape, dummyRC, dummyGISU);
3799       if (aRC.IsNull() && !dummyRC.IsNull())
3800         aRC = dummyRC;
3801     }
3802     else if (aFirstShapeL.Length() > 1) {
3803       Handle(StepRepr_CompositeShapeAspect) aCSA;
3804       for (Standard_Integer shIt = 1; shIt <= aFirstShapeL.Length(); shIt++) {
3805         TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(aFirstShapeL.Value(shIt));
3806         Handle(StepRepr_ShapeAspect) aSA = WriteShapeAspect(WS, aDimensionL, aShape, dummyRC, dummyGISU);
3807         if (aSA.IsNull())
3808           continue;
3809         if (aCSA.IsNull()) {
3810           aCSA = new StepRepr_CompositeShapeAspect();
3811           aCSA->Init(aSA->Name(), aSA->Description(), aSA->OfShape(), aSA->ProductDefinitional());
3812           aModel->AddWithRefs(aCSA);
3813         }
3814         Handle(StepRepr_ShapeAspectRelationship) aSAR = new StepRepr_ShapeAspectRelationship();
3815         aSAR->Init(new TCollection_HAsciiString(), Standard_False, new TCollection_HAsciiString(), aCSA, aSA);
3816         aModel->AddWithRefs(aSAR);
3817         if (aRC.IsNull() && !dummyRC.IsNull())
3818           aRC = dummyRC;
3819       }
3820       aFirstSA = aCSA;
3821     }
3822     if (aSecondShapeL.Length() == 1) {
3823       TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(aSecondShapeL.Value(1));
3824       aSecondSA = WriteShapeAspect(WS, aDimensionL, aShape, dummyRC, dummyGISU);
3825       if (aRC.IsNull() && !dummyRC.IsNull())
3826         aRC = dummyRC;
3827     }
3828     else if (aSecondShapeL.Length() > 1) {
3829       Handle(StepRepr_CompositeShapeAspect) aCSA;
3830       for (Standard_Integer shIt = 1; shIt <= aSecondShapeL.Length(); shIt++) {
3831         TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(aSecondShapeL.Value(shIt));
3832         Handle(StepRepr_ShapeAspect) aSA = WriteShapeAspect(WS, aDimensionL, aShape, dummyRC, dummyGISU);
3833         if (aCSA.IsNull() && !aSA.IsNull())
3834           aCSA = new StepRepr_CompositeShapeAspect();
3835           aCSA->Init(aSA->Name(), aSA->Description(), aSA->OfShape(), aSA->ProductDefinitional());
3836         if (!aSA.IsNull()) {
3837           Handle(StepRepr_ShapeAspectRelationship) aSAR = new StepRepr_ShapeAspectRelationship();
3838           aSAR->Init(new TCollection_HAsciiString(), Standard_False, new TCollection_HAsciiString(), aCSA, aSA);
3839           aModel->AddWithRefs(aSAR);
3840         }
3841         if (aRC.IsNull() && !dummyRC.IsNull())
3842           aRC = dummyRC;
3843       }
3844       aSecondSA = aCSA;
3845     }
3846
3847     if (anObject->GetType() == XCAFDimTolObjects_DimensionType_DimensionPresentation)
3848     {
3849       WritePresentation(WS, anObject->GetPresentation(), anObject->GetPresentationName(), anObject->HasPlane(),
3850         Standard_False, anObject->GetPlane(), anObject->GetPointTextAttach(), aFirstSA);
3851       continue;
3852     }
3853
3854     // Write dimensions
3855     StepShape_DimensionalCharacteristic aDimension;
3856     if (anObject->HasPoint() || anObject->HasPoint2())
3857       WriteDerivedGeometry(WS, anObject, aCGRepr, aFirstSA, aSecondSA, aConnectionPnts);
3858     XCAFDimTolObjects_DimensionType aDimType = anObject->GetType();
3859     if (STEPCAFControl_GDTProperty::IsDimensionalLocation(aDimType)) {
3860       // Dimensional_Location
3861       Handle(StepShape_DimensionalLocation) aDim = new StepShape_DimensionalLocation();
3862       aDim->Init(STEPCAFControl_GDTProperty::GetDimTypeName(aDimType), Standard_False, NULL, aFirstSA, aSecondSA);
3863       aDimension.SetValue(aDim);
3864     }
3865     else if (aDimType == XCAFDimTolObjects_DimensionType_Location_Angular) {
3866       // Angular_Location
3867       Handle(StepShape_AngularLocation) aDim = new StepShape_AngularLocation();
3868       StepShape_AngleRelator aRelator = StepShape_Equal;
3869       if (anObject->HasQualifier()) {
3870         XCAFDimTolObjects_DimensionQualifier aQualifier = anObject->GetQualifier();
3871         switch (aQualifier) {
3872           case XCAFDimTolObjects_DimensionQualifier_Min: aRelator = StepShape_Small;
3873             break;
3874           case XCAFDimTolObjects_DimensionQualifier_Max: aRelator = StepShape_Large;
3875             break;
3876           default: aRelator = StepShape_Equal;
3877         }
3878       }
3879       aDim->Init(new TCollection_HAsciiString(), Standard_False, NULL, aFirstSA, aSecondSA, aRelator);
3880       aDimension.SetValue(aDim);
3881     }
3882     else if (aDimType == XCAFDimTolObjects_DimensionType_Location_WithPath) {
3883       // Dimensional_Location_With_Path
3884       Handle(StepShape_DimensionalLocationWithPath) aDim = new StepShape_DimensionalLocationWithPath();
3885       Handle(StepRepr_ShapeAspect) aPathSA = WriteShapeAspect(WS, aDimensionL, anObject->GetPath(), dummyRC, dummyGISU);
3886       aDim->Init(new TCollection_HAsciiString(), Standard_False, NULL, aFirstSA, aSecondSA, aPathSA);
3887       aDimension.SetValue(aDim);
3888     }
3889     else if (STEPCAFControl_GDTProperty::IsDimensionalSize(aDimType)) {
3890       // Dimensional_Size
3891       Handle(StepShape_DimensionalSize) aDim = new StepShape_DimensionalSize();
3892       aDim->Init(aFirstSA, STEPCAFControl_GDTProperty::GetDimTypeName(aDimType));
3893       aDimension.SetValue(aDim);
3894     }
3895     else if (aDimType == XCAFDimTolObjects_DimensionType_Size_Angular) {
3896       // Angular_Size
3897       Handle(StepShape_AngularSize) aDim = new StepShape_AngularSize();
3898       StepShape_AngleRelator aRelator = StepShape_Equal;
3899       if (anObject->HasQualifier()) {
3900         XCAFDimTolObjects_DimensionQualifier aQualifier = anObject->GetQualifier();
3901         switch (aQualifier) {
3902           case XCAFDimTolObjects_DimensionQualifier_Min: aRelator = StepShape_Small;
3903             break;
3904           case XCAFDimTolObjects_DimensionQualifier_Max: aRelator = StepShape_Large;
3905             break;
3906           default: aRelator = StepShape_Equal;
3907         }
3908       }
3909       aDim->Init(aFirstSA, new TCollection_HAsciiString(), aRelator);
3910       aDimension.SetValue(aDim);
3911     }
3912     else if (aDimType == XCAFDimTolObjects_DimensionType_Size_WithPath) {
3913       // Dimensional_Size_With_Path
3914       Handle(StepShape_DimensionalSizeWithPath) aDim = new StepShape_DimensionalSizeWithPath();
3915       Handle(StepRepr_ShapeAspect) aPathSA = WriteShapeAspect(WS, aDimensionL, anObject->GetPath(), dummyRC, dummyGISU);
3916       aDim->Init(aFirstSA, new TCollection_HAsciiString(), aPathSA);
3917       aDimension.SetValue(aDim);
3918     }
3919
3920     // Write values
3921     WriteDimValues(WS, anObject, aRC, aDimension);
3922     //Annotation plane and Presentation
3923     WritePresentation(WS, anObject->GetPresentation(), anObject->GetPresentationName(), Standard_True, anObject->HasPlane(),
3924       anObject->GetPlane(), anObject->GetPointTextAttach(), aDimension.Value());
3925   }
3926   // Write Derived geometry
3927   if (aConnectionPnts.Length() > 0) {
3928     Handle(StepRepr_HArray1OfRepresentationItem) anItems = new StepRepr_HArray1OfRepresentationItem(1, aConnectionPnts.Length());
3929     for (Standard_Integer i = 0; i < aConnectionPnts.Length(); i++)
3930       anItems->SetValue(i + 1, aConnectionPnts(i));
3931     aCGRepr->Init(new TCollection_HAsciiString(), anItems, dummyRC);
3932     aCGReprRel->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), dummyGISU->UsedRepresentation(), aCGRepr);
3933     aModel->AddWithRefs(aCGReprRel);
3934   }
3935
3936   //----------------------------//
3937   // write Geometric Tolerances //
3938   //----------------------------//
3939   aDGTLabels.Clear();
3940   DGTTool->GetGeomToleranceLabels(aDGTLabels);
3941   for (Standard_Integer i = 1; i <= aDGTLabels.Length(); i++) {
3942     TDF_Label aGeomTolL = aDGTLabels.Value(i);
3943     TDF_LabelSequence aFirstShapeL, aNullSeqL;
3944     if (!DGTTool->GetRefShapeLabel(aGeomTolL, aFirstShapeL, aNullSeqL))
3945       continue;
3946     TDF_LabelSequence aDatumSeq;
3947     DGTTool->GetDatumWithObjectOfTolerLabels(aGeomTolL, aDatumSeq);
3948     Handle(StepDimTol_HArray1OfDatumSystemOrReference) aDatumSystem;
3949     if (aDatumSeq.Length() > 0)
3950       aDatumSystem = WriteDatumSystem(WS, aGeomTolL, aDatumSeq, aDatumMap, aRC);
3951     WriteGeomTolerance(WS, aFirstShapeL, aGeomTolL, aDatumSystem, aRC);
3952   }
3953
3954   // Write Draughting model for Annotation Planes
3955   if (myGDTAnnotations.Length() == 0)
3956     return Standard_True;
3957
3958   Handle(StepRepr_HArray1OfRepresentationItem) aItems =
3959     new StepRepr_HArray1OfRepresentationItem(1, myGDTAnnotations.Length());
3960   for (Standard_Integer i = 1; i <= aItems->Length(); i++) {
3961     aItems->SetValue(i, myGDTAnnotations.Value(i - 1));
3962   }
3963   myGDTPresentationDM->Init(new TCollection_HAsciiString(), aItems, aRC);
3964   aModel->AddWithRefs(myGDTPresentationDM);
3965
3966   return Standard_True;
3967 }
3968
3969 //=======================================================================
3970 //function : FindPDSforRI
3971 //purpose  : auxilary: 
3972 //=======================================================================
3973 static Standard_Boolean FindPDSforRI(const Interface_Graph &aGraph,
3974                                      const Handle(Standard_Transient) &ent,
3975                                      Handle(StepRepr_ProductDefinitionShape) &PDS,
3976                                      Handle(StepRepr_RepresentationContext) &RC)
3977 {
3978   if(ent.IsNull() || !ent->IsKind(STANDARD_TYPE(StepRepr_RepresentationItem)))
3979     return Standard_False;
3980   Interface_EntityIterator subs = aGraph.Sharings(ent);
3981   for(subs.Start(); subs.More() && PDS.IsNull(); subs.Next()) {
3982     Handle(StepShape_ShapeRepresentation) SR = 
3983       Handle(StepShape_ShapeRepresentation)::DownCast(subs.Value());
3984     if(SR.IsNull()) continue;
3985     RC = SR->ContextOfItems();
3986     Interface_EntityIterator subs1 = aGraph.Sharings(SR);
3987     for(subs1.Start(); subs1.More() && PDS.IsNull(); subs1.Next()) {
3988       Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
3989         Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs1.Value());
3990       if(SDR.IsNull()) continue;
3991       Handle(StepRepr_PropertyDefinition) PropD = SDR->Definition().PropertyDefinition();
3992       if(PropD.IsNull()) continue;
3993       PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(PropD);
3994     }
3995   }
3996   return Standard_True;
3997 }
3998
3999
4000 //=======================================================================
4001 //function : WriteMaterials
4002 //purpose  : 
4003 //=======================================================================
4004
4005 Standard_Boolean STEPCAFControl_Writer::WriteMaterials (const Handle(XSControl_WorkSession) &WS,
4006                                                         const TDF_LabelSequence  &labels ) const
4007 {
4008   
4009   if ( labels.Length() <=0 ) return Standard_False;
4010
4011   // get working data
4012   const Handle(Interface_InterfaceModel) &Model = WS->Model();
4013   const Handle(XSControl_TransferWriter) &TW = WS->TransferWriter();
4014   const Handle(Transfer_FinderProcess) &FP = TW->FinderProcess();
4015
4016   const Handle(Interface_HGraph) aHGraph = WS->HGraph();
4017   if(aHGraph.IsNull())
4018     return Standard_False;
4019
4020   Interface_Graph aGraph = WS->HGraph()->Graph();
4021   Handle(XCAFDoc_ShapeTool) ShTool = XCAFDoc_DocumentTool::ShapeTool( labels(1) );
4022   if(ShTool.IsNull() ) return Standard_False;
4023   Handle(XCAFDoc_MaterialTool) MatTool = XCAFDoc_DocumentTool::MaterialTool( labels(1) );
4024   if(MatTool.IsNull() ) return Standard_False;
4025
4026   STEPConstruct_DataMapOfAsciiStringTransient MapDRI,MapMRI;
4027   TDF_LabelSequence TopLabels;
4028   ShTool->GetShapes(TopLabels);
4029   for(Standard_Integer i=1; i<=TopLabels.Length(); i++) {
4030     TDF_Label ShL = TopLabels.Value(i);
4031     Handle(TDataStd_TreeNode) Node;
4032     if( ShL.FindAttribute(XCAFDoc::MaterialRefGUID(),Node) && Node->HasFather() ) {
4033       // find PDS for current shape
4034       TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(ShL);
4035       TopLoc_Location Loc;
4036       TColStd_SequenceOfTransient seqRI;
4037       FindEntities( FP, aShape, Loc, seqRI );
4038       if(seqRI.Length()<=0) continue;
4039       Handle(StepRepr_ProductDefinitionShape) PDS;
4040       Handle(StepRepr_RepresentationContext) RC;
4041       Handle(Standard_Transient) ent = seqRI.Value(1);
4042       FindPDSforRI(aGraph,ent,PDS,RC);
4043       if(PDS.IsNull()) continue;
4044       Handle(StepBasic_ProductDefinition) aProdDef = 
4045         PDS->Definition().ProductDefinition();
4046       if(aProdDef.IsNull())
4047         continue;
4048       // write material entities
4049       TDF_Label MatL = Node->Father()->Label();
4050       Handle(TCollection_HAsciiString) aName;
4051       Handle(TCollection_HAsciiString) aDescription;
4052       Standard_Real aDensity;
4053       Handle(TCollection_HAsciiString) aDensName;
4054       Handle(TCollection_HAsciiString) aDensValType;
4055       Handle(StepRepr_Representation) RepDRI;
4056       Handle(StepRepr_Representation) RepMRI;
4057       if(MatTool->GetMaterial(MatL,aName,aDescription,aDensity,aDensName,aDensValType)) {
4058         if(aName->Length()==0) continue;
4059         TCollection_AsciiString aKey(aName->ToCString());
4060         if(MapDRI.IsBound(aKey)) {
4061           RepDRI = Handle(StepRepr_Representation)::DownCast(MapDRI.Find(aKey));
4062           if(MapMRI.IsBound(aKey)) {
4063             RepMRI = Handle(StepRepr_Representation)::DownCast(MapMRI.Find(aKey));
4064           }
4065         }
4066         else {
4067           // write DRI
4068           Handle(StepRepr_DescriptiveRepresentationItem) DRI = new StepRepr_DescriptiveRepresentationItem;
4069           DRI->Init(aName,aDescription);
4070           Handle(StepRepr_HArray1OfRepresentationItem) HARI = new StepRepr_HArray1OfRepresentationItem(1,1);
4071           HARI->SetValue(1,DRI);
4072           RepDRI = new StepRepr_Representation();
4073           RepDRI->Init(new TCollection_HAsciiString("material name"),HARI,RC);
4074           Model->AddWithRefs(RepDRI);
4075           // write MRI
4076           if( aDensity > 0 ) {
4077             // mass
4078             Handle(StepBasic_SiUnitAndMassUnit) SMU = new StepBasic_SiUnitAndMassUnit;
4079             SMU->SetName(StepBasic_sunGram);
4080             Handle(StepBasic_DerivedUnitElement) DUE1 = new StepBasic_DerivedUnitElement;
4081             DUE1->Init(SMU,3.0);
4082             // length
4083             Handle(StepBasic_SiUnitAndLengthUnit) SLU = new StepBasic_SiUnitAndLengthUnit;
4084             SLU->Init(Standard_True,StepBasic_spCenti,StepBasic_sunMetre);
4085             Handle(StepBasic_DerivedUnitElement) DUE2 = new StepBasic_DerivedUnitElement;
4086             DUE2->Init(SLU,2.0);
4087             // other
4088             Handle(StepBasic_HArray1OfDerivedUnitElement) HADUE = new StepBasic_HArray1OfDerivedUnitElement(1,2);
4089             HADUE->SetValue(1,DUE1);
4090             HADUE->SetValue(2,DUE2);
4091             Handle(StepBasic_DerivedUnit) DU = new StepBasic_DerivedUnit;
4092             DU->Init(HADUE);
4093             Model->AddWithRefs(DU);
4094             StepBasic_Unit aUnit;
4095             aUnit.SetValue(DU);
4096             Handle(StepBasic_MeasureValueMember) MVM = new StepBasic_MeasureValueMember;
4097             MVM->SetName(aDensValType->ToCString());
4098             MVM->SetReal(aDensity);
4099             Handle(StepRepr_MeasureRepresentationItem) MRI = new StepRepr_MeasureRepresentationItem;
4100             MRI->Init(aDensName,MVM,aUnit);
4101             HARI = new StepRepr_HArray1OfRepresentationItem(1,1);
4102             HARI->SetValue(1,MRI);
4103             RepMRI = new StepRepr_Representation();
4104             RepMRI->Init(new TCollection_HAsciiString("density"),HARI,RC);
4105             Model->AddWithRefs(RepMRI);
4106           }
4107           //WriteNewMaterial(Model,aName,aDescription,aDensity,aDensName,aDensValType,RC,RepDRI,RepMRI);
4108           MapDRI.Bind(aKey,RepDRI);
4109           if ( !RepMRI.IsNull() ) MapMRI.Bind (aKey, RepMRI);
4110         }
4111       }
4112       
4113       if( !RepDRI.IsNull() )
4114       {
4115         StepRepr_CharacterizedDefinition CD1;
4116         CD1.SetValue(aProdDef);
4117         Handle(StepRepr_PropertyDefinition) PropD1 = new StepRepr_PropertyDefinition;
4118         PropD1->Init(new TCollection_HAsciiString("material property"),Standard_True,
4119           new TCollection_HAsciiString("material name"),CD1);
4120         Model->AddWithRefs(PropD1);
4121         StepRepr_RepresentedDefinition RD1;
4122         RD1.SetValue(PropD1);
4123         Handle(StepRepr_PropertyDefinitionRepresentation) PDR1 =
4124           new StepRepr_PropertyDefinitionRepresentation;
4125         PDR1->Init(RD1,RepDRI);
4126         Model->AddWithRefs(PDR1);
4127
4128         if( !RepMRI.IsNull() )
4129         {
4130           StepRepr_CharacterizedDefinition CD2;
4131           CD2.SetValue (aProdDef);
4132           Handle (StepRepr_PropertyDefinition) PropD2 = new StepRepr_PropertyDefinition;
4133           PropD2->Init (new TCollection_HAsciiString ("material property"), Standard_True,
4134             new TCollection_HAsciiString ("density"), CD2);
4135           Model->AddWithRefs (PropD2);
4136           StepRepr_RepresentedDefinition RD2;
4137           RD2.SetValue (PropD2);
4138           Handle (StepRepr_PropertyDefinitionRepresentation) PDR2 =
4139             new StepRepr_PropertyDefinitionRepresentation;
4140           PDR2->Init (RD2, RepMRI);
4141           Model->AddWithRefs (PDR2);
4142         }
4143       }
4144     }
4145   }
4146
4147   return Standard_True;
4148 }
4149
4150
4151 //=======================================================================
4152 //function : SetColorMode
4153 //purpose  : 
4154 //=======================================================================
4155
4156 void STEPCAFControl_Writer::SetColorMode (const Standard_Boolean colormode)
4157 {
4158   myColorMode = colormode;
4159 }
4160
4161
4162 //=======================================================================
4163 //function : GetColorMode
4164 //purpose  : 
4165 //=======================================================================
4166
4167 Standard_Boolean STEPCAFControl_Writer::GetColorMode () const
4168 {
4169   return myColorMode;
4170 }
4171
4172
4173 //=======================================================================
4174 //function : SetNameMode
4175 //purpose  : 
4176 //=======================================================================
4177
4178 void STEPCAFControl_Writer::SetNameMode (const Standard_Boolean namemode)
4179 {
4180   myNameMode = namemode;
4181 }
4182
4183
4184 //=======================================================================
4185 //function : GetNameMode
4186 //purpose  : 
4187 //=======================================================================
4188
4189 Standard_Boolean STEPCAFControl_Writer::GetNameMode () const
4190 {
4191   return myNameMode;
4192 }
4193
4194
4195 //=======================================================================
4196 //function : SetLayerMode
4197 //purpose  : 
4198 //=======================================================================
4199
4200 void STEPCAFControl_Writer::SetLayerMode (const Standard_Boolean layermode)
4201 {
4202   myLayerMode = layermode;
4203 }
4204
4205
4206 //=======================================================================
4207 //function : GetLayerMode
4208 //purpose  : 
4209 //=======================================================================
4210
4211 Standard_Boolean STEPCAFControl_Writer::GetLayerMode () const
4212 {
4213   return myLayerMode;
4214 }
4215
4216
4217 //=======================================================================
4218 //function : SetPropsMode
4219 //purpose  : 
4220 //=======================================================================
4221
4222 void STEPCAFControl_Writer::SetPropsMode (const Standard_Boolean propsmode)
4223 {
4224   myPropsMode = propsmode;
4225 }
4226
4227
4228 //=======================================================================
4229 //function : GetPropsMode
4230 //purpose  : 
4231 //=======================================================================
4232
4233 Standard_Boolean STEPCAFControl_Writer::GetPropsMode () const
4234 {
4235   return myPropsMode;
4236 }
4237
4238
4239 //=======================================================================
4240 //function : SetSHUOMode
4241 //purpose  : 
4242 //=======================================================================
4243
4244 void STEPCAFControl_Writer::SetSHUOMode (const Standard_Boolean mode)
4245 {
4246   mySHUOMode = mode;
4247 }
4248
4249
4250 //=======================================================================
4251 //function : GetSHUOMode
4252 //purpose  : 
4253 //=======================================================================
4254
4255 Standard_Boolean STEPCAFControl_Writer::GetSHUOMode () const
4256 {
4257   return mySHUOMode;
4258 }
4259
4260
4261 //=======================================================================
4262 //function : SetDimTolMode
4263 //purpose  : 
4264 //=======================================================================
4265
4266 void STEPCAFControl_Writer::SetDimTolMode(const Standard_Boolean dimtolmode)
4267 {
4268   myDGTMode = dimtolmode;
4269 }
4270
4271
4272 //=======================================================================
4273 //function : GetDimTolMode
4274 //purpose  : 
4275 //=======================================================================
4276
4277 Standard_Boolean STEPCAFControl_Writer::GetDimTolMode() const
4278 {
4279   return myDGTMode;
4280 }
4281
4282
4283 //=======================================================================
4284 //function : SetMaterialMode
4285 //purpose  : 
4286 //=======================================================================
4287
4288 void STEPCAFControl_Writer::SetMaterialMode(const Standard_Boolean matmode)
4289 {
4290   myMatMode = matmode;
4291 }
4292
4293
4294 //=======================================================================
4295 //function : GetMaterialMode
4296 //purpose  : 
4297 //=======================================================================
4298
4299 Standard_Boolean STEPCAFControl_Writer::GetMaterialMode() const
4300 {
4301   return myMatMode;
4302 }