0022627: Change OCCT memory management defaults
[occt.git] / src / STEPCAFControl / STEPCAFControl_Writer.cxx
1 // File:        STEPCAFControl_Writer.cxx
2 // Created:     Tue Aug 15 17:35:36 2000
3 // Author:      Andrey BETENEV
4 //              <abv@doomox.nnov.matra-dtv.fr>
5 //
6 // CURRENT LIMITATIONS: 
7 //
8 // when val props and names assigned to instance of 
9 // component in assembly, it is in fact supposed that only one CDSR corresponds
10 // to such shape. This can be wrong and should be handled more carefully
11 // (analysis of SDRs which the CDSR links should be done)
12 //
13 // Names and validation props are supported for top-level shapes only
14
15 #include <STEPCAFControl_Writer.ixx>
16 #include <STEPControl_StepModelType.hxx>
17 #include <XCAFDoc_ShapeTool.hxx>
18 #include <TDF_LabelSequence.hxx>
19 #include <TopoDS_Shape.hxx>
20 #include <XCAFPrs_DataMapOfShapeStyle.hxx>
21 #include <XCAFPrs.hxx>
22 #include <XCAFPrs_DataMapOfStyleShape.hxx>
23 #include <XCAFPrs_Style.hxx>
24 #include <XCAFPrs_DataMapIteratorOfDataMapOfStyleShape.hxx>
25 #include <TopTools_SequenceOfShape.hxx>
26 #include <TopoDS_Iterator.hxx>
27 #include <STEPConstruct_Styles.hxx>
28 #include <XCAFDoc_ColorTool.hxx>
29 #include <STEPConstruct.hxx>
30 #include <TopTools_MapOfShape.hxx>
31 #include <XSControl_TransferWriter.hxx>
32 #include <TDataStd_Name.hxx>
33 #include <StepShape_ShapeDefinitionRepresentation.hxx>
34 #include <TransferBRep_ShapeMapper.hxx>
35 #include <TransferBRep.hxx>
36 #include <StepRepr_PropertyDefinition.hxx>
37 #include <StepBasic_ProductDefinition.hxx>
38 #include <StepBasic_Product.hxx>
39 #include <TCollection_HAsciiString.hxx>
40 #include <TCollection_AsciiString.hxx>
41 #include <Transfer_FinderProcess.hxx>
42 #include <StepBasic_ProductDefinitionFormation.hxx>
43 #include <XCAFDoc_DocumentTool.hxx>
44 #include <TDF_Label.hxx>
45 #include <STEPCAFControl_Controller.hxx>
46 #include <STEPCAFControl_IteratorOfDictionaryOfExternFile.hxx>
47 #include <STEPConstruct_ExternRefs.hxx>
48 #include <Interface_Static.hxx>
49 #include <TopoDS_Compound.hxx>
50 #include <BRep_Builder.hxx>
51 #include <Transfer_ActorOfFinderProcess.hxx>
52 #include <STEPCAFControl_ActorWrite.hxx>
53 #include <STEPConstruct_ValidationProps.hxx>
54 #include <XCAFDoc_Area.hxx>
55 #include <XCAFDoc_Volume.hxx>
56 #include <XCAFDoc_Centroid.hxx>
57 #include <StepShape_ContextDependentShapeRepresentation.hxx>
58 #include <StepRepr_ProductDefinitionShape.hxx>
59 #include <StepBasic_ProductDefinitionRelationship.hxx>
60 #include <XCAFDoc_GraphNode.hxx>
61 #include <XCAFDoc_LayerTool.hxx>
62 #include <StepVisual_PresentationLayerAssignment.hxx>
63 #include <XCAFDoc.hxx>
64 #include <StepVisual_HArray1OfLayeredItem.hxx>
65 #include <TColStd_HSequenceOfTransient.hxx>
66 #include <TDF_Tool.hxx>
67 #include <Message_Messenger.hxx>
68
69 #include <Transfer_Binder.hxx>
70 #include <Transfer_TransientListBinder.hxx>
71 #include <StepVisual_InvisibleItem.hxx>
72 #include <TDataStd_UAttribute.hxx>
73 #include <StepVisual_Invisibility.hxx>
74 #include <StepVisual_HArray1OfInvisibleItem.hxx>
75 #include <HeaderSection_FileSchema.hxx>
76 #include <StepData_StepModel.hxx>
77 #include <StepAP214_Protocol.hxx>
78 #include <OSD_Path.hxx>
79 #include <XSControl_WorkSession.hxx>
80 #include <StepRepr_HArray1OfRepresentationItem.hxx>
81 #include <MoniTool_DataMapIteratorOfDataMapOfShapeTransient.hxx>
82 #include <StepRepr_Representation.hxx>
83 #include <StepVisual_MechanicalDesignGeometricPresentationRepresentation.hxx>
84 #include <Quantity_TypeOfColor.hxx>
85 #include <StepVisual_HArray1OfPresentationStyleAssignment.hxx>
86 #include <StepVisual_PresentationStyleAssignment.hxx>
87 #include <StepVisual_StyledItem.hxx>
88 #include <StepVisual_PresentationStyleByContext.hxx>
89 #include <StepVisual_HArray1OfPresentationStyleSelect.hxx>
90 #include <TDF_AttributeSequence.hxx>
91 #include <TColStd_MapOfTransient.hxx>
92 // #include <TColStd_IndexedDataMapOfTransientTransient.hxx>
93 #include <StepRepr_NextAssemblyUsageOccurrence.hxx>
94 #include <Interface_EntityIterator.hxx>
95 #include <StepRepr_SpecifiedHigherUsageOccurrence.hxx>
96
97 // added by skl 15.01.2004 for D&GT writing
98 #include <XCAFDoc_DimTolTool.hxx>
99 #include <XCAFDoc_DimTol.hxx>
100 #include <XCAFDoc_Datum.hxx>
101 #include <STEPConstruct_DataMapOfAsciiStringTransient.hxx>
102 #include <STEPConstruct_DataMapOfPointTransient.hxx>
103 #include <StepBasic_MeasureValueMember.hxx>
104 #include <StepBasic_SiUnitAndLengthUnit.hxx>
105 #include <StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext.hxx>
106 #include <StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx.hxx>
107 #include <StepBasic_LengthMeasureWithUnit.hxx>
108 #include <StepShape_EdgeCurve.hxx>
109 #include <StepShape_AdvancedFace.hxx>
110 #include <StepShape_OrientedEdge.hxx>
111 #include <StepShape_EdgeLoop.hxx>
112 #include <StepShape_FaceBound.hxx>
113 #include <StepShape_ConnectedFaceSet.hxx>
114 #include <StepShape_ShapeRepresentation.hxx>
115 #include <StepShape_DimensionalSize.hxx>
116 #include <StepShape_ShapeDimensionRepresentation.hxx>
117 #include <StepShape_DimensionalCharacteristicRepresentation.hxx>
118 #include <StepRepr_ShapeAspect.hxx>
119 #include <StepRepr_ShapeAspectRelationship.hxx>
120 #include <StepRepr_ReprItemAndLengthMeasureWithUnit.hxx>
121 //#include <StepRepr_CompoundItemDefinition.hxx>
122 //#include <StepRepr_CompoundItemDefinitionMember.hxx>
123 #include <StepRepr_ValueRange.hxx>
124 #include <StepData_Logical.hxx>
125 #include <StepDimTol_DatumFeature.hxx>
126 #include <StepDimTol_Datum.hxx>
127 #include <StepDimTol_DatumReference.hxx>
128 #include <StepDimTol_HArray1OfDatumReference.hxx>
129 #include <StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol.hxx>
130 #include <StepDimTol_ModifiedGeometricTolerance.hxx>
131 #include <StepDimTol_GeometricToleranceWithDatumReference.hxx>
132 #include <StepDimTol_AngularityTolerance.hxx>
133 #include <StepDimTol_CircularRunoutTolerance.hxx>
134 #include <StepDimTol_CoaxialityTolerance.hxx>
135 #include <StepDimTol_ConcentricityTolerance.hxx>
136 #include <StepDimTol_ParallelismTolerance.hxx>
137 #include <StepDimTol_PerpendicularityTolerance.hxx>
138 #include <StepDimTol_SymmetryTolerance.hxx>
139 #include <StepDimTol_TotalRunoutTolerance.hxx>
140 #include <StepDimTol_CylindricityTolerance.hxx>
141 #include <StepDimTol_FlatnessTolerance.hxx>
142 #include <StepDimTol_LineProfileTolerance.hxx>
143 #include <StepDimTol_PositionTolerance.hxx>
144 #include <StepDimTol_RoundnessTolerance.hxx>
145 #include <StepDimTol_StraightnessTolerance.hxx>
146 #include <StepDimTol_SurfaceProfileTolerance.hxx>
147 #include <TColStd_HArray1OfReal.hxx>
148 #include <TColStd_HArray1OfTransient.hxx>
149
150 // added by skl 12.02.2004 for writing materials
151 #include <XCAFDoc_MaterialTool.hxx>
152 #include <XCAFDoc_Material.hxx>
153 #include <TDataStd_TreeNode.hxx>
154 #include <StepRepr_DescriptiveRepresentationItem.hxx>
155 #include <StepBasic_SiUnitAndMassUnit.hxx>
156 #include <StepBasic_DerivedUnitElement.hxx>
157 #include <StepBasic_HArray1OfDerivedUnitElement.hxx>
158 #include <StepBasic_DerivedUnit.hxx>
159 #include <StepRepr_MeasureRepresentationItem.hxx>
160 #include <StepBasic_ProductDefinition.hxx>
161
162 //=======================================================================
163 //function : GetLabelName
164 //purpose  : auxilary function: take name of label and append it to str
165 //=======================================================================
166 static Standard_Boolean GetLabelName (const TDF_Label &L, Handle(TCollection_HAsciiString) &str)
167 {
168   Handle(TDataStd_Name) N;
169   if ( ! L.FindAttribute ( TDataStd_Name::GetID(), N ) ) return Standard_False;
170   TCollection_ExtendedString name = N->Get();
171   if ( name.Length() <=0 ) return Standard_False;
172
173   // set name, converting it to Ascii and removing spaces
174   TCollection_AsciiString buf ( name, '?' );
175   buf.LeftAdjust();
176   buf.RightAdjust();
177   buf.ChangeAll(' ','_');
178   str->AssignCat ( buf.ToCString() );
179   return Standard_True;
180 }
181
182
183 //=======================================================================
184 //function : STEPCAFControl_Writer
185 //purpose  :
186 //=======================================================================
187
188 STEPCAFControl_Writer::STEPCAFControl_Writer () :
189        myColorMode( Standard_True ),
190        myNameMode ( Standard_True ),
191        myLayerMode( Standard_True ),
192        myPropsMode( Standard_True ),
193        mySHUOMode ( Standard_True ),
194        myDGTMode  ( Standard_True ),
195        myMatMode  ( Standard_True )
196 {
197   STEPCAFControl_Controller::Init();
198   Handle(XSControl_WorkSession) WS = new XSControl_WorkSession;
199   Init ( WS );
200 }
201
202
203 //=======================================================================
204 //function : STEPCAFControl_Writer
205 //purpose  :
206 //=======================================================================
207
208 STEPCAFControl_Writer::STEPCAFControl_Writer (const Handle(XSControl_WorkSession)& WS,
209                                               const Standard_Boolean scratch)
210 {
211   STEPCAFControl_Controller::Init();
212   Init ( WS, scratch );
213   myColorMode = Standard_True;
214   myNameMode = Standard_True;
215   myLayerMode = Standard_True;
216   myPropsMode = Standard_True;
217   mySHUOMode = Standard_True;
218 }
219
220
221 //=======================================================================
222 //function : Init
223 //purpose  :
224 //=======================================================================
225
226 void STEPCAFControl_Writer::Init (const Handle(XSControl_WorkSession)& WS,
227                                   const Standard_Boolean scratch)
228 {
229   WS->SelectNorm ( "STEP" );
230   myWriter.SetWS (WS,scratch);
231   myFiles = new STEPCAFControl_DictionaryOfExternFile;
232   myLabEF.Clear();
233   myLabels.Clear();
234 }
235
236
237 //=======================================================================
238 //function : Write
239 //purpose  :
240 //=======================================================================
241
242 IFSelect_ReturnStatus STEPCAFControl_Writer::Write (const Standard_CString filename)
243 {
244   IFSelect_ReturnStatus status = myWriter.Write ( filename );
245
246   // get directory name of the main file
247   OSD_Path mainfile ( filename );
248   mainfile.SetName ( "" );
249   mainfile.SetExtension ( "" );
250   TCollection_AsciiString dpath;
251   mainfile.SystemName ( dpath );
252
253   STEPCAFControl_IteratorOfDictionaryOfExternFile it ( myFiles );
254   for ( ; it.More(); it.Next() ) {
255     Handle(STEPCAFControl_ExternFile) EF = it.Value();
256     if ( EF->GetWriteStatus() != IFSelect_RetVoid ) continue;
257
258     // construct extern file name
259     TCollection_AsciiString fname = OSD_Path::AbsolutePath ( dpath, EF->GetName()->String() );
260     if ( fname.Length() <= 0 ) fname = EF->GetName()->String();
261 #ifdef DEB
262     cout << "Writing external file: " << fname.ToCString() << endl;
263 #endif
264     
265     EF->SetWriteStatus ( EF->GetWS()->SendAll ( fname.ToCString() ) );
266   }
267
268   return status;
269 }
270
271
272 //=======================================================================
273 //function : Transfer
274 //purpose  :
275 //=======================================================================
276
277 Standard_Boolean STEPCAFControl_Writer::Transfer (const Handle(TDocStd_Document) &doc,
278                                                   const STEPControl_StepModelType mode,
279                                                   const Standard_CString multi)
280 {
281   Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( doc->Main() );
282   if ( STool.IsNull() ) return Standard_False;
283
284   TDF_LabelSequence labels;
285   STool->GetFreeShapes ( labels );
286   return Transfer ( myWriter, labels, mode, multi );
287 }
288
289
290 //=======================================================================
291 //function : Transfer
292 //purpose  :
293 //=======================================================================
294
295 Standard_Boolean STEPCAFControl_Writer::Transfer (const TDF_Label &L,
296                                                   const STEPControl_StepModelType mode,
297                                                   const Standard_CString multi)
298 {
299   TDF_LabelSequence labels;
300   labels.Append ( L );
301   return Transfer ( myWriter, labels, mode, multi );
302 }
303
304
305 //=======================================================================
306 //function : Perform
307 //purpose  :
308 //=======================================================================
309
310 Standard_Boolean STEPCAFControl_Writer::Perform (const Handle(TDocStd_Document) &doc,
311                                                  const Standard_CString filename)
312 {
313   if ( ! Transfer ( doc ) ) return Standard_False;
314   return Write ( filename ) == IFSelect_RetDone;
315 }
316
317
318 //=======================================================================
319 //function : Perform
320 //purpose  :
321 //=======================================================================
322
323 Standard_Boolean STEPCAFControl_Writer::Perform (const Handle(TDocStd_Document) &doc,
324                                                  const TCollection_AsciiString &filename)
325 {
326   if ( ! Transfer ( doc ) ) return Standard_False;
327   return Write ( filename.ToCString() ) == IFSelect_RetDone;
328 }
329
330
331 //=======================================================================
332 //function : ExternFiles
333 //purpose  :
334 //=======================================================================
335
336 const Handle(STEPCAFControl_DictionaryOfExternFile) &STEPCAFControl_Writer::ExternFiles () const
337 {
338   return myFiles;
339 }
340
341
342 //=======================================================================
343 //function : ExternFile
344 //purpose  :
345 //=======================================================================
346
347 Standard_Boolean STEPCAFControl_Writer::ExternFile (const TDF_Label &L,
348                                                     Handle(STEPCAFControl_ExternFile) &ef) const
349 {
350   ef.Nullify();
351   if ( ! myLabEF.IsBound ( L ) ) return Standard_False;
352   ef = myLabEF.Find ( L );
353   return Standard_True;
354 }
355
356
357 //=======================================================================
358 //function : ExternFile
359 //purpose  :
360 //=======================================================================
361
362 Standard_Boolean STEPCAFControl_Writer::ExternFile (const Standard_CString name,
363                                                     Handle(STEPCAFControl_ExternFile) &ef) const
364 {
365   ef.Nullify();
366   if ( ! myFiles.IsNull() || ! myFiles->HasItem ( name ) )
367     return Standard_False;
368   ef = myFiles->Item ( name );
369   return Standard_True;
370 }
371
372
373 //=======================================================================
374 //function : Writer
375 //purpose  :
376 //=======================================================================
377
378 STEPControl_Writer &STEPCAFControl_Writer::ChangeWriter ()
379 {
380   return myWriter;
381 }
382
383
384 //=======================================================================
385 //function : Writer
386 //purpose  :
387 //=======================================================================
388
389 const STEPControl_Writer &STEPCAFControl_Writer::Writer () const
390 {
391   return myWriter;
392 }
393
394
395 //=======================================================================
396 //function : Transfer
397 //purpose  :
398 //=======================================================================
399
400 Standard_Boolean STEPCAFControl_Writer::Transfer (STEPControl_Writer &writer,
401                                                   const TDF_LabelSequence &labels,
402                                                   const STEPControl_StepModelType mode,
403                                                   const Standard_CString multi,
404                                                   const Standard_Boolean isExternFile)
405 {
406   if ( labels.Length() <=0 ) return Standard_False;
407
408   Handle(STEPCAFControl_ActorWrite) Actor =
409     Handle(STEPCAFControl_ActorWrite)::DownCast ( writer.WS()->NormAdaptor()->ActorWrite() );
410
411   // translate free top-level shapes of the DECAF document
412 #ifdef DEB // includes Transfer_ActorOfFinderProcess
413 //  cout << "Actor is " << writer.WS()->NormAdaptor()->ActorWrite()->DynamicType()->Name() << endl;
414 #endif
415   Standard_Integer ap = Interface_Static::IVal ("write.step.schema");
416   TDF_LabelSequence sublabels;
417   for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
418     TDF_Label L = labels.Value(i);
419     TopoDS_Shape dummy;
420     if ( myLabels.IsBound ( L ) ) continue; // already processed
421
422     TopoDS_Shape shape = XCAFDoc_ShapeTool::GetShape ( L );
423     if ( shape.IsNull() ) continue;
424     
425     // write shape either as a whole, or as multifile (with extern refs)
426     if ( ! multi /* || ! XCAFDoc_ShapeTool::IsAssembly ( L ) */ ) {
427       Actor->SetStdMode ( Standard_False );
428
429       // fill sequence of (sub) shapes for which attributes should be written
430       // and set actor to handle assemblies in a proper way
431       TDF_LabelSequence comp;
432       XCAFDoc_ShapeTool::GetComponents ( L, comp, Standard_True );
433       for ( Standard_Integer k=1; k <= comp.Length(); k++ ) {
434         TDF_Label ref;
435         if ( ! XCAFDoc_ShapeTool::GetReferredShape ( comp(k), ref ) ) continue;
436         if ( ! myLabels.IsBound ( ref ) ) {
437           TopoDS_Shape refS = XCAFDoc_ShapeTool::GetShape ( ref );
438           myLabels.Bind ( ref, refS );
439           sublabels.Append ( ref );
440           if ( XCAFDoc_ShapeTool::IsAssembly ( ref ) )
441             Actor->RegisterAssembly ( refS );
442         }
443       }
444       myLabels.Bind ( L, shape );
445       sublabels.Append ( L );
446       if ( XCAFDoc_ShapeTool::IsAssembly ( L ) )
447         Actor->RegisterAssembly ( shape );
448
449       writer.Transfer(shape,mode,Standard_False);
450       Actor->SetStdMode ( Standard_True ); // restore default behaviour
451     }
452     else {
453       // translate final solids
454       TopoDS_Shape Sass = TransferExternFiles ( L, mode, sublabels, multi );
455
456       // translate main assembly structure
457 /*
458       if ( ap == 3 ) { // if AP203, switch to AP214
459         Interface_Static::SetCVal ("write.step.schema", "AP214DIS");
460         Handle(StepData_StepModel) model = 
461           Handle(StepData_StepModel)::DownCast ( writer.WS()->Model() );
462         if ( model->HasHeaderEntity(STANDARD_TYPE(HeaderSection_FileSchema)) ) {
463           Handle(HeaderSection_FileSchema) fs = 
464             Handle(HeaderSection_FileSchema)::DownCast ( model->HeaderEntity(STANDARD_TYPE(HeaderSection_FileSchema)) );
465           Handle(TCollection_HAsciiString) str = fs->SchemaIdentifiersValue ( 1 );
466           Handle(TCollection_HAsciiString) ap214 = new TCollection_HAsciiString ( "AUTOMOTIVE_DESIGN" );
467           if ( str->Search ( ap214 ) <0 ) {
468             str->Clear();
469             str->AssignCat ( ap214 );
470           }
471         }
472       }
473 */      
474       Standard_Integer assemblymode = Interface_Static::IVal ("write.step.assembly");
475       Interface_Static::SetCVal ("write.step.assembly", "On");
476       writer.Transfer ( Sass, STEPControl_AsIs );
477       Interface_Static::SetIVal ("write.step.assembly", assemblymode);
478       Interface_Static::SetIVal ("write.step.schema", ap);
479     }
480   }
481
482   writer.WS()->ComputeGraph(Standard_True );// added by skl 03.11.2003 since we use
483                                             // writer.Transfer() wihtout compute graph
484
485   // write names
486   if ( GetNameMode() )
487     WriteNames ( writer.WS(), sublabels );
488
489   if ( !multi ) {
490     // write colors
491     if ( GetColorMode() )
492       WriteColors ( writer.WS(), sublabels );
493     
494     // write layers
495     if ( GetLayerMode() )
496       WriteLayers ( writer.WS(), sublabels );
497
498     // write SHUO entities
499     if ( GetSHUOMode() && !isExternFile ) 
500       // do not store SHUO for extern reference for the moment
501       WriteSHUOs (  writer.WS(), sublabels );
502     
503     // write G&DTs
504     if(GetDimTolMode())
505       WriteDGTs(writer.WS(),sublabels);
506
507     // write Materials
508     if(GetMaterialMode())
509       WriteMaterials(writer.WS(),sublabels);
510
511     // register all MDGPRs in model
512     MoniTool_DataMapIteratorOfDataMapOfShapeTransient anItr(myMapCompMDGPR);
513     for (; anItr.More(); anItr.Next()) {
514       Handle(Interface_InterfaceModel) Model = writer.WS()->Model();
515       Model->AddWithRefs( anItr.Value() );
516     }
517   }
518   
519   if ( multi ) { // external refs
520     WriteExternRefs ( writer.WS(), sublabels );
521   }
522
523   // write validation props
524 //  if ( multi && ap ==3 ) {
525 //      Interface_Static::SetCVal ("write.step.schema", "AP214DIS");
526 //  }
527   if ( GetPropsMode() ) 
528     WriteValProps ( writer.WS(), sublabels, multi );
529
530   Interface_Static::SetIVal ("write.step.schema", ap);
531
532   // refresh graph
533   writer.WS()->ComputeGraph ( Standard_True );
534
535   return Standard_True;
536 }
537
538
539 //=======================================================================
540 //function : TransferExternFiles
541 //purpose  :
542 //=======================================================================
543
544 TopoDS_Shape STEPCAFControl_Writer::TransferExternFiles (const TDF_Label &L,
545                                                          const STEPControl_StepModelType mode,
546                                                          TDF_LabelSequence &labels,
547                                                          const Standard_CString prefix)
548 {
549   // if label already translated, just return the shape
550   if ( myLabels.IsBound ( L ) ) {
551     return myLabels.Find ( L );
552   }
553
554   TopoDS_Compound C;
555   BRep_Builder B;
556   B.MakeCompound ( C );
557   labels.Append ( L );
558
559   // if not assembly, write to separate file
560   if ( ! XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
561
562     // prepare for transfer
563     Handle(XSControl_WorkSession) newWS = new XSControl_WorkSession;
564     newWS->SelectNorm ( "STEP" );
565     STEPControl_Writer sw ( newWS, Standard_True );
566     TDF_LabelSequence Lseq;
567     Lseq.Append ( L );
568
569     // construct the name for extern file
570     Handle(TCollection_HAsciiString) basename = new TCollection_HAsciiString;
571     if ( prefix && prefix[0] ) basename->AssignCat ( prefix );
572     GetLabelName ( L, basename );
573     Handle(TCollection_HAsciiString) name = new TCollection_HAsciiString ( basename );
574     name->AssignCat ( ".stp" );
575     if ( myFiles->HasItem ( name->ToCString() ) ) { // avoid confusions
576       for ( Standard_Integer k=1; k < 32000; k++ ) {
577         name = new TCollection_HAsciiString ( basename );
578         name->AssignCat ( "_" );
579         name->AssignCat ( TCollection_AsciiString ( k ).ToCString() );
580         name->AssignCat ( ".stp" );
581         if ( ! myFiles->HasItem ( name->ToCString() ) ) break;
582       }
583     }
584
585     // translate and record extern file
586     Handle(STEPCAFControl_ExternFile) EF = new STEPCAFControl_ExternFile;
587     EF->SetWS ( newWS );
588     EF->SetName ( name );
589     EF->SetLabel ( L );
590     Standard_Integer assemblymode = Interface_Static::IVal ("write.step.assembly");
591     Interface_Static::SetCVal ("write.step.assembly", "Off");
592     const Standard_CString multi = 0;
593     EF->SetTransferStatus ( Transfer ( sw, Lseq, mode, multi, Standard_True ) );
594     Interface_Static::SetIVal ("write.step.assembly", assemblymode);
595     myLabEF.Bind ( L, EF );
596     myFiles->SetItem ( name->ToCString(), EF );
597
598     // return empty compound as replacement for the shape
599     myLabels.Bind ( L, C );
600     return C;
601   }
602
603   // else iterate on components add create structure of empty compounds
604   // representing the assembly
605   TDF_LabelSequence comp;
606   XCAFDoc_ShapeTool::GetComponents ( L, comp, Standard_False );
607   for ( Standard_Integer k=1; k <= comp.Length(); k++ ) {
608     TDF_Label lab = comp(k);
609     TDF_Label ref;
610     if ( ! XCAFDoc_ShapeTool::GetReferredShape ( lab, ref ) ) continue;
611     TopoDS_Shape Scomp = TransferExternFiles ( ref, mode, labels, prefix );
612     Scomp.Location ( XCAFDoc_ShapeTool::GetLocation ( lab ) );
613     B.Add ( C, Scomp );
614   }
615   myLabels.Bind ( L, C );
616   return C;
617 }
618
619
620 //=======================================================================
621 //function : WriteExternRefs
622 //purpose  :
623 //=======================================================================
624
625 Standard_Boolean STEPCAFControl_Writer::WriteExternRefs (const Handle(XSControl_WorkSession) &WS,
626                                                          const TDF_LabelSequence &labels) const
627 {
628   if ( labels.Length() <=0 ) return Standard_False;
629
630   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
631   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
632   STEPConstruct_ExternRefs EFTool ( WS );
633   Standard_Integer schema = Interface_Static::IVal("write.step.schema");
634   for ( Standard_Integer k=1; k <= labels.Length(); k++ ) {
635     TDF_Label lab = labels(k);
636     if ( XCAFDoc_ShapeTool::IsAssembly ( lab ) ) continue; // skip assemblies
637
638     // get extern file
639     Handle(STEPCAFControl_ExternFile) EF;
640     if ( ! ExternFile ( lab, EF ) ) continue; // should never be
641
642     // find SDR
643     if ( ! myLabels.IsBound ( lab ) ) continue; // not recorded as translated, skip
644     TopoDS_Shape S = myLabels.Find ( lab );
645
646     Handle(StepShape_ShapeDefinitionRepresentation) SDR;
647     Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, S );
648     if ( ! FP->FindTypedTransient ( mapper, STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation), SDR ) ) {
649 #ifdef DEB
650       cout << "Warning: Cannot find SDR for " << S.TShape()->DynamicType()->Name() << endl;
651 #endif
652       continue;
653     }
654
655     // add extern ref
656     const Standard_CString format = (const Standard_CString) ( schema == 3 ? "STEP AP203" : "STEP AP214" );
657     // try to get PD from SDR
658     StepRepr_RepresentedDefinition RD = SDR->Definition();
659     Handle(StepRepr_PropertyDefinition) aPropDef = RD.PropertyDefinition();
660     if (aPropDef.IsNull()) {
661 #ifdef DEB
662       cout << "Warning: STEPCAFControl_Writer::WriteExternRefs StepRepr_PropertyDefinition is null for " << S.TShape()->DynamicType()->Name() << endl;
663 #endif
664       continue;
665     }
666     StepRepr_CharacterizedDefinition CharDef = aPropDef->Definition();
667     Handle(StepBasic_ProductDefinition) PD = CharDef.ProductDefinition();
668     if (PD.IsNull()) {
669 #ifdef DEB
670       cout << "Warning: STEPCAFControl_Writer::WriteExternRefs StepBasic_ProductDefinition is null for " << S.TShape()->DynamicType()->Name() << endl;
671 #endif
672       continue;
673     }
674     EFTool.AddExternRef ( EF->GetName()->ToCString(), PD, format );
675   }
676   EFTool.WriteExternRefs(schema);
677   return Standard_True;
678 }
679
680
681 //=======================================================================
682 //function : FindEntities
683 //purpose  : auxilary
684 //=======================================================================
685 static Standard_Integer FindEntities (const Handle(Transfer_FinderProcess) &FP,
686                                       const TopoDS_Shape &S,
687                                       TopLoc_Location &L,
688                                       TColStd_SequenceOfTransient &seqRI)
689 {
690   Handle(StepRepr_RepresentationItem) item = STEPConstruct::FindEntity ( FP, S, L );
691
692   if ( ! item.IsNull() ) {
693     seqRI.Append ( item );
694     return 1;
695   }
696       
697   // may be S was splited during shape processing
698   Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, S );
699   Handle(Transfer_Binder) bnd = FP->Find ( mapper );
700   if ( bnd.IsNull() ) return 0;
701   
702   Handle(Transfer_TransientListBinder) TransientListBinder =
703     //Handle(Transfer_TransientListBinder)::DownCast( bnd->Next(Standard_True) );
704     Handle(Transfer_TransientListBinder)::DownCast( bnd );
705   Standard_Integer nres=0;
706   if ( TransientListBinder.IsNull() && S.ShapeType() == TopAbs_COMPOUND) 
707   {
708     for ( TopoDS_Iterator it(S); it.More(); it.Next() ) {
709       Handle(StepRepr_RepresentationItem) item = STEPConstruct::FindEntity ( FP, it.Value(), L );
710       if ( item.IsNull() ) continue;
711       nres++;
712       seqRI.Append ( item );
713     }
714   }
715   else
716   {
717     const Standard_Integer nb = TransientListBinder->NbTransients();
718     for (Standard_Integer i=1; i<=nb; i++) {
719       Handle(Standard_Transient) t = TransientListBinder->Transient(i);
720       item = Handle(StepRepr_RepresentationItem)::DownCast(t);
721       if ( item.IsNull() ) continue;
722       nres++;
723       seqRI.Append ( item );
724     }
725   }
726 /*  works but is obsolete: another approach
727   if (i<=nb) {
728     TopoDS_Shape comp = TransferBRep::ShapeResult(bnd);
729     if ( ! comp.IsNull() && comp.ShapeType() < S.ShapeType() ) {
730       for ( TopoDS_Iterator it(comp); it.More(); it.Next() ) {
731         MakeSTEPStyles(Styles, it.Value(), settings, STEPstyle, 
732                        Map, ( hasOwn ? &style : 0 ) );
733       }
734     }
735   }
736 */
737   return nres;
738 }
739
740
741 //=======================================================================
742 //function : getStyledItem
743 //purpose  : auxilary
744 //=======================================================================
745 static Standard_Boolean getStyledItem(const TopoDS_Shape& S,
746                                       const Handle(XCAFDoc_ShapeTool)& STool,
747                                       const STEPConstruct_Styles &Styles, 
748                                       Handle(StepVisual_StyledItem) &resSelItem,
749                                       const MoniTool_DataMapOfShapeTransient& myMapCompMDGPR)
750 {
751   TDF_Label aTopShL = STool->FindShape(S, Standard_False);
752   TopoDS_Shape aTopLevSh = STool->GetShape( aTopShL );
753   Standard_Boolean found = Standard_False;
754   if ( !aTopLevSh.IsNull() &&  myMapCompMDGPR.IsBound( aTopLevSh ) ) {
755     Handle(StepVisual_PresentationRepresentation) aMDGPR = 
756       Handle(StepVisual_PresentationRepresentation)::DownCast( myMapCompMDGPR.Find( aTopLevSh ) );
757     Handle(StepRepr_HArray1OfRepresentationItem) anSelItmHArr = aMDGPR->Items();
758     // search for PSA of Monifold solid
759     if ( !anSelItmHArr.IsNull() )
760     {
761       for (Standard_Integer si = 1; si <= anSelItmHArr->Length(); si++) {
762         Handle(StepVisual_StyledItem) aSelItm =
763           Handle(StepVisual_StyledItem)::DownCast(anSelItmHArr->Value(si));
764
765         if ( aSelItm.IsNull() ) 
766           continue;
767
768         // check that it is a stiled item for monifold solid brep
769         TopLoc_Location Loc;
770         TColStd_SequenceOfTransient aNewseqRI;
771         FindEntities ( Styles.FinderProcess(), aTopLevSh, Loc, aNewseqRI );
772         if ( aNewseqRI.Length() > 0 )
773         {
774           
775           Handle(StepRepr_RepresentationItem) anItem = aSelItm->Item();
776           Standard_Boolean isSameMonSolBR = Standard_False;
777           for (Standard_Integer mi = 1; mi <= aNewseqRI.Length(); mi++) {
778             if ( !anItem.IsNull() && anItem == aNewseqRI.Value( mi ) ) {
779               isSameMonSolBR = Standard_True;
780               break;
781             }
782           }
783           if (!isSameMonSolBR)
784             continue;
785         }
786         
787         
788         for (Standard_Integer jsi = 1; jsi <= aSelItm->NbStyles() && !found; jsi++) {
789           Handle(StepVisual_PresentationStyleAssignment) aFatherPSA =
790             Handle(StepVisual_PresentationStyleAssignment)::DownCast(aSelItm->StylesValue(jsi));
791           // check for PSA for top-level (not Presentation style by contex for NAUO)
792           if (aFatherPSA.IsNull() || aFatherPSA->IsKind(STANDARD_TYPE(StepVisual_PresentationStyleByContext)))
793             continue;
794           resSelItem = aSelItm;
795           found = Standard_True;
796         }
797       }
798     }
799   }
800   return found;
801 }
802
803
804 //=======================================================================
805 //function : setDefaultInstanceColor
806 //purpose  : auxilary
807 //=======================================================================
808 static Standard_Boolean setDefaultInstanceColor (const Handle(StepVisual_StyledItem) &aSelItm,
809                                                  Handle(StepVisual_PresentationStyleAssignment)& PSA)
810 {
811    Standard_Boolean found = Standard_False;
812   for (Standard_Integer jsi = 1; jsi <= aSelItm->NbStyles() && !found; jsi++) {
813     Handle(StepVisual_PresentationStyleAssignment) aFatherPSA =
814     Handle(StepVisual_PresentationStyleAssignment)::DownCast(aSelItm->StylesValue(jsi));
815   // check for PSA for top-level (not Presentation style by contex for NAUO)
816   if (aFatherPSA.IsNull() || aFatherPSA->IsKind(STANDARD_TYPE(StepVisual_PresentationStyleByContext))) 
817     return Standard_False;
818           
819   // get style select from father PSA
820   if (aFatherPSA->NbStyles() > 0) {
821     Handle(StepVisual_HArray1OfPresentationStyleSelect) aFatherStyles =
822       new StepVisual_HArray1OfPresentationStyleSelect(1, aFatherPSA->NbStyles());
823     for (Standard_Integer k = 1; k <= aFatherPSA->NbStyles(); k++) {
824       StepVisual_PresentationStyleSelect PSS;
825       StepVisual_PresentationStyleSelect olDPSS = aFatherPSA->StylesValue(k);
826       if (!olDPSS.PointStyle().IsNull())
827         PSS.SetValue (olDPSS.PointStyle());
828       else if (!olDPSS.CurveStyle().IsNull())
829         PSS.SetValue (olDPSS.CurveStyle());
830       else if (!olDPSS.SurfaceStyleUsage().IsNull())
831         PSS.SetValue (olDPSS.SurfaceStyleUsage());
832       else {
833         found = Standard_False;
834         break;
835       }
836       //aFatherStyles->SetValue( k, PSS );
837       aFatherStyles->SetValue( k, olDPSS );
838       found = Standard_True;
839     }
840             // init PSA of NAUO
841     if (found) {
842       PSA->Init( aFatherStyles );
843     }
844   }
845     
846   }
847   return found;
848 }
849
850
851 //=======================================================================
852 //function : MakeSTEPStyles
853 //purpose  : auxilary
854 //=======================================================================
855 static void MakeSTEPStyles (STEPConstruct_Styles &Styles,
856                             const TopoDS_Shape &S,
857                             const XCAFPrs_DataMapOfShapeStyle &settings,
858                             Handle(StepVisual_StyledItem) &override,
859                             TopTools_MapOfShape &Map,
860                             const MoniTool_DataMapOfShapeTransient& myMapCompMDGPR,
861                             STEPConstruct_DataMapOfAsciiStringTransient &DPDCs,
862                             STEPConstruct_DataMapOfPointTransient &ColRGBs,
863                             const Handle(XCAFDoc_ColorTool)& CTool,
864                             const XCAFPrs_Style *inherit = 0,
865                             const Standard_Boolean isComponent = Standard_False)
866 {
867   // skip already processed shapes
868   if ( ! Map.Add ( S ) ) return;
869
870   // check if shape has its own style (r inherits from ancestor)
871   XCAFPrs_Style style;
872   if ( inherit ) style = *inherit;
873   if ( settings.IsBound(S) ) {
874     XCAFPrs_Style own = settings.Find(S);
875     if ( !own.IsVisible() ) style.SetVisibility ( Standard_False );
876     if ( own.IsSetColorCurv() ) style.SetColorCurv ( own.GetColorCurv() );
877     if ( own.IsSetColorSurf() ) style.SetColorSurf ( own.GetColorSurf() );
878   }
879
880   // translate colors to STEP
881   Handle(StepVisual_Colour) surfColor, curvColor;
882   if ( style.IsSetColorSurf() )
883     surfColor = Styles.EncodeColor(style.GetColorSurf(),DPDCs,ColRGBs);
884   if ( style.IsSetColorCurv() )
885     curvColor = Styles.EncodeColor(style.GetColorCurv(),DPDCs,ColRGBs);
886   
887   Standard_Boolean hasOwn = ( ! surfColor.IsNull() || 
888                               ! curvColor.IsNull() ||
889                               ! style.IsVisible() );
890
891   // find target item and assign style to it
892   Handle(StepVisual_StyledItem) STEPstyle = override;
893   if ( hasOwn ) {
894     if ( S.ShapeType() != TopAbs_COMPOUND || isComponent ) { // skip compounds, let subshapes inherit its colors
895       TopLoc_Location L;
896       TColStd_SequenceOfTransient seqRI;
897       Standard_Integer nb = FindEntities ( Styles.FinderProcess(), S, L, seqRI );
898 #ifdef DEB
899       if ( nb <=0 ) cout << "Warning: Cannot find RI for " << S.TShape()->DynamicType()->Name() << endl;
900 #endif
901       //Get overridden style gka 10.06.03
902       if ( isComponent && nb) 
903         getStyledItem(S, CTool->ShapeTool(), Styles, override,myMapCompMDGPR);
904        
905            
906       for ( Standard_Integer i=1; i <= nb; i++ ) {
907         Handle(StepRepr_RepresentationItem) item = 
908           Handle(StepRepr_RepresentationItem)::DownCast(seqRI(i));
909         Handle(StepVisual_PresentationStyleAssignment) PSA;
910         if ( style.IsVisible() || !surfColor.IsNull() || !curvColor.IsNull() ) {
911           PSA = Styles.MakeColorPSA ( item, surfColor, curvColor, isComponent );
912         }
913         else {
914           // default white color
915           surfColor = Styles.EncodeColor(Quantity_Color(1,1,1,Quantity_TOC_RGB),DPDCs,ColRGBs);
916           PSA = Styles.MakeColorPSA ( item, surfColor, curvColor, isComponent );
917           if ( isComponent ) 
918             setDefaultInstanceColor( override, PSA);
919           
920         } // end of component case
921         
922         STEPstyle = Styles.AddStyle ( item, PSA, override );
923         hasOwn = Standard_False;
924       }
925     }
926   }
927
928   // iterate on subshapes (except vertices :)
929   if ( S.ShapeType() == TopAbs_EDGE ) return;
930   if ( !isComponent ) // PTV 10.02.2003
931     for ( TopoDS_Iterator it(S); it.More(); it.Next() ) {
932       MakeSTEPStyles ( Styles, it.Value(), settings, STEPstyle,
933                       Map, myMapCompMDGPR, DPDCs, ColRGBs, CTool,
934                       ( hasOwn ? &style : 0 ) );
935     }
936 }
937
938 /*
939 static Standard_Boolean getFatherColor (const TDF_Label& L,
940                                         const Handle(XCAFDoc_ColorTool)& CTool,
941                                         XCAFPrs_Style& style)
942 {
943   Standard_Boolean done = Standard_False;
944   TopoDS_Shape aSh = CTool->ShapeTool()->GetShape( L );
945   TDF_Label aFL = CTool->ShapeTool()->FindShape( aSh );
946   if (aFL.IsNull() || aFL == L)
947     return done;
948   Quantity_Color C;
949   if ( CTool->GetColor ( aFL, XCAFDoc_ColorGen, C ) ) {
950     style.SetColorCurv ( C );
951     style.SetColorSurf ( C );
952     done = Standard_True;
953   }
954   if ( CTool->GetColor ( aFL, XCAFDoc_ColorSurf, C ) ) {
955     style.SetColorSurf ( C );
956     done = Standard_True;
957   }
958   if ( CTool->GetColor ( aFL, XCAFDoc_ColorCurv, C ) ) {
959     style.SetColorCurv ( C );
960     done = Standard_True;
961   }
962   
963   return done;
964 }
965 */
966
967
968 //=======================================================================
969 //function : WriteColors
970 //purpose  : 
971 //=======================================================================
972
973 Standard_Boolean STEPCAFControl_Writer::WriteColors (const Handle(XSControl_WorkSession) &WS,
974                                                      const TDF_LabelSequence &labels)
975 {
976   if ( labels.Length() <=0 ) return Standard_False;
977
978   // Iterate on shapes in the document
979   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( labels(1) );
980   if ( CTool.IsNull() ) return Standard_False;
981
982   STEPConstruct_Styles Styles ( WS );
983   STEPConstruct_DataMapOfAsciiStringTransient DPDCs;
984   STEPConstruct_DataMapOfPointTransient ColRGBs;
985   for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
986     TDF_Label L = labels.Value(i);
987
988     Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( labels(1) );
989     // Skip assemblies: colors assigned to assemblies and their instances
990     // are not supported (it is not clear how to encode that in STEP)
991     if ( XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
992 #ifdef DEB
993       cout << "Warning: Cannot write color  for Assembly" << endl;
994       cout << "Info: Check for colors assigned to components in assembly" << endl;
995 #endif
996       // PTV 22.01.2003 Write color for instances.
997       TDF_LabelSequence compLabels;
998       if ( aSTool.IsNull() )
999         continue;
1000       if (!aSTool->GetComponents(L, compLabels))
1001         continue;
1002       WriteColors(WS, compLabels);
1003       continue;
1004     }
1005     Styles.ClearStyles();
1006
1007     // get a target shape and try to find corresponding context
1008     // (all the colors set under that label will be put into that context)
1009     TopoDS_Shape S;
1010     if ( ! XCAFDoc_ShapeTool::GetShape ( L, S ) ) continue;
1011     Standard_Boolean isComponent = aSTool->IsComponent( L );
1012     TopoDS_Shape aTopSh = S;
1013     Handle(StepRepr_RepresentationContext) Context = Styles.FindContext ( S );
1014     if ( isComponent ) {
1015       TDF_Label aTopShL = aSTool->FindShape(S, Standard_False);
1016       if (aTopShL.IsNull())
1017         continue;
1018       aTopSh = aSTool->GetShape( aTopShL );
1019       Context = Styles.FindContext ( aTopSh );
1020     }
1021     if ( Context.IsNull() )
1022         continue;
1023     
1024     // collect settings set on that label
1025     XCAFPrs_DataMapOfShapeStyle settings;
1026     TDF_LabelSequence seq;
1027     seq.Append ( L );
1028     XCAFDoc_ShapeTool::GetSubShapes ( L, seq );
1029     Standard_Boolean isVisible = Standard_True;
1030     for ( Standard_Integer j = 1; j <= seq.Length(); j++ ) {
1031       TDF_Label lab = seq.Value(j);
1032       XCAFPrs_Style style;
1033       Quantity_Color C;
1034       if ( isComponent && lab == L ) {
1035         // check for invisible status of object on label
1036         if ( !CTool->IsVisible( lab ) ) {
1037           isVisible = Standard_False;
1038           style.SetVisibility( Standard_False );
1039         }
1040       }
1041       if ( CTool->GetColor ( lab, XCAFDoc_ColorGen, C ) ) {
1042         style.SetColorCurv ( C );
1043         style.SetColorSurf ( C );
1044       }
1045       if ( CTool->GetColor ( lab, XCAFDoc_ColorSurf, C ) )
1046         style.SetColorSurf ( C );
1047       if ( CTool->GetColor ( lab, XCAFDoc_ColorCurv, C ) )
1048         style.SetColorCurv ( C );
1049       
1050       // commented, cause we are need to take reference from 
1051 //       if ( isComponent && lab == L && !isVisible)
1052 //         if ( !style.IsSetColorSurf() && !style.IsSetColorCurv() ) {
1053 //           getFatherColor ( L, CTool, style);
1054 //         }
1055       if ( ! style.IsSetColorCurv() && ! style.IsSetColorSurf() && isVisible ) continue;
1056
1057       TopoDS_Shape sub = XCAFDoc_ShapeTool::GetShape ( lab );
1058       settings.Bind ( sub, style );
1059     }
1060     
1061     if ( settings.Extent() <=0 ) continue;
1062
1063     // iterate on subshapes and create STEP styles
1064     Handle(StepVisual_StyledItem) override;
1065     TopTools_MapOfShape Map;
1066     
1067     MakeSTEPStyles(Styles,S,settings,override,Map,myMapCompMDGPR,DPDCs,ColRGBs,CTool,0,isComponent);
1068     
1069     // create MDGPR and record it in model
1070     Handle(StepVisual_MechanicalDesignGeometricPresentationRepresentation) aMDGPR;
1071
1072     if (!isComponent) {
1073       if ( myMapCompMDGPR.IsBound( aTopSh )) {
1074 #ifdef DEB
1075         cerr << "Error: Current Top-Level shape have MDGPR already " << endl;
1076 #endif
1077       }
1078       Styles.CreateMDGPR ( Context, aMDGPR );
1079       if (!aMDGPR.IsNull())
1080         myMapCompMDGPR.Bind( aTopSh, aMDGPR );
1081     }
1082     else {
1083       // create SDR and add to model.
1084       Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1085       Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
1086       Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, S );
1087       Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1088       if ( FP->FindTypedTransient(mapper, 
1089                                   STANDARD_TYPE(StepShape_ContextDependentShapeRepresentation),
1090                                   CDSR) ) {
1091         // create SDR for NAUO
1092         Handle(StepRepr_ProductDefinitionShape) nullPDS; // important to be NULL
1093         Styles.CreateNAUOSRD( Context, CDSR, nullPDS );
1094         
1095         // search for MDGPR of the component top-level shape
1096         if ( myMapCompMDGPR.IsBound( aTopSh )) {
1097           aMDGPR = Handle(StepVisual_MechanicalDesignGeometricPresentationRepresentation)::DownCast( myMapCompMDGPR.Find( aTopSh ) );
1098         } else {
1099           aMDGPR = new StepVisual_MechanicalDesignGeometricPresentationRepresentation;
1100           Handle(TCollection_HAsciiString) ReprName = new TCollection_HAsciiString ( "" );
1101           aMDGPR->SetName( ReprName );
1102           aMDGPR->SetContextOfItems( Context );
1103           myMapCompMDGPR.Bind ( aTopSh, aMDGPR );
1104         }
1105         Handle(StepRepr_HArray1OfRepresentationItem) oldItems = aMDGPR->Items();
1106         Standard_Integer oldLengthlen = 0;
1107         if (!oldItems.IsNull())
1108           oldLengthlen = oldItems->Length();
1109         const Standard_Integer nbIt = oldLengthlen + Styles.NbStyles();
1110         if(!nbIt)
1111           continue;
1112         Handle(StepRepr_HArray1OfRepresentationItem) newItems =
1113           new StepRepr_HArray1OfRepresentationItem(1, nbIt);
1114         Standard_Integer si;
1115         Standard_Integer el = 1;
1116         for ( si=1; si <= oldLengthlen; si++ )
1117           newItems->SetValue( el++, oldItems->Value( si ) );
1118         for ( si=1; si <= Styles.NbStyles(); si++ ) {
1119           newItems->SetValue( el++, Handle(StepRepr_RepresentationItem)::DownCast(Styles.Style(si)));
1120 //           WP->Model()->AddWithRefs ( Handle(StepRepr_RepresentationItem)::DownCast (Styles.Style(si)));
1121         }
1122         if ( !isVisible ) {
1123           // create invisibility item and refer for stiledItem
1124           Handle(StepVisual_Invisibility) Invsblt = new StepVisual_Invisibility();
1125           Handle(StepVisual_HArray1OfInvisibleItem) HInvsblItm = 
1126             new StepVisual_HArray1OfInvisibleItem (1,Styles.NbStyles());
1127           // put all style item into the harray
1128           for ( si=1; si <= Styles.NbStyles(); si++ ) {
1129             Handle(StepRepr_RepresentationItem) styledItm =
1130               Handle(StepRepr_RepresentationItem)::DownCast(Styles.Style(si));
1131             StepVisual_InvisibleItem anInvItem;
1132             anInvItem.SetValue( styledItm );
1133             HInvsblItm->SetValue( si, anInvItem );
1134           }
1135           // set the invisibility of items
1136           Invsblt->Init( HInvsblItm );
1137           WS->Model()->AddWithRefs( Invsblt );
1138         }
1139         
1140         if (newItems->Length() > 0)
1141           aMDGPR->SetItems( newItems );
1142       } //end of work with CDSR
1143     }
1144   }
1145
1146   return Standard_True;
1147 }
1148
1149
1150 //=======================================================================
1151 //function : WriteNames
1152 //purpose  :
1153 //=======================================================================
1154
1155 Standard_Boolean STEPCAFControl_Writer::WriteNames (const Handle(XSControl_WorkSession) &WS,
1156                                                     const TDF_LabelSequence &labels) const
1157 {
1158   if ( labels.Length() <=0 ) return Standard_False;
1159
1160   // get working data
1161   Handle(Interface_InterfaceModel) Model = WS->Model();
1162   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1163   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
1164 //  Handle(XCAFDoc_ShapeTool) STool = XCAFDoc_DocumentTool::ShapeTool( labels(1) );
1165 //  if ( STool.IsNull() ) return Standard_False;
1166
1167   // Iterate on requested shapes
1168   for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
1169     TDF_Label L = labels.Value(i);
1170
1171     // get name
1172     Handle(TCollection_HAsciiString) hName = new TCollection_HAsciiString;
1173     if ( ! GetLabelName (L, hName) ) continue;
1174 //    Handle(TDataStd_Name) N;
1175 //    if ( ! L.FindAttribute ( TDataStd_Name::GetID(), N ) ) continue;
1176 //    TCollection_ExtendedString name = N->Get();
1177 //    if ( name.Length() <=0 ) continue;
1178
1179     // find target STEP entity for the current shape
1180 //    TopoDS_Shape S;
1181 //    if ( ! XCAFDoc_ShapeTool::GetShape ( L, S ) ) continue;
1182     if ( ! myLabels.IsBound ( L ) ) continue; // not recorded as translated, skip
1183     TopoDS_Shape S = myLabels.Find ( L );
1184
1185     Handle(StepShape_ShapeDefinitionRepresentation) SDR;
1186     Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, S );
1187     if ( ! FP->FindTypedTransient ( mapper, STANDARD_TYPE(StepShape_ShapeDefinitionRepresentation), SDR ) ) {
1188 #ifdef DEB
1189       cout << "Warning: Cannot find SDR for " << S.TShape()->DynamicType()->Name() << endl;
1190 #endif
1191       continue;
1192     }
1193
1194     // set the name to the PRODUCT
1195     Handle(StepRepr_PropertyDefinition) PropD = SDR->Definition().PropertyDefinition();
1196     if ( PropD.IsNull() ) continue;
1197     Handle(StepBasic_ProductDefinition) PD = PropD->Definition().ProductDefinition();
1198     if ( PD.IsNull() ) continue;
1199     Handle(StepBasic_Product) Prod = PD->Formation()->OfProduct();
1200
1201     Prod->SetId ( hName );
1202     Prod->SetName ( hName );
1203
1204     // write names for components of assemblies
1205     if ( XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1206       TDF_LabelSequence seq;
1207       XCAFDoc_ShapeTool::GetComponents ( L, seq );
1208       for (Standard_Integer k=1; k <= seq.Length(); k++) {
1209         TDF_Label lab = seq(k);
1210
1211         // get shape with correct location
1212         TDF_Label Lref;
1213         if ( ! XCAFDoc_ShapeTool::GetReferredShape ( lab, Lref ) || 
1214              ! myLabels.IsBound ( Lref ) ) continue;
1215         S = myLabels.Find ( Lref );
1216         S.Move ( XCAFDoc_ShapeTool::GetLocation ( lab ) );
1217         
1218         hName = new TCollection_HAsciiString;
1219         if ( ! GetLabelName (lab, hName) ) continue;
1220         
1221         // find the target CDSR corresponding to a shape
1222         mapper = TransferBRep::ShapeMapper ( FP, S );
1223         Handle(Transfer_Binder) binder = FP->Find ( mapper );
1224         Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1225         if ( ! FP->FindTypedTransient (mapper,STANDARD_TYPE(StepShape_ContextDependentShapeRepresentation), CDSR) ) 
1226           continue;
1227         Handle(StepRepr_ProductDefinitionShape) PDS = CDSR->RepresentedProductRelation();
1228         Handle(StepBasic_ProductDefinitionRelationship) NAUO = PDS->Definition().ProductDefinitionRelationship();
1229         if ( ! NAUO.IsNull() ) NAUO->SetName ( hName );
1230       }
1231     }
1232   }
1233
1234   return Standard_True;
1235 }
1236
1237
1238 //=======================================================================
1239 //function : WritePropsForLabel
1240 //purpose  :
1241 //=======================================================================
1242 static Standard_Boolean WritePropsForLabel(const Handle(XSControl_WorkSession) &WS,
1243                                            const Handle(XCAFDoc_ShapeTool) &aSTool,
1244                                            const STEPCAFControl_DataMapOfLabelShape &myLabels,
1245                                            const TDF_Label &L,
1246                                            const Standard_CString multi)
1247 {
1248   if(L.IsNull()) return Standard_False;
1249
1250   STEPConstruct_ValidationProps Props ( WS );
1251
1252   TopoDS_Shape S = aSTool->GetShape(L);
1253   if(S.IsNull()) return Standard_False;
1254
1255   if ( ! multi || XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1256     // write area
1257     Handle(XCAFDoc_Area) A;
1258     L.FindAttribute ( XCAFDoc_Area::GetID(), A );
1259     if ( ! A.IsNull() ) {
1260       Props.AddArea ( S, A->Get() );
1261     }
1262     // write volume
1263     Handle(XCAFDoc_Volume) V;
1264     L.FindAttribute ( XCAFDoc_Volume::GetID(), V );
1265     if ( ! V.IsNull() ) {
1266       Props.AddVolume ( S, V->Get() );
1267     }
1268   }
1269   // write centroid
1270   Handle(XCAFDoc_Centroid) C;
1271   L.FindAttribute ( XCAFDoc_Centroid::GetID(), C );
1272   if ( ! C.IsNull() ) {
1273     Props.AddCentroid ( S, C->Get() );
1274   }
1275
1276   if( XCAFDoc_ShapeTool::IsCompound(L) || XCAFDoc_ShapeTool::IsAssembly(L) ) {
1277     if(L.HasChild()) {
1278       for(Standard_Integer ich=1; ich<=L.NbChildren(); ich++) {
1279         WritePropsForLabel(WS,aSTool,myLabels,L.FindChild(ich),multi);
1280       }
1281     }
1282   }
1283
1284   return Standard_True;
1285 }
1286
1287
1288 //=======================================================================
1289 //function : WriteValProps
1290 //purpose  :
1291 //=======================================================================
1292
1293 Standard_Boolean STEPCAFControl_Writer::WriteValProps (const Handle(XSControl_WorkSession) &WS,
1294                                                        const TDF_LabelSequence &labels,
1295                                                        const Standard_CString multi) const
1296 {
1297   if ( labels.Length() <=0 ) return Standard_False;
1298
1299   // get working data
1300 //  STEPConstruct_ValidationProps Props ( WS );
1301   Handle(XCAFDoc_ShapeTool) aSTool = XCAFDoc_DocumentTool::ShapeTool( labels(1) );
1302
1303   // Iterate on requested shapes
1304   for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
1305     TDF_Label L = labels.Value(i);
1306
1307     WritePropsForLabel(WS,aSTool,myLabels,L,multi);
1308 /*    
1309     // find target STEP entity for the current shape
1310     if ( ! myLabels.IsBound ( L ) ) continue; // not recorded as translated, skip
1311     TopoDS_Shape S = myLabels.Find ( L );
1312
1313     // write area and volume (except for components in multifile mode)
1314     if ( ! multi || XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1315       Handle(XCAFDoc_Area) A;
1316       L.FindAttribute ( XCAFDoc_Area::GetID(), A );
1317       if ( ! A.IsNull() ) Props.AddArea ( S, A->Get() );
1318
1319       Handle(XCAFDoc_Volume) V;
1320       L.FindAttribute ( XCAFDoc_Volume::GetID(), V );
1321       if ( ! V.IsNull() ) Props.AddVolume ( S, V->Get() );
1322     }
1323
1324     // write centroid
1325     Handle(XCAFDoc_Centroid) C;
1326     L.FindAttribute ( XCAFDoc_Centroid::GetID(), C );
1327     if ( ! C.IsNull() ) Props.AddCentroid ( S, C->Get() );
1328
1329     // write centroid for components of assemblies
1330     if ( XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1331       TDF_LabelSequence seq;
1332       XCAFDoc_ShapeTool::GetComponents ( L, seq );
1333       for (Standard_Integer k=1; k <= seq.Length(); k++) {
1334         TDF_Label lab = seq(k);
1335
1336         // get shape with correct location
1337         TDF_Label Lref;
1338         if ( ! XCAFDoc_ShapeTool::GetReferredShape ( lab, Lref ) || 
1339              ! myLabels.IsBound ( Lref ) ) continue;
1340         TopLoc_Location Loc = XCAFDoc_ShapeTool::GetLocation ( lab );
1341         S = myLabels.Find ( Lref );
1342         S.Move ( Loc );
1343                 
1344         C.Nullify();
1345         lab.FindAttribute ( XCAFDoc_Centroid::GetID(), C );
1346         // if centroid is not assigned to an instance, 
1347         // use (shifted) centroid of original shape
1348         gp_Pnt center;
1349         if ( C.IsNull() ) {
1350           Lref.FindAttribute ( XCAFDoc_Centroid::GetID(), C );
1351           if ( C.IsNull() ) continue;
1352           center = C->Get().Transformed ( Loc.Transformation() );
1353         }
1354         else center = C->Get();
1355
1356         Props.AddCentroid ( S, center, Standard_True );
1357       }
1358     }
1359 */
1360   }
1361
1362   return Standard_True;
1363 }
1364
1365
1366 //=======================================================================
1367 //function : WriteLayers
1368 //purpose  : 
1369 //=======================================================================
1370
1371 Standard_Boolean STEPCAFControl_Writer::WriteLayers (const Handle(XSControl_WorkSession) &WS,
1372                                                      const TDF_LabelSequence  &labels ) const
1373 {
1374   
1375   if ( labels.Length() <=0 ) return Standard_False;
1376
1377   // get working data
1378   Handle(Interface_InterfaceModel) Model = WS->Model();
1379   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1380   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
1381   Handle(XCAFDoc_LayerTool) LTool = XCAFDoc_DocumentTool::LayerTool( labels(1) );
1382   if (LTool.IsNull() ) return Standard_False;
1383
1384   TDF_LabelSequence LayerLS;
1385   LTool->GetLayerLabels(LayerLS);
1386   if ( LayerLS.Length() <=0 ) return Standard_False;
1387
1388   // Iterate on requested layers and for each layer take set of shapes.
1389   for ( Standard_Integer i=1; i <= LayerLS.Length(); i++ ) {
1390     TDF_Label L = LayerLS.Value(i);
1391     
1392     // get labels of shapes in that layer
1393     TDF_LabelSequence ShapeLs;
1394     LTool->GetShapesOfLayer(L, ShapeLs);
1395     if ( ShapeLs.Length() <=0 ) continue;
1396     
1397     // name of layer: if not set, is considered as being empty
1398     Handle(TCollection_HAsciiString) hName = new TCollection_HAsciiString;
1399     GetLabelName ( L, hName );
1400
1401     // Find target STEP entity for each shape and add to StepVisual_PresentationLayerAssignment items.
1402     TColStd_SequenceOfTransient seqRI;
1403     for ( Standard_Integer j=1; j <= ShapeLs.Length(); j++) {
1404       TDF_Label shLabel = ShapeLs.Value(j);
1405       if ( shLabel.IsNull() ) continue;
1406       
1407       // there is no way to assign layer to instance in STEP
1408       if ( XCAFDoc_ShapeTool::IsAssembly ( shLabel ) ||
1409            XCAFDoc_ShapeTool::IsReference ( shLabel ) )
1410         continue;
1411       
1412       // check that the shape is one of (uub)labels written during current transfer
1413       Standard_Integer k = 1;
1414       for ( ; k <= labels.Length(); k++ )
1415         if ( shLabel.IsDescendant ( labels(k) ) ) break;
1416       if ( k > labels.Length() ) continue;
1417
1418       // get target STEP entity
1419       TopoDS_Shape oneShape = XCAFDoc_ShapeTool::GetShape(shLabel);
1420       
1421       TopLoc_Location Loc;
1422       Standard_Integer nb = 
1423         FindEntities ( FP, oneShape, Loc, seqRI );
1424       if ( nb <=0 ) 
1425         FP->Messenger() << "Warning: Cannot find RI for " << oneShape.TShape()->DynamicType()->Name() << endl;
1426     }
1427     if ( seqRI.Length() <= 0 ) continue;
1428
1429     // analyze visibility
1430     Handle(StepVisual_PresentationLayerAssignment) StepLayerAs = new StepVisual_PresentationLayerAssignment;
1431     Handle(TCollection_HAsciiString) descr;
1432     Handle(TDataStd_UAttribute) aUAttr;
1433     Standard_Boolean isLinv = Standard_False;
1434     if (L.FindAttribute(XCAFDoc::InvisibleGUID(), aUAttr)) {
1435       descr = new TCollection_HAsciiString ("invisible");
1436 #ifdef DEB
1437       FP->Messenger() << "\tLayer \"" << hName->String().ToCString() << "\" is invisible"<<endl;
1438 #endif
1439       isLinv = Standard_True;
1440     }
1441     else descr = new TCollection_HAsciiString ("visible");
1442     
1443     // create layer entity
1444     Handle(StepVisual_HArray1OfLayeredItem) HArrayOfLItem = 
1445       new StepVisual_HArray1OfLayeredItem ( 1, seqRI.Length() );
1446     for (Standard_Integer i1 = 1; i1<=seqRI.Length(); i1++) {
1447       StepVisual_LayeredItem LI;
1448       LI.SetValue ( seqRI.Value(i1) );
1449       HArrayOfLItem->SetValue( i1, LI );
1450     }
1451     StepLayerAs->Init(hName, descr, HArrayOfLItem);
1452     Model->AddWithRefs( StepLayerAs );
1453     // PTV 23.01.2003 add the invisibility AFTER adding layer into the model.
1454     // add the invisibility for the layer
1455     if (isLinv) {
1456       // Invisibility Item for containig invisible layers.
1457       Handle(StepVisual_HArray1OfInvisibleItem) HInvsblItm = new StepVisual_HArray1OfInvisibleItem (1,1);
1458       StepVisual_InvisibleItem InvIt;
1459       InvIt.SetValue( StepLayerAs );
1460       HInvsblItm->SetValue( 1, InvIt);
1461       
1462       Handle(StepVisual_Invisibility) Invsblt = new StepVisual_Invisibility();
1463       Invsblt->Init( HInvsblItm );
1464       Model->AddWithRefs( Invsblt );
1465     }
1466   }
1467   return Standard_True;
1468 }
1469
1470
1471 //=======================================================================
1472 //function : getSHUOstyle
1473 //purpose  : auxilary
1474 //=======================================================================
1475 static Standard_Boolean getSHUOstyle(const TDF_Label& aSHUOlab,
1476                                      const Handle(XCAFDoc_ColorTool)& CTool,
1477                                      XCAFPrs_Style& SHUOstyle)
1478 {
1479   Quantity_Color C;
1480   if (!CTool->IsVisible( aSHUOlab ) )
1481     SHUOstyle.SetVisibility(Standard_False);
1482   else {
1483     if ( CTool->GetColor ( aSHUOlab, XCAFDoc_ColorGen, C ) ) {
1484       SHUOstyle.SetColorCurv ( C );
1485       SHUOstyle.SetColorSurf ( C );
1486     }
1487     if ( CTool->GetColor ( aSHUOlab, XCAFDoc_ColorSurf, C ) )
1488       SHUOstyle.SetColorSurf ( C );
1489     if ( CTool->GetColor ( aSHUOlab, XCAFDoc_ColorCurv, C ) )
1490       SHUOstyle.SetColorCurv ( C );
1491   }
1492   if ( !SHUOstyle.IsSetColorCurv() && 
1493       !SHUOstyle.IsSetColorSurf() &&
1494       SHUOstyle.IsVisible() )
1495     return Standard_False;
1496   return Standard_True;
1497 }
1498
1499
1500 //=======================================================================
1501 //function : getProDefinitionOfNAUO
1502 //purpose  : auxilary
1503 //=======================================================================
1504 static Standard_Boolean getProDefinitionOfNAUO(const Handle(XSControl_WorkSession)& WS,
1505                                                const TopoDS_Shape& theShape,
1506                                                Handle(StepBasic_ProductDefinition)& PD,
1507                                                Handle(StepRepr_NextAssemblyUsageOccurrence)& NAUO,
1508                                                Standard_Boolean IsRelating)
1509 {
1510   if ( theShape.IsNull() )
1511     return Standard_False;
1512   // get CDSR
1513   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1514   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
1515   Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1516   Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, theShape );
1517   if (!FP->FindTypedTransient(mapper, 
1518                               STANDARD_TYPE(StepShape_ContextDependentShapeRepresentation),
1519                               CDSR))
1520     return Standard_False;
1521   // get PDS of NAUO
1522   Handle(StepRepr_ProductDefinitionShape) PDS = CDSR->RepresentedProductRelation();
1523   if (PDS.IsNull())
1524     return Standard_False;
1525   // get the NAUO entity
1526   Interface_Graph aGraph = WS->HGraph()->Graph();
1527   Interface_EntityIterator subs = aGraph.Shareds(PDS);
1528   for ( subs.Start(); subs.More(); subs.Next() ) {
1529     if (!subs.Value()->IsKind(STANDARD_TYPE(StepRepr_NextAssemblyUsageOccurrence)))
1530       continue;
1531     NAUO = Handle(StepRepr_NextAssemblyUsageOccurrence)::DownCast(subs.Value());
1532     break;
1533   }
1534   if ( NAUO.IsNull() )
1535     return Standard_False;
1536   // get Relatinf or Related product definition
1537   if ( !IsRelating )
1538     PD = NAUO->RelatedProductDefinition();
1539   else
1540     PD = NAUO->RelatingProductDefinition();
1541   if ( PD.IsNull() )
1542     return Standard_False;
1543   return Standard_True;
1544 }
1545
1546
1547 //=======================================================================
1548 //function : writeSHUO
1549 //purpose  : auxilary
1550 //=======================================================================
1551 static Standard_Boolean writeSHUO (const Handle(XCAFDoc_GraphNode)& theSHUO,
1552                                    const Handle(XCAFDoc_ShapeTool)& theSTool,
1553                                    const Handle(XSControl_WorkSession)& WS,
1554                                    Handle(StepRepr_SpecifiedHigherUsageOccurrence)& theTopSHUO,
1555                                    TopoDS_Shape& NAUOShape,
1556                                    Handle(StepBasic_ProductDefinition)& theRelatingPD,
1557                                    Standard_Boolean& isDeepest)
1558 {
1559   // set the ProductDefinitionRelationship descriptin information as empty strings.
1560   Handle(TCollection_HAsciiString) EmptyString = new TCollection_HAsciiString("");
1561   
1562   TDF_LabelSequence aNextUsageLabs;
1563   theSTool->GetSHUONextUsage( theSHUO->Label(), aNextUsageLabs );
1564   Handle(XCAFDoc_GraphNode) NuSHUO;
1565   if ( theTopSHUO.IsNull() ) {
1566     // the top SHUO
1567     if (aNextUsageLabs.Length() < 1)
1568       return Standard_False;
1569     theSTool->GetSHUO( aNextUsageLabs.Value(1), NuSHUO );
1570     if (NuSHUO.IsNull())
1571       return Standard_False;
1572     // get relating product definition
1573     TopoDS_Shape aTopCompShape = theSTool->GetShape( theSHUO->Label().Father() ); 
1574     Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO;
1575     if (!getProDefinitionOfNAUO( WS, aTopCompShape,
1576                                  theRelatingPD, UUNAUO, Standard_True ))
1577       return Standard_False;
1578     // get related product definition
1579     TopoDS_Shape aNUShape = theSTool->GetShape( NuSHUO->Label().Father() );
1580     Handle(StepBasic_ProductDefinition) aRelatedPD;
1581     Handle(StepRepr_NextAssemblyUsageOccurrence) NUNAUO;
1582     if (!getProDefinitionOfNAUO( WS, aNUShape,
1583                                  aRelatedPD, NUNAUO, Standard_False ))
1584       return Standard_False;
1585     
1586     theTopSHUO = new StepRepr_SpecifiedHigherUsageOccurrence;
1587     // create deepest shuo EmptyString
1588     theTopSHUO->Init(/*id*/EmptyString, /*name*/EmptyString,
1589                      /*no description*/Standard_False,/*description*/EmptyString,
1590                      theRelatingPD, aRelatedPD,
1591                      /*no ACURefDesignator*/Standard_False,/*ACURefDesignator*/EmptyString,
1592                      /*upper_usage*/UUNAUO, /*next_usage*/NUNAUO);
1593     // write the other SHUO.
1594     if(!writeSHUO( NuSHUO, theSTool, WS, theTopSHUO, NAUOShape, theRelatingPD, isDeepest )) {
1595       theTopSHUO.Nullify();
1596       return Standard_False;
1597     }
1598     
1599     return Standard_True;
1600   }
1601 //   Handle(XCAFDoc_GraphNode) NuSHUO;
1602   if ( aNextUsageLabs.Length() > 0) {
1603     // store SHUO recursive
1604 #ifdef DEB
1605     if ( aNextUsageLabs.Length() > 1 )
1606       cout << "Warning: store only one next_usage of current SHUO"  << endl;
1607 #endif    
1608     theSTool->GetSHUO( aNextUsageLabs.Value(1), NuSHUO );
1609     Handle(StepRepr_SpecifiedHigherUsageOccurrence) aNUEntSHUO =
1610       new StepRepr_SpecifiedHigherUsageOccurrence;
1611     if (!writeSHUO( NuSHUO, theSTool, WS, aNUEntSHUO, NAUOShape, theRelatingPD, isDeepest ))
1612       return Standard_False;
1613     
1614     // store the deepest SHUO to the dociment
1615     TopoDS_Shape aNUSh, aUUSh;
1616     aNUSh = theSTool->GetShape( NuSHUO->Label().Father() );
1617     aUUSh = theSTool->GetShape( theSHUO->Label().Father() );
1618     // get relating PD with upper_usage and related PD with next_usage
1619     Handle(StepBasic_ProductDefinition) nullPD;// no need to use,case have shared <theRelatingPD>
1620     Handle(StepBasic_ProductDefinition) aRelatedPD;
1621     Handle(StepRepr_NextAssemblyUsageOccurrence) UUNAUO, NUNAUO;
1622     if (!getProDefinitionOfNAUO( WS, aUUSh, nullPD, UUNAUO, Standard_True ) ||
1623         !getProDefinitionOfNAUO( WS, aNUSh, aRelatedPD, NUNAUO, Standard_False )) {
1624 #ifdef DEB
1625       cout << "Warning: cannot get related or relating PD" << endl;
1626 #endif
1627       return Standard_False;
1628     }
1629     aNUEntSHUO->Init(/*id*/EmptyString, /*name*/EmptyString,
1630                      /*no description*/Standard_False,/*description*/EmptyString,
1631                      theRelatingPD, aRelatedPD,
1632                      /*no ACURefDesignator*/Standard_False,/*ACURefDesignator*/EmptyString,
1633                      /*upper_usage*/theTopSHUO, /*next_usage*/NUNAUO);
1634     if ( isDeepest ) {
1635       isDeepest = Standard_False;
1636     }
1637     WS->Model()->AddWithRefs ( aNUEntSHUO );
1638     return Standard_True;
1639   } // end of recurse storing
1640     
1641   // get shape 
1642   TDF_Label aShapeL = theSHUO->Label().Father();
1643   NAUOShape = theSTool->GetShape( aShapeL );
1644   // return to the deepest level from SHUO shape level
1645   // it is because SHUO is attribute on deep level and shape level.
1646   isDeepest = Standard_True;
1647   return Standard_True;
1648 }
1649
1650
1651 //=======================================================================
1652 //function : createSHUOStyledItem
1653 //purpose  : auxilary
1654 //=======================================================================
1655 static Standard_Boolean createSHUOStyledItem (const XCAFPrs_Style& style,
1656                                               const Handle(StepRepr_ProductDefinitionShape)& PDS,
1657                                               const Handle(XSControl_WorkSession) &WS,
1658                                               const TopoDS_Shape& Sh,
1659                                               const Handle(XCAFDoc_ShapeTool)& STool,
1660                                               MoniTool_DataMapOfShapeTransient& myMapCompMDGPR)
1661 {
1662   // create styled item for the indicated SHUO and store to the model
1663   STEPConstruct_Styles Styles( WS );
1664   // translate colors to STEP
1665   Handle(StepVisual_Colour) surfColor, curvColor;
1666   if ( style.IsSetColorSurf() )
1667     surfColor = Styles.EncodeColor ( style.GetColorSurf() );
1668   if ( style.IsSetColorCurv() )
1669     curvColor = Styles.EncodeColor ( style.GetColorCurv() );
1670   Standard_Boolean isComponent = Standard_True;// cause need to get PSBC
1671   Handle(StepRepr_RepresentationItem) item;
1672   // set default color for invisible SHUO.
1673   Standard_Boolean isSetDefaultColor = Standard_False;
1674   if (surfColor.IsNull() && curvColor.IsNull() && !style.IsVisible() ) {
1675     surfColor = Styles.EncodeColor ( Quantity_Color( 1, 1, 1, Quantity_TOC_RGB ) );
1676     isSetDefaultColor = Standard_True;
1677   }
1678   Handle(StepVisual_PresentationStyleAssignment) PSA =
1679     Styles.MakeColorPSA ( item, surfColor, curvColor, isComponent );
1680   Handle(StepVisual_StyledItem) override; //null styled item
1681   
1682   // find the repr item of the shape
1683   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1684   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
1685   Handle(TransferBRep_ShapeMapper) mapper = TransferBRep::ShapeMapper ( FP, Sh );
1686   Handle(StepShape_ContextDependentShapeRepresentation) CDSR;
1687   FP->FindTypedTransient(mapper, 
1688                          STANDARD_TYPE(StepShape_ContextDependentShapeRepresentation),
1689                          CDSR);
1690   if ( CDSR.IsNull() )
1691     return Standard_False;
1692   // find context
1693   Handle(StepRepr_RepresentationContext) Context = Styles.FindContext( Sh );
1694   TopoDS_Shape aTopSh = Sh;
1695   if (Context.IsNull()) {
1696     TDF_Label aTopShL = STool->FindShape(Sh, Standard_False);
1697     if (aTopShL.IsNull())
1698       return Standard_False;
1699     aTopSh = STool->GetShape( aTopShL );
1700     Context = Styles.FindContext ( aTopSh );
1701   }
1702   if (Context.IsNull())
1703     return Standard_False;
1704   // get representation item of the shape
1705   TopLoc_Location L;
1706   TColStd_SequenceOfTransient seqRI;
1707   FindEntities ( FP, Sh, L, seqRI );
1708 #ifdef DEB
1709   if ( seqRI.Length() <=0 ) 
1710     FP->Messenger() << "Warning: Cannot find RI for " << Sh.TShape()->DynamicType()->Name() << endl;
1711 #endif
1712   item = Handle(StepRepr_RepresentationItem)::DownCast(seqRI(1));
1713   //get overridden styled item
1714   getStyledItem(Sh,STool, Styles, override,myMapCompMDGPR);
1715   
1716   // get STEP STYLED ITEM
1717   Handle(StepVisual_StyledItem) STEPstyle = Styles.AddStyle ( item, PSA, override );
1718   // create SR, SDR and all necessary references between them and ST, PDS, PSBC, GRC
1719   Styles.CreateNAUOSRD( Context, CDSR, PDS );
1720   
1721   // add step styled item of SHUO to the model
1722   // do it by additing styled item to the MDGPR
1723   if ( !aTopSh.IsNull() &&  !myMapCompMDGPR.IsBound( aTopSh ) ) {
1724     // create MDGPR and record it in model
1725 #ifdef DEB
1726     cout << "Warning: " << __FILE__ << ": Create new MDGPR for SHUO instance"  << endl;
1727 #endif
1728     Handle(StepVisual_MechanicalDesignGeometricPresentationRepresentation) aMDGPR;
1729     Styles.CreateMDGPR ( Context, aMDGPR );
1730     if (!aMDGPR.IsNull())
1731       myMapCompMDGPR.Bind( aTopSh, aMDGPR );
1732   }
1733   else if ( !aTopSh.IsNull() &&  myMapCompMDGPR.IsBound( aTopSh ) ) {
1734     // get MDGPR of the top-level shape
1735     Handle(StepVisual_PresentationRepresentation) aMDGPR = 
1736       Handle(StepVisual_PresentationRepresentation)::DownCast( myMapCompMDGPR.Find( aTopSh ) );
1737     // get old styled items to not lose it
1738     Handle(StepRepr_HArray1OfRepresentationItem) oldItems = aMDGPR->Items();
1739     Standard_Integer oldLengthlen = 0;
1740     if (!oldItems.IsNull())
1741       oldLengthlen = oldItems->Length();
1742     // create new array of styled items by an olds and new one
1743     Handle(StepRepr_HArray1OfRepresentationItem) newItems =
1744       new StepRepr_HArray1OfRepresentationItem(1, oldLengthlen + 1);
1745     Standard_Integer si;
1746     Standard_Integer el = 1;
1747     for ( si=1; si <= oldLengthlen; si++ )
1748       newItems->SetValue( el++, oldItems->Value( si ) );
1749     newItems->SetValue( el++, Handle(StepRepr_RepresentationItem)::DownCast(STEPstyle) );
1750     // init MDGPR be new array of styled items
1751     if (newItems->Length() > 0)
1752       aMDGPR->SetItems( newItems );
1753   }
1754   else {
1755     WS->Model()->AddWithRefs ( STEPstyle ); // add as root to the model, but it is not good
1756 #ifdef DEB
1757     cout << "Warning: " << __FILE__ << ": adds styled item of SHUO as root, casue cannot find MDGPR" << endl;
1758 #endif
1759   }
1760   // create invisibility item for the styled item
1761   if ( !style.IsVisible() ) {
1762     if (isSetDefaultColor) {
1763       // try to set default color from top-level shape
1764       
1765       setDefaultInstanceColor(override, PSA);
1766     }
1767     // create invisibility item and refer for stiledItem
1768     Handle(StepVisual_Invisibility) Invsblt = new StepVisual_Invisibility();
1769     Handle(StepVisual_HArray1OfInvisibleItem) HInvsblItm = 
1770       new StepVisual_HArray1OfInvisibleItem (1,1);
1771     // put all style item into the harray
1772     StepVisual_InvisibleItem anInvItem;
1773     anInvItem.SetValue( STEPstyle );
1774     HInvsblItm->SetValue( 1, anInvItem );
1775     Invsblt->Init( HInvsblItm );
1776     WS->Model()->AddWithRefs( Invsblt );
1777   }
1778   
1779   return Standard_True;
1780 }
1781
1782
1783 //=======================================================================
1784 //function : WriteSHUOs
1785 //purpose  : 
1786 //=======================================================================
1787
1788 Standard_Boolean STEPCAFControl_Writer::WriteSHUOs (const Handle(XSControl_WorkSession) &WS,
1789                                                     const TDF_LabelSequence  &labels )
1790 {
1791   if ( labels.Length() <=0 ) return Standard_False;
1792
1793   // get working data
1794   Handle(Interface_InterfaceModel) Model = WS->Model();
1795   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1796   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
1797   Handle(XCAFDoc_ColorTool) CTool = XCAFDoc_DocumentTool::ColorTool( labels(1) );
1798   if (CTool.IsNull() )
1799     return Standard_False;
1800   // map of transfered SHUO
1801   TColStd_MapOfTransient aMapOfMainSHUO;
1802 //   TColStd_IndexedDataMapOfTransientTransient aIndxMapOfSHUOEnt;
1803   // Iterate on requested shapes
1804   for ( Standard_Integer i=1; i <= labels.Length(); i++ ) {
1805     TDF_Label L = labels.Value(i);
1806     if ( ! myLabels.IsBound ( L ) ) continue; // not recorded as translated, skip
1807 //     TopoDS_Shape S = myLabels.Find ( L );
1808     if ( XCAFDoc_ShapeTool::IsAssembly ( L ) ) {
1809       TDF_LabelSequence seq;
1810       XCAFDoc_ShapeTool::GetComponents ( L, seq );
1811       // iterates on components of assembly
1812       for (Standard_Integer k=1; k <= seq.Length(); k++) {
1813         TDF_Label lab = seq(k);
1814         TDF_AttributeSequence anAttrSeq;
1815         CTool->ShapeTool()->GetAllComponentSHUO( lab, anAttrSeq );
1816         // work with SHUO
1817         for (Standard_Integer j = 1; j <= anAttrSeq.Length(); j++) {
1818           Handle(XCAFDoc_GraphNode) aSHUO = 
1819             Handle(XCAFDoc_GraphNode)::DownCast(anAttrSeq.Value( j ));
1820           // take label of SHUO
1821           TDF_Label aSHUOlab = aSHUO->Label();
1822           TDF_LabelSequence aUpLabels;
1823           // check is it SHUO of upper_usage
1824           CTool->ShapeTool()->GetSHUOUpperUsage( aSHUOlab, aUpLabels );
1825           if ( aUpLabels.Length() > 0 )
1826             continue; // transfer only main SHUO
1827           if ( aMapOfMainSHUO.Contains( aSHUO ) )
1828             continue; // do not try to transfer SHUO twice
1829           aMapOfMainSHUO.Add( aSHUO );
1830           // check if it is styled SHUO
1831           XCAFPrs_Style SHUOstyle;
1832           if ( !getSHUOstyle ( aSHUOlab, CTool, SHUOstyle ) ) {
1833 #ifdef DEB
1834             cout << "Warning: " << __FILE__ << ": do not store SHUO without any style to the STEP model" << endl;
1835 #endif
1836             continue;
1837           }
1838           // write SHUO to the model amd then add structure type.
1839           TopoDS_Shape NAUOShape; // shape of the deepest NAUO in the SHUO structure
1840           Standard_Boolean isDeepest = Standard_False;
1841           Handle(StepRepr_SpecifiedHigherUsageOccurrence) anEntOfSHUO;
1842           Handle(StepBasic_ProductDefinition) aRelatingPD;
1843           // create the top SHUO and all other.
1844           writeSHUO( aSHUO, CTool->ShapeTool(), WS, anEntOfSHUO, NAUOShape, aRelatingPD, isDeepest );
1845           if ( anEntOfSHUO.IsNull() || NAUOShape.IsNull() ) {
1846 #ifdef DEB
1847             cout << "Warning: " << __FILE__ << ": Cannot store SHUO" << endl;
1848 #endif
1849             continue;
1850           }
1851           // create new Product Definition Shape for TOP SHUO
1852 #ifdef DEB
1853             cout << "Info: " << __FILE__ << ": Create NEW PDS for current SHUO " << endl;
1854 #endif
1855           Handle(StepRepr_ProductDefinitionShape) PDS = new StepRepr_ProductDefinitionShape;
1856           Handle(TCollection_HAsciiString) aPDSname = new TCollection_HAsciiString("SHUO");
1857           Handle(TCollection_HAsciiString) descrStr = new TCollection_HAsciiString("");
1858           StepRepr_CharacterizedDefinition aCharDef;
1859           aCharDef.SetValue( anEntOfSHUO );
1860           PDS->Init( aPDSname, Standard_False, descrStr, aCharDef );
1861           
1862           // create styled item for SHUO and add to the model
1863           createSHUOStyledItem ( SHUOstyle, PDS, WS, NAUOShape, CTool->ShapeTool(), myMapCompMDGPR );
1864           
1865         } // end work with SHUO
1866       } // end of an assembly components
1867     } // end of IsAssembly case
1868     // nothing to do if it is not assembly
1869     continue;
1870   } // end of iterates on indicated labels
1871   return Standard_True;
1872 }
1873
1874
1875 //=======================================================================
1876 //function : FindPDSforDGT
1877 //purpose  : auxilary: find PDS for AdvancedFace or EdgeCurve for creation
1878 //                     needed ShapeAspect in D&GT structure
1879 //=======================================================================
1880 static Standard_Boolean FindPDSforDGT(const Interface_Graph &aGraph,
1881                                       const Handle(Standard_Transient) &ent,
1882                                       Handle(StepRepr_ProductDefinitionShape) &PDS,
1883                                       Handle(StepRepr_RepresentationContext) &RC,
1884                                       Handle(StepShape_AdvancedFace) &AF,
1885                                       Handle(StepShape_EdgeCurve) &EC)
1886 {
1887   if( !ent->IsKind(STANDARD_TYPE(StepShape_EdgeCurve)) && 
1888       !ent->IsKind(STANDARD_TYPE(StepShape_AdvancedFace)) ) 
1889     return Standard_False;
1890
1891   AF = Handle(StepShape_AdvancedFace)::DownCast(ent);
1892   if( ent->IsKind(STANDARD_TYPE(StepShape_EdgeCurve)) ) {
1893     EC = Handle(StepShape_EdgeCurve)::DownCast(ent);
1894     Interface_EntityIterator subs = aGraph.Sharings(EC);
1895     for(subs.Start(); subs.More() && AF.IsNull(); subs.Next()) {
1896       Handle(StepShape_OrientedEdge) OE = Handle(StepShape_OrientedEdge)::DownCast(subs.Value());
1897       if(OE.IsNull()) continue;
1898       Interface_EntityIterator subs1 = aGraph.Sharings(OE);
1899       for(subs1.Start(); subs1.More() && AF.IsNull(); subs1.Next()) {
1900         Handle(StepShape_EdgeLoop) EL = Handle(StepShape_EdgeLoop)::DownCast(subs1.Value());
1901         if(EL.IsNull()) continue;
1902         Interface_EntityIterator subs2 = aGraph.Sharings(EL);
1903         for(subs2.Start(); subs2.More() && AF.IsNull(); subs2.Next()) {
1904           Handle(StepShape_FaceBound) FB = Handle(StepShape_FaceBound)::DownCast(subs2.Value());
1905           if(FB.IsNull()) continue;
1906           Interface_EntityIterator subs3 = aGraph.Sharings(FB);
1907           for(subs3.Start(); subs3.More() && AF.IsNull(); subs3.Next()) {
1908             AF = Handle(StepShape_AdvancedFace)::DownCast(subs3.Value());
1909           }
1910         }
1911       }
1912     }
1913   }
1914   if(AF.IsNull()) return Standard_False;
1915
1916   Interface_EntityIterator subs = aGraph.Sharings(AF);
1917   for(subs.Start(); subs.More() && PDS.IsNull(); subs.Next()) {
1918     Handle(StepShape_ConnectedFaceSet) CFS =
1919       Handle(StepShape_ConnectedFaceSet)::DownCast(subs.Value());
1920     if(CFS.IsNull()) continue;
1921     Interface_EntityIterator subs1 = aGraph.Sharings(CFS);
1922     for(subs1.Start(); subs1.More() && PDS.IsNull(); subs1.Next()) {
1923       Handle(StepRepr_RepresentationItem) RI = 
1924         Handle(StepRepr_RepresentationItem)::DownCast(subs1.Value());
1925       if(RI.IsNull()) continue;
1926       Interface_EntityIterator subs2 = aGraph.Sharings(RI);
1927       for(subs2.Start(); subs2.More() && PDS.IsNull(); subs2.Next()) {
1928         Handle(StepShape_ShapeRepresentation) SR = 
1929           Handle(StepShape_ShapeRepresentation)::DownCast(subs2.Value());
1930         if(SR.IsNull()) continue;
1931         RC = SR->ContextOfItems();
1932         Interface_EntityIterator subs3 = aGraph.Sharings(SR);
1933         for(subs3.Start(); subs3.More() && PDS.IsNull(); subs3.Next()) {
1934           Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
1935             Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs3.Value());
1936           if(SDR.IsNull()) continue;
1937           Handle(StepRepr_PropertyDefinition) PropD = SDR->Definition().PropertyDefinition();
1938           if(PropD.IsNull()) continue;
1939           PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(PropD);
1940         }
1941       }
1942     }
1943   }
1944   
1945   return Standard_True;
1946 }
1947
1948
1949 //=======================================================================
1950 //function : WriteDGTs
1951 //purpose  : 
1952 //=======================================================================
1953
1954 Standard_Boolean STEPCAFControl_Writer::WriteDGTs (const Handle(XSControl_WorkSession) &WS,
1955                                                    const TDF_LabelSequence  &labels ) const
1956 {
1957   
1958   if ( labels.Length() <=0 ) return Standard_False;
1959
1960   // get working data
1961   Handle(Interface_InterfaceModel) Model = WS->Model();
1962   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
1963   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
1964   Interface_Graph aGraph = WS->HGraph()->Graph();
1965   Handle(XCAFDoc_DimTolTool) DGTTool = XCAFDoc_DocumentTool::DimTolTool( labels(1) );
1966   if(DGTTool.IsNull() ) return Standard_False;
1967
1968   TDF_LabelSequence DGTLabels;
1969   STEPConstruct_DataMapOfAsciiStringTransient DatumMap;
1970
1971   // write Datums
1972   DGTTool->GetDatumLabels(DGTLabels);
1973   if(DGTLabels.Length()<=0) return Standard_False;
1974   Standard_Integer i;
1975   for(i=1; i<=DGTLabels.Length(); i++) {
1976     TDF_Label DatumL = DGTLabels.Value(i);
1977     TDF_Label ShapeL;
1978     if(!DGTTool->GetRefShapeLabel(DatumL,ShapeL)) continue;
1979     // find target shape
1980     TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(ShapeL);
1981     TopLoc_Location Loc;
1982     TColStd_SequenceOfTransient seqRI;
1983     FindEntities( FP, aShape, Loc, seqRI );
1984     if ( seqRI.Length() <= 0 ) {
1985       FP->Messenger() << "Warning: Cannot find RI for "<<aShape.TShape()->DynamicType()->Name()<<endl;
1986       continue;
1987     }
1988     Handle(StepRepr_ProductDefinitionShape) PDS;
1989     Handle(StepRepr_RepresentationContext) RC;
1990     Handle(Standard_Transient) ent = seqRI.Value(1);
1991     Handle(StepShape_AdvancedFace) AF;
1992     Handle(StepShape_EdgeCurve) EC;
1993     FindPDSforDGT(aGraph,ent,PDS,RC,AF,EC);
1994     if(PDS.IsNull()) continue;
1995     //cout<<"Model->Number(PDS)="<<Model->Number(PDS)<<endl;
1996     Handle(XCAFDoc_Datum) DatumAttr;
1997     if(!DatumL.FindAttribute(XCAFDoc_Datum::GetID(),DatumAttr)) continue;
1998     Handle(TCollection_HAsciiString) aName = DatumAttr->GetName();
1999     Handle(TCollection_HAsciiString) aDescription = DatumAttr->GetDescription();
2000     Handle(TCollection_HAsciiString) anIdentification = DatumAttr->GetIdentification();
2001     Handle(StepDimTol_DatumFeature) DF = new StepDimTol_DatumFeature;
2002     Handle(StepDimTol_Datum) aDatum = new StepDimTol_Datum;
2003     DF->Init(aName, new TCollection_HAsciiString, PDS, StepData_LTrue);
2004     Model->AddWithRefs(DF);
2005     aDatum->Init(aName, new TCollection_HAsciiString, PDS, StepData_LFalse, anIdentification);
2006     Model->AddWithRefs(aDatum);
2007     Handle(StepRepr_ShapeAspectRelationship) SAR = new StepRepr_ShapeAspectRelationship;
2008     SAR->SetName(aName);
2009     SAR->SetRelatingShapeAspect(DF);
2010     SAR->SetRelatedShapeAspect(aDatum);
2011     Model->AddWithRefs(SAR);
2012     // write chain for DatumFeature
2013     StepRepr_CharacterizedDefinition CD;
2014     CD.SetValue(DF);
2015     Handle(StepRepr_PropertyDefinition) PropD = new StepRepr_PropertyDefinition;
2016     PropD->Init(aName,Standard_True,aDescription,CD);
2017     Model->AddWithRefs(PropD);
2018     StepRepr_RepresentedDefinition RD;
2019     RD.SetValue(PropD);
2020     Handle(StepShape_ShapeRepresentation) SR = new StepShape_ShapeRepresentation;
2021     Handle(StepRepr_HArray1OfRepresentationItem) HARI =
2022       new StepRepr_HArray1OfRepresentationItem(1,1);
2023     HARI->SetValue(1,AF);
2024     SR->Init(aName,HARI,RC);
2025     Handle(StepShape_ShapeDefinitionRepresentation) SDR = new StepShape_ShapeDefinitionRepresentation;
2026     SDR->Init(RD,SR);
2027     Model->AddWithRefs(SDR);
2028     // write chain for Datum 
2029     StepRepr_CharacterizedDefinition CD1;
2030     CD1.SetValue(aDatum);
2031     Handle(StepRepr_PropertyDefinition) PropD1 = new StepRepr_PropertyDefinition;
2032     PropD1->Init(aName,Standard_True,aDescription,CD1);
2033     Model->AddWithRefs(PropD1);
2034     StepRepr_RepresentedDefinition RD1;
2035     RD1.SetValue(PropD1);
2036     Handle(StepShape_ShapeRepresentation) SR1 = new StepShape_ShapeRepresentation;
2037     Handle(StepRepr_HArray1OfRepresentationItem) HARI1 =
2038       new StepRepr_HArray1OfRepresentationItem(1,1);
2039     HARI1->SetValue(1,AF->FaceGeometry());
2040     SR1->Init(aName,HARI1,RC);
2041     Model->AddWithRefs(SR1);
2042     Handle(StepShape_ShapeDefinitionRepresentation) SDR1 = new StepShape_ShapeDefinitionRepresentation;
2043     SDR1->Init(RD1,SR1);
2044     Model->AddWithRefs(SDR1);
2045     // add created Datum into Map
2046     TCollection_AsciiString stmp(aName->ToCString());
2047     stmp.AssignCat(aDescription->ToCString());
2048     stmp.AssignCat(anIdentification->ToCString());
2049     DatumMap.Bind(stmp,aDatum);
2050   }
2051
2052   // write Tolerances and Dimensions
2053   DGTLabels.Clear();
2054   DGTTool->GetDimTolLabels(DGTLabels);
2055   if(DGTLabels.Length()<=0) return Standard_False;
2056   for(i=1; i<=DGTLabels.Length(); i++) {
2057     TDF_Label DimTolL = DGTLabels.Value(i);
2058     TDF_Label ShapeL;
2059     if(!DGTTool->GetRefShapeLabel(DimTolL,ShapeL)) continue;
2060     // find target shape
2061     TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(ShapeL);
2062     TopLoc_Location Loc;
2063     TColStd_SequenceOfTransient seqRI;
2064     FindEntities( FP, aShape, Loc, seqRI );
2065     if ( seqRI.Length() <= 0 ) {
2066       FP->Messenger() << "Warning: Cannot find RI for "<<aShape.TShape()->DynamicType()->Name()<<endl;
2067       continue;
2068     }
2069     Handle(StepRepr_ProductDefinitionShape) PDS;
2070     Handle(StepRepr_RepresentationContext) RC;
2071     Handle(Standard_Transient) ent = seqRI.Value(1);
2072     Handle(StepShape_AdvancedFace) AF;
2073     Handle(StepShape_EdgeCurve) EC;
2074     FindPDSforDGT(aGraph,ent,PDS,RC,AF,EC);
2075     if(PDS.IsNull()) continue;
2076     //cout<<"Model->Number(PDS)="<<Model->Number(PDS)<<endl;
2077
2078     Handle(XCAFDoc_DimTol) DimTolAttr;
2079     if(!DimTolL.FindAttribute(XCAFDoc_DimTol::GetID(),DimTolAttr)) continue;
2080     Standard_Integer kind = DimTolAttr->GetKind();
2081     Handle(TColStd_HArray1OfReal) aVal = DimTolAttr->GetVal();
2082     Handle(TCollection_HAsciiString) aName = DimTolAttr->GetName();
2083     Handle(TCollection_HAsciiString) aDescription = DimTolAttr->GetDescription();
2084
2085     // common part of writing D&GT entities
2086     StepRepr_CharacterizedDefinition CD;
2087     Handle(StepRepr_ShapeAspect) SA = new StepRepr_ShapeAspect;
2088     SA->Init(aName, new TCollection_HAsciiString, PDS, StepData_LTrue);
2089     Model->AddWithRefs(SA);
2090     CD.SetValue(SA);
2091     Handle(StepRepr_PropertyDefinition) PropD = new StepRepr_PropertyDefinition;
2092     PropD->Init(aName,Standard_True,aDescription,CD);
2093     Model->AddWithRefs(PropD);
2094     StepRepr_RepresentedDefinition RD;
2095     RD.SetValue(PropD);
2096     Handle(StepShape_ShapeRepresentation) SR = new StepShape_ShapeRepresentation;
2097     Handle(StepRepr_HArray1OfRepresentationItem) HARI =
2098       new StepRepr_HArray1OfRepresentationItem(1,1);
2099     if(kind<20) 
2100       HARI->SetValue(1,EC);
2101     else
2102       HARI->SetValue(1,AF);
2103     SR->Init(aName,HARI,RC);
2104     Handle(StepShape_ShapeDefinitionRepresentation) SDR = new StepShape_ShapeDefinitionRepresentation;
2105     SDR->Init(RD,SR);
2106     Model->AddWithRefs(SDR);
2107     // define aUnit for creation LengthMeasureWithUnit (common for all)
2108     StepBasic_Unit aUnit;
2109     Handle(StepBasic_SiUnitAndLengthUnit) SLU;
2110     Handle(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext) Ctx =
2111       Handle(StepGeom_GeometricRepresentationContextAndGlobalUnitAssignedContext)::DownCast(RC);
2112     if(!Ctx.IsNull()) {
2113       for(Standard_Integer j=1; j<=Ctx->NbUnits(); j++) {
2114         if(Ctx->UnitsValue(j)->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndLengthUnit))) {
2115           SLU = Handle(StepBasic_SiUnitAndLengthUnit)::DownCast(Ctx->UnitsValue(j));
2116           break;
2117         }
2118       }
2119     }
2120     if(SLU.IsNull()) {
2121       Handle(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx) Ctx1 =
2122         Handle(StepGeom_GeomRepContextAndGlobUnitAssCtxAndGlobUncertaintyAssCtx)::DownCast(RC);
2123       if(!Ctx1.IsNull()) {
2124         for(Standard_Integer j=1; j<=Ctx1->NbUnits(); j++) {
2125           if(Ctx1->UnitsValue(j)->IsKind(STANDARD_TYPE(StepBasic_SiUnitAndLengthUnit))) {
2126             SLU = Handle(StepBasic_SiUnitAndLengthUnit)::DownCast(Ctx1->UnitsValue(j));
2127             break;
2128           }
2129         }
2130       }
2131     }
2132     if(SLU.IsNull()) {
2133       SLU = new StepBasic_SiUnitAndLengthUnit;
2134     }
2135     aUnit.SetValue(SLU);
2136
2137     // specific part of writing D&GT entities
2138     if(kind<20) { //dimension
2139       Handle(StepShape_DimensionalSize) DimSize = new StepShape_DimensionalSize;
2140       DimSize->Init(SA,aDescription);
2141       Model->AddWithRefs(DimSize);
2142       if(aVal->Length()>1) {
2143         // create MeasureWithUnits
2144         Handle(StepBasic_MeasureValueMember) MVM1 = new StepBasic_MeasureValueMember;
2145         MVM1->SetName("POSITIVE_LENGTH_MEASURE");
2146         MVM1->SetReal(aVal->Value(1));
2147         Handle(StepBasic_MeasureWithUnit) MWU1 = new StepBasic_MeasureWithUnit;
2148         MWU1->Init(MVM1,aUnit);
2149         Handle(StepBasic_MeasureValueMember) MVM2 = new StepBasic_MeasureValueMember;
2150         MVM2->SetName("POSITIVE_LENGTH_MEASURE");
2151         MVM2->SetReal(aVal->Value(2));
2152         Handle(StepBasic_MeasureWithUnit) MWU2 = new StepBasic_MeasureWithUnit;
2153         MWU2->Init(MVM2,aUnit);
2154         Handle(StepRepr_RepresentationItem) RI1 = new StepRepr_RepresentationItem;
2155         RI1->Init(new TCollection_HAsciiString("lower limit"));
2156         Handle(StepRepr_RepresentationItem) RI2 = new StepRepr_RepresentationItem;
2157         RI2->Init(new TCollection_HAsciiString("upper limit"));
2158         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMU1 =
2159           new StepRepr_ReprItemAndLengthMeasureWithUnit;
2160         RILMU1->Init(MWU1,RI1);
2161         Handle(StepRepr_ReprItemAndLengthMeasureWithUnit) RILMU2 =
2162           new StepRepr_ReprItemAndLengthMeasureWithUnit;
2163         RILMU2->Init(MWU2,RI2);
2164         Model->AddWithRefs(RILMU1);
2165         Model->AddWithRefs(RILMU2);
2166         //Handle(StepRepr_CompoundItemDefinitionMember) CIDM =
2167         //  new StepRepr_CompoundItemDefinitionMember;
2168         //Handle(TColStd_HArray1OfTransient) ArrTr = new TColStd_HArray1OfTransient(1,2);
2169         //ArrTr->SetValue(1,RILMU1);
2170         //ArrTr->SetValue(2,RILMU2);
2171         //CIDM->SetArrTransient(ArrTr);
2172         //CIDM->SetName("SET_REPRESENTATION_ITEM");
2173         //StepRepr_CompoundItemDefinition CID;
2174         //CID.SetValue(CIDM);
2175         Handle(StepRepr_HArray1OfRepresentationItem) HARIVR =
2176           new StepRepr_HArray1OfRepresentationItem(1,2);
2177         HARIVR->SetValue(1,RILMU1);
2178         HARIVR->SetValue(2,RILMU2);
2179         Handle(StepRepr_ValueRange) VR = new StepRepr_ValueRange;
2180         //VR->Init(aName,CID);
2181         VR->Init(aName,HARIVR);
2182         Model->AddEntity(VR);
2183         Handle(StepShape_ShapeDimensionRepresentation) SDimR =
2184           new StepShape_ShapeDimensionRepresentation;
2185         Handle(StepRepr_HArray1OfRepresentationItem) HARI =
2186           new StepRepr_HArray1OfRepresentationItem(1,1);
2187         HARI->SetValue(1,VR);
2188         SDimR->Init(aName,HARI,RC);
2189         Model->AddWithRefs(SDimR);
2190         Handle(StepShape_DimensionalCharacteristicRepresentation) DimCharR =
2191           new StepShape_DimensionalCharacteristicRepresentation;
2192         StepShape_DimensionalCharacteristic DimChar;
2193         DimChar.SetValue(DimSize);
2194         DimCharR->Init(DimChar,SDimR);
2195         Model->AddEntity(DimCharR);
2196       }
2197     }
2198     else if(kind<50) { //tolerance
2199       if(kind<35) { // tolerance with datum system
2200         TDF_LabelSequence DatumLabels;
2201         DGTTool->GetDatumTolerLabels(DimTolL,DatumLabels);
2202         Standard_Integer NbDR = DatumLabels.Length();
2203         Handle(StepDimTol_HArray1OfDatumReference) HADR = new StepDimTol_HArray1OfDatumReference(1,NbDR);
2204         for(Standard_Integer j=1; j<=NbDR; j++) {
2205           Handle(XCAFDoc_Datum) DatumAttr;
2206           TDF_Label DatumL = DatumLabels.Value(j);
2207           if(!DatumL.FindAttribute(XCAFDoc_Datum::GetID(),DatumAttr)) continue;
2208           Handle(TCollection_HAsciiString) aNameD = DatumAttr->GetName();
2209           Handle(TCollection_HAsciiString) aDescriptionD = DatumAttr->GetDescription();
2210           Handle(TCollection_HAsciiString) anIdentificationD = DatumAttr->GetIdentification();
2211           TCollection_AsciiString stmp(aNameD->ToCString());
2212           stmp.AssignCat(aDescriptionD->ToCString());
2213           stmp.AssignCat(anIdentificationD->ToCString());
2214           if(DatumMap.IsBound(stmp)) {
2215             Handle(StepDimTol_Datum) aDatum = 
2216               Handle(StepDimTol_Datum)::DownCast(DatumMap.Find(stmp));
2217             Handle(StepDimTol_DatumReference) DR = new StepDimTol_DatumReference;
2218             DR->Init(j,aDatum);
2219             Model->AddWithRefs(DR);
2220             HADR->SetValue(j,DR);
2221           }
2222         }
2223         // create LengthMeasureWithUnit
2224         Handle(StepBasic_MeasureValueMember) MVM = new StepBasic_MeasureValueMember;
2225         MVM->SetName("LENGTH_MEASURE");
2226         MVM->SetReal(aVal->Value(1));
2227         Handle(StepBasic_LengthMeasureWithUnit) LMWU = new StepBasic_LengthMeasureWithUnit;
2228         LMWU->Init(MVM,aUnit);
2229         // create tolerance by it's type
2230         if(kind<24) {
2231           Handle(StepDimTol_GeometricToleranceWithDatumReference) GTWDR =
2232             new StepDimTol_GeometricToleranceWithDatumReference;
2233           GTWDR->SetDatumSystem(HADR);
2234           Handle(StepDimTol_ModifiedGeometricTolerance) MGT =
2235             new StepDimTol_ModifiedGeometricTolerance;
2236           if(kind==21) MGT->SetModifier(StepDimTol_MaximumMaterialCondition);
2237           else if(kind==22) MGT->SetModifier(StepDimTol_LeastMaterialCondition);
2238           else if(kind==23) MGT->SetModifier(StepDimTol_RegardlessOfFeatureSize);
2239           Handle(StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol) GTComplex =
2240             new StepDimTol_GeoTolAndGeoTolWthDatRefAndModGeoTolAndPosTol;
2241           GTComplex->Init(aName,aDescription,LMWU,SA,GTWDR,MGT);
2242           Model->AddWithRefs(GTComplex);
2243         }
2244         else if(kind==24) {
2245           Handle(StepDimTol_AngularityTolerance) aToler =
2246             new StepDimTol_AngularityTolerance;
2247           aToler->Init(aName,aDescription,LMWU,SA,HADR);
2248           Model->AddWithRefs(aToler);
2249         }
2250         else if(kind==25) {
2251           Handle(StepDimTol_CircularRunoutTolerance) aToler =
2252             new StepDimTol_CircularRunoutTolerance;
2253           aToler->Init(aName,aDescription,LMWU,SA,HADR);
2254           Model->AddWithRefs(aToler);
2255         }
2256         else if(kind==26) {
2257           Handle(StepDimTol_CoaxialityTolerance) aToler =
2258             new StepDimTol_CoaxialityTolerance;
2259           aToler->Init(aName,aDescription,LMWU,SA,HADR);
2260           Model->AddWithRefs(aToler);
2261         }
2262         else if(kind==27) {
2263           Handle(StepDimTol_ConcentricityTolerance) aToler =
2264             new StepDimTol_ConcentricityTolerance;
2265           aToler->Init(aName,aDescription,LMWU,SA,HADR);
2266           Model->AddWithRefs(aToler);
2267         }
2268         else if(kind==28) {
2269           Handle(StepDimTol_ParallelismTolerance) aToler =
2270             new StepDimTol_ParallelismTolerance;
2271           aToler->Init(aName,aDescription,LMWU,SA,HADR);
2272           Model->AddWithRefs(aToler);
2273         }
2274         else if(kind==29) {
2275           Handle(StepDimTol_PerpendicularityTolerance) aToler =
2276             new StepDimTol_PerpendicularityTolerance;
2277           aToler->Init(aName,aDescription,LMWU,SA,HADR);
2278           Model->AddWithRefs(aToler);
2279         }
2280         else if(kind==30) {
2281           Handle(StepDimTol_SymmetryTolerance) aToler =
2282             new StepDimTol_SymmetryTolerance;
2283           aToler->Init(aName,aDescription,LMWU,SA,HADR);
2284           Model->AddWithRefs(aToler);
2285         }
2286         else if(kind==31) {
2287           Handle(StepDimTol_TotalRunoutTolerance) aToler =
2288             new StepDimTol_TotalRunoutTolerance;
2289           aToler->Init(aName,aDescription,LMWU,SA,HADR);
2290           Model->AddWithRefs(aToler);
2291         }
2292       }
2293     }
2294   }
2295
2296   return Standard_True;
2297 }
2298
2299
2300 //=======================================================================
2301 //function : FindPDSforRI
2302 //purpose  : auxilary: 
2303 //=======================================================================
2304 static Standard_Boolean FindPDSforRI(const Interface_Graph &aGraph,
2305                                      const Handle(Standard_Transient) &ent,
2306                                      Handle(StepRepr_ProductDefinitionShape) &PDS,
2307                                      Handle(StepRepr_RepresentationContext) &RC)
2308 {
2309   if(!ent->IsKind(STANDARD_TYPE(StepRepr_RepresentationItem))) return Standard_False;
2310   Interface_EntityIterator subs = aGraph.Sharings(ent);
2311   for(subs.Start(); subs.More() && PDS.IsNull(); subs.Next()) {
2312     Handle(StepShape_ShapeRepresentation) SR = 
2313       Handle(StepShape_ShapeRepresentation)::DownCast(subs.Value());
2314     if(SR.IsNull()) continue;
2315     RC = SR->ContextOfItems();
2316     Interface_EntityIterator subs1 = aGraph.Sharings(SR);
2317     for(subs1.Start(); subs1.More() && PDS.IsNull(); subs1.Next()) {
2318       Handle(StepShape_ShapeDefinitionRepresentation) SDR = 
2319         Handle(StepShape_ShapeDefinitionRepresentation)::DownCast(subs1.Value());
2320       if(SDR.IsNull()) continue;
2321       Handle(StepRepr_PropertyDefinition) PropD = SDR->Definition().PropertyDefinition();
2322       if(PropD.IsNull()) continue;
2323       PDS = Handle(StepRepr_ProductDefinitionShape)::DownCast(PropD);
2324     }
2325   }
2326   return Standard_True;
2327 }
2328
2329
2330 //=======================================================================
2331 //function : WriteMaterials
2332 //purpose  : 
2333 //=======================================================================
2334
2335 Standard_Boolean STEPCAFControl_Writer::WriteMaterials (const Handle(XSControl_WorkSession) &WS,
2336                                                         const TDF_LabelSequence  &labels ) const
2337 {
2338   
2339   if ( labels.Length() <=0 ) return Standard_False;
2340
2341   // get working data
2342   Handle(Interface_InterfaceModel) Model = WS->Model();
2343   Handle(XSControl_TransferWriter) TW = WS->TransferWriter();
2344   Handle(Transfer_FinderProcess) FP = TW->FinderProcess();
2345   Interface_Graph aGraph = WS->HGraph()->Graph();
2346   Handle(XCAFDoc_ShapeTool) ShTool = XCAFDoc_DocumentTool::ShapeTool( labels(1) );
2347   if(ShTool.IsNull() ) return Standard_False;
2348   Handle(XCAFDoc_MaterialTool) MatTool = XCAFDoc_DocumentTool::MaterialTool( labels(1) );
2349   if(MatTool.IsNull() ) return Standard_False;
2350
2351   STEPConstruct_DataMapOfAsciiStringTransient MapDRI,MapMRI;
2352   TDF_LabelSequence TopLabels;
2353   ShTool->GetShapes(TopLabels);
2354   for(Standard_Integer i=1; i<=TopLabels.Length(); i++) {
2355     TDF_Label ShL = TopLabels.Value(i);
2356     Handle(TDataStd_TreeNode) Node;
2357     if( ShL.FindAttribute(XCAFDoc::MaterialRefGUID(),Node) && Node->HasFather() ) {
2358       // find PDS for current shape
2359       TopoDS_Shape aShape = XCAFDoc_ShapeTool::GetShape(ShL);
2360       TopLoc_Location Loc;
2361       TColStd_SequenceOfTransient seqRI;
2362       FindEntities( FP, aShape, Loc, seqRI );
2363       if(seqRI.Length()<=0) continue;
2364       Handle(StepRepr_ProductDefinitionShape) PDS;
2365       Handle(StepRepr_RepresentationContext) RC;
2366       Handle(Standard_Transient) ent = seqRI.Value(1);
2367       FindPDSforRI(aGraph,ent,PDS,RC);
2368       if(PDS.IsNull()) continue;
2369       Handle(StepBasic_ProductDefinition) aProdDef = 
2370         PDS->Definition().ProductDefinition();
2371       if(aProdDef.IsNull())
2372         continue;
2373       // write material entities
2374       TDF_Label MatL = Node->Father()->Label();
2375       Handle(TCollection_HAsciiString) aName;
2376       Handle(TCollection_HAsciiString) aDescription;
2377       Standard_Real aDensity;
2378       Handle(TCollection_HAsciiString) aDensName;
2379       Handle(TCollection_HAsciiString) aDensValType;
2380       Handle(StepRepr_Representation) RepDRI = new StepRepr_Representation;
2381       Handle(StepRepr_Representation) RepMRI = new StepRepr_Representation;
2382       if(MatTool->GetMaterial(MatL,aName,aDescription,aDensity,aDensName,aDensValType)) {
2383         if(aName->Length()==0) continue;
2384         TCollection_AsciiString aKey(aName->ToCString());
2385         if(MapDRI.IsBound(aKey)) {
2386           RepDRI = Handle(StepRepr_Representation)::DownCast(MapDRI.Find(aKey));
2387           if(MapMRI.IsBound(aKey)) {
2388             RepMRI = Handle(StepRepr_Representation)::DownCast(MapMRI.Find(aKey));
2389           }
2390         }
2391         else {
2392           // write DRI
2393           Handle(StepRepr_DescriptiveRepresentationItem) DRI = new StepRepr_DescriptiveRepresentationItem;
2394           DRI->Init(aName,aDescription);
2395           Handle(StepRepr_HArray1OfRepresentationItem) HARI = new StepRepr_HArray1OfRepresentationItem(1,1);
2396           HARI->SetValue(1,DRI);
2397           RepDRI->Init(new TCollection_HAsciiString("material name"),HARI,RC);
2398           Model->AddWithRefs(RepDRI);
2399           // write MRI
2400           if(aDensity>0) {
2401             // mass
2402             Handle(StepBasic_SiUnitAndMassUnit) SMU = new StepBasic_SiUnitAndMassUnit;
2403             SMU->SetName(StepBasic_sunGram);
2404             Handle(StepBasic_DerivedUnitElement) DUE1 = new StepBasic_DerivedUnitElement;
2405             DUE1->Init(SMU,3.0);
2406             // length
2407             Handle(StepBasic_SiUnitAndLengthUnit) SLU = new StepBasic_SiUnitAndLengthUnit;
2408             SLU->Init(Standard_True,StepBasic_spCenti,StepBasic_sunMetre);
2409             Handle(StepBasic_DerivedUnitElement) DUE2 = new StepBasic_DerivedUnitElement;
2410             DUE2->Init(SLU,2.0);
2411             // other
2412             Handle(StepBasic_HArray1OfDerivedUnitElement) HADUE = new StepBasic_HArray1OfDerivedUnitElement(1,2);
2413             HADUE->SetValue(1,DUE1);
2414             HADUE->SetValue(2,DUE2);
2415             Handle(StepBasic_DerivedUnit) DU = new StepBasic_DerivedUnit;
2416             DU->Init(HADUE);
2417             Model->AddWithRefs(DU);
2418             StepBasic_Unit aUnit;
2419             aUnit.SetValue(DU);
2420             Handle(StepBasic_MeasureValueMember) MVM = new StepBasic_MeasureValueMember;
2421             MVM->SetName(aDensValType->ToCString());
2422             MVM->SetReal(aDensity);
2423             Handle(StepRepr_MeasureRepresentationItem) MRI = new StepRepr_MeasureRepresentationItem;
2424             MRI->Init(aDensName,MVM,aUnit);
2425             HARI = new StepRepr_HArray1OfRepresentationItem(1,1);
2426             HARI->SetValue(1,MRI);
2427             RepMRI->Init(new TCollection_HAsciiString("density"),HARI,RC);
2428             Model->AddWithRefs(RepMRI);
2429           }
2430           //WriteNewMaterial(Model,aName,aDescription,aDensity,aDensName,aDensValType,RC,RepDRI,RepMRI);
2431           MapDRI.Bind(aKey,RepDRI);
2432           if(!RepMRI.IsNull()) MapMRI.Bind(aKey,RepMRI);
2433         }
2434       }
2435       // write chain PDS---(DRI,MRI)
2436       StepRepr_CharacterizedDefinition CD1;
2437       CD1.SetValue(aProdDef);
2438       Handle(StepRepr_PropertyDefinition) PropD1 = new StepRepr_PropertyDefinition;
2439       PropD1->Init(new TCollection_HAsciiString("material property"),Standard_True,
2440                    new TCollection_HAsciiString("material name"),CD1);
2441       Model->AddWithRefs(PropD1);
2442       StepRepr_RepresentedDefinition RD1;
2443       RD1.SetValue(PropD1);
2444       Handle(StepRepr_PropertyDefinitionRepresentation) PDR1 =
2445         new StepRepr_PropertyDefinitionRepresentation;
2446       PDR1->Init(RD1,RepDRI);
2447       Model->AddWithRefs(PDR1);
2448       StepRepr_CharacterizedDefinition CD2;
2449       CD2.SetValue(aProdDef);
2450       Handle(StepRepr_PropertyDefinition) PropD2 = new StepRepr_PropertyDefinition;
2451       PropD2->Init(new TCollection_HAsciiString("material property"),Standard_True,
2452                    new TCollection_HAsciiString("density"),CD2);
2453       Model->AddWithRefs(PropD2);
2454       StepRepr_RepresentedDefinition RD2;
2455       RD2.SetValue(PropD2);
2456       Handle(StepRepr_PropertyDefinitionRepresentation) PDR2 =
2457         new StepRepr_PropertyDefinitionRepresentation;
2458       PDR2->Init(RD2,RepMRI);
2459       Model->AddWithRefs(PDR2);
2460     }
2461   }
2462
2463   return Standard_True;
2464 }
2465
2466
2467 //=======================================================================
2468 //function : SetColorMode
2469 //purpose  : 
2470 //=======================================================================
2471
2472 void STEPCAFControl_Writer::SetColorMode (const Standard_Boolean colormode)
2473 {
2474   myColorMode = colormode;
2475 }
2476
2477
2478 //=======================================================================
2479 //function : GetColorMode
2480 //purpose  : 
2481 //=======================================================================
2482
2483 Standard_Boolean STEPCAFControl_Writer::GetColorMode () const
2484 {
2485   return myColorMode;
2486 }
2487
2488
2489 //=======================================================================
2490 //function : SetNameMode
2491 //purpose  : 
2492 //=======================================================================
2493
2494 void STEPCAFControl_Writer::SetNameMode (const Standard_Boolean namemode)
2495 {
2496   myNameMode = namemode;
2497 }
2498
2499
2500 //=======================================================================
2501 //function : GetNameMode
2502 //purpose  : 
2503 //=======================================================================
2504
2505 Standard_Boolean STEPCAFControl_Writer::GetNameMode () const
2506 {
2507   return myNameMode;
2508 }
2509
2510
2511 //=======================================================================
2512 //function : SetLayerMode
2513 //purpose  : 
2514 //=======================================================================
2515
2516 void STEPCAFControl_Writer::SetLayerMode (const Standard_Boolean layermode)
2517 {
2518   myLayerMode = layermode;
2519 }
2520
2521
2522 //=======================================================================
2523 //function : GetLayerMode
2524 //purpose  : 
2525 //=======================================================================
2526
2527 Standard_Boolean STEPCAFControl_Writer::GetLayerMode () const
2528 {
2529   return myLayerMode;
2530 }
2531
2532
2533 //=======================================================================
2534 //function : SetPropsMode
2535 //purpose  : 
2536 //=======================================================================
2537
2538 void STEPCAFControl_Writer::SetPropsMode (const Standard_Boolean propsmode)
2539 {
2540   myPropsMode = propsmode;
2541 }
2542
2543
2544 //=======================================================================
2545 //function : GetPropsMode
2546 //purpose  : 
2547 //=======================================================================
2548
2549 Standard_Boolean STEPCAFControl_Writer::GetPropsMode () const
2550 {
2551   return myPropsMode;
2552 }
2553
2554
2555 //=======================================================================
2556 //function : SetSHUOMode
2557 //purpose  : 
2558 //=======================================================================
2559
2560 void STEPCAFControl_Writer::SetSHUOMode (const Standard_Boolean mode)
2561 {
2562   mySHUOMode = mode;
2563 }
2564
2565
2566 //=======================================================================
2567 //function : GetSHUOMode
2568 //purpose  : 
2569 //=======================================================================
2570
2571 Standard_Boolean STEPCAFControl_Writer::GetSHUOMode () const
2572 {
2573   return mySHUOMode;
2574 }
2575
2576
2577 //=======================================================================
2578 //function : SetDimTolMode
2579 //purpose  : 
2580 //=======================================================================
2581
2582 void STEPCAFControl_Writer::SetDimTolMode(const Standard_Boolean dimtolmode)
2583 {
2584   myDGTMode = dimtolmode;
2585 }
2586
2587
2588 //=======================================================================
2589 //function : GetDimTolMode
2590 //purpose  : 
2591 //=======================================================================
2592
2593 Standard_Boolean STEPCAFControl_Writer::GetDimTolMode() const
2594 {
2595   return myDGTMode;
2596 }
2597
2598
2599 //=======================================================================
2600 //function : SetMaterialMode
2601 //purpose  : 
2602 //=======================================================================
2603
2604 void STEPCAFControl_Writer::SetMaterialMode(const Standard_Boolean matmode)
2605 {
2606   myMatMode = matmode;
2607 }
2608
2609
2610 //=======================================================================
2611 //function : GetMaterialMode
2612 //purpose  : 
2613 //=======================================================================
2614
2615 Standard_Boolean STEPCAFControl_Writer::GetMaterialMode() const
2616 {
2617   return myMatMode;
2618 }