62714149ad909c64911440f2c6544004f8e4f2eb
[occt.git] / src / ViewerTest / ViewerTest_ViewerCommands.cxx
1 // File:  ViewerTest_ViewerCommands.cxx
2 // Created: Tue Sep  1 10:28:35 1998
3 // Author:  Robert COUBLANC
4 //    <rob@robox.paris1.matra-dtv.fr>
5
6 // Robert Boehne 30 May 2000 : Dec Osf
7
8 #ifdef HAVE_CONFIG_H
9 # include <config.h>
10 #endif
11
12 #ifdef WNT
13 #include <windows.h>
14 #endif
15
16 #include <Graphic3d_ExportFormat.hxx>
17 #include <ViewerTest.hxx>
18 #include <ViewerTest_EventManager.hxx>
19 #include <Visual3d_View.hxx>
20 #include <Visual3d_ViewManager.hxx>
21 #include <V3d_LayerMgr.hxx>
22 #include <NIS_View.hxx>
23 #include <NIS_Triangulated.hxx>
24 #include <NIS_InteractiveContext.hxx>
25 #include <AIS_InteractiveContext.hxx>
26 #include <Draw_Interpretor.hxx>
27 #include <Draw.hxx>
28 #include <Draw_Appli.hxx>
29 #include <Aspect_PrintAlgo.hxx>
30 #include <Image_PixMap.hxx>
31 #include <TColStd_SequenceOfInteger.hxx>
32
33 #ifdef WNT
34 #undef DrawText
35 #endif
36
37 #include <Visual3d_Layer.hxx>
38
39 #ifndef WNT
40 #include <Graphic3d_GraphicDevice.hxx>
41 #include <Xw_GraphicDevice.hxx>
42 #include <Xw_WindowQuality.hxx>
43 #include <Xw_Window.hxx>
44 #include <X11/Xlib.h> /* contains some dangerous #defines such as Status, True etc. */
45 #include <X11/Xutil.h>
46 #include <tk.h>
47
48 #else
49
50 #include <Graphic3d_WNTGraphicDevice.hxx>
51 #include <WNT_WClass.hxx>
52 #include <WNT_Window.hxx>
53
54 #define _CRT_SECURE_NO_DEPRECATE
55 #pragma warning (disable:4996)
56
57 #endif
58
59 #define OCC120
60
61 //==============================================================================
62
63 //==============================================================================
64 //  VIEWER GLOBAL VARIABLES
65 //==============================================================================
66
67 Standard_IMPORT Standard_Boolean Draw_VirtualWindows;
68
69 Standard_EXPORT int ViewerMainLoop(Standard_Integer , const char** argv);
70 extern const Handle(NIS_InteractiveContext)& TheNISContext();
71
72 #ifdef WNT
73 static Handle(Graphic3d_WNTGraphicDevice)& GetG3dDevice(){
74   static Handle(Graphic3d_WNTGraphicDevice) GD;
75   return GD;
76 }
77
78 static Handle(WNT_Window)& VT_GetWindow() {
79   static Handle(WNT_Window) WNTWin;
80   return WNTWin;
81 }
82
83 #else
84 static Handle(Graphic3d_GraphicDevice)& GetG3dDevice(){
85   static Handle(Graphic3d_GraphicDevice) GD;
86   return GD;
87 }
88 static Handle(Xw_Window)& VT_GetWindow(){
89   static Handle(Xw_Window) XWWin;
90   return XWWin;
91 }
92 static Display *display;
93
94 static void VProcessEvents(ClientData,int);
95 #endif
96
97 #ifdef OCC120
98 static Standard_Boolean DegenerateMode = Standard_True;
99 #endif
100
101 #define ZCLIPWIDTH 1.
102
103 static void OSWindowSetup();
104
105 //==============================================================================
106 //  EVENT GLOBAL VARIABLES
107 //==============================================================================
108
109 static int Start_Rot = 0;
110 static int ZClipIsOn = 0;
111 static int X_Motion= 0,Y_Motion=0; // Current cursor position
112 static int X_ButtonPress = 0, Y_ButtonPress = 0; // Last ButtonPress position
113
114
115 //==============================================================================
116
117 #ifdef WNT
118 static LRESULT WINAPI ViewerWindowProc(
119                                        HWND hwnd,
120                                        UINT uMsg,
121                                        WPARAM wParam,
122                                        LPARAM lParam );
123 static LRESULT WINAPI AdvViewerWindowProc(
124   HWND hwnd,
125   UINT uMsg,
126   WPARAM wParam,
127   LPARAM lParam );
128 #endif
129
130
131 //==============================================================================
132 //function : WClass
133 //purpose  :
134 //==============================================================================
135
136 const Handle(MMgt_TShared)& ViewerTest::WClass()
137 {
138   static Handle(MMgt_TShared) theWClass;
139 #ifdef WNT
140   if (theWClass.IsNull()) {
141     theWClass = new WNT_WClass ("GW3D_Class", AdvViewerWindowProc,
142       CS_VREDRAW | CS_HREDRAW, 0, 0,
143       ::LoadCursor (NULL, IDC_ARROW));
144   }
145 #endif
146   return theWClass;
147 }
148
149 //==============================================================================
150 //function : ViewerInit
151 //purpose  : Create the window viewer and initialize all the global variable
152 //==============================================================================
153
154 void ViewerTest::ViewerInit (const Standard_Integer thePxLeft,  const Standard_Integer thePxTop,
155                              const Standard_Integer thePxWidth, const Standard_Integer thePxHeight)
156 {
157   static Standard_Boolean isFirst = Standard_True;
158
159   Standard_Integer aPxLeft   = 0;
160   Standard_Integer aPxTop    = 460;
161   Standard_Integer aPxWidth  = 409;
162   Standard_Integer aPxHeight = 409;
163   if (thePxWidth != 0 && thePxHeight != 0)
164   {
165     aPxLeft   = thePxLeft;
166     aPxTop    = thePxTop;
167     aPxWidth  = thePxWidth;
168     aPxHeight = thePxHeight;
169   }
170
171   if (isFirst)
172   {
173     // Create the Graphic device
174 #ifdef WNT
175     if (GetG3dDevice().IsNull()) GetG3dDevice() = new Graphic3d_WNTGraphicDevice();
176     if (VT_GetWindow().IsNull())
177     {
178       // Create the Graphic device and the window
179       Handle(WNT_GraphicDevice) g_Device = new WNT_GraphicDevice();
180
181       VT_GetWindow() = new WNT_Window (g_Device, "Test3d",
182                                        Handle(WNT_WClass)::DownCast (WClass()),
183                                        WS_OVERLAPPEDWINDOW,
184                                        aPxLeft, aPxTop,
185                                        aPxWidth, aPxHeight,
186                                        Quantity_NOC_BLACK);
187       VT_GetWindow()->SetVirtual (Draw_VirtualWindows);
188     }
189 #else
190     if (GetG3dDevice().IsNull()) GetG3dDevice() =
191       new Graphic3d_GraphicDevice (getenv ("DISPLAY"), Xw_TOM_READONLY);
192     if (VT_GetWindow().IsNull())
193     {
194       VT_GetWindow() = new Xw_Window (GetG3dDevice(),
195                                       "Test3d",
196                                       aPxLeft, aPxTop,
197                                       aPxWidth, aPxHeight,
198                                       Xw_WQ_3DQUALITY,
199                                       Quantity_NOC_BLACK);
200       VT_GetWindow()->SetVirtual (Draw_VirtualWindows);
201     }
202 #endif
203
204     Handle(V3d_Viewer) a3DViewer, a3DCollector;
205     // Viewer and View creation
206
207     TCollection_ExtendedString NameOfWindow("Visu3D");
208
209     a3DViewer = new V3d_Viewer(GetG3dDevice(), NameOfWindow.ToExtString());
210     NameOfWindow = TCollection_ExtendedString("Collector");
211     a3DCollector = new V3d_Viewer(GetG3dDevice(), NameOfWindow.ToExtString());
212     a3DViewer->SetDefaultBackgroundColor(Quantity_NOC_BLACK);
213     a3DCollector->SetDefaultBackgroundColor(Quantity_NOC_STEELBLUE);
214     Handle(NIS_View) aView =
215       Handle(NIS_View)::DownCast(ViewerTest::CurrentView());
216     if ( aView.IsNull() ) {
217       //       Handle (V3d_View) V = a3DViewer->CreateView();
218       aView = new NIS_View (a3DViewer, VT_GetWindow());
219       ViewerTest::CurrentView(aView);
220       TheNISContext()->AttachView (aView);
221     }
222     Handle(V3d_View) a3DViewCol;
223     if ( a3DViewCol.IsNull() ) a3DViewCol    = a3DViewer->CreateView();
224
225     // AIS setup
226     if ( ViewerTest::GetAISContext().IsNull() ) {
227       Handle(AIS_InteractiveContext) C =
228         new AIS_InteractiveContext(a3DViewer,a3DCollector);
229       ViewerTest::SetAISContext(C);
230     }
231
232     // Setup for X11 or NT
233     OSWindowSetup();
234     // Viewer and View creation
235
236     a3DViewer->SetDefaultBackgroundColor(Quantity_NOC_BLACK);
237
238     Handle (V3d_View) V = ViewerTest::CurrentView();
239
240     V->SetDegenerateModeOn();
241 #ifdef OCC120
242     DegenerateMode = V->DegenerateModeIsOn();
243 #endif
244     //    V->SetWindow(VT_GetWindow(), NULL, MyViewProc, NULL);
245
246     V->SetZClippingDepth(0.5);
247     V->SetZClippingWidth(ZCLIPWIDTH/2.);
248     a3DViewer->SetDefaultLights();
249     a3DViewer->SetLightOn();
250
251 #ifndef WNT
252 #if TCL_MAJOR_VERSION  < 8
253     Tk_CreateFileHandler((void*)ConnectionNumber(display),
254       TK_READABLE, VProcessEvents, (ClientData) VT_GetWindow()->XWindow() );
255 #else
256     Tk_CreateFileHandler(ConnectionNumber(display),
257       TK_READABLE, VProcessEvents, (ClientData) VT_GetWindow()->XWindow() );
258 #endif
259 #endif
260
261     isFirst = Standard_False;
262   }
263   VT_GetWindow()->Map();
264 }
265
266 //==============================================================================
267 //function : Vinit
268 //purpose  : Create the window viewer and initialize all the global variable
269 //    Use Tk_CreateFileHandler on UNIX to cath the X11 Viewer event
270 //==============================================================================
271
272 static int VInit (Draw_Interpretor& , Standard_Integer argc, const char** argv)
273 {
274   Standard_Integer aPxLeft   = (argc > 1) ? atoi (argv[1]) : 0;
275   Standard_Integer aPxTop    = (argc > 2) ? atoi (argv[2]) : 0;
276   Standard_Integer aPxWidth  = (argc > 3) ? atoi (argv[3]) : 0;
277   Standard_Integer aPxHeight = (argc > 4) ? atoi (argv[4]) : 0;
278   ViewerTest::ViewerInit (aPxLeft, aPxTop, aPxWidth, aPxHeight);
279   return 0;
280 }
281
282 //==============================================================================
283 //function : ProcessKeyPress
284 //purpose  : Handle KeyPress event from a CString
285 //==============================================================================
286
287 static void ProcessKeyPress( char *buf_ret )
288 {
289   //cout << "KeyPress" << endl;
290   const Handle(V3d_View) aView = ViewerTest::CurrentView();
291   const Handle(NIS_View) aNisView = Handle(NIS_View)::DownCast (aView);
292   // Letter in alphabetic order
293
294   if ( !strcasecmp(buf_ret, "A") ) {
295     // AXO
296     aView->SetProj(V3d_XposYnegZpos);
297   }
298   else if ( !strcasecmp(buf_ret, "D") ) {
299     // Reset
300     aView->Reset();
301   }
302   else if ( !strcasecmp(buf_ret, "F") ) {
303     // FitAll
304     if (aNisView.IsNull())
305       aView->FitAll();
306     else
307       aNisView->FitAll3d();
308   }
309   else if ( !strcasecmp(buf_ret, "H") ) {
310     // HLR
311     cout << "HLR" << endl;
312 #ifdef OCC120
313     if (aView->DegenerateModeIsOn()) ViewerTest::CurrentView()->SetDegenerateModeOff();
314     else aView->SetDegenerateModeOn();
315     DegenerateMode = aView->DegenerateModeIsOn();
316 #else
317     ViewerTest::CurrentView()->SetDegenerateModeOff();
318 #endif
319   }
320   else if ( !strcasecmp(buf_ret, "D") ) {
321     // Reset
322     aView->Reset();
323   }
324   else if ( !strcasecmp(buf_ret, "S") ) {
325     // SHADING
326     cout << "passage en mode 1 (shading pour les shapes)" << endl;
327 #ifndef OCC120
328     ViewerTest::CurrentView()->SetDegenerateModeOn();
329 #endif
330     Handle(AIS_InteractiveContext) Ctx = ViewerTest::GetAISContext();
331     if(Ctx->NbCurrents()==0 ||
332       Ctx->NbSelected()==0)
333       Ctx->SetDisplayMode(AIS_Shaded);
334     else{
335       if(Ctx->HasOpenedContext()){
336         for(Ctx->InitSelected();Ctx->MoreSelected();Ctx->NextSelected())
337           Ctx->SetDisplayMode(Ctx->Interactive(),1,Standard_False);
338       }
339       else{
340         for(Ctx->InitCurrent();Ctx->MoreCurrent();Ctx->NextCurrent())
341           Ctx->SetDisplayMode(Ctx->Current(),1,Standard_False);
342       }
343       Ctx->UpdateCurrentViewer();
344     }
345   }
346   else if ( !strcasecmp(buf_ret, "U") ) {
347     // SHADING
348     cout<<"passage au mode par defaut"<<endl;
349 #ifndef OCC120
350     ViewerTest::CurrentView()->SetDegenerateModeOn();
351 #endif
352     Handle(AIS_InteractiveContext) Ctx = ViewerTest::GetAISContext();
353     if(Ctx->NbCurrents()==0 ||
354       Ctx->NbSelected()==0)
355       Ctx->SetDisplayMode(AIS_WireFrame);
356     else{
357       if(Ctx->HasOpenedContext()){
358         for(Ctx->InitSelected();Ctx->MoreSelected();Ctx->NextSelected())
359           Ctx->UnsetDisplayMode(Ctx->Interactive(),Standard_False);
360       }
361       else{
362         for(Ctx->InitCurrent();Ctx->MoreCurrent();Ctx->NextCurrent())
363           Ctx->UnsetDisplayMode(Ctx->Current(),Standard_False);
364       }
365       Ctx->UpdateCurrentViewer();
366     }
367
368   }
369   else if ( !strcasecmp(buf_ret, "T") ) {
370     // Top
371     aView->SetProj(V3d_Zpos);
372   }
373   else if ( !strcasecmp(buf_ret, "B") ) {
374     // Top
375     aView->SetProj(V3d_Zneg);
376   }
377   else if ( !strcasecmp(buf_ret, "L") ) {
378     // Top
379     aView->SetProj(V3d_Xneg);
380   }
381   else if ( !strcasecmp(buf_ret, "R") ) {
382     // Top
383     aView->SetProj(V3d_Xpos);
384   }
385
386   else if ( !strcasecmp(buf_ret, "W") ) {
387     // WIREFRAME
388 #ifndef OCC120
389     ViewerTest::CurrentView()->SetDegenerateModeOn();
390 #endif
391     cout << "passage en mode 0 (filaire pour les shapes)" << endl;
392 #ifndef OCC120
393     ViewerTest::CurrentView()->SetDegenerateModeOn();
394 #endif
395     Handle(AIS_InteractiveContext) Ctx = ViewerTest::GetAISContext();
396     if(Ctx->NbCurrents()==0 ||
397       Ctx->NbSelected()==0)
398       Ctx->SetDisplayMode(AIS_WireFrame);
399     else{
400       if(Ctx->HasOpenedContext()){
401         for(Ctx->InitSelected();Ctx->MoreSelected();Ctx->NextSelected())
402           Ctx->SetDisplayMode(Ctx->Interactive(),0,Standard_False);
403       }
404       else{
405         for(Ctx->InitCurrent();Ctx->MoreCurrent();Ctx->NextCurrent())
406           Ctx->SetDisplayMode(Ctx->Current(),0,Standard_False);
407       }
408       Ctx->UpdateCurrentViewer();
409     }
410   }
411   else if ( !strcasecmp(buf_ret, "Z") ) {
412     // ZCLIP
413
414     if ( ZClipIsOn ) {
415       cout << "ZClipping OFF" << endl;
416       ZClipIsOn = 0;
417
418       aView->SetZClippingType(V3d_OFF);
419       aView->Redraw();
420     }
421     else {
422       cout << "ZClipping ON" << endl;
423       ZClipIsOn = 1;
424
425       aView->SetZClippingType(V3d_FRONT);
426       aView->Redraw();
427     }
428   }
429   else if ( !strcasecmp(buf_ret, ",") ) {
430     ViewerTest::GetAISContext()->HilightNextDetected(ViewerTest::CurrentView());
431
432
433   }
434   else if ( !strcasecmp(buf_ret, ".") ) {
435     ViewerTest::GetAISContext()->HilightPreviousDetected(ViewerTest::CurrentView());
436   }
437   // Number
438   else{
439     Standard_Integer Num = atoi(buf_ret);
440     if(Num>=0 && Num<=7)
441       ViewerTest::StandardModeActivation(Num);
442   }
443 }
444
445 //==============================================================================
446 //function : ProcessExpose
447 //purpose  : Redraw the View on an Expose Event
448 //==============================================================================
449
450 static void ProcessExpose(  )
451 { //cout << "Expose" << endl;
452   ViewerTest::CurrentView()->Redraw();
453 }
454
455 //==============================================================================
456 //function : ProcessConfigure
457 //purpose  : Resize the View on an Configure Event
458 //==============================================================================
459
460 static void ProcessConfigure()
461 {
462   Handle(V3d_View) V = ViewerTest::CurrentView();
463   V->MustBeResized();
464   V->Update();
465   V->Redraw();
466 }
467
468 //==============================================================================
469 //function : ProcessButton1Press
470 //purpose  : Picking
471 //==============================================================================
472
473 static Standard_Boolean ProcessButton1Press(
474   Standard_Integer ,
475   const char** argv,
476   Standard_Boolean pick,
477   Standard_Boolean shift )
478 {
479   Handle(ViewerTest_EventManager) EM = ViewerTest::CurrentEventManager();
480   if ( pick ) {
481     Standard_Real X, Y, Z;
482
483     ViewerTest::CurrentView()->Convert(X_Motion, Y_Motion, X, Y, Z);
484
485     Draw::Set(argv[1], X);
486     Draw::Set(argv[2], Y);
487     Draw::Set(argv[3], Z);}
488
489   if(shift)
490     EM->ShiftSelect();
491   else
492     EM->Select();
493
494   pick = 0;
495   return pick;
496 }
497
498 //==============================================================================
499 //function : ProcessButton3Press
500 //purpose  : Start Rotation
501 //==============================================================================
502
503 static void ProcessButton3Press()
504
505 { // Start rotation
506   Start_Rot = 1;
507   ViewerTest::CurrentView()->SetDegenerateModeOn();
508   ViewerTest::CurrentView()->StartRotation( X_ButtonPress, Y_ButtonPress );
509
510 }
511 //==============================================================================
512 //function : ProcessButtonRelease
513 //purpose  : Start Rotation
514 //==============================================================================
515
516 static void ProcessButtonRelease()
517
518 { // End rotation
519 #ifdef OCC120
520   if (Start_Rot) {
521     Start_Rot = 0;
522     if (!DegenerateMode) ViewerTest::CurrentView()->SetDegenerateModeOff();
523   }
524 #else
525   Start_Rot = 0;
526   ViewerTest::CurrentView()->SetDegenerateModeOff();
527 #endif
528 }
529
530 //==============================================================================
531 //function : ProcessZClipMotion
532 //purpose  : Zoom
533 //==============================================================================
534
535 void ProcessZClipMotion()
536 {
537   Handle(V3d_View)  a3DView = ViewerTest::CurrentView();
538   if ( Abs(X_Motion - X_ButtonPress) > 2 ) {
539     static Standard_Real CurZPos = 0.;
540
541     //Quantity_Length VDX, VDY;
542     //a3DView->Size(VDX,VDY);
543     //Standard_Real VDZ = a3DView->ZSize();
544     //printf("View size (%lf,%lf,%lf)\n", VDX, VDY, VDZ);
545
546     Quantity_Length dx = a3DView->Convert(X_Motion - X_ButtonPress);
547
548     // Front = Depth + width/2.
549     Standard_Real D = 0.5;
550     Standard_Real W = 0.1;
551
552     CurZPos += (dx);
553
554     D += CurZPos;
555
556     //printf("dx %lf Depth %lf Width %lf\n", dx, D, W);
557
558     a3DView->SetZClippingType(V3d_OFF);
559     a3DView->SetZClippingDepth(D);
560     a3DView->SetZClippingWidth(W);
561     a3DView->SetZClippingType(V3d_FRONT);
562
563     a3DView->Redraw();
564
565     X_ButtonPress = X_Motion;
566     Y_ButtonPress = Y_Motion;
567   }
568 }
569
570 //==============================================================================
571 //function : ProcessControlButton1Motion
572 //purpose  : Zoom
573 //==============================================================================
574
575 static void ProcessControlButton1Motion()
576 {
577   ViewerTest::CurrentView()->Zoom( X_ButtonPress, Y_ButtonPress, X_Motion, Y_Motion);
578
579   X_ButtonPress = X_Motion;
580   Y_ButtonPress = Y_Motion;
581 }
582
583 //==============================================================================
584 //function : ProcessControlButton2Motion
585 //purpose  : Pann
586 //==============================================================================
587
588 static void ProcessControlButton2Motion()
589 {
590   Quantity_Length dx = ViewerTest::CurrentView()->Convert(X_Motion - X_ButtonPress);
591   Quantity_Length dy = ViewerTest::CurrentView()->Convert(Y_Motion - Y_ButtonPress);
592
593   dy = -dy; // Xwindow Y axis is from top to Bottom
594
595   ViewerTest::CurrentView()->Panning( dx, dy );
596
597   X_ButtonPress = X_Motion;
598   Y_ButtonPress = Y_Motion;
599 }
600
601 //==============================================================================
602 //function : ProcessControlButton3Motion
603 //purpose  : Rotation
604 //==============================================================================
605
606 static void ProcessControlButton3Motion()
607 {
608   if ( Start_Rot ) ViewerTest::CurrentView()->Rotation( X_Motion, Y_Motion);
609 }
610
611 //==============================================================================
612 //function : ProcessPointerMotion
613 //purpose  : Rotation
614 //==============================================================================
615
616 static void ProcessMotion()
617 {
618   //pre-hilights detected objects at mouse position
619
620   Handle(ViewerTest_EventManager) EM = ViewerTest::CurrentEventManager();
621   EM->MoveTo(X_Motion, Y_Motion);
622 }
623
624
625 void ViewerTest::GetMousePosition(Standard_Integer& Xpix,Standard_Integer& Ypix)
626 {
627   Xpix = X_Motion;Ypix=Y_Motion;
628 }
629
630 //==============================================================================
631 //function : VAxo
632 //purpose  : Switch to an Axonometric view
633 //Draw arg : No args
634 //==============================================================================
635
636 static int VAxo(Draw_Interpretor& di, Standard_Integer , const char** )
637 { if ( ViewerTest::CurrentView().IsNull() ) {
638   di<<"La commande vinit n'a pas ete appele avant"<<"\n";
639   //  VInit(di, argc, argv);
640 }
641
642 ViewerTest::CurrentView()->SetProj(V3d_XposYnegZpos);
643
644 return 0;
645 }
646
647 //==============================================================================
648 //function : VTop
649 //purpose  : Switch to a Top View
650 //Draw arg : No args
651 //==============================================================================
652
653 static int VTop(Draw_Interpretor& di, Standard_Integer , const char** )
654 {
655
656   if ( ViewerTest::CurrentView().IsNull() ) {
657     di<<"La commande vinit n'a pas ete appele avant"<<"\n";
658
659     //  VInit(di, , argv);
660   }
661
662   ViewerTest::CurrentView()->SetProj(V3d_Zpos);
663   return 0;
664
665 }
666
667 //==============================================================================
668 //function : VHelp
669 //purpose  : Dsiplay help on viewer Keyboead and mouse commands
670 //Draw arg : No args
671 //==============================================================================
672
673 static int VHelp(Draw_Interpretor& di, Standard_Integer , const char** )
674 {
675
676   di << "Q : Quit the application" << "\n";
677
678   di << "========================="<<"\n";
679   di << "F : FitAll" << "\n";
680   di << "T : TopView" << "\n";
681   di << "A : AxonometricView" << "\n";
682   di << "R : ResetView" << "\n";
683
684   di << "========================="<<"\n";
685   di << "S : Shading" << "\n";
686   di << "W : Wireframe" << "\n";
687   di << "H : HidelLineRemoval" << "\n";
688
689   di << "========================="<<"\n";
690   di << "Selection mode "<<"\n";
691   di << "0 : Shape" <<"\n";
692   di << "1 : Vertex" <<"\n";
693   di << "2 : Edge" <<"\n";
694   di << "3 : Wire" <<"\n";
695   di << "4 : Face" <<"\n";
696   di << "5 : Shell" <<"\n";
697   di << "6 : Solid" <<"\n";
698   di << "7 : Compound" <<"\n";
699
700   di << "=========================="<<"\n";
701   di << "D : Remove Selected Object"<<"\n";
702   di << "=========================="<<"\n";
703
704   return 0;
705 }
706
707 Standard_Boolean IsDragged = Standard_False;
708
709 Standard_Integer xx1, yy1, xx2, yy2;
710 //the first and last point in viewer co-ordinates
711
712 Standard_Boolean DragFirst;
713
714
715 #ifdef WNT
716
717 static Standard_Boolean Ppick = 0;
718 static Standard_Integer Pargc = 0;
719 static const char**           Pargv = NULL;
720
721
722 static LRESULT WINAPI AdvViewerWindowProc( HWND hwnd,
723                                           UINT Msg,
724                                           WPARAM wParam,
725                                           LPARAM lParam )
726 {
727   if ( !ViewerTest::CurrentView().IsNull() ) {
728
729     WPARAM fwKeys = wParam;
730
731     switch( Msg ) {
732
733     case WM_LBUTTONUP:
734       IsDragged = Standard_False;
735       if( !DragFirst )
736       {
737         HDC hdc = GetDC( hwnd );
738         HGDIOBJ anObj = SelectObject( hdc, GetStockObject( WHITE_PEN ) );
739         SelectObject( hdc, GetStockObject( HOLLOW_BRUSH ) );
740         SetROP2( hdc, R2_NOT );
741         Rectangle( hdc, xx1, yy1, xx2, yy2 );
742         ReleaseDC( hwnd, hdc );
743
744         const Handle(ViewerTest_EventManager) EM =
745           ViewerTest::CurrentEventManager();
746         if ( fwKeys & MK_SHIFT )
747           EM->ShiftSelect( min( xx1, xx2 ), max( yy1, yy2 ),
748           max( xx1, xx2 ), min( yy1, yy2 ));
749         else
750           EM->Select( min( xx1, xx2 ), max( yy1, yy2 ),
751           max( xx1, xx2 ), min( yy1, yy2 ));
752       }
753       return ViewerWindowProc( hwnd, Msg, wParam, lParam );
754
755     case WM_LBUTTONDOWN:
756       if( fwKeys == MK_LBUTTON || fwKeys == ( MK_LBUTTON | MK_SHIFT ) )
757       {
758         IsDragged = Standard_True;
759         DragFirst = Standard_True;
760         xx1 = LOWORD(lParam);
761         yy1 = HIWORD(lParam);
762       }
763       return ViewerWindowProc( hwnd, Msg, wParam, lParam );
764
765       break;
766
767     case WM_MOUSEMOVE:
768       if( IsDragged )
769       {
770         HDC hdc = GetDC( hwnd );
771
772         HGDIOBJ anObj = SelectObject( hdc, GetStockObject( WHITE_PEN ) );
773         SelectObject( hdc, GetStockObject( HOLLOW_BRUSH ) );
774         SetROP2( hdc, R2_NOT );
775
776         if( !DragFirst )
777           Rectangle( hdc, xx1, yy1, xx2, yy2 );
778
779         DragFirst = Standard_False;
780         xx2 = LOWORD(lParam);
781         yy2 = HIWORD(lParam);
782
783         Rectangle( hdc, xx1, yy1, xx2, yy2 );
784
785         SelectObject( hdc, anObj );
786
787         ReleaseDC( hwnd, hdc );
788       }
789       else
790         return ViewerWindowProc( hwnd, Msg, wParam, lParam );
791       break;
792
793     default:
794       return ViewerWindowProc( hwnd, Msg, wParam, lParam );
795     }
796     return 0;
797   }
798   return ViewerWindowProc( hwnd, Msg, wParam, lParam );
799 }
800
801
802 static LRESULT WINAPI ViewerWindowProc( HWND hwnd,
803                                        UINT Msg,
804                                        WPARAM wParam,
805                                        LPARAM lParam )
806 {
807   /*static Standard_Boolean Ppick = 0;
808   static Standard_Integer Pargc = 0;
809   static char**           Pargv = NULL;*/
810
811   static int Up = 1;
812
813   if ( !ViewerTest::CurrentView().IsNull() ) {
814     PAINTSTRUCT    ps;
815
816     switch( Msg ) {
817     case WM_CLOSE:
818       // do not destroy the window - just hide it!
819       VT_GetWindow()->Unmap();
820       return 0;
821     case WM_PAINT:
822       //cout << "\t WM_PAINT" << endl;
823       BeginPaint(hwnd, &ps);
824       EndPaint(hwnd, &ps);
825       ProcessExpose();
826       break;
827
828     case WM_SIZE:
829       //cout << "\t WM_SIZE" << endl;
830       ProcessConfigure();
831       break;
832
833     case WM_KEYDOWN:
834       //cout << "\t WM_KEYDOWN " << (int) wParam << endl;
835
836       if ( (wParam != VK_SHIFT) && (wParam != VK_CONTROL) ) {
837         char c[2];
838         c[0] = (char) wParam;
839         c[1] = '\0';
840         ProcessKeyPress( c);
841       }
842       break;
843
844     case WM_LBUTTONUP:
845     case WM_MBUTTONUP:
846     case WM_RBUTTONUP:
847       //cout << "\t WM_xBUTTONUP" << endl;
848       Up = 1;
849       ProcessButtonRelease();
850       break;
851
852     case WM_LBUTTONDOWN:
853     case WM_MBUTTONDOWN:
854     case WM_RBUTTONDOWN:
855       {
856         //cout << "\t WM_xBUTTONDOWN" << endl;
857         WPARAM fwKeys = wParam;
858
859         Up = 0;
860
861         X_ButtonPress = LOWORD(lParam);
862         Y_ButtonPress = HIWORD(lParam);
863
864         if ( Msg == WM_LBUTTONDOWN) {
865           if(fwKeys & MK_CONTROL) {
866             Ppick = ProcessButton1Press( Pargc, Pargv, Ppick,  (fwKeys & MK_SHIFT) );
867           } else
868             ProcessButton1Press( Pargc, Pargv, Ppick,  (fwKeys & MK_SHIFT) );
869         }
870         else if ( Msg == WM_RBUTTONDOWN ) {
871           // Start rotation
872           ProcessButton3Press( );
873         }
874       }
875       break;
876
877     case WM_MOUSEMOVE:
878       {
879         //cout << "\t WM_MOUSEMOVE" << endl;
880         WPARAM fwKeys = wParam;
881         X_Motion = LOWORD(lParam);
882         Y_Motion = HIWORD(lParam);
883
884         if ( Up &&
885           fwKeys & ( MK_LBUTTON|MK_MBUTTON|MK_RBUTTON ) ) {
886             Up = 0;
887             X_ButtonPress = LOWORD(lParam);
888             Y_ButtonPress = HIWORD(lParam);
889
890             if ( fwKeys & MK_RBUTTON ) {
891               // Start rotation
892               ProcessButton3Press();
893             }
894           }
895
896           if ( fwKeys & MK_CONTROL ) {
897             if ( fwKeys & MK_LBUTTON ) {
898               ProcessControlButton1Motion();
899             }
900             else if ( fwKeys & MK_MBUTTON ||
901               ((fwKeys&MK_LBUTTON) &&
902               (fwKeys&MK_RBUTTON) ) ){
903                 ProcessControlButton2Motion();
904               }
905             else if ( fwKeys & MK_RBUTTON ) {
906               ProcessControlButton3Motion();
907             }
908           }
909 #ifdef BUG
910           else if ( fwKeys & MK_SHIFT ) {
911             if ( fwKeys & MK_MBUTTON ||
912               ((fwKeys&MK_LBUTTON) &&
913               (fwKeys&MK_RBUTTON) ) ) {
914                 cout << "ProcessZClipMotion()" << endl;
915                 ProcessZClipMotion();
916               }
917           }
918 #endif
919           else
920             if (( fwKeys & MK_MBUTTON || ((fwKeys&MK_LBUTTON) && (fwKeys&MK_RBUTTON) ) )){
921               ProcessZClipMotion();
922             }
923             else {
924               ProcessMotion();
925             }
926       }
927       break;
928
929     default:
930       return( DefWindowProc( hwnd, Msg, wParam, lParam ));
931     }
932     return 0L;
933   }
934
935   return DefWindowProc( hwnd, Msg, wParam, lParam );
936 }
937
938
939
940
941 //==============================================================================
942 //function : ViewerMainLoop
943 //purpose  : Get a Event on the view and dispatch it
944 //==============================================================================
945
946
947 static int ViewerMainLoop(Standard_Integer argc, const char** argv)
948 {
949
950   //cout << "No yet implemented on WNT" << endl;
951   /*static Standard_Boolean Ppick = 0;
952   static Standard_Integer Pargc = 0;
953   static char**           Pargv = NULL;*/
954
955   //Ppick = (argc > 0)? -1 : 0;
956   Ppick = (argc > 0)? 1 : 0;
957   Pargc = argc;
958   Pargv = argv;
959
960   if ( Ppick ) {
961     MSG msg;
962     msg.wParam = 1;
963
964     cout << "Start picking" << endl;
965
966     //while ( Ppick == -1 ) {
967     while ( Ppick == 1 ) {
968       // Wait for a ProcessButton1Press() to toggle pick to 1 or 0
969       if (GetMessage(&msg, NULL, 0, 0) ) {
970         TranslateMessage(&msg);
971         DispatchMessage(&msg);
972       }
973     }
974
975     cout << "Picking done" << endl;
976   }
977
978   return Ppick;
979 }
980
981
982 #else
983
984 int min( int a, int b )
985 {
986   if( a<b )
987     return a;
988   else
989     return b;
990 }
991
992 int max( int a, int b )
993 {
994   if( a>b )
995     return a;
996   else
997     return b;
998 }
999
1000 int ViewerMainLoop(Standard_Integer argc, const char** argv)
1001
1002 { Standard_Boolean pick = argc > 0;
1003
1004 // X11 Event loop
1005
1006 static XEvent report;
1007
1008 XNextEvent( display, &report );
1009 //    cout << "rep type = " << report.type << endl;
1010 //    cout << "rep button = " << report.xbutton.button << endl;
1011
1012 switch ( report.type ) {
1013       case Expose:
1014         {
1015           ProcessExpose();
1016         }
1017         break;
1018       case ConfigureNotify:
1019         {
1020           ProcessConfigure();
1021         }
1022         break;
1023       case KeyPress:
1024         {
1025
1026           KeySym ks_ret ;
1027           char buf_ret[11] ;
1028           int ret_len ;
1029           XComposeStatus status_in_out;
1030
1031           ret_len = XLookupString( ( XKeyEvent *)&report ,
1032             (char *) buf_ret , 10 ,
1033             &ks_ret , &status_in_out ) ;
1034
1035
1036           buf_ret[ret_len] = '\0' ;
1037
1038           if ( ret_len ) {
1039             ProcessKeyPress( buf_ret);
1040           }
1041         }
1042         break;
1043       case ButtonPress:
1044         //  cout << "ButtonPress" << endl;
1045         {
1046           X_ButtonPress = report.xbutton.x;
1047           Y_ButtonPress = report.xbutton.y;
1048
1049           if ( report.xbutton.button == Button1 )
1050             if(  report.xbutton.state & ControlMask )
1051               pick = ProcessButton1Press( argc, argv, pick,
1052               ( report.xbutton.state & ShiftMask) );
1053             else
1054             {
1055               IsDragged = Standard_True;
1056               xx1 = X_ButtonPress;
1057               yy1 = Y_ButtonPress;
1058               DragFirst = Standard_True;
1059             }
1060           else if ( report.xbutton.button == Button3 )
1061             // Start rotation
1062             ProcessButton3Press();
1063         }
1064         break;
1065       case ButtonRelease:
1066         {
1067           //    cout<<"relachement du bouton "<<(report.xbutton.button==3 ? "3": "on s'en fout") <<endl;
1068           //    cout << IsDragged << endl;
1069           //    cout << DragFirst << endl;
1070
1071           if( IsDragged )
1072           {
1073             if( !DragFirst )
1074             {
1075               Aspect_Handle aWindow = VT_GetWindow()->XWindow();
1076               GC gc = XCreateGC( display, aWindow, 0, 0 );
1077               //  XSetFunction( display, gc, GXinvert );
1078               XDrawRectangle( display, aWindow, gc, min( xx1, xx2 ), min( yy1, yy2 ), abs( xx2-xx1 ), abs( yy2-yy1 ) );
1079             }
1080
1081             Handle( AIS_InteractiveContext ) aContext = ViewerTest::GetAISContext();
1082             if( aContext.IsNull() )
1083             {
1084               cout << "The context is null. Please use vinit before createmesh" << endl;
1085               return 0;
1086             }
1087
1088             Standard_Boolean ShiftPressed = ( report.xbutton.state & ShiftMask );
1089             if( report.xbutton.button==1 )
1090               if( DragFirst )
1091                 if( ShiftPressed )
1092                 {
1093                   aContext->ShiftSelect();
1094                   //                   cout << "shift select" << endl;
1095                 }
1096                 else
1097                 {
1098                   aContext->Select();
1099                   //                   cout << "select" << endl;
1100                 }
1101               else
1102                 if( ShiftPressed )
1103                 {
1104                   aContext->ShiftSelect( min( xx1, xx2 ), min( yy1, yy2 ),
1105                     max( xx1, xx2 ), max( yy1, yy2 ),
1106                     ViewerTest::CurrentView());
1107                   //                   cout << "shift select" << endl;
1108                 }
1109                 else
1110                 {
1111                   aContext->Select( min( xx1, xx2 ), min( yy1, yy2 ),
1112                     max( xx1, xx2 ), max( yy1, yy2 ),
1113                     ViewerTest::CurrentView() );
1114                   //                   cout << "select" << endl;
1115                 }
1116             else
1117               ProcessButtonRelease();
1118
1119             IsDragged = Standard_False;
1120           }
1121           else
1122             ProcessButtonRelease();
1123         }
1124         break;
1125       case MotionNotify:
1126         {
1127           //    XEvent dummy;
1128
1129           X_Motion = report.xmotion.x;
1130           Y_Motion = report.xmotion.y;
1131
1132           if( IsDragged )
1133           {
1134             Aspect_Handle aWindow = VT_GetWindow()->XWindow();
1135             GC gc = XCreateGC( display, aWindow, 0, 0 );
1136             XSetFunction( display, gc, GXinvert );
1137
1138             if( !DragFirst )
1139               XDrawRectangle( display, aWindow, gc, min( xx1, xx2 ), min( yy1, yy2 ), abs( xx2-xx1 ), abs( yy2-yy1 ) );
1140
1141             xx2 = X_Motion;
1142             yy2 = Y_Motion;
1143             DragFirst = Standard_False;
1144
1145             //cout << "draw rect : " << xx2 << ", " << yy2 << endl;
1146             XDrawRectangle( display, aWindow, gc, min( xx1, xx2 ), min( yy1, yy2 ), abs( xx2-xx1 ), abs( yy2-yy1 ) );
1147           }
1148           else
1149           {
1150
1151             //cout << "MotionNotify " << X_Motion << "," << Y_Motion << endl;
1152
1153             // remove all the ButtonMotionMask
1154             while( XCheckMaskEvent( display, ButtonMotionMask, &report) ) ;
1155
1156             if ( ZClipIsOn && report.xmotion.state & ShiftMask ) {
1157               if ( Abs(X_Motion - X_ButtonPress) > 2 ) {
1158
1159                 Quantity_Length VDX, VDY;
1160
1161                 ViewerTest::CurrentView()->Size(VDX,VDY);
1162                 Standard_Real VDZ =0 ;
1163                 VDZ = ViewerTest::CurrentView()->ZSize();
1164
1165                 //          printf("%lf,%lf,%lf\n", VDX, VDY, VDZ);
1166                 printf("%f,%f,%f\n", VDX, VDY, VDZ);
1167
1168                 Quantity_Length dx = 0 ;
1169                 dx = ViewerTest::CurrentView()->Convert(X_Motion - X_ButtonPress);
1170
1171                 cout << dx << endl;
1172
1173                 dx = dx / VDX * VDZ;
1174
1175                 cout << dx << endl;
1176
1177                 // Front = Depth + width/2.
1178                 //ViewerTest::CurrentView()->SetZClippingDepth(dx);
1179                 //ViewerTest::CurrentView()->SetZClippingWidth(0.);
1180
1181                 ViewerTest::CurrentView()->Redraw();
1182               }
1183             }
1184
1185             if ( report.xmotion.state & ControlMask ) {
1186               if ( report.xmotion.state & Button1Mask ) {
1187                 ProcessControlButton1Motion();
1188               }
1189               else if ( report.xmotion.state & Button2Mask ) {
1190                 ProcessControlButton2Motion();
1191               }
1192               else if ( report.xmotion.state & Button3Mask ) {
1193                 ProcessControlButton3Motion();
1194               }
1195             }
1196             else {
1197               ProcessMotion();
1198             }
1199           }
1200         }
1201         break;
1202 }
1203
1204
1205 return pick;
1206 }
1207
1208 //==============================================================================
1209 //function : VProcessEvents
1210 //purpose  : call by Tk_CreateFileHandler() to be able to manage the
1211 //       event in the Viewer window
1212 //==============================================================================
1213
1214 static void VProcessEvents(ClientData,int)
1215 {
1216   //cout << "VProcessEvents" << endl;
1217
1218   // test for X Event
1219   while (XPending(display)) {
1220     ViewerMainLoop( 0, NULL);
1221   }
1222 }
1223 #endif
1224
1225 //==============================================================================
1226 //function : OSWindowSetup
1227 //purpose  : Setup for the X11 window to be able to cath the event
1228 //==============================================================================
1229
1230
1231 static void OSWindowSetup()
1232 {
1233 #ifndef WNT
1234   // X11
1235
1236   Window  window   = VT_GetWindow()->XWindow();
1237
1238   Standard_Address theDisplay = GetG3dDevice()->XDisplay();
1239   display = (Display * ) theDisplay;
1240   //  display = (Display *)GetG3dDevice()->XDisplay();
1241
1242   XSynchronize(display, 1);
1243
1244   VT_GetWindow()->Map();
1245
1246   // X11 : For keyboard on SUN
1247   XWMHints wmhints;
1248   wmhints.flags = InputHint;
1249   wmhints.input = 1;
1250
1251   XSetWMHints( display, window, &wmhints);
1252
1253   XSelectInput( display, window,  ExposureMask | KeyPressMask |
1254     ButtonPressMask | ButtonReleaseMask |
1255     StructureNotifyMask |
1256     PointerMotionMask |
1257     Button1MotionMask | Button2MotionMask |
1258     Button3MotionMask
1259     );
1260
1261   XSynchronize(display, 0);
1262
1263 #else
1264   // WNT
1265 #endif
1266
1267 }
1268
1269
1270 //==============================================================================
1271 //function : VFit
1272
1273 //purpose  : Fitall, no DRAW arguments
1274 //Draw arg : No args
1275 //==============================================================================
1276
1277 static int VFit(Draw_Interpretor& , Standard_Integer , const char** )
1278 {
1279   const Handle(V3d_View) aView = ViewerTest::CurrentView();
1280   Handle(NIS_View) V = Handle(NIS_View)::DownCast(aView);
1281   if (V.IsNull() == Standard_False) {
1282     V->FitAll3d();
1283   } else if (aView.IsNull() == Standard_False) {
1284     aView->FitAll();
1285   }
1286   return 0;
1287 }
1288
1289 //==============================================================================
1290 //function : VZFit
1291 //purpose  : ZFitall, no DRAW arguments
1292 //Draw arg : No args
1293 //==============================================================================
1294
1295 static int VZFit(Draw_Interpretor& , Standard_Integer , const char** )
1296 {
1297   Handle(V3d_View) V = ViewerTest::CurrentView();
1298   if ( !V.IsNull() ) V->ZFitAll(); return 0; }
1299
1300
1301 static int VRepaint(Draw_Interpretor& , Standard_Integer , const char** )
1302 {
1303   Handle(V3d_View) V = ViewerTest::CurrentView();
1304   if ( !V.IsNull() ) V->Redraw(); return 0;
1305 }
1306
1307
1308 //==============================================================================
1309 //function : VClear
1310 //purpose  : Remove all the object from the viewer
1311 //Draw arg : No args
1312 //==============================================================================
1313
1314 static int VClear(Draw_Interpretor& , Standard_Integer , const char** )
1315 {
1316   Handle(V3d_View) V = ViewerTest::CurrentView();
1317   if(!V.IsNull())
1318     ViewerTest::Clear();
1319   return 0;
1320 }
1321
1322 //==============================================================================
1323 //function : VPick
1324 //purpose  :
1325 //==============================================================================
1326
1327 static int VPick(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
1328 { if (ViewerTest::CurrentView().IsNull() ) return 1;
1329
1330 if ( argc < 4 ) {
1331   di << argv[0] << "Invalid number of arguments" << "\n";
1332   return 1;
1333 }
1334
1335 while (ViewerMainLoop( argc, argv)) {
1336 }
1337
1338 return 0;
1339 }
1340
1341
1342
1343 //==============================================================================
1344 //function : InitViewerTest
1345 //purpose  : initialisation de toutes les variables static de  ViewerTest (dp)
1346 //==============================================================================
1347
1348 void ViewerTest_InitViewerTest (const Handle(AIS_InteractiveContext)& context)
1349 {
1350   Handle(V3d_Viewer) viewer = context->CurrentViewer();
1351   ViewerTest::SetAISContext(context);
1352   viewer->InitActiveViews();
1353   Handle(V3d_View) view = viewer->ActiveView();
1354   if (viewer->MoreActiveViews()) ViewerTest::CurrentView(view);
1355   ViewerTest::ResetEventManager();
1356   Handle(Aspect_GraphicDevice) device = viewer->Device();
1357   Handle(Aspect_Window) window = view->Window();
1358 #ifndef WNT
1359   // X11
1360   VT_GetWindow() = Handle(Xw_Window)::DownCast(window);
1361   GetG3dDevice() = Handle(Graphic3d_GraphicDevice)::DownCast(device);
1362   OSWindowSetup();
1363   static int first = 1;
1364   if ( first ) {
1365 #if TCL_MAJOR_VERSION  < 8
1366     Tk_CreateFileHandler((void*)ConnectionNumber(display),
1367       TK_READABLE, VProcessEvents, (ClientData) 0);
1368 #else
1369     Tk_CreateFileHandler(ConnectionNumber(display),
1370       TK_READABLE, VProcessEvents, (ClientData) 0);
1371 #endif
1372     first = 0;
1373   }
1374 #endif
1375 }
1376
1377
1378 //==============================================================================
1379 //function : VSetBg
1380 //purpose  : Load image as background
1381 //==============================================================================
1382
1383 static int VSetBg(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
1384 {
1385   if (argc < 2 || argc > 3)
1386   {
1387     di << "Usage : " << argv[0] << " imagefile [filltype] : Load image as background" << "\n";
1388     di << "filltype can be one of CENTERED, TILED, STRETCH, NONE" << "\n";
1389     return 1;
1390   }
1391
1392   Handle(AIS_InteractiveContext) AISContext = ViewerTest::GetAISContext();
1393   if(AISContext.IsNull())
1394   {
1395     di << "use 'vinit' command before " << argv[0] << "\n";
1396     return 1;
1397   }
1398
1399   Aspect_FillMethod aFillType = Aspect_FM_CENTERED;
1400   if (argc == 3)
1401   {
1402     const char* szType = argv[2];
1403     if      (strcmp(szType, "NONE"    ) == 0) aFillType = Aspect_FM_NONE;
1404     else if (strcmp(szType, "CENTERED") == 0) aFillType = Aspect_FM_CENTERED;
1405     else if (strcmp(szType, "TILED"   ) == 0) aFillType = Aspect_FM_TILED;
1406     else if (strcmp(szType, "STRETCH" ) == 0) aFillType = Aspect_FM_STRETCH;
1407     else
1408     {
1409       di << "Wrong fill type : " << szType << "\n";
1410       di << "Must be one of CENTERED, TILED, STRETCH, NONE" << "\n";
1411       return 1;
1412     }
1413   }
1414
1415   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
1416   V3dView->SetBackgroundImage(argv[1], aFillType, Standard_True);
1417
1418   return 0;
1419 }
1420
1421 //==============================================================================
1422 //function : VSetBgMode
1423 //purpose  : Change background image fill type
1424 //==============================================================================
1425
1426 static int VSetBgMode(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
1427 {
1428   if (argc != 2)
1429   {
1430     di << "Usage : " << argv[0] << " filltype : Change background image mode" << "\n";
1431     di << "filltype must be one of CENTERED, TILED, STRETCH, NONE" << "\n";
1432     return 1;
1433   }
1434
1435   Handle(AIS_InteractiveContext) AISContext = ViewerTest::GetAISContext();
1436   if(AISContext.IsNull())
1437   {
1438     di << "use 'vinit' command before " << argv[0] << "\n";
1439     return 1;
1440   }
1441
1442   Aspect_FillMethod aFillType;
1443   if (argc == 2)
1444   {
1445     const char* szType = argv[1];
1446     if      (strcmp(szType, "NONE"    ) == 0) aFillType = Aspect_FM_NONE;
1447     else if (strcmp(szType, "CENTERED") == 0) aFillType = Aspect_FM_CENTERED;
1448     else if (strcmp(szType, "TILED"   ) == 0) aFillType = Aspect_FM_TILED;
1449     else if (strcmp(szType, "STRETCH" ) == 0) aFillType = Aspect_FM_STRETCH;
1450     else
1451     {
1452       di << "Wrong fill type : " << szType << "\n";
1453       di << "Must be one of CENTERED, TILED, STRETCH, NONE" << "\n";
1454       return 1;
1455     }
1456   }
1457
1458   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
1459   V3dView->SetBgImageStyle(aFillType, Standard_True);
1460
1461   return 0;
1462 }
1463
1464 //==============================================================================
1465 //function : VSetGradientBg
1466 //purpose  : Mount gradient background
1467 //==============================================================================
1468 static int VSetGradientBg(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
1469 {
1470   if (argc != 8 )
1471   {
1472     di << "Usage : " << argv[0] << " R1 G1 B1 R2 G2 B2 Type : Mount gradient background" << "\n";
1473     di << "R1,G1,B1,R2,G2,B2 = [0..255]" << "\n";
1474     di << "Type must be one of 0 = NONE, 1 = HOR, 2 = VER, 3 = DIAG1, 4 = DIAG2" << "\n";
1475     di << "                    5 = CORNER1, 6 = CORNER2, 7 = CORNER3, 8 = CORNER4" << "\n";
1476     return 1;
1477   }
1478
1479   Handle(AIS_InteractiveContext) AISContext = ViewerTest::GetAISContext();
1480   if(AISContext.IsNull())
1481   {
1482     di << "use 'vinit' command before " << argv[0] << "\n";
1483     return 1;
1484   }
1485   if (argc == 8)
1486   {
1487
1488     Standard_Real R1 = atof(argv[1])/255.;
1489     Standard_Real G1 = atof(argv[2])/255.;
1490     Standard_Real B1 = atof(argv[3])/255.;
1491     Quantity_Color aColor1(R1,G1,B1,Quantity_TOC_RGB);
1492
1493     Standard_Real R2 = atof(argv[4])/255.;
1494     Standard_Real G2 = atof(argv[5])/255.;
1495     Standard_Real B2 = atof(argv[6])/255.;
1496
1497     Quantity_Color aColor2(R2,G2,B2,Quantity_TOC_RGB);
1498     int aType = atoi(argv[7]);
1499     if( aType < 0 || aType > 8 )
1500     {
1501       di << "Wrong fill type " << "\n";
1502       di << "Must be one of 0 = NONE, 1 = HOR, 2 = VER, 3 = DIAG1, 4 = DIAG2" << "\n";
1503       di << "               5 = CORNER1, 6 = CORNER2, 7 = CORNER3, 8 = CORNER4" << "\n";
1504       return 1;
1505     }
1506
1507     Aspect_GradientFillMethod aMethod = Aspect_GradientFillMethod(aType);
1508
1509     Handle(V3d_View) V3dView = ViewerTest::CurrentView();
1510     V3dView->SetBgGradientColors( aColor1, aColor2, aMethod, 1);
1511   }
1512
1513   return 0;
1514 }
1515
1516 //==============================================================================
1517 //function : VSetGradientBgMode
1518 //purpose  : Change gradient background fill style
1519 //==============================================================================
1520 static int VSetGradientBgMode(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
1521 {
1522   if (argc != 2 )
1523   {
1524     di << "Usage : " << argv[0] << " Type : Change gradient background fill type" << "\n";
1525     di << "Type must be one of 0 = NONE, 1 = HOR, 2 = VER, 3 = DIAG1, 4 = DIAG2" << "\n";
1526     di << "                    5 = CORNER1, 6 = CORNER2, 7 = CORNER3, 8 = CORNER4" << "\n";
1527     return 1;
1528   }
1529
1530   Handle(AIS_InteractiveContext) AISContext = ViewerTest::GetAISContext();
1531   if(AISContext.IsNull())
1532   {
1533     di << "use 'vinit' command before " << argv[0] << "\n";
1534     return 1;
1535   }
1536   if (argc == 2)
1537   {
1538     int aType = atoi(argv[1]);
1539     if( aType < 0 || aType > 8 )
1540     {
1541       di << "Wrong fill type " << "\n";
1542       di << "Must be one of 0 = NONE, 1 = HOR, 2 = VER, 3 = DIAG1, 4 = DIAG2" << "\n";
1543       di << "               5 = CORNER1, 6 = CORNER2, 7 = CORNER3, 8 = CORNER4" << "\n";
1544       return 1;
1545     }
1546
1547     Aspect_GradientFillMethod aMethod = Aspect_GradientFillMethod(aType);
1548
1549     Handle(V3d_View) V3dView = ViewerTest::CurrentView();
1550     V3dView->SetBgGradientStyle( aMethod, 1 );
1551   }
1552
1553   return 0;
1554 }
1555
1556 //==============================================================================
1557 //function : VSetColorBg
1558 //purpose  : Set color background
1559 //==============================================================================
1560 static int VSetColorBg(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
1561 {
1562   if (argc != 4 )
1563   {
1564     di << "Usage : " << argv[0] << " R G B : Set color background" << "\n";
1565     di << "R,G,B = [0..255]" << "\n";
1566     return 1;
1567   }
1568
1569   Handle(AIS_InteractiveContext) AISContext = ViewerTest::GetAISContext();
1570   if(AISContext.IsNull())
1571   {
1572     di << "use 'vinit' command before " << argv[0] << "\n";
1573     return 1;
1574   }
1575   if (argc == 4)
1576   {
1577
1578     Standard_Real R = atof(argv[1])/255.;
1579     Standard_Real G = atof(argv[2])/255.;
1580     Standard_Real B = atof(argv[3])/255.;
1581     Quantity_Color aColor(R,G,B,Quantity_TOC_RGB);
1582
1583     Handle(V3d_View) V3dView = ViewerTest::CurrentView();
1584     V3dView->SetBackgroundColor( aColor );
1585     V3dView->Update();
1586   }
1587
1588   return 0;
1589 }
1590
1591 //==============================================================================
1592 //function : VScale
1593 //purpose  : View Scaling
1594 //==============================================================================
1595
1596 static int VScale(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
1597 {
1598   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
1599   if ( V3dView.IsNull() ) return 1;
1600
1601   if ( argc != 4 ) {
1602     di << argv[0] << "Invalid number of arguments" << "\n";
1603     return 1;
1604   }
1605   V3dView->SetAxialScale( atof(argv[1]),  atof(argv[2]),  atof(argv[3]) );
1606   return 0;
1607 }
1608 //==============================================================================
1609 //function : VTestZBuffTrihedron
1610 //purpose  : Displays a V3d_ZBUFFER'ed trihedron at the bottom left corner of the view
1611 //==============================================================================
1612
1613 static int VTestZBuffTrihedron(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
1614 {
1615   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
1616   if ( V3dView.IsNull() ) return 1;
1617
1618   // Set up default trihedron parameters
1619   V3dView->ZBufferTriedronSetup();
1620   V3dView->TriedronDisplay( Aspect_TOTP_LEFT_LOWER, Quantity_NOC_WHITE, 0.1, V3d_ZBUFFER );
1621   V3dView->ZFitAll();
1622   return 0;
1623 }
1624
1625 //==============================================================================
1626 //function : VRotate
1627 //purpose  : Camera Rotating
1628 //==============================================================================
1629
1630 static int VRotate( Draw_Interpretor& di, Standard_Integer argc, const char** argv ) {
1631   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
1632   if ( V3dView.IsNull() ) {
1633     return 1;
1634   }
1635
1636   if ( argc == 4 ) {
1637     V3dView->Rotate( atof(argv[1]), atof(argv[2]), atof(argv[3]) );
1638     return 0;
1639   } else if ( argc == 7 ) {
1640     V3dView->Rotate( atof(argv[1]), atof(argv[2]), atof(argv[3]), atof(argv[4]), atof(argv[5]), atof(argv[6]) );
1641     return 0;
1642   } else {
1643     di << argv[0] << " Invalid number of arguments" << "\n";
1644     return 1;
1645   }
1646 }
1647
1648 //==============================================================================
1649 //function : VZoom
1650 //purpose  : View zoom in / out (relative to current zoom)
1651 //==============================================================================
1652
1653 static int VZoom( Draw_Interpretor& di, Standard_Integer argc, const char** argv ) {
1654   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
1655   if ( V3dView.IsNull() ) {
1656     return 1;
1657   }
1658
1659   if ( argc == 2 ) {
1660     Standard_Real coef = atof(argv[1]);
1661     if ( coef <= 0.0 ) {
1662       di << argv[1] << "Invalid value" << "\n";
1663       return 1;
1664     }
1665     V3dView->SetZoom( atof(argv[1]) );
1666     return 0;
1667   } else {
1668     di << argv[0] << " Invalid number of arguments" << "\n";
1669     return 1;
1670   }
1671 }
1672
1673 //==============================================================================
1674 //function : VPan
1675 //purpose  : View panning (in pixels)
1676 //==============================================================================
1677
1678 static int VPan( Draw_Interpretor& di, Standard_Integer argc, const char** argv ) {
1679   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
1680   if ( V3dView.IsNull() ) return 1;
1681
1682   if ( argc == 3 ) {
1683     V3dView->Pan( atoi(argv[1]), atoi(argv[2]) );
1684     return 0;
1685   } else {
1686     di << argv[0] << " Invalid number of arguments" << "\n";
1687     return 1;
1688   }
1689 }
1690
1691
1692 //==============================================================================
1693 //function : VExport
1694 //purpose  : Export the view to a vector graphic format (PS, EMF, PDF)
1695 //==============================================================================
1696
1697 static int VExport(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
1698 {
1699   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
1700   if (V3dView.IsNull())
1701     return 1;
1702
1703   if (argc == 1)
1704   {
1705     std::cout << "Usage: " << argv[0] << " Filename [Format]\n";
1706     return 1;
1707   }
1708
1709   Graphic3d_ExportFormat anExpFormat = Graphic3d_EF_PDF;
1710   TCollection_AsciiString aFormatStr;
1711
1712   TCollection_AsciiString aFileName (argv[1]);
1713   Standard_Integer aLen = aFileName.Length();
1714
1715   if (argc > 2)
1716   {
1717     aFormatStr = TCollection_AsciiString (argv[2]);
1718   }
1719   else if (aLen >= 4)
1720   {
1721     if (aFileName.Value (aLen - 2) == '.')
1722     {
1723       aFormatStr = aFileName.SubString (aLen - 1, aLen);
1724     }
1725     else if (aFileName.Value (aLen - 3) == '.')
1726     {
1727       aFormatStr = aFileName.SubString (aLen - 2, aLen);
1728     }
1729     else
1730     {
1731       std::cout << "Export format couln't be detected from filename '" << argv[1] << "'\n";
1732       return 1;
1733     }
1734   }
1735   else
1736   {
1737     std::cout << "Export format couln't be detected from filename '" << argv[1] << "'\n";
1738     return 1;
1739   }
1740
1741   aFormatStr.UpperCase();
1742   if (aFormatStr == "PS")
1743     anExpFormat = Graphic3d_EF_PostScript;
1744   else if (aFormatStr == "EPS")
1745     anExpFormat = Graphic3d_EF_EnhPostScript;
1746   else if (aFormatStr == "TEX")
1747     anExpFormat = Graphic3d_EF_TEX;
1748   else if (aFormatStr == "PDF")
1749     anExpFormat = Graphic3d_EF_PDF;
1750   else if (aFormatStr == "SVG")
1751     anExpFormat = Graphic3d_EF_SVG;
1752   else if (aFormatStr == "PGF")
1753     anExpFormat = Graphic3d_EF_PGF;
1754   else if (aFormatStr == "EMF")
1755     anExpFormat = Graphic3d_EF_EMF;
1756   else
1757   {
1758     std::cout << "Invalid export format '" << aFormatStr << "'\n";
1759     return 1;
1760   }
1761
1762   if (!V3dView->View()->Export (argv[1], anExpFormat))
1763   {
1764     std::cout << "Export failed!\n";
1765     return 1;
1766   }
1767   return 0;
1768 }
1769
1770 //==============================================================================
1771 //function : VColorScale
1772 //purpose  : representation color scale
1773 //==============================================================================
1774 #include <V3d_ColorScale.hxx>
1775
1776 static int VColorScale (Draw_Interpretor& di, Standard_Integer argc, const char ** argv)
1777 {
1778   if ( argc != 1 && argc != 4 && argc != 5 && argc != 6 && argc != 8 )
1779   {
1780     di << "Usage : " << argv[0] << " [RangeMin = 0 RangeMax = 100 Intervals = 10 HeightFont = 16 Position = Right X = 0 Y = 0]  " << "\n";
1781     return 1;
1782   }
1783
1784   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
1785   if(aContext.IsNull()) {
1786     di << argv[0] << " ERROR : use 'vinit' command before " << "\n";
1787     return -1;
1788   }
1789
1790   Standard_Real minRange = 0. , maxRange = 100. ;
1791
1792   Standard_Integer numIntervals = 10 ;
1793   Standard_Real textHeight = 16. ;
1794   Aspect_TypeOfColorScalePosition position = Aspect_TOCSP_RIGHT;
1795   Standard_Real X = 0., Y = 0. ;
1796
1797   if ( argc < 9 )
1798   {
1799      if( argc > 3 )
1800      {
1801        minRange = atof( argv[1] );
1802        maxRange = atof( argv[2] );
1803        numIntervals = atoi( argv[3] );
1804      }
1805      if ( argc > 4 )
1806        textHeight = atof( argv[4] );
1807      if ( argc > 5 )
1808        position = (Aspect_TypeOfColorScalePosition)atoi( argv[5] );
1809      if ( argc > 7 )
1810      {
1811        X = atof( argv[6] );
1812        Y = atof( argv[7] );
1813      }
1814   }
1815   Handle(V3d_View) curView = ViewerTest::CurrentView( );
1816   if ( curView.IsNull( ) )
1817     return 1;
1818   Handle(Aspect_ColorScale) aCSV = curView->ColorScale( );
1819   Handle(V3d_ColorScale) aCS = ( Handle( V3d_ColorScale )::DownCast( aCSV ) );
1820   if( ! aCS.IsNull( ) )
1821   {
1822     aCS->SetPosition( X , Y );
1823     aCS->SetHeight( 0.95) ;
1824     aCS->SetTextHeight( textHeight );
1825     aCS->SetRange( minRange , maxRange );
1826     aCS->SetNumberOfIntervals( numIntervals );
1827     aCS->SetLabelPosition( position );
1828     if( !curView->ColorScaleIsDisplayed() )
1829       curView->ColorScaleDisplay( );
1830   }
1831   return 0;
1832 }
1833
1834 //==============================================================================
1835 //function : VGraduatedTrihedron
1836 //purpose  : Displays a graduated trihedron
1837 //==============================================================================
1838
1839 static void AddMultibyteString (TCollection_ExtendedString &name, const char *arg)
1840 {
1841   const char *str = arg;
1842   while (*str)
1843   {
1844     unsigned short c1 = *str++;
1845     unsigned short c2 = *str++;
1846     if (!c1 || !c2) break;
1847     name += (Standard_ExtCharacter)((c1 << 8) | c2);
1848   }
1849 }
1850
1851 static int VGraduatedTrihedron(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
1852 {
1853   // Check arguments
1854   if (argc != 2 && argc < 5)
1855   {
1856     di<<"Error: "<<argv[0]<<" - invalid number of arguments\n";
1857     di<<"Usage: type help "<<argv[0]<<"\n";
1858     return 1; //TCL_ERROR
1859   }
1860
1861   Handle(V3d_View) aV3dView = ViewerTest::CurrentView();
1862
1863   // Create 3D view if it doesn't exist
1864   if ( aV3dView.IsNull() )
1865   {
1866     ViewerTest::ViewerInit(); 
1867     aV3dView = ViewerTest::CurrentView();
1868     if( aV3dView.IsNull() )
1869     {
1870       di << "Error: Cannot create a 3D view\n";
1871       return 1; //TCL_ERROR
1872     }
1873   }
1874
1875   // Erase (==0) or display (!=0)
1876   const int display = atoi(argv[1]);
1877
1878   if (display)
1879   {
1880     // Text font
1881     TCollection_AsciiString font;
1882     if (argc < 6)
1883       font.AssignCat("Courier");
1884     else
1885       font.AssignCat(argv[5]);
1886
1887     // Text is multibyte
1888     const Standard_Boolean isMultibyte = (argc < 7)? Standard_False : (atoi(argv[6]) != 0);
1889
1890     // Set axis names
1891     TCollection_ExtendedString xname, yname, zname;
1892     if (argc >= 5)
1893     {
1894       if (isMultibyte)
1895       {
1896         AddMultibyteString(xname, argv[2]);
1897         AddMultibyteString(yname, argv[3]);
1898         AddMultibyteString(zname, argv[4]);
1899       }
1900       else
1901       {
1902         xname += argv[2];
1903         yname += argv[3];
1904         zname += argv[4];
1905       }
1906     }
1907     else
1908     {
1909       xname += "X (mm)";
1910       yname += "Y (mm)";
1911       zname += "Z (mm)";
1912     }
1913
1914     aV3dView->GraduatedTrihedronDisplay(xname, yname, zname,
1915                                         Standard_True/*xdrawname*/, Standard_True/*ydrawname*/, Standard_True/*zdrawname*/,
1916                                         Standard_True/*xdrawvalues*/, Standard_True/*ydrawvalues*/, Standard_True/*zdrawvalues*/,
1917                                         Standard_True/*drawgrid*/,
1918                                         Standard_True/*drawaxes*/,
1919                                         5/*nbx*/, 5/*nby*/, 5/*nbz*/,
1920                                         10/*xoffset*/, 10/*yoffset*/, 10/*zoffset*/,
1921                                         30/*xaxisoffset*/, 30/*yaxisoffset*/, 30/*zaxisoffset*/,
1922                                         Standard_True/*xdrawtickmarks*/, Standard_True/*ydrawtickmarks*/, Standard_True/*zdrawtickmarks*/,
1923                                         10/*xtickmarklength*/, 10/*ytickmarklength*/, 10/*ztickmarklength*/,
1924                                         Quantity_NOC_WHITE/*gridcolor*/,
1925                                         Quantity_NOC_RED/*xnamecolor*/,Quantity_NOC_GREEN/*ynamecolor*/,Quantity_NOC_BLUE1/*znamecolor*/,
1926                                         Quantity_NOC_RED/*xcolor*/,Quantity_NOC_GREEN/*ycolor*/,Quantity_NOC_BLUE1/*zcolor*/,font);
1927   }
1928   else
1929     aV3dView->GraduatedTrihedronErase();
1930
1931   ViewerTest::GetAISContext()->UpdateCurrentViewer();
1932   aV3dView->Redraw();
1933
1934   return 0;
1935 }
1936
1937 //==============================================================================
1938 //function : VPrintView
1939 //purpose  : Test printing algorithm, print the view to image file with given
1940 //           width and height. Printing implemented only for WNT.
1941 //==============================================================================
1942 static int VPrintView (Draw_Interpretor& di, Standard_Integer argc, 
1943                        const char** argv)
1944 {
1945 #ifndef WNT
1946   di << "Printing implemented only for wnt!\n";
1947   return 1;
1948 #else
1949
1950   Handle(AIS_InteractiveContext) aContextAIS = NULL;
1951   Handle(V3d_View) aView = NULL;
1952   aContextAIS = ViewerTest::GetAISContext();
1953   if (!aContextAIS.IsNull())
1954   {
1955     const Handle(V3d_Viewer)& Vwr = aContextAIS->CurrentViewer();
1956     Vwr->InitActiveViews();
1957     if(Vwr->MoreActiveViews())
1958       aView = Vwr->ActiveView();
1959   }
1960
1961   // check for errors
1962   if (aView.IsNull())
1963   {
1964     di << "Call vinit before!\n";
1965     return 1;
1966   }
1967   else if (argc < 4)
1968   {
1969     di << "Use: " << argv[0];
1970     di << " width height filename [print algo=0]\n";
1971     di << "width, height of the intermediate buffer for operation\n";
1972     di << "algo : {0|1}\n";
1973     di << "        0 - stretch algorithm\n";
1974     di << "        1 - tile algorithm\n";
1975     di << "test printing algorithms into an intermediate buffer\n";
1976     di << "with saving output to an image file\n";
1977     return 1;
1978   }
1979
1980   // get the input params
1981   Standard_Integer aWidth  = atoi (argv[1]);
1982   Standard_Integer aHeight = atoi (argv[2]);
1983   Standard_Integer aMode   = 0;
1984   TCollection_AsciiString aFileName = TCollection_AsciiString (argv[3]);
1985   if (argc==5)
1986     aMode = atoi (argv[4]);
1987
1988   // check the input parameters
1989   if (aWidth <= 0 || aHeight <= 0)
1990   {
1991     di << "Width and height must be positive values!\n";
1992     return 1;
1993   }
1994   if (aMode != 0 && aMode != 1)
1995     aMode = 0;
1996
1997   Image_CRawBufferData aRawBuffer;
1998   HDC anDC = CreateCompatibleDC(0);
1999
2000   // define compatible bitmap
2001   BITMAPINFO aBitmapData;
2002   memset (&aBitmapData, 0, sizeof (BITMAPINFOHEADER));
2003   aBitmapData.bmiHeader.biSize          = sizeof (BITMAPINFOHEADER);
2004   aBitmapData.bmiHeader.biWidth         = aWidth ;
2005   aBitmapData.bmiHeader.biHeight        = aHeight;
2006   aBitmapData.bmiHeader.biPlanes        = 1;
2007   aBitmapData.bmiHeader.biBitCount      = 24;
2008   aBitmapData.bmiHeader.biXPelsPerMeter = 0;
2009   aBitmapData.bmiHeader.biYPelsPerMeter = 0;
2010   aBitmapData.bmiHeader.biClrUsed       = 0;
2011   aBitmapData.bmiHeader.biClrImportant  = 0;
2012   aBitmapData.bmiHeader.biCompression   = BI_RGB;
2013   aBitmapData.bmiHeader.biSizeImage     = 0;
2014
2015   // Create Device Independent Bitmap
2016   HBITMAP aMemoryBitmap = CreateDIBSection (anDC, &aBitmapData, DIB_RGB_COLORS,
2017                                             &aRawBuffer.dataPtr, NULL, 0);
2018   HGDIOBJ anOldBitmap   = SelectObject(anDC, aMemoryBitmap);
2019
2020   Standard_Boolean isSaved = Standard_False, isPrinted = Standard_False;
2021   if (aRawBuffer.dataPtr != 0)
2022   {    
2023     if (aMode == 0)
2024       isPrinted = aView->Print(anDC,1,1,0,Aspect_PA_STRETCH);
2025     else
2026       isPrinted = aView->Print(anDC,1,1,0,Aspect_PA_TILE);
2027
2028     // succesfully printed into an intermediate buffer
2029     if (isPrinted)
2030     {
2031       Handle(Image_PixMap) anImageBitmap =
2032                          new Image_PixMap ((Standard_PByte)aRawBuffer.dataPtr,
2033                                            aWidth, aHeight,
2034                                            aWidth*3 + aWidth%4, 24, 0);
2035       isSaved = anImageBitmap->Dump(aFileName.ToCString());
2036     }
2037     else
2038     {
2039       di << "Print operation failed due to printing errors or\n";
2040       di << "insufficient memory available\n";
2041       di << "Please, try to use smaller dimensions for this test\n";
2042       di << "command, as it allocates intermediate buffer for storing\n";
2043       di << "the result\n";
2044     }
2045   }
2046   else
2047   {
2048     di << "Can't allocate memory for intermediate buffer\n";
2049     di << "Please use smaller dimensions\n";
2050   }
2051
2052   if (aMemoryBitmap)
2053   {
2054     SelectObject (anDC, anOldBitmap);
2055     DeleteObject (aMemoryBitmap);
2056     DeleteDC(anDC);
2057   }
2058
2059   if (!isSaved)
2060   {
2061     di << "Save to file operation failed. This operation may fail\n";
2062     di << "if you don't have enough available memory, then you can\n";
2063     di << "use smaller dimensions for the output file\n";
2064     return 1;
2065   }
2066
2067   return 0;
2068
2069 #endif
2070 }
2071
2072 //==============================================================================
2073 //function : VZLayer
2074 //purpose  : Test z layer operations for v3d viewer
2075 //==============================================================================
2076 static int VZLayer (Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2077 {
2078   Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext ();
2079   if (aContextAIS.IsNull())
2080   {
2081     di << "Call vinit before!\n";
2082     return 1;
2083   }
2084   else if (argc < 2)
2085   {
2086     di << "Use: vzlayer " << argv[0];
2087     di << " add/del/get [id]\n";
2088     di << " add - add new z layer to viewer and print its id\n";
2089     di << " del - del z layer by its id\n";
2090     di << " get - print sequence of z layers in increasing order of their overlay level\n";
2091     di << "id - the layer identificator value defined when removing z layer\n";
2092     return 1;
2093   }
2094
2095   const Handle(V3d_Viewer)& aViewer = aContextAIS->CurrentViewer();
2096   if (aViewer.IsNull())
2097   {
2098     di << "No active viewer!\n";
2099     return 1;
2100   }
2101
2102   // perform operation
2103   TCollection_AsciiString anOp = TCollection_AsciiString (argv[1]);
2104   if (anOp == "add")
2105   {
2106     Standard_Integer aNewId;
2107     if (!aViewer->AddZLayer (aNewId))
2108     {
2109       di << "Impossible to add new z layer!\n";
2110       return 1;
2111     }
2112
2113     di << "New z layer added with index: " << aNewId << "\n";
2114   }
2115   else if (anOp == "del")
2116   {
2117     if (argc < 3)
2118     {
2119       di << "Please also provide as argument id of z layer to remove\n";
2120       return 1;
2121     }
2122
2123     Standard_Integer aDelId = atoi (argv[2]);
2124     if (!aViewer->RemoveZLayer (aDelId))
2125     {
2126       di << "Impossible to remove the z layer or invalid id!\n";
2127       return 1;
2128     }
2129
2130     di << "Z layer " << aDelId << " has been removed\n";
2131   }
2132   else if (anOp == "get")
2133   {
2134     TColStd_SequenceOfInteger anIds;
2135     aViewer->GetAllZLayers (anIds);
2136     for (Standard_Integer aSeqIdx = 1; aSeqIdx <= anIds.Length(); aSeqIdx++)
2137     {
2138       di << anIds.Value (aSeqIdx) << " ";
2139     }
2140
2141     di << "\n";
2142   }
2143   else
2144   {
2145     di << "Invalid operation, please use { add / del / get }\n";
2146     return 1;
2147   }
2148
2149   return 0;
2150 }
2151
2152 DEFINE_STANDARD_HANDLE(V3d_TextItem, Visual3d_LayerItem)
2153
2154 // this class provides a presentation of text item in v3d view under-/overlayer
2155 class V3d_TextItem : public Visual3d_LayerItem
2156 {
2157 public:
2158
2159   // CASCADE RTTI
2160   DEFINE_STANDARD_RTTI(V3d_TextItem)
2161
2162   // constructor
2163   Standard_EXPORT V3d_TextItem(const TCollection_AsciiString& theText,
2164                                const Standard_Real theX1,
2165                                const Standard_Real theY1,
2166                                const Standard_Real theHeight,
2167                                const TCollection_AsciiString& theFontName,
2168                                const Quantity_Color& theColor,
2169                                const Quantity_Color& theSubtitleColor,
2170                                const Aspect_TypeOfDisplayText& theTypeOfDisplay,
2171                                const Handle(Visual3d_Layer)& theLayer);
2172
2173   // redraw method
2174   Standard_EXPORT void RedrawLayerPrs();
2175
2176 private:
2177
2178   Standard_Real            myX1;
2179   Standard_Real            myY1;
2180   Standard_Real            myHeight;
2181   TCollection_AsciiString  myText;
2182   TCollection_AsciiString  myFontName;
2183   Quantity_Color           myColor;
2184   Quantity_Color           mySubtitleColor;
2185   Aspect_TypeOfDisplayText myType;
2186   Handle(Visual3d_Layer)   myLayer;
2187
2188 };
2189
2190 IMPLEMENT_STANDARD_HANDLE(V3d_TextItem, Visual3d_LayerItem)
2191 IMPLEMENT_STANDARD_RTTIEXT(V3d_TextItem, Visual3d_LayerItem)
2192
2193 // create and add to display the text item
2194 V3d_TextItem::V3d_TextItem (const TCollection_AsciiString& theText,
2195                             const Standard_Real theX1,
2196                             const Standard_Real theY1,
2197                             const Standard_Real theHeight,
2198                             const TCollection_AsciiString& theFontName,
2199                             const Quantity_Color& theColor,
2200                             const Quantity_Color& theSubtitleColor,
2201                             const Aspect_TypeOfDisplayText& theTypeOfDisplay,
2202                             const Handle(Visual3d_Layer)& theLayer)
2203  : myX1 (theX1), myY1 (theY1),
2204    myText (theText),
2205    myHeight (theHeight),
2206    myLayer (theLayer),
2207    myColor (theColor),
2208    mySubtitleColor (theSubtitleColor),
2209    myType (theTypeOfDisplay),
2210    myFontName (theFontName)
2211 {
2212   if (!myLayer.IsNull ())
2213     myLayer->AddLayerItem (this);
2214 }
2215
2216 // render item
2217 void V3d_TextItem::RedrawLayerPrs ()
2218
2219   if (myLayer.IsNull ())
2220     return;
2221
2222   myLayer->SetColor (myColor);
2223   myLayer->SetTextAttributes (myFontName.ToCString (), myType, mySubtitleColor);
2224   myLayer->DrawText (myText.ToCString (), myX1, myY1, myHeight);
2225 }
2226
2227 //=======================================================================
2228 //function : VOverlayText
2229 //purpose  : Test text displaying in view overlay
2230 //=======================================================================
2231 static int VOverlayText (Draw_Interpretor& di, Standard_Integer argc, const char**argv)
2232 {
2233   // get the active view
2234   Handle(V3d_View) aView = ViewerTest::CurrentView();
2235   if (aView.IsNull())
2236   {
2237     di << "No active view. Please call vinit.\n";
2238     return 1;
2239   }
2240   else if (argc < 4 || argc > 13)
2241   {
2242     di << "Use: " << argv[0];
2243     di << " text x y [height] [font_name] [text_color: R G B] [displayType]\n";
2244     di << "[background_color: R G B]\n";
2245     di << "  height - pixel height of the text (default=10.0)\n";
2246     di << "  font_name - name of font (default=courier)\n";
2247     di << "  text_color - R G B values of text color (default=255.0 255.0 255.0)\n";
2248     di << "  display_type = {normal/subtitle/decal/blend}, (default=normal)\n";
2249     di << "  background_color- R G B values used for subtitle and decal text\n";
2250     di << "(default=255.0 255.0 255.0)\n";
2251     return 1;
2252   }
2253   
2254   TCollection_AsciiString aText (argv[1]);
2255   Standard_Real aPosX = atof(argv[2]);
2256   Standard_Real aPosY = atof(argv[3]);
2257   Standard_Real aHeight = (argc >= 5) ? atof (argv[4]) : 10.0;
2258
2259   // font name
2260   TCollection_AsciiString aFontName = "Courier";
2261   if (argc >= 6)
2262     aFontName = TCollection_AsciiString (argv[5]);
2263
2264   // text colors
2265   Quantity_Parameter aColorRed   = 1.0;
2266   Quantity_Parameter aColorGreen = 1.0;
2267   Quantity_Parameter aColorBlue  = 1.0;
2268   if (argc >= 9)
2269   {
2270     aColorRed   = atof (argv[6])/255.;
2271     aColorGreen = atof (argv[7])/255.;
2272     aColorBlue  = atof (argv[8])/255.;
2273   }
2274
2275   // display type
2276   TCollection_AsciiString aDispStr;
2277   if (argc >= 10)
2278     aDispStr = TCollection_AsciiString (argv[9]);
2279
2280   Aspect_TypeOfDisplayText aTextType = Aspect_TODT_NORMAL;
2281   if (aDispStr.IsEqual ("subtitle"))
2282     aTextType = Aspect_TODT_SUBTITLE;
2283   else if (aDispStr.IsEqual ("decal"))
2284     aTextType = Aspect_TODT_DEKALE;
2285   else if (aDispStr.IsEqual ("blend"))
2286     aTextType = Aspect_TODT_BLEND;
2287
2288   // subtitle color
2289   Quantity_Parameter aSubRed   = 1.0;
2290   Quantity_Parameter aSubGreen = 1.0;
2291   Quantity_Parameter aSubBlue  = 1.0;
2292   if (argc == 13)
2293   {
2294     aSubRed   = atof (argv[10])/255.;
2295     aSubGreen = atof (argv[11])/255.;
2296     aSubBlue  = atof (argv[12])/255.;
2297   }
2298
2299   // check fo current overlay
2300   Handle(Visual3d_Layer) anOverlay = aView->Viewer()->Viewer()->OverLayer ();
2301   if (anOverlay.IsNull ())
2302   {
2303     Handle(V3d_LayerMgr) aMgr = new V3d_LayerMgr (aView);
2304     anOverlay = aMgr->Overlay ();
2305     aView->SetLayerMgr (aMgr);
2306   }
2307
2308   Quantity_Color aTextColor (aColorRed, aColorGreen, 
2309     aColorBlue, Quantity_TOC_RGB);
2310   Quantity_Color aSubtColor (aSubRed, aSubGreen, 
2311     aSubBlue, Quantity_TOC_RGB);
2312
2313   // add text item
2314   Handle(V3d_TextItem) anItem = new V3d_TextItem (aText, aPosX, aPosY,
2315     aHeight, aFontName, aTextColor, aSubtColor, aTextType, anOverlay);
2316
2317   // update view
2318   aView->MustBeResized();
2319   aView->Redraw();
2320
2321   return 0;
2322 }
2323
2324 //=======================================================================
2325 //function : ViewerCommands
2326 //purpose  :
2327 //=======================================================================
2328
2329 void ViewerTest::ViewerCommands(Draw_Interpretor& theCommands)
2330 {
2331
2332   const char *group = "ZeViewer";
2333   theCommands.Add("vinit" ,
2334     "vinit            : vinit [leftPx topPx widthPx heightPx] : Create the Viewer window",
2335     __FILE__,VInit,group);
2336   theCommands.Add("vhelp" ,
2337     "vhelp            : display help on the viewer commands",
2338     __FILE__,VHelp,group);
2339   theCommands.Add("vtop" ,
2340     "vtop or <T>         : Top view" ,
2341     __FILE__,VTop,group);
2342   theCommands.Add("vaxo" ,
2343     " vaxo or <A>     : Axonometric view ",
2344     __FILE__,VAxo,group);
2345   theCommands.Add("vpick" ,
2346     "vpick           : vpick X Y Z [shape subshape] ( all variables as string )",
2347     VPick,group);
2348   theCommands.Add("vfit"    ,
2349     "vfit or <F>         : vfit",
2350     __FILE__,VFit,group);
2351   theCommands.Add("vzfit"    ,
2352     "vzfit",
2353     __FILE__,VZFit,group);
2354   theCommands.Add("vrepaint",
2355     "vrepaint        : vrepaint, force redraw",
2356     __FILE__,VRepaint,group);
2357   theCommands.Add("vclear",
2358     "vclear          : vclear",
2359     __FILE__,VClear,group);
2360   theCommands.Add("vsetbg",
2361     "vsetbg          : vsetbg imagefile [filltype] : Load image as background",
2362     __FILE__,VSetBg,group);
2363   theCommands.Add("vsetbgmode",
2364     "vsetbgmode      : vsetbgmode filltype : Change background image fill type",
2365     __FILE__,VSetBgMode,group);
2366   theCommands.Add("vsetgradientbg",
2367     "vsetgradientbg  : vsetgradientbg r1 g1 b1 r2 g2 b2 filltype : Mount gradient background",
2368     __FILE__,VSetGradientBg,group);
2369   theCommands.Add("vsetgrbgmode",
2370     "vsetgrbgmode    : vsetgrbgmode filltype : Change gradient background fill type",
2371     __FILE__,VSetGradientBgMode,group);
2372   theCommands.Add("vsetcolorbg",
2373     "vsetcolorbg     : vsetcolorbg r g b : Set background color",
2374     __FILE__,VSetColorBg,group);
2375   theCommands.Add("vscale",
2376     "vscale          : vscale X Y Z",
2377     __FILE__,VScale,group);
2378   theCommands.Add("vzbufftrihedron",
2379     "vzbufftrihedron : Displays a V3d_ZBUFFER'ed trihedron at the bottom left corner of the view",
2380     __FILE__,VTestZBuffTrihedron,group);
2381   theCommands.Add("vrotate",
2382     "vrotate         : vrotate AX AY AZ [X Y Z]",
2383     __FILE__,VRotate,group);
2384   theCommands.Add("vzoom",
2385     "vzoom           : vzoom coef",
2386     __FILE__,VZoom,group);
2387   theCommands.Add("vpan",
2388     "vpan            : vpan dx dy",
2389     __FILE__,VPan,group);
2390   theCommands.Add("vexport",
2391     "vexport         : vexport full_file_path {PS | EPS | TEX | PDF | SVG | PGF | EMF }"
2392     " : exports the view to a vector file of a given format"
2393     " : notice that EMF format requires patched gl2ps",
2394     __FILE__,VExport,group);
2395   theCommands.Add("vcolorscale",
2396     "vcolorscale     : vcolorscale [RangeMin = 0 RangeMax = 100 Intervals = 10 HeightFont = 16 Position = 2 X = 0 Y = 0]: draw color scale",
2397     __FILE__,VColorScale,group);
2398   theCommands.Add("vgraduatedtrihedron",
2399     "vgraduatedtrihedron : 1/0 (display/erase) [Xname Yname Zname [Font [isMultibyte]]]",
2400     __FILE__,VGraduatedTrihedron,group);
2401   theCommands.Add("vprintview" ,
2402     "vprintview : width height filename [algo=0] : Test print algorithm: algo = 0 - stretch, algo = 1 - tile",
2403     __FILE__,VPrintView,group);
2404   theCommands.Add("vzlayer",
2405     "vzlayer : add/del/get [id] : Z layer operations in v3d viewer: add new z layer, delete z layer, get z layer ids",
2406     __FILE__,VZLayer,group);
2407   theCommands.Add("voverlaytext",
2408     "voverlaytext : text x y [height] [font_name] [text_color: R G B] [display_type] [background_color: R G B]"
2409     " : height - pixel height of the text (default=10.0)"
2410     " : font_name - name of font (default=courier)"
2411     " : text_color - three values: RedColor GreenColor BlueColor (default = 255.0 255.0 255.0) "
2412     " : display_type = {normal/subtitle/decal/blend}, (default=normal) "
2413     " : background_color - three values: RedColor GreenColor BlueColor (default = 255.0 255.0 255.0), the parameter is defined for subtitle and decal display types ",
2414     __FILE__,VOverlayText,group);
2415 }