1 // ImportExport.cpp: implementation of the CImportExport class.
2 //
3 //////////////////////////////////////////////////////////////////////
4 
5 #include "stdafx.h"
6 #include "ImportExport.h"
7 #include <OCC_App.h>
8 
9 #include "SaveSTEPDlg.h"
10 
11 #include "TColStd_SequenceOfAsciiString.hxx"
12 #include "TColStd_SequenceOfExtendedString.hxx"
13 #include "OSD_Timer.hxx"
14 
15 #include "IGESControl_Reader.hxx"
16 #include "STEPControl_Controller.hxx"
17 
18 #include <BRepAlgo.hxx>
19 #include <IGESControl_Controller.hxx>
20 #include <IGESControl_Writer.hxx>
21 #include <Interface_Static.hxx>
22 #include <STEPControl_Reader.hxx>
23 #include <Geom_Curve.hxx>
24 #include <STEPControl_Writer.hxx>
25 #include <TopoDS_Compound.hxx>
26 #include <Geom_Line.hxx>
27 #include <StlAPI_Writer.hxx>
28 #include <VrmlAPI_Writer.hxx>
29 #include <VrmlData_Scene.hxx>
30 #include <VrmlData_ShapeConvert.hxx>
31 #include <VrmlData_Appearance.hxx>
32 #include <VrmlData_Material.hxx>
33 #include <VrmlData_Group.hxx>
34 #include <VrmlData_ListOfNode.hxx>
35 #include <VrmlData_ShapeNode.hxx>
36 
37 #include <XSControl_WorkSession.hxx>
38 #include <XSControl_TransferReader.hxx>
39 #include <STEPConstruct_Styles.hxx>
40 #include <TColStd_HSequenceOfTransient.hxx>
41 #include <STEPConstruct.hxx>
42 #include <StepVisual_StyledItem.hxx>
43 
44 #ifdef _DEBUG
45 #undef THIS_FILE
46 static char THIS_FILE[]=__FILE__;
47 //#define new DEBUG_NEW
48 #endif
49 
50 //////////////////////////////////////////////////////////////////////
51 // Construction/Destruction
52 //////////////////////////////////////////////////////////////////////
53 
Handle(TopTools_HSequenceOfShape)54 Handle(TopTools_HSequenceOfShape) CImportExport::BuildSequenceFromContext(const Handle(AIS_InteractiveContext)& anInteractiveContext,
55                                                                           Handle(Quantity_HArray1OfColor)&      anArrayOfColors,
56                                                                           Handle(TColStd_HArray1OfReal)&        anArrayOfTransparencies)
57 {
58     Handle(TopTools_HSequenceOfShape) aSequence;
59     Standard_Integer nb = anInteractiveContext->NbSelected(), i = 1;
60     if (!nb)
61         return aSequence;
62 
63     aSequence               = new TopTools_HSequenceOfShape();
64     anArrayOfColors         = new Quantity_HArray1OfColor(1, nb);
65     anArrayOfTransparencies = new TColStd_HArray1OfReal  (1, nb);
66 
67     Handle(AIS_InteractiveObject) picked;
68     for (anInteractiveContext->InitSelected(); anInteractiveContext->MoreSelected(); anInteractiveContext->NextSelected())
69       {
70         picked = anInteractiveContext->SelectedInteractive();
71         if (picked->IsKind (STANDARD_TYPE (AIS_Shape)))
72 	     {
73             Handle(AIS_Shape) aisShape = Handle(AIS_Shape)::DownCast(picked);
74 	        TopoDS_Shape aShape = aisShape->Shape();
75             aSequence->Append(aShape);
76 
77             Quantity_Color color;
78             aisShape->Color(color);
79             anArrayOfColors->SetValue(i, color);
80 
81             Standard_Real transparency = aisShape->Transparency();
82             anArrayOfTransparencies->SetValue(i, transparency);
83 
84             i++;
85 	     }
86       }
87       return aSequence;
88 }
89 
90 //======================================================================
91 //=                                                                    =
92 //=                      BREP                                          =
93 //=                                                                    =
94 //======================================================================
95 
ReadBREP(const Handle (AIS_InteractiveContext)& anInteractiveContext)96 int CImportExport::ReadBREP (const Handle(AIS_InteractiveContext)& anInteractiveContext)
97 {
98     Handle(TopTools_HSequenceOfShape) aSequence = CImportExport::ReadBREP();
99 	if(aSequence->IsEmpty())
100 		return 1;
101 	Handle(AIS_Shape) aShape;
102     for(int i=1;i<= aSequence->Length();i++){
103 		aShape = new AIS_Shape(aSequence->Value(i));
104 		anInteractiveContext->SetDisplayMode(aShape, 1, Standard_False);
105 		anInteractiveContext->Display(aShape, Standard_False);
106 		const Handle(AIS_InteractiveObject)& aPrs = aShape; // A small trick to avoid compiler error (C2668).
107 		anInteractiveContext->SetSelected (aPrs, Standard_False);
108 	}
109 	return 0;
110 }
111 
Handle(TopTools_HSequenceOfShape)112 Handle(TopTools_HSequenceOfShape) CImportExport::ReadBREP()
113 {
114   CFileDialog dlg(TRUE,
115 		  NULL,
116 		  NULL,
117 		  OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
118 		  L"BREP Files (*.brep , *.rle)|*.brep;  *.BREP; *.rle; *.RLE; |All Files (*.*)|*.*||",
119 		  NULL );
120 
121   CString SHAREPATHValue;
122   SHAREPATHValue.GetEnvironmentVariable (L"CSF_OCCTDataPath");
123   CString initdir = (SHAREPATHValue + "\\occ");
124 
125   dlg.m_ofn.lpstrInitialDir = initdir;
126 
127   Handle(TopTools_HSequenceOfShape) aSequence= new TopTools_HSequenceOfShape();
128 
129   if (dlg.DoModal() == IDOK)
130   {
131     SetCursor(AfxGetApp()->LoadStandardCursor(IDC_WAIT));
132     CString filename = dlg.GetPathName();
133     TopoDS_Shape aShape;
134     Standard_Boolean result = ReadBREP (filename, aShape);
135     if (result)
136     {
137       if (!BRepAlgo::IsValid(aShape))
138         MessageBoxW (AfxGetMainWnd()->m_hWnd, L"Warning: The shape is not valid!", L"Cascade Warning", MB_ICONWARNING);
139 
140       aSequence->Append(aShape);
141     }
142     else
143       MessageBoxW (AfxGetMainWnd()->m_hWnd, L"Error: The file was not read", L"Cascade Error", MB_ICONERROR);
144 
145     SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));
146   }
147 
148   return aSequence;
149 }
150 //----------------------------------------------------------------------
151 
ReadBREP(CString aFileName,TopoDS_Shape & aShape)152 Standard_Boolean CImportExport::ReadBREP(CString      aFileName,
153                                         TopoDS_Shape& aShape)
154 {
155   aShape.Nullify();
156 
157   std::filebuf aFileBuf;
158   std::istream aStream (&aFileBuf);
159   if (!aFileBuf.open (aFileName, std::ios::in))
160   {
161     return Standard_False;
162   }
163 
164   BRep_Builder aBuilder;
165   BRepTools::Read (aShape, aStream, aBuilder);
166   return !aShape.IsNull();
167 }
168 
SaveBREP(const Handle (AIS_InteractiveContext)& anInteractiveContext)169 void CImportExport::SaveBREP(const Handle(AIS_InteractiveContext)& anInteractiveContext)
170 {
171 	anInteractiveContext->InitSelected();
172 	if (anInteractiveContext->NbSelected() == 0){
173 		AfxMessageBox (L"No shape selected for export!");
174 		return;
175 	}
176 	Handle(TopTools_HSequenceOfShape) aHSequenceOfShape;
177     Handle(Quantity_HArray1OfColor)   anArrayOfColors;
178     Handle(TColStd_HArray1OfReal)     anArrayOfTransparencies;
179 	aHSequenceOfShape = BuildSequenceFromContext(anInteractiveContext, anArrayOfColors, anArrayOfTransparencies);
180 	int aLength = aHSequenceOfShape->Length();
181 	if (aLength == 1){
182 		TopoDS_Shape RES = aHSequenceOfShape->Value(1);
183 		CImportExport::SaveBREP(RES);
184 	} else {
185 		TopoDS_Compound RES;
186 		BRep_Builder MKCP;
187 		MKCP.MakeCompound(RES);
188 		for (Standard_Integer i=1;i<=aLength;i++)
189 		{
190 			TopoDS_Shape aShape= aHSequenceOfShape->Value(i);
191 			if ( aShape.IsNull() )
192 			{
193 				continue;
194 			}
195 			MKCP.Add(RES, aShape);
196 		}
197 		CImportExport::SaveBREP(RES);
198 	}
199 }
200 
SaveBREP(const TopoDS_Shape & aShape)201 Standard_Boolean CImportExport::SaveBREP(const TopoDS_Shape& aShape)
202 {
203   CFileDialog dlg (FALSE, L"*.brep",NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
204                    L"BREP Files (*.brep)|*.brep;|BREP Files (*.BREP)|*.BREP;||", NULL);
205 
206 CString SHAREPATHValue;
207 SHAREPATHValue.GetEnvironmentVariable (L"CSF_OCCTDataPath");
208 CString initdir = (SHAREPATHValue + "\\occ");
209 
210 dlg.m_ofn.lpstrInitialDir = initdir;
211 
212   Standard_Boolean result = Standard_False;
213   if (dlg.DoModal() == IDOK)
214   {
215     SetCursor(AfxGetApp()->LoadStandardCursor(IDC_WAIT));
216     CString filename = dlg.GetPathName();
217     result = SaveBREP (filename, aShape);
218     if (!result)
219        MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd,
220                     L"Error : The shape or shapes were not saved.",
221                     L"CasCade Error", MB_ICONERROR);
222     SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));
223   }
224   return result;
225 }
226 
227 //----------------------------------------------------------------------------------------
SaveBREP(CString aFileName,const TopoDS_Shape & aShape)228 Standard_Boolean CImportExport::SaveBREP (CString             aFileName,
229                                           const TopoDS_Shape& aShape)
230 {
231   std::filebuf aFileBuf;
232   std::ostream aStream (&aFileBuf);
233   if (!aFileBuf.open (aFileName, std::ios::out))
234   {
235     return Standard_False;
236   }
237 
238   BRepTools::Write (aShape, aStream);
239   return Standard_True;
240 }
241 
242 //======================================================================
243 //=                                                                    =
244 //=                      IGES                                          =
245 //=                                                                    =
246 //======================================================================
247 
248 
249 
ReadIGES(const Handle (AIS_InteractiveContext)& anInteractiveContext)250 void CImportExport::ReadIGES(const Handle(AIS_InteractiveContext)& anInteractiveContext)
251 {
252     Handle(TopTools_HSequenceOfShape) aSequence = CImportExport::ReadIGES();
253     for(int i=1;i<= aSequence->Length();i++)
254         anInteractiveContext->Display (new AIS_Shape (aSequence->Value (i)), Standard_False);
255     anInteractiveContext->UpdateCurrentViewer();
256 }
257 
Handle(TopTools_HSequenceOfShape)258 Handle(TopTools_HSequenceOfShape) CImportExport::ReadIGES()// not by reference --> the sequence is created here !!
259 {
260   CFileDialog dlg(TRUE,
261                   NULL,
262                   NULL,
263                   OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
264                   L"IGES Files (*.iges , *.igs)|*.iges; *.igs|All Files (*.*)|*.*||",
265                   NULL );
266 
267 CString SHAREPATHValue;
268 SHAREPATHValue.GetEnvironmentVariable (L"CSF_OCCTDataPath");
269 CString initdir = (SHAREPATHValue + "\\iges");
270 
271 dlg.m_ofn.lpstrInitialDir = initdir;
272 
273   Handle(TopTools_HSequenceOfShape) aSequence = new TopTools_HSequenceOfShape();
274   if (dlg.DoModal() == IDOK)
275   {
276     SetCursor(AfxGetApp()->LoadStandardCursor(IDC_WAIT));
277     TCollection_AsciiString aFileName ((const wchar_t* )dlg.GetPathName());
278     Standard_Integer status = ReadIGES (aFileName.ToCString(), aSequence);
279     if (status != IFSelect_RetDone)
280     {
281       MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"Error : The file is not read", L"CasCade Error", MB_ICONERROR);
282     }
283 
284 	SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));
285    }
286   return aSequence;
287 }
288 //----------------------------------------------------------------------
289 
ReadIGES(const Standard_CString & aFileName,Handle (TopTools_HSequenceOfShape)& aHSequenceOfShape)290 Standard_Integer CImportExport::ReadIGES(const Standard_CString& aFileName,
291                                          Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape)
292 {
293 
294     IGESControl_Reader Reader;
295 
296     Standard_Integer status = Reader.ReadFile(aFileName);
297 
298     if (status != IFSelect_RetDone) return status;
299     Reader.TransferRoots();
300     TopoDS_Shape aShape = Reader.OneShape();
301 	aHSequenceOfShape->Append(aShape);
302 
303     return status;
304 }
305 //----------------------------------------------------------------------
306 
SaveIGES(const Handle (AIS_InteractiveContext)& anInteractiveContext)307 void CImportExport::SaveIGES(const Handle(AIS_InteractiveContext)& anInteractiveContext)
308 {
309 	anInteractiveContext->InitSelected();
310 	if (anInteractiveContext->NbSelected() == 0){
311 		AfxMessageBox (L"No shape selected for export!");
312 		return;
313 	}
314     Handle(Quantity_HArray1OfColor)   anArrayOfColors;
315     Handle(TColStd_HArray1OfReal)     anArrayOfTransparencies;
316     CImportExport::SaveIGES(BuildSequenceFromContext(anInteractiveContext, anArrayOfColors, anArrayOfTransparencies));
317 }
318 
SaveIGES(const Handle (TopTools_HSequenceOfShape)& aHSequenceOfShape)319 Standard_Boolean CImportExport::SaveIGES(const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape)
320 {
321     if (aHSequenceOfShape->Length() == 0)
322     {
323         MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"No Shape in the HSequence!!", L"CasCade Warning", MB_ICONWARNING);
324         return Standard_False;
325     }
326 
327   CFileDialog dlg(FALSE, L"*.iges",NULL,OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
328                   L"IGES Files (*.iges )|*.iges;|IGES Files (*.igs )| *.igs;||", NULL);
329 
330 CString SHAREPATHValue;
331 SHAREPATHValue.GetEnvironmentVariable (L"CSF_OCCTDataPath");
332 CString initdir = (SHAREPATHValue + "\\iges");
333 
334 dlg.m_ofn.lpstrInitialDir = initdir;
335 
336   Standard_Boolean result=Standard_False;
337   if (dlg.DoModal() == IDOK)
338   {
339     SetCursor(AfxGetApp()->LoadStandardCursor(IDC_WAIT));
340 
341     TCollection_AsciiString aFileName ((const wchar_t* )dlg.GetPathName());
342 
343     result = SaveIGES (aFileName.ToCString(), aHSequenceOfShape);
344     SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));
345    }
346     return result;
347 }
348 //----------------------------------------------------------------------
349 
SaveIGES(const Standard_CString & aFileName,const Handle (TopTools_HSequenceOfShape)& aHSequenceOfShape)350 Standard_Boolean CImportExport::SaveIGES(const Standard_CString& aFileName,
351                                          const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape)
352 {
353 
354     IGESControl_Controller::Init();
355 	IGESControl_Writer ICW (Interface_Static::CVal("XSTEP.iges.unit"),
356                Interface_Static::IVal("XSTEP.iges.writebrep.mode"));
357 
358 	for (Standard_Integer i=1;i<=aHSequenceOfShape->Length();i++)
359 		ICW.AddShape (aHSequenceOfShape->Value(i));
360 
361 	ICW.ComputeModel();
362 	Standard_Boolean result = ICW.Write(aFileName );
363     return result;
364 }
365 
366 //======================================================================
367 
368 //======================================================================
369 //=                                                                    =
370 //=                      STEP                                          =
371 //=                                                                    =
372 //======================================================================
373 
ReadSTEP(const Handle (AIS_InteractiveContext)& anInteractiveContext)374 void CImportExport::ReadSTEP(const Handle(AIS_InteractiveContext)& anInteractiveContext)
375 {
376     Handle(TopTools_HSequenceOfShape) aSequence = CImportExport::ReadSTEP();
377 		if (!aSequence.IsNull()) {
378 			for(int i=1;i<= aSequence->Length();i++)
379         anInteractiveContext->Display(new AIS_Shape(aSequence->Value(i)), Standard_False);
380 		}
381 }
382 
Handle(TopTools_HSequenceOfShape)383 Handle(TopTools_HSequenceOfShape) CImportExport::ReadSTEP()// not by reference --> the sequence is created here !!
384 {
385   CFileDialog dlg(TRUE,
386                   NULL,
387                   NULL,
388                   OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
389                   L"STEP Files (*.stp;*.step)|*.stp; *.step|All Files (*.*)|*.*||",
390                   NULL );
391 
392 CString SHAREPATHValue;
393 SHAREPATHValue.GetEnvironmentVariable (L"CSF_OCCTDataPath");
394 CString initdir = (SHAREPATHValue + "\\step");
395 
396 dlg.m_ofn.lpstrInitialDir = initdir;
397 
398   Handle(TopTools_HSequenceOfShape) aSequence= new TopTools_HSequenceOfShape();
399   if (dlg.DoModal() == IDOK)
400   {
401     SetCursor(AfxGetApp()->LoadStandardCursor(IDC_WAIT));
402     TCollection_AsciiString aFileName ((const wchar_t* )dlg.GetPathName());
403 	IFSelect_ReturnStatus ReturnStatus = ReadSTEP (aFileName.ToCString(), aSequence);
404     switch (ReturnStatus)
405     {
406        case IFSelect_RetError :
407            MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"Not a valid Step file", L"ERROR", MB_ICONWARNING);
408        break;
409        case IFSelect_RetFail :
410            MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"Reading has failed", L"ERROR", MB_ICONWARNING);
411        break;
412        case IFSelect_RetVoid :
413             MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"Nothing to transfer", L"ERROR", MB_ICONWARNING);
414        break;
415     }
416     SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));
417   }
418   return aSequence;
419 }
420 
ReadSTEP(const Standard_CString & aFileName,Handle (TopTools_HSequenceOfShape)& aHSequenceOfShape)421 IFSelect_ReturnStatus CImportExport::ReadSTEP(const Standard_CString& aFileName,
422                                               Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape)
423 {
424   aHSequenceOfShape->Clear();
425 
426   // create additional log file
427   STEPControl_Reader aReader;
428   IFSelect_ReturnStatus status = aReader.ReadFile(aFileName);
429   if (status != IFSelect_RetDone)
430     return status;
431 
432   aReader.WS()->TransferReader()->TransientProcess()->SetTraceLevel(2); // increase default trace level
433 
434   Standard_Boolean failsonly = Standard_False;
435   aReader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity);
436 
437   // Root transfers
438   Standard_Integer nbr = aReader.NbRootsForTransfer();
439   aReader.PrintCheckTransfer (failsonly, IFSelect_ItemsByEntity);
440   for ( Standard_Integer n = 1; n<=nbr; n++) {
441     /*Standard_Boolean ok =*/ aReader.TransferRoot(n);
442   }
443 
444   // Collecting resulting entities
445   Standard_Integer nbs = aReader.NbShapes();
446   if (nbs == 0) {
447     return IFSelect_RetVoid;
448   }
449   for (Standard_Integer i=1; i<=nbs; i++) {
450     aHSequenceOfShape->Append(aReader.Shape(i));
451   }
452 
453   return status;
454 }
455 
456 
457 //----------------------------------------------------------------------
SaveSTEP(const Handle (AIS_InteractiveContext)& anInteractiveContext)458 void CImportExport::SaveSTEP(const Handle(AIS_InteractiveContext)& anInteractiveContext)
459 {
460 	anInteractiveContext->InitSelected();
461 	if (anInteractiveContext->NbSelected() == 0){
462 		AfxMessageBox (L"No shape selected for export!");
463 		return;
464 	}
465     Handle(Quantity_HArray1OfColor)   anArrayOfColors;
466     Handle(TColStd_HArray1OfReal)     anArrayOfTransparencies;
467     CImportExport::SaveSTEP(BuildSequenceFromContext(anInteractiveContext, anArrayOfColors, anArrayOfTransparencies));
468 }
469 
470 // Return True if no error
TestFacetedBrep(const Handle (TopTools_HSequenceOfShape)& aHSequenceOfShape)471 Standard_Boolean TestFacetedBrep(const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape)
472 {
473 	Standard_Boolean OneErrorFound = Standard_False;
474 	for (Standard_Integer i=1;i<=aHSequenceOfShape->Length();i++)
475 	{
476 	  TopoDS_Shape aShape= aHSequenceOfShape->Value(i);
477 
478 	  TopExp_Explorer Ex(aShape,TopAbs_FACE);
479 	  while (Ex.More() && !OneErrorFound)
480 		{
481 		// Get the 	Geom_Surface outside the TopoDS_Face
482 		Handle(Geom_Surface) aSurface = BRep_Tool::Surface(TopoDS::Face(Ex.Current()));
483 		// check if it is a plane.
484 		if (!aSurface->IsKind(STANDARD_TYPE(Geom_Plane)))
485 		    OneErrorFound=Standard_True;
486 		Ex.Next();
487 		}
488 	  TopExp_Explorer Ex2(aShape,TopAbs_EDGE);
489 	  while (Ex2.More() && !OneErrorFound)
490 		{
491 		// Get the 	Geom_Curve outside the TopoDS_Face
492 		Standard_Real FirstDummy,LastDummy;
493 		Handle(Geom_Curve) aCurve = BRep_Tool::Curve(TopoDS::Edge(Ex2.Current()),FirstDummy,LastDummy);
494 		// check if it is a line.
495 		if (!aCurve->IsKind(STANDARD_TYPE(Geom_Line)))
496 		    OneErrorFound=Standard_True;
497 		Ex2.Next();
498 		}
499 	}
500 	return !OneErrorFound;
501 }
502 
SaveSTEP(const Handle (TopTools_HSequenceOfShape)& aHSequenceOfShape)503 IFSelect_ReturnStatus CImportExport::SaveSTEP(const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape)
504 {
505     if (aHSequenceOfShape->Length() == 0)
506       {
507         MessageBox (AfxGetApp()->m_pMainWnd->m_hWnd, L"No Shape in the HSequence!!", L"CasCade Warning", MB_ICONWARNING);
508         return IFSelect_RetError;
509       }
510 
511     IFSelect_ReturnStatus status = IFSelect_RetVoid;
512 
513 	CFileSaveSTEPDialog aDlg(NULL);
514 
515 	aDlg.m_Cc1ModelType = STEPControl_AsIs;
516 
517 	if (aDlg.DoModal() == IDOK) {
518         SetCursor(AfxGetApp()->LoadStandardCursor(IDC_WAIT));
519     TCollection_AsciiString aFileName ((const wchar_t* )aDlg.GetPathName());
520 
521 		STEPControl_StepModelType selection = aDlg.m_Cc1ModelType;
522 
523         if(selection == STEPControl_FacetedBrep)
524 
525     	if (!TestFacetedBrep(aHSequenceOfShape))
526 	    {
527           MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"At least one shape doesn't contain facetes", L"CasCade Warning", MB_ICONWARNING);
528             return IFSelect_RetError;
529 	    }
530 
531 
532         status =  SaveSTEP (aFileName.ToCString(), aHSequenceOfShape, selection);
533         switch (status)
534           {
535             case IFSelect_RetError:
536                 MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"Incorrect Data", L"ERROR", MB_ICONWARNING);
537             break;
538             case IFSelect_RetFail:
539                 MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"Writing has failed", L"ERROR", MB_ICONWARNING);
540             break;
541             case IFSelect_RetVoid:
542                 MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"Nothing to transfer", L"ERROR", MB_ICONWARNING);
543             break;
544           }
545         SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));
546   }
547   return status;
548 }
549 //----------------------------------------------------------------------------------------
SaveSTEP(const Standard_CString & aFileName,const Handle (TopTools_HSequenceOfShape)& aHSequenceOfShape,const STEPControl_StepModelType aValue)550 IFSelect_ReturnStatus CImportExport::SaveSTEP(const Standard_CString& aFileName,
551                                               const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape,
552 
553 const STEPControl_StepModelType aValue /* =TopoDSToCc1Act_ManifoldSolidBrep */ )
554 
555 {
556     // CREATE THE WRITER
557 
558     STEPControl_Writer aWriter;
559 
560 	IFSelect_ReturnStatus status;
561 	for (Standard_Integer i=1;i<=aHSequenceOfShape->Length();i++)
562         {
563 			status =  aWriter.Transfer(aHSequenceOfShape->Value(i), aValue);
564             if ( status != IFSelect_RetDone ) return status;
565         }
566     status = aWriter.Write(aFileName);
567     return status;
568 }
569 
570 
571 
572 //======================================================================
573 //=                                                                    =
574 //=                      STL                                           =
575 //=                                                                    =
576 //======================================================================
577 
SaveSTL(const Handle (AIS_InteractiveContext)& anInteractiveContext)578 void CImportExport::SaveSTL(const Handle(AIS_InteractiveContext)& anInteractiveContext)
579 {
580   anInteractiveContext->InitSelected();
581 	if (anInteractiveContext->NbSelected() == 0){
582 		AfxMessageBox (L"No shape selected for export!");
583 		return;
584 	}
585     Handle(Quantity_HArray1OfColor)   anArrayOfColors;
586     Handle(TColStd_HArray1OfReal)     anArrayOfTransparencies;
587 	CImportExport::SaveSTL(BuildSequenceFromContext(anInteractiveContext, anArrayOfColors, anArrayOfTransparencies));
588 }
589 
SaveSTL(const Handle (TopTools_HSequenceOfShape)& aHSequenceOfShape)590 Standard_Boolean CImportExport::SaveSTL(const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape)
591 {
592   CFileDialog dlg(FALSE, L"*.stl", NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
593 	              L"stl Files (*.stl)|*.stl;|STL Files (*.STL)|*.STL;||", NULL);
594 
595 CString SHAREPATHValue;
596 SHAREPATHValue.GetEnvironmentVariable (L"CSF_OCCTDataPath");
597 CString initdir = (SHAREPATHValue + "\\stl");
598 
599 dlg.m_ofn.lpstrInitialDir = initdir;
600 
601 	Standard_Boolean result = Standard_False;
602 
603 	if (dlg.DoModal() == IDOK) {
604         SetCursor(AfxGetApp()->LoadStandardCursor(IDC_WAIT));
605         TCollection_AsciiString aFileName ((const wchar_t* )dlg.GetPathName());
606         TCollection_AsciiString Message;
607         result = SaveSTL (aFileName.ToCString(), aHSequenceOfShape, Message);
608         CString aMsg (TCollection_ExtendedString (Message).ToWideString());
609         MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, aMsg, result ? L"CasCade" : L"CasCade Error", result ? MB_OK : MB_ICONERROR);
610         SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));
611     }
612   return result;
613 }
614 
SaveSTL(const Standard_CString & aFileName,const Handle (TopTools_HSequenceOfShape)& aHSequenceOfShape,TCollection_AsciiString & ReturnMessage)615 Standard_Boolean CImportExport::SaveSTL(const Standard_CString& aFileName,
616                                           const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape,
617                                           TCollection_AsciiString& ReturnMessage)
618 {
619 	Standard_Boolean ReturnValue = Standard_True;
620     if (aHSequenceOfShape->Length() == 0)
621     {
622         MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"No Shape in the HSequence!!", L"CasCade Warning", MB_ICONWARNING);
623         return Standard_False;
624     }
625 
626     ReturnMessage += "The Object have be saved in the file ";
627     ReturnMessage += aFileName;
628     ReturnMessage += "\n with the names : ";
629 
630 	TopoDS_Compound RES;
631 	BRep_Builder MKCP;
632 	MKCP.MakeCompound(RES);
633 
634 	for (Standard_Integer i=1;i<=aHSequenceOfShape->Length();i++)
635 	{
636 		TopoDS_Shape aShape= aHSequenceOfShape->Value(i);
637 		TCollection_AsciiString anObjectName("anObjectName_");
638 		anObjectName += i;
639 		ReturnMessage += anObjectName;
640 		ReturnMessage += " \n";
641 
642 		if ( aShape.IsNull() )
643 		{
644 			ReturnMessage += " Error : Invalid shape \n";
645 			ReturnValue = Standard_False;
646 			continue;
647 		 }
648 
649 		MKCP.Add(RES, aShape);
650 	}
651 
652 	StlAPI_Writer myStlWriter;
653 	myStlWriter.Write(RES, aFileName);
654 
655     return ReturnValue;
656 }
657 
658 
659 //======================================================================
660 //=                                                                    =
661 //=                      VRML                                          =
662 //=                                                                    =
663 //======================================================================
664 
SaveVRML(const Handle (AIS_InteractiveContext)& anInteractiveContext)665 void CImportExport::SaveVRML(const Handle(AIS_InteractiveContext)& anInteractiveContext)
666 {
667   anInteractiveContext->InitSelected();
668 	if (anInteractiveContext->NbSelected() == 0){
669 		AfxMessageBox (L"No shape selected for export!");
670 		return;
671 	}
672     Handle(Quantity_HArray1OfColor) anArrayOfColors;
673     Handle(TColStd_HArray1OfReal)   anArrayOfTransparencies;
674 	CImportExport::SaveVRML(BuildSequenceFromContext(anInteractiveContext, anArrayOfColors, anArrayOfTransparencies),
675                             anArrayOfColors, anArrayOfTransparencies);
676 }
677 
SaveVRML(const Handle (TopTools_HSequenceOfShape)& aHSequenceOfShape,const Handle (Quantity_HArray1OfColor)& anArrayOfColors,const Handle (TColStd_HArray1OfReal)& anArrayOfTransparencies)678 Standard_Boolean CImportExport::SaveVRML(const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape,
679                                          const Handle(Quantity_HArray1OfColor)&   anArrayOfColors,
680                                          const Handle(TColStd_HArray1OfReal)&     anArrayOfTransparencies)
681 {
682   CFileDialog dlg(FALSE, L"*.vrml", NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
683 	              L"vrml Files (*.vrml)|*.vrml;|vrm Files (*.vrm)|*.vrm;||", NULL);
684 
685 CString SHAREPATHValue;
686 SHAREPATHValue.GetEnvironmentVariable (L"CSF_OCCTDataPath");
687 CString initdir = (SHAREPATHValue + "\\vrml");
688 
689 dlg.m_ofn.lpstrInitialDir = initdir;
690 
691   Standard_Boolean result = Standard_False;
692 
693 	if (dlg.DoModal() == IDOK) {
694         SetCursor(AfxGetApp()->LoadStandardCursor(IDC_WAIT));
695         TCollection_AsciiString aFileName ((const wchar_t* )dlg.GetPathName());
696         TCollection_AsciiString Message;
697         result = SaveVRML (aFileName.ToCString(), aHSequenceOfShape, anArrayOfColors, anArrayOfTransparencies, Message);
698         CString aMsg (TCollection_ExtendedString(Message).ToWideString());
699         MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, aMsg, result ? L"CasCade" : L"CasCade Error", result ? MB_OK : MB_ICONERROR);
700         SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));
701     }
702   return result;
703 }
704 
SaveVRML(const Standard_CString & aFileName,const Handle (TopTools_HSequenceOfShape)& aHSequenceOfShape,const Handle (Quantity_HArray1OfColor)& anArrayOfColors,const Handle (TColStd_HArray1OfReal)& anArrayOfTransparencies,TCollection_AsciiString & ReturnMessage)705 Standard_Boolean CImportExport::SaveVRML(const Standard_CString&                  aFileName,
706                                          const Handle(TopTools_HSequenceOfShape)& aHSequenceOfShape,
707                                          const Handle(Quantity_HArray1OfColor)&   anArrayOfColors,
708                                          const Handle(TColStd_HArray1OfReal)&     anArrayOfTransparencies,
709                                          TCollection_AsciiString&                 ReturnMessage)
710 {
711 	Standard_Boolean ReturnValue = Standard_True;
712     if (aHSequenceOfShape->Length() == 0)
713     {
714         MessageBoxW (AfxGetApp()->m_pMainWnd->m_hWnd, L"No Shape in the HSequence!!", L"CasCade Warning", MB_ICONWARNING);
715         return Standard_False;
716     }
717 
718     ReturnMessage += "The Object has been saved in the file ";
719     ReturnMessage += aFileName;
720     ReturnMessage += "\n with the names : ";
721 
722     // VRML scene.
723     VrmlData_Scene scene;
724     VrmlData_ShapeConvert converter(scene/*, 0.001*/); // from mm to meters
725     Standard_Integer iShape = 1; // Counter of shapes
726 
727     for (int i = 1; i <= aHSequenceOfShape->Length(); i++)
728     {
729         // Shape
730         TopoDS_Shape shape = aHSequenceOfShape->Value(i);
731         if (shape.IsNull())
732         {
733           ReturnMessage += " Error : Invalid shape \n";
734           ReturnValue = Standard_False;
735           continue;
736         }
737 
738         // Color
739         Quantity_Color color; // yellow
740         if (!anArrayOfColors.IsNull())
741             color = anArrayOfColors->Value(i);
742 
743         // Transparency
744         Standard_Real transparency = 0.0;
745         if (!anArrayOfTransparencies.IsNull())
746             transparency = anArrayOfTransparencies->Value(i);
747 
748         // Give a name to the shape.
749         TCollection_AsciiString name("Shape");
750         name += TCollection_AsciiString(iShape++);
751         converter.AddShape(shape, name.ToCString());
752         ReturnMessage += name;
753         ReturnMessage += '\n';
754 
755         // Check presence of faces in the shape.
756         TopExp_Explorer expl(shape, TopAbs_FACE);
757         if (expl.More())
758             converter.Convert(true, false, 0.01); // faces only
759         else
760             converter.Convert(false, true, 0.01); // edges only
761 
762         // Name of the color & transparency.
763         // It will be uniquely saved in VRML file.
764         TCollection_AsciiString cname = Quantity_Color::StringName(color.Name());
765         cname += transparency;
766 
767         // Make the appearance (VRML attribute)
768         Handle(VrmlData_Appearance) appearance = Handle(VrmlData_Appearance)::DownCast(scene.FindNode(cname.ToCString()));
769         if (appearance.IsNull())
770         {
771             // Not found ... create a new one.
772             Handle(VrmlData_Material) material = new VrmlData_Material(scene, cname.ToCString(), 0.2, 0.2, transparency);
773             material->SetDiffuseColor(color);
774             material->SetEmissiveColor(color);
775             material->SetSpecularColor(color);
776             scene.AddNode(material, false);
777             appearance = new VrmlData_Appearance(scene, cname.ToCString());
778             appearance->SetMaterial(material);
779             scene.AddNode(appearance, false);
780         }
781 
782         // Apply the material to the shape of entity.
783         Handle(VrmlData_Group) group = Handle(VrmlData_Group)::DownCast(scene.FindNode(name.ToCString()));
784         if (!group.IsNull())
785         {
786             VrmlData_ListOfNode::Iterator itr = group->NodeIterator();
787             for (; itr.More(); itr.Next())
788             {
789                 Handle(VrmlData_Node) node = itr.Value();
790                 if (node->DynamicType() == STANDARD_TYPE(VrmlData_ShapeNode))
791                 {
792                     Handle(VrmlData_ShapeNode) aShape = Handle(VrmlData_ShapeNode)::DownCast(node);
793                     aShape->SetAppearance(appearance);
794                 }
795                 else if (itr.Value()->DynamicType() == STANDARD_TYPE(VrmlData_Group))
796                 {
797                     Handle(VrmlData_Group) groupc = Handle(VrmlData_Group)::DownCast(itr.Value());
798                     VrmlData_ListOfNode::Iterator itrc = groupc->NodeIterator();
799                     for (; itrc.More(); itrc.Next())
800                     {
801                         Handle(VrmlData_Node) nodec = itrc.Value();
802                         if (nodec->DynamicType() == STANDARD_TYPE(VrmlData_ShapeNode))
803                         {
804                             Handle(VrmlData_ShapeNode) shapec = Handle(VrmlData_ShapeNode)::DownCast(nodec);
805                             shapec->SetAppearance(appearance);
806                         }
807                     } // for of group nodes...
808                 } // if (it is a shape node...
809             } // for of group nodes...
810         } // if (!group.IsNull...
811     } // iterator of shapes
812 
813     // Call VRML writer
814     std::ofstream writer(aFileName);
815     writer<<scene;
816     writer.close();
817 
818     /* Old approach to store shapes in VRML (without color & transparency).
819 	TopoDS_Compound RES;
820 	BRep_Builder MKCP;
821 	MKCP.MakeCompound(RES);
822 
823 	for (Standard_Integer i=1;i<=aHSequenceOfShape->Length();i++)
824 	{
825 		TopoDS_Shape aShape= aHSequenceOfShape->Value(i);
826 		TCollection_AsciiString anObjectName("anObjectName_");
827 		anObjectName += i;
828 		ReturnMessage += anObjectName;
829 		ReturnMessage += " \n";
830 
831 		if ( aShape.IsNull() )
832 		{
833 			ReturnMessage += " Error : Invalid shape \n";
834 			ReturnValue = Standard_False;
835 			continue;
836 		 }
837 
838 		MKCP.Add(RES, aShape);
839 	}
840 
841 	VrmlAPI_Writer myVrmlWriter;
842 	myVrmlWriter.Write(RES, aFileName);
843     */
844 
845     return ReturnValue;
846 }
847 
848 
849 
850 
851