09aa5f3162f7bd8c208b59887e77f1775671b559
[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_DictionaryOfExternFile.hxx>
51 #include <STEPCAFControl_ExternFile.hxx>
52 #include <STEPCAFControl_IteratorOfDictionaryOfExternFile.hxx>
53 #include <STEPCAFControl_Writer.hxx>
54 #include <STEPConstruct.hxx>
55 #include <STEPConstruct_DataMapOfAsciiStringTransient.hxx>
56 #include <STEPConstruct_DataMapOfPointTransient.hxx>
57 #include <STEPConstruct_ExternRefs.hxx>
58 #include <STEPCAFControl_GDTProperty.hxx>
59 #include <STEPConstruct_Styles.hxx>
60 #include <STEPConstruct_ValidationProps.hxx>
61 #include <STEPControl_StepModelType.hxx>
62 #include <STEPControl_Writer.hxx>
63 #include <StepData_Logical.hxx>
64 #include <StepData_StepModel.hxx>
65 #include <StepDimTol_AngularityTolerance.hxx>
66 #include <StepDimTol_CircularRunoutTolerance.hxx>
67 #include <StepDimTol_CoaxialityTolerance.hxx>
68 #include <StepDimTol_ConcentricityTolerance.hxx>
69 #include <StepDimTol_CylindricityTolerance.hxx>
70 #include <StepDimTol_Datum.hxx>
71 #include <StepDimTol_DatumFeature.hxx>
72 #include <StepDimTol_DatumReference.hxx>
73 #include <StepDimTol_DatumReferenceElement.hxx>
74 #include <StepDimTol_DatumSystem.hxx>
75 #include <StepDimTol_DatumSystemOrReference.hxx>
76 #include <StepDimTol_DatumTarget.hxx>
77 #include <StepDimTol_FlatnessTolerance.hxx>
78 #include <StepDimTol_GeometricToleranceType.hxx>
79 #include <StepDimTol_GeometricToleranceWithDatumReference.hxx>
80 #include <StepDimTol_GeometricToleranceWithModifiers.hxx>
81 #include <StepDimTol_GeoTolAndGeoTolWthDatRef.hxx>
82 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol.hxx>
83 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod.hxx>
84 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol.hxx>
85 #include <StepDimTol_GeoTolAndGeoTolWthMaxTol.hxx>
86 #include <StepDimTol_GeoTolAndGeoTolWthMod.hxx>
87 #include <StepDimTol_HArray1OfDatumReference.hxx>
88 #include <StepDimTol_HArray1OfDatumReferenceElement.hxx>
89 #include <StepDimTol_HArray1OfDatumReferenceModifier.hxx>
90 #include <StepDimTol_HArray1OfDatumSystemOrReference.hxx>
91 #include <StepDimTol_LineProfileTolerance.hxx>
92 #include <StepDimTol_ModifiedGeometricTolerance.hxx>
93 #include <StepDimTol_ParallelismTolerance.hxx>
94 #include <StepDimTol_PerpendicularityTolerance.hxx>
95 #include <StepDimTol_PlacedDatumTargetFeature.hxx>
96 #include <StepDimTol_PositionTolerance.hxx>
97 #include <StepDimTol_RoundnessTolerance.hxx>
98 #include <StepDimTol_RunoutZoneDefinition.hxx>
99 #include <StepDimTol_RunoutZoneOrientation.hxx>
100 #include <StepDimTol_StraightnessTolerance.hxx>
101 #include <StepDimTol_SurfaceProfileTolerance.hxx>
102 #include <StepDimTol_SymmetryTolerance.hxx>
103 #include <StepDimTol_ToleranceZone.hxx>
104 #include <StepDimTol_ToleranceZoneForm.hxx>
105 #include <StepDimTol_TotalRunoutTolerance.hxx>
106 #include <StepGeom_Axis2Placement3d.hxx>
107 #include <StepGeom_CartesianPoint.hxx>
108 #include <StepGeom_Direction.hxx>
109 #include <StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext.hxx>
110 #include <StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx.hxx>
111 #include <StepGeom_Plane.hxx>
112 #include <StepGeom_Surface.hxx>
113 #include <StepRepr_CompGroupShAspAndCompShAspAndDatumFeatAndShAsp.hxx>
114 #include <StepRepr_CompositeShapeAspect.hxx>
115 #include <StepRepr_DescriptiveRepresentationItem.hxx>
116 #include <StepRepr_FeatureForDatumTargetRelationship.hxx>
117 #include <StepRepr_HArray1OfRepresentationItem.hxx>
118 #include <StepRepr_MeasureRepresentationItem.hxx>
119 #include <StepRepr_NextAssemblyUsageOccurrence.hxx>
120 #include <StepRepr_ProductDefinitionShape.hxx>
121 #include <StepRepr_PropertyDefinition.hxx>
122 #include <StepRepr_RepresentedDefinition.hxx>
123 #include <StepRepr_Representation.hxx>
124 #include <StepRepr_RepresentationItem.hxx>
125 #include <StepRepr_ReprItemAndLengthMeasureWithUnit.hxx>
126 #include <StepRepr_ReprItemAndLengthMeasureWithUnitAndQRI.hxx>
127 #include <StepRepr_ReprItemAndPlaneAngleMeasureWithUnit.hxx>
128 #include <StepRepr_ReprItemAndPlaneAngleMeasureWithUnitAndQRI.hxx>
129 #include <StepRepr_ShapeAspect.hxx>
130 #include <StepRepr_ShapeAspectRelationship.hxx>
131 #include <StepRepr_SpecifiedHigherUsageOccurrence.hxx>
132 #include <StepRepr_ValueRange.hxx>
133 #include <StepShape_AdvancedFace.hxx>
134 #include <StepShape_AngleRelator.hxx>
135 #include <StepShape_AngularLocation.hxx>
136 #include <StepShape_AngularSize.hxx>
137 #include <StepShape_ConnectedFaceSet.hxx>
138 #include <StepShape_ContextDependentShapeRepresentation.hxx>
139 #include <StepShape_DimensionalCharacteristic.hxx>
140 #include <StepShape_DimensionalCharacteristicRepresentation.hxx>
141 #include <StepShape_DimensionalLocation.hxx>
142 #include <StepShape_DimensionalLocationWithPath.hxx>
143 #include <StepShape_DimensionalSize.hxx>
144 #include <StepShape_DimensionalSizeWithPath.hxx>
145 #include <StepShape_EdgeCurve.hxx>
146 #include <StepShape_EdgeLoop.hxx>
147 #include <StepShape_FaceBound.hxx>
148 #include <StepShape_LimitsAndFits.hxx>
149 #include <StepShape_OrientedEdge.hxx>
150 #include <StepShape_PlusMinusTolerance.hxx>
151 #include <StepShape_QualifiedRepresentationItem.hxx>
152 #include <StepShape_ShapeDefinitionRepresentation.hxx>
153 #include <StepShape_ShapeDimensionRepresentation.hxx>
154 #include <StepShape_ShapeRepresentation.hxx>
155 #include <StepShape_ShapeRepresentationWithParameters.hxx>
156 #include <StepShape_ToleranceValue.hxx>
157 #include <StepShape_TypeQualifier.hxx>
158 #include <StepShape_ValueFormatTypeQualifier.hxx>
159 #include <StepVisual_AnnotationPlane.hxx>
160 #include <StepVisual_CurveStyle.hxx>
161 #include <StepVisual_DraughtingCallout.hxx>
162 #include <StepVisual_DraughtingModel.hxx>
163 #include <StepVisual_HArray1OfInvisibleItem.hxx>
164 #include <StepVisual_HArray1OfLayeredItem.hxx>
165 #include <StepVisual_HArray1OfPresentationStyleAssignment.hxx>
166 #include <StepVisual_HArray1OfPresentationStyleSelect.hxx>
167 #include <StepVisual_Invisibility.hxx>
168 #include <StepVisual_InvisibleItem.hxx>
169 #include <StepVisual_MechanicalDesignGeometricPresentationRepresentation.hxx>
170 #include <StepVisual_NullStyleMember.hxx>
171 #include <StepVisual_PointStyle.hxx>
172 #include <StepVisual_PresentationLayerAssignment.hxx>
173 #include <StepVisual_PresentationRepresentation.hxx>
174 #include <StepVisual_PresentationStyleAssignment.hxx>
175 #include <StepVisual_PresentationStyleByContext.hxx>
176 #include <StepVisual_StyledItem.hxx>
177 #include <StepVisual_SurfaceStyleUsage.hxx>
178 #include <StepVisual_TessellatedAnnotationOccurrence.hxx>
179 #include <StepVisual_TessellatedGeometricSet.hxx>
180 #include <TCollection_AsciiString.hxx>
181 #include <TCollection_HAsciiString.hxx>
182 #include <TColStd_HArray1OfReal.hxx>
183 #include <TColStd_HArray1OfTransient.hxx>
184 #include <TColStd_HSequenceOfTransient.hxx>
185 #include <TColStd_MapOfAsciiString.hxx>
186 #include <TColStd_MapOfTransient.hxx>
187 #include <TDataStd_Name.hxx>
188 #include <TDataStd_TreeNode.hxx>
189 #include <TDataStd_UAttribute.hxx>
190 #include <TDF_AttributeSequence.hxx>
191 #include <TDF_ChildIterator.hxx>
192 #include <TDF_Label.hxx>
193 #include <TDF_LabelSequence.hxx>
194 #include <TDF_Tool.hxx>
195 #include <TDocStd_Document.hxx>
196 #include <TopoDS_Compound.hxx>
197 #include <TopoDS_Iterator.hxx>
198 #include <TopoDS_Shape.hxx>
199 #include <TopTools_MapOfShape.hxx>
200 #include <TopTools_SequenceOfShape.hxx>
201 #include <Transfer_ActorOfFinderProcess.hxx>
202 #include <Transfer_Binder.hxx>
203 #include <Transfer_FinderProcess.hxx>
204 #include <Transfer_TransientListBinder.hxx>
205 #include <TransferBRep.hxx>
206 #include <TransferBRep_ShapeMapper.hxx>
207 #include <XCAFDimTolObjects_DatumObject.hxx>
208 #include <XCAFDimTolObjects_DimensionFormVariance.hxx>
209 #include <XCAFDimTolObjects_DimensionGrade.hxx>
210 #include <XCAFDimTolObjects_DimensionObject.hxx>
211 #include <XCAFDimTolObjects_DimensionModif.hxx>
212 #include <XCAFDimTolObjects_DimensionModifiersSequence.hxx>
213 #include <XCAFDimTolObjects_DimensionQualifier.hxx>
214 #include <XCAFDimTolObjects_GeomToleranceObject.hxx>
215 #include <XCAFDoc.hxx>
216 #include <XCAFDoc_Area.hxx>
217 #include <XCAFDoc_Centroid.hxx>
218 #include <XCAFDoc_ColorTool.hxx>
219 #include <XCAFDoc_Datum.hxx>
220 #include <XCAFDoc_Dimension.hxx>
221 #include <XCAFDoc_DimTol.hxx>
222 #include <XCAFDoc_DimTolTool.hxx>
223 #include <XCAFDoc_DocumentTool.hxx>
224 #include <XCAFDoc_GeomTolerance.hxx>
225 #include <XCAFDoc_GraphNode.hxx>
226 #include <XCAFDoc_LayerTool.hxx>
227 #include <XCAFDoc_Material.hxx>
228 #include <XCAFDoc_MaterialTool.hxx>
229 #include <XCAFDoc_ShapeTool.hxx>
230 #include <XCAFDoc_Volume.hxx>
231 #include <XCAFPrs.hxx>
232 #include <XCAFPrs_DataMapIteratorOfDataMapOfStyleShape.hxx>
233 #include <XCAFPrs_DataMapOfShapeStyle.hxx>
234 #include <XCAFPrs_DataMapOfStyleShape.hxx>
235 #include <XCAFPrs_Style.hxx>
236 #include <XSControl_TransferWriter.hxx>
237 #include <XSControl_WorkSession.hxx>
238
239 static NCollection_Vector<Handle(StepVisual_AnnotationPlane)> gdtAnnotationPlanes;
240 static Handle(StepVisual_DraughtingModel) gdtPresentationDM;
241 static Handle(StepVisual_HArray1OfPresentationStyleAssignment) gdtPrsCurveStyle;
242
243 // added by skl 15.01.2004 for D&GT writing
244 //#include <StepRepr_CompoundItemDefinition.hxx>
245 //#include <StepRepr_CompoundItemDefinitionMember.hxx>
246 // added by skl 12.02.2004 for writing materials
247 //=======================================================================
248 //function : GetLabelName
249 //purpose  : auxilary function: take name of label and append it to str
250 //=======================================================================
251 static Standard_Boolean GetLabelName (const TDF_Label &L, Handle(TCollection_HAsciiString) &str)
252 {
253   Handle(TDataStd_Name) N;
254   if ( ! L.FindAttribute ( TDataStd_Name::GetID(), N ) ) return Standard_False;
255   TCollection_ExtendedString name = N->Get();
256   if ( name.Length() <=0 ) return Standard_False;
257
258   // set name, converting it to Ascii and removing spaces
259   TCollection_AsciiString buf ( name, '?' );
260   buf.LeftAdjust();
261   buf.RightAdjust();
262   buf.ChangeAll(' ','_');
263   str->AssignCat ( buf.ToCString() );
264   return Standard_True;
265 }
266
267
268 //=======================================================================
269 //function : STEPCAFControl_Writer
270 //purpose  :
271 //=======================================================================
272
273 STEPCAFControl_Writer::STEPCAFControl_Writer () :
274        myColorMode( Standard_True ),
275        myNameMode ( Standard_True ),
276        myLayerMode( Standard_True ),
277        myPropsMode( Standard_True ),
278        mySHUOMode ( Standard_True ),
279        myDGTMode  ( Standard_True ),
280        myMatMode  ( Standard_True )
281 {
282   STEPCAFControl_Controller::Init();
283   Handle(XSControl_WorkSession) WS = new XSControl_WorkSession;
284   Init ( WS );
285 }
286
287
288 //=======================================================================
289 //function : STEPCAFControl_Writer
290 //purpose  :
291 //=======================================================================
292
293 STEPCAFControl_Writer::STEPCAFControl_Writer (const Handle(XSControl_WorkSession)& WS,
294                                               const Standard_Boolean scratch)
295 {
296   STEPCAFControl_Controller::Init();
297   Init ( WS, scratch );
298   myColorMode = Standard_True;
299   myNameMode = Standard_True;
300   myLayerMode = Standard_True;
301   myPropsMode = Standard_True;
302   mySHUOMode = Standard_True;
303 }
304
305
306 //=======================================================================
307 //function : Init
308 //purpose  :
309 //=======================================================================
310
311 void STEPCAFControl_Writer::Init (const Handle(XSControl_WorkSession)& WS,
312                                   const Standard_Boolean scratch)
313 {
314   WS->SelectNorm ( "STEP" );
315   myWriter.SetWS (WS,scratch);
316   myFiles = new STEPCAFControl_DictionaryOfExternFile;
317   myLabEF.Clear();
318   myLabels.Clear();
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   STEPCAFControl_IteratorOfDictionaryOfExternFile 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 Handle(STEPCAFControl_DictionaryOfExternFile) &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.IsNull() || ! myFiles->HasItem ( name ) )
463     return Standard_False;
464   ef = myFiles->Item ( 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     MoniTool_DataMapIteratorOfDataMapOfShapeTransient anItr(myMapCompMDGPR);
641     for (; anItr.More(); anItr.Next()) {
642       Handle(Interface_InterfaceModel) Model = writer.WS()->Model();
643       Model->AddWithRefs( anItr.Value() );
644     }
645   }
646   
647   if ( multi ) { // external refs
648     WriteExternRefs ( writer.WS(), sublabels );
649   }
650
651   // write validation props
652 //  if ( multi && ap ==3 ) {
653 //      Interface_Static::SetCVal ("write.step.schema", "AP214DIS");
654 //  }
655   if ( GetPropsMode() ) 
656     WriteValProps ( writer.WS(), sublabels, multi );
657
658   Interface_Static::SetIVal ("write.step.schema", ap);
659
660   // refresh graph
661   writer.WS()->ComputeGraph ( Standard_True );
662
663   /* ================================
664     *  Write names for the sub-shapes
665     * ================================ */
666
667   if ( Interface_Static::IVal("write.stepcaf.subshapes.name") )
668   {
669     Handle(XSControl_TransferWriter) TW = this->ChangeWriter().WS()->TransferWriter();
670     Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
671
672     for ( int i = 1; i <= labels.Length(); i++ )
673     {
674       TDF_Label L = labels.Value(i);
675
676       for ( TDF_ChildIterator it(L, Standard_True); it.More(); it.Next() )
677       {
678         TDF_Label SubL = it.Value();
679
680         // Access name recorded in OCAF TDataStd_Name attribute
681         Handle(TCollection_HAsciiString) hSubName = new TCollection_HAsciiString;
682         if ( !GetLabelName(SubL, hSubName) )
683           continue;
684
685         // Access topological data
686         TopoDS_Shape SubS = XCAFDoc_ShapeTool::GetShape(SubL);
687         if ( SubS.IsNull() )
688           continue;
689
690         // Access the correspondent STEP Representation Item
691         Handle(StepRepr_RepresentationItem) RI;
692         Handle(TransferBRep_ShapeMapper) aShMapper = TransferBRep::ShapeMapper(FP, SubS);
693         if ( !FP->FindTypedTransient(aShMapper, STANDARD_TYPE(StepRepr_RepresentationItem), RI) )
694           continue;
695
696         // Record the name
697         RI->SetName(hSubName);
698       }
699     }
700   }
701
702   return Standard_True;
703 }
704
705
706 //=======================================================================
707 //function : TransferExternFiles
708 //purpose  :
709 //=======================================================================
710
711 TopoDS_Shape STEPCAFControl_Writer::TransferExternFiles (const TDF_Label &L,
712                                                          const STEPControl_StepModelType mode,
713                                                          TDF_LabelSequence &labels,
714                                                          const Standard_CString prefix)
715 {
716   // if label already translated, just return the shape
717   if ( myLabels.IsBound ( L ) ) {
718     return myLabels.Find ( L );
719   }
720
721   TopoDS_Compound C;
722   BRep_Builder B;
723   B.MakeCompound ( C );
724   //labels.Append ( L ); 
725   // if not assembly, write to separate file
726   if ( ! XCAFDoc_ShapeTool::IsAssembly ( L ) && !XCAFDoc_ShapeTool::IsComponent ( L )) {
727     labels.Append ( L );
728     // prepare for transfer
729     Handle(XSControl_WorkSession) newWS = new XSControl_WorkSession;
730     newWS->SelectNorm ( "STEP" );
731     STEPControl_Writer sw ( newWS, Standard_True );
732     TDF_LabelSequence Lseq;
733     Lseq.Append ( L );
734
735     // construct the name for extern file
736     Handle(TCollection_HAsciiString) basename = new TCollection_HAsciiString;
737     if ( prefix && prefix[0] ) basename->AssignCat ( prefix );
738     GetLabelName ( L, basename );
739     Handle(TCollection_HAsciiString) name = new TCollection_HAsciiString ( basename );
740     name->AssignCat ( ".stp" );
741     if ( myFiles->HasItem ( name->ToCString() ) ) { // avoid confusions
742       for ( Standard_Integer k=1; k < 32000; k++ ) {
743         name = new TCollection_HAsciiString ( basename );
744         name->AssignCat ( "_" );
745         name->AssignCat ( TCollection_AsciiString ( k ).ToCString() );
746         name->AssignCat ( ".stp" );
747         if ( ! myFiles->HasItem ( name->ToCString() ) ) break;
748       }
749     }
750
751     // translate and record extern file
752     Handle(STEPCAFControl_ExternFile) EF = new STEPCAFControl_ExternFile;
753     EF->SetWS ( newWS );
754     EF->SetName ( name );
755     EF->SetLabel ( L );
756     Standard_Integer assemblymode = Interface_Static::IVal ("write.step.assembly");
757     Interface_Static::SetCVal ("write.step.assembly", "Off");
758     const Standard_CString multi = 0;
759     EF->SetTransferStatus ( Transfer ( sw, Lseq, mode, multi, Standard_True ) );
760     Interface_Static::SetIVal ("write.step.assembly", assemblymode);
761     myLabEF.Bind ( L, EF );
762     myFiles->SetItem ( name->ToCString(), EF );
763
764     // return empty compound as replacement for the shape
765     myLabels.Bind ( L, C );
766     return C;
767   }
768   TDF_LabelSequence comp;
769   TDF_Label aCurL = L;
770   //if specified shape is component then high-level assembly is considered
771   //to get valid structure with location
772   if ( XCAFDoc_ShapeTool::IsComponent ( L ) )
773   {
774     comp.Append(L);
775     aCurL = L.Father();
776   }
777   // else iterate on components add create structure of empty compounds
778   // representing the assembly
779   else if (XCAFDoc_ShapeTool::IsAssembly ( L ))
780     XCAFDoc_ShapeTool::GetComponents ( L, comp, Standard_False );
781
782   labels.Append ( aCurL );
783   for ( Standard_Integer k=1; k <= comp.Length(); k++ ) {
784     TDF_Label lab = comp(k);
785     TDF_Label ref;
786     if ( ! XCAFDoc_ShapeTool::GetReferredShape ( lab, ref ) ) continue;
787     TopoDS_Shape Scomp = TransferExternFiles ( ref, mode, labels, prefix );
788     Scomp.Location ( XCAFDoc_ShapeTool::GetLocation ( lab ) );
789     B.Add ( C, Scomp );
790   }
791   myLabels.Bind ( aCurL, C );
792   return C;
793 }
794
795
796 //=======================================================================
797 //function : WriteExternRefs
798 //purpose  :
799 //=======================================================================
800
801 Standard_Boolean STEPCAFControl_Writer::WriteExternRefs (const Handle(XSControl_WorkSession) &WS,
802                                                          const TDF_LabelSequence &labels) const
803 {
804   if ( labels.Length() <=0 ) return Standard_False;
805
806   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
807   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
808   STEPConstruct_ExternRefs EFTool ( WS );
809   Standard_Integer schema = Interface_Static::IVal("write.step.schema");
810   for ( Standard_Integer k=1; k <= labels.Length(); k++ ) {
811     TDF_Label lab = labels(k);
812     if ( XCAFDoc_ShapeTool::IsAssembly ( lab ) ) continue; // skip assemblies
813
814     // get extern file
815     Handle(STEPCAFControl_ExternFile) EF;
816     if ( ! ExternFile ( lab, EF ) ) continue; // should never be
817
818     // find SDR
819     if ( ! myLabels.IsBound ( lab ) ) continue; // not recorded as translated, skip
820     TopoDS_Shape S = myLabels.Find ( lab );
821
822     Handle(StepShape_ShapeDefinitionRepresentation) SDR;
823     Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, S );
824     if ( ! FP->FindTypedTransient ( mapper, STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation), SDR ) ) {
825 #ifdef OCCT_DEBUG
826       cout << "Warning: Cannot find SDR for " << S.TShape()->DynamicType()->Name() << endl;
827 #endif
828       continue;
829     }
830
831     // add extern ref
832     const Standard_CString format = (const Standard_CString) ( schema == 3 ? "STEP AP203" : "STEP AP214" );
833     // try to get PD from SDR
834     StepRepr_RepresentedDefinition RD = SDR->Definition();
835     Handle(StepRepr_PropertyDefinition) aPropDef = RD.PropertyDefinition();
836     if (aPropDef.IsNull()) {
837 #ifdef OCCT_DEBUG
838       cout << "Warning: STEPCAFControl_Writer::WriteExternRefs StepRepr_PropertyDefinition is null for " << S.TShape()->DynamicType()->Name() << endl;
839 #endif
840       continue;
841     }
842     StepRepr_CharacterizedDefinition CharDef = aPropDef->Definition();
843     Handle(StepBasic_ProductDefinition) PD = CharDef.ProductDefinition();
844     if (PD.IsNull()) {
845 #ifdef OCCT_DEBUG
846       cout << "Warning: STEPCAFControl_Writer::WriteExternRefs StepBasic_ProductDefinition is null for " << S.TShape()->DynamicType()->Name() << endl;
847 #endif
848       continue;
849     }
850     EFTool.AddExternRef ( EF->GetName()->ToCString(), PD, format );
851   }
852   EFTool.WriteExternRefs(schema);
853   return Standard_True;
854 }
855
856
857 //=======================================================================
858 //function : FindEntities
859 //purpose  : auxilary
860 //=======================================================================
861 static Standard_Integer FindEntities (const Handle(Transfer_FinderProcess) &FP,
862                                       const TopoDS_Shape &S,
863                                       TopLoc_Location &L,
864                                       TColStd_SequenceOfTransient &seqRI)
865 {
866   Handle(StepRepr_RepresentationItem) item = STEPConstruct::FindEntity ( FP, S, L );
867
868   if ( ! item.IsNull() ) {
869     seqRI.Append ( item );
870     return 1;
871   }
872       
873   // may be S was splited during shape processing
874   Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, S );
875   Handle(Transfer_Binder) bnd = FP->Find ( mapper );
876   if ( bnd.IsNull() ) return 0;
877   
878   Handle(Transfer_TransientListBinder) TransientListBinder =
879     //Handle(Transfer_TransientListBinder)::DownCast( bnd->Next(Standard_True) );
880     Handle(Transfer_TransientListBinder)::DownCast( bnd );
881   Standard_Integer nres=0;
882   if ( TransientListBinder.IsNull() && S.ShapeType() == TopAbs_COMPOUND) 
883   {
884     for ( TopoDS_Iterator it(S); it.More(); it.Next() ) {
885       Handle(StepRepr_RepresentationItem) aLocalItem = STEPConstruct::FindEntity ( FP, it.Value(), L );
886       if (aLocalItem.IsNull() ) continue;
887       nres++;
888       seqRI.Append (aLocalItem);
889     }
890   }
891   else
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       Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1259       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   Handle(Interface_InterfaceModel) Model = WS->Model();
1334   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1335   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
1336 //  Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( labels(1) );
1337 //  if ( STool.IsNull() ) return Standard_False;
1338
1339   // Iterate on requested shapes
1340   for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
1341     TDF_Label L = labels.Value(i);
1342
1343     // get name
1344     Handle(TCollection_HAsciiString) hName = new TCollection_HAsciiString;
1345     if ( ! GetLabelName (L, hName) ) continue;
1346 //    Handle(TDataStd_Name) N;
1347 //    if ( ! L.FindAttribute ( TDataStd_Name::GetID(), N ) ) continue;
1348 //    TCollection_ExtendedString name = N->Get();
1349 //    if ( name.Length() <=0 ) continue;
1350
1351     // find target STEP entity for the current shape
1352 //    TopoDS_Shape S;
1353 //    if ( ! XCAFDoc_ShapeTool::GetShape ( L, S ) ) continue;
1354     if ( ! myLabels.IsBound ( L ) ) continue; // not recorded as translated, skip
1355     TopoDS_Shape S = myLabels.Find ( L );
1356
1357     Handle(StepShape_ShapeDefinitionRepresentation) SDR;
1358     Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, S );
1359     if ( ! FP->FindTypedTransient ( mapper, STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation), SDR ) ) {
1360 #ifdef OCCT_DEBUG
1361       cout << "Warning: Cannot find SDR for " << S.TShape()->DynamicType()->Name() << endl;
1362 #endif
1363       continue;
1364     }
1365
1366     // set the name to the PRODUCT
1367     Handle(StepRepr_PropertyDefinition) PropD = SDR->Definition().PropertyDefinition();
1368     if ( PropD.IsNull() ) continue;
1369     Handle(StepBasic_ProductDefinition) PD = PropD->Definition().ProductDefinition();
1370     if ( PD.IsNull() ) continue;
1371     Handle(StepBasic_Product) Prod = PD->Formation()->OfProduct();
1372
1373     Prod->SetId ( hName );
1374     Prod->SetName ( hName );
1375
1376     // write names for components of assemblies
1377     if ( XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1378       TDF_LabelSequence seq;
1379       XCAFDoc_ShapeTool::GetComponents ( L, seq );
1380       for (Standard_Integer k=1; k <= seq.Length(); k++) {
1381         TDF_Label lab = seq(k);
1382
1383         // get shape with correct location
1384         TDF_Label Lref;
1385         if ( ! XCAFDoc_ShapeTool::GetReferredShape ( lab, Lref ) || 
1386              ! myLabels.IsBound ( Lref ) ) continue;
1387         S = myLabels.Find ( Lref );
1388         S.Move ( XCAFDoc_ShapeTool::GetLocation ( lab ) );
1389         
1390         hName = new TCollection_HAsciiString;
1391         if ( ! GetLabelName (lab, hName) ) continue;
1392         
1393         // find the target CDSR corresponding to a shape
1394         mapper = TransferBRep::ShapeMapper ( FP, S );
1395         Handle(Transfer_Binder) binder = FP->Find ( mapper );
1396         Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1397         if ( ! FP->FindTypedTransient (mapper,STANDARD_TYPE(StepShape_ContextDependentShapeRepresentation), CDSR) ) 
1398           continue;
1399         Handle(StepRepr_ProductDefinitionShape) PDS = CDSR->RepresentedProductRelation();
1400         Handle(StepBasic_ProductDefinitionRelationship) NAUO = PDS->Definition().ProductDefinitionRelationship();
1401         if ( ! NAUO.IsNull() ) NAUO->SetName ( hName );
1402       }
1403     }
1404   }
1405
1406   return Standard_True;
1407 }
1408
1409
1410 //=======================================================================
1411 //function : WritePropsForLabel
1412 //purpose  :
1413 //=======================================================================
1414 static Standard_Boolean WritePropsForLabel(const Handle(XSControl_WorkSession) &WS,
1415                                            const Handle(XCAFDoc_ShapeTool) &aSTool,
1416                                            const STEPCAFControl_DataMapOfLabelShape &myLabels,
1417                                            const TDF_Label &L,
1418                                            const Standard_CString multi)
1419 {
1420   if(L.IsNull()) return Standard_False;
1421
1422   STEPConstruct_ValidationProps Props ( WS );
1423
1424   TopoDS_Shape S = aSTool->GetShape(L);
1425   if(S.IsNull()) return Standard_False;
1426
1427   if ( ! multi || XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1428     // write area
1429     Handle(XCAFDoc_Area) A;
1430     L.FindAttribute ( XCAFDoc_Area::GetID(), A );
1431     if ( ! A.IsNull() ) {
1432       Props.AddArea ( S, A->Get() );
1433     }
1434     // write volume
1435     Handle(XCAFDoc_Volume) V;
1436     L.FindAttribute ( XCAFDoc_Volume::GetID(), V );
1437     if ( ! V.IsNull() ) {
1438       Props.AddVolume ( S, V->Get() );
1439     }
1440   }
1441   // write centroid
1442   Handle(XCAFDoc_Centroid) C;
1443   L.FindAttribute ( XCAFDoc_Centroid::GetID(), C );
1444   if ( ! C.IsNull() ) {
1445     Props.AddCentroid ( S, C->Get() );
1446   }
1447
1448   if( XCAFDoc_ShapeTool::IsCompound(L) || XCAFDoc_ShapeTool::IsAssembly(L) ) {
1449     if(L.HasChild()) {
1450       for(Standard_Integer ich=1; ich<=L.NbChildren(); ich++) {
1451         WritePropsForLabel(WS,aSTool,myLabels,L.FindChild(ich),multi);
1452       }
1453     }
1454   }
1455
1456   return Standard_True;
1457 }
1458
1459
1460 //=======================================================================
1461 //function : WriteValProps
1462 //purpose  :
1463 //=======================================================================
1464
1465 Standard_Boolean STEPCAFControl_Writer::WriteValProps (const Handle(XSControl_WorkSession) &WS,
1466                                                        const TDF_LabelSequence &labels,
1467                                                        const Standard_CString multi) const
1468 {
1469   if ( labels.Length() <=0 ) return Standard_False;
1470
1471   // get working data
1472 //  STEPConstruct_ValidationProps Props ( WS );
1473   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( labels(1) );
1474
1475   // Iterate on requested shapes
1476   for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
1477     TDF_Label L = labels.Value(i);
1478
1479     WritePropsForLabel(WS,aSTool,myLabels,L,multi);
1480 /*    
1481     // find target STEP entity for the current shape
1482     if ( ! myLabels.IsBound ( L ) ) continue; // not recorded as translated, skip
1483     TopoDS_Shape S = myLabels.Find ( L );
1484
1485     // write area and volume (except for components in multifile mode)
1486     if ( ! multi || XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1487       Handle(XCAFDoc_Area) A;
1488       L.FindAttribute ( XCAFDoc_Area::GetID(), A );
1489       if ( ! A.IsNull() ) Props.AddArea ( S, A->Get() );
1490
1491       Handle(XCAFDoc_Volume) V;
1492       L.FindAttribute ( XCAFDoc_Volume::GetID(), V );
1493       if ( ! V.IsNull() ) Props.AddVolume ( S, V->Get() );
1494     }
1495
1496     // write centroid
1497     Handle(XCAFDoc_Centroid) C;
1498     L.FindAttribute ( XCAFDoc_Centroid::GetID(), C );
1499     if ( ! C.IsNull() ) Props.AddCentroid ( S, C->Get() );
1500
1501     // write centroid for components of assemblies
1502     if ( XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1503       TDF_LabelSequence seq;
1504       XCAFDoc_ShapeTool::GetComponents ( L, seq );
1505       for (Standard_Integer k=1; k <= seq.Length(); k++) {
1506         TDF_Label lab = seq(k);
1507
1508         // get shape with correct location
1509         TDF_Label Lref;
1510         if ( ! XCAFDoc_ShapeTool::GetReferredShape ( lab, Lref ) || 
1511              ! myLabels.IsBound ( Lref ) ) continue;
1512         TopLoc_Location Loc = XCAFDoc_ShapeTool::GetLocation ( lab );
1513         S = myLabels.Find ( Lref );
1514         S.Move ( Loc );
1515                 
1516         C.Nullify();
1517         lab.FindAttribute ( XCAFDoc_Centroid::GetID(), C );
1518         // if centroid is not assigned to an instance, 
1519         // use (shifted) centroid of original shape
1520         gp_Pnt center;
1521         if ( C.IsNull() ) {
1522           Lref.FindAttribute ( XCAFDoc_Centroid::GetID(), C );
1523           if ( C.IsNull() ) continue;
1524           center = C->Get().Transformed ( Loc.Transformation() );
1525         }
1526         else center = C->Get();
1527
1528         Props.AddCentroid ( S, center, Standard_True );
1529       }
1530     }
1531 */
1532   }
1533
1534   return Standard_True;
1535 }
1536
1537
1538 //=======================================================================
1539 //function : WriteLayers
1540 //purpose  : 
1541 //=======================================================================
1542
1543 Standard_Boolean STEPCAFControl_Writer::WriteLayers (const Handle(XSControl_WorkSession) &WS,
1544                                                      const TDF_LabelSequence  &labels ) const
1545 {
1546   
1547   if ( labels.Length() <=0 ) return Standard_False;
1548
1549   // get working data
1550   Handle(Interface_InterfaceModel) Model = WS->Model();
1551   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1552   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
1553   Handle(XCAFDoc_LayerTool) LTool = XCAFDoc_DocumentTool::LayerTool( labels(1) );
1554   if (LTool.IsNull() ) return Standard_False;
1555
1556   TDF_LabelSequence LayerLS;
1557   LTool->GetLayerLabels(LayerLS);
1558   if ( LayerLS.Length() <=0 ) return Standard_False;
1559
1560   // Iterate on requested layers and for each layer take set of shapes.
1561   for ( Standard_Integer i=1; i <= LayerLS.Length(); i++ ) {
1562     TDF_Label L = LayerLS.Value(i);
1563     
1564     // get labels of shapes in that layer
1565     TDF_LabelSequence ShapeLs;
1566     LTool->GetShapesOfLayer(L, ShapeLs);
1567     if ( ShapeLs.Length() <=0 ) continue;
1568     
1569     // name of layer: if not set, is considered as being empty
1570     Handle(TCollection_HAsciiString) hName = new TCollection_HAsciiString;
1571     GetLabelName ( L, hName );
1572
1573     // Find target STEP entity for each shape and add to StepVisual_PresentationLayerAssignment items.
1574     TColStd_SequenceOfTransient seqRI;
1575     for ( Standard_Integer j=1; j <= ShapeLs.Length(); j++) {
1576       TDF_Label shLabel = ShapeLs.Value(j);
1577       if ( shLabel.IsNull() ) continue;
1578       
1579       // there is no way to assign layer to instance in STEP
1580       if ( XCAFDoc_ShapeTool::IsAssembly ( shLabel ) ||
1581            XCAFDoc_ShapeTool::IsReference ( shLabel ) )
1582         continue;
1583       
1584       // check that the shape is one of (uub)labels written during current transfer
1585       Standard_Integer k = 1;
1586       for ( ; k <= labels.Length(); k++ )
1587         if ( shLabel.IsDescendant ( labels(k) ) ) break;
1588       if ( k > labels.Length() ) continue;
1589
1590       // get target STEP entity
1591       TopoDS_Shape oneShape = XCAFDoc_ShapeTool::GetShape(shLabel);
1592       
1593       TopLoc_Location Loc;
1594       Standard_Integer nb = 
1595         FindEntities ( FP, oneShape, Loc, seqRI );
1596       if ( nb <=0 ) 
1597         FP->Messenger() << "Warning: Cannot find RI for " << oneShape.TShape()->DynamicType()->Name() << endl;
1598     }
1599     if ( seqRI.Length() <= 0 ) continue;
1600
1601     // analyze visibility
1602     Handle(StepVisual_PresentationLayerAssignment) StepLayerAs = new StepVisual_PresentationLayerAssignment;
1603     Handle(TCollection_HAsciiString) descr;
1604     Handle(TDataStd_UAttribute) aUAttr;
1605     Standard_Boolean isLinv = Standard_False;
1606     if (L.FindAttribute(XCAFDoc::InvisibleGUID(), aUAttr)) {
1607       descr = new TCollection_HAsciiString ("invisible");
1608 #ifdef OCCT_DEBUG
1609       FP->Messenger() << "\tLayer \"" << hName->String().ToCString() << "\" is invisible"<<endl;
1610 #endif
1611       isLinv = Standard_True;
1612     }
1613     else descr = new TCollection_HAsciiString ("visible");
1614     
1615     // create layer entity
1616     Handle(StepVisual_HArray1OfLayeredItem) HArrayOfLItem = 
1617       new StepVisual_HArray1OfLayeredItem ( 1, seqRI.Length() );
1618     for (Standard_Integer i1 = 1; i1<=seqRI.Length(); i1++) {
1619       StepVisual_LayeredItem LI;
1620       LI.SetValue ( seqRI.Value(i1) );
1621       HArrayOfLItem->SetValue( i1, LI );
1622     }
1623     StepLayerAs->Init(hName, descr, HArrayOfLItem);
1624     Model->AddWithRefs( StepLayerAs );
1625     // PTV 23.01.2003 add the invisibility AFTER adding layer into the model.
1626     // add the invisibility for the layer
1627     if (isLinv) {
1628       // Invisibility Item for containig invisible layers.
1629       Handle(StepVisual_HArray1OfInvisibleItem) HInvsblItm = new StepVisual_HArray1OfInvisibleItem (1,1);
1630       StepVisual_InvisibleItem InvIt;
1631       InvIt.SetValue( StepLayerAs );
1632       HInvsblItm->SetValue( 1, InvIt);
1633       
1634       Handle(StepVisual_Invisibility) Invsblt = new StepVisual_Invisibility();
1635       Invsblt->Init( HInvsblItm );
1636       Model->AddWithRefs( Invsblt );
1637     }
1638   }
1639   return Standard_True;
1640 }
1641
1642
1643 //=======================================================================
1644 //function : getSHUOstyle
1645 //purpose  : auxilary
1646 //=======================================================================
1647 static Standard_Boolean getSHUOstyle(const TDF_Label& aSHUOlab,
1648                                      const Handle(XCAFDoc_ColorTool)& CTool,
1649                                      XCAFPrs_Style& SHUOstyle)
1650 {
1651   Quantity_Color C;
1652   if (!CTool->IsVisible( aSHUOlab ) )
1653     SHUOstyle.SetVisibility(Standard_False);
1654   else {
1655     if ( CTool->GetColor ( aSHUOlab, XCAFDoc_ColorGen, C ) ) {
1656       SHUOstyle.SetColorCurv ( C );
1657       SHUOstyle.SetColorSurf ( C );
1658     }
1659     if ( CTool->GetColor ( aSHUOlab, XCAFDoc_ColorSurf, C ) )
1660       SHUOstyle.SetColorSurf ( C );
1661     if ( CTool->GetColor ( aSHUOlab, XCAFDoc_ColorCurv, C ) )
1662       SHUOstyle.SetColorCurv ( C );
1663   }
1664   if ( !SHUOstyle.IsSetColorCurv() && 
1665       !SHUOstyle.IsSetColorSurf() &&
1666       SHUOstyle.IsVisible() )
1667     return Standard_False;
1668   return Standard_True;
1669 }
1670
1671
1672 //=======================================================================
1673 //function : getProDefinitionOfNAUO
1674 //purpose  : auxilary
1675 //=======================================================================
1676 static Standard_Boolean getProDefinitionOfNAUO(const Handle(XSControl_WorkSession)& WS,
1677                                                const TopoDS_Shape& theShape,
1678                                                Handle(StepBasic_ProductDefinition)& PD,
1679                                                Handle(StepRepr_NextAssemblyUsageOccurrence)& NAUO,
1680                                                Standard_Boolean IsRelating)
1681 {
1682   if ( theShape.IsNull() )
1683     return Standard_False;
1684   // get CDSR
1685   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1686   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
1687   Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1688   Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, theShape );
1689   if (!FP->FindTypedTransient(mapper, 
1690                               STANDARD_TYPE(StepShape_ContextDependentShapeRepresentation),
1691                               CDSR))
1692     return Standard_False;
1693   // get PDS of NAUO
1694   Handle(StepRepr_ProductDefinitionShape) PDS = CDSR->RepresentedProductRelation();
1695   if (PDS.IsNull())
1696     return Standard_False;
1697   // get the NAUO entity
1698   Interface_Graph aGraph = WS->HGraph()->Graph();
1699   Interface_EntityIterator subs = aGraph.Shareds(PDS);
1700   for ( subs.Start(); subs.More(); subs.Next() ) {
1701     if (!subs.Value()->IsKind(STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence)))
1702       continue;
1703     NAUO = Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subs.Value());
1704     break;
1705   }
1706   if ( NAUO.IsNull() )
1707     return Standard_False;
1708   // get Relatinf or Related product definition
1709   if ( !IsRelating )
1710     PD = NAUO->RelatedProductDefinition();
1711   else
1712     PD = NAUO->RelatingProductDefinition();
1713   if ( PD.IsNull() )
1714     return Standard_False;
1715   return Standard_True;
1716 }
1717
1718
1719 //=======================================================================
1720 //function : writeSHUO
1721 //purpose  : auxilary
1722 //=======================================================================
1723 static Standard_Boolean writeSHUO (const Handle(XCAFDoc_GraphNode)& theSHUO,
1724                                    const Handle(XCAFDoc_ShapeTool)& theSTool,
1725                                    const Handle(XSControl_WorkSession)& WS,
1726                                    Handle(StepRepr_SpecifiedHigherUsageOccurrence)& theTopSHUO,
1727                                    TopoDS_Shape& NAUOShape,
1728                                    Handle(StepBasic_ProductDefinition)& theRelatingPD,
1729                                    Standard_Boolean& isDeepest)
1730 {
1731   // set the ProductDefinitionRelationship descriptin information as empty strings.
1732   Handle(TCollection_HAsciiString) EmptyString = new TCollection_HAsciiString("");
1733   
1734   TDF_LabelSequence aNextUsageLabs;
1735   theSTool->GetSHUONextUsage( theSHUO->Label(), aNextUsageLabs );
1736   Handle(XCAFDoc_GraphNode) NuSHUO;
1737   if ( theTopSHUO.IsNull() ) {
1738     // the top SHUO
1739     if (aNextUsageLabs.Length() < 1)
1740       return Standard_False;
1741     theSTool->GetSHUO( aNextUsageLabs.Value(1), NuSHUO );
1742     if (NuSHUO.IsNull())
1743       return Standard_False;
1744     // get relating product definition
1745     TopoDS_Shape aTopCompShape = theSTool->GetShape( theSHUO->Label().Father() ); 
1746     Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO;
1747     if (!getProDefinitionOfNAUO( WS, aTopCompShape,
1748                                  theRelatingPD, UUNAUO, Standard_True ))
1749       return Standard_False;
1750     // get related product definition
1751     TopoDS_Shape aNUShape = theSTool->GetShape( NuSHUO->Label().Father() );
1752     Handle(StepBasic_ProductDefinition) aRelatedPD;
1753     Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO;
1754     if (!getProDefinitionOfNAUO( WS, aNUShape,
1755                                  aRelatedPD, NUNAUO, Standard_False ))
1756       return Standard_False;
1757     
1758     theTopSHUO = new StepRepr_SpecifiedHigherUsageOccurrence;
1759     // create deepest shuo EmptyString
1760     theTopSHUO->Init(/*id*/EmptyString, /*name*/EmptyString,
1761                      /*no description*/Standard_False,/*description*/EmptyString,
1762                      theRelatingPD, aRelatedPD,
1763                      /*no ACURefDesignator*/Standard_False,/*ACURefDesignator*/EmptyString,
1764                      /*upper_usage*/UUNAUO, /*next_usage*/NUNAUO);
1765     // write the other SHUO.
1766     if(!writeSHUO( NuSHUO, theSTool, WS, theTopSHUO, NAUOShape, theRelatingPD, isDeepest )) {
1767       theTopSHUO.Nullify();
1768       return Standard_False;
1769     }
1770     
1771     return Standard_True;
1772   }
1773 //   Handle(XCAFDoc_GraphNode) NuSHUO;
1774   if ( aNextUsageLabs.Length() > 0) {
1775     // store SHUO recursive
1776 #ifdef OCCT_DEBUG
1777     if ( aNextUsageLabs.Length() > 1 )
1778       cout << "Warning: store only one next_usage of current SHUO"  << endl;
1779 #endif    
1780     theSTool->GetSHUO( aNextUsageLabs.Value(1), NuSHUO );
1781     Handle(StepRepr_SpecifiedHigherUsageOccurrence) aNUEntSHUO =
1782       new StepRepr_SpecifiedHigherUsageOccurrence;
1783     if (!writeSHUO( NuSHUO, theSTool, WS, aNUEntSHUO, NAUOShape, theRelatingPD, isDeepest ))
1784       return Standard_False;
1785     
1786     // store the deepest SHUO to the dociment
1787     TopoDS_Shape aNUSh, aUUSh;
1788     aNUSh = theSTool->GetShape( NuSHUO->Label().Father() );
1789     aUUSh = theSTool->GetShape( theSHUO->Label().Father() );
1790     // get relating PD with upper_usage and related PD with next_usage
1791     Handle(StepBasic_ProductDefinition) nullPD;// no need to use,case have shared <theRelatingPD>
1792     Handle(StepBasic_ProductDefinition) aRelatedPD;
1793     Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO, NUNAUO;
1794     if (!getProDefinitionOfNAUO( WS, aUUSh, nullPD, UUNAUO, Standard_True ) ||
1795         !getProDefinitionOfNAUO( WS, aNUSh, aRelatedPD, NUNAUO, Standard_False )) {
1796 #ifdef OCCT_DEBUG
1797       cout << "Warning: cannot get related or relating PD" << endl;
1798 #endif
1799       return Standard_False;
1800     }
1801     aNUEntSHUO->Init(/*id*/EmptyString, /*name*/EmptyString,
1802                      /*no description*/Standard_False,/*description*/EmptyString,
1803                      theRelatingPD, aRelatedPD,
1804                      /*no ACURefDesignator*/Standard_False,/*ACURefDesignator*/EmptyString,
1805                      /*upper_usage*/theTopSHUO, /*next_usage*/NUNAUO);
1806     if ( isDeepest ) {
1807       isDeepest = Standard_False;
1808     }
1809     WS->Model()->AddWithRefs ( aNUEntSHUO );
1810     return Standard_True;
1811   } // end of recurse storing
1812     
1813   // get shape 
1814   TDF_Label aShapeL = theSHUO->Label().Father();
1815   NAUOShape = theSTool->GetShape( aShapeL );
1816   // return to the deepest level from SHUO shape level
1817   // it is because SHUO is attribute on deep level and shape level.
1818   isDeepest = Standard_True;
1819   return Standard_True;
1820 }
1821
1822
1823 //=======================================================================
1824 //function : createSHUOStyledItem
1825 //purpose  : auxilary
1826 //=======================================================================
1827 static Standard_Boolean createSHUOStyledItem (const XCAFPrs_Style& style,
1828                                               const Handle(StepRepr_ProductDefinitionShape)& PDS,
1829                                               const Handle(XSControl_WorkSession) &WS,
1830                                               const TopoDS_Shape& Sh,
1831                                               const Handle(XCAFDoc_ShapeTool)& STool,
1832                                               MoniTool_DataMapOfShapeTransient& myMapCompMDGPR)
1833 {
1834   // create styled item for the indicated SHUO and store to the model
1835   STEPConstruct_Styles Styles( WS );
1836   // translate colors to STEP
1837   Handle(StepVisual_Colour) surfColor, curvColor;
1838   if ( style.IsSetColorSurf() )
1839     surfColor = Styles.EncodeColor ( style.GetColorSurf() );
1840   if ( style.IsSetColorCurv() )
1841     curvColor = Styles.EncodeColor ( style.GetColorCurv() );
1842   Standard_Boolean isComponent = Standard_True;// cause need to get PSBC
1843   Handle(StepRepr_RepresentationItem) item;
1844   // set default color for invisible SHUO.
1845   Standard_Boolean isSetDefaultColor = Standard_False;
1846   if (surfColor.IsNull() && curvColor.IsNull() && !style.IsVisible() ) {
1847     surfColor = Styles.EncodeColor ( Quantity_Color( 1, 1, 1, Quantity_TOC_RGB ) );
1848     isSetDefaultColor = Standard_True;
1849   }
1850   Handle(StepVisual_PresentationStyleAssignment) PSA =
1851     Styles.MakeColorPSA ( item, surfColor, curvColor, isComponent );
1852   Handle(StepVisual_StyledItem) override; //null styled item
1853   
1854   // find the repr item of the shape
1855   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1856   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
1857   Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, Sh );
1858   Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1859   FP->FindTypedTransient(mapper, 
1860                          STANDARD_TYPE(StepShape_ContextDependentShapeRepresentation),
1861                          CDSR);
1862   if ( CDSR.IsNull() )
1863     return Standard_False;
1864   // find context
1865   Handle(StepRepr_RepresentationContext) Context = Styles.FindContext( Sh );
1866   TopoDS_Shape aTopSh = Sh;
1867   if (Context.IsNull()) {
1868     TDF_Label aTopShL = STool->FindShape(Sh, Standard_False);
1869     if (aTopShL.IsNull())
1870       return Standard_False;
1871     aTopSh = STool->GetShape( aTopShL );
1872     Context = Styles.FindContext ( aTopSh );
1873   }
1874   if (Context.IsNull())
1875     return Standard_False;
1876   // get representation item of the shape
1877   TopLoc_Location L;
1878   TColStd_SequenceOfTransient seqRI;
1879   FindEntities ( FP, Sh, L, seqRI );
1880 #ifdef OCCT_DEBUG
1881   if ( seqRI.Length() <=0 ) 
1882     FP->Messenger() << "Warning: Cannot find RI for " << Sh.TShape()->DynamicType()->Name() << endl;
1883 #endif
1884   item = Handle(StepRepr_RepresentationItem)::DownCast(seqRI(1));
1885   //get overridden styled item
1886   getStyledItem(Sh,STool, Styles, override,myMapCompMDGPR);
1887   
1888   // get STEP STYLED ITEM
1889   Handle(StepVisual_StyledItem) STEPstyle = Styles.AddStyle ( item, PSA, override );
1890   // create SR, SDR and all necessary references between them and ST, PDS, PSBC, GRC
1891   Styles.CreateNAUOSRD( Context, CDSR, PDS );
1892   
1893   // add step styled item of SHUO to the model
1894   // do it by additing styled item to the MDGPR
1895   if ( !aTopSh.IsNull() &&  !myMapCompMDGPR.IsBound( aTopSh ) ) {
1896     // create MDGPR and record it in model
1897 #ifdef OCCT_DEBUG
1898     cout << "Warning: " << __FILE__ << ": Create new MDGPR for SHUO instance"  << endl;
1899 #endif
1900     Handle(StepVisual_MechanicalDesignGeometricPresentationRepresentation) aMDGPR;
1901     Styles.CreateMDGPR ( Context, aMDGPR );
1902     if (!aMDGPR.IsNull())
1903       myMapCompMDGPR.Bind( aTopSh, aMDGPR );
1904   }
1905   else if ( !aTopSh.IsNull() &&  myMapCompMDGPR.IsBound( aTopSh ) ) {
1906     // get MDGPR of the top-level shape
1907     Handle(StepVisual_PresentationRepresentation) aMDGPR = 
1908       Handle(StepVisual_PresentationRepresentation)::DownCast( myMapCompMDGPR.Find( aTopSh ) );
1909     // get old styled items to not lose it
1910     Handle(StepRepr_HArray1OfRepresentationItem) oldItems = aMDGPR->Items();
1911     Standard_Integer oldLengthlen = 0;
1912     if (!oldItems.IsNull())
1913       oldLengthlen = oldItems->Length();
1914     // create new array of styled items by an olds and new one
1915     Handle(StepRepr_HArray1OfRepresentationItem) newItems =
1916       new StepRepr_HArray1OfRepresentationItem(1, oldLengthlen + 1);
1917     Standard_Integer si;
1918     Standard_Integer el = 1;
1919     for ( si=1; si <= oldLengthlen; si++ )
1920       newItems->SetValue( el++, oldItems->Value( si ) );
1921     newItems->SetValue (el++, STEPstyle);
1922     // init MDGPR be new array of styled items
1923     if (newItems->Length() > 0)
1924       aMDGPR->SetItems( newItems );
1925   }
1926   else {
1927     WS->Model()->AddWithRefs ( STEPstyle ); // add as root to the model, but it is not good
1928 #ifdef OCCT_DEBUG
1929     cout << "Warning: " << __FILE__ << ": adds styled item of SHUO as root, casue cannot find MDGPR" << endl;
1930 #endif
1931   }
1932   // create invisibility item for the styled item
1933   if ( !style.IsVisible() ) {
1934     if (isSetDefaultColor) {
1935       // try to set default color from top-level shape
1936       
1937       setDefaultInstanceColor(override, PSA);
1938     }
1939     // create invisibility item and refer for stiledItem
1940     Handle(StepVisual_Invisibility) Invsblt = new StepVisual_Invisibility();
1941     Handle(StepVisual_HArray1OfInvisibleItem) HInvsblItm = 
1942       new StepVisual_HArray1OfInvisibleItem (1,1);
1943     // put all style item into the harray
1944     StepVisual_InvisibleItem anInvItem;
1945     anInvItem.SetValue( STEPstyle );
1946     HInvsblItm->SetValue( 1, anInvItem );
1947     Invsblt->Init( HInvsblItm );
1948     WS->Model()->AddWithRefs( Invsblt );
1949   }
1950   
1951   return Standard_True;
1952 }
1953
1954
1955 //=======================================================================
1956 //function : WriteSHUOs
1957 //purpose  : 
1958 //=======================================================================
1959
1960 Standard_Boolean STEPCAFControl_Writer::WriteSHUOs (const Handle(XSControl_WorkSession) &WS,
1961                                                     const TDF_LabelSequence  &labels )
1962 {
1963   if ( labels.Length() <=0 ) return Standard_False;
1964
1965   // get working data
1966   Handle(Interface_InterfaceModel) Model = WS->Model();
1967   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1968   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
1969   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( labels(1) );
1970   if (CTool.IsNull() )
1971     return Standard_False;
1972   // map of transfered SHUO
1973   TColStd_MapOfTransient aMapOfMainSHUO;
1974 //   TColStd_IndexedDataMapOfTransientTransient aIndxMapOfSHUOEnt;
1975   // Iterate on requested shapes
1976   for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
1977     TDF_Label L = labels.Value(i);
1978     if ( ! myLabels.IsBound ( L ) ) continue; // not recorded as translated, skip
1979 //     TopoDS_Shape S = myLabels.Find ( L );
1980     if ( XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1981       TDF_LabelSequence seq;
1982       XCAFDoc_ShapeTool::GetComponents ( L, seq );
1983       // iterates on components of assembly
1984       for (Standard_Integer k=1; k <= seq.Length(); k++) {
1985         TDF_Label lab = seq(k);
1986         TDF_AttributeSequence anAttrSeq;
1987         CTool->ShapeTool()->GetAllComponentSHUO( lab, anAttrSeq );
1988         // work with SHUO
1989         for (Standard_Integer j = 1; j <= anAttrSeq.Length(); j++) {
1990           Handle(XCAFDoc_GraphNode) aSHUO = 
1991             Handle(XCAFDoc_GraphNode)::DownCast(anAttrSeq.Value( j ));
1992           // take label of SHUO
1993           TDF_Label aSHUOlab = aSHUO->Label();
1994           TDF_LabelSequence aUpLabels;
1995           // check is it SHUO of upper_usage
1996           CTool->ShapeTool()->GetSHUOUpperUsage( aSHUOlab, aUpLabels );
1997           if ( aUpLabels.Length() > 0 )
1998             continue; // transfer only main SHUO
1999           if ( aMapOfMainSHUO.Contains( aSHUO ) )
2000             continue; // do not try to transfer SHUO twice
2001           aMapOfMainSHUO.Add( aSHUO );
2002           // check if it is styled SHUO
2003           XCAFPrs_Style SHUOstyle;
2004           if ( !getSHUOstyle ( aSHUOlab, CTool, SHUOstyle ) ) {
2005 #ifdef OCCT_DEBUG
2006             cout << "Warning: " << __FILE__ << ": do not store SHUO without any style to the STEP model" << endl;
2007 #endif
2008             continue;
2009           }
2010           // write SHUO to the model amd then add structure type.
2011           TopoDS_Shape NAUOShape; // shape of the deepest NAUO in the SHUO structure
2012           Standard_Boolean isDeepest = Standard_False;
2013           Handle(StepRepr_SpecifiedHigherUsageOccurrence) anEntOfSHUO;
2014           Handle(StepBasic_ProductDefinition) aRelatingPD;
2015           // create the top SHUO and all other.
2016           writeSHUO( aSHUO, CTool->ShapeTool(), WS, anEntOfSHUO, NAUOShape, aRelatingPD, isDeepest );
2017           if ( anEntOfSHUO.IsNull() || NAUOShape.IsNull() ) {
2018 #ifdef OCCT_DEBUG
2019             cout << "Warning: " << __FILE__ << ": Cannot store SHUO" << endl;
2020 #endif
2021             continue;
2022           }
2023           // create new Product Definition Shape for TOP SHUO
2024 #ifdef OCCT_DEBUG
2025             cout << "Info: " << __FILE__ << ": Create NEW PDS for current SHUO " << endl;
2026 #endif
2027           Handle(StepRepr_ProductDefinitionShape) PDS = new StepRepr_ProductDefinitionShape;
2028           Handle(TCollection_HAsciiString) aPDSname = new TCollection_HAsciiString("SHUO");
2029           Handle(TCollection_HAsciiString) descrStr = new TCollection_HAsciiString("");
2030           StepRepr_CharacterizedDefinition aCharDef;
2031           aCharDef.SetValue( anEntOfSHUO );
2032           PDS->Init( aPDSname, Standard_False, descrStr, aCharDef );
2033           
2034           // create styled item for SHUO and add to the model
2035           createSHUOStyledItem ( SHUOstyle, PDS, WS, NAUOShape, CTool->ShapeTool(), myMapCompMDGPR );
2036           
2037         } // end work with SHUO
2038       } // end of an assembly components
2039     } // end of IsAssembly case
2040     // nothing to do if it is not assembly
2041     continue;
2042   } // end of iterates on indicated labels
2043   return Standard_True;
2044 }
2045
2046
2047 //=======================================================================
2048 //function : FindPDSforDGT
2049 //purpose  : auxilary: find PDS for AdvancedFace or EdgeCurve for creation
2050 //                     needed ShapeAspect in D&GT structure
2051 //=======================================================================
2052 static Standard_Boolean FindPDSforDGT(const Interface_Graph &aGraph,
2053                                       const Handle(Standard_Transient) &ent,
2054                                       Handle(StepRepr_ProductDefinitionShape) &PDS,
2055                                       Handle(StepRepr_RepresentationContext) &RC,
2056                                       Handle(StepShape_AdvancedFace) &AF,
2057                                       Handle(StepShape_EdgeCurve) &EC)
2058 {
2059   if( !ent->IsKind(STANDARD_TYPE(StepShape_EdgeCurve)) && 
2060       !ent->IsKind(STANDARD_TYPE(StepShape_AdvancedFace)) ) 
2061     return Standard_False;
2062
2063   AF = Handle(StepShape_AdvancedFace)::DownCast(ent);
2064   if( ent->IsKind(STANDARD_TYPE(StepShape_EdgeCurve)) ) {
2065     EC = Handle(StepShape_EdgeCurve)::DownCast(ent);
2066     Interface_EntityIterator subs = aGraph.Sharings(EC);
2067     for(subs.Start(); subs.More() && AF.IsNull(); subs.Next()) {
2068       Handle(StepShape_OrientedEdge) OE = Handle(StepShape_OrientedEdge)::DownCast(subs.Value());
2069       if(OE.IsNull()) continue;
2070       Interface_EntityIterator subs1 = aGraph.Sharings(OE);
2071       for(subs1.Start(); subs1.More() && AF.IsNull(); subs1.Next()) {
2072         Handle(StepShape_EdgeLoop) EL = Handle(StepShape_EdgeLoop)::DownCast(subs1.Value());
2073         if(EL.IsNull()) continue;
2074         Interface_EntityIterator subs2 = aGraph.Sharings(EL);
2075         for(subs2.Start(); subs2.More() && AF.IsNull(); subs2.Next()) {
2076           Handle(StepShape_FaceBound) FB = Handle(StepShape_FaceBound)::DownCast(subs2.Value());
2077           if(FB.IsNull()) continue;
2078           Interface_EntityIterator subs3 = aGraph.Sharings(FB);
2079           for(subs3.Start(); subs3.More() && AF.IsNull(); subs3.Next()) {
2080             AF = Handle(StepShape_AdvancedFace)::DownCast(subs3.Value());
2081           }
2082         }
2083       }
2084     }
2085   }
2086   if(AF.IsNull()) return Standard_False;
2087
2088   Interface_EntityIterator subs = aGraph.Sharings(AF);
2089   for(subs.Start(); subs.More() && PDS.IsNull(); subs.Next()) {
2090     Handle(StepShape_ConnectedFaceSet) CFS =
2091       Handle(StepShape_ConnectedFaceSet)::DownCast(subs.Value());
2092     if(CFS.IsNull()) continue;
2093     Interface_EntityIterator subs1 = aGraph.Sharings(CFS);
2094     for(subs1.Start(); subs1.More() && PDS.IsNull(); subs1.Next()) {
2095       Handle(StepRepr_RepresentationItem) RI = 
2096         Handle(StepRepr_RepresentationItem)::DownCast(subs1.Value());
2097       if(RI.IsNull()) continue;
2098       Interface_EntityIterator subs2 = aGraph.Sharings(RI);
2099       for(subs2.Start(); subs2.More() && PDS.IsNull(); subs2.Next()) {
2100         Handle(StepShape_ShapeRepresentation) SR = 
2101           Handle(StepShape_ShapeRepresentation)::DownCast(subs2.Value());
2102         if(SR.IsNull()) continue;
2103         RC = SR->ContextOfItems();
2104         Interface_EntityIterator subs3 = aGraph.Sharings(SR);
2105         for(subs3.Start(); subs3.More() && PDS.IsNull(); subs3.Next()) {
2106           Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
2107             Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs3.Value());
2108           if(SDR.IsNull()) continue;
2109           Handle(StepRepr_PropertyDefinition) PropD = SDR->Definition().PropertyDefinition();
2110           if(PropD.IsNull()) continue;
2111           PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(PropD);
2112         }
2113       }
2114     }
2115   }
2116   
2117   return Standard_True;
2118 }
2119
2120 //=======================================================================
2121 //function : GetUnit
2122 //purpose  : auxiliary
2123 //=======================================================================
2124
2125 static StepBasic_Unit GetUnit(const Handle(StepRepr_RepresentationContext)& theRC,
2126                               const Standard_Boolean isAngle = Standard_False)
2127 {
2128   StepBasic_Unit aUnit;
2129   if (isAngle) {
2130     Handle(StepBasic_SiUnitAndPlaneAngleUnit) aSiPAU;
2131     Handle(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext) aCtx =
2132       Handle(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext)::DownCast(theRC);
2133     if(!aCtx.IsNull()) {
2134       for(Standard_Integer j = 1; j <= aCtx->NbUnits(); j++) {
2135         if(aCtx->UnitsValue(j)->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndPlaneAngleUnit))) {
2136           aSiPAU = Handle(StepBasic_SiUnitAndPlaneAngleUnit)::DownCast(aCtx->UnitsValue(j));
2137           break;
2138         }
2139       }
2140     }
2141     if(aSiPAU.IsNull()) {
2142       Handle(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx) aCtx1 =
2143         Handle(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx)::DownCast(theRC);
2144       if(!aCtx1.IsNull()) {
2145         for(Standard_Integer j = 1; j <= aCtx1->NbUnits(); j++) {
2146           if(aCtx1->UnitsValue(j)->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndPlaneAngleUnit))) {
2147             aSiPAU = Handle(StepBasic_SiUnitAndPlaneAngleUnit)::DownCast(aCtx1->UnitsValue(j));
2148             break;
2149           }
2150         }
2151       }
2152     }
2153     if(aSiPAU.IsNull())
2154       aSiPAU = new StepBasic_SiUnitAndPlaneAngleUnit;
2155     aUnit.SetValue(aSiPAU);
2156   }
2157   else {
2158     Handle(StepBasic_SiUnitAndLengthUnit) aSiLU;
2159     Handle(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext) aCtx =
2160       Handle(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext)::DownCast(theRC);
2161     if(!aCtx.IsNull()) {
2162       for(Standard_Integer j = 1; j <= aCtx->NbUnits(); j++) {
2163         if(aCtx->UnitsValue(j)->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndLengthUnit))) {
2164           aSiLU = Handle(StepBasic_SiUnitAndLengthUnit)::DownCast(aCtx->UnitsValue(j));
2165           break;
2166         }
2167       }
2168     }
2169     if(aSiLU.IsNull()) {
2170       Handle(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx) aCtx1 =
2171         Handle(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx)::DownCast(theRC);
2172       if(!aCtx1.IsNull()) {
2173         for(Standard_Integer j = 1; j <= aCtx1->NbUnits(); j++) {
2174           if(aCtx1->UnitsValue(j)->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndLengthUnit))) {
2175             aSiLU = Handle(StepBasic_SiUnitAndLengthUnit)::DownCast(aCtx1->UnitsValue(j));
2176             break;
2177           }
2178         }
2179       }
2180     }
2181     if(aSiLU.IsNull())
2182       aSiLU = new StepBasic_SiUnitAndLengthUnit;
2183     aUnit.SetValue(aSiLU);
2184   }
2185   return aUnit;
2186 }
2187
2188 //=======================================================================
2189 //function : CreateDimValue
2190 //purpose  : auxiliary
2191 //======================================================================
2192 static Handle(StepRepr_ReprItemAndMeasureWithUnit) CreateDimValue(const Standard_Real theValue,
2193                                                                   const StepBasic_Unit theUnit,
2194                                                                   const Handle(TCollection_HAsciiString)& theName,
2195                                                                   const Standard_CString theMeasureName,
2196                                                                   const Standard_Boolean isAngle,
2197                                                                   const Standard_Boolean isQualified = Standard_False,
2198                                                                   const Handle(StepShape_QualifiedRepresentationItem)& theQRI = NULL)
2199 {
2200   Handle(StepRepr_RepresentationItem) aReprItem = new StepRepr_RepresentationItem();
2201   aReprItem->Init(new TCollection_HAsciiString(theName));
2202   Handle(StepBasic_MeasureWithUnit) aMWU = new StepBasic_MeasureWithUnit();
2203   Handle(StepBasic_MeasureValueMember) aValueMember = new StepBasic_MeasureValueMember();
2204   aValueMember->SetName(theMeasureName);
2205   aValueMember->SetReal(theValue);
2206   aMWU->Init(aValueMember, theUnit);
2207   if (isQualified) {
2208     if (isAngle) {
2209       // Angle & with qualifiers
2210       Handle(StepRepr_ReprItemAndPlaneAngleMeasureWithUnitAndQRI) anItem = 
2211         new StepRepr_ReprItemAndPlaneAngleMeasureWithUnitAndQRI();
2212       anItem->Init(aMWU, aReprItem, theQRI);
2213       return anItem;
2214     }
2215     else {
2216       // Length & with qualifiers
2217       Handle(StepRepr_ReprItemAndLengthMeasureWithUnitAndQRI) anItem = 
2218         new StepRepr_ReprItemAndLengthMeasureWithUnitAndQRI();
2219       anItem->Init(aMWU, aReprItem, theQRI);
2220       return anItem;
2221     }
2222   }
2223   else {
2224     if (isAngle) {
2225       // Angle & without qualifiers
2226       Handle(StepRepr_ReprItemAndPlaneAngleMeasureWithUnit) anItem = 
2227         new StepRepr_ReprItemAndPlaneAngleMeasureWithUnit();
2228       anItem->Init(aMWU, aReprItem);
2229       return anItem;
2230     }
2231     else {
2232       // Length & without qualifiers
2233       Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) anItem = 
2234         new StepRepr_ReprItemAndLengthMeasureWithUnit();
2235       anItem->Init(aMWU, aReprItem);
2236       return anItem;
2237     }
2238   }
2239 }
2240
2241 //=======================================================================
2242 //function : WriteShapeAspect
2243 //purpose  : auxiliary (write Shape_Aspect entity for given shape)
2244 //=======================================================================
2245
2246 static Handle(StepRepr_ShapeAspect) WriteShapeAspect (const Handle(XSControl_WorkSession) &WS,
2247                                                       const TDF_Label theLabel,
2248                                                       const TopoDS_Shape theShape,
2249                                                       Handle(StepRepr_RepresentationContext)& theRC,
2250                                                       Handle(StepAP242_GeometricItemSpecificUsage)& theGISU)
2251 {
2252   // Get working data
2253   Handle(Interface_InterfaceModel) Model = WS->Model();
2254   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
2255   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
2256   const Handle(Interface_HGraph) aHGraph = WS->HGraph();
2257   if (aHGraph.IsNull())
2258     return NULL;
2259   Interface_Graph aGraph = aHGraph->Graph();
2260
2261   TopLoc_Location aLoc;
2262   TColStd_SequenceOfTransient aSeqRI;
2263   FindEntities( FP, theShape, aLoc, aSeqRI );
2264   if ( aSeqRI.Length() <= 0 ) {
2265     FP->Messenger() << "Warning: Cannot find RI for "<<theShape.TShape()->DynamicType()->Name()<<endl;
2266     return NULL;
2267   }
2268
2269   Handle(StepRepr_ProductDefinitionShape) aPDS;
2270   Handle(StepRepr_RepresentationContext) aRC;
2271   Handle(Standard_Transient) anEnt = aSeqRI.Value(1);
2272   Handle(StepShape_AdvancedFace) anAF;
2273   Handle(StepShape_EdgeCurve) anEC;
2274   FindPDSforDGT(aGraph, anEnt, aPDS, aRC, anAF, anEC);
2275   if(aPDS.IsNull()) 
2276     return NULL;
2277
2278   theRC = aRC;
2279   // Shape_Aspect
2280   Handle(TCollection_HAsciiString) aName = new TCollection_HAsciiString();
2281   Handle(TDataStd_Name) aNameAttr;
2282   if (theLabel.FindAttribute(TDataStd_Name::GetID(), aNameAttr)) {
2283     aName = new TCollection_HAsciiString(TCollection_AsciiString(aNameAttr->Get(), '?'));
2284     Standard_Integer aFirstSpace = aName->Search(" ");
2285     if (aFirstSpace != -1)
2286       aName = aName->SubString(aFirstSpace + 1, aName->Length());
2287     else
2288       aName = new TCollection_HAsciiString();
2289   }
2290   Handle(TCollection_HAsciiString) aDescription = new TCollection_HAsciiString();
2291   Handle(StepRepr_ShapeAspect) aSA = new StepRepr_ShapeAspect;
2292   aSA->Init(aName, aDescription, aPDS, StepData_LTrue);
2293
2294   // Geometric_Item_Specific_Usage
2295   Handle(StepAP242_GeometricItemSpecificUsage) aGISU = new StepAP242_GeometricItemSpecificUsage();
2296   StepAP242_ItemIdentifiedRepresentationUsageDefinition aDefinition;
2297   aDefinition.SetValue(aSA);
2298   Handle(StepRepr_HArray1OfRepresentationItem) anReprItems = new StepRepr_HArray1OfRepresentationItem(1, 1);
2299   Handle(StepRepr_RepresentationItem) anIdentifiedItem = Handle(StepRepr_RepresentationItem)::DownCast(anEnt);
2300   anReprItems->SetValue(1, anIdentifiedItem);
2301   Interface_EntityIterator subs = aGraph.Sharings(aPDS);
2302   Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
2303   for (subs.Start(); subs.More() && aSDR.IsNull(); subs.Next()) {
2304     Handle(Standard_Transient) anEntity = subs.Value();
2305     aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(anEntity);
2306   }
2307   if (aSDR.IsNull())
2308     return NULL;
2309
2310   // Set entities to model
2311   aGISU->Init(aName, aDescription, aDefinition, aSDR->UsedRepresentation(), anReprItems);
2312   Model->AddWithRefs(aSA);
2313   Model->AddWithRefs(aGISU);
2314   theGISU = aGISU;
2315   return aSA;
2316 }
2317
2318 //=======================================================================
2319 //function : WritePresentation
2320 //purpose  : auxiliary (write annotation plane and presentation)
2321 //======================================================================
2322 static void WritePresentation(const Handle(XSControl_WorkSession) &WS,
2323                               const TopoDS_Shape thePresentation,
2324                               const gp_Ax2 theAnnotationPlane,
2325                               const gp_Pnt theTextPosition,
2326                               const Handle(Standard_Transient) theDimension)
2327 {
2328   if (thePresentation.IsNull())
2329     return;
2330   // Get working data
2331   Handle(Interface_InterfaceModel) aModel = WS->Model();
2332
2333   // Presentation
2334   Handle(StepVisual_TessellatedGeometricSet) aGeomSet = STEPCAFControl_GDTProperty::GetTessellation(thePresentation);
2335   Handle(StepVisual_TessellatedAnnotationOccurrence) aTAO = new StepVisual_TessellatedAnnotationOccurrence();
2336   aTAO->Init(new TCollection_HAsciiString(), gdtPrsCurveStyle, aGeomSet);
2337   StepVisual_DraughtingCalloutElement aDCElement;
2338   aDCElement.SetValue(aTAO);
2339   Handle(StepVisual_HArray1OfDraughtingCalloutElement) aTAOs = new StepVisual_HArray1OfDraughtingCalloutElement(1, 1);
2340   aTAOs->SetValue(1, aDCElement);
2341   Handle(StepVisual_DraughtingCallout) aDCallout = new StepVisual_DraughtingCallout();
2342   aDCallout->Init(new TCollection_HAsciiString(), aTAOs);
2343   Handle(StepRepr_HArray1OfRepresentationItem) aDCsForDMIA = new StepRepr_HArray1OfRepresentationItem(1, 1);
2344   aDCsForDMIA->SetValue(1, aDCallout);
2345   StepAP242_ItemIdentifiedRepresentationUsageDefinition aDimension;
2346   aDimension.SetValue(theDimension);
2347   Handle(StepAP242_DraughtingModelItemAssociation) aDMIA =
2348     new StepAP242_DraughtingModelItemAssociation();
2349   aDMIA->Init(new TCollection_HAsciiString("PMI representation to presentation link"),
2350       new TCollection_HAsciiString(), aDimension, gdtPresentationDM, aDCsForDMIA);
2351   aModel->AddWithRefs(aDMIA);
2352
2353   // Annotation plane
2354   // Presentation Style
2355   Handle(StepVisual_NullStyleMember) aNullStyle = new StepVisual_NullStyleMember();
2356   aNullStyle->SetEnumText(0, ".NULL.");
2357   StepVisual_PresentationStyleSelect aStyleItem;
2358   aStyleItem.SetValue(aNullStyle);
2359   Handle(StepVisual_HArray1OfPresentationStyleSelect) aStyles = new StepVisual_HArray1OfPresentationStyleSelect(1, 1);
2360   aStyles->SetValue(1, aStyleItem);
2361   Handle(StepVisual_PresentationStyleAssignment) aPrsStyle = new StepVisual_PresentationStyleAssignment();
2362   aPrsStyle->Init(aStyles);
2363   Handle(StepVisual_HArray1OfPresentationStyleAssignment) aPrsStyles = 
2364     new StepVisual_HArray1OfPresentationStyleAssignment(1, 1);
2365   aPrsStyles->SetValue(1, aPrsStyle);
2366   // Plane
2367   Handle(StepGeom_Plane) aPlane = new StepGeom_Plane();
2368   Handle(StepGeom_Axis2Placement3d) anAxis = STEPCAFControl_GDTProperty::GetAxis2Placement3D(theAnnotationPlane);
2369   // Set text position to plane origin
2370   Handle(StepGeom_CartesianPoint) aTextPos = new StepGeom_CartesianPoint();
2371   Handle(TColStd_HArray1OfReal) aCoords = new TColStd_HArray1OfReal(1, 3);
2372   for (Standard_Integer i = 1; i <= 3; i++)
2373     aCoords->SetValue(i, theTextPosition.Coord(i));
2374   aTextPos->Init(new TCollection_HAsciiString(), aCoords);
2375   anAxis->SetLocation(aTextPos);
2376   aPlane->Init(new TCollection_HAsciiString(), anAxis);
2377   // Annotation plane element
2378   StepVisual_AnnotationPlaneElement aPlaneElement;
2379   aPlaneElement.SetValue(aDCallout);
2380   Handle(StepVisual_HArray1OfAnnotationPlaneElement) aDCsForAnnPln = new StepVisual_HArray1OfAnnotationPlaneElement(1, 1);
2381   aDCsForAnnPln->SetValue(1, aPlaneElement);
2382   // Init AnnotationPlane entity
2383   Handle(StepVisual_AnnotationPlane) anAnnPlane = new StepVisual_AnnotationPlane();
2384   anAnnPlane->Init(new TCollection_HAsciiString(), aPrsStyles, aPlane, aDCsForAnnPln);
2385   gdtAnnotationPlanes.Append(anAnnPlane);
2386   aModel->AddWithRefs(anAnnPlane);
2387 }
2388
2389 //=======================================================================
2390 //function : WriteDatumAP242
2391 //purpose  : auxiliary (write Datum entity for given shape or write all 
2392 //           necessary entities and link them to already written datum 
2393 //           in case of multiple features association)
2394 //=======================================================================
2395 static Handle(StepDimTol_Datum) WriteDatumAP242(const Handle(XSControl_WorkSession) &WS,
2396                                                 const TDF_Label theShapeL,
2397                                                 const TDF_Label theDatumL,
2398                                                 const Standard_Boolean isFirstDTarget,
2399                                                 const Handle(StepDimTol_Datum) theWrittenDatum)
2400 {
2401   // Get working data
2402   Handle(Interface_InterfaceModel) Model = WS->Model();
2403   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
2404   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
2405   const Handle(Interface_HGraph) aHGraph = WS->HGraph();
2406   if (aHGraph.IsNull())
2407     return NULL;
2408   Interface_Graph aGraph = aHGraph->Graph();
2409
2410   Handle(StepRepr_ShapeAspect) aSA;
2411   Handle(StepAP242_GeometricItemSpecificUsage) aGISU;
2412   // Link with datum feature
2413   Handle(StepRepr_ProductDefinitionShape) aPDS;
2414   Handle(StepRepr_RepresentationContext) aRC;
2415   Handle(Standard_Transient) anEnt;
2416   Handle(StepShape_AdvancedFace) anAF;
2417   Handle(StepShape_EdgeCurve) anEC;
2418   TopoDS_Shape aShape;
2419   TopLoc_Location aLoc;
2420   TColStd_SequenceOfTransient aSeqRI;
2421
2422   aShape = XCAFDoc_ShapeTool::GetShape(theShapeL);
2423   FindEntities( FP, aShape, aLoc, aSeqRI );
2424   if ( aSeqRI.Length() <= 0 ) {
2425     FP->Messenger() << "Warning: Cannot find RI for "<<aShape.TShape()->DynamicType()->Name()<<endl;
2426     return NULL;
2427   }
2428   anEnt = aSeqRI.Value(1);
2429   FindPDSforDGT(aGraph, anEnt, aPDS, aRC, anAF, anEC);
2430   if (aPDS.IsNull()) 
2431     return NULL;
2432
2433   aSA = WriteShapeAspect(WS, theDatumL, aShape, aRC, aGISU);
2434   if (aSA.IsNull())
2435     return NULL;
2436   Standard_Integer aSANum = Model->Number(aSA);
2437   Standard_Integer aGISUNum = Model->Number(aGISU);
2438   // Find if datum has datum targets and get common datum attributes
2439   Handle(XCAFDoc_Datum) aDatumAttr;
2440   if (!theDatumL.FindAttribute(XCAFDoc_Datum::GetID(), aDatumAttr)) 
2441     return NULL;
2442   Handle(XCAFDimTolObjects_DatumObject) anObject = aDatumAttr->GetObject();
2443   if (anObject.IsNull())
2444     return NULL;
2445   Standard_Boolean isSimpleDatum = !anObject->IsDatumTarget();
2446   Handle(TCollection_HAsciiString) anIdentifier = anObject->GetName();
2447   Handle(TCollection_HAsciiString) aTargetId = (anObject->GetDatumTargetNumber() == 0 ? 
2448     new TCollection_HAsciiString() : new TCollection_HAsciiString(anObject->GetDatumTargetNumber()));
2449
2450   // If datum type is area, but there is no area in object, write as simple datum
2451   if (anObject->GetDatumTargetType() == XCAFDimTolObjects_DatumTargetType_Area &&
2452     anObject->GetDatumTarget().IsNull())
2453     isSimpleDatum = Standard_True;
2454
2455   // Simple datum
2456   if (isSimpleDatum) {
2457     Handle(StepDimTol_DatumFeature) aDF = new StepDimTol_DatumFeature();
2458     aDF->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), aSA->OfShape(), aSA->ProductDefinitional());
2459     Model->ReplaceEntity(aSANum, aDF);
2460     aSA = aDF;
2461     StepAP242_ItemIdentifiedRepresentationUsageDefinition aDefinition;
2462     aDefinition.SetValue(aDF);
2463     aGISU->SetDefinition(aDefinition);
2464     Model->ReplaceEntity(aGISUNum, aGISU);
2465   }
2466   // Datum with datum targets
2467   else {
2468     XCAFDimTolObjects_DatumTargetType aDatumType = anObject->GetDatumTargetType();
2469     Handle(StepDimTol_DatumTarget) aDatumTarget;
2470     // Note: the given way to write such datum type may be incorrect (too little information)
2471     if (aDatumType == XCAFDimTolObjects_DatumTargetType_Area) {
2472       TopoDS_Shape aDTShape = anObject->GetDatumTarget();
2473       Handle(StepAP242_GeometricItemSpecificUsage) anAreaGISU;
2474       Handle(StepRepr_ShapeAspect) anAreaSA = WriteShapeAspect(WS, theDatumL, aDTShape, aRC, anAreaGISU);
2475       aSANum = Model->Number(anAreaSA);
2476       aGISUNum = Model->Number(anAreaGISU);
2477       Handle(StepDimTol_DatumTarget) aDT = new StepDimTol_DatumTarget();
2478       aDT->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString("area"), anAreaSA->OfShape(),
2479         anAreaSA->ProductDefinitional(), aTargetId);
2480       Model->ReplaceEntity(aSANum, aDT);
2481       StepAP242_ItemIdentifiedRepresentationUsageDefinition aDefinition;
2482       aDefinition.SetValue(aDT);
2483       anAreaGISU->SetDefinition(aDefinition);
2484       Model->ReplaceEntity(aGISUNum, anAreaGISU);
2485   }
2486     else {
2487       Handle(StepDimTol_PlacedDatumTargetFeature) aPDTF = new StepDimTol_PlacedDatumTargetFeature();
2488       aPDTF->Init(new TCollection_HAsciiString(), STEPCAFControl_GDTProperty::GetDatumTargetName(aDatumType),
2489         aPDS, StepData_LTrue, aTargetId);
2490       Model->AddWithRefs(aPDTF);
2491       aDatumTarget = aPDTF;
2492       // Datum targets
2493       Handle(StepRepr_PropertyDefinition) aPD = new StepRepr_PropertyDefinition();
2494       StepRepr_CharacterizedDefinition aCDefinition;
2495       aCDefinition.SetValue(aPDTF);
2496       aPD->Init(new TCollection_HAsciiString(), Standard_False, NULL, aCDefinition);
2497       Handle(StepShape_ShapeRepresentationWithParameters) aSRWP = new StepShape_ShapeRepresentationWithParameters();
2498       // Common for all datum targets
2499       StepBasic_Unit aUnit = GetUnit(aRC);
2500       gp_Ax2 aDTAxis = anObject->GetDatumTargetAxis();
2501       Handle(StepGeom_Axis2Placement3d) anA2P3D = 
2502         STEPCAFControl_GDTProperty::GetAxis2Placement3D(aDTAxis);
2503       anA2P3D->SetName(new TCollection_HAsciiString("orientation"));
2504       Handle(StepRepr_HArray1OfRepresentationItem) anItems;
2505       // Process each datum target type
2506       if (aDatumType == XCAFDimTolObjects_DatumTargetType_Point) {
2507         anItems = new StepRepr_HArray1OfRepresentationItem(1, 1);
2508       }
2509       else  {
2510         Handle(TCollection_HAsciiString) aTargetValueName;
2511         if (aDatumType == XCAFDimTolObjects_DatumTargetType_Line) {
2512           anItems = new StepRepr_HArray1OfRepresentationItem(1, 2);
2513           aTargetValueName = new TCollection_HAsciiString("target length");
2514         }
2515         else if (aDatumType == XCAFDimTolObjects_DatumTargetType_Rectangle) {
2516           anItems = new StepRepr_HArray1OfRepresentationItem(1, 3);
2517           aTargetValueName = new TCollection_HAsciiString("target length");
2518           // Additional value
2519           Handle(StepRepr_ReprItemAndMeasureWithUnit) aTargetValue = CreateDimValue(anObject->GetDatumTargetWidth(),
2520             aUnit, new TCollection_HAsciiString("target width"), "POSITIVE_LENGTH_MEASURE", Standard_False);
2521           anItems->SetValue(2, aTargetValue);
2522           Model->AddWithRefs(aTargetValue);
2523         }
2524         else if (aDatumType == XCAFDimTolObjects_DatumTargetType_Circle) {
2525           anItems = new StepRepr_HArray1OfRepresentationItem(1, 2);
2526           aTargetValueName = new TCollection_HAsciiString("target diameter");
2527         }
2528         // Value
2529         Handle(StepRepr_ReprItemAndMeasureWithUnit) aTargetValue= CreateDimValue(anObject->GetDatumTargetLength(),
2530           aUnit, aTargetValueName, "POSITIVE_LENGTH_MEASURE", Standard_False);
2531         anItems->SetValue(1, aTargetValue);
2532         Model->AddWithRefs(aTargetValue);
2533       }
2534       anItems->SetValue(anItems->Length(), anA2P3D);
2535       aSRWP->Init(new TCollection_HAsciiString(), anItems, aRC);
2536   
2537       // Create and write auxiliary entities
2538       Handle (StepShape_ShapeDefinitionRepresentation) aSDR = new StepShape_ShapeDefinitionRepresentation();
2539       StepRepr_RepresentedDefinition aRDefinition;
2540       aRDefinition.SetValue(aPD);
2541       aSDR->Init(aRDefinition, aSRWP);
2542       Model->AddWithRefs(aPD);
2543       Model->AddWithRefs(aSRWP);
2544       Model->AddWithRefs(aSDR);
2545     }
2546     // Link datum target to datum feature
2547     Handle(StepRepr_FeatureForDatumTargetRelationship) aFFDTR = new StepRepr_FeatureForDatumTargetRelationship();
2548     aFFDTR->Init(new TCollection_HAsciiString(), Standard_False, NULL, aDatumTarget, aSA);
2549     Model->AddWithRefs(aFFDTR);
2550     aSA = aDatumTarget;
2551   }
2552
2553   // Datum
2554   Handle(StepDimTol_Datum) aDatum = theWrittenDatum;
2555   if (isFirstDTarget) {
2556     aDatum = new StepDimTol_Datum();
2557     aDatum->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), aPDS, StepData_LTrue, anIdentifier);
2558     Model->AddWithRefs(aDatum);
2559   }
2560
2561   // Shape_Aspect_Relationship
2562   Handle(StepRepr_ShapeAspectRelationship) aSAR = new StepRepr_ShapeAspectRelationship();
2563   aSAR->Init(new TCollection_HAsciiString(), Standard_False, NULL, aSA, aDatum);
2564   Model->AddWithRefs(aSAR);
2565
2566   // Auxiliary entities
2567   // Property_Definition
2568   Handle(StepRepr_PropertyDefinition) aPD = new StepRepr_PropertyDefinition();
2569   Handle(TCollection_HAsciiString) aPDName = new TCollection_HAsciiString("Datum Feature Symbol ");
2570   aPDName = aPDName->Cat(anIdentifier)->Cat(aTargetId);
2571   StepRepr_CharacterizedDefinition aCD;
2572   aCD.SetValue(aSA);
2573   aPD->Init(aPDName, Standard_False, NULL, aCD);
2574   Model->AddWithRefs(aPD);
2575   // Shape_Representation
2576   Handle(StepShape_ShapeRepresentation) aShapeRepr = new StepShape_ShapeRepresentation();
2577   aShapeRepr->Init(aPDName, aGISU->IdentifiedItem(), aRC);
2578   Model->AddWithRefs(aShapeRepr);
2579   // Shape_Definition_Representation
2580   Handle (StepShape_ShapeDefinitionRepresentation) aSDR = new StepShape_ShapeDefinitionRepresentation();
2581   StepRepr_RepresentedDefinition aRDefinition;
2582   aRDefinition.SetValue(aPD);
2583   aSDR->Init(aRDefinition, aShapeRepr);
2584   Model->AddWithRefs(aSDR);
2585
2586   //Annotation plane and Presentation
2587   WritePresentation(WS, anObject->GetPresentation(), anObject->GetPlane(), anObject->GetPointTextAttach(), aSA);
2588
2589   return aDatum;
2590 }
2591
2592 //=======================================================================
2593 //function : WriteDimValues
2594 //purpose  : auxiliary (write all data for given dimension: values, 
2595 //           qualifiers, modifiers, orientation and tolerance class)
2596 //======================================================================
2597 static void WriteDimValues(const Handle(XSControl_WorkSession) &WS,
2598                            const Handle(XCAFDimTolObjects_DimensionObject) theObject,
2599                            const Handle(StepRepr_RepresentationContext) theRC,
2600                            const StepShape_DimensionalCharacteristic theDimension)
2601 {
2602   // Get working data
2603   Handle(Interface_InterfaceModel) aModel = WS->Model();
2604   XCAFDimTolObjects_DimensionModifiersSequence aModifiers = theObject->GetModifiers();
2605   Handle(Standard_Transient) aDim = theDimension.Value();
2606   Standard_Boolean isAngle = aDim->IsKind(STANDARD_TYPE(StepShape_AngularLocation)) ||
2607                              aDim->IsKind(STANDARD_TYPE(StepShape_AngularSize));
2608
2609   // Unit
2610   StepBasic_Unit aUnit = GetUnit(theRC, isAngle);
2611   Standard_CString aMeasureName;
2612   if (isAngle)
2613     aMeasureName = "POSITIVE_PLANE_ANGLE_MEASURE";
2614   else
2615     aMeasureName = "POSITIVE_LENGTH_MEASURE";
2616
2617   // Values
2618   Handle(StepRepr_HArray1OfRepresentationItem) aValues;
2619   Standard_Integer aNbItems = 1, aValIt = 1;
2620   if (theObject->IsDimWithRange())
2621     aNbItems += 2;
2622   if (aModifiers.Length() > 0)
2623     aNbItems++;
2624   if (theObject->GetType() == XCAFDimTolObjects_DimensionType_Location_Oriented)
2625     aNbItems++;
2626   aNbItems += theObject->NbDescriptions();
2627   aValues = new StepRepr_HArray1OfRepresentationItem(1, aNbItems);
2628
2629   // Nominal value
2630   Standard_Real aNominal = theObject->GetValue();
2631   Standard_Integer aLeftNbDigits, aRightNbDigits;
2632   theObject->GetNbOfDecimalPlaces(aLeftNbDigits, aRightNbDigits);
2633   Standard_Integer aNbQualifiers = 0;
2634   if (theObject->HasQualifier() && !isAngle)
2635     aNbQualifiers++;
2636   if (aLeftNbDigits > 0 || aRightNbDigits > 0)
2637     aNbQualifiers++;
2638   // With qualifiers
2639   if (aNbQualifiers > 0) {
2640     Handle(StepShape_QualifiedRepresentationItem) aQRI = new StepShape_QualifiedRepresentationItem();
2641     Handle(StepShape_HArray1OfValueQualifier) aQualifiers = new StepShape_HArray1OfValueQualifier(1, aNbQualifiers);
2642     // Type qualifier
2643     if (theObject->HasQualifier() && !isAngle) {
2644       StepShape_ValueQualifier anItem;
2645       Handle(StepShape_TypeQualifier) aType = new StepShape_TypeQualifier();
2646       XCAFDimTolObjects_DimensionQualifier aQualifier = theObject->GetQualifier();
2647       aType->Init(STEPCAFControl_GDTProperty::GetDimQualifierName(aQualifier));
2648       aModel->AddWithRefs(aType);
2649       anItem.SetValue(aType);
2650       aQualifiers->SetValue(1, anItem);
2651     }
2652     // Number of decimal places
2653     if (aLeftNbDigits > 0 || aRightNbDigits > 0) {
2654       StepShape_ValueQualifier anItem;
2655       Handle(StepShape_ValueFormatTypeQualifier) aType = new StepShape_ValueFormatTypeQualifier();
2656       Handle(TCollection_HAsciiString) aFormatType = new TCollection_HAsciiString("NR2 ");
2657       aFormatType->AssignCat(new TCollection_HAsciiString(aLeftNbDigits));
2658       aFormatType->AssignCat(new TCollection_HAsciiString("."));
2659       aFormatType->AssignCat(new TCollection_HAsciiString(aRightNbDigits));
2660       aType->Init(aFormatType);
2661       aModel->AddWithRefs(aType);
2662       anItem.SetValue(aType);
2663       aQualifiers->SetValue(aNbQualifiers, anItem);
2664     }
2665     // Set qualifiers
2666     aQRI->SetQualifiers(aQualifiers);
2667     Handle(StepRepr_ReprItemAndMeasureWithUnit) anItem = CreateDimValue(aNominal, aUnit,
2668       new TCollection_HAsciiString("nominal value"), aMeasureName, isAngle, Standard_True, aQRI);
2669     aValues->SetValue(aValIt, anItem);
2670     aValIt++;
2671   }
2672   // Without qualifiers
2673   else {
2674     Handle(StepRepr_ReprItemAndMeasureWithUnit) anItem = CreateDimValue(aNominal, aUnit,
2675       new TCollection_HAsciiString("nominal value"), aMeasureName, isAngle);
2676     aValues->SetValue(aValIt, anItem);
2677     aValIt++;
2678   }
2679
2680   // Ranges
2681   if (theObject->IsDimWithRange()) {
2682     Handle(StepRepr_ReprItemAndMeasureWithUnit) aLowerItem = CreateDimValue(theObject->GetLowerBound(), aUnit,
2683       new TCollection_HAsciiString("lower limit"), aMeasureName, isAngle);
2684     Handle(StepRepr_ReprItemAndMeasureWithUnit) anUpperItem = CreateDimValue(theObject->GetUpperBound(), aUnit,
2685       new TCollection_HAsciiString("upper limit"), aMeasureName, isAngle);
2686     aValues->SetValue(aValIt, aLowerItem);
2687     aValIt++;
2688     aValues->SetValue(aValIt, anUpperItem);
2689     aValIt++;
2690   }
2691
2692   // Modifiers
2693   if (aModifiers.Length() > 0) {
2694     Handle(StepRepr_CompoundRepresentationItem) aCompoundRI = new StepRepr_CompoundRepresentationItem();
2695     Handle (StepRepr_HArray1OfRepresentationItem) aModifItems = 
2696       new StepRepr_HArray1OfRepresentationItem(1, aModifiers.Length());
2697     for (Standard_Integer i = 1; i <= aModifiers.Length(); i++) {
2698       XCAFDimTolObjects_DimensionModif aModif = aModifiers.Value(i);
2699       Handle(StepRepr_DescriptiveRepresentationItem) aModifItem = 
2700         new StepRepr_DescriptiveRepresentationItem();
2701       aModifItem->Init(new TCollection_HAsciiString(), STEPCAFControl_GDTProperty::GetDimModifierName(aModif));
2702       aModel->AddWithRefs(aModifItem);
2703       aModifItems->SetValue(i, aModifItem);
2704     }
2705     aCompoundRI->Init(new TCollection_HAsciiString(), aModifItems);
2706     aValues->SetValue(aValIt, aCompoundRI);
2707     aValIt++;
2708   }
2709
2710   // Orientation
2711   if (theObject->GetType() == XCAFDimTolObjects_DimensionType_Location_Oriented) {
2712     Handle(StepGeom_Axis2Placement3d) anOrientation = new StepGeom_Axis2Placement3d();
2713     gp_Dir aDir;
2714     theObject->GetDirection(aDir);
2715     GeomToStep_MakeCartesianPoint MkPoint(theObject->GetPoints()->Value(1));
2716     Handle(StepGeom_CartesianPoint) aLoc = MkPoint.Value();
2717     Handle(StepGeom_Direction) anAxis = new StepGeom_Direction();
2718     Handle(TColStd_HArray1OfReal) aCoords = new TColStd_HArray1OfReal(1, 3);
2719     aCoords->SetValue(1, aDir.X());
2720     aCoords->SetValue(2, aDir.Y());
2721     aCoords->SetValue(3, aDir.Z());
2722     anAxis->Init(new TCollection_HAsciiString(), aCoords);
2723     anOrientation->Init(new TCollection_HAsciiString("orientation"), aLoc, Standard_True, anAxis, Standard_False, NULL);
2724     aValues->SetValue(aValIt, anOrientation);
2725     aValIt++;
2726   }
2727
2728   // Descriptions
2729   if (theObject->HasDescriptions()) {
2730     for (Standard_Integer i = 0; i < theObject->NbDescriptions(); i++) {
2731       Handle(StepRepr_DescriptiveRepresentationItem) aDRI = new StepRepr_DescriptiveRepresentationItem();
2732       aDRI->Init(theObject->GetDescriptionName(i), theObject->GetDescription(i));
2733       aValues->SetValue(aValIt, aDRI);
2734       aValIt++;
2735     }
2736   }
2737
2738   for (Standard_Integer i = 1; i <= aValues->Length(); i++)
2739     aModel->AddWithRefs(aValues->Value(i));
2740
2741   // Create resulting Shape_Dimension_Representation
2742   Handle(StepShape_ShapeDimensionRepresentation) aSDR = new StepShape_ShapeDimensionRepresentation();
2743   aSDR->Init(new TCollection_HAsciiString(), aValues, theRC);
2744   aModel->AddWithRefs(aSDR);
2745   Handle(StepShape_DimensionalCharacteristicRepresentation) aDCR = new StepShape_DimensionalCharacteristicRepresentation();
2746   aDCR->Init(theDimension, aSDR);
2747   aModel->AddWithRefs(aDCR);
2748
2749   // Plus_Minus_Tolerance
2750   if (theObject->IsDimWithPlusMinusTolerance()) {
2751     Handle(TCollection_HAsciiString) aDummyName = new TCollection_HAsciiString(aMeasureName);
2752     aDummyName = aDummyName->SubString(9, aDummyName->Length()); //delete "POSITIVE_"
2753     aMeasureName = aDummyName->ToCString();
2754     Standard_Real aLowerTolValue = -theObject->GetLowerTolValue(),
2755                   anUpperTolValue = theObject->GetUpperTolValue();
2756     // Upper
2757     Handle(StepBasic_MeasureWithUnit) anUpperMWU = new StepBasic_MeasureWithUnit();
2758     Handle(StepBasic_MeasureValueMember) anUpperValue = new StepBasic_MeasureValueMember();
2759     anUpperValue->SetName(aMeasureName);
2760     anUpperValue->SetReal(anUpperTolValue);
2761     anUpperMWU->Init(anUpperValue, aUnit);
2762     aModel->AddWithRefs(anUpperMWU);
2763     // Lower
2764     Handle(StepBasic_MeasureWithUnit) aLowerMWU = new StepBasic_MeasureWithUnit();
2765     Handle(StepBasic_MeasureValueMember) aLowerValue = new StepBasic_MeasureValueMember();
2766     aLowerValue->SetName(aMeasureName);
2767     aLowerValue->SetReal(aLowerTolValue);
2768     aLowerMWU->Init(aLowerValue, aUnit);
2769     aModel->AddWithRefs(aLowerMWU);
2770     // Tolerance
2771     Handle(StepShape_ToleranceValue) aTolValue = new StepShape_ToleranceValue();
2772     aTolValue->Init(aLowerMWU, anUpperMWU);
2773     aModel->AddWithRefs(aTolValue);
2774     StepShape_ToleranceMethodDefinition aMethod;
2775     aMethod.SetValue(aTolValue);
2776     Handle(StepShape_PlusMinusTolerance) aPlusMinusTol = new StepShape_PlusMinusTolerance();
2777     aPlusMinusTol->Init(aMethod, theDimension);
2778     aModel->AddWithRefs(aPlusMinusTol);
2779   }
2780   // Tolerance class
2781   if (theObject->IsDimWithClassOfTolerance()) {
2782     Standard_Boolean isHole;
2783     XCAFDimTolObjects_DimensionFormVariance aFormVariance;
2784     XCAFDimTolObjects_DimensionGrade aGrade;
2785     if (!theObject->GetClassOfTolerance(isHole, aFormVariance, aGrade))
2786       return;
2787     Handle(StepShape_LimitsAndFits) aLAF = STEPCAFControl_GDTProperty::GetLimitsAndFits(isHole, aFormVariance, aGrade);
2788     aModel->AddWithRefs(aLAF);
2789     StepShape_ToleranceMethodDefinition aMethod;
2790     aMethod.SetValue(aLAF);
2791     Handle(StepShape_PlusMinusTolerance) aPlusMinusTol = new StepShape_PlusMinusTolerance();
2792     aPlusMinusTol->Init(aMethod, theDimension);
2793     aModel->AddWithRefs(aPlusMinusTol);
2794   }
2795 }
2796
2797 //=======================================================================
2798 //function : WriteDatumSystem
2799 //purpose  : auxiliary (write Write datum system for given
2800 //           geometric_tolerance)
2801 //======================================================================
2802 static Handle(StepDimTol_HArray1OfDatumSystemOrReference) WriteDatumSystem(const Handle(XSControl_WorkSession) &WS,
2803                                                                            const TDF_Label theGeomTolL,
2804                                                                            const TDF_LabelSequence theDatumSeq,
2805                                                                            const STEPConstruct_DataMapOfAsciiStringTransient theDatumMap,
2806                                                                            const Handle(StepRepr_RepresentationContext)& theRC)
2807 {
2808   // Get working data
2809   Handle(Interface_InterfaceModel) Model = WS->Model();
2810   const Handle(Interface_HGraph) aHGraph = WS->HGraph();
2811   if (aHGraph.IsNull())
2812     return NULL;
2813   Interface_Graph aGraph = aHGraph->Graph();
2814   Handle(XCAFDoc_GeomTolerance) aGTAttr;
2815   if (!theGeomTolL.FindAttribute(XCAFDoc_GeomTolerance::GetID(), aGTAttr)) 
2816     return NULL;
2817   Handle(XCAFDimTolObjects_GeomToleranceObject) anObject = aGTAttr->GetObject();
2818   if (anObject.IsNull())
2819     return NULL;
2820
2821   // Unit
2822   StepBasic_Unit aUnit = GetUnit(theRC);
2823
2824   XCAFDimTolObjects_DatumObjectSequence aDatums;
2825   Standard_Integer aMaxDatumNum = 0;
2826   for (Standard_Integer i = 1; i <= theDatumSeq.Length(); i++) {
2827     Handle(XCAFDoc_Datum) aDatumAttr;
2828     if (!theDatumSeq.Value(i).FindAttribute(XCAFDoc_Datum::GetID(), aDatumAttr)) 
2829       continue;
2830     Handle(XCAFDimTolObjects_DatumObject) aDatumObj = aDatumAttr->GetObject();
2831     if (aDatumObj.IsNull())
2832       continue;
2833     aDatums.Append(aDatumObj);
2834     aMaxDatumNum = Max(aMaxDatumNum, aDatumObj->GetPosition());
2835   }
2836
2837   Handle(StepDimTol_HArray1OfDatumReferenceCompartment) aConstituents =
2838     new StepDimTol_HArray1OfDatumReferenceCompartment(1, aMaxDatumNum);
2839   // Auxiliary datum to initialize attributes in Datum_System
2840   Handle(StepDimTol_Datum) aFirstDatum;
2841   Standard_Integer aConstituentsNum = 0;
2842   for (Standard_Integer i = 1; i <= aMaxDatumNum; i++) {
2843     // Collect datums with i-th position
2844     XCAFDimTolObjects_DatumObjectSequence aDatumSeqPos;
2845     for (Standard_Integer j = 1; j <= aDatums.Length(); j++)
2846       if (aDatums.Value(j)->GetPosition() == i)
2847         aDatumSeqPos.Append(aDatums.Value(j));
2848     if (aDatumSeqPos.Length() < 1)
2849       continue;
2850
2851     aConstituentsNum++;
2852     // Initialize Datum_Reference_Compartment
2853     StepDimTol_DatumOrCommonDatum aDatumRef;
2854     Handle(StepDimTol_DatumReferenceCompartment) aCompartment =
2855       new StepDimTol_DatumReferenceCompartment();
2856     Handle(StepDimTol_HArray1OfDatumReferenceModifier) aModifiers;
2857     if (aDatumSeqPos.Length() == 1) {
2858       // Datum entity
2859       Handle(Standard_Transient) aFDValue;
2860       if (theDatumMap.Find(aDatumSeqPos.Value(1)->GetName()->String(), aFDValue))
2861         aFirstDatum = Handle(StepDimTol_Datum)::DownCast (aFDValue);
2862       aDatumRef.SetValue(aFirstDatum);
2863       // Modifiers
2864       XCAFDimTolObjects_DatumModifiersSequence aSimpleModifiers = aDatumSeqPos.Value(1)->GetModifiers();
2865       XCAFDimTolObjects_DatumModifWithValue aModifWithVal;
2866       Standard_Real aValue = 0;
2867       aDatumSeqPos.Value(1)->GetModifierWithValue(aModifWithVal, aValue);
2868       aModifiers = STEPCAFControl_GDTProperty::GetDatumRefModifiers(aSimpleModifiers, aModifWithVal, aValue, aUnit);
2869       // Add Datum_Reference_Modifier_With_Value
2870       if (!aModifiers.IsNull()) {
2871         Handle(StepDimTol_DatumReferenceModifierWithValue) aDRMWV = 
2872           aModifiers->Value(aModifiers->Length()).DatumReferenceModifierWithValue();
2873         if (!aDRMWV.IsNull()) {
2874           Model->AddWithRefs(aDRMWV);
2875         }
2876       }
2877     }
2878     else {
2879       Handle(StepDimTol_HArray1OfDatumReferenceElement) aCommonDatumList = new StepDimTol_HArray1OfDatumReferenceElement(1, aDatumSeqPos.Length());
2880       for (Standard_Integer j = 1; j <= aDatumSeqPos.Length(); j++) {
2881         // Datum entity
2882         Handle(StepDimTol_Datum) aDatum;
2883         Handle(Standard_Transient) aDValue;
2884         if (theDatumMap.Find(aDatumSeqPos.Value(j)->GetName()->String(), aDValue))
2885           aDatum = Handle(StepDimTol_Datum)::DownCast (aDValue);
2886         StepDimTol_DatumOrCommonDatum anElemDatumRef;
2887         anElemDatumRef.SetValue(aDatum);
2888         if (aFirstDatum.IsNull())
2889           aFirstDatum = aDatum;
2890         // Modifiers
2891         XCAFDimTolObjects_DatumModifiersSequence aSimpleModifiers = aDatumSeqPos.Value(j)->GetModifiers();
2892         XCAFDimTolObjects_DatumModifWithValue aModifWithVal;
2893         Standard_Real aValue = 0;
2894         aDatumSeqPos.Value(j)->GetModifierWithValue(aModifWithVal, aValue);
2895         Handle(StepDimTol_HArray1OfDatumReferenceModifier) anElemModifiers =
2896           STEPCAFControl_GDTProperty::GetDatumRefModifiers(aSimpleModifiers, aModifWithVal, aValue, aUnit);
2897         // Add Datum_Reference_Modifier_With_Value
2898         if (!anElemModifiers.IsNull()) {
2899           Handle(StepDimTol_DatumReferenceModifierWithValue) aDRMWV = 
2900             anElemModifiers->Value(aModifiers->Length()).DatumReferenceModifierWithValue();
2901           if (!aDRMWV.IsNull()) {
2902             Model->AddWithRefs(aDRMWV);
2903           }
2904         }
2905         // Datum_Reference_Element
2906         Handle(StepDimTol_DatumReferenceElement) anElement = new StepDimTol_DatumReferenceElement();
2907         anElement->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), aDatum->OfShape(),
2908           aDatum->ProductDefinitional(), anElemDatumRef, !anElemModifiers.IsNull(), anElemModifiers);
2909         Model->AddWithRefs(anElement);
2910         aCommonDatumList->SetValue(j, anElement);
2911       }
2912       aDatumRef.SetValue(aCommonDatumList);
2913     }
2914     aCompartment->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), aFirstDatum->OfShape(),
2915       aFirstDatum->ProductDefinitional(), aDatumRef, !aModifiers.IsNull(), aModifiers);
2916     Model->AddWithRefs(aCompartment);
2917     aConstituents->SetValue(aConstituentsNum, aCompartment);
2918   }
2919   // Remove null elements from aConstituents
2920   Standard_Integer aNbConstituents = 0;
2921   for (Standard_Integer i = 1; i <= aConstituents->Length(); i++)
2922     if (!aConstituents->Value(i).IsNull())
2923       aNbConstituents++;
2924   Handle(StepDimTol_HArray1OfDatumReferenceCompartment) aResConstituents =
2925     new StepDimTol_HArray1OfDatumReferenceCompartment(1, aNbConstituents);
2926   Standard_Integer aConstituentsIt = 0;
2927   for (Standard_Integer i = 1; i <= aConstituents->Length(); i++)
2928     if (!aConstituents->Value(i).IsNull()) {
2929       aConstituentsIt++;
2930       aResConstituents->SetValue(aConstituentsIt, aConstituents->Value(i));
2931     }
2932
2933   Handle(StepDimTol_HArray1OfDatumSystemOrReference) aDatumSystem;
2934   Handle(StepDimTol_DatumSystem) aDS = new StepDimTol_DatumSystem();
2935   aDS->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(), aFirstDatum->OfShape(),
2936     aFirstDatum->ProductDefinitional(), aResConstituents);
2937   Model->AddWithRefs(aDS);
2938   StepDimTol_DatumSystemOrReference anArrayValue;
2939   anArrayValue.SetValue(aDS);
2940   aDatumSystem = new StepDimTol_HArray1OfDatumSystemOrReference(1, 1);
2941   aDatumSystem->SetValue(1, anArrayValue);
2942
2943   // Axis
2944   if (anObject->HasAxis()) {
2945     Handle(StepGeom_Axis2Placement3d) anAxis =
2946       STEPCAFControl_GDTProperty::GetAxis2Placement3D(anObject->GetAxis());
2947     anAxis->SetName(new TCollection_HAsciiString("orientation"));
2948     Handle(StepAP242_GeometricItemSpecificUsage) aGISU = new StepAP242_GeometricItemSpecificUsage();
2949     StepAP242_ItemIdentifiedRepresentationUsageDefinition aDefinition;
2950     aDefinition.SetValue(aDS);
2951     Handle(StepRepr_HArray1OfRepresentationItem) anReprItems = new StepRepr_HArray1OfRepresentationItem(1, 1);
2952     Handle(StepRepr_RepresentationItem) anIdentifiedItem = anAxis;
2953     anReprItems->SetValue(1, anIdentifiedItem);
2954     Interface_EntityIterator subs = aGraph.Sharings(aFirstDatum->OfShape());
2955     Handle(StepShape_ShapeDefinitionRepresentation) aSDR;
2956     for (subs.Start(); subs.More() && aSDR.IsNull(); subs.Next()) {
2957       Handle(Standard_Transient) anEntity = subs.Value();
2958       aSDR = Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(anEntity);
2959     }
2960     if (aSDR.IsNull())
2961       return aDatumSystem;
2962     
2963     aGISU->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(),
2964       aDefinition, aSDR->UsedRepresentation(), anReprItems);
2965     Model->AddWithRefs(anAxis);
2966     Model->AddWithRefs(aGISU);
2967   }
2968
2969   return aDatumSystem;
2970 }
2971
2972 //=======================================================================
2973 //function : WriteToleranceZone
2974 //purpose  : auxiliary (write tolerace zones)
2975 //=======================================================================
2976 static void WriteToleranceZone (const Handle(XSControl_WorkSession) &WS,
2977                                 const Handle(XCAFDimTolObjects_GeomToleranceObject)& theObject,
2978                                 const Handle(StepDimTol_GeometricTolerance)& theEntity,
2979                                 const Handle(StepRepr_RepresentationContext)& theRC)
2980 {
2981   // Get working data
2982   Handle(Interface_InterfaceModel) Model = WS->Model();
2983   if (theEntity.IsNull() || theObject.IsNull())
2984     return;
2985
2986   // Return if there is no tolerance zones
2987   if (theObject->GetTypeOfValue() == XCAFDimTolObjects_GeomToleranceTypeValue_None &&
2988       theObject->GetZoneModifier() != XCAFDimTolObjects_GeomToleranceZoneModif_Runout)
2989     return;
2990
2991   // Create Tolerance_Zone
2992   Handle(StepDimTol_ToleranceZoneForm) aForm = new StepDimTol_ToleranceZoneForm();
2993   Model->AddWithRefs(aForm);
2994   aForm->Init(STEPCAFControl_GDTProperty::GetTolValueType(theObject->GetTypeOfValue()));
2995   Handle(StepDimTol_HArray1OfToleranceZoneTarget) aZoneTargetArray = new StepDimTol_HArray1OfToleranceZoneTarget(1, 1);
2996   StepDimTol_ToleranceZoneTarget aTarget;
2997   aTarget.SetValue(theEntity);
2998   aZoneTargetArray->SetValue(1, aTarget);
2999   Handle(StepDimTol_ToleranceZone) aZone = new StepDimTol_ToleranceZone();
3000   aZone->Init(new TCollection_HAsciiString(), new TCollection_HAsciiString(),
3001     theEntity->TolerancedShapeAspect().ShapeAspect()->OfShape(), StepData_LFalse,
3002     aZoneTargetArray, aForm);
3003   Model->AddWithRefs(aZone);
3004
3005   // Runout_Tolerance_Zone
3006   Handle(StepBasic_PlaneAngleMeasureWithUnit) aPAMWU = new StepBasic_PlaneAngleMeasureWithUnit();
3007   Handle(StepBasic_MeasureValueMember) aValueMember = new StepBasic_MeasureValueMember();
3008   aValueMember->SetName("PLANE_ANGLE_MEASURE");
3009   aValueMember->SetReal(theObject->GetValueOfZoneModifier());
3010   aPAMWU->Init(aValueMember, GetUnit(theRC, Standard_True));
3011   Handle(StepDimTol_RunoutZoneOrientation) anOrientation = new StepDimTol_RunoutZoneOrientation();
3012   anOrientation->Init(aPAMWU);
3013   Handle(StepDimTol_RunoutZoneDefinition) aDefinition = new StepDimTol_RunoutZoneDefinition();
3014   aDefinition->Init(aZone, NULL, anOrientation);
3015   Model->AddWithRefs(aDefinition);
3016   Model->AddWithRefs(anOrientation);
3017   Model->AddWithRefs(aPAMWU);
3018 }
3019
3020 //=======================================================================
3021 //function : WriteGeomTolerance
3022 //purpose  : auxiliary (write Geometric_Tolerance entity for given shapes,
3023 //           label and datum system)
3024 //======================================================================
3025 static void WriteGeomTolerance (const Handle(XSControl_WorkSession) &WS,
3026                                 const TDF_LabelSequence theShapeSeqL,
3027                                 const TDF_Label theGeomTolL,
3028                                 const Handle(StepDimTol_HArray1OfDatumSystemOrReference)& theDatumSystem,
3029                                 const Handle(StepRepr_RepresentationContext)& theRC)
3030 {
3031   // Get working data
3032   Handle(Interface_InterfaceModel) Model = WS->Model();
3033   Handle(XCAFDoc_GeomTolerance) aGTAttr;
3034   if (!theGeomTolL.FindAttribute(XCAFDoc_GeomTolerance::GetID(), aGTAttr)) 
3035     return;
3036   Handle(XCAFDimTolObjects_GeomToleranceObject) anObject = aGTAttr->GetObject();
3037   if (anObject.IsNull())
3038     return;
3039
3040   // Value
3041   Handle(StepBasic_LengthMeasureWithUnit) aLMWU = new StepBasic_LengthMeasureWithUnit();
3042   StepBasic_Unit aUnit = GetUnit(theRC);
3043   Handle(StepBasic_MeasureValueMember) aValueMember = new StepBasic_MeasureValueMember();
3044   aValueMember->SetName("LENGTH_MEASURE");
3045   aValueMember->SetReal(anObject->GetValue());
3046   aLMWU->Init(aValueMember, aUnit);
3047   Model->AddWithRefs(aLMWU);
3048
3049   // Geometric_Tolerance target
3050   Handle(StepRepr_ShapeAspect) aMainSA;
3051   Handle(StepRepr_RepresentationContext) dummyRC;
3052   Handle(StepAP242_GeometricItemSpecificUsage) dummyGISU;
3053   if (theShapeSeqL.Length() == 1) {
3054     TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(theShapeSeqL.Value(1));
3055     aMainSA = WriteShapeAspect(WS, theGeomTolL, aShape, dummyRC, dummyGISU);
3056     Model->AddWithRefs(aMainSA);
3057   }
3058   else {
3059     Handle(StepRepr_CompositeShapeAspect) aCSA;
3060     for (Standard_Integer i = 1; i <= theShapeSeqL.Length(); i++) {
3061       TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(theShapeSeqL.Value(i));
3062       Handle(StepRepr_ShapeAspect) aSA = WriteShapeAspect(WS, theGeomTolL, aShape, dummyRC, dummyGISU);
3063       if (aSA.IsNull())
3064         continue;
3065       if (aCSA.IsNull()) {
3066         aCSA = new StepRepr_CompositeShapeAspect();
3067         aCSA->Init(aSA->Name(), aSA->Description(), aSA->OfShape(), aSA->ProductDefinitional());
3068         Model->AddWithRefs(aCSA);
3069       }
3070       Handle(StepRepr_ShapeAspectRelationship) aSAR = new StepRepr_ShapeAspectRelationship();
3071       aSAR->Init(new TCollection_HAsciiString(), Standard_False, NULL, aCSA, aSA);
3072       Model->AddWithRefs(aSAR);
3073     }
3074     aMainSA = aCSA;
3075   }
3076   StepDimTol_GeometricToleranceTarget aGTTarget;
3077   aGTTarget.SetValue(aMainSA);
3078
3079   Standard_Boolean isWithModif = Standard_False,
3080                    isWithDatRef = Standard_False,
3081                    isWithMaxTol = Standard_False;
3082   // Modifiers
3083   // Simple modifiers
3084   XCAFDimTolObjects_GeomToleranceModifiersSequence aModifiers = anObject->GetModifiers();
3085   Handle(StepDimTol_HArray1OfGeometricToleranceModifier) aModifArray;
3086   Handle(StepBasic_LengthMeasureWithUnit) aMaxLMWU;
3087   Standard_Integer aModifNb = aModifiers.Length();
3088   if (anObject->GetMaterialRequirementModifier() != XCAFDimTolObjects_GeomToleranceMatReqModif_None)
3089       aModifNb++;
3090   for (Standard_Integer i = 1; i < aModifiers.Length(); i++)
3091     if (aModifiers.Value(i) == XCAFDimTolObjects_GeomToleranceModif_All_Around ||
3092         aModifiers.Value(i) == XCAFDimTolObjects_GeomToleranceModif_All_Over)
3093         aModifNb--;
3094   if (aModifNb > 0) {
3095     isWithModif = Standard_True;
3096     aModifArray = new StepDimTol_HArray1OfGeometricToleranceModifier(1, aModifNb);
3097     Standard_Integer k = 1;
3098     for (Standard_Integer i = 1; i <= aModifiers.Length(); i++) {
3099       if (aModifiers.Value(i) == XCAFDimTolObjects_GeomToleranceModif_All_Around ||
3100         aModifiers.Value(i) == XCAFDimTolObjects_GeomToleranceModif_All_Over)
3101         continue;
3102       StepDimTol_GeometricToleranceModifier aModif = 
3103         STEPCAFControl_GDTProperty::GetGeomToleranceModifier(aModifiers.Value(i));
3104       aModifArray->SetValue(k, aModif);
3105       k++;
3106     }
3107     if (anObject->GetMaterialRequirementModifier() == XCAFDimTolObjects_GeomToleranceMatReqModif_L) {
3108       aModifArray->SetValue(aModifNb, StepDimTol_GTMLeastMaterialRequirement);
3109     }
3110     else if (anObject->GetMaterialRequirementModifier() == XCAFDimTolObjects_GeomToleranceMatReqModif_M) {
3111       aModifArray->SetValue(aModifNb, StepDimTol_GTMMaximumMaterialRequirement);
3112     }
3113     // Modifier with value
3114     if (anObject->GetMaxValueModifier() != 0) {
3115       isWithMaxTol = Standard_True;
3116       aMaxLMWU = new StepBasic_LengthMeasureWithUnit();
3117       Handle(StepBasic_MeasureValueMember) aModifierValueMember = new StepBasic_MeasureValueMember();
3118       aModifierValueMember->SetName("LENGTH_MEASURE");
3119       aModifierValueMember->SetReal(anObject->GetMaxValueModifier());
3120       aMaxLMWU->Init(aModifierValueMember, aUnit);
3121       Model->AddWithRefs(aMaxLMWU);
3122     }
3123   }
3124
3125   // Datum Reference
3126   isWithDatRef = !theDatumSystem.IsNull();
3127
3128   // Collect all attributes
3129   Handle(TCollection_HAsciiString) aName = new TCollection_HAsciiString(),
3130                                   aDescription = new TCollection_HAsciiString();
3131   Handle(StepDimTol_GeometricToleranceWithDatumReference) aGTWDR = 
3132     new StepDimTol_GeometricToleranceWithDatumReference();
3133   aGTWDR->SetDatumSystem(theDatumSystem);
3134   Handle(StepDimTol_GeometricToleranceWithModifiers) aGTWM = 
3135     new StepDimTol_GeometricToleranceWithModifiers();
3136   aGTWM->SetModifiers(aModifArray);
3137   StepDimTol_GeometricToleranceType aType = 
3138     STEPCAFControl_GDTProperty::GetGeomToleranceType(anObject->GetType());
3139
3140   // Init and write necessary subtype of Geometric_Tolerance entity
3141   Handle(StepDimTol_GeometricTolerance) aGeomTol;
3142   if (isWithModif) {
3143     if (isWithMaxTol) {
3144       if (isWithDatRef) {
3145         // Geometric_Tolerance & Geometric_Tolerance_With_Datum_Reference & 
3146         //Geometric_Tolerance_With_Maximum_Tolerance & Geometric_Tolerance_With_Modifiers
3147         Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol) aResult =
3148           new StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMaxTol();
3149         aResult->Init(aName, aDescription, aLMWU, aGTTarget, aGTWDR, aGTWM, aMaxLMWU, aType);
3150         aGeomTol = aResult;
3151       }
3152       else {
3153         // Geometric_Tolerance & Geometric_Tolerance_With_Maximum_Tolerance & Geometric_Tolerance_With_Modifiers
3154         Handle(StepDimTol_GeoTolAndGeoTolWthMaxTol) aResult =
3155           new StepDimTol_GeoTolAndGeoTolWthMaxTol();
3156         aResult->Init(aName, aDescription, aLMWU, aGTTarget, aGTWM, aMaxLMWU, aType);
3157         aGeomTol = aResult;
3158       }
3159     }
3160     else {
3161       if (isWithDatRef) {
3162         // Geometric_Tolerance & Geometric_Tolerance_With_Datum_Reference & Geometric_Tolerance_With_Modifiers
3163         Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod) aResult =
3164           new StepDimTol_GeoTolAndGeoTolWthDatRefAndGeoTolWthMod();
3165         aResult->Init(aName, aDescription, aLMWU, aGTTarget, aGTWDR, aGTWM, aType);
3166         aGeomTol = aResult;
3167       }
3168       else {
3169         // Geometric_Tolerance & Geometric_Tolerance_With_Modifiers
3170         Handle(StepDimTol_GeoTolAndGeoTolWthMod) aResult =
3171           new StepDimTol_GeoTolAndGeoTolWthMod();
3172         aResult->Init(aName, aDescription, aLMWU, aGTTarget, aGTWM, aType);
3173         aGeomTol = aResult;
3174       }
3175     }
3176   }
3177   else {
3178     if (isWithDatRef) {
3179       // Geometric_Tolerance & Geometric_Tolerance_With_Datum_Reference
3180       Handle(StepDimTol_GeoTolAndGeoTolWthDatRef) aResult =
3181           new StepDimTol_GeoTolAndGeoTolWthDatRef();
3182         aResult->Init(aName, aDescription, aLMWU, aGTTarget, aGTWDR, aType);
3183         aGeomTol = aResult;
3184     }
3185     else {
3186       // Geometric_Tolerance
3187       Handle(StepDimTol_GeometricTolerance) aResult = 
3188         STEPCAFControl_GDTProperty::GetGeomTolerance(anObject->GetType());
3189       if (!aResult.IsNull()) {
3190         aResult->Init(aName, aDescription, aLMWU, aGTTarget);
3191         aGeomTol = aResult;
3192       }
3193     }
3194   }
3195   Model->AddWithRefs(aGeomTol);
3196   WriteToleranceZone(WS, anObject, aGeomTol, theRC);
3197   //Annotation plane and Presentation
3198   WritePresentation(WS, anObject->GetPresentation(), anObject->GetPlane(), anObject->GetPointTextAttach(), aGeomTol);
3199 }
3200
3201 //=======================================================================
3202 //function : WriteDGTs
3203 //purpose  : 
3204 //=======================================================================
3205 Standard_Boolean STEPCAFControl_Writer::WriteDGTs (const Handle(XSControl_WorkSession) &WS,
3206                                                    const TDF_LabelSequence  &labels ) const
3207 {
3208   
3209   if ( labels.Length() <=0 ) return Standard_False;
3210   
3211   // get working data
3212   Handle(Interface_InterfaceModel) Model = WS->Model();
3213   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
3214   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
3215
3216   const Handle(Interface_HGraph) aHGraph = WS->HGraph();
3217   if(aHGraph.IsNull())
3218     return Standard_False;
3219
3220   Interface_Graph aGraph = aHGraph->Graph();
3221   Handle(XCAFDoc_DimTolTool) DGTTool = XCAFDoc_DocumentTool::DimTolTool( labels(1) );
3222   if(DGTTool.IsNull() ) return Standard_False;
3223
3224   TDF_LabelSequence DGTLabels;
3225
3226   STEPConstruct_DataMapOfAsciiStringTransient DatumMap;
3227
3228   // write Datums
3229   DGTLabels.Clear();
3230   DGTTool->GetDatumLabels(DGTLabels);
3231   if(DGTLabels.Length()<=0) return Standard_False;
3232   Standard_Integer i;
3233   for(i=1; i<=DGTLabels.Length(); i++) {
3234     TDF_Label DatumL = DGTLabels.Value(i);
3235     TDF_LabelSequence ShapeL;
3236     TDF_LabelSequence aNullSeq;
3237     if(!DGTTool->GetRefShapeLabel(DatumL,ShapeL,aNullSeq)) continue;
3238     // find target shape
3239     TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(ShapeL.Value(1));
3240     TopLoc_Location Loc;
3241     TColStd_SequenceOfTransient seqRI;
3242     FindEntities( FP, aShape, Loc, seqRI );
3243     if ( seqRI.Length() <= 0 ) {
3244       FP->Messenger() << "Warning: Cannot find RI for "<<aShape.TShape()->DynamicType()->Name()<<endl;
3245       continue;
3246     }
3247     Handle(StepRepr_ProductDefinitionShape) PDS;
3248     Handle(StepRepr_RepresentationContext) RC;
3249     Handle(Standard_Transient) ent = seqRI.Value(1);
3250     Handle(StepShape_AdvancedFace) AF;
3251     Handle(StepShape_EdgeCurve) EC;
3252     FindPDSforDGT(aGraph,ent,PDS,RC,AF,EC);
3253     if(PDS.IsNull()) continue;
3254     //cout<<"Model->Number(PDS)="<<Model->Number(PDS)<<endl;
3255     Handle(XCAFDoc_Datum) DatumAttr;
3256     if(!DatumL.FindAttribute(XCAFDoc_Datum::GetID(),DatumAttr)) continue;
3257     Handle(TCollection_HAsciiString) aName = DatumAttr->GetName();
3258     Handle(TCollection_HAsciiString) aDescription = DatumAttr->GetDescription();
3259     Handle(TCollection_HAsciiString) anIdentification = DatumAttr->GetIdentification();
3260     Handle(StepDimTol_DatumFeature) DF = new StepDimTol_DatumFeature;
3261     Handle(StepDimTol_Datum) aDatum = new StepDimTol_Datum;
3262     DF->Init(aName, new TCollection_HAsciiString, PDS, StepData_LTrue);
3263     Model->AddWithRefs(DF);
3264     aDatum->Init(aName, new TCollection_HAsciiString, PDS, StepData_LFalse, anIdentification);
3265     Model->AddWithRefs(aDatum);
3266     Handle(StepRepr_ShapeAspectRelationship) SAR = new StepRepr_ShapeAspectRelationship;
3267     SAR->SetName(aName);
3268     SAR->SetRelatingShapeAspect(DF);
3269     SAR->SetRelatedShapeAspect(aDatum);
3270     Model->AddWithRefs(SAR);
3271     // write chain for DatumFeature
3272     StepRepr_CharacterizedDefinition CD;
3273     CD.SetValue(DF);
3274     Handle(StepRepr_PropertyDefinition) PropD = new StepRepr_PropertyDefinition;
3275     PropD->Init(aName,Standard_True,aDescription,CD);
3276     Model->AddWithRefs(PropD);
3277     StepRepr_RepresentedDefinition RD;
3278     RD.SetValue(PropD);
3279     Handle(StepShape_ShapeRepresentation) SR = new StepShape_ShapeRepresentation;
3280     Handle(StepRepr_HArray1OfRepresentationItem) HARI =
3281       new StepRepr_HArray1OfRepresentationItem(1,1);
3282     HARI->SetValue(1,AF);
3283     SR->Init(aName,HARI,RC);
3284     Handle(StepShape_ShapeDefinitionRepresentation) SDR = new StepShape_ShapeDefinitionRepresentation;
3285     SDR->Init(RD,SR);
3286     Model->AddWithRefs(SDR);
3287     // write chain for Datum 
3288     StepRepr_CharacterizedDefinition CD1;
3289     CD1.SetValue(aDatum);
3290     Handle(StepRepr_PropertyDefinition) PropD1 = new StepRepr_PropertyDefinition;
3291     PropD1->Init(aName,Standard_True,aDescription,CD1);
3292     Model->AddWithRefs(PropD1);
3293     StepRepr_RepresentedDefinition RD1;
3294     RD1.SetValue(PropD1);
3295     Handle(StepShape_ShapeRepresentation) SR1 = new StepShape_ShapeRepresentation;
3296     Handle(StepRepr_HArray1OfRepresentationItem) HARI1 =
3297       new StepRepr_HArray1OfRepresentationItem(1,1);
3298     HARI1->SetValue(1,AF->FaceGeometry());
3299     SR1->Init(aName,HARI1,RC);
3300     Model->AddWithRefs(SR1);
3301     Handle(StepShape_ShapeDefinitionRepresentation) SDR1 = new StepShape_ShapeDefinitionRepresentation;
3302     SDR1->Init(RD1,SR1);
3303     Model->AddWithRefs(SDR1);
3304     // add created Datum into Map
3305     TCollection_AsciiString stmp(aName->ToCString());
3306     stmp.AssignCat(aDescription->ToCString());
3307     stmp.AssignCat(anIdentification->ToCString());
3308     DatumMap.Bind(stmp,aDatum);
3309   }
3310
3311   // write Tolerances and Dimensions
3312   DGTLabels.Clear();
3313   DGTTool->GetDimTolLabels(DGTLabels);
3314   if(DGTLabels.Length()<=0) return Standard_False;
3315   for(i=1; i<=DGTLabels.Length(); i++) {
3316     TDF_Label DimTolL = DGTLabels.Value(i);
3317     TDF_LabelSequence ShapeL;
3318     TDF_LabelSequence aNullSeq;
3319     if(!DGTTool->GetRefShapeLabel(DimTolL,ShapeL,aNullSeq)) continue;
3320     // find target shape
3321     TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(ShapeL.Value(1));
3322     TopLoc_Location Loc;
3323     TColStd_SequenceOfTransient seqRI;
3324     FindEntities( FP, aShape, Loc, seqRI );
3325     if ( seqRI.Length() <= 0 ) {
3326       FP->Messenger() << "Warning: Cannot find RI for "<<aShape.TShape()->DynamicType()->Name()<<endl;
3327       continue;
3328     }
3329     Handle(StepRepr_ProductDefinitionShape) PDS;
3330     Handle(StepRepr_RepresentationContext) RC;
3331     Handle(Standard_Transient) ent = seqRI.Value(1);
3332     Handle(StepShape_AdvancedFace) AF;
3333     Handle(StepShape_EdgeCurve) EC;
3334     FindPDSforDGT(aGraph,ent,PDS,RC,AF,EC);
3335     if(PDS.IsNull()) continue;
3336     //cout<<"Model->Number(PDS)="<<Model->Number(PDS)<<endl;
3337
3338     Handle(XCAFDoc_DimTol) DimTolAttr;
3339     if(!DimTolL.FindAttribute(XCAFDoc_DimTol::GetID(),DimTolAttr)) continue;
3340     Standard_Integer kind = DimTolAttr->GetKind();
3341     Handle(TColStd_HArray1OfReal) aVal = DimTolAttr->GetVal();
3342     Handle(TCollection_HAsciiString) aName = DimTolAttr->GetName();
3343     Handle(TCollection_HAsciiString) aDescription = DimTolAttr->GetDescription();
3344
3345     // common part of writing D&GT entities
3346     StepRepr_CharacterizedDefinition CD;
3347     Handle(StepRepr_ShapeAspect) SA = new StepRepr_ShapeAspect;
3348     SA->Init(aName, new TCollection_HAsciiString, PDS, StepData_LTrue);
3349     Model->AddWithRefs(SA);
3350     CD.SetValue(SA);
3351     Handle(StepRepr_PropertyDefinition) PropD = new StepRepr_PropertyDefinition;
3352     PropD->Init(aName,Standard_True,aDescription,CD);
3353     Model->AddWithRefs(PropD);
3354     StepRepr_RepresentedDefinition RD;
3355     RD.SetValue(PropD);
3356     Handle(StepShape_ShapeRepresentation) SR = new StepShape_ShapeRepresentation;
3357     Handle(StepRepr_HArray1OfRepresentationItem) HARI =
3358       new StepRepr_HArray1OfRepresentationItem(1,1);
3359     if(kind<20) 
3360       HARI->SetValue(1,EC);
3361     else
3362       HARI->SetValue(1,AF);
3363     SR->Init(aName,HARI,RC);
3364     Handle(StepShape_ShapeDefinitionRepresentation) SDR = new StepShape_ShapeDefinitionRepresentation;
3365     SDR->Init(RD,SR);
3366     Model->AddWithRefs(SDR);
3367     // define aUnit for creation LengthMeasureWithUnit (common for all)
3368     StepBasic_Unit aUnit;
3369     Handle(StepBasic_SiUnitAndLengthUnit) SLU;
3370     Handle(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext) Ctx =
3371       Handle(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext)::DownCast(RC);
3372     if(!Ctx.IsNull()) {
3373       for(Standard_Integer j=1; j<=Ctx->NbUnits(); j++) {
3374         if(Ctx->UnitsValue(j)->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndLengthUnit))) {
3375           SLU = Handle(StepBasic_SiUnitAndLengthUnit)::DownCast(Ctx->UnitsValue(j));
3376           break;
3377         }
3378       }
3379     }
3380     if(SLU.IsNull()) {
3381       Handle(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx) Ctx1 =
3382         Handle(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx)::DownCast(RC);
3383       if(!Ctx1.IsNull()) {
3384         for(Standard_Integer j=1; j<=Ctx1->NbUnits(); j++) {
3385           if(Ctx1->UnitsValue(j)->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndLengthUnit))) {
3386             SLU = Handle(StepBasic_SiUnitAndLengthUnit)::DownCast(Ctx1->UnitsValue(j));
3387             break;
3388           }
3389         }
3390       }
3391     }
3392     if(SLU.IsNull()) {
3393       SLU = new StepBasic_SiUnitAndLengthUnit;
3394     }
3395     aUnit.SetValue(SLU);
3396
3397     // specific part of writing D&GT entities
3398     if(kind<20) { //dimension
3399       Handle(StepShape_DimensionalSize) DimSize = new StepShape_DimensionalSize;
3400       DimSize->Init(SA,aDescription);
3401       Model->AddWithRefs(DimSize);
3402       if(aVal->Length()>1) {
3403         // create MeasureWithUnits
3404         Handle(StepBasic_MeasureValueMember) MVM1 = new StepBasic_MeasureValueMember;
3405         MVM1->SetName("POSITIVE_LENGTH_MEASURE");
3406         MVM1->SetReal(aVal->Value(1));
3407         Handle(StepBasic_MeasureWithUnit) MWU1 = new StepBasic_MeasureWithUnit;
3408         MWU1->Init(MVM1,aUnit);
3409         Handle(StepBasic_MeasureValueMember) MVM2 = new StepBasic_MeasureValueMember;
3410         MVM2->SetName("POSITIVE_LENGTH_MEASURE");
3411         MVM2->SetReal(aVal->Value(2));
3412         Handle(StepBasic_MeasureWithUnit) MWU2 = new StepBasic_MeasureWithUnit;
3413         MWU2->Init(MVM2,aUnit);
3414         Handle(StepRepr_RepresentationItem) RI1 = new StepRepr_RepresentationItem;
3415         RI1->Init(new TCollection_HAsciiString("lower limit"));
3416         Handle(StepRepr_RepresentationItem) RI2 = new StepRepr_RepresentationItem;
3417         RI2->Init(new TCollection_HAsciiString("upper limit"));
3418         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMU1 =
3419           new StepRepr_ReprItemAndLengthMeasureWithUnit;
3420         RILMU1->Init(MWU1,RI1);
3421         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMU2 =
3422           new StepRepr_ReprItemAndLengthMeasureWithUnit;
3423         RILMU2->Init(MWU2,RI2);
3424         Model->AddWithRefs(RILMU1);
3425         Model->AddWithRefs(RILMU2);
3426         //Handle(StepRepr_CompoundItemDefinitionMember) CIDM =
3427         //  new StepRepr_CompoundItemDefinitionMember;
3428         //Handle(TColStd_HArray1OfTransient) ArrTr = new TColStd_HArray1OfTransient(1,2);
3429         //ArrTr->SetValue(1,RILMU1);
3430         //ArrTr->SetValue(2,RILMU2);
3431         //CIDM->SetArrTransient(ArrTr);
3432         //CIDM->SetName("SET_REPRESENTATION_ITEM");
3433         //StepRepr_CompoundItemDefinition CID;
3434         //CID.SetValue(CIDM);
3435         Handle(StepRepr_HArray1OfRepresentationItem) HARIVR =
3436           new StepRepr_HArray1OfRepresentationItem(1,2);
3437         HARIVR->SetValue(1,RILMU1);
3438         HARIVR->SetValue(2,RILMU2);
3439         Handle(StepRepr_ValueRange) VR = new StepRepr_ValueRange;
3440         //VR->Init(aName,CID);
3441         VR->Init(aName,HARIVR);
3442         Model->AddEntity(VR);
3443         Handle(StepShape_ShapeDimensionRepresentation) SDimR =
3444           new StepShape_ShapeDimensionRepresentation;
3445         Handle(StepRepr_HArray1OfRepresentationItem) aHARI =
3446           new StepRepr_HArray1OfRepresentationItem(1,1);
3447         aHARI->SetValue(1,VR);
3448         SDimR->Init(aName,aHARI,RC);
3449         Model->AddWithRefs(SDimR);
3450         Handle(StepShape_DimensionalCharacteristicRepresentation) DimCharR =
3451           new StepShape_DimensionalCharacteristicRepresentation;
3452         StepShape_DimensionalCharacteristic DimChar;
3453         DimChar.SetValue(DimSize);
3454         DimCharR->Init(DimChar,SDimR);
3455         Model->AddEntity(DimCharR);
3456       }
3457     }
3458     else if(kind<50) { //tolerance
3459       if(kind<35) { // tolerance with datum system
3460         TDF_LabelSequence DatumLabels;
3461         DGTTool->GetDatumOfTolerLabels(DimTolL,DatumLabels);
3462         Standard_Integer NbDR = DatumLabels.Length();
3463         Handle(StepDimTol_HArray1OfDatumReference) HADR = new StepDimTol_HArray1OfDatumReference(1,NbDR);
3464         for(Standard_Integer j=1; j<=NbDR; j++) {
3465           Handle(XCAFDoc_Datum) DatumAttr;
3466           TDF_Label DatumL = DatumLabels.Value(j);
3467           if(!DatumL.FindAttribute(XCAFDoc_Datum::GetID(),DatumAttr)) continue;
3468           Handle(TCollection_HAsciiString) aNameD = DatumAttr->GetName();
3469           Handle(TCollection_HAsciiString) aDescriptionD = DatumAttr->GetDescription();
3470           Handle(TCollection_HAsciiString) anIdentificationD = DatumAttr->GetIdentification();
3471           TCollection_AsciiString stmp(aNameD->ToCString());
3472           stmp.AssignCat(aDescriptionD->ToCString());
3473           stmp.AssignCat(anIdentificationD->ToCString());
3474           if(DatumMap.IsBound(stmp)) {
3475             Handle(StepDimTol_Datum) aDatum = 
3476               Handle(StepDimTol_Datum)::DownCast(DatumMap.Find(stmp));
3477             Handle(StepDimTol_DatumReference) DR = new StepDimTol_DatumReference;
3478             DR->Init(j,aDatum);
3479             Model->AddWithRefs(DR);
3480             HADR->SetValue(j,DR);
3481           }
3482         }
3483         // create LengthMeasureWithUnit
3484         Handle(StepBasic_MeasureValueMember) MVM = new StepBasic_MeasureValueMember;
3485         MVM->SetName("LENGTH_MEASURE");
3486         MVM->SetReal(aVal->Value(1));
3487         Handle(StepBasic_LengthMeasureWithUnit) LMWU = new StepBasic_LengthMeasureWithUnit;
3488         LMWU->Init(MVM,aUnit);
3489         // create tolerance by it's type
3490         if(kind<24) {
3491           Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
3492             new StepDimTol_GeometricToleranceWithDatumReference;
3493           GTWDR->SetDatumSystem(HADR);
3494           Handle(StepDimTol_ModifiedGeometricTolerance) MGT =
3495             new StepDimTol_ModifiedGeometricTolerance;
3496           if(kind==21) MGT->SetModifier(StepDimTol_MaximumMaterialCondition);
3497           else if(kind==22) MGT->SetModifier(StepDimTol_LeastMaterialCondition);
3498           else if(kind==23) MGT->SetModifier(StepDimTol_RegardlessOfFeatureSize);
3499           Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol) GTComplex =
3500             new StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol;
3501           GTComplex->Init(aName,aDescription,LMWU,SA,GTWDR,MGT);
3502           Model->AddWithRefs(GTComplex);
3503         }
3504         else if(kind==24) {
3505           Handle(StepDimTol_AngularityTolerance) aToler =
3506             new StepDimTol_AngularityTolerance;
3507           aToler->Init(aName,aDescription,LMWU,SA,HADR);
3508           Model->AddWithRefs(aToler);
3509         }
3510         else if(kind==25) {
3511           Handle(StepDimTol_CircularRunoutTolerance) aToler =
3512             new StepDimTol_CircularRunoutTolerance;
3513           aToler->Init(aName,aDescription,LMWU,SA,HADR);
3514           Model->AddWithRefs(aToler);
3515         }
3516         else if(kind==26) {
3517           Handle(StepDimTol_CoaxialityTolerance) aToler =
3518             new StepDimTol_CoaxialityTolerance;
3519           aToler->Init(aName,aDescription,LMWU,SA,HADR);
3520           Model->AddWithRefs(aToler);
3521         }
3522         else if(kind==27) {
3523           Handle(StepDimTol_ConcentricityTolerance) aToler =
3524             new StepDimTol_ConcentricityTolerance;
3525           aToler->Init(aName,aDescription,LMWU,SA,HADR);
3526           Model->AddWithRefs(aToler);
3527         }
3528         else if(kind==28) {
3529           Handle(StepDimTol_ParallelismTolerance) aToler =
3530             new StepDimTol_ParallelismTolerance;
3531           aToler->Init(aName,aDescription,LMWU,SA,HADR);
3532           Model->AddWithRefs(aToler);
3533         }
3534         else if(kind==29) {
3535           Handle(StepDimTol_PerpendicularityTolerance) aToler =
3536             new StepDimTol_PerpendicularityTolerance;
3537           aToler->Init(aName,aDescription,LMWU,SA,HADR);
3538           Model->AddWithRefs(aToler);
3539         }
3540         else if(kind==30) {
3541           Handle(StepDimTol_SymmetryTolerance) aToler =
3542             new StepDimTol_SymmetryTolerance;
3543           aToler->Init(aName,aDescription,LMWU,SA,HADR);
3544           Model->AddWithRefs(aToler);
3545         }
3546         else if(kind==31) {
3547           Handle(StepDimTol_TotalRunoutTolerance) aToler =
3548             new StepDimTol_TotalRunoutTolerance;
3549           aToler->Init(aName,aDescription,LMWU,SA,HADR);
3550           Model->AddWithRefs(aToler);
3551         }
3552       }
3553     }
3554   }
3555
3556   return Standard_True;
3557 }
3558
3559 //=======================================================================
3560 //function : WriteDGTsAP242
3561 //purpose  : 
3562 //=======================================================================
3563
3564 Standard_Boolean STEPCAFControl_Writer::WriteDGTsAP242 (const Handle(XSControl_WorkSession) &WS,
3565                                                         const TDF_LabelSequence  &labels ) const
3566 {
3567   // Get working data
3568   Handle(Interface_InterfaceModel) aModel = WS->Model();
3569   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
3570   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
3571
3572   const Handle(Interface_HGraph) aHGraph = WS->HGraph();
3573   if(aHGraph.IsNull())
3574     return Standard_False;
3575
3576   Interface_Graph aGraph = aHGraph->Graph();
3577   Handle(XCAFDoc_DimTolTool) DGTTool = XCAFDoc_DocumentTool::DimTolTool(labels(1));
3578   if(DGTTool.IsNull())
3579     return Standard_False;
3580
3581   // Common entities for presentation
3582   gdtPresentationDM = new StepVisual_DraughtingModel();
3583   STEPConstruct_Styles aStyles (WS);
3584   Handle(StepVisual_Colour) aCurvColor = aStyles.EncodeColor(Quantity_NOC_WHITE);
3585   Handle(StepRepr_RepresentationItem) anItem = NULL;
3586   gdtPrsCurveStyle = new StepVisual_HArray1OfPresentationStyleAssignment(1, 1);
3587   gdtPrsCurveStyle->SetValue(1, aStyles.MakeColorPSA(anItem, aCurvColor, aCurvColor));
3588
3589   TDF_LabelSequence aDGTLabels;
3590   STEPConstruct_DataMapOfAsciiStringTransient aDatumMap;
3591   Handle(StepRepr_RepresentationContext) aRC;
3592
3593   //------------- //
3594   // write Datums //
3595   //--------------//
3596   DGTTool->GetDatumLabels(aDGTLabels);
3597   // Find all shapes with datums
3598   TColStd_MapOfAsciiString aNameIdMap;
3599   for(Standard_Integer i = 1; i <= aDGTLabels.Length(); i++) {
3600     TDF_Label aDatumL = aDGTLabels.Value(i);
3601     TDF_LabelSequence aShapeL;
3602     TDF_LabelSequence aNullSeq;
3603     if(!DGTTool->GetRefShapeLabel(aDatumL, aShapeL, aNullSeq))
3604       continue;
3605     Handle(XCAFDoc_Datum) aDatumAttr;
3606     aDatumL.FindAttribute(XCAFDoc_Datum::GetID(), aDatumAttr);
3607     Handle(XCAFDimTolObjects_DatumObject) anObject = aDatumAttr->GetObject();
3608     TCollection_AsciiString aDatumName = anObject->GetName()->String();
3609     TCollection_AsciiString aDatumTargetId = TCollection_AsciiString(anObject->GetDatumTargetNumber());
3610     if (!aNameIdMap.Add(aDatumName.Cat(aDatumTargetId)))
3611       continue;
3612     Handle(Standard_Transient) aWrittenDatum;
3613     Standard_Boolean isFirstDT = !aDatumMap.Find(aDatumName, aWrittenDatum);
3614     Handle(StepDimTol_Datum) aDatum = WriteDatumAP242(WS, aShapeL.First(), aDatumL, isFirstDT, 
3615                                                       Handle(StepDimTol_Datum)::DownCast (aWrittenDatum));
3616     // Add created Datum into Map
3617     aDatumMap.Bind(aDatumName, aDatum);
3618   }
3619
3620   //----------------- //
3621   // write Dimensions //
3622   //------------------//
3623   aDGTLabels.Clear();
3624   DGTTool->GetDimensionLabels(aDGTLabels);
3625   for (Standard_Integer i = 1; i <= aDGTLabels.Length(); i++) {
3626     TDF_Label aDimensionL = aDGTLabels.Value(i);
3627     TDF_LabelSequence aFirstShapeL, aSecondShapeL;
3628     if (!DGTTool->GetRefShapeLabel(aDimensionL, aFirstShapeL, aSecondShapeL))
3629       continue;
3630     Handle(XCAFDoc_Dimension) aDimAttr;
3631     if (!aDimensionL.FindAttribute(XCAFDoc_Dimension::GetID(),aDimAttr)) 
3632       continue;
3633     Handle(XCAFDimTolObjects_DimensionObject) anObject = aDimAttr->GetObject();
3634     if (anObject.IsNull())
3635       continue;
3636
3637     // Write links with shapes
3638     Handle(StepRepr_RepresentationContext) dummyRC;
3639     Handle(StepAP242_GeometricItemSpecificUsage) dummyGISU;
3640     Handle(StepRepr_ShapeAspect) aFirstSA, aSecondSA;
3641     if (aFirstShapeL.Length() == 1) {
3642       TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(aFirstShapeL.Value(1));
3643       aFirstSA = WriteShapeAspect(WS, aDimensionL, aShape, dummyRC, dummyGISU);
3644       if (aRC.IsNull() && !dummyRC.IsNull())
3645         aRC = dummyRC;
3646     }
3647     else if (aFirstShapeL.Length() > 1) {
3648       Handle(StepRepr_CompositeShapeAspect) aCSA;
3649       for (Standard_Integer shIt = 1; shIt <= aFirstShapeL.Length(); shIt++) {
3650         TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(aFirstShapeL.Value(shIt));
3651         Handle(StepRepr_ShapeAspect) aSA = WriteShapeAspect(WS, aDimensionL, aShape, dummyRC, dummyGISU);
3652         if (aCSA.IsNull() && !aSA.IsNull())
3653           aCSA = new StepRepr_CompositeShapeAspect();
3654           aCSA->Init(aSA->Name(), aSA->Description(), aSA->OfShape(), aSA->ProductDefinitional());
3655           aModel->AddWithRefs(aCSA);
3656         if (!aSA.IsNull()) {
3657           Handle(StepRepr_ShapeAspectRelationship) aSAR = new StepRepr_ShapeAspectRelationship();
3658           aSAR->Init(new TCollection_HAsciiString(), Standard_False, new TCollection_HAsciiString(), aCSA, aSA);
3659           aModel->AddWithRefs(aSAR);
3660         }
3661         if (aRC.IsNull() && !dummyRC.IsNull())
3662           aRC = dummyRC;
3663       }
3664       aFirstSA = aCSA;
3665     }
3666     if (aSecondShapeL.Length() == 1) {
3667       TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(aSecondShapeL.Value(1));
3668       aSecondSA = WriteShapeAspect(WS, aDimensionL, aShape, dummyRC, dummyGISU);
3669       if (aRC.IsNull() && !dummyRC.IsNull())
3670         aRC = dummyRC;
3671     }
3672     else if (aSecondShapeL.Length() > 1) {
3673       Handle(StepRepr_CompositeShapeAspect) aCSA;
3674       for (Standard_Integer shIt = 1; shIt <= aSecondShapeL.Length(); shIt++) {
3675         TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(aSecondShapeL.Value(shIt));
3676         Handle(StepRepr_ShapeAspect) aSA = WriteShapeAspect(WS, aDimensionL, aShape, dummyRC, dummyGISU);
3677         if (aCSA.IsNull() && !aSA.IsNull())
3678           aCSA = new StepRepr_CompositeShapeAspect();
3679           aCSA->Init(aSA->Name(), aSA->Description(), aSA->OfShape(), aSA->ProductDefinitional());
3680         if (!aSA.IsNull()) {
3681           Handle(StepRepr_ShapeAspectRelationship) aSAR = new StepRepr_ShapeAspectRelationship();
3682           aSAR->Init(new TCollection_HAsciiString(), Standard_False, new TCollection_HAsciiString(), aCSA, aSA);
3683           aModel->AddWithRefs(aSAR);
3684         }
3685         if (aRC.IsNull() && !dummyRC.IsNull())
3686           aRC = dummyRC;
3687       }
3688       aSecondSA = aCSA;
3689     }
3690
3691     // Write dimensions
3692     StepShape_DimensionalCharacteristic aDimension;
3693     XCAFDimTolObjects_DimensionType aDimType = anObject->GetType();
3694     if (STEPCAFControl_GDTProperty::IsDimensionalLocation(aDimType)) {
3695       // Dimensional_Location
3696       Handle(StepShape_DimensionalLocation) aDim = new StepShape_DimensionalLocation();
3697       aDim->Init(STEPCAFControl_GDTProperty::GetDimTypeName(aDimType), Standard_False, NULL, aFirstSA, aSecondSA);
3698       aDimension.SetValue(aDim);
3699     }
3700     else if (aDimType == XCAFDimTolObjects_DimensionType_Location_Angular) {
3701       // Angular_Location
3702       Handle(StepShape_AngularLocation) aDim = new StepShape_AngularLocation();
3703       StepShape_AngleRelator aRelator = StepShape_Equal;
3704       if (anObject->HasQualifier()) {
3705         XCAFDimTolObjects_DimensionQualifier aQualifier = anObject->GetQualifier();
3706         switch (aQualifier) {
3707           case XCAFDimTolObjects_DimensionQualifier_Min: aRelator = StepShape_Small;
3708             break;
3709           case XCAFDimTolObjects_DimensionQualifier_Max: aRelator = StepShape_Large;
3710             break;
3711           default: aRelator = StepShape_Equal;
3712         }
3713       }
3714       aDim->Init(new TCollection_HAsciiString(), Standard_False, NULL, aFirstSA, aSecondSA, aRelator);
3715       aDimension.SetValue(aDim);
3716     }
3717     else if (aDimType == XCAFDimTolObjects_DimensionType_Location_WithPath) {
3718       // Dimensional_Location_With_Path
3719       Handle(StepShape_DimensionalLocationWithPath) aDim = new StepShape_DimensionalLocationWithPath();
3720       Handle(StepRepr_ShapeAspect) aPathSA = WriteShapeAspect(WS, aDimensionL, anObject->GetPath(), dummyRC, dummyGISU);
3721       aDim->Init(new TCollection_HAsciiString(), Standard_False, NULL, aFirstSA, aSecondSA, aPathSA);
3722       aDimension.SetValue(aDim);
3723     }
3724     else if (STEPCAFControl_GDTProperty::IsDimensionalSize(aDimType)) {
3725       // Dimensional_Size
3726       Handle(StepShape_DimensionalSize) aDim = new StepShape_DimensionalSize();
3727       aDim->Init(aFirstSA, STEPCAFControl_GDTProperty::GetDimTypeName(aDimType));
3728       aDimension.SetValue(aDim);
3729     }
3730     else if (aDimType == XCAFDimTolObjects_DimensionType_Size_Angular) {
3731       // Angular_Size
3732       Handle(StepShape_AngularSize) aDim = new StepShape_AngularSize();
3733       StepShape_AngleRelator aRelator = StepShape_Equal;
3734       if (anObject->HasQualifier()) {
3735         XCAFDimTolObjects_DimensionQualifier aQualifier = anObject->GetQualifier();
3736         switch (aQualifier) {
3737           case XCAFDimTolObjects_DimensionQualifier_Min: aRelator = StepShape_Small;
3738             break;
3739           case XCAFDimTolObjects_DimensionQualifier_Max: aRelator = StepShape_Large;
3740             break;
3741           default: aRelator = StepShape_Equal;
3742         }
3743       }
3744       aDim->Init(aFirstSA, new TCollection_HAsciiString(), aRelator);
3745       aDimension.SetValue(aDim);
3746     }
3747     else if (aDimType == XCAFDimTolObjects_DimensionType_Size_WithPath) {
3748       // Dimensional_Size_With_Path
3749       Handle(StepShape_DimensionalSizeWithPath) aDim = new StepShape_DimensionalSizeWithPath();
3750       Handle(StepRepr_ShapeAspect) aPathSA = WriteShapeAspect(WS, aDimensionL, anObject->GetPath(), dummyRC, dummyGISU);
3751       aDim->Init(aFirstSA, new TCollection_HAsciiString(), aPathSA);
3752       aDimension.SetValue(aDim);
3753     }
3754
3755     // Write values
3756     WriteDimValues(WS, anObject, aRC, aDimension);
3757     //Annotation plane and Presentation
3758     WritePresentation(WS, anObject->GetPresentation(), anObject->GetPlane(), anObject->GetPointTextAttach(), aDimension.Value());
3759   }
3760
3761   //----------------------------//
3762   // write Geometric Tolerances //
3763   //----------------------------//
3764   aDGTLabels.Clear();
3765   DGTTool->GetGeomToleranceLabels(aDGTLabels);
3766   for (Standard_Integer i = 1; i <= aDGTLabels.Length(); i++) {
3767     TDF_Label aGeomTolL = aDGTLabels.Value(i);
3768     TDF_LabelSequence aFirstShapeL, aNullSeqL;
3769     if (!DGTTool->GetRefShapeLabel(aGeomTolL, aFirstShapeL, aNullSeqL))
3770       continue;
3771     TDF_LabelSequence aDatumSeq;
3772     DGTTool->GetDatumWithObjectOfTolerLabels(aGeomTolL, aDatumSeq);
3773     Handle(StepDimTol_HArray1OfDatumSystemOrReference) aDatumSystem;
3774     if (aDatumSeq.Length() > 0)
3775       aDatumSystem = WriteDatumSystem(WS, aGeomTolL, aDatumSeq, aDatumMap, aRC);
3776     WriteGeomTolerance(WS, aFirstShapeL, aGeomTolL, aDatumSystem, aRC);
3777   }
3778
3779   // Write Draughting model for Annotation Planes
3780   if (gdtAnnotationPlanes.Length() == 0)
3781     return Standard_True;
3782
3783   Handle(StepRepr_HArray1OfRepresentationItem) aItems =
3784     new StepRepr_HArray1OfRepresentationItem(1, gdtAnnotationPlanes.Length());
3785   for (Standard_Integer i = 1; i <= aItems->Length(); i++) {
3786     aItems->SetValue(i, gdtAnnotationPlanes.Value(i - 1));
3787   }
3788   gdtPresentationDM->Init(new TCollection_HAsciiString(), aItems, aRC);
3789   aModel->AddWithRefs(gdtPresentationDM);
3790
3791   return Standard_True;
3792 }
3793
3794 //=======================================================================
3795 //function : FindPDSforRI
3796 //purpose  : auxilary: 
3797 //=======================================================================
3798 static Standard_Boolean FindPDSforRI(const Interface_Graph &aGraph,
3799                                      const Handle(Standard_Transient) &ent,
3800                                      Handle(StepRepr_ProductDefinitionShape) &PDS,
3801                                      Handle(StepRepr_RepresentationContext) &RC)
3802 {
3803   if(!ent->IsKind(STANDARD_TYPE(StepRepr_RepresentationItem))) return Standard_False;
3804   Interface_EntityIterator subs = aGraph.Sharings(ent);
3805   for(subs.Start(); subs.More() && PDS.IsNull(); subs.Next()) {
3806     Handle(StepShape_ShapeRepresentation) SR = 
3807       Handle(StepShape_ShapeRepresentation)::DownCast(subs.Value());
3808     if(SR.IsNull()) continue;
3809     RC = SR->ContextOfItems();
3810     Interface_EntityIterator subs1 = aGraph.Sharings(SR);
3811     for(subs1.Start(); subs1.More() && PDS.IsNull(); subs1.Next()) {
3812       Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
3813         Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs1.Value());
3814       if(SDR.IsNull()) continue;
3815       Handle(StepRepr_PropertyDefinition) PropD = SDR->Definition().PropertyDefinition();
3816       if(PropD.IsNull()) continue;
3817       PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(PropD);
3818     }
3819   }
3820   return Standard_True;
3821 }
3822
3823
3824 //=======================================================================
3825 //function : WriteMaterials
3826 //purpose  : 
3827 //=======================================================================
3828
3829 Standard_Boolean STEPCAFControl_Writer::WriteMaterials (const Handle(XSControl_WorkSession) &WS,
3830                                                         const TDF_LabelSequence  &labels ) const
3831 {
3832   
3833   if ( labels.Length() <=0 ) return Standard_False;
3834
3835   // get working data
3836   Handle(Interface_InterfaceModel) Model = WS->Model();
3837   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
3838   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
3839
3840   const Handle(Interface_HGraph) aHGraph = WS->HGraph();
3841   if(aHGraph.IsNull())
3842     return Standard_False;
3843
3844   Interface_Graph aGraph = WS->HGraph()->Graph();
3845   Handle(XCAFDoc_ShapeTool) ShTool = XCAFDoc_DocumentTool::ShapeTool( labels(1) );
3846   if(ShTool.IsNull() ) return Standard_False;
3847   Handle(XCAFDoc_MaterialTool) MatTool = XCAFDoc_DocumentTool::MaterialTool( labels(1) );
3848   if(MatTool.IsNull() ) return Standard_False;
3849
3850   STEPConstruct_DataMapOfAsciiStringTransient MapDRI,MapMRI;
3851   TDF_LabelSequence TopLabels;
3852   ShTool->GetShapes(TopLabels);
3853   for(Standard_Integer i=1; i<=TopLabels.Length(); i++) {
3854     TDF_Label ShL = TopLabels.Value(i);
3855     Handle(TDataStd_TreeNode) Node;
3856     if( ShL.FindAttribute(XCAFDoc::MaterialRefGUID(),Node) && Node->HasFather() ) {
3857       // find PDS for current shape
3858       TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(ShL);
3859       TopLoc_Location Loc;
3860       TColStd_SequenceOfTransient seqRI;
3861       FindEntities( FP, aShape, Loc, seqRI );
3862       if(seqRI.Length()<=0) continue;
3863       Handle(StepRepr_ProductDefinitionShape) PDS;
3864       Handle(StepRepr_RepresentationContext) RC;
3865       Handle(Standard_Transient) ent = seqRI.Value(1);
3866       FindPDSforRI(aGraph,ent,PDS,RC);
3867       if(PDS.IsNull()) continue;
3868       Handle(StepBasic_ProductDefinition) aProdDef = 
3869         PDS->Definition().ProductDefinition();
3870       if(aProdDef.IsNull())
3871         continue;
3872       // write material entities
3873       TDF_Label MatL = Node->Father()->Label();
3874       Handle(TCollection_HAsciiString) aName;
3875       Handle(TCollection_HAsciiString) aDescription;
3876       Standard_Real aDensity;
3877       Handle(TCollection_HAsciiString) aDensName;
3878       Handle(TCollection_HAsciiString) aDensValType;
3879       Handle(StepRepr_Representation) RepDRI;
3880       Handle(StepRepr_Representation) RepMRI;
3881       if(MatTool->GetMaterial(MatL,aName,aDescription,aDensity,aDensName,aDensValType)) {
3882         if(aName->Length()==0) continue;
3883         TCollection_AsciiString aKey(aName->ToCString());
3884         if(MapDRI.IsBound(aKey)) {
3885           RepDRI = Handle(StepRepr_Representation)::DownCast(MapDRI.Find(aKey));
3886           if(MapMRI.IsBound(aKey)) {
3887             RepMRI = Handle(StepRepr_Representation)::DownCast(MapMRI.Find(aKey));
3888           }
3889         }
3890         else {
3891           // write DRI
3892           Handle(StepRepr_DescriptiveRepresentationItem) DRI = new StepRepr_DescriptiveRepresentationItem;
3893           DRI->Init(aName,aDescription);
3894           Handle(StepRepr_HArray1OfRepresentationItem) HARI = new StepRepr_HArray1OfRepresentationItem(1,1);
3895           HARI->SetValue(1,DRI);
3896           RepDRI = new StepRepr_Representation();
3897           RepDRI->Init(new TCollection_HAsciiString("material name"),HARI,RC);
3898           Model->AddWithRefs(RepDRI);
3899           // write MRI
3900           if( aDensity > 0 ) {
3901             // mass
3902             Handle(StepBasic_SiUnitAndMassUnit) SMU = new StepBasic_SiUnitAndMassUnit;
3903             SMU->SetName(StepBasic_sunGram);
3904             Handle(StepBasic_DerivedUnitElement) DUE1 = new StepBasic_DerivedUnitElement;
3905             DUE1->Init(SMU,3.0);
3906             // length
3907             Handle(StepBasic_SiUnitAndLengthUnit) SLU = new StepBasic_SiUnitAndLengthUnit;
3908             SLU->Init(Standard_True,StepBasic_spCenti,StepBasic_sunMetre);
3909             Handle(StepBasic_DerivedUnitElement) DUE2 = new StepBasic_DerivedUnitElement;
3910             DUE2->Init(SLU,2.0);
3911             // other
3912             Handle(StepBasic_HArray1OfDerivedUnitElement) HADUE = new StepBasic_HArray1OfDerivedUnitElement(1,2);
3913             HADUE->SetValue(1,DUE1);
3914             HADUE->SetValue(2,DUE2);
3915             Handle(StepBasic_DerivedUnit) DU = new StepBasic_DerivedUnit;
3916             DU->Init(HADUE);
3917             Model->AddWithRefs(DU);
3918             StepBasic_Unit aUnit;
3919             aUnit.SetValue(DU);
3920             Handle(StepBasic_MeasureValueMember) MVM = new StepBasic_MeasureValueMember;
3921             MVM->SetName(aDensValType->ToCString());
3922             MVM->SetReal(aDensity);
3923             Handle(StepRepr_MeasureRepresentationItem) MRI = new StepRepr_MeasureRepresentationItem;
3924             MRI->Init(aDensName,MVM,aUnit);
3925             HARI = new StepRepr_HArray1OfRepresentationItem(1,1);
3926             HARI->SetValue(1,MRI);
3927             RepMRI = new StepRepr_Representation();
3928             RepMRI->Init(new TCollection_HAsciiString("density"),HARI,RC);
3929             Model->AddWithRefs(RepMRI);
3930           }
3931           //WriteNewMaterial(Model,aName,aDescription,aDensity,aDensName,aDensValType,RC,RepDRI,RepMRI);
3932           MapDRI.Bind(aKey,RepDRI);
3933           if ( !RepMRI.IsNull() ) MapMRI.Bind (aKey, RepMRI);
3934         }
3935       }
3936       
3937       if( !RepDRI.IsNull() )
3938       {
3939         StepRepr_CharacterizedDefinition CD1;
3940         CD1.SetValue(aProdDef);
3941         Handle(StepRepr_PropertyDefinition) PropD1 = new StepRepr_PropertyDefinition;
3942         PropD1->Init(new TCollection_HAsciiString("material property"),Standard_True,
3943           new TCollection_HAsciiString("material name"),CD1);
3944         Model->AddWithRefs(PropD1);
3945         StepRepr_RepresentedDefinition RD1;
3946         RD1.SetValue(PropD1);
3947         Handle(StepRepr_PropertyDefinitionRepresentation) PDR1 =
3948           new StepRepr_PropertyDefinitionRepresentation;
3949         PDR1->Init(RD1,RepDRI);
3950         Model->AddWithRefs(PDR1);
3951
3952         if( !RepMRI.IsNull() )
3953         {
3954           StepRepr_CharacterizedDefinition CD2;
3955           CD2.SetValue (aProdDef);
3956           Handle (StepRepr_PropertyDefinition) PropD2 = new StepRepr_PropertyDefinition;
3957           PropD2->Init (new TCollection_HAsciiString ("material property"), Standard_True,
3958             new TCollection_HAsciiString ("density"), CD2);
3959           Model->AddWithRefs (PropD2);
3960           StepRepr_RepresentedDefinition RD2;
3961           RD2.SetValue (PropD2);
3962           Handle (StepRepr_PropertyDefinitionRepresentation) PDR2 =
3963             new StepRepr_PropertyDefinitionRepresentation;
3964           PDR2->Init (RD2, RepMRI);
3965           Model->AddWithRefs (PDR2);
3966         }
3967       }
3968     }
3969   }
3970
3971   return Standard_True;
3972 }
3973
3974
3975 //=======================================================================
3976 //function : SetColorMode
3977 //purpose  : 
3978 //=======================================================================
3979
3980 void STEPCAFControl_Writer::SetColorMode (const Standard_Boolean colormode)
3981 {
3982   myColorMode = colormode;
3983 }
3984
3985
3986 //=======================================================================
3987 //function : GetColorMode
3988 //purpose  : 
3989 //=======================================================================
3990
3991 Standard_Boolean STEPCAFControl_Writer::GetColorMode () const
3992 {
3993   return myColorMode;
3994 }
3995
3996
3997 //=======================================================================
3998 //function : SetNameMode
3999 //purpose  : 
4000 //=======================================================================
4001
4002 void STEPCAFControl_Writer::SetNameMode (const Standard_Boolean namemode)
4003 {
4004   myNameMode = namemode;
4005 }
4006
4007
4008 //=======================================================================
4009 //function : GetNameMode
4010 //purpose  : 
4011 //=======================================================================
4012
4013 Standard_Boolean STEPCAFControl_Writer::GetNameMode () const
4014 {
4015   return myNameMode;
4016 }
4017
4018
4019 //=======================================================================
4020 //function : SetLayerMode
4021 //purpose  : 
4022 //=======================================================================
4023
4024 void STEPCAFControl_Writer::SetLayerMode (const Standard_Boolean layermode)
4025 {
4026   myLayerMode = layermode;
4027 }
4028
4029
4030 //=======================================================================
4031 //function : GetLayerMode
4032 //purpose  : 
4033 //=======================================================================
4034
4035 Standard_Boolean STEPCAFControl_Writer::GetLayerMode () const
4036 {
4037   return myLayerMode;
4038 }
4039
4040
4041 //=======================================================================
4042 //function : SetPropsMode
4043 //purpose  : 
4044 //=======================================================================
4045
4046 void STEPCAFControl_Writer::SetPropsMode (const Standard_Boolean propsmode)
4047 {
4048   myPropsMode = propsmode;
4049 }
4050
4051
4052 //=======================================================================
4053 //function : GetPropsMode
4054 //purpose  : 
4055 //=======================================================================
4056
4057 Standard_Boolean STEPCAFControl_Writer::GetPropsMode () const
4058 {
4059   return myPropsMode;
4060 }
4061
4062
4063 //=======================================================================
4064 //function : SetSHUOMode
4065 //purpose  : 
4066 //=======================================================================
4067
4068 void STEPCAFControl_Writer::SetSHUOMode (const Standard_Boolean mode)
4069 {
4070   mySHUOMode = mode;
4071 }
4072
4073
4074 //=======================================================================
4075 //function : GetSHUOMode
4076 //purpose  : 
4077 //=======================================================================
4078
4079 Standard_Boolean STEPCAFControl_Writer::GetSHUOMode () const
4080 {
4081   return mySHUOMode;
4082 }
4083
4084
4085 //=======================================================================
4086 //function : SetDimTolMode
4087 //purpose  : 
4088 //=======================================================================
4089
4090 void STEPCAFControl_Writer::SetDimTolMode(const Standard_Boolean dimtolmode)
4091 {
4092   myDGTMode = dimtolmode;
4093 }
4094
4095
4096 //=======================================================================
4097 //function : GetDimTolMode
4098 //purpose  : 
4099 //=======================================================================
4100
4101 Standard_Boolean STEPCAFControl_Writer::GetDimTolMode() const
4102 {
4103   return myDGTMode;
4104 }
4105
4106
4107 //=======================================================================
4108 //function : SetMaterialMode
4109 //purpose  : 
4110 //=======================================================================
4111
4112 void STEPCAFControl_Writer::SetMaterialMode(const Standard_Boolean matmode)
4113 {
4114   myMatMode = matmode;
4115 }
4116
4117
4118 //=======================================================================
4119 //function : GetMaterialMode
4120 //purpose  : 
4121 //=======================================================================
4122
4123 Standard_Boolean STEPCAFControl_Writer::GetMaterialMode() const
4124 {
4125   return myMatMode;
4126 }