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