c466b685596ca3d3cf07dbac82db5bf3dfaec7d7
[occt.git] / src / ViewerTest / ViewerTest_ViewerCommands.cxx
1 // Created on: 1998-09-01
2 // Created by: Robert COUBLANC
3 // Copyright (c) 1998-1999 Matra Datavision
4 // Copyright (c) 1999-2012 OPEN CASCADE SAS
5 //
6 // The content of this file is subject to the Open CASCADE Technology Public
7 // License Version 6.5 (the "License"). You may not use the content of this file
8 // except in compliance with the License. Please obtain a copy of the License
9 // at http://www.opencascade.org and read it completely before using this file.
10 //
11 // The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
12 // main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
13 //
14 // The Original Code and all software distributed under the License is
15 // distributed on an "AS IS" basis, without warranty of any kind, and the
16 // Initial Developer hereby disclaims all such warranties, including without
17 // limitation, any warranties of merchantability, fitness for a particular
18 // purpose or non-infringement. Please see the License for the specific terms
19 // and conditions governing the rights and limitations under the License.
20
21 #ifdef HAVE_CONFIG_H
22   #include <config.h>
23 #endif
24
25 #include <OpenGl_GlCore20.hxx>
26 #include <AIS_Shape.hxx>
27 #include <AIS_Drawer.hxx>
28 #include <AIS_InteractiveObject.hxx>
29 #include <AIS_ListOfInteractive.hxx>
30 #include <AIS_ListIteratorOfListOfInteractive.hxx>
31 #include <DBRep.hxx>
32 #include <Graphic3d_AspectMarker3d.hxx>
33 #include <Graphic3d_ExportFormat.hxx>
34 #include <Graphic3d_NameOfTextureEnv.hxx>
35 #include <Graphic3d_TextureEnv.hxx>
36 #include <Graphic3d_TextureParams.hxx>
37 #include <Graphic3d_TypeOfTextureFilter.hxx>
38 #include <Graphic3d_AspectFillArea3d.hxx>
39 #include <ViewerTest.hxx>
40 #include <ViewerTest_EventManager.hxx>
41 #include <ViewerTest_DoubleMapOfInteractiveAndName.hxx>
42 #include <ViewerTest_DoubleMapIteratorOfDoubleMapOfInteractiveAndName.hxx>
43 #include <Visual3d_View.hxx>
44 #include <Visual3d_ViewManager.hxx>
45 #include <V3d_LayerMgr.hxx>
46 #include <NCollection_DoubleMap.hxx>
47 #include <NCollection_List.hxx>
48 #include <NCollection_Vector.hxx>
49 #include <NIS_View.hxx>
50 #include <NIS_Triangulated.hxx>
51 #include <NIS_InteractiveContext.hxx>
52 #include <AIS_InteractiveContext.hxx>
53 #include <Draw_Interpretor.hxx>
54 #include <Draw.hxx>
55 #include <Draw_Appli.hxx>
56 #include <Aspect_PrintAlgo.hxx>
57 #include <Image_AlienPixMap.hxx>
58 #include <OpenGl_GraphicDriver.hxx>
59 #include <OSD_Timer.hxx>
60 #include <TColStd_SequenceOfInteger.hxx>
61 #include <TColStd_HSequenceOfReal.hxx>
62 #include <TColgp_Array1OfPnt2d.hxx>
63 #include <Visual3d_LayerItem.hxx>
64 #include <V3d_LayerMgr.hxx>
65 #include <V3d_LayerMgrPointer.hxx>
66 #include <Aspect_TypeOfLine.hxx>
67 #include <Image_Diff.hxx>
68 #include <Aspect_DisplayConnection.hxx>
69 #include <Graphic3d.hxx>
70 #include <gp_Pnt.hxx>
71 #include <gp_Dir.hxx>
72 #include <gp_Pln.hxx>
73 #include <PrsMgr_PresentableObject.hxx>
74 #include <Graphic3d_ClipPlane.hxx>
75 #include <NCollection_DataMap.hxx>
76 #include <Graphic3d_Texture2Dmanual.hxx>
77 #include <Prs3d_ShadingAspect.hxx>
78
79 #ifdef WNT
80 #undef DrawText
81 #endif
82
83 #include <Visual3d_Layer.hxx>
84 #include <cstdlib>
85
86 #if defined(_WIN32)
87   #include <WNT_WClass.hxx>
88   #include <WNT_Window.hxx>
89
90   #if defined(_MSC_VER)
91     #define _CRT_SECURE_NO_DEPRECATE
92     #pragma warning (disable:4996)
93   #endif
94 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
95   #include <Cocoa_Window.hxx>
96   #include <tk.h>
97 #else
98   #include <Xw_Window.hxx>
99   #include <X11/Xlib.h> /* contains some dangerous #defines such as Status, True etc. */
100   #include <X11/Xutil.h>
101   #include <tk.h>
102 #endif
103
104 // Auxiliary definitions
105 static const char THE_KEY_DELETE = 127;
106
107 //==============================================================================
108 //  VIEWER GLOBAL VARIABLES
109 //==============================================================================
110
111 Standard_IMPORT Standard_Boolean Draw_VirtualWindows;
112 Standard_IMPORT Standard_Boolean Draw_Interprete (const char* theCommand);
113
114 Standard_EXPORT int ViewerMainLoop(Standard_Integer , const char** argv);
115 extern const Handle(NIS_InteractiveContext)& TheNISContext();
116 extern ViewerTest_DoubleMapOfInteractiveAndName& GetMapOfAIS();
117
118 extern int VErase (Draw_Interpretor& theDI,
119                    Standard_Integer  theArgNb,
120                    const char**      theArgVec);
121
122 #if defined(_WIN32)
123 static Handle(WNT_Window)& VT_GetWindow() {
124   static Handle(WNT_Window) WNTWin;
125   return WNTWin;
126 }
127 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
128 static Handle(Cocoa_Window)& VT_GetWindow()
129 {
130   static Handle(Cocoa_Window) aWindow;
131   return aWindow;
132 }
133 extern void ViewerTest_SetCocoaEventManagerView (const Handle(Cocoa_Window)& theWindow);
134 extern void SetCocoaWindowTitle (const Handle(Cocoa_Window)& theWindow, Standard_CString theTitle);
135 extern void GetCocoaScreenResolution (Standard_Integer& theWidth, Standard_Integer& theHeight);
136
137 #else
138 static Handle(Xw_Window)& VT_GetWindow(){
139   static Handle(Xw_Window) XWWin;
140   return XWWin;
141 }
142
143 static void VProcessEvents(ClientData,int);
144 #endif
145
146 static Handle(Aspect_DisplayConnection)& GetDisplayConnection()
147 {
148   static Handle(Aspect_DisplayConnection) aDisplayConnection;
149   return aDisplayConnection;
150 }
151
152 static void SetDisplayConnection (const Handle(Aspect_DisplayConnection)& theDisplayConnection)
153 {
154   GetDisplayConnection() = theDisplayConnection;
155 }
156
157 #if defined(_WIN32) || (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
158 Aspect_Handle GetWindowHandle(const Handle(Aspect_Window)& theWindow)
159 {
160   Aspect_Handle aWindowHandle = (Aspect_Handle)NULL;
161 #if defined(_WIN32)
162   const Handle (WNT_Window) aWindow = Handle(WNT_Window)::DownCast (theWindow);
163   if (!aWindow.IsNull())
164     return aWindow->HWindow();
165 #elif (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
166   const Handle (Xw_Window) aWindow = Handle(Xw_Window)::DownCast (theWindow);
167   if (!aWindow.IsNull())
168   return aWindow->XWindow();
169 #endif
170   return aWindowHandle;
171 }
172 #endif
173
174 static Standard_Boolean MyHLRIsOn = Standard_False;
175
176 NCollection_DoubleMap <TCollection_AsciiString, Handle(V3d_View)> ViewerTest_myViews;
177 static NCollection_DoubleMap <TCollection_AsciiString, Handle(AIS_InteractiveContext)>  ViewerTest_myContexts;
178 static NCollection_DoubleMap <TCollection_AsciiString, Handle(Graphic3d_GraphicDriver)> ViewerTest_myDrivers;
179 static OpenGl_Caps ViewerTest_myDefaultCaps;
180
181 #define ZCLIPWIDTH 1.
182
183 static void OSWindowSetup();
184
185 //==============================================================================
186 //  EVENT GLOBAL VARIABLES
187 //==============================================================================
188
189 static int Start_Rot = 0;
190 static int ZClipIsOn = 0;
191 int X_Motion = 0; // Current cursor position
192 int Y_Motion = 0;
193 int X_ButtonPress = 0; // Last ButtonPress position
194 int Y_ButtonPress = 0;
195 Standard_Boolean IsDragged = Standard_False;
196 Standard_Boolean DragFirst;
197
198 //==============================================================================
199
200 #ifdef WNT
201 static LRESULT WINAPI ViewerWindowProc(
202                                        HWND hwnd,
203                                        UINT uMsg,
204                                        WPARAM wParam,
205                                        LPARAM lParam );
206 static LRESULT WINAPI AdvViewerWindowProc(
207   HWND hwnd,
208   UINT uMsg,
209   WPARAM wParam,
210   LPARAM lParam );
211 #endif
212
213
214 //==============================================================================
215 //function : WClass
216 //purpose  :
217 //==============================================================================
218
219 const Handle(MMgt_TShared)& ViewerTest::WClass()
220 {
221   static Handle(MMgt_TShared) theWClass;
222 #if defined(_WIN32)
223   if (theWClass.IsNull())
224   {
225     theWClass = new WNT_WClass ("GW3D_Class", AdvViewerWindowProc,
226       CS_VREDRAW | CS_HREDRAW, 0, 0,
227       ::LoadCursor (NULL, IDC_ARROW));
228   }
229 #endif
230   return theWClass;
231 }
232
233 //==============================================================================
234 //function : CreateName
235 //purpose  : Create numerical name for new object in theMap
236 //==============================================================================
237 template <typename ObjectType>
238 TCollection_AsciiString CreateName (const NCollection_DoubleMap <TCollection_AsciiString, ObjectType>& theObjectMap,
239                                     const TCollection_AsciiString& theDefaultString)
240 {
241   if (theObjectMap.IsEmpty())
242     return theDefaultString + TCollection_AsciiString(1);
243
244   Standard_Integer aNextKey = 1;
245   Standard_Boolean isFound = Standard_False;
246   while (!isFound)
247   {
248     TCollection_AsciiString aStringKey = theDefaultString + TCollection_AsciiString(aNextKey);
249     // Look for objects with default names
250     if (theObjectMap.IsBound1(aStringKey))
251     {
252       aNextKey++;
253     }
254     else
255       isFound = Standard_True;
256   }
257
258   return theDefaultString + TCollection_AsciiString(aNextKey);
259 }
260
261 //==============================================================================
262 //structure : ViewerTest_Names
263 //purpose   : Allow to operate with full view name: driverName/viewerName/viewName
264 //==============================================================================
265 struct ViewerTest_Names
266 {
267 private:
268   TCollection_AsciiString myDriverName;
269   TCollection_AsciiString myViewerName;
270   TCollection_AsciiString myViewName;
271
272 public:
273
274   const TCollection_AsciiString& GetDriverName () const
275   {
276     return myDriverName;
277   }
278   void SetDriverName (const TCollection_AsciiString& theDriverName)
279   {
280     myDriverName = theDriverName;
281   }
282   const TCollection_AsciiString& GetViewerName () const
283   {
284     return myViewerName;
285   }
286   void SetViewerName (const TCollection_AsciiString& theViewerName)
287   {
288     myViewerName = theViewerName;
289   }
290   const TCollection_AsciiString& GetViewName () const
291   {
292     return myViewName;
293   }
294   void SetViewName (const TCollection_AsciiString& theViewName)
295   {
296     myViewName = theViewName;
297   }
298
299   //===========================================================================
300   //function : Constructor for ViewerTest_Names
301   //purpose  : Get view, viewer, driver names from custom string
302   //===========================================================================
303
304   ViewerTest_Names (const TCollection_AsciiString& theInputString)
305   {
306     TCollection_AsciiString aName(theInputString);
307     if (theInputString.IsEmpty())
308     {
309       // Get current configuration
310       if (ViewerTest_myDrivers.IsEmpty())
311         myDriverName = CreateName<Handle(Graphic3d_GraphicDriver)>
312           (ViewerTest_myDrivers, TCollection_AsciiString("Driver"));
313       else
314         myDriverName = ViewerTest_myDrivers.Find2
315         (ViewerTest::GetAISContext()->CurrentViewer()->Driver());
316
317       if(ViewerTest_myContexts.IsEmpty())
318       {
319         myViewerName = CreateName <Handle(AIS_InteractiveContext)>
320           (ViewerTest_myContexts, TCollection_AsciiString (myDriverName + "/Viewer"));
321       }
322       else
323         myViewerName = ViewerTest_myContexts.Find2 (ViewerTest::GetAISContext());
324
325         myViewName = CreateName <Handle(V3d_View)>
326           (ViewerTest_myViews, TCollection_AsciiString(myViewerName + "/View"));
327     }
328     else
329     {
330       // There is at least view name
331       Standard_Integer aParserNumber = 0;
332       for (Standard_Integer i = 0; i < 3; ++i)
333       {
334         Standard_Integer aParserPos = aName.SearchFromEnd("/");
335         if(aParserPos != -1)
336         {
337           aParserNumber++;
338           aName.Split(aParserPos-1);
339         }
340         else
341           break;
342       }
343       if (aParserNumber == 0)
344       {
345         // Only view name
346         if (!ViewerTest::GetAISContext().IsNull())
347         {
348           myDriverName = ViewerTest_myDrivers.Find2
349           (ViewerTest::GetAISContext()->CurrentViewer()->Driver());
350           myViewerName = ViewerTest_myContexts.Find2
351           (ViewerTest::GetAISContext());
352         }
353         else
354         {
355           // There is no opened contexts here, need to create names for viewer and driver
356           myDriverName = CreateName<Handle(Graphic3d_GraphicDriver)>
357             (ViewerTest_myDrivers, TCollection_AsciiString("Driver"));
358
359           myViewerName = CreateName <Handle(AIS_InteractiveContext)>
360             (ViewerTest_myContexts, TCollection_AsciiString (myDriverName + "/Viewer"));
361         }
362         myViewName = TCollection_AsciiString(myViewerName + "/" + theInputString);
363       }
364       else if (aParserNumber == 1)
365       {
366         // Here is viewerName/viewName
367         if (!ViewerTest::GetAISContext().IsNull())
368           myDriverName = ViewerTest_myDrivers.Find2
369           (ViewerTest::GetAISContext()->CurrentViewer()->Driver());
370         else
371         {
372           // There is no opened contexts here, need to create name for driver
373           myDriverName = CreateName<Handle(Graphic3d_GraphicDriver)>
374             (ViewerTest_myDrivers, TCollection_AsciiString("Driver"));
375         }
376         myViewerName = TCollection_AsciiString(myDriverName + "/" + aName);
377
378         myViewName = TCollection_AsciiString(myDriverName + "/" + theInputString);
379       }
380       else
381       {
382         //Here is driverName/viewerName/viewName
383         myDriverName = TCollection_AsciiString(aName);
384
385         TCollection_AsciiString aViewerName(theInputString);
386         aViewerName.Split(aViewerName.SearchFromEnd("/") - 1);
387         myViewerName = TCollection_AsciiString(aViewerName);
388
389         myViewName = TCollection_AsciiString(theInputString);
390       }
391     }
392   }
393 };
394
395 //==============================================================================
396 //function : FindContextByView
397 //purpose  : Find AIS_InteractiveContext by View
398 //==============================================================================
399
400 Handle(AIS_InteractiveContext) FindContextByView (const Handle(V3d_View)& theView)
401 {
402   Handle(AIS_InteractiveContext) anAISContext;
403
404   for (NCollection_DoubleMap<TCollection_AsciiString, Handle(AIS_InteractiveContext)>::Iterator
405        anIter (ViewerTest_myContexts); anIter.More(); anIter.Next())
406   {
407     if (anIter.Value()->CurrentViewer() == theView->Viewer())
408        return anIter.Key2();
409   }
410   return anAISContext;
411 }
412
413
414 //==============================================================================
415 //function : SetWindowTitle
416 //purpose  : Set window title
417 //==============================================================================
418
419 void SetWindowTitle (const Handle(Aspect_Window)& theWindow,
420                      Standard_CString theTitle)
421 {
422 #if defined(_WIN32)
423   SetWindowText ((HWND)Handle(WNT_Window)::DownCast(theWindow)->HWindow(),
424     theTitle);
425 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
426   SetCocoaWindowTitle (Handle(Cocoa_Window)::DownCast(theWindow), theTitle);
427 #else
428   if(GetDisplayConnection()->GetDisplay())
429   {
430     Window aWindow =
431       Handle(Xw_Window)::DownCast(theWindow)->XWindow();
432     XStoreName (GetDisplayConnection()->GetDisplay(), aWindow , theTitle);
433   }
434 #endif
435 }
436
437 //==============================================================================
438 //function : IsWindowOverlapped
439 //purpose  : Check if theWindow overlapp another view
440 //==============================================================================
441
442 Standard_Boolean IsWindowOverlapped (const Standard_Integer thePxLeft,
443                                      const Standard_Integer thePxTop,
444                                      const Standard_Integer thePxRight,
445                                      const Standard_Integer thePxBottom,
446                                      TCollection_AsciiString& theViewId)
447 {
448   for(NCollection_DoubleMap <TCollection_AsciiString, Handle(V3d_View)>::Iterator
449       anIter(ViewerTest_myViews); anIter.More(); anIter.Next())
450   {
451     Standard_Integer aTop = 0,
452       aLeft = 0,
453       aRight = 0,
454       aBottom = 0;
455     anIter.Value()->Window()->Position(aLeft, aTop, aRight, aBottom);
456     if ((thePxLeft >= aLeft && thePxLeft <= aRight && thePxTop >= aTop && thePxTop <= aBottom) ||
457         (thePxLeft >= aLeft && thePxLeft <= aRight && thePxBottom >= aTop && thePxBottom <= aBottom) ||
458         (thePxRight >= aLeft && thePxRight <= aRight && thePxTop >= aTop && thePxTop <= aBottom) ||
459         (thePxRight >= aLeft && thePxRight <= aRight && thePxBottom >= aTop && thePxBottom <= aBottom))
460     {
461       theViewId = anIter.Key1();
462       return Standard_True;
463     }
464   }
465   return Standard_False;
466 }
467
468 // Workaround: to create and delete non-orthographic views outside ViewerTest
469 void ViewerTest::RemoveViewName (const TCollection_AsciiString& theName)
470 {
471   ViewerTest_myViews.UnBind1 (theName);
472 }
473
474 void ViewerTest::InitViewName (const TCollection_AsciiString& theName,
475                                const Handle(V3d_View)& theView)
476 {
477   ViewerTest_myViews.Bind (theName, theView);
478 }
479
480 TCollection_AsciiString ViewerTest::GetCurrentViewName ()
481 {
482   return ViewerTest_myViews.Find2( ViewerTest::CurrentView());
483 }
484 //==============================================================================
485 //function : ViewerInit
486 //purpose  : Create the window viewer and initialize all the global variable
487 //==============================================================================
488
489 TCollection_AsciiString ViewerTest::ViewerInit (const Standard_Integer thePxLeft,
490                                                 const Standard_Integer thePxTop,
491                                                 const Standard_Integer thePxWidth,
492                                                 const Standard_Integer thePxHeight,
493                                                 Standard_CString theViewName,
494                                                 Standard_CString theDisplayName)
495 {
496   // Default position and dimension of the viewer window.
497   // Note that left top corner is set to be sufficiently small to have
498   // window fit in the small screens (actual for remote desktops, see #23003).
499   // The position corresponds to the window's client area, thus some
500   // gap is added for window frame to be visible.
501   Standard_Integer aPxLeft   = 20;
502   Standard_Integer aPxTop    = 40;
503   Standard_Integer aPxWidth  = 409;
504   Standard_Integer aPxHeight = 409;
505   Standard_Boolean toCreateViewer = Standard_False;
506
507   Handle(OpenGl_GraphicDriver) aGraphicDriver;
508   ViewerTest_Names aViewNames(theViewName);
509   if (ViewerTest_myViews.IsBound1 (aViewNames.GetViewName ()))
510     aViewNames.SetViewName (aViewNames.GetViewerName() + "/" + CreateName<Handle(V3d_View)>(ViewerTest_myViews, "View"));
511
512   if (thePxLeft != 0)
513     aPxLeft = thePxLeft;
514   if (thePxTop != 0)
515     aPxTop = thePxTop;
516   if (thePxWidth != 0)
517     aPxWidth = thePxWidth;
518   if (thePxHeight != 0)
519     aPxHeight = thePxHeight;
520
521   // Get graphic driver (create it or get from another view)
522   if (!ViewerTest_myDrivers.IsBound1 (aViewNames.GetDriverName()))
523   {
524     // Get connection string
525   #if !defined(_WIN32) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
526     TCollection_AsciiString aDisplayName(theDisplayName);
527     if (!aDisplayName.IsEmpty())
528       SetDisplayConnection (new Aspect_DisplayConnection ());
529     else
530       SetDisplayConnection (new Aspect_DisplayConnection (aDisplayName));
531   #else
532     (void)theDisplayName; // avoid warning on unused argument
533     SetDisplayConnection (new Aspect_DisplayConnection ());
534   #endif
535     aGraphicDriver = new OpenGl_GraphicDriver();
536     aGraphicDriver->ChangeOptions() = ViewerTest_myDefaultCaps;
537     aGraphicDriver->Begin (GetDisplayConnection());
538     ViewerTest_myDrivers.Bind (aViewNames.GetDriverName(), aGraphicDriver);
539     toCreateViewer = Standard_True;
540   }
541   else
542   {
543     aGraphicDriver = Handle(OpenGl_GraphicDriver)::DownCast (ViewerTest_myDrivers.Find1 (aViewNames.GetDriverName()));
544   }
545
546   //Dispose the window if input parameters are default
547   if (!ViewerTest_myViews.IsEmpty() && thePxLeft == 0 && thePxTop == 0)
548   {
549     Standard_Integer aTop = 0,
550                      aLeft = 0,
551                      aRight = 0,
552                      aBottom = 0,
553                      aScreenWidth = 0,
554                      aScreenHeight = 0;
555
556     // Get screen resolution
557 #if defined(_WIN32) || defined(__WIN32__)
558     RECT aWindowSize;
559     GetClientRect(GetDesktopWindow(), &aWindowSize);
560     aScreenHeight = aWindowSize.bottom;
561     aScreenWidth = aWindowSize.right;
562 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
563     GetCocoaScreenResolution (aScreenWidth, aScreenHeight);
564 #else
565     Screen *aScreen = DefaultScreenOfDisplay(GetDisplayConnection()->GetDisplay());
566     aScreenWidth = WidthOfScreen(aScreen);
567     aScreenHeight = HeightOfScreen(aScreen);
568 #endif
569
570     TCollection_AsciiString anOverlappedViewId("");
571
572     while (IsWindowOverlapped (aPxLeft, aPxTop, aPxLeft + aPxWidth, aPxTop + aPxHeight, anOverlappedViewId))
573     {
574       ViewerTest_myViews.Find1(anOverlappedViewId)->Window()->Position (aLeft, aTop, aRight, aBottom);
575
576       if (IsWindowOverlapped (aRight + 20, aPxTop, aRight + 20 + aPxWidth, aPxTop + aPxHeight, anOverlappedViewId)
577         && aRight + 2*aPxWidth + 40 > aScreenWidth)
578       {
579         if (aBottom + aPxHeight + 40 > aScreenHeight)
580         {
581           aPxLeft = 20;
582           aPxTop = 40;
583           break;
584         }
585         aPxLeft = 20;
586         aPxTop = aBottom + 40;
587       }
588       else
589         aPxLeft = aRight + 20;
590     }
591   }
592
593   // Get viewer name
594   TCollection_AsciiString aTitle("3D View - ");
595   aTitle = aTitle + aViewNames.GetViewName() + "(*)";
596
597   // Change name of current active window
598   if (!ViewerTest::CurrentView().IsNull())
599   {
600     TCollection_AsciiString aTitle("3D View - ");
601     aTitle = aTitle
602       + ViewerTest_myViews.Find2 (ViewerTest::CurrentView());
603     SetWindowTitle (ViewerTest::CurrentView()->Window(), aTitle.ToCString());
604   }
605
606   // Create viewer
607   Handle(V3d_Viewer) a3DViewer;
608   // If it's the single view, we first look for empty context
609   if (ViewerTest_myViews.IsEmpty() && !ViewerTest_myContexts.IsEmpty())
610   {
611     NCollection_DoubleMap <TCollection_AsciiString, Handle(AIS_InteractiveContext)>::Iterator
612       anIter(ViewerTest_myContexts);
613     if (anIter.More())
614       ViewerTest::SetAISContext (anIter.Value());
615     a3DViewer = ViewerTest::GetAISContext()->CurrentViewer();
616   }
617   else if (ViewerTest_myContexts.IsBound1(aViewNames.GetViewerName()))
618   {
619     ViewerTest::SetAISContext(ViewerTest_myContexts.Find1(aViewNames.GetViewerName()));
620     a3DViewer = ViewerTest::GetAISContext()->CurrentViewer();
621   }
622   else if (a3DViewer.IsNull())
623   {
624     toCreateViewer = Standard_True;
625     TCollection_ExtendedString NameOfWindow("Viewer3D");
626     a3DViewer = new V3d_Viewer(aGraphicDriver, NameOfWindow.ToExtString());
627
628     NameOfWindow = TCollection_ExtendedString("Collector");
629
630     a3DViewer->SetDefaultBackgroundColor(Quantity_NOC_BLACK);
631   }
632
633   // AIS context setup
634   if (ViewerTest::GetAISContext().IsNull() ||
635       !(ViewerTest_myContexts.IsBound1(aViewNames.GetViewerName())))
636   {
637     Handle(AIS_InteractiveContext) aContext =
638       new AIS_InteractiveContext(a3DViewer);
639     ViewerTest::SetAISContext (aContext);
640     ViewerTest_myContexts.Bind (aViewNames.GetViewerName(), ViewerTest::GetAISContext());
641   }
642   else
643     ViewerTest::ResetEventManager();
644
645   // Create window
646 #if defined(_WIN32) || defined(__WIN32__)
647       VT_GetWindow() = new WNT_Window (aTitle.ToCString(),
648                                        Handle(WNT_WClass)::DownCast (WClass()),
649                                        Draw_VirtualWindows ? WS_POPUPWINDOW : WS_OVERLAPPEDWINDOW,
650                                        aPxLeft, aPxTop,
651                                        aPxWidth, aPxHeight,
652                                        Quantity_NOC_BLACK);
653 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
654       VT_GetWindow() = new Cocoa_Window (aTitle.ToCString(),
655                                          aPxLeft, aPxTop,
656                                          aPxWidth, aPxHeight);
657       ViewerTest_SetCocoaEventManagerView (VT_GetWindow());
658 #else
659       VT_GetWindow() = new Xw_Window (aGraphicDriver->GetDisplayConnection(),
660                                       aTitle.ToCString(),
661                                       aPxLeft, aPxTop,
662                                       aPxWidth, aPxHeight);
663 #endif
664   VT_GetWindow()->SetVirtual (Draw_VirtualWindows);
665
666   // NIS setup
667   Handle(NIS_View) aView = new NIS_View (a3DViewer, VT_GetWindow());
668
669   ViewerTest::CurrentView(aView);
670   ViewerTest_myViews.Bind (aViewNames.GetViewName(), aView);
671   TheNISContext()->AttachView (aView);
672
673   // Setup for X11 or NT
674   OSWindowSetup();
675
676   // Set parameters for V3d_View and V3d_Viewer
677   const Handle (V3d_View) aV3dView = ViewerTest::CurrentView();
678   aV3dView->SetComputedMode(Standard_False);
679   MyHLRIsOn = aV3dView->ComputedMode();
680   aV3dView->SetZClippingDepth(0.5);
681   aV3dView->SetZClippingWidth(ZCLIPWIDTH/2.);
682
683   a3DViewer->SetDefaultBackgroundColor(Quantity_NOC_BLACK);
684   if (toCreateViewer)
685   {
686     a3DViewer->SetDefaultLights();
687     a3DViewer->SetLightOn();
688   }
689
690   #if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
691   #if TCL_MAJOR_VERSION  < 8
692   Tk_CreateFileHandler((void*)XConnectionNumber(GetDisplayConnection()->GetDisplay()),
693       TK_READABLE, VProcessEvents, (ClientData) VT_GetWindow()->XWindow() );
694   #else
695   Tk_CreateFileHandler(XConnectionNumber(GetDisplayConnection()->GetDisplay()),
696       TK_READABLE, VProcessEvents, (ClientData) VT_GetWindow()->XWindow() );
697   #endif
698   #endif
699
700   VT_GetWindow()->Map();
701
702   // Set the handle of created view in the event manager
703   ViewerTest::ResetEventManager();
704
705   ViewerTest::CurrentView()->Redraw();
706
707   aView.Nullify();
708   a3DViewer.Nullify();
709
710   return aViewNames.GetViewName();
711 }
712
713 //==============================================================================
714 //function : RedrawAllViews
715 //purpose  : Redraw all created views
716 //==============================================================================
717 void ViewerTest::RedrawAllViews()
718 {
719   NCollection_DoubleMap<TCollection_AsciiString, Handle(V3d_View)>::Iterator aViewIt(ViewerTest_myViews);
720   for (; aViewIt.More(); aViewIt.Next())
721   {
722     const Handle(V3d_View)& aView = aViewIt.Key2();
723     aView->Redraw();
724   }
725 }
726
727 //==============================================================================
728 //function : SplitParameter
729 //purpose  : Split parameter string to parameter name an patameter value
730 //==============================================================================
731 Standard_Boolean SplitParameter (const TCollection_AsciiString& theString,
732                                       TCollection_AsciiString& theName,
733                                       TCollection_AsciiString& theValue)
734 {
735   Standard_Integer aParamNameEnd = theString.FirstLocationInSet("=",1, theString.Length());
736   if (aParamNameEnd == 0)
737     return Standard_False;
738   TCollection_AsciiString aString(theString);
739   if (aParamNameEnd != 0)
740   {
741     theValue = aString.Split(aParamNameEnd);
742     aString.Split(aString.Length()-1);
743     theName = aString;
744   }
745   return Standard_True;
746 }
747
748 //==============================================================================
749 //function : Vinit
750 //purpose  : Create the window viewer and initialize all the global variable
751 //    Use Tk_CreateFileHandler on UNIX to cath the X11 Viewer event
752 //==============================================================================
753
754 static int VInit (Draw_Interpretor& theDi, Standard_Integer theArgsNb, const char** theArgVec)
755 {
756 if (theArgsNb > 9)
757   {
758     theDi << theArgVec[0] << ": incorrect number of command arguments.\n"
759       << "Type help for more information.\n";
760     return 1;
761   }
762   TCollection_AsciiString aViewName (""),
763                           aDisplayName ("");
764   Standard_Integer aPxLeft = 0,
765                   aPxTop = 0,
766                   aPxWidth = 0,
767                   aPxHeight = 0;
768
769   for (Standard_Integer i = 1; i < theArgsNb; ++i)
770   {
771     TCollection_AsciiString aName = "", aValue = "";
772     if(!SplitParameter (TCollection_AsciiString(theArgVec[i]),aName,aValue) && theArgsNb == 2)
773     {
774       // In case of syntax: vinit ViewName
775       aViewName = theArgVec[1];
776     }
777     else
778     {
779       if (aName == "name")
780       {
781         aViewName = aValue;
782       }
783       else if (aName == "l" || aName == "left")
784         aPxLeft = aValue.IntegerValue();
785       else if (aName == "t" || aName == "top")
786         aPxTop = aValue.IntegerValue();
787 #if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
788       else if (aName == "display")
789         aDisplayName = aValue;
790 #endif
791       else if (aName == "w" || aName == "width")
792         aPxWidth = aValue.IntegerValue();
793       else if (aName == "h" || aName == "height")
794         aPxHeight = aValue.IntegerValue();
795       else
796       {
797         theDi << theArgVec[0] << ": Warning: unknown parameter " << aName.ToCString() << ".\n";
798       }
799     }
800   }
801
802   ViewerTest_Names aViewNames (aViewName);
803   if (ViewerTest_myViews.IsBound1 (aViewNames.GetViewName ()))
804   {
805     TCollection_AsciiString aCommand("vactivate ");
806     aCommand = aCommand + aViewNames.GetViewName();
807     theDi.Eval(aCommand.ToCString());
808     return 0;
809   }
810
811   TCollection_AsciiString aViewId = ViewerTest::ViewerInit (aPxLeft, aPxTop, aPxWidth, aPxHeight,
812                                                             aViewName.ToCString(),
813                                                             aDisplayName.ToCString());
814   cout << theArgVec[0] << ": 3D View - " << aViewId << " was created.\n";
815   return 0;
816 }
817
818 //==============================================================================
819 //function : VHLR
820 //purpose  : hidden lines removal algorithm
821 //==============================================================================
822
823 static int VHLR (Draw_Interpretor& di, Standard_Integer argc, const char** argv)
824 {
825   if (ViewerTest::CurrentView().IsNull())
826   {
827     di << argv[0] << ": Call vinit before this command, please.\n";
828     return 1;
829   }
830
831   if (argc != 2)
832   {
833     di << argv[0] << ": Wrong number of command arguments.\n"
834       << "Type help " << argv[0] << " for more information.\n";
835     return 1;
836   }
837
838   Standard_Boolean isHLROn =
839     (!strcasecmp (argv[1], "on")) ? Standard_True : Standard_False;
840
841   if (isHLROn == MyHLRIsOn)
842   {
843     return 0;
844   }
845
846   MyHLRIsOn = isHLROn;
847   ViewerTest::CurrentView()->SetComputedMode (MyHLRIsOn);
848
849   return 0;
850 }
851
852 //==============================================================================
853 //function : VHLRType
854 //purpose  : change type of using HLR algorithm
855 //==============================================================================
856
857 static int VHLRType (Draw_Interpretor& di, Standard_Integer argc, const char** argv)
858 {
859   if (ViewerTest::CurrentView().IsNull())
860   {
861     di << argv[0] << ": Call vinit before this command, please.\n";
862     return 1;
863   }
864
865   if (argc < 2)
866   {
867     di << argv[0] << ": Wrong number of command arguments.\n"
868       << "Type help " << argv[0] << " for more information.\n";
869     return 1;
870   }
871
872   Prs3d_TypeOfHLR aTypeOfHLR =
873     (!strcasecmp (argv[1], "algo")) ? Prs3d_TOH_Algo : Prs3d_TOH_PolyAlgo;
874
875   if (argc == 2)
876   {
877     AIS_ListOfInteractive aListOfShapes;
878     ViewerTest::GetAISContext()->DisplayedObjects (aListOfShapes);
879     ViewerTest::GetAISContext()->DefaultDrawer()->SetTypeOfHLR(aTypeOfHLR);
880     for (AIS_ListIteratorOfListOfInteractive anIter(aListOfShapes);
881       anIter.More(); anIter.Next())
882     {
883       Handle(AIS_Shape) aShape = Handle(AIS_Shape)::DownCast(anIter.Value());
884       if (aShape.IsNull())
885         continue;
886       if (aShape->TypeOfHLR() != aTypeOfHLR)
887         aShape->SetTypeOfHLR (aTypeOfHLR);
888       if (MyHLRIsOn)
889         aShape->Redisplay();
890     }
891     ViewerTest::CurrentView()->Update();
892     return 0;
893   }
894   else
895   {
896     for (Standard_Integer i = 2; i < argc; ++i)
897     {
898       ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
899       TCollection_AsciiString aName (argv[i]);
900
901       if (!aMap.IsBound2 (aName))
902       {
903         di << argv[0] << ":" << " Wrong shape name:" << aName.ToCString() << ".\n";
904         continue;
905       }
906       Handle(AIS_Shape) anAISObject =
907         Handle(AIS_Shape)::DownCast (aMap.Find2(aName));
908       if (anAISObject.IsNull())
909         continue;
910       anAISObject->SetTypeOfHLR (aTypeOfHLR);
911       if (MyHLRIsOn)
912         anAISObject->Redisplay();
913     }
914     ViewerTest::CurrentView()->Update();
915   }
916
917   return 0;
918 }
919
920 //==============================================================================
921 //function : FindViewIdByWindowHandle
922 //purpose  : Find theView Id in the map of views by window handle
923 //==============================================================================
924 #if defined(_WIN32) || defined(__WIN32__) || (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
925 TCollection_AsciiString FindViewIdByWindowHandle(const Aspect_Handle theWindowHandle)
926 {
927   for (NCollection_DoubleMap<TCollection_AsciiString, Handle(V3d_View)>::Iterator
928        anIter(ViewerTest_myViews); anIter.More(); anIter.Next())
929   {
930     Aspect_Handle aWindowHandle = GetWindowHandle(anIter.Value()->Window());
931     if (aWindowHandle == theWindowHandle)
932       return anIter.Key1();
933   }
934   return TCollection_AsciiString("");
935 }
936 #endif
937
938 //==============================================================================
939 //function : ActivateView
940 //purpose  : Make the view active
941 //==============================================================================
942
943 void ActivateView (const TCollection_AsciiString& theViewName)
944 {
945   const Handle(V3d_View) aView = ViewerTest_myViews.Find1(theViewName);
946   if (!aView.IsNull())
947   {
948     Handle(AIS_InteractiveContext) anAISContext = FindContextByView(aView);
949     if (!anAISContext.IsNull())
950     {
951       if (!ViewerTest::CurrentView().IsNull())
952       {
953         TCollection_AsciiString aTitle("3D View - ");
954         aTitle = aTitle + ViewerTest_myViews.Find2 (ViewerTest::CurrentView());
955         SetWindowTitle (ViewerTest::CurrentView()->Window(), aTitle.ToCString());
956       }
957
958       ViewerTest::CurrentView (aView);
959       // Update degenerate mode
960       MyHLRIsOn = ViewerTest::CurrentView()->ComputedMode();
961       ViewerTest::SetAISContext (anAISContext);
962       TCollection_AsciiString aTitle = TCollection_AsciiString("3D View - ");
963       aTitle = aTitle + theViewName + "(*)";
964       SetWindowTitle (ViewerTest::CurrentView()->Window(), aTitle.ToCString());
965 #if defined(_WIN32) || defined(__WIN32__)
966       VT_GetWindow() = Handle(WNT_Window)::DownCast(ViewerTest::CurrentView()->Window());
967 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
968       VT_GetWindow() = Handle(Cocoa_Window)::DownCast(ViewerTest::CurrentView()->Window());
969 #else
970       VT_GetWindow() = Handle(Xw_Window)::DownCast(ViewerTest::CurrentView()->Window());
971 #endif
972       SetDisplayConnection(ViewerTest::CurrentView()->Viewer()->Driver()->GetDisplayConnection());
973       ViewerTest::CurrentView()->Redraw();
974     }
975   }
976 }
977
978 //==============================================================================
979 //function : RemoveView
980 //purpose  : Close and remove view from display, clear maps if neccessary
981 //==============================================================================
982 void ViewerTest::RemoveView (const TCollection_AsciiString& theViewName, const Standard_Boolean isContextRemoved)
983 {
984   if (!ViewerTest_myViews.IsBound1(theViewName))
985   {
986     cout << "Wrong view name\n";
987     return;
988   }
989
990   // Activate another view if it's active now
991   if (ViewerTest_myViews.Find1(theViewName) == ViewerTest::CurrentView())
992   {
993     if (ViewerTest_myViews.Extent() > 1)
994     {
995       TCollection_AsciiString aNewViewName;
996       for (NCollection_DoubleMap <TCollection_AsciiString, Handle(V3d_View)> :: Iterator
997            anIter(ViewerTest_myViews); anIter.More(); anIter.Next())
998         if (anIter.Key1() != theViewName)
999         {
1000           aNewViewName = anIter.Key1();
1001           break;
1002         }
1003         ActivateView (aNewViewName);
1004     }
1005     else
1006     {
1007       Handle(V3d_View) anEmptyView;
1008 #if defined(_WIN32) || defined(__WIN32__)
1009       Handle(WNT_Window) anEmptyWindow;
1010 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
1011       Handle(Cocoa_Window) anEmptyWindow;
1012 #else
1013       Handle(Xw_Window) anEmptyWindow;
1014 #endif
1015       VT_GetWindow() = anEmptyWindow;
1016       ViewerTest::CurrentView (anEmptyView);
1017       if (isContextRemoved)
1018       {
1019         Handle(AIS_InteractiveContext) anEmptyContext;
1020         ViewerTest::SetAISContext(anEmptyContext);
1021       }
1022     }
1023   }
1024
1025   // Delete view
1026   Handle(V3d_View) aView = ViewerTest_myViews.Find1(theViewName);
1027   Handle(AIS_InteractiveContext) aCurrentContext = FindContextByView(aView);
1028
1029   // Remove view resources
1030   TheNISContext()->DetachView(Handle(NIS_View)::DownCast(aView));
1031   ViewerTest_myViews.UnBind1(theViewName);
1032   aView->Remove();
1033
1034 #if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
1035   XFlush (GetDisplayConnection()->GetDisplay());
1036 #endif
1037
1038   // Keep context opened only if the closed view is last to avoid
1039   // unused empty contexts
1040   if (!aCurrentContext.IsNull())
1041   {
1042     // Check if there are more difined views in the viewer
1043     aCurrentContext->CurrentViewer()->InitDefinedViews();
1044     if ((isContextRemoved || ViewerTest_myContexts.Size() != 1) && !aCurrentContext->CurrentViewer()->MoreDefinedViews())
1045     {
1046       // Remove driver if there is no viewers that use it
1047       Standard_Boolean isRemoveDriver = Standard_True;
1048       for(NCollection_DoubleMap<TCollection_AsciiString, Handle(AIS_InteractiveContext)>::Iterator
1049           anIter(ViewerTest_myContexts); anIter.More(); anIter.Next())
1050       {
1051         if (aCurrentContext != anIter.Key2() &&
1052           aCurrentContext->CurrentViewer()->Driver() == anIter.Value()->CurrentViewer()->Driver())
1053         {
1054           isRemoveDriver = Standard_False;
1055           break;
1056         }
1057       }
1058       if(isRemoveDriver)
1059       {
1060         ViewerTest_myDrivers.UnBind2 (aCurrentContext->CurrentViewer()->Driver());
1061       #if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
1062         #if TCL_MAJOR_VERSION  < 8
1063         Tk_DeleteFileHandler((void*)XConnectionNumber(aCurrentContext->CurrentViewer()->Driver()->GetDisplayConnection()->GetDisplay()));
1064         #else
1065         Tk_DeleteFileHandler(XConnectionNumber(aCurrentContext->CurrentViewer()->Driver()->GetDisplayConnection()->GetDisplay()));
1066         #endif
1067       #endif
1068       }
1069
1070       ViewerTest_myContexts.UnBind2(aCurrentContext);
1071     }
1072   }
1073   cout << "3D View - " << theViewName << " was deleted.\n";
1074
1075 }
1076
1077 //==============================================================================
1078 //function : VClose
1079 //purpose  : Remove the view defined by its name
1080 //==============================================================================
1081
1082 static int VClose (Draw_Interpretor& /*theDi*/,
1083                    Standard_Integer  theArgsNb,
1084                    const char**      theArgVec)
1085 {
1086   NCollection_List<TCollection_AsciiString> aViewList;
1087   if (theArgsNb > 1)
1088   {
1089     TCollection_AsciiString anArg (theArgVec[1]);
1090     anArg.UpperCase();
1091     if (anArg.IsEqual ("ALL")
1092      || anArg.IsEqual ("*"))
1093     {
1094       for (NCollection_DoubleMap<TCollection_AsciiString, Handle(V3d_View)>::Iterator anIter (ViewerTest_myViews);
1095            anIter.More(); anIter.Next())
1096       {
1097         aViewList.Append (anIter.Key1());
1098       }
1099       if (aViewList.IsEmpty())
1100       {
1101         std::cout << "No view to close\n";
1102         return 0;
1103       }
1104     }
1105     else
1106     {
1107       ViewerTest_Names aViewName (theArgVec[1]);
1108       if (!ViewerTest_myViews.IsBound1 (aViewName.GetViewName()))
1109       {
1110         std::cerr << "The view with name '" << theArgVec[1] << "' does not exist\n";
1111         return 1;
1112       }
1113       aViewList.Append (aViewName.GetViewName());
1114     }
1115   }
1116   else
1117   {
1118     // close active view
1119     if (ViewerTest::CurrentView().IsNull())
1120     {
1121       std::cerr << "No active view!\n";
1122       return 1;
1123     }
1124     aViewList.Append (ViewerTest_myViews.Find2 (ViewerTest::CurrentView()));
1125   }
1126
1127   Standard_Boolean toRemoveContext = (theArgsNb != 3 || Draw::Atoi (theArgVec[2]) != 1);
1128   for (NCollection_List<TCollection_AsciiString>::Iterator anIter(aViewList);
1129        anIter.More(); anIter.Next())
1130   {
1131     ViewerTest::RemoveView (anIter.Value(), toRemoveContext);
1132   }
1133
1134   return 0;
1135 }
1136
1137 //==============================================================================
1138 //function : VActivate
1139 //purpose  : Activate the view defined by its ID
1140 //==============================================================================
1141
1142 static int VActivate (Draw_Interpretor& theDi, Standard_Integer theArgsNb, const char** theArgVec)
1143 {
1144   if (theArgsNb > 2)
1145   {
1146     theDi << theArgVec[0] << ": wrong number of command arguments.\n"
1147     << "Usage: " << theArgVec[0] << " ViewID\n";
1148     return 1;
1149   }
1150   if(theArgsNb == 1)
1151   {
1152     theDi.Eval("vviewlist");
1153     return 0;
1154   }
1155
1156   TCollection_AsciiString aNameString(theArgVec[1]);
1157   if ( strcasecmp( aNameString.ToCString(), "NONE" ) == 0 )
1158   {
1159     TCollection_AsciiString aTitle("3D View - ");
1160     aTitle = aTitle + ViewerTest_myViews.Find2(ViewerTest::CurrentView());
1161     SetWindowTitle (ViewerTest::CurrentView()->Window(), aTitle.ToCString());
1162     Handle(V3d_View) anEmptyView;
1163 #if defined(_WIN32) || defined(__WIN32__)
1164     Handle(WNT_Window) anEmptyWindow;
1165 #elif defined(__APPLE__) && !defined(MACOSX_USE_GLX)
1166     Handle(Cocoa_Window) anEmptyWindow;
1167 #else
1168     Handle(Xw_Window) anEmptyWindow;
1169 #endif
1170     VT_GetWindow() = anEmptyWindow;
1171     ViewerTest::CurrentView (anEmptyView);
1172     ViewerTest::ResetEventManager();
1173     theDi << theArgVec[0] << ": all views are inactive\n";
1174     return 0;
1175   }
1176
1177   ViewerTest_Names aViewNames(aNameString);
1178
1179   // Check if this view exists in the viewer with the driver
1180   if (!ViewerTest_myViews.IsBound1(aViewNames.GetViewName()))
1181   {
1182     theDi << "Wrong view name\n";
1183     return 1;
1184   }
1185
1186   // Check if it is active already
1187   if (ViewerTest::CurrentView() == ViewerTest_myViews.Find1(aViewNames.GetViewName()))
1188   {
1189     theDi << theArgVec[0] << ": the view is active already\n";
1190     return 0;
1191   }
1192
1193   ActivateView (aViewNames.GetViewName());
1194   return 0;
1195 }
1196
1197 //==============================================================================
1198 //function : VViewList
1199 //purpose  : Print current list of views per viewer and graphic driver ID
1200 //           shared between viewers
1201 //==============================================================================
1202
1203 static int VViewList (Draw_Interpretor& theDi, Standard_Integer theArgsNb, const char** theArgVec)
1204 {
1205   if (theArgsNb > 2)
1206   {
1207     theDi << theArgVec[0] << ": Wrong number of command arguments\n"
1208           << "Usage: " << theArgVec[0] << " name";
1209     return 1;
1210   }
1211   if (ViewerTest_myContexts.Size() < 1)
1212     return 0;
1213
1214   Standard_Boolean isTreeView =
1215     (( theArgsNb==1 ) || ( strcasecmp( theArgVec[1], "long" ) != 0 ));
1216
1217   if (isTreeView)
1218     theDi << theArgVec[0] <<":\n";
1219
1220     for (NCollection_DoubleMap <TCollection_AsciiString, Handle(Graphic3d_GraphicDriver)>::Iterator
1221       aDriverIter(ViewerTest_myDrivers); aDriverIter.More(); aDriverIter.Next())
1222     {
1223       if (isTreeView)
1224         theDi << aDriverIter.Key1() << ":\n";
1225
1226       for (NCollection_DoubleMap <TCollection_AsciiString, Handle(AIS_InteractiveContext)>::Iterator
1227         aContextIter(ViewerTest_myContexts); aContextIter.More(); aContextIter.Next())
1228       {
1229         if (aContextIter.Key1().Search(aDriverIter.Key1()) != -1)
1230         {
1231           if (isTreeView)
1232           {
1233             TCollection_AsciiString aContextName(aContextIter.Key1());
1234             theDi << " " << aContextName.Split(aDriverIter.Key1().Length() + 1) << ":" << "\n";
1235           }
1236
1237           for (NCollection_DoubleMap <TCollection_AsciiString, Handle(V3d_View)>::Iterator
1238             aViewIter(ViewerTest_myViews); aViewIter.More(); aViewIter.Next())
1239           {
1240             if (aViewIter.Key1().Search(aContextIter.Key1()) != -1)
1241             {
1242               TCollection_AsciiString aViewName(aViewIter.Key1());
1243               if (isTreeView)
1244               {
1245                 if (aViewIter.Value() == ViewerTest::CurrentView())
1246                   theDi << "  " << aViewName.Split(aContextIter.Key1().Length() + 1) << "(*)" << "\n";
1247                 else
1248                   theDi << "  " << aViewName.Split(aContextIter.Key1().Length() + 1) << "\n";
1249               }
1250               else
1251               {
1252                 theDi << aViewName << " ";
1253               }
1254             }
1255           }
1256         }
1257       }
1258     }
1259   return 0;
1260 }
1261
1262 //==============================================================================
1263 //function : VT_ProcessKeyPress
1264 //purpose  : Handle KeyPress event from a CString
1265 //==============================================================================
1266 void VT_ProcessKeyPress (const char* buf_ret)
1267 {
1268   //cout << "KeyPress" << endl;
1269   const Handle(V3d_View) aView = ViewerTest::CurrentView();
1270   const Handle(NIS_View) aNisView = Handle(NIS_View)::DownCast (aView);
1271   // Letter in alphabetic order
1272
1273   if (!strcasecmp (buf_ret, "A"))
1274   {
1275     // AXO
1276     aView->SetProj(V3d_XposYnegZpos);
1277   }
1278   else if (!strcasecmp (buf_ret, "D"))
1279   {
1280     // Reset
1281     aView->Reset();
1282   }
1283   else if (!strcasecmp (buf_ret, "F"))
1284   {
1285     // FitAll
1286     if (aNisView.IsNull())
1287       aView->FitAll();
1288     else
1289       aNisView->FitAll3d();
1290   }
1291   else if (!strcasecmp (buf_ret, "H"))
1292   {
1293     // HLR
1294     cout << "HLR" << endl;
1295     aView->SetComputedMode (!aView->ComputedMode());
1296     MyHLRIsOn = aView->ComputedMode();
1297   }
1298   else if (!strcasecmp (buf_ret, "P"))
1299   {
1300     // Type of HLR
1301     Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
1302     if (aContext->DefaultDrawer()->TypeOfHLR() == Prs3d_TOH_Algo)
1303       aContext->DefaultDrawer()->SetTypeOfHLR(Prs3d_TOH_PolyAlgo);
1304     else
1305       aContext->DefaultDrawer()->SetTypeOfHLR(Prs3d_TOH_Algo);
1306     if (aContext->NbCurrents()==0 || aContext->NbSelected() == 0)
1307     {
1308       AIS_ListOfInteractive aListOfShapes;
1309       aContext->DisplayedObjects(aListOfShapes);
1310       for (AIS_ListIteratorOfListOfInteractive anIter(aListOfShapes);
1311         anIter.More(); anIter.Next())
1312       {
1313         Handle(AIS_Shape) aShape = Handle(AIS_Shape)::DownCast(anIter.Value());
1314         if (aShape.IsNull())
1315           continue;
1316         if (aShape->TypeOfHLR() == Prs3d_TOH_PolyAlgo)
1317           aShape->SetTypeOfHLR (Prs3d_TOH_Algo);
1318         else
1319           aShape->SetTypeOfHLR (Prs3d_TOH_PolyAlgo);
1320         aShape->Redisplay();
1321       }
1322     }
1323     else
1324     {
1325       for (aContext->InitCurrent();aContext->MoreCurrent();aContext->NextCurrent())
1326       {
1327         Handle(AIS_Shape) aShape = Handle(AIS_Shape)::DownCast(aContext->Current());
1328         if (aShape.IsNull())
1329           continue;
1330         if(aShape->TypeOfHLR() == Prs3d_TOH_PolyAlgo)
1331           aShape->SetTypeOfHLR (Prs3d_TOH_Algo);
1332         else
1333           aShape->SetTypeOfHLR (Prs3d_TOH_PolyAlgo);
1334         aShape->Redisplay();
1335       }
1336     }
1337
1338     aContext->UpdateCurrentViewer();
1339
1340   }
1341   else if (!strcasecmp (buf_ret, "S"))
1342   {
1343     std::cout << "setup Shaded display mode" << std::endl;
1344
1345     Handle(AIS_InteractiveContext) Ctx = ViewerTest::GetAISContext();
1346     if(Ctx->NbCurrents()==0 ||
1347       Ctx->NbSelected()==0)
1348       Ctx->SetDisplayMode(AIS_Shaded);
1349     else{
1350       if(Ctx->HasOpenedContext()){
1351         for(Ctx->InitSelected();Ctx->MoreSelected();Ctx->NextSelected())
1352           Ctx->SetDisplayMode(Ctx->Interactive(),1,Standard_False);
1353       }
1354       else{
1355         for(Ctx->InitCurrent();Ctx->MoreCurrent();Ctx->NextCurrent())
1356           Ctx->SetDisplayMode(Ctx->Current(),1,Standard_False);
1357       }
1358       Ctx->UpdateCurrentViewer();
1359     }
1360   }
1361   else if (!strcasecmp (buf_ret, "U"))
1362   {
1363     // Unset display mode
1364     std::cout << "reset display mode to defaults" << std::endl;
1365
1366     Handle(AIS_InteractiveContext) Ctx = ViewerTest::GetAISContext();
1367     if(Ctx->NbCurrents()==0 ||
1368       Ctx->NbSelected()==0)
1369       Ctx->SetDisplayMode(AIS_WireFrame);
1370     else{
1371       if(Ctx->HasOpenedContext()){
1372         for(Ctx->InitSelected();Ctx->MoreSelected();Ctx->NextSelected())
1373           Ctx->UnsetDisplayMode(Ctx->Interactive(),Standard_False);
1374       }
1375       else{
1376         for(Ctx->InitCurrent();Ctx->MoreCurrent();Ctx->NextCurrent())
1377           Ctx->UnsetDisplayMode(Ctx->Current(),Standard_False);
1378       }
1379       Ctx->UpdateCurrentViewer();
1380     }
1381
1382   }
1383   else if (!strcasecmp (buf_ret, "T"))
1384   {
1385     // Top
1386     aView->SetProj(V3d_Zpos);
1387   }
1388   else if (!strcasecmp (buf_ret, "B"))
1389   {
1390     // Bottom
1391     aView->SetProj(V3d_Zneg);
1392   }
1393   else if (!strcasecmp (buf_ret, "L"))
1394   {
1395     // Left
1396     aView->SetProj(V3d_Xneg);
1397   }
1398   else if (!strcasecmp (buf_ret, "R"))
1399   {
1400     // Right
1401     aView->SetProj(V3d_Xpos);
1402   }
1403   else if (!strcasecmp (buf_ret, "W"))
1404   {
1405     std::cout << "setup WireFrame display mode" << std::endl;
1406     Handle(AIS_InteractiveContext) Ctx = ViewerTest::GetAISContext();
1407     if(Ctx->NbCurrents()==0 ||
1408       Ctx->NbSelected()==0)
1409       Ctx->SetDisplayMode(AIS_WireFrame);
1410     else{
1411       if(Ctx->HasOpenedContext()){
1412         for(Ctx->InitSelected();Ctx->MoreSelected();Ctx->NextSelected())
1413           Ctx->SetDisplayMode(Ctx->Interactive(),0,Standard_False);
1414       }
1415       else{
1416         for(Ctx->InitCurrent();Ctx->MoreCurrent();Ctx->NextCurrent())
1417           Ctx->SetDisplayMode(Ctx->Current(),0,Standard_False);
1418       }
1419       Ctx->UpdateCurrentViewer();
1420     }
1421   }
1422   else if (!strcasecmp (buf_ret, "Z"))
1423   {
1424     // ZCLIP
1425     if ( ZClipIsOn ) {
1426       cout << "ZClipping OFF" << endl;
1427       ZClipIsOn = 0;
1428
1429       aView->SetZClippingType(V3d_OFF);
1430       aView->Redraw();
1431     }
1432     else {
1433       cout << "ZClipping ON" << endl;
1434       ZClipIsOn = 1;
1435
1436       aView->SetZClippingType(V3d_FRONT);
1437       aView->Redraw();
1438     }
1439   }
1440   else if (!strcasecmp (buf_ret, ","))
1441   {
1442     ViewerTest::GetAISContext()->HilightNextDetected(ViewerTest::CurrentView());
1443   }
1444   else if (!strcasecmp (buf_ret, "."))
1445   {
1446     ViewerTest::GetAISContext()->HilightPreviousDetected(ViewerTest::CurrentView());
1447   }
1448   else if (*buf_ret == THE_KEY_DELETE)
1449   {
1450     Handle(AIS_InteractiveContext) aCtx = ViewerTest::GetAISContext();
1451     if (!aCtx.IsNull()
1452      && aCtx->NbCurrents() > 0
1453      && aCtx->NbSelected() > 0)
1454     {
1455       Draw_Interprete ("verase");
1456     }
1457   }
1458   else
1459   {
1460     // Number
1461     Standard_Integer Num = Draw::Atoi(buf_ret);
1462     if(Num>=0 && Num<=7)
1463       ViewerTest::StandardModeActivation(Num);
1464   }
1465 }
1466
1467 //==============================================================================
1468 //function : VT_ProcessExpose
1469 //purpose  : Redraw the View on an Expose Event
1470 //==============================================================================
1471 void VT_ProcessExpose()
1472 {
1473   Handle(V3d_View) aView3d = ViewerTest::CurrentView();
1474   if (!aView3d.IsNull())
1475   {
1476     aView3d->Redraw();
1477   }
1478 }
1479
1480 //==============================================================================
1481 //function : VT_ProcessConfigure
1482 //purpose  : Resize the View on an Configure Event
1483 //==============================================================================
1484 void VT_ProcessConfigure()
1485 {
1486   Handle(V3d_View) aView3d = ViewerTest::CurrentView();
1487   if (aView3d.IsNull())
1488   {
1489     return;
1490   }
1491
1492   aView3d->MustBeResized();
1493   aView3d->Update();
1494   aView3d->Redraw();
1495 }
1496
1497 //==============================================================================
1498 //function : VT_ProcessButton1Press
1499 //purpose  : Picking
1500 //==============================================================================
1501 Standard_Boolean VT_ProcessButton1Press(
1502   Standard_Integer ,
1503   const char**     argv,
1504   Standard_Boolean pick,
1505   Standard_Boolean shift)
1506 {
1507   Handle(ViewerTest_EventManager) EM = ViewerTest::CurrentEventManager();
1508   if ( pick ) {
1509     Standard_Real X, Y, Z;
1510
1511     ViewerTest::CurrentView()->Convert(X_Motion, Y_Motion, X, Y, Z);
1512
1513     Draw::Set(argv[1], X);
1514     Draw::Set(argv[2], Y);
1515     Draw::Set(argv[3], Z);}
1516
1517   if(shift)
1518     EM->ShiftSelect();
1519   else
1520     EM->Select();
1521
1522   pick = 0;
1523   return pick;
1524 }
1525
1526 //==============================================================================
1527 //function : VT_ProcessButton1Release
1528 //purpose  : End selecting
1529 //==============================================================================
1530 void VT_ProcessButton1Release (Standard_Boolean theIsShift)
1531 {
1532   if (IsDragged)
1533   {
1534     IsDragged = Standard_False;
1535     Handle(ViewerTest_EventManager) EM = ViewerTest::CurrentEventManager();
1536     if (theIsShift)
1537     {
1538       EM->ShiftSelect (Min (X_ButtonPress, X_Motion), Max (Y_ButtonPress, Y_Motion),
1539                        Max (X_ButtonPress, X_Motion), Min (Y_ButtonPress, Y_Motion));
1540     }
1541     else
1542     {
1543       EM->Select (Min (X_ButtonPress, X_Motion), Max (Y_ButtonPress, Y_Motion),
1544                   Max (X_ButtonPress, X_Motion), Min (Y_ButtonPress, Y_Motion));
1545     }
1546   }
1547 }
1548
1549 //==============================================================================
1550 //function : VT_ProcessButton3Press
1551 //purpose  : Start Rotation
1552 //==============================================================================
1553 void VT_ProcessButton3Press()
1554 {
1555   Start_Rot = 1;
1556   if (MyHLRIsOn)
1557   {
1558     ViewerTest::CurrentView()->SetComputedMode (Standard_False);
1559   }
1560   ViewerTest::CurrentView()->StartRotation( X_ButtonPress, Y_ButtonPress );
1561 }
1562
1563 //==============================================================================
1564 //function : VT_ProcessButton3Release
1565 //purpose  : End rotation
1566 //==============================================================================
1567 void VT_ProcessButton3Release()
1568 {
1569   if (Start_Rot)
1570   {
1571     Start_Rot = 0;
1572     if (MyHLRIsOn)
1573     {
1574       ViewerTest::CurrentView()->SetComputedMode (Standard_True);
1575     }
1576   }
1577 }
1578
1579 //==============================================================================
1580 //function : ProcessZClipMotion
1581 //purpose  : Zoom
1582 //==============================================================================
1583
1584 void ProcessZClipMotion()
1585 {
1586   Handle(V3d_View)  a3DView = ViewerTest::CurrentView();
1587   if ( Abs(X_Motion - X_ButtonPress) > 2 ) {
1588     static Standard_Real CurZPos = 0.;
1589
1590     //Quantity_Length VDX, VDY;
1591     //a3DView->Size(VDX,VDY);
1592     //Standard_Real VDZ = a3DView->ZSize();
1593     //printf("View size (%lf,%lf,%lf)\n", VDX, VDY, VDZ);
1594
1595     Quantity_Length dx = a3DView->Convert(X_Motion - X_ButtonPress);
1596
1597     // Front = Depth + width/2.
1598     Standard_Real D = 0.5;
1599     Standard_Real W = 0.1;
1600
1601     CurZPos += (dx);
1602
1603     D += CurZPos;
1604
1605     //printf("dx %lf Depth %lf Width %lf\n", dx, D, W);
1606
1607     a3DView->SetZClippingType(V3d_OFF);
1608     a3DView->SetZClippingDepth(D);
1609     a3DView->SetZClippingWidth(W);
1610     a3DView->SetZClippingType(V3d_FRONT);
1611
1612     a3DView->Redraw();
1613
1614     X_ButtonPress = X_Motion;
1615     Y_ButtonPress = Y_Motion;
1616   }
1617 }
1618
1619 //==============================================================================
1620 //function : ProcessControlButton1Motion
1621 //purpose  : Zoom
1622 //==============================================================================
1623
1624 static void ProcessControlButton1Motion()
1625 {
1626   ViewerTest::CurrentView()->Zoom( X_ButtonPress, Y_ButtonPress, X_Motion, Y_Motion);
1627
1628   X_ButtonPress = X_Motion;
1629   Y_ButtonPress = Y_Motion;
1630 }
1631
1632 //==============================================================================
1633 //function : VT_ProcessControlButton2Motion
1634 //purpose  : Panning
1635 //==============================================================================
1636 void VT_ProcessControlButton2Motion()
1637 {
1638   Quantity_Length dx = ViewerTest::CurrentView()->Convert(X_Motion - X_ButtonPress);
1639   Quantity_Length dy = ViewerTest::CurrentView()->Convert(Y_Motion - Y_ButtonPress);
1640
1641   dy = -dy; // Xwindow Y axis is from top to Bottom
1642
1643   ViewerTest::CurrentView()->Panning( dx, dy );
1644
1645   X_ButtonPress = X_Motion;
1646   Y_ButtonPress = Y_Motion;
1647 }
1648
1649 //==============================================================================
1650 //function : VT_ProcessControlButton3Motion
1651 //purpose  : Rotation
1652 //==============================================================================
1653 void VT_ProcessControlButton3Motion()
1654 {
1655   if (Start_Rot)
1656   {
1657     ViewerTest::CurrentView()->Rotation (X_Motion, Y_Motion);
1658   }
1659 }
1660
1661 //==============================================================================
1662 //function : VT_ProcessMotion
1663 //purpose  :
1664 //==============================================================================
1665 void VT_ProcessMotion()
1666 {
1667   //pre-hilights detected objects at mouse position
1668
1669   Handle(ViewerTest_EventManager) EM = ViewerTest::CurrentEventManager();
1670   EM->MoveTo(X_Motion, Y_Motion);
1671 }
1672
1673
1674 void ViewerTest::GetMousePosition(Standard_Integer& Xpix,Standard_Integer& Ypix)
1675 {
1676   Xpix = X_Motion;Ypix=Y_Motion;
1677 }
1678
1679 //==============================================================================
1680 //function : ViewProject: implements VAxo, VTop, VLeft, ...
1681 //purpose  : Switches to an axonometric, top, left and other views
1682 //==============================================================================
1683
1684 static int ViewProject(Draw_Interpretor& di, const V3d_TypeOfOrientation ori)
1685 {
1686   if ( ViewerTest::CurrentView().IsNull() )
1687   {
1688     di<<"Call vinit before this command, please"<<"\n";
1689     return 1;
1690   }
1691
1692   ViewerTest::CurrentView()->SetProj(ori);
1693   return 0;
1694 }
1695
1696 //==============================================================================
1697 //function : VAxo
1698 //purpose  : Switch to an Axonometric view
1699 //Draw arg : No args
1700 //==============================================================================
1701
1702 static int VAxo(Draw_Interpretor& di, Standard_Integer , const char** )
1703 {
1704   return ViewProject(di, V3d_XposYnegZpos);
1705 }
1706
1707 //==============================================================================
1708 //function : VTop
1709 //purpose  : Switch to a Top View
1710 //Draw arg : No args
1711 //==============================================================================
1712
1713 static int VTop(Draw_Interpretor& di, Standard_Integer , const char** )
1714 {
1715   return ViewProject(di, V3d_Zpos);
1716 }
1717
1718 //==============================================================================
1719 //function : VBottom
1720 //purpose  : Switch to a Bottom View
1721 //Draw arg : No args
1722 //==============================================================================
1723
1724 static int VBottom(Draw_Interpretor& di, Standard_Integer , const char** )
1725 {
1726   return ViewProject(di, V3d_Zneg);
1727 }
1728
1729 //==============================================================================
1730 //function : VLeft
1731 //purpose  : Switch to a Left View
1732 //Draw arg : No args
1733 //==============================================================================
1734
1735 static int VLeft(Draw_Interpretor& di, Standard_Integer , const char** )
1736 {
1737   return ViewProject(di, V3d_Ypos);
1738 }
1739
1740 //==============================================================================
1741 //function : VRight
1742 //purpose  : Switch to a Right View
1743 //Draw arg : No args
1744 //==============================================================================
1745
1746 static int VRight(Draw_Interpretor& di, Standard_Integer , const char** )
1747 {
1748   return ViewProject(di, V3d_Yneg);
1749 }
1750
1751 //==============================================================================
1752 //function : VFront
1753 //purpose  : Switch to a Front View
1754 //Draw arg : No args
1755 //==============================================================================
1756
1757 static int VFront(Draw_Interpretor& di, Standard_Integer , const char** )
1758 {
1759   return ViewProject(di, V3d_Xpos);
1760 }
1761
1762 //==============================================================================
1763 //function : VBack
1764 //purpose  : Switch to a Back View
1765 //Draw arg : No args
1766 //==============================================================================
1767
1768 static int VBack(Draw_Interpretor& di, Standard_Integer , const char** )
1769 {
1770   return ViewProject(di, V3d_Xneg);
1771 }
1772
1773 //==============================================================================
1774 //function : VHelp
1775 //purpose  : Dsiplay help on viewer Keyboead and mouse commands
1776 //Draw arg : No args
1777 //==============================================================================
1778
1779 static int VHelp(Draw_Interpretor& di, Standard_Integer , const char** )
1780 {
1781
1782   di << "Q : Quit the application" << "\n";
1783
1784   di << "========================="<<"\n";
1785   di << "F : FitAll" << "\n";
1786   di << "T : TopView" << "\n";
1787   di << "B : BottomView" << "\n";
1788   di << "R : RightView" << "\n";
1789   di << "L : LeftView" << "\n";
1790   di << "A : AxonometricView" << "\n";
1791   di << "D : ResetView" << "\n";
1792
1793   di << "========================="<<"\n";
1794   di << "S : Shading" << "\n";
1795   di << "W : Wireframe" << "\n";
1796   di << "H : HidelLineRemoval" << "\n";
1797   di << "U : Unset display mode" << "\n";
1798   di << "Delete : Remove selection from viewer" << "\n";
1799
1800   di << "========================="<<"\n";
1801   di << "Selection mode "<<"\n";
1802   di << "0 : Shape" <<"\n";
1803   di << "1 : Vertex" <<"\n";
1804   di << "2 : Edge" <<"\n";
1805   di << "3 : Wire" <<"\n";
1806   di << "4 : Face" <<"\n";
1807   di << "5 : Shell" <<"\n";
1808   di << "6 : Solid" <<"\n";
1809   di << "7 : Compound" <<"\n";
1810
1811   di << "========================="<<"\n";
1812   di << "Z : Switch Z clipping On/Off" << "\n";
1813   di << ", : Hilight next detected" << "\n";
1814   di << ". : Hilight previous detected" << "\n";
1815
1816   return 0;
1817 }
1818
1819 #ifdef WNT
1820
1821 static Standard_Boolean Ppick = 0;
1822 static Standard_Integer Pargc = 0;
1823 static const char**           Pargv = NULL;
1824
1825
1826 static LRESULT WINAPI AdvViewerWindowProc( HWND hwnd,
1827                                           UINT Msg,
1828                                           WPARAM wParam,
1829                                           LPARAM lParam )
1830 {
1831   if (!ViewerTest_myViews.IsEmpty()) {
1832
1833     WPARAM fwKeys = wParam;
1834
1835     switch( Msg ) {
1836     case WM_CLOSE:
1837        {
1838          // Delete view from map of views
1839          ViewerTest::RemoveView(FindViewIdByWindowHandle(hwnd));
1840          return 0;
1841        }
1842        break;
1843     case WM_ACTIVATE:
1844       if(LOWORD(wParam) == WA_CLICKACTIVE || LOWORD(wParam) == WA_ACTIVE
1845         || ViewerTest::CurrentView().IsNull())
1846       {
1847         // Activate inactive window
1848         if(GetWindowHandle(VT_GetWindow()) != hwnd)
1849         {
1850           ActivateView (FindViewIdByWindowHandle(hwnd));
1851         }
1852       }
1853       break;
1854     case WM_LBUTTONUP:
1855       IsDragged = Standard_False;
1856       if( !DragFirst )
1857       {
1858         HDC hdc = GetDC( hwnd );
1859         SelectObject( hdc, GetStockObject( HOLLOW_BRUSH ) );
1860         SetROP2( hdc, R2_NOT );
1861         Rectangle( hdc, X_ButtonPress, Y_ButtonPress, X_Motion, Y_Motion );
1862         ReleaseDC( hwnd, hdc );
1863
1864         const Handle(ViewerTest_EventManager) EM =
1865           ViewerTest::CurrentEventManager();
1866         if ( fwKeys & MK_SHIFT )
1867           EM->ShiftSelect( min( X_ButtonPress, X_Motion ), max( Y_ButtonPress, Y_Motion ),
1868           max( X_ButtonPress, X_Motion ), min( Y_ButtonPress, Y_Motion ));
1869         else
1870           EM->Select( min( X_ButtonPress, X_Motion ), max( Y_ButtonPress, Y_Motion ),
1871           max( X_ButtonPress, X_Motion ), min( Y_ButtonPress, Y_Motion ));
1872       }
1873       return ViewerWindowProc( hwnd, Msg, wParam, lParam );
1874
1875     case WM_LBUTTONDOWN:
1876       if( fwKeys == MK_LBUTTON || fwKeys == ( MK_LBUTTON | MK_SHIFT ) )
1877       {
1878         IsDragged = Standard_True;
1879         DragFirst = Standard_True;
1880         X_ButtonPress = LOWORD(lParam);
1881         Y_ButtonPress = HIWORD(lParam);
1882       }
1883       return ViewerWindowProc( hwnd, Msg, wParam, lParam );
1884
1885       break;
1886
1887     case WM_MOUSEMOVE:
1888       if( IsDragged )
1889       {
1890         HDC hdc = GetDC( hwnd );
1891
1892         HGDIOBJ anObj = SelectObject( hdc, GetStockObject( WHITE_PEN ) );
1893         SelectObject( hdc, GetStockObject( HOLLOW_BRUSH ) );
1894         SetROP2( hdc, R2_NOT );
1895
1896         if( !DragFirst )
1897           Rectangle( hdc, X_ButtonPress, Y_ButtonPress, X_Motion, Y_Motion );
1898
1899         DragFirst = Standard_False;
1900         X_Motion = LOWORD(lParam);
1901         Y_Motion = HIWORD(lParam);
1902
1903         Rectangle( hdc, X_ButtonPress, Y_ButtonPress, X_Motion, Y_Motion );
1904
1905         SelectObject( hdc, anObj );
1906
1907         ReleaseDC( hwnd, hdc );
1908       }
1909       else
1910         return ViewerWindowProc( hwnd, Msg, wParam, lParam );
1911       break;
1912
1913     default:
1914       return ViewerWindowProc( hwnd, Msg, wParam, lParam );
1915     }
1916     return 0;
1917   }
1918   return ViewerWindowProc( hwnd, Msg, wParam, lParam );
1919 }
1920
1921
1922 static LRESULT WINAPI ViewerWindowProc( HWND hwnd,
1923                                        UINT Msg,
1924                                        WPARAM wParam,
1925                                        LPARAM lParam )
1926 {
1927   static int Up = 1;
1928
1929   if ( !ViewerTest::CurrentView().IsNull() ) {
1930     PAINTSTRUCT    ps;
1931
1932     switch( Msg ) {
1933     case WM_PAINT:
1934       BeginPaint(hwnd, &ps);
1935       EndPaint(hwnd, &ps);
1936       VT_ProcessExpose();
1937       break;
1938
1939     case WM_SIZE:
1940       VT_ProcessConfigure();
1941       break;
1942
1943     case WM_KEYDOWN:
1944       if ((wParam != VK_SHIFT) && (wParam != VK_CONTROL))
1945       {
1946         char c[2];
1947         c[0] = (char) wParam;
1948         c[1] = '\0';
1949         if (wParam == VK_DELETE)
1950         {
1951           c[0] = THE_KEY_DELETE;
1952         }
1953         VT_ProcessKeyPress (c);
1954       }
1955       break;
1956
1957     case WM_LBUTTONUP:
1958     case WM_MBUTTONUP:
1959     case WM_RBUTTONUP:
1960       Up = 1;
1961       VT_ProcessButton3Release();
1962       break;
1963
1964     case WM_LBUTTONDOWN:
1965     case WM_MBUTTONDOWN:
1966     case WM_RBUTTONDOWN:
1967       {
1968         WPARAM fwKeys = wParam;
1969
1970         Up = 0;
1971
1972         X_ButtonPress = LOWORD(lParam);
1973         Y_ButtonPress = HIWORD(lParam);
1974
1975         if (Msg == WM_LBUTTONDOWN)
1976         {
1977           if (fwKeys & MK_CONTROL)
1978           {
1979             Ppick = VT_ProcessButton1Press (Pargc, Pargv, Ppick, (fwKeys & MK_SHIFT));
1980           }
1981           else
1982           {
1983             VT_ProcessButton1Press (Pargc, Pargv, Ppick, (fwKeys & MK_SHIFT));
1984           }
1985         }
1986         else if (Msg == WM_RBUTTONDOWN)
1987         {
1988           // Start rotation
1989           VT_ProcessButton3Press();
1990         }
1991       }
1992       break;
1993
1994     case WM_MOUSEMOVE:
1995       {
1996         //cout << "\t WM_MOUSEMOVE" << endl;
1997         WPARAM fwKeys = wParam;
1998         X_Motion = LOWORD(lParam);
1999         Y_Motion = HIWORD(lParam);
2000
2001         if ( Up &&
2002           fwKeys & ( MK_LBUTTON|MK_MBUTTON|MK_RBUTTON ) ) {
2003             Up = 0;
2004             X_ButtonPress = LOWORD(lParam);
2005             Y_ButtonPress = HIWORD(lParam);
2006
2007             if ( fwKeys & MK_RBUTTON ) {
2008               // Start rotation
2009               VT_ProcessButton3Press();
2010             }
2011           }
2012
2013           if ( fwKeys & MK_CONTROL ) {
2014             if ( fwKeys & MK_LBUTTON ) {
2015               ProcessControlButton1Motion();
2016             }
2017             else if ( fwKeys & MK_MBUTTON ||
2018               ((fwKeys&MK_LBUTTON) &&
2019               (fwKeys&MK_RBUTTON) ) ){
2020                 VT_ProcessControlButton2Motion();
2021               }
2022             else if ( fwKeys & MK_RBUTTON ) {
2023               VT_ProcessControlButton3Motion();
2024             }
2025           }
2026 #ifdef BUG
2027           else if ( fwKeys & MK_SHIFT ) {
2028             if ( fwKeys & MK_MBUTTON ||
2029               ((fwKeys&MK_LBUTTON) &&
2030               (fwKeys&MK_RBUTTON) ) ) {
2031                 cout << "ProcessZClipMotion()" << endl;
2032                 ProcessZClipMotion();
2033               }
2034           }
2035 #endif
2036           else if (GetWindowHandle (VT_GetWindow()) == hwnd)
2037           {
2038             if ((fwKeys & MK_MBUTTON
2039             || ((fwKeys & MK_LBUTTON) && (fwKeys & MK_RBUTTON))))
2040             {
2041               ProcessZClipMotion();
2042             }
2043             else
2044             {
2045               VT_ProcessMotion();
2046             }
2047           }
2048       }
2049       break;
2050
2051     default:
2052       return( DefWindowProc( hwnd, Msg, wParam, lParam ));
2053     }
2054     return 0L;
2055   }
2056
2057   return DefWindowProc( hwnd, Msg, wParam, lParam );
2058 }
2059
2060
2061
2062
2063 //==============================================================================
2064 //function : ViewerMainLoop
2065 //purpose  : Get a Event on the view and dispatch it
2066 //==============================================================================
2067
2068
2069 int ViewerMainLoop(Standard_Integer argc, const char** argv)
2070 {
2071   Ppick = (argc > 0)? 1 : 0;
2072   Pargc = argc;
2073   Pargv = argv;
2074
2075   if ( Ppick ) {
2076     MSG msg;
2077     msg.wParam = 1;
2078
2079     cout << "Start picking" << endl;
2080
2081     while ( Ppick == 1 ) {
2082       // Wait for a VT_ProcessButton1Press() to toggle pick to 1 or 0
2083       if (GetMessage(&msg, NULL, 0, 0) ) {
2084         TranslateMessage(&msg);
2085         DispatchMessage(&msg);
2086       }
2087     }
2088
2089     cout << "Picking done" << endl;
2090   }
2091
2092   return Ppick;
2093 }
2094
2095 #elif !defined(__APPLE__) || defined(MACOSX_USE_GLX)
2096
2097 int min( int a, int b )
2098 {
2099   if( a<b )
2100     return a;
2101   else
2102     return b;
2103 }
2104
2105 int max( int a, int b )
2106 {
2107   if( a>b )
2108     return a;
2109   else
2110     return b;
2111 }
2112
2113 int ViewerMainLoop(Standard_Integer argc, const char** argv)
2114
2115 {
2116   static XEvent aReport;
2117   Standard_Boolean pick = argc > 0;
2118   Display *aDisplay = GetDisplayConnection()->GetDisplay();
2119   XNextEvent (aDisplay, &aReport);
2120
2121   // Handle event for the chosen display connection
2122   switch (aReport.type) {
2123       case ClientMessage:
2124         {
2125           if(aReport.xclient.data.l[0] == GetDisplayConnection()->GetAtom(Aspect_XA_DELETE_WINDOW))
2126           {
2127             // Close the window
2128             ViewerTest::RemoveView(FindViewIdByWindowHandle (aReport.xclient.window));
2129           }
2130         }
2131         return 0;
2132      case FocusIn:
2133       {
2134          // Activate inactive view
2135          Window aWindow = GetWindowHandle(VT_GetWindow());
2136          if(aWindow != aReport.xfocus.window)
2137          {
2138            ActivateView (FindViewIdByWindowHandle (aReport.xfocus.window));
2139          }
2140       }
2141       break;
2142       case Expose:
2143         {
2144           VT_ProcessExpose();
2145         }
2146         break;
2147       case ConfigureNotify:
2148         {
2149           VT_ProcessConfigure();
2150         }
2151         break;
2152       case KeyPress:
2153         {
2154
2155           KeySym ks_ret ;
2156           char buf_ret[11] ;
2157           int ret_len ;
2158           XComposeStatus status_in_out;
2159
2160           ret_len = XLookupString( ( XKeyEvent *)&aReport ,
2161             (char *) buf_ret , 10 ,
2162             &ks_ret , &status_in_out ) ;
2163
2164
2165           buf_ret[ret_len] = '\0' ;
2166
2167           if (ret_len)
2168           {
2169             VT_ProcessKeyPress (buf_ret);
2170           }
2171         }
2172         break;
2173       case ButtonPress:
2174         {
2175           X_ButtonPress = aReport.xbutton.x;
2176           Y_ButtonPress = aReport.xbutton.y;
2177
2178           if (aReport.xbutton.button == Button1)
2179           {
2180             if (aReport.xbutton.state & ControlMask)
2181             {
2182               pick = VT_ProcessButton1Press (argc, argv, pick, (aReport.xbutton.state & ShiftMask));
2183             }
2184             else
2185             {
2186               IsDragged = Standard_True;
2187               DragFirst = Standard_True;
2188             }
2189           }
2190           else if (aReport.xbutton.button == Button3)
2191           {
2192             // Start rotation
2193             VT_ProcessButton3Press();
2194           }
2195         }
2196         break;
2197       case ButtonRelease:
2198         {
2199           if( IsDragged )
2200           {
2201             if( !DragFirst )
2202             {
2203               Aspect_Handle aWindow = VT_GetWindow()->XWindow();
2204               GC gc = XCreateGC( aDisplay, aWindow, 0, 0 );
2205               XDrawRectangle( aDisplay, aWindow, gc, min( X_ButtonPress, X_Motion ), min( Y_ButtonPress, Y_Motion ), abs( X_Motion-X_ButtonPress ), abs( Y_Motion-Y_ButtonPress ) );
2206             }
2207
2208             Handle( AIS_InteractiveContext ) aContext = ViewerTest::GetAISContext();
2209             if( aContext.IsNull() )
2210             {
2211               cout << "The context is null. Please use vinit before createmesh" << endl;
2212               return 0;
2213             }
2214
2215             Standard_Boolean ShiftPressed = ( aReport.xbutton.state & ShiftMask );
2216             if( aReport.xbutton.button==1 )
2217               if( DragFirst )
2218                 if( ShiftPressed )
2219                 {
2220                   aContext->ShiftSelect();
2221                 }
2222                 else
2223                 {
2224                   aContext->Select();
2225                 }
2226               else
2227                 if( ShiftPressed )
2228                 {
2229                   aContext->ShiftSelect( min( X_ButtonPress, X_Motion ), min( Y_ButtonPress, Y_Motion ),
2230                     max( X_ButtonPress, X_Motion ), max( Y_ButtonPress, Y_Motion ),
2231                     ViewerTest::CurrentView());
2232                 }
2233                 else
2234                 {
2235                   aContext->Select( min( X_ButtonPress, X_Motion ), min( Y_ButtonPress, Y_Motion ),
2236                     max( X_ButtonPress, X_Motion ), max( Y_ButtonPress, Y_Motion ),
2237                     ViewerTest::CurrentView() );
2238                 }
2239             else
2240               VT_ProcessButton3Release();
2241
2242             IsDragged = Standard_False;
2243           }
2244           else
2245             VT_ProcessButton3Release();
2246         }
2247         break;
2248       case MotionNotify:
2249         {
2250           if (GetWindowHandle (VT_GetWindow()) != aReport.xmotion.window)
2251           {
2252             break;
2253           }
2254           if( IsDragged )
2255           {
2256             Aspect_Handle aWindow = VT_GetWindow()->XWindow();
2257             GC gc = XCreateGC( aDisplay, aWindow, 0, 0 );
2258             XSetFunction( aDisplay, gc, GXinvert );
2259
2260             if( !DragFirst )
2261               XDrawRectangle(aDisplay, aWindow, gc, min( X_ButtonPress, X_Motion ), min( Y_ButtonPress, Y_Motion ), abs( X_Motion-X_ButtonPress ), abs( Y_Motion-Y_ButtonPress ) );
2262
2263             X_Motion = aReport.xmotion.x;
2264             Y_Motion = aReport.xmotion.y;
2265             DragFirst = Standard_False;
2266
2267             XDrawRectangle( aDisplay, aWindow, gc, min( X_ButtonPress, X_Motion ), min( Y_ButtonPress, Y_Motion ), abs( X_Motion-X_ButtonPress ), abs( Y_Motion-Y_ButtonPress ) );
2268           }
2269           else
2270           {
2271             X_Motion = aReport.xmotion.x;
2272             Y_Motion = aReport.xmotion.y;
2273
2274             // remove all the ButtonMotionMaskr
2275             while( XCheckMaskEvent( aDisplay, ButtonMotionMask, &aReport) ) ;
2276
2277             if ( ZClipIsOn && aReport.xmotion.state & ShiftMask ) {
2278               if ( Abs(X_Motion - X_ButtonPress) > 2 ) {
2279
2280                 Quantity_Length VDX, VDY;
2281
2282                 ViewerTest::CurrentView()->Size(VDX,VDY);
2283                 Standard_Real VDZ =0 ;
2284                 VDZ = ViewerTest::CurrentView()->ZSize();
2285
2286                 printf("%f,%f,%f\n", VDX, VDY, VDZ);
2287
2288                 Quantity_Length dx = 0 ;
2289                 dx = ViewerTest::CurrentView()->Convert(X_Motion - X_ButtonPress);
2290
2291                 cout << dx << endl;
2292
2293                 dx = dx / VDX * VDZ;
2294
2295                 cout << dx << endl;
2296
2297                 ViewerTest::CurrentView()->Redraw();
2298               }
2299             }
2300
2301             if ( aReport.xmotion.state & ControlMask ) {
2302               if ( aReport.xmotion.state & Button1Mask ) {
2303                 ProcessControlButton1Motion();
2304               }
2305               else if ( aReport.xmotion.state & Button2Mask ) {
2306                 VT_ProcessControlButton2Motion();
2307               }
2308               else if ( aReport.xmotion.state & Button3Mask ) {
2309                 VT_ProcessControlButton3Motion();
2310               }
2311             }
2312             else
2313             {
2314               VT_ProcessMotion();
2315             }
2316           }
2317         }
2318         break;
2319 }
2320 return pick;
2321 }
2322
2323 //==============================================================================
2324 //function : VProcessEvents
2325 //purpose  : call by Tk_CreateFileHandler() to be able to manage the
2326 //       event in the Viewer window
2327 //==============================================================================
2328
2329 static void VProcessEvents(ClientData,int)
2330 {
2331   NCollection_Vector<int> anEventNumbers;
2332   // Get number of messages from every display
2333   for (NCollection_DoubleMap <TCollection_AsciiString, Handle(Graphic3d_GraphicDriver)>::Iterator
2334        anIter (ViewerTest_myDrivers); anIter.More(); anIter.Next())
2335   {
2336     anEventNumbers.Append(XPending (anIter.Key2()->GetDisplayConnection()->GetDisplay()));
2337   }
2338     // Handle events for every display
2339   int anEventIter = 0;
2340   for (NCollection_DoubleMap <TCollection_AsciiString, Handle(Graphic3d_GraphicDriver)>::Iterator
2341        anIter (ViewerTest_myDrivers); anIter.More(); anIter.Next(), anEventIter++)
2342   {
2343     for (int i = 0; i < anEventNumbers.Value(anEventIter) &&
2344          XPending (anIter.Key2()->GetDisplayConnection()->GetDisplay()) > 0; ++i)
2345     {
2346       SetDisplayConnection (anIter.Key2()->GetDisplayConnection());
2347       int anEventResult = ViewerMainLoop( 0, NULL);
2348       // If window is closed or context was not found finish current event processing loop
2349       if (!anEventResult)
2350         return;
2351     }
2352   }
2353
2354   SetDisplayConnection (ViewerTest::GetAISContext()->CurrentViewer()->Driver()->GetDisplayConnection());
2355
2356 }
2357 #endif
2358
2359 //==============================================================================
2360 //function : OSWindowSetup
2361 //purpose  : Setup for the X11 window to be able to cath the event
2362 //==============================================================================
2363
2364
2365 static void OSWindowSetup()
2366 {
2367 #if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
2368   // X11
2369
2370   Window  window   = VT_GetWindow()->XWindow();
2371   SetDisplayConnection (ViewerTest::CurrentView()->Viewer()->Driver()->GetDisplayConnection());
2372   Display *aDisplay = GetDisplayConnection()->GetDisplay();
2373   XSynchronize(aDisplay, 1);
2374
2375   // X11 : For keyboard on SUN
2376   XWMHints wmhints;
2377   wmhints.flags = InputHint;
2378   wmhints.input = 1;
2379
2380   XSetWMHints( aDisplay, window, &wmhints);
2381
2382   XSelectInput( aDisplay, window,  ExposureMask | KeyPressMask |
2383     ButtonPressMask | ButtonReleaseMask |
2384     StructureNotifyMask |
2385     PointerMotionMask |
2386     Button1MotionMask | Button2MotionMask |
2387     Button3MotionMask | FocusChangeMask
2388     );
2389   Atom aDeleteWindowAtom = GetDisplayConnection()->GetAtom(Aspect_XA_DELETE_WINDOW);
2390   XSetWMProtocols(aDisplay, window, &aDeleteWindowAtom, 1);
2391
2392   XSynchronize(aDisplay, 0);
2393
2394 #else
2395   // WNT
2396 #endif
2397
2398 }
2399
2400
2401 //==============================================================================
2402 //function : VFit
2403
2404 //purpose  : Fitall, no DRAW arguments
2405 //Draw arg : No args
2406 //==============================================================================
2407
2408 static int VFit(Draw_Interpretor& , Standard_Integer , const char** )
2409 {
2410   const Handle(V3d_View) aView = ViewerTest::CurrentView();
2411   Handle(NIS_View) V = Handle(NIS_View)::DownCast(aView);
2412   if (V.IsNull() == Standard_False) {
2413     V->FitAll3d();
2414   } else if (aView.IsNull() == Standard_False) {
2415     aView->FitAll();
2416   }
2417   return 0;
2418 }
2419
2420 //==============================================================================
2421 //function : VZFit
2422 //purpose  : ZFitall, no DRAW arguments
2423 //Draw arg : No args
2424 //==============================================================================
2425
2426 static int VZFit(Draw_Interpretor& , Standard_Integer , const char** )
2427 {
2428   Handle(V3d_View) V = ViewerTest::CurrentView();
2429   if ( !V.IsNull() ) V->ZFitAll(); return 0; }
2430
2431
2432 static int VRepaint(Draw_Interpretor& , Standard_Integer , const char** )
2433 {
2434   Handle(V3d_View) V = ViewerTest::CurrentView();
2435   if ( !V.IsNull() ) V->Redraw(); return 0;
2436 }
2437
2438
2439 //==============================================================================
2440 //function : VClear
2441 //purpose  : Remove all the object from the viewer
2442 //Draw arg : No args
2443 //==============================================================================
2444
2445 static int VClear(Draw_Interpretor& , Standard_Integer , const char** )
2446 {
2447   Handle(V3d_View) V = ViewerTest::CurrentView();
2448   if(!V.IsNull())
2449     ViewerTest::Clear();
2450   return 0;
2451 }
2452
2453 //==============================================================================
2454 //function : VPick
2455 //purpose  :
2456 //==============================================================================
2457
2458 static int VPick(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2459 { if (ViewerTest::CurrentView().IsNull() ) return 1;
2460
2461 if ( argc < 4 ) {
2462   di << argv[0] << "Invalid number of arguments" << "\n";
2463   return 1;
2464 }
2465
2466 while (ViewerMainLoop( argc, argv)) {
2467 }
2468
2469 return 0;
2470 }
2471
2472 //==============================================================================
2473 //function : InitViewerTest
2474 //purpose  : initialisation de toutes les variables static de  ViewerTest (dp)
2475 //==============================================================================
2476
2477 void ViewerTest_InitViewerTest (const Handle(AIS_InteractiveContext)& theContext)
2478 {
2479   Handle(V3d_Viewer) aViewer = theContext->CurrentViewer();
2480   ViewerTest::SetAISContext(theContext);
2481   aViewer->InitActiveViews();
2482   Handle(V3d_View) aView = aViewer->ActiveView();
2483   if (aViewer->MoreActiveViews()) ViewerTest::CurrentView(aView);
2484   ViewerTest::ResetEventManager();
2485   Handle(Aspect_Window) aWindow = aView->Window();
2486 #if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
2487   // X11
2488   VT_GetWindow() = Handle(Xw_Window)::DownCast(aWindow);
2489   OSWindowSetup();
2490   static int aFirst = 1;
2491   if ( aFirst ) {
2492 #if TCL_MAJOR_VERSION  < 8
2493     Tk_CreateFileHandler((void*)XConnectionNumber(GetDisplayConnection()->GetDisplay()),
2494       TK_READABLE, VProcessEvents, (ClientData) 0);
2495 #else
2496     Tk_CreateFileHandler(XConnectionNumber(GetDisplayConnection()->GetDisplay()),
2497       TK_READABLE, VProcessEvents, (ClientData) 0);
2498 #endif
2499     aFirst = 0;
2500   }
2501 #endif
2502 }
2503
2504 //==============================================================================
2505 //function : VSetBg
2506 //purpose  : Load image as background
2507 //==============================================================================
2508
2509 static int VSetBg(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2510 {
2511   if (argc < 2 || argc > 3)
2512   {
2513     di << "Usage : " << argv[0] << " imagefile [filltype] : Load image as background" << "\n";
2514     di << "filltype can be one of CENTERED, TILED, STRETCH, NONE" << "\n";
2515     return 1;
2516   }
2517
2518   Handle(AIS_InteractiveContext) AISContext = ViewerTest::GetAISContext();
2519   if(AISContext.IsNull())
2520   {
2521     di << "use 'vinit' command before " << argv[0] << "\n";
2522     return 1;
2523   }
2524
2525   Aspect_FillMethod aFillType = Aspect_FM_CENTERED;
2526   if (argc == 3)
2527   {
2528     const char* szType = argv[2];
2529     if      (strcmp(szType, "NONE"    ) == 0) aFillType = Aspect_FM_NONE;
2530     else if (strcmp(szType, "CENTERED") == 0) aFillType = Aspect_FM_CENTERED;
2531     else if (strcmp(szType, "TILED"   ) == 0) aFillType = Aspect_FM_TILED;
2532     else if (strcmp(szType, "STRETCH" ) == 0) aFillType = Aspect_FM_STRETCH;
2533     else
2534     {
2535       di << "Wrong fill type : " << szType << "\n";
2536       di << "Must be one of CENTERED, TILED, STRETCH, NONE" << "\n";
2537       return 1;
2538     }
2539   }
2540
2541   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2542   V3dView->SetBackgroundImage(argv[1], aFillType, Standard_True);
2543
2544   return 0;
2545 }
2546
2547 //==============================================================================
2548 //function : VSetBgMode
2549 //purpose  : Change background image fill type
2550 //==============================================================================
2551
2552 static int VSetBgMode(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2553 {
2554   if (argc != 2)
2555   {
2556     di << "Usage : " << argv[0] << " filltype : Change background image mode" << "\n";
2557     di << "filltype must be one of CENTERED, TILED, STRETCH, NONE" << "\n";
2558     return 1;
2559   }
2560
2561   Handle(AIS_InteractiveContext) AISContext = ViewerTest::GetAISContext();
2562   if(AISContext.IsNull())
2563   {
2564     di << "use 'vinit' command before " << argv[0] << "\n";
2565     return 1;
2566   }
2567   Aspect_FillMethod aFillType = Aspect_FM_NONE;
2568   const char* szType = argv[1];
2569   if      (strcmp(szType, "NONE"    ) == 0) aFillType = Aspect_FM_NONE;
2570   else if (strcmp(szType, "CENTERED") == 0) aFillType = Aspect_FM_CENTERED;
2571   else if (strcmp(szType, "TILED"   ) == 0) aFillType = Aspect_FM_TILED;
2572   else if (strcmp(szType, "STRETCH" ) == 0) aFillType = Aspect_FM_STRETCH;
2573   else
2574   {
2575     di << "Wrong fill type : " << szType << "\n";
2576     di << "Must be one of CENTERED, TILED, STRETCH, NONE" << "\n";
2577     return 1;
2578   }
2579   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2580   V3dView->SetBgImageStyle(aFillType, Standard_True);
2581   return 0;
2582 }
2583
2584 //==============================================================================
2585 //function : VSetGradientBg
2586 //purpose  : Mount gradient background
2587 //==============================================================================
2588 static int VSetGradientBg(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2589 {
2590   if (argc != 8 )
2591   {
2592     di << "Usage : " << argv[0] << " R1 G1 B1 R2 G2 B2 Type : Mount gradient background" << "\n";
2593     di << "R1,G1,B1,R2,G2,B2 = [0..255]" << "\n";
2594     di << "Type must be one of 0 = NONE, 1 = HOR, 2 = VER, 3 = DIAG1, 4 = DIAG2" << "\n";
2595     di << "                    5 = CORNER1, 6 = CORNER2, 7 = CORNER3, 8 = CORNER4" << "\n";
2596     return 1;
2597   }
2598
2599   Handle(AIS_InteractiveContext) AISContext = ViewerTest::GetAISContext();
2600   if(AISContext.IsNull())
2601   {
2602     di << "use 'vinit' command before " << argv[0] << "\n";
2603     return 1;
2604   }
2605   if (argc == 8)
2606   {
2607
2608     Standard_Real R1 = Draw::Atof(argv[1])/255.;
2609     Standard_Real G1 = Draw::Atof(argv[2])/255.;
2610     Standard_Real B1 = Draw::Atof(argv[3])/255.;
2611     Quantity_Color aColor1(R1,G1,B1,Quantity_TOC_RGB);
2612
2613     Standard_Real R2 = Draw::Atof(argv[4])/255.;
2614     Standard_Real G2 = Draw::Atof(argv[5])/255.;
2615     Standard_Real B2 = Draw::Atof(argv[6])/255.;
2616
2617     Quantity_Color aColor2(R2,G2,B2,Quantity_TOC_RGB);
2618     int aType = Draw::Atoi(argv[7]);
2619     if( aType < 0 || aType > 8 )
2620     {
2621       di << "Wrong fill type " << "\n";
2622       di << "Must be one of 0 = NONE, 1 = HOR, 2 = VER, 3 = DIAG1, 4 = DIAG2" << "\n";
2623       di << "               5 = CORNER1, 6 = CORNER2, 7 = CORNER3, 8 = CORNER4" << "\n";
2624       return 1;
2625     }
2626
2627     Aspect_GradientFillMethod aMethod = Aspect_GradientFillMethod(aType);
2628
2629     Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2630     V3dView->SetBgGradientColors( aColor1, aColor2, aMethod, 1);
2631   }
2632
2633   return 0;
2634 }
2635
2636 //==============================================================================
2637 //function : VSetGradientBgMode
2638 //purpose  : Change gradient background fill style
2639 //==============================================================================
2640 static int VSetGradientBgMode(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2641 {
2642   if (argc != 2 )
2643   {
2644     di << "Usage : " << argv[0] << " Type : Change gradient background fill type" << "\n";
2645     di << "Type must be one of 0 = NONE, 1 = HOR, 2 = VER, 3 = DIAG1, 4 = DIAG2" << "\n";
2646     di << "                    5 = CORNER1, 6 = CORNER2, 7 = CORNER3, 8 = CORNER4" << "\n";
2647     return 1;
2648   }
2649
2650   Handle(AIS_InteractiveContext) AISContext = ViewerTest::GetAISContext();
2651   if(AISContext.IsNull())
2652   {
2653     di << "use 'vinit' command before " << argv[0] << "\n";
2654     return 1;
2655   }
2656   if (argc == 2)
2657   {
2658     int aType = Draw::Atoi(argv[1]);
2659     if( aType < 0 || aType > 8 )
2660     {
2661       di << "Wrong fill type " << "\n";
2662       di << "Must be one of 0 = NONE, 1 = HOR, 2 = VER, 3 = DIAG1, 4 = DIAG2" << "\n";
2663       di << "               5 = CORNER1, 6 = CORNER2, 7 = CORNER3, 8 = CORNER4" << "\n";
2664       return 1;
2665     }
2666
2667     Aspect_GradientFillMethod aMethod = Aspect_GradientFillMethod(aType);
2668
2669     Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2670     V3dView->SetBgGradientStyle( aMethod, 1 );
2671   }
2672
2673   return 0;
2674 }
2675
2676 //==============================================================================
2677 //function : VSetColorBg
2678 //purpose  : Set color background
2679 //==============================================================================
2680 static int VSetColorBg(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2681 {
2682   if (argc != 4 )
2683   {
2684     di << "Usage : " << argv[0] << " R G B : Set color background" << "\n";
2685     di << "R,G,B = [0..255]" << "\n";
2686     return 1;
2687   }
2688
2689   Handle(AIS_InteractiveContext) AISContext = ViewerTest::GetAISContext();
2690   if(AISContext.IsNull())
2691   {
2692     di << "use 'vinit' command before " << argv[0] << "\n";
2693     return 1;
2694   }
2695   if (argc == 4)
2696   {
2697
2698     Standard_Real R = Draw::Atof(argv[1])/255.;
2699     Standard_Real G = Draw::Atof(argv[2])/255.;
2700     Standard_Real B = Draw::Atof(argv[3])/255.;
2701     Quantity_Color aColor(R,G,B,Quantity_TOC_RGB);
2702
2703     Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2704     V3dView->SetBackgroundColor( aColor );
2705     V3dView->Update();
2706   }
2707
2708   return 0;
2709 }
2710
2711 //==============================================================================
2712 //function : VScale
2713 //purpose  : View Scaling
2714 //==============================================================================
2715
2716 static int VScale(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2717 {
2718   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2719   if ( V3dView.IsNull() ) return 1;
2720
2721   if ( argc != 4 ) {
2722     di << argv[0] << "Invalid number of arguments" << "\n";
2723     return 1;
2724   }
2725   V3dView->SetAxialScale( Draw::Atof(argv[1]),  Draw::Atof(argv[2]),  Draw::Atof(argv[3]) );
2726   return 0;
2727 }
2728 //==============================================================================
2729 //function : VTestZBuffTrihedron
2730 //purpose  : Displays a V3d_ZBUFFER'ed or V3d_WIREFRAME'd trihedron
2731 //==============================================================================
2732
2733 static int VTestZBuffTrihedron(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2734 {
2735   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2736   if ( V3dView.IsNull() ) return 1;
2737
2738   V3dView->ZBufferTriedronSetup();
2739
2740   if ( argc == 1 ) {
2741     // Set up default trihedron parameters
2742     V3dView->TriedronDisplay( Aspect_TOTP_LEFT_LOWER, Quantity_NOC_WHITE, 0.1, V3d_ZBUFFER );
2743   } else
2744   if ( argc == 7 )
2745   {
2746     Aspect_TypeOfTriedronPosition aPosition = Aspect_TOTP_LEFT_LOWER;
2747     const char* aPosType = argv[1];
2748
2749     if ( strcmp(aPosType, "center") == 0 )
2750     {
2751       aPosition = Aspect_TOTP_CENTER;
2752     } else
2753     if (strcmp(aPosType, "left_lower") == 0)
2754     {
2755       aPosition = Aspect_TOTP_LEFT_LOWER;
2756     } else
2757     if (strcmp(aPosType, "left_upper") == 0)
2758     {
2759       aPosition = Aspect_TOTP_LEFT_UPPER;
2760     } else
2761     if (strcmp(aPosType, "right_lower") == 0)
2762     {
2763       aPosition = Aspect_TOTP_RIGHT_LOWER;
2764     } else
2765     if (strcmp(aPosType, "right_upper") == 0)
2766     {
2767       aPosition = Aspect_TOTP_RIGHT_UPPER;
2768     } else
2769     {
2770       di << argv[1] << " Invalid type of alignment"  << "\n";
2771       di << "Must be one of [ center, left_lower,"   << "\n";
2772       di << "left_upper, right_lower, right_upper ]" << "\n";
2773       return 1;
2774     }
2775
2776     Standard_Real R = Draw::Atof(argv[2])/255.;
2777     Standard_Real G = Draw::Atof(argv[3])/255.;
2778     Standard_Real B = Draw::Atof(argv[4])/255.;
2779     Quantity_Color aColor(R, G, B, Quantity_TOC_RGB);
2780
2781     Standard_Real aScale = Draw::Atof(argv[5]);
2782
2783     if( aScale <= 0.0 )
2784     {
2785       di << argv[5] << " Invalid value. Must be > 0" << "\n";
2786       return 1;
2787     }
2788
2789     V3d_TypeOfVisualization aPresentation = V3d_ZBUFFER;
2790     const char* aPresType = argv[6];
2791
2792     if ( strcmp(aPresType, "wireframe") == 0 )
2793     {
2794       aPresentation = V3d_WIREFRAME;
2795     } else
2796     if (strcmp(aPresType, "zbuffer") == 0)
2797     {
2798       aPresentation = V3d_ZBUFFER;
2799     } else
2800     {
2801       di << argv[6] << " Invalid type of visualization" << "\n";
2802       di << "Must be one of [ wireframe, zbuffer ]"     << "\n";
2803       return 1;
2804     }
2805
2806     V3dView->TriedronDisplay( aPosition, aColor.Name(), aScale, aPresentation );
2807
2808   } else
2809   {
2810     di << argv[0] << " Invalid number of arguments" << "\n";
2811     return 1;
2812   }
2813
2814   V3dView->ZFitAll();
2815
2816   return 0;
2817 }
2818
2819 //==============================================================================
2820 //function : VRotate
2821 //purpose  : Camera Rotating
2822 //==============================================================================
2823
2824 static int VRotate( Draw_Interpretor& di, Standard_Integer argc, const char** argv ) {
2825   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2826   if ( V3dView.IsNull() ) {
2827     return 1;
2828   }
2829
2830   if ( argc == 4 ) {
2831     V3dView->Rotate( Draw::Atof(argv[1]), Draw::Atof(argv[2]), Draw::Atof(argv[3]) );
2832     return 0;
2833   } else if ( argc == 7 ) {
2834     V3dView->Rotate( Draw::Atof(argv[1]), Draw::Atof(argv[2]), Draw::Atof(argv[3]), Draw::Atof(argv[4]), Draw::Atof(argv[5]), Draw::Atof(argv[6]) );
2835     return 0;
2836   } else {
2837     di << argv[0] << " Invalid number of arguments" << "\n";
2838     return 1;
2839   }
2840 }
2841
2842 //==============================================================================
2843 //function : VZoom
2844 //purpose  : View zoom in / out (relative to current zoom)
2845 //==============================================================================
2846
2847 static int VZoom( Draw_Interpretor& di, Standard_Integer argc, const char** argv ) {
2848   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2849   if ( V3dView.IsNull() ) {
2850     return 1;
2851   }
2852
2853   if ( argc == 2 ) {
2854     Standard_Real coef = Draw::Atof(argv[1]);
2855     if ( coef <= 0.0 ) {
2856       di << argv[1] << "Invalid value" << "\n";
2857       return 1;
2858     }
2859     V3dView->SetZoom( Draw::Atof(argv[1]) );
2860     return 0;
2861   } else {
2862     di << argv[0] << " Invalid number of arguments" << "\n";
2863     return 1;
2864   }
2865 }
2866
2867 //==============================================================================
2868 //function : VPan
2869 //purpose  : View panning (in pixels)
2870 //==============================================================================
2871
2872 static int VPan( Draw_Interpretor& di, Standard_Integer argc, const char** argv ) {
2873   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2874   if ( V3dView.IsNull() ) return 1;
2875
2876   if ( argc == 3 ) {
2877     V3dView->Pan( Draw::Atoi(argv[1]), Draw::Atoi(argv[2]) );
2878     return 0;
2879   } else {
2880     di << argv[0] << " Invalid number of arguments" << "\n";
2881     return 1;
2882   }
2883 }
2884
2885
2886 //==============================================================================
2887 //function : VExport
2888 //purpose  : Export the view to a vector graphic format (PS, EMF, PDF)
2889 //==============================================================================
2890
2891 static int VExport(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
2892 {
2893   Handle(V3d_View) V3dView = ViewerTest::CurrentView();
2894   if (V3dView.IsNull())
2895     return 1;
2896
2897   if (argc == 1)
2898   {
2899     std::cout << "Usage: " << argv[0] << " Filename [Format]\n";
2900     return 1;
2901   }
2902
2903   Graphic3d_ExportFormat anExpFormat = Graphic3d_EF_PDF;
2904   TCollection_AsciiString aFormatStr;
2905
2906   TCollection_AsciiString aFileName (argv[1]);
2907   Standard_Integer aLen = aFileName.Length();
2908
2909   if (argc > 2)
2910   {
2911     aFormatStr = TCollection_AsciiString (argv[2]);
2912   }
2913   else if (aLen >= 4)
2914   {
2915     if (aFileName.Value (aLen - 2) == '.')
2916     {
2917       aFormatStr = aFileName.SubString (aLen - 1, aLen);
2918     }
2919     else if (aFileName.Value (aLen - 3) == '.')
2920     {
2921       aFormatStr = aFileName.SubString (aLen - 2, aLen);
2922     }
2923     else
2924     {
2925       std::cout << "Export format couln't be detected from filename '" << argv[1] << "'\n";
2926       return 1;
2927     }
2928   }
2929   else
2930   {
2931     std::cout << "Export format couln't be detected from filename '" << argv[1] << "'\n";
2932     return 1;
2933   }
2934
2935   aFormatStr.UpperCase();
2936   if (aFormatStr == "PS")
2937     anExpFormat = Graphic3d_EF_PostScript;
2938   else if (aFormatStr == "EPS")
2939     anExpFormat = Graphic3d_EF_EnhPostScript;
2940   else if (aFormatStr == "TEX")
2941     anExpFormat = Graphic3d_EF_TEX;
2942   else if (aFormatStr == "PDF")
2943     anExpFormat = Graphic3d_EF_PDF;
2944   else if (aFormatStr == "SVG")
2945     anExpFormat = Graphic3d_EF_SVG;
2946   else if (aFormatStr == "PGF")
2947     anExpFormat = Graphic3d_EF_PGF;
2948   else if (aFormatStr == "EMF")
2949     anExpFormat = Graphic3d_EF_EMF;
2950   else
2951   {
2952     std::cout << "Invalid export format '" << aFormatStr << "'\n";
2953     return 1;
2954   }
2955
2956   try {
2957     if (!V3dView->View()->Export (argv[1], anExpFormat))
2958     {
2959       di << "Error: export of image to " << aFormatStr << " failed!\n";
2960     }
2961   }
2962   catch (Standard_Failure)
2963   {
2964     di << "Error: export of image to " << aFormatStr << " failed";
2965     di << " (exception: " << Standard_Failure::Caught()->GetMessageString() << ")";
2966   }
2967   return 0;
2968 }
2969
2970 //==============================================================================
2971 //function : VColorScale
2972 //purpose  : representation color scale
2973 //==============================================================================
2974 #include <V3d_ColorScale.hxx>
2975
2976 static int VColorScale (Draw_Interpretor& di, Standard_Integer argc, const char ** argv)
2977 {
2978   if ( argc != 1 && argc != 4 && argc != 5 && argc != 6 && argc != 8 )
2979   {
2980     di << "Usage : " << argv[0] << " [RangeMin = 0 RangeMax = 100 Intervals = 10 HeightFont = 16 Position = Right X = 0 Y = 0]  " << "\n";
2981     return 1;
2982   }
2983
2984   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
2985   if(aContext.IsNull()) {
2986     di << argv[0] << " ERROR : use 'vinit' command before " << "\n";
2987     return -1;
2988   }
2989
2990   Standard_Real minRange = 0. , maxRange = 100. ;
2991
2992   Standard_Integer numIntervals = 10 ;
2993   Standard_Integer textHeight = 16;
2994   Aspect_TypeOfColorScalePosition position = Aspect_TOCSP_RIGHT;
2995   Standard_Real X = 0., Y = 0. ;
2996
2997   if ( argc < 9 )
2998   {
2999      if( argc > 3 )
3000      {
3001        minRange = Draw::Atof( argv[1] );
3002        maxRange = Draw::Atof( argv[2] );
3003        numIntervals = Draw::Atoi( argv[3] );
3004      }
3005      if ( argc > 4 )
3006        textHeight = Draw::Atoi( argv[4] );
3007      if ( argc > 5 )
3008        position = (Aspect_TypeOfColorScalePosition)Draw::Atoi( argv[5] );
3009      if ( argc > 7 )
3010      {
3011        X = Draw::Atof( argv[6] );
3012        Y = Draw::Atof( argv[7] );
3013      }
3014   }
3015   Handle(V3d_View) curView = ViewerTest::CurrentView( );
3016   if ( curView.IsNull( ) )
3017     return 1;
3018   Handle(Aspect_ColorScale) aCSV = curView->ColorScale( );
3019   Handle(V3d_ColorScale) aCS = ( Handle( V3d_ColorScale )::DownCast( aCSV ) );
3020   if( ! aCS.IsNull( ) )
3021   {
3022     aCS->SetPosition( X , Y );
3023     aCS->SetHeight( 0.95) ;
3024     aCS->SetTextHeight( textHeight );
3025     aCS->SetRange( minRange , maxRange );
3026     aCS->SetNumberOfIntervals( numIntervals );
3027     aCS->SetLabelPosition( position );
3028     if( !curView->ColorScaleIsDisplayed() )
3029       curView->ColorScaleDisplay( );
3030   }
3031   return 0;
3032 }
3033
3034 //==============================================================================
3035 //function : VGraduatedTrihedron
3036 //purpose  : Displays a graduated trihedron
3037 //==============================================================================
3038
3039 static void AddMultibyteString (TCollection_ExtendedString &name, const char *arg)
3040 {
3041   const char *str = arg;
3042   while (*str)
3043   {
3044     unsigned short c1 = *str++;
3045     unsigned short c2 = *str++;
3046     if (!c1 || !c2) break;
3047     name += (Standard_ExtCharacter)((c1 << 8) | c2);
3048   }
3049 }
3050
3051 static int VGraduatedTrihedron(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
3052 {
3053   // Check arguments
3054   if (argc != 2 && argc < 5)
3055   {
3056     di<<"Error: "<<argv[0]<<" - invalid number of arguments\n";
3057     di<<"Usage: type help "<<argv[0]<<"\n";
3058     return 1; //TCL_ERROR
3059   }
3060
3061   Handle(V3d_View) aV3dView = ViewerTest::CurrentView();
3062
3063   // Create 3D view if it doesn't exist
3064   if ( aV3dView.IsNull() )
3065   {
3066     ViewerTest::ViewerInit();
3067     aV3dView = ViewerTest::CurrentView();
3068     if( aV3dView.IsNull() )
3069     {
3070       di << "Error: Cannot create a 3D view\n";
3071       return 1; //TCL_ERROR
3072     }
3073   }
3074
3075   // Erase (==0) or display (!=0)
3076   const int display = Draw::Atoi(argv[1]);
3077
3078   if (display)
3079   {
3080     // Text font
3081     TCollection_AsciiString font;
3082     if (argc < 6)
3083       font.AssignCat("Courier");
3084     else
3085       font.AssignCat(argv[5]);
3086
3087     // Text is multibyte
3088     const Standard_Boolean isMultibyte = (argc < 7)? Standard_False : (Draw::Atoi(argv[6]) != 0);
3089
3090     // Set axis names
3091     TCollection_ExtendedString xname, yname, zname;
3092     if (argc >= 5)
3093     {
3094       if (isMultibyte)
3095       {
3096         AddMultibyteString(xname, argv[2]);
3097         AddMultibyteString(yname, argv[3]);
3098         AddMultibyteString(zname, argv[4]);
3099       }
3100       else
3101       {
3102         xname += argv[2];
3103         yname += argv[3];
3104         zname += argv[4];
3105       }
3106     }
3107     else
3108     {
3109       xname += "X (mm)";
3110       yname += "Y (mm)";
3111       zname += "Z (mm)";
3112     }
3113
3114     aV3dView->GraduatedTrihedronDisplay(xname, yname, zname,
3115                                         Standard_True/*xdrawname*/, Standard_True/*ydrawname*/, Standard_True/*zdrawname*/,
3116                                         Standard_True/*xdrawvalues*/, Standard_True/*ydrawvalues*/, Standard_True/*zdrawvalues*/,
3117                                         Standard_True/*drawgrid*/,
3118                                         Standard_True/*drawaxes*/,
3119                                         5/*nbx*/, 5/*nby*/, 5/*nbz*/,
3120                                         10/*xoffset*/, 10/*yoffset*/, 10/*zoffset*/,
3121                                         30/*xaxisoffset*/, 30/*yaxisoffset*/, 30/*zaxisoffset*/,
3122                                         Standard_True/*xdrawtickmarks*/, Standard_True/*ydrawtickmarks*/, Standard_True/*zdrawtickmarks*/,
3123                                         10/*xtickmarklength*/, 10/*ytickmarklength*/, 10/*ztickmarklength*/,
3124                                         Quantity_NOC_WHITE/*gridcolor*/,
3125                                         Quantity_NOC_RED/*xnamecolor*/,Quantity_NOC_GREEN/*ynamecolor*/,Quantity_NOC_BLUE1/*znamecolor*/,
3126                                         Quantity_NOC_RED/*xcolor*/,Quantity_NOC_GREEN/*ycolor*/,Quantity_NOC_BLUE1/*zcolor*/,font);
3127   }
3128   else
3129     aV3dView->GraduatedTrihedronErase();
3130
3131   ViewerTest::GetAISContext()->UpdateCurrentViewer();
3132   aV3dView->Redraw();
3133
3134   return 0;
3135 }
3136
3137 //==============================================================================
3138 //function : VPrintView
3139 //purpose  : Test printing algorithm, print the view to image file with given
3140 //           width and height. Printing implemented only for WNT.
3141 //==============================================================================
3142 static int VPrintView (Draw_Interpretor& di, Standard_Integer argc,
3143                        const char** argv)
3144 {
3145 #ifndef WNT
3146   di << "Printing implemented only for wnt!\n";
3147   return 1;
3148 #else
3149
3150   Handle(AIS_InteractiveContext) aContextAIS = NULL;
3151   Handle(V3d_View) aView = NULL;
3152   aContextAIS = ViewerTest::GetAISContext();
3153   if (!aContextAIS.IsNull())
3154   {
3155     const Handle(V3d_Viewer)& Vwr = aContextAIS->CurrentViewer();
3156     Vwr->InitActiveViews();
3157     if(Vwr->MoreActiveViews())
3158       aView = Vwr->ActiveView();
3159   }
3160
3161   // check for errors
3162   if (aView.IsNull())
3163   {
3164     di << "Call vinit before!\n";
3165     return 1;
3166   }
3167   else if (argc < 4)
3168   {
3169     di << "Use: " << argv[0];
3170     di << " width height filename [print algo=0]\n";
3171     di << "width, height of the intermediate buffer for operation\n";
3172     di << "algo : {0|1}\n";
3173     di << "        0 - stretch algorithm\n";
3174     di << "        1 - tile algorithm\n";
3175     di << "test printing algorithms into an intermediate buffer\n";
3176     di << "with saving output to an image file\n";
3177     return 1;
3178   }
3179
3180   // get the input params
3181   Standard_Integer aWidth  = Draw::Atoi (argv[1]);
3182   Standard_Integer aHeight = Draw::Atoi (argv[2]);
3183   Standard_Integer aMode   = 0;
3184   TCollection_AsciiString aFileName = TCollection_AsciiString (argv[3]);
3185   if (argc==5)
3186     aMode = Draw::Atoi (argv[4]);
3187
3188   // check the input parameters
3189   if (aWidth <= 0 || aHeight <= 0)
3190   {
3191     di << "Width and height must be positive values!\n";
3192     return 1;
3193   }
3194   if (aMode != 0 && aMode != 1)
3195     aMode = 0;
3196
3197   // define compatible bitmap
3198   HDC anDC = CreateCompatibleDC(0);
3199   BITMAPINFO aBitmapData;
3200   memset (&aBitmapData, 0, sizeof (BITMAPINFOHEADER));
3201   aBitmapData.bmiHeader.biSize          = sizeof (BITMAPINFOHEADER);
3202   aBitmapData.bmiHeader.biWidth         = aWidth ;
3203   aBitmapData.bmiHeader.biHeight        = aHeight;
3204   aBitmapData.bmiHeader.biPlanes        = 1;
3205   aBitmapData.bmiHeader.biBitCount      = 24;
3206   aBitmapData.bmiHeader.biXPelsPerMeter = 0;
3207   aBitmapData.bmiHeader.biYPelsPerMeter = 0;
3208   aBitmapData.bmiHeader.biClrUsed       = 0;
3209   aBitmapData.bmiHeader.biClrImportant  = 0;
3210   aBitmapData.bmiHeader.biCompression   = BI_RGB;
3211   aBitmapData.bmiHeader.biSizeImage     = 0;
3212
3213   // Create Device Independent Bitmap
3214   void* aBitsOut = NULL;
3215   HBITMAP aMemoryBitmap = CreateDIBSection (anDC, &aBitmapData, DIB_RGB_COLORS,
3216                                             &aBitsOut, NULL, 0);
3217   HGDIOBJ anOldBitmap   = SelectObject(anDC, aMemoryBitmap);
3218
3219   Standard_Boolean isSaved = Standard_False, isPrinted = Standard_False;
3220   if (aBitsOut != NULL)
3221   {
3222     if (aMode == 0)
3223       isPrinted = aView->Print(anDC,1,1,0,Aspect_PA_STRETCH);
3224     else
3225       isPrinted = aView->Print(anDC,1,1,0,Aspect_PA_TILE);
3226
3227     // succesfully printed into an intermediate buffer
3228     if (isPrinted)
3229     {
3230       Image_PixMap aWrapper;
3231       aWrapper.InitWrapper (Image_PixMap::ImgBGR, (Standard_Byte* )aBitsOut, aWidth, aHeight, aWidth * 3 + aWidth % 4);
3232       aWrapper.SetTopDown (false);
3233
3234       Image_AlienPixMap anImageBitmap;
3235       anImageBitmap.InitCopy (aWrapper);
3236       isSaved = anImageBitmap.Save (aFileName);
3237     }
3238     else
3239     {
3240       di << "Print operation failed due to printing errors or\n";
3241       di << "insufficient memory available\n";
3242       di << "Please, try to use smaller dimensions for this test\n";
3243       di << "command, as it allocates intermediate buffer for storing\n";
3244       di << "the result\n";
3245     }
3246   }
3247   else
3248   {
3249     di << "Can't allocate memory for intermediate buffer\n";
3250     di << "Please use smaller dimensions\n";
3251   }
3252
3253   if (aMemoryBitmap)
3254   {
3255     SelectObject (anDC, anOldBitmap);
3256     DeleteObject (aMemoryBitmap);
3257     DeleteDC(anDC);
3258   }
3259
3260   if (!isSaved)
3261   {
3262     di << "Save to file operation failed. This operation may fail\n";
3263     di << "if you don't have enough available memory, then you can\n";
3264     di << "use smaller dimensions for the output file\n";
3265     return 1;
3266   }
3267
3268   return 0;
3269
3270 #endif
3271 }
3272
3273 //==============================================================================
3274 //function : VZLayer
3275 //purpose  : Test z layer operations for v3d viewer
3276 //==============================================================================
3277 static int VZLayer (Draw_Interpretor& di, Standard_Integer argc, const char** argv)
3278 {
3279   Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext ();
3280   if (aContextAIS.IsNull())
3281   {
3282     di << "Call vinit before!\n";
3283     return 1;
3284   }
3285   else if (argc < 2)
3286   {
3287     di << "Use: vzlayer " << argv[0];
3288     di << " add/del/get [id]\n";
3289     di << " add - add new z layer to viewer and print its id\n";
3290     di << " del - del z layer by its id\n";
3291     di << " get - print sequence of z layers in increasing order of their overlay level\n";
3292     di << "id - the layer identificator value defined when removing z layer\n";
3293     return 1;
3294   }
3295
3296   const Handle(V3d_Viewer)& aViewer = aContextAIS->CurrentViewer();
3297   if (aViewer.IsNull())
3298   {
3299     di << "No active viewer!\n";
3300     return 1;
3301   }
3302
3303   // perform operation
3304   TCollection_AsciiString anOp = TCollection_AsciiString (argv[1]);
3305   if (anOp == "add")
3306   {
3307     Standard_Integer aNewId;
3308     if (!aViewer->AddZLayer (aNewId))
3309     {
3310       di << "Impossible to add new z layer!\n";
3311       return 1;
3312     }
3313
3314     di << "New z layer added with index: " << aNewId << "\n";
3315   }
3316   else if (anOp == "del")
3317   {
3318     if (argc < 3)
3319     {
3320       di << "Please also provide as argument id of z layer to remove\n";
3321       return 1;
3322     }
3323
3324     Standard_Integer aDelId = Draw::Atoi (argv[2]);
3325     if (!aViewer->RemoveZLayer (aDelId))
3326     {
3327       di << "Impossible to remove the z layer or invalid id!\n";
3328       return 1;
3329     }
3330
3331     di << "Z layer " << aDelId << " has been removed\n";
3332   }
3333   else if (anOp == "get")
3334   {
3335     TColStd_SequenceOfInteger anIds;
3336     aViewer->GetAllZLayers (anIds);
3337     for (Standard_Integer aSeqIdx = 1; aSeqIdx <= anIds.Length(); aSeqIdx++)
3338     {
3339       di << anIds.Value (aSeqIdx) << " ";
3340     }
3341
3342     di << "\n";
3343   }
3344   else
3345   {
3346     di << "Invalid operation, please use { add / del / get }\n";
3347     return 1;
3348   }
3349
3350   return 0;
3351 }
3352
3353 DEFINE_STANDARD_HANDLE(V3d_TextItem, Visual3d_LayerItem)
3354
3355 // this class provides a presentation of text item in v3d view under-/overlayer
3356 class V3d_TextItem : public Visual3d_LayerItem
3357 {
3358 public:
3359
3360   // CASCADE RTTI
3361   DEFINE_STANDARD_RTTI(V3d_TextItem)
3362
3363   // constructor
3364   Standard_EXPORT V3d_TextItem(const TCollection_AsciiString& theText,
3365                                const Standard_Real theX1,
3366                                const Standard_Real theY1,
3367                                const Standard_Real theHeight,
3368                                const TCollection_AsciiString& theFontName,
3369                                const Quantity_Color& theColor,
3370                                const Quantity_Color& theSubtitleColor,
3371                                const Aspect_TypeOfDisplayText& theTypeOfDisplay,
3372                                const Handle(Visual3d_Layer)& theLayer);
3373
3374   // redraw method
3375   Standard_EXPORT void RedrawLayerPrs();
3376
3377 private:
3378
3379   Standard_Real            myX1;
3380   Standard_Real            myY1;
3381   TCollection_AsciiString  myText;
3382   Standard_Real            myHeight;
3383   Handle(Visual3d_Layer)   myLayer;
3384   Quantity_Color           myColor;
3385   Quantity_Color           mySubtitleColor;
3386   Aspect_TypeOfDisplayText myType;
3387   TCollection_AsciiString  myFontName;
3388 };
3389
3390 IMPLEMENT_STANDARD_HANDLE(V3d_TextItem, Visual3d_LayerItem)
3391 IMPLEMENT_STANDARD_RTTIEXT(V3d_TextItem, Visual3d_LayerItem)
3392
3393 // create and add to display the text item
3394 V3d_TextItem::V3d_TextItem (const TCollection_AsciiString& theText,
3395                             const Standard_Real theX1,
3396                             const Standard_Real theY1,
3397                             const Standard_Real theHeight,
3398                             const TCollection_AsciiString& theFontName,
3399                             const Quantity_Color& theColor,
3400                             const Quantity_Color& theSubtitleColor,
3401                             const Aspect_TypeOfDisplayText& theTypeOfDisplay,
3402                             const Handle(Visual3d_Layer)& theLayer)
3403  : myX1 (theX1), myY1 (theY1),
3404    myText (theText),
3405    myHeight (theHeight),
3406    myLayer (theLayer),
3407    myColor (theColor),
3408    mySubtitleColor (theSubtitleColor),
3409    myType (theTypeOfDisplay),
3410    myFontName (theFontName)
3411 {
3412   if (!myLayer.IsNull ())
3413     myLayer->AddLayerItem (this);
3414 }
3415
3416 // render item
3417 void V3d_TextItem::RedrawLayerPrs ()
3418 {
3419   if (myLayer.IsNull ())
3420     return;
3421
3422   myLayer->SetColor (myColor);
3423   myLayer->SetTextAttributes (myFontName.ToCString (), myType, mySubtitleColor);
3424   myLayer->DrawText (myText.ToCString (), myX1, myY1, myHeight);
3425 }
3426
3427 DEFINE_STANDARD_HANDLE(V3d_LineItem, Visual3d_LayerItem)
3428
3429 // The Visual3d_LayerItem line item for "vlayerline" command
3430 // it provides a presentation of line with user-defined
3431 // linewidth, linetype and transparency.
3432 class V3d_LineItem : public Visual3d_LayerItem
3433 {
3434 public:
3435   // CASCADE RTTI
3436   DEFINE_STANDARD_RTTI(V3d_LineItem)
3437
3438   // constructor
3439   Standard_EXPORT V3d_LineItem(Standard_Real X1, Standard_Real Y1,
3440                                Standard_Real X2, Standard_Real Y2,
3441                                V3d_LayerMgrPointer theLayerMgr,
3442                                Aspect_TypeOfLine theType = Aspect_TOL_SOLID,
3443                                Standard_Real theWidth    = 0.5,
3444                                Standard_Real theTransp   = 1.0);
3445
3446   // redraw method
3447   Standard_EXPORT   void RedrawLayerPrs();
3448
3449 private:
3450
3451   Standard_Real       myX1, myY1, myX2, myY2;
3452   V3d_LayerMgrPointer myLayerMgr;
3453   Aspect_TypeOfLine   myType;
3454   Standard_Real       myWidth;
3455   Standard_Real       myTransparency;
3456 };
3457
3458 IMPLEMENT_STANDARD_HANDLE(V3d_LineItem, Visual3d_LayerItem)
3459 IMPLEMENT_STANDARD_RTTIEXT(V3d_LineItem, Visual3d_LayerItem)
3460
3461 // default constructor for line item
3462 V3d_LineItem::V3d_LineItem(Standard_Real X1, Standard_Real Y1,
3463                            Standard_Real X2, Standard_Real Y2,
3464                            V3d_LayerMgrPointer theLayerMgr,
3465                            Aspect_TypeOfLine theType,
3466                            Standard_Real theWidth,
3467                            Standard_Real theTransp) :
3468   myX1(X1), myY1(Y1), myX2(X2), myY2(Y2), myLayerMgr(theLayerMgr),
3469   myType(theType), myWidth(theWidth), myTransparency(theTransp)
3470 {
3471   if (myLayerMgr && !myLayerMgr->Overlay().IsNull())
3472     myLayerMgr->Overlay()->AddLayerItem (this);
3473 }
3474
3475 // render line
3476 void V3d_LineItem::RedrawLayerPrs ()
3477 {
3478   Handle (Visual3d_Layer) aOverlay;
3479
3480   if (myLayerMgr)
3481     aOverlay = myLayerMgr->Overlay();
3482
3483   if (!aOverlay.IsNull())
3484   {
3485     Quantity_Color aColor(1.0, 0, 0, Quantity_TOC_RGB);
3486     aOverlay->SetColor(aColor);
3487     aOverlay->SetTransparency((Standard_ShortReal)myTransparency);
3488     aOverlay->SetLineAttributes((Aspect_TypeOfLine)myType, myWidth);
3489     aOverlay->BeginPolyline();
3490     aOverlay->AddVertex(myX1, myY1);
3491     aOverlay->AddVertex(myX2, myY2);
3492     aOverlay->ClosePrimitive();
3493   }
3494 }
3495
3496 //=============================================================================
3497 //function : VLayerLine
3498 //purpose  : Draws line in the v3d view layer with given attributes: linetype,
3499 //         : linewidth, transparency coefficient
3500 //============================================================================
3501 static int VLayerLine(Draw_Interpretor& di, Standard_Integer argc, const char** argv)
3502 {
3503   // get the active view
3504   Handle(V3d_View) aView = ViewerTest::CurrentView();
3505   if (aView.IsNull())
3506   {
3507     di << "Call vinit before!\n";
3508     return 1;
3509   }
3510   else if (argc < 5)
3511   {
3512     di << "Use: " << argv[0];
3513     di << " x1 y1 x2 y2 [linewidth = 0.5] [linetype = 0] [transparency = 1]\n";
3514     di << " linetype : { 0 | 1 | 2 | 3 } \n";
3515     di << "              0 - solid  \n";
3516     di << "              1 - dashed \n";
3517     di << "              2 - dot    \n";
3518     di << "              3 - dashdot\n";
3519     di << " transparency : { 0.0 - 1.0 } \n";
3520     di << "                  0.0 - transparent\n";
3521     di << "                  1.0 - visible    \n";
3522     return 1;
3523   }
3524
3525   // get the input params
3526   Standard_Real X1 = Draw::Atof(argv[1]);
3527   Standard_Real Y1 = Draw::Atof(argv[2]);
3528   Standard_Real X2 = Draw::Atof(argv[3]);
3529   Standard_Real Y2 = Draw::Atof(argv[4]);
3530
3531   Standard_Real    aWidth = 0.5;
3532   Standard_Integer aType  = 0;
3533   Standard_Real    aTransparency = 1.0;
3534
3535   // has width
3536   if (argc > 5)
3537     aWidth = Draw::Atof(argv[5]);
3538
3539   // has type
3540   if (argc > 6)
3541      aType = (Standard_Integer) Draw::Atoi(argv[6]);
3542
3543   // has transparency
3544   if (argc > 7)
3545   {
3546     aTransparency = Draw::Atof(argv[7]);
3547     if (aTransparency < 0 || aTransparency > 1.0)
3548       aTransparency = 1.0;
3549   }
3550
3551   // select appropriate line type
3552   Aspect_TypeOfLine aLineType;
3553   switch (aType)
3554   {
3555     case 1:
3556       aLineType = Aspect_TOL_DASH;
3557     break;
3558
3559     case 2:
3560       aLineType = Aspect_TOL_DOT;
3561     break;
3562
3563     case 3:
3564       aLineType = Aspect_TOL_DOTDASH;
3565     break;
3566
3567     default:
3568       aLineType = Aspect_TOL_SOLID;
3569   }
3570
3571   // replace layer manager
3572   Handle(V3d_LayerMgr) aMgr = new V3d_LayerMgr(aView);
3573   aView->SetLayerMgr(aMgr);
3574
3575   // add line item
3576   Handle (V3d_LineItem) anItem = new V3d_LineItem(X1, Y1, X2, Y2,
3577                                                   aMgr.operator->(),
3578                                                   aLineType, aWidth,
3579                                                   aTransparency);
3580
3581   // update view
3582   aView->MustBeResized();
3583   aView->Redraw();
3584
3585   return 0;
3586 }
3587
3588 //=======================================================================
3589 //function : VOverlayText
3590 //purpose  : Test text displaying in view overlay
3591 //=======================================================================
3592 static int VOverlayText (Draw_Interpretor& di, Standard_Integer argc, const char**argv)
3593 {
3594   // get the active view
3595   Handle(V3d_View) aView = ViewerTest::CurrentView();
3596   if (aView.IsNull())
3597   {
3598     di << "No active view. Please call vinit.\n";
3599     return 1;
3600   }
3601   else if (argc < 4 || argc > 13)
3602   {
3603     di << "Use: " << argv[0];
3604     di << " text x y [height] [font_name] [text_color: R G B] [displayType]\n";
3605     di << "[background_color: R G B]\n";
3606     di << "  height - pixel height of the text (default=10.0)\n";
3607     di << "  font_name - name of font (default=courier)\n";
3608     di << "  text_color - R G B values of text color (default=255.0 255.0 255.0)\n";
3609     di << "  display_type = {normal/subtitle/decal/blend/dimension}, (default=normal)\n";
3610     di << "  background_color- R G B values used for subtitle and decal text\n";
3611     di << "(default=255.0 255.0 255.0)\n";
3612     return 1;
3613   }
3614
3615   TCollection_AsciiString aText (argv[1]);
3616   Standard_Real aPosX = Draw::Atof(argv[2]);
3617   Standard_Real aPosY = Draw::Atof(argv[3]);
3618   Standard_Real aHeight = (argc >= 5) ? Draw::Atof (argv[4]) : 10.0;
3619
3620   // font name
3621   TCollection_AsciiString aFontName = "Courier";
3622   if (argc >= 6)
3623     aFontName = TCollection_AsciiString (argv[5]);
3624
3625   // text colors
3626   Quantity_Parameter aColorRed   = 1.0;
3627   Quantity_Parameter aColorGreen = 1.0;
3628   Quantity_Parameter aColorBlue  = 1.0;
3629   if (argc >= 9)
3630   {
3631     aColorRed   = Draw::Atof (argv[6])/255.;
3632     aColorGreen = Draw::Atof (argv[7])/255.;
3633     aColorBlue  = Draw::Atof (argv[8])/255.;
3634   }
3635
3636   // display type
3637   TCollection_AsciiString aDispStr;
3638   if (argc >= 10)
3639     aDispStr = TCollection_AsciiString (argv[9]);
3640
3641   Aspect_TypeOfDisplayText aTextType = Aspect_TODT_NORMAL;
3642   if (aDispStr.IsEqual ("subtitle"))
3643     aTextType = Aspect_TODT_SUBTITLE;
3644   else if (aDispStr.IsEqual ("decal"))
3645     aTextType = Aspect_TODT_DEKALE;
3646   else if (aDispStr.IsEqual ("blend"))
3647     aTextType = Aspect_TODT_BLEND;
3648   else if (aDispStr.IsEqual ("dimension"))
3649     aTextType = Aspect_TODT_DIMENSION;
3650
3651   // subtitle color
3652   Quantity_Parameter aSubRed   = 1.0;
3653   Quantity_Parameter aSubGreen = 1.0;
3654   Quantity_Parameter aSubBlue  = 1.0;
3655   if (argc == 13)
3656   {
3657     aSubRed   = Draw::Atof (argv[10])/255.;
3658     aSubGreen = Draw::Atof (argv[11])/255.;
3659     aSubBlue  = Draw::Atof (argv[12])/255.;
3660   }
3661
3662   // check fo current overlay
3663   Handle(Visual3d_Layer) anOverlay = aView->Viewer()->Viewer()->OverLayer ();
3664   if (anOverlay.IsNull ())
3665   {
3666     Handle(V3d_LayerMgr) aMgr = new V3d_LayerMgr (aView);
3667     anOverlay = aMgr->Overlay ();
3668     aView->SetLayerMgr (aMgr);
3669   }
3670
3671   Quantity_Color aTextColor (aColorRed, aColorGreen,
3672     aColorBlue, Quantity_TOC_RGB);
3673   Quantity_Color aSubtColor (aSubRed, aSubGreen,
3674     aSubBlue, Quantity_TOC_RGB);
3675
3676   // add text item
3677   Handle(V3d_TextItem) anItem = new V3d_TextItem (aText, aPosX, aPosY,
3678     aHeight, aFontName, aTextColor, aSubtColor, aTextType, anOverlay);
3679
3680   // update view
3681   aView->MustBeResized();
3682   aView->Redraw();
3683
3684   return 0;
3685 }
3686
3687 //==============================================================================
3688 //function : VGrid
3689 //purpose  :
3690 //==============================================================================
3691
3692 static int VGrid (Draw_Interpretor& /*theDI*/,
3693                   Standard_Integer  theArgNb,
3694                   const char**      theArgVec)
3695 {
3696   // get the active view
3697   Handle(V3d_View)   aView   = ViewerTest::CurrentView();
3698   Handle(V3d_Viewer) aViewer = ViewerTest::GetViewerFromContext();
3699   if (aView.IsNull() || aViewer.IsNull())
3700   {
3701     std::cerr << "No active view. Please call vinit.\n";
3702     return 1;
3703   }
3704
3705   Aspect_GridType     aType = aViewer->GridType();
3706   Aspect_GridDrawMode aMode = aViewer->GridDrawMode();
3707
3708   Standard_Integer anIter = 1;
3709   for (; anIter < theArgNb; ++anIter)
3710   {
3711     const char* aValue = theArgVec[anIter];
3712     if (*aValue == 'r')
3713     {
3714       aType = Aspect_GT_Rectangular;
3715     }
3716     else if (*aValue == 'c')
3717     {
3718       aType = Aspect_GT_Circular;
3719     }
3720     else if (*aValue == 'l')
3721     {
3722       aMode = Aspect_GDM_Lines;
3723     }
3724     else if (*aValue == 'p')
3725     {
3726       aMode = Aspect_GDM_Points;
3727     }
3728     else if (strcmp (aValue, "off" ) == 0)
3729     {
3730       aViewer->DeactivateGrid();
3731       return 0;
3732     }
3733     else
3734     {
3735       break;
3736     }
3737   }
3738
3739   Standard_Integer aTail = (theArgNb - anIter);
3740   if (aTail == 0)
3741   {
3742     aViewer->ActivateGrid (aType, aMode);
3743     return 0;
3744   }
3745   else if (aTail != 2 && aTail != 5)
3746   {
3747     std::cerr << "Incorrect arguments number! Usage:\n"
3748               << "vgrid [off] [Mode={r|c}] [Type={l|p}] [OriginX OriginY [StepX/StepRadius StepY/DivNb RotAngle]]\n";
3749     return 1;
3750   }
3751
3752   Quantity_Length anOriginX, anOriginY;
3753   Quantity_PlaneAngle aRotAngle;
3754   if (aType == Aspect_GT_Rectangular)
3755   {
3756     Quantity_Length aRStepX, aRStepY;
3757     aViewer->RectangularGridValues (anOriginX, anOriginY, aRStepX, aRStepY, aRotAngle);
3758
3759     anOriginX = Draw::Atof (theArgVec[anIter++]);
3760     anOriginY = Draw::Atof (theArgVec[anIter++]);
3761     if (aTail == 5)
3762     {
3763       aRStepX   = Draw::Atof (theArgVec[anIter++]);
3764       aRStepY   = Draw::Atof (theArgVec[anIter++]);
3765       aRotAngle = Draw::Atof (theArgVec[anIter++]);
3766     }
3767     aViewer->SetRectangularGridValues (anOriginX, anOriginY, aRStepX, aRStepY, aRotAngle);
3768     aViewer->ActivateGrid (aType, aMode);
3769   }
3770   else if (aType == Aspect_GT_Circular)
3771   {
3772     Quantity_Length aRadiusStep;
3773     Standard_Integer aDivisionNumber;
3774     aViewer->CircularGridValues (anOriginX, anOriginY, aRadiusStep, aDivisionNumber, aRotAngle);
3775
3776     anOriginX = Draw::Atof (theArgVec[anIter++]);
3777     anOriginY = Draw::Atof (theArgVec[anIter++]);
3778     if (aTail == 5)
3779     {
3780       aRadiusStep     = Draw::Atof (theArgVec[anIter++]);
3781       aDivisionNumber = Draw::Atoi (theArgVec[anIter++]);
3782       aRotAngle       = Draw::Atof (theArgVec[anIter++]);
3783     }
3784
3785     aViewer->SetCircularGridValues (anOriginX, anOriginY, aRadiusStep, aDivisionNumber, aRotAngle);
3786     aViewer->ActivateGrid (aType, aMode);
3787   }
3788
3789   return 0;
3790 }
3791
3792 //==============================================================================
3793 //function : VFps
3794 //purpose  :
3795 //==============================================================================
3796
3797 static int VFps (Draw_Interpretor& theDI,
3798                  Standard_Integer  theArgNb,
3799                  const char**      theArgVec)
3800 {
3801   // get the active view
3802   Handle(V3d_View) aView = ViewerTest::CurrentView();
3803   if (aView.IsNull())
3804   {
3805     std::cerr << "No active view. Please call vinit.\n";
3806     return 1;
3807   }
3808
3809   Standard_Integer aFramesNb = (theArgNb > 1) ? Draw::Atoi(theArgVec[1]) : 100;
3810   if (aFramesNb <= 0)
3811   {
3812     std::cerr << "Incorrect arguments!\n";
3813     return 1;
3814   }
3815
3816   // the time is meaningless for first call
3817   // due to async OpenGl rendering
3818   aView->Redraw();
3819
3820   // redraw view in loop to estimate average values
3821   OSD_Timer aTimer;
3822   aTimer.Start();
3823   for (Standard_Integer anInter = 0; anInter < aFramesNb; ++anInter)
3824   {
3825     aView->Redraw();
3826   }
3827   aTimer.Stop();
3828   Standard_Real aCpu;
3829   const Standard_Real aTime = aTimer.ElapsedTime();
3830   aTimer.OSD_Chronometer::Show (aCpu);
3831
3832   const Standard_Real aFpsAver = Standard_Real(aFramesNb) / aTime;
3833   const Standard_Real aCpuAver = aCpu / Standard_Real(aFramesNb);
3834
3835   // return statistics
3836   theDI << "FPS: " << aFpsAver << "\n"
3837         << "CPU: " << (1000.0 * aCpuAver) << " msec\n";
3838
3839   return 0;
3840 }
3841
3842 //==============================================================================
3843 //function : VGlDebug
3844 //purpose  :
3845 //==============================================================================
3846
3847 static int VGlDebug (Draw_Interpretor& theDI,
3848                      Standard_Integer  theArgNb,
3849                      const char**      theArgVec)
3850 {
3851   if (theArgNb < 2)
3852   {
3853     Handle(V3d_View) aView = ViewerTest::CurrentView();
3854     if (aView.IsNull())
3855     {
3856       std::cerr << "No active view. Please call vinit.\n";
3857       return 0;
3858     }
3859
3860     Standard_Boolean isActive = OpenGl_Context::CheckExtension ((const char* )glGetString (GL_EXTENSIONS),
3861                                                                 "GL_ARB_debug_output");
3862     std::cout << "Active graphic driver: debug " << (isActive ? "ON" : "OFF") << "\n";
3863     theDI << (isActive ? "1" : "0");
3864     return 0;
3865   }
3866
3867   ViewerTest_myDefaultCaps.contextDebug = Draw::Atoi (theArgVec[1]) != 0;
3868   return 0;
3869 }
3870
3871 //==============================================================================
3872 //function : VVbo
3873 //purpose  :
3874 //==============================================================================
3875
3876 static int VVbo (Draw_Interpretor& theDI,
3877                  Standard_Integer  theArgNb,
3878                  const char**      theArgVec)
3879 {
3880   const Standard_Boolean toSet    = (theArgNb > 1);
3881   const Standard_Boolean toUseVbo = toSet ? (Draw::Atoi (theArgVec[1]) == 0) : 1;
3882   if (toSet)
3883   {
3884     ViewerTest_myDefaultCaps.vboDisable = toUseVbo;
3885   }
3886
3887   // get the context
3888   Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext();
3889   if (aContextAIS.IsNull())
3890   {
3891     if (!toSet)
3892     {
3893       std::cerr << "No active view!\n";
3894     }
3895     return 1;
3896   }
3897   Handle(OpenGl_GraphicDriver) aDriver = Handle(OpenGl_GraphicDriver)::DownCast (aContextAIS->CurrentViewer()->Driver());
3898   if (!aDriver.IsNull())
3899   {
3900     if (!toSet)
3901     {
3902       theDI << (aDriver->Options().vboDisable ? "0" : "1") << "\n";
3903     }
3904     else
3905     {
3906       aDriver->ChangeOptions().vboDisable = toUseVbo;
3907     }
3908   }
3909
3910   return 0;
3911 }
3912
3913 //==============================================================================
3914 //function : VCaps
3915 //purpose  :
3916 //==============================================================================
3917
3918 static int VCaps (Draw_Interpretor& theDI,
3919                   Standard_Integer  theArgNb,
3920                   const char**      theArgVec)
3921 {
3922   OpenGl_Caps* aCaps = &ViewerTest_myDefaultCaps;
3923   Handle(OpenGl_GraphicDriver)   aDriver;
3924   Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext();
3925   if (!aContextAIS.IsNull())
3926   {
3927     aDriver = Handle(OpenGl_GraphicDriver)::DownCast (aContextAIS->CurrentViewer()->Driver());
3928     aCaps   = &aDriver->ChangeOptions();
3929   }
3930
3931   if (theArgNb < 2)
3932   {
3933     theDI << "VBO:     " << (aCaps->vboDisable        ? "0" : "1") << "\n";
3934     theDI << "Sprites: " << (aCaps->pntSpritesDisable ? "0" : "1") << "\n";
3935     theDI << "SoftMode:" << (aCaps->contextNoAccel    ? "1" : "0") << "\n";
3936     return 0;
3937   }
3938
3939   for (Standard_Integer anArgIter = 1; anArgIter < theArgNb; ++anArgIter)
3940   {
3941     const TCollection_AsciiString anArg (theArgVec[anArgIter]);
3942     if (anArg.Search ("vbo=") > -1)
3943     {
3944       aCaps->vboDisable        = anArg.Token ("=", 2).IntegerValue() == 0;
3945     }
3946     else if (anArg.Search ("sprites=") > -1)
3947     {
3948       aCaps->pntSpritesDisable = anArg.Token ("=", 2).IntegerValue() == 0;
3949     }
3950     else if (anArg.Search ("soft=") > -1)
3951     {
3952       aCaps->contextNoAccel = anArg.Token ("=", 2).IntegerValue() != 0;
3953     }
3954     else
3955     {
3956       std::cerr << "Unknown argument: " << anArg << "\n";
3957     }
3958   }
3959   if (aCaps != &ViewerTest_myDefaultCaps)
3960   {
3961     ViewerTest_myDefaultCaps = *aCaps;
3962   }
3963   return 0;
3964 }
3965
3966 //==============================================================================
3967 //function : VMemGpu
3968 //purpose  :
3969 //==============================================================================
3970
3971 static int VMemGpu (Draw_Interpretor& theDI,
3972                     Standard_Integer  theArgNb,
3973                     const char**      theArgVec)
3974 {
3975   // get the context
3976   Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext();
3977   if (aContextAIS.IsNull())
3978   {
3979     std::cerr << "No active view. Please call vinit.\n";
3980     return 1;
3981   }
3982
3983   Handle(Graphic3d_GraphicDriver) aDriver = aContextAIS->CurrentViewer()->Driver();
3984   if (aDriver.IsNull())
3985   {
3986     std::cerr << "Graphic driver not available.\n";
3987     return 1;
3988   }
3989
3990   Standard_Size aFreeBytes = 0;
3991   TCollection_AsciiString anInfo;
3992   if (!aDriver->MemoryInfo (aFreeBytes, anInfo))
3993   {
3994     std::cerr << "Information not available.\n";
3995     return 1;
3996   }
3997
3998   if (theArgNb > 1 && *theArgVec[1] == 'f')
3999   {
4000     theDI << Standard_Real (aFreeBytes);
4001   }
4002   else
4003   {
4004     theDI << anInfo;
4005   }
4006
4007   return 0;
4008 }
4009
4010 // ==============================================================================
4011 // function : VReadPixel
4012 // purpose  :
4013 // ==============================================================================
4014 static int VReadPixel (Draw_Interpretor& theDI,
4015                        Standard_Integer  theArgNb,
4016                        const char**      theArgVec)
4017 {
4018   // get the active view
4019   Handle(V3d_View) aView = ViewerTest::CurrentView();
4020   if (aView.IsNull())
4021   {
4022     std::cerr << "No active view. Please call vinit.\n";
4023     return 1;
4024   }
4025   else if (theArgNb < 3)
4026   {
4027     std::cerr << "Usage : " << theArgVec[0] << " xPixel yPixel [{rgb|rgba|depth|hls|rgbf|rgbaf}=rgba] [name]\n";
4028     return 1;
4029   }
4030
4031   Image_PixMap::ImgFormat aFormat     = Image_PixMap::IsBigEndianHost() ? Image_PixMap::ImgRGBA : Image_PixMap::ImgBGRA;
4032   Graphic3d_BufferType    aBufferType = Graphic3d_BT_RGBA;
4033
4034   Standard_Integer aWidth, aHeight;
4035   aView->Window()->Size (aWidth, aHeight);
4036   const Standard_Integer anX = Draw::Atoi (theArgVec[1]);
4037   const Standard_Integer anY = Draw::Atoi (theArgVec[2]);
4038   if (anX < 0 || anX >= aWidth || anY < 0 || anY > aHeight)
4039   {
4040     std::cerr << "Pixel coordinates (" << anX << "; " << anY << ") are out of view (" << aWidth << " x " << aHeight << ")\n";
4041     return 1;
4042   }
4043
4044   Standard_Boolean toShowName = Standard_False;
4045   Standard_Boolean toShowHls  = Standard_False;
4046   for (Standard_Integer anIter = 3; anIter < theArgNb; ++anIter)
4047   {
4048     const char* aParam = theArgVec[anIter];
4049     if ( strcasecmp( aParam, "rgb" ) == 0 )
4050     {
4051       aFormat     = Image_PixMap::IsBigEndianHost() ? Image_PixMap::ImgRGB : Image_PixMap::ImgBGR;
4052       aBufferType = Graphic3d_BT_RGB;
4053     }
4054     else if ( strcasecmp( aParam, "hls" ) == 0 )
4055     {
4056       aFormat     = Image_PixMap::IsBigEndianHost() ? Image_PixMap::ImgRGB : Image_PixMap::ImgBGR;
4057       aBufferType = Graphic3d_BT_RGB;
4058       toShowHls   = Standard_True;
4059     }
4060     else if ( strcasecmp( aParam, "rgbf" ) == 0 )
4061     {
4062       aFormat     = Image_PixMap::ImgRGBF;
4063       aBufferType = Graphic3d_BT_RGB;
4064     }
4065     else if ( strcasecmp( aParam, "rgba" ) == 0 )
4066     {
4067       aFormat     = Image_PixMap::IsBigEndianHost() ? Image_PixMap::ImgRGBA : Image_PixMap::ImgBGRA;
4068       aBufferType = Graphic3d_BT_RGBA;
4069     }
4070     else if ( strcasecmp( aParam, "rgbaf" ) == 0 )
4071     {
4072       aFormat     = Image_PixMap::ImgRGBAF;
4073       aBufferType = Graphic3d_BT_RGBA;
4074     }
4075     else if ( strcasecmp( aParam, "depth" ) == 0 )
4076     {
4077       aFormat     = Image_PixMap::ImgGrayF;
4078       aBufferType = Graphic3d_BT_Depth;
4079     }
4080     else if ( strcasecmp( aParam, "name" ) == 0 )
4081     {
4082       toShowName = Standard_True;
4083     }
4084   }
4085
4086   Image_PixMap anImage;
4087   if (!anImage.InitTrash (aFormat, aWidth, aHeight))
4088   {
4089     std::cerr << "Image allocation failed\n";
4090     return 1;
4091   }
4092   else if (!aView->ToPixMap (anImage, aWidth, aHeight, aBufferType))
4093   {
4094     std::cerr << "Image dump failed\n";
4095     return 1;
4096   }
4097
4098   Quantity_Parameter anAlpha;
4099   Quantity_Color aColor = anImage.PixelColor (anX, anY, anAlpha);
4100   if (toShowName)
4101   {
4102     if (aBufferType == Graphic3d_BT_RGBA)
4103     {
4104       theDI << Quantity_Color::StringName (aColor.Name()) << " " << anAlpha << "\n";
4105     }
4106     else
4107     {
4108       theDI << Quantity_Color::StringName (aColor.Name()) << "\n";
4109     }
4110   }
4111   else
4112   {
4113     switch (aBufferType)
4114     {
4115       default:
4116       case Graphic3d_BT_RGB:
4117       {
4118         if (toShowHls)
4119         {
4120           theDI << aColor.Hue() << " " << aColor.Light() << " " << aColor.Saturation() << "\n";
4121         }
4122         else
4123         {
4124           theDI << aColor.Red() << " " << aColor.Green() << " " << aColor.Blue() << "\n";
4125         }
4126         break;
4127       }
4128       case Graphic3d_BT_RGBA:
4129       {
4130         theDI << aColor.Red() << " " << aColor.Green() << " " << aColor.Blue() << " " << anAlpha << "\n";
4131         break;
4132       }
4133       case Graphic3d_BT_Depth:
4134       {
4135         theDI << aColor.Red() << "\n";
4136         break;
4137       }
4138     }
4139   }
4140
4141   return 0;
4142 }
4143
4144 //==============================================================================
4145 //function : VDiffImage
4146 //purpose  : The draw-command compares two images.
4147 //==============================================================================
4148
4149 static int VDiffImage (Draw_Interpretor& theDI, Standard_Integer theArgNb, const char** theArgVec)
4150 {
4151   if (theArgNb < 6)
4152   {
4153     theDI << "Not enough arguments.\n";
4154     return 1;
4155   }
4156
4157   // image file names
4158   const char* anImgPathRef = theArgVec[1];
4159   const char* anImgPathNew = theArgVec[2];
4160
4161   // get string tolerance and check its validity
4162   Standard_Real aTolColor = Draw::Atof (theArgVec[3]);
4163   if (aTolColor < 0.0)
4164     aTolColor = 0.0;
4165   if (aTolColor > 1.0)
4166     aTolColor = 1.0;
4167
4168   Standard_Boolean toBlackWhite     = (Draw::Atoi (theArgVec[4]) == 1);
4169   Standard_Boolean isBorderFilterOn = (Draw::Atoi (theArgVec[5]) == 1);
4170
4171   // image file of difference
4172   const char* aDiffImagePath = (theArgNb >= 7) ? theArgVec[6] : NULL;
4173
4174   // compare the images
4175   Image_Diff aComparer;
4176   if (!aComparer.Init (anImgPathRef, anImgPathNew, toBlackWhite))
4177   {
4178     return 1;
4179   }
4180
4181   aComparer.SetColorTolerance (aTolColor);
4182   aComparer.SetBorderFilterOn (isBorderFilterOn);
4183   Standard_Integer aDiffColorsNb = aComparer.Compare();
4184   theDI << aDiffColorsNb << "\n";
4185
4186   // save image of difference
4187   if (aDiffImagePath != NULL)
4188   {
4189     aComparer.SaveDiffImage (aDiffImagePath);
4190   }
4191
4192   return 0;
4193 }
4194
4195 //=======================================================================
4196 //function : VSelect
4197 //purpose  : Emulates different types of selection by mouse:
4198 //           1) single click selection
4199 //           2) selection with rectangle having corners at pixel positions (x1,y1) and (x2,y2)
4200 //           3) selection with polygon having corners at
4201 //           pixel positions (x1,y1),...,(xn,yn)
4202 //           4) any of these selections with shift button pressed
4203 //=======================================================================
4204 static Standard_Integer VSelect (Draw_Interpretor& di,
4205                                  Standard_Integer argc,
4206                                  const char ** argv)
4207 {
4208   if(argc < 3)
4209   {
4210     di << "Usage : " << argv[0] << " x1 y1 [x2 y2 [... xn yn]] [shift_selection = 1|0]" << "\n";
4211     return 1;
4212   }
4213
4214   Handle(AIS_InteractiveContext) myAIScontext = ViewerTest::GetAISContext();
4215   if(myAIScontext.IsNull())
4216   {
4217     di << "use 'vinit' command before " << argv[0] << "\n";
4218     return 1;
4219   }
4220   const Standard_Boolean isShiftSelection = (argc>3 && !(argc%2) && (atoi(argv[argc-1])==1));
4221   Handle(ViewerTest_EventManager) aCurrentEventManager = ViewerTest::CurrentEventManager();
4222   aCurrentEventManager->MoveTo(atoi(argv[1]),atoi(argv[2]));
4223   if(argc <= 4)
4224   {
4225     if(isShiftSelection)
4226       aCurrentEventManager->ShiftSelect();
4227     else
4228       aCurrentEventManager->Select();
4229   }
4230   else if(argc <= 6)
4231   {
4232     if(isShiftSelection)
4233       aCurrentEventManager->ShiftSelect(atoi(argv[1]),atoi(argv[2]),atoi(argv[3]),atoi(argv[4]));
4234     else
4235       aCurrentEventManager->Select(atoi(argv[1]),atoi(argv[2]),atoi(argv[3]),atoi(argv[4]));
4236   }
4237   else
4238   {
4239     Standard_Integer anUpper = 0;
4240
4241     if(isShiftSelection)
4242       anUpper = (argc-1)/2;
4243     else
4244       anUpper = argc/2;
4245     TColgp_Array1OfPnt2d aPolyline(1,anUpper);
4246
4247     for(Standard_Integer i=1;i<=anUpper;++i)
4248       aPolyline.SetValue(i,gp_Pnt2d(atoi(argv[2*i-1]),atoi(argv[2*i])));
4249
4250     if(isShiftSelection)
4251       aCurrentEventManager->ShiftSelect(aPolyline);
4252     else
4253       aCurrentEventManager->Select(aPolyline);
4254   }
4255   return 0;
4256 }
4257
4258 //=======================================================================
4259 //function : VMoveTo
4260 //purpose  : Emulates cursor movement to defined pixel position
4261 //=======================================================================
4262 static Standard_Integer VMoveTo (Draw_Interpretor& di,
4263                                 Standard_Integer argc,
4264                                 const char ** argv)
4265 {
4266   if(argc != 3)
4267   {
4268     di << "Usage : " << argv[0] << " x y" << "\n";
4269     return 1;
4270   }
4271
4272   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4273   if(aContext.IsNull())
4274   {
4275     di << "use 'vinit' command before " << argv[0] << "\n";
4276     return 1;
4277   }
4278   ViewerTest::CurrentEventManager()->MoveTo(atoi(argv[1]),atoi(argv[2]));
4279   return 0;
4280 }
4281
4282 //=======================================================================
4283 //function : VViewParams
4284 //purpose  : Gets or sets AIS View characteristics
4285 //=======================================================================
4286 static Standard_Integer VViewParams (Draw_Interpretor& di,
4287                                 Standard_Integer argc,
4288                                 const char ** argv)
4289 {
4290   if ( argc != 1 && argc != 13)
4291   {
4292     di << "Usage : " << argv[0] << "\n";
4293     return 1;
4294   }
4295   Handle (V3d_View) anAISView = ViewerTest::CurrentView ();
4296   if ( anAISView.IsNull () )
4297   {
4298     di << "use 'vinit' command before " << argv[0] << "\n";
4299     return 1;
4300   }
4301   if(argc==1){
4302     Quantity_Factor anAISViewScale = anAISView -> V3d_View::Scale ();
4303     Standard_Real anAISViewCenterCoordinateX = 0.0;
4304     Standard_Real anAISViewCenterCoordinateY = 0.0;
4305     anAISView -> V3d_View::Center (anAISViewCenterCoordinateX, anAISViewCenterCoordinateY);
4306     Standard_Real anAISViewProjX = 0.0;
4307     Standard_Real anAISViewProjY = 0.0;
4308     Standard_Real anAISViewProjZ = 0.0;
4309     anAISView -> V3d_View::Proj (anAISViewProjX, anAISViewProjY, anAISViewProjZ);
4310     Standard_Real anAISViewUpX = 0.0;
4311     Standard_Real anAISViewUpY = 0.0;
4312     Standard_Real anAISViewUpZ = 0.0;
4313     anAISView -> V3d_View::Up (anAISViewUpX, anAISViewUpY, anAISViewUpZ);
4314     Standard_Real anAISViewAtX = 0.0;
4315     Standard_Real anAISViewAtY = 0.0;
4316     Standard_Real anAISViewAtZ = 0.0;
4317     anAISView -> V3d_View::At (anAISViewAtX, anAISViewAtY, anAISViewAtZ);
4318     di << "Scale of current view: " << anAISViewScale << "\n";
4319     di << "Center on X : "<< anAISViewCenterCoordinateX << "; on Y: " << anAISViewCenterCoordinateY << "\n";
4320     di << "Proj on X : " << anAISViewProjX << "; on Y: " << anAISViewProjY << "; on Z: " << anAISViewProjZ << "\n";
4321     di << "Up on X : " << anAISViewUpX << "; on Y: " << anAISViewUpY << "; on Z: " << anAISViewUpZ << "\n";
4322     di << "At on X : " << anAISViewAtX << "; on Y: " << anAISViewAtY << "; on Z: " << anAISViewAtZ << "\n";
4323   }
4324   else
4325   {
4326     Quantity_Factor anAISViewScale = atof (argv [1]);
4327     Standard_Real anAISViewCenterCoordinateX = atof (argv [2]);
4328     Standard_Real anAISViewCenterCoordinateY = atof (argv [3]);
4329     Standard_Real anAISViewProjX = atof (argv [4]);
4330     Standard_Real anAISViewProjY = atof (argv [5]);
4331     Standard_Real anAISViewProjZ = atof (argv [6]);
4332     Standard_Real anAISViewUpX = atof (argv [7]);
4333     Standard_Real anAISViewUpY = atof (argv [8]);
4334     Standard_Real anAISViewUpZ = atof (argv [9]);
4335     Standard_Real anAISViewAtX = atof (argv [10]);
4336     Standard_Real anAISViewAtY = atof (argv [11]);
4337     Standard_Real anAISViewAtZ = atof (argv [12]);
4338     anAISView -> V3d_View::SetScale (anAISViewScale);
4339     anAISView -> V3d_View::SetCenter (anAISViewCenterCoordinateX, anAISViewCenterCoordinateY);
4340     anAISView -> V3d_View::SetAt (anAISViewAtX, anAISViewAtY, anAISViewAtZ);
4341     anAISView -> V3d_View::SetProj (anAISViewProjX, anAISViewProjY, anAISViewProjZ);
4342     anAISView -> V3d_View::SetUp (anAISViewUpX, anAISViewUpY, anAISViewUpZ);
4343   }
4344   return 0;
4345 }
4346
4347 //=======================================================================
4348 //function : VChangeSelected
4349 //purpose  : Adds the shape to selection or remove one from it
4350 //=======================================================================
4351 static Standard_Integer VChangeSelected (Draw_Interpretor& di,
4352                                 Standard_Integer argc,
4353                                 const char ** argv)
4354 {
4355   if(argc != 2)
4356   {
4357     di<<"Usage : " << argv[0] << " shape \n";
4358     return 1;
4359   }
4360   //get AIS_Shape:
4361   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4362   ViewerTest_DoubleMapOfInteractiveAndName& aMap = GetMapOfAIS();
4363   TCollection_AsciiString aName(argv[1]);
4364   Handle(AIS_InteractiveObject) anAISObject;
4365
4366   if(!aMap.IsBound2(aName))
4367   {
4368     di<<"Use 'vdisplay' before";
4369     return 1;
4370   }
4371   else
4372   {
4373     anAISObject = Handle(AIS_InteractiveObject)::DownCast(aMap.Find2(aName));
4374     if(anAISObject.IsNull()){
4375       di<<"No interactive object \n";
4376       return 1;
4377     }
4378
4379     if(aContext->HasOpenedContext())
4380     {
4381       aContext->AddOrRemoveSelected(anAISObject);
4382     }
4383     else
4384     {
4385       aContext->AddOrRemoveCurrentObject(anAISObject);
4386     }
4387   }
4388   return 0;
4389 }
4390
4391 //=======================================================================
4392 //function : VZClipping
4393 //purpose  : Gets or sets ZClipping mode, width and depth
4394 //=======================================================================
4395 static Standard_Integer VZClipping (Draw_Interpretor& di,
4396                                 Standard_Integer argc,
4397                                 const char ** argv)
4398 {
4399   if(argc>4)
4400   {
4401     di << "Usage : " << argv[0] << " [mode] [depth  width]" << "\n"
4402       <<"mode = OFF|BACK|FRONT|SLICE depth = [0..1] width = [0..1]" << "\n";
4403     return -1;
4404   }
4405   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4406   if(aContext.IsNull())
4407   {
4408     di << "use 'vinit' command before " << argv[0] << "\n";
4409     return 1;
4410   }
4411   Handle(V3d_View) aView = ViewerTest::CurrentView();
4412   V3d_TypeOfZclipping aZClippingMode = V3d_OFF;
4413   if(argc==1)
4414   {
4415     TCollection_AsciiString aZClippingModeString;
4416     Quantity_Length aDepth, aWidth;
4417     aZClippingMode = aView->ZClipping(aDepth, aWidth);
4418     switch (aZClippingMode)
4419     {
4420     case V3d_OFF:
4421       aZClippingModeString.Copy("OFF");
4422       break;
4423     case V3d_BACK:
4424       aZClippingModeString.Copy("BACK");
4425       break;
4426     case V3d_FRONT:
4427       aZClippingModeString.Copy("FRONT");
4428       break;
4429     case V3d_SLICE:
4430       aZClippingModeString.Copy("SLICE");
4431       break;
4432     default:
4433       aZClippingModeString.Copy(TCollection_AsciiString(aZClippingMode));
4434       break;
4435     }
4436     di << "ZClippingMode = " << aZClippingModeString.ToCString() << "\n"
4437       << "ZClipping depth = " << aDepth << "\n"
4438       << "ZClipping width = " << aWidth << "\n";
4439   }
4440   else
4441   {
4442     if(argc !=3)
4443     {
4444       Standard_Integer aStatus = 0;
4445       if ( strcmp (argv [1], "OFF") == 0 ) {
4446         aStatus = 1;
4447         aZClippingMode = V3d_OFF;
4448       }
4449       if ( strcmp (argv [1], "BACK") == 0 ) {
4450         aStatus = 1;
4451         aZClippingMode = V3d_BACK;
4452       }
4453       if ( strcmp (argv [1], "FRONT") == 0 ) {
4454         aStatus = 1;
4455         aZClippingMode = V3d_FRONT;
4456       }
4457       if ( strcmp (argv [1], "SLICE") == 0 ) {
4458         aStatus = 1;
4459         aZClippingMode = V3d_SLICE;
4460       }
4461       if (aStatus != 1)
4462       {
4463         di << "Bad mode; Usage : " << argv[0] << " [mode] [depth width]" << "\n"
4464           << "mode = OFF|BACK|FRONT|SLICE depth = [0..1] width = [0..1]" << "\n";
4465         return 1;
4466       }
4467       aView->SetZClippingType(aZClippingMode);
4468     }
4469     if(argc >2)
4470     {
4471       Quantity_Length aDepth = 0., aWidth = 1.;
4472       if(argc == 3)
4473       {
4474         aDepth = atof(argv[1]);
4475         aWidth = atof(argv[2]);
4476       }
4477       else if(argc == 4)
4478       {
4479         aDepth = atof(argv[2]);
4480         aWidth = atof(argv[3]);
4481       }
4482
4483       if(aDepth<0. || aDepth>1.)
4484       {
4485         di << "Bad depth; Usage : " << argv[0] << " [mode] [depth width]" << "\n"
4486         << "mode = OFF|BACK|FRONT|SLICE depth = [0..1] width = [0..1]" << "\n";
4487         return 1;
4488       }
4489       if(aWidth<0. || aWidth>1.)
4490       {
4491         di << "Bad width; Usage : " << argv[0] << " [mode] [depth width]" << "\n"
4492         << "mode = OFF|BACK|FRONT|SLICE depth = [0..1] width = [0..1]" << "\n";
4493         return 1;
4494       }
4495
4496       aView->SetZClippingDepth(aDepth);
4497       aView->SetZClippingWidth(aWidth);
4498     }
4499     aView->Redraw();
4500   }
4501   return 0;
4502 }
4503
4504 //=======================================================================
4505 //function : VNbSelected
4506 //purpose  : Returns number of selected objects
4507 //=======================================================================
4508 static Standard_Integer VNbSelected (Draw_Interpretor& di,
4509                                 Standard_Integer argc,
4510                                 const char ** argv)
4511 {
4512   if(argc != 1)
4513   {
4514     di << "Usage : " << argv[0] << "\n";
4515     return 1;
4516   }
4517   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4518   if(aContext.IsNull())
4519   {
4520     di << "use 'vinit' command before " << argv[0] << "\n";
4521     return 1;
4522   }
4523   di << aContext->NbSelected() << "\n";
4524   return 0;
4525 }
4526
4527 //=======================================================================
4528 //function : VAntialiasing
4529 //purpose  : Switches altialiasing on or off
4530 //=======================================================================
4531 static Standard_Integer VAntialiasing (Draw_Interpretor& di,
4532                                 Standard_Integer argc,
4533                                 const char ** argv)
4534 {
4535   if(argc > 2)
4536   {
4537     di << "Usage : " << argv[0] << " [1|0]" << "\n";
4538     return 1;
4539   }
4540
4541   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4542   if(aContext.IsNull())
4543   {
4544     di << "use 'vinit' command before " << argv[0] << "\n";
4545     return 1;
4546   }
4547
4548   Handle(V3d_View) aView = ViewerTest::CurrentView();
4549
4550   if((argc == 2) && (atof(argv[1]) == 0))
4551     aView->SetAntialiasingOff();
4552   else
4553     aView->SetAntialiasingOn();
4554   aView->Update();
4555   return 0;
4556 }
4557
4558 //=======================================================================
4559 //function : VPurgeDisplay
4560 //purpose  : Switches altialiasing on or off
4561 //=======================================================================
4562 static Standard_Integer VPurgeDisplay (Draw_Interpretor& di,
4563                                 Standard_Integer argc,
4564                                 const char ** argv)
4565 {
4566   if (argc > 1)
4567   {
4568     di << "Usage : " << argv[0] << "\n";
4569     return 1;
4570   }
4571   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4572   if (aContext.IsNull())
4573   {
4574     di << "use 'vinit' command before " << argv[0] << "\n";
4575     return 1;
4576   }
4577   aContext->CloseAllContexts(Standard_False);
4578   di << aContext->PurgeDisplay() << "\n";
4579   return 0;
4580 }
4581
4582 //=======================================================================
4583 //function : VSetViewSize
4584 //purpose  :
4585 //=======================================================================
4586 static Standard_Integer VSetViewSize (Draw_Interpretor& di,
4587                                 Standard_Integer argc,
4588                                 const char ** argv)
4589 {
4590   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4591   if(aContext.IsNull())
4592   {
4593     di << "use 'vinit' command before " << argv[0] << "\n";
4594     return 1;
4595   }
4596   if(argc != 2)
4597   {
4598     di<<"Usage : " << argv[0] << " Size\n";
4599     return 1;
4600   }
4601   Standard_Real aSize = atof(argv[1]);
4602   if (aSize <= 0.)
4603   {
4604     di<<"Bad Size value  : " << aSize << "\n";
4605     return 1;
4606   }
4607
4608   Handle(V3d_View) aView = ViewerTest::CurrentView();
4609   aView->SetSize(aSize);
4610   return 0;
4611 }
4612
4613 //=======================================================================
4614 //function : VMoveView
4615 //purpose  :
4616 //=======================================================================
4617 static Standard_Integer VMoveView (Draw_Interpretor& di,
4618                                 Standard_Integer argc,
4619                                 const char ** argv)
4620 {
4621   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4622   if(aContext.IsNull())
4623   {
4624     di << "use 'vinit' command before " << argv[0] << "\n";
4625     return 1;
4626   }
4627   if(argc < 4 || argc > 5)
4628   {
4629     di<<"Usage : " << argv[0] << " Dx Dy Dz [Start = 1|0]\n";
4630     return 1;
4631   }
4632   Standard_Real Dx = atof(argv[1]);
4633   Standard_Real Dy = atof(argv[2]);
4634   Standard_Real Dz = atof(argv[3]);
4635   Standard_Boolean aStart = Standard_True;
4636   if (argc == 5)
4637   {
4638       aStart = (atoi(argv[4]) > 0);
4639   }
4640
4641   Handle(V3d_View) aView = ViewerTest::CurrentView();
4642   aView->Move(Dx,Dy,Dz,aStart);
4643   return 0;
4644 }
4645
4646 //=======================================================================
4647 //function : VTranslateView
4648 //purpose  :
4649 //=======================================================================
4650 static Standard_Integer VTranslateView (Draw_Interpretor& di,
4651                                 Standard_Integer argc,
4652                                 const char ** argv)
4653 {
4654   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4655   if(aContext.IsNull())
4656   {
4657     di << "use 'vinit' command before " << argv[0] << "\n";
4658     return 1;
4659   }
4660   if(argc < 4 || argc > 5)
4661   {
4662     di<<"Usage : " << argv[0] << " Dx Dy Dz [Start = 1|0]\n";
4663     return 1;
4664   }
4665   Standard_Real Dx = atof(argv[1]);
4666   Standard_Real Dy = atof(argv[2]);
4667   Standard_Real Dz = atof(argv[3]);
4668   Standard_Boolean aStart = Standard_True;
4669   if (argc == 5)
4670   {
4671       aStart = (atoi(argv[4]) > 0);
4672   }
4673
4674   Handle(V3d_View) aView = ViewerTest::CurrentView();
4675   aView->Translate(Dx,Dy,Dz,aStart);
4676   return 0;
4677 }
4678
4679 //=======================================================================
4680 //function : VTurnView
4681 //purpose  :
4682 //=======================================================================
4683 static Standard_Integer VTurnView (Draw_Interpretor& di,
4684                                 Standard_Integer argc,
4685                                 const char ** argv)
4686 {
4687   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
4688   if(aContext.IsNull()) {
4689     di << "use 'vinit' command before " << argv[0] << "\n";
4690     return 1;
4691   }
4692   if(argc < 4 || argc > 5){
4693     di<<"Usage : " << argv[0] << " Ax Ay Az [Start = 1|0]\n";
4694     return 1;
4695   }
4696   Standard_Real Ax = atof(argv[1]);
4697   Standard_Real Ay = atof(argv[2]);
4698   Standard_Real Az = atof(argv[3]);
4699   Standard_Boolean aStart = Standard_True;
4700   if (argc == 5)
4701   {
4702       aStart = (atoi(argv[4]) > 0);
4703   }
4704
4705   Handle(V3d_View) aView = ViewerTest::CurrentView();
4706   aView->Turn(Ax,Ay,Az,aStart);
4707   return 0;
4708 }
4709
4710 //==============================================================================
4711 //function : VTextureEnv
4712 //purpose  : ENables or disables environment mapping
4713 //==============================================================================
4714 class OCC_TextureEnv : public Graphic3d_TextureEnv
4715 {
4716 public:
4717   OCC_TextureEnv(const Standard_CString FileName);
4718   OCC_TextureEnv(const Graphic3d_NameOfTextureEnv aName);
4719   void SetTextureParameters(const Standard_Boolean theRepeatFlag,
4720                             const Standard_Boolean theModulateFlag,
4721                             const Graphic3d_TypeOfTextureFilter theFilter,
4722                             const Standard_ShortReal theXScale,
4723                             const Standard_ShortReal theYScale,
4724                             const Standard_ShortReal theXShift,
4725                             const Standard_ShortReal theYShift,
4726                             const Standard_ShortReal theAngle);
4727   DEFINE_STANDARD_RTTI(OCC_TextureEnv);
4728 };
4729 DEFINE_STANDARD_HANDLE(OCC_TextureEnv, Graphic3d_TextureEnv);
4730 IMPLEMENT_STANDARD_HANDLE(OCC_TextureEnv, Graphic3d_TextureEnv);
4731 IMPLEMENT_STANDARD_RTTIEXT(OCC_TextureEnv, Graphic3d_TextureEnv);
4732
4733 OCC_TextureEnv::OCC_TextureEnv(const Standard_CString theFileName)
4734   : Graphic3d_TextureEnv(theFileName)
4735 {
4736 }
4737
4738 OCC_TextureEnv::OCC_TextureEnv(const Graphic3d_NameOfTextureEnv theTexId)
4739   : Graphic3d_TextureEnv(theTexId)
4740 {
4741 }
4742
4743 void OCC_TextureEnv::SetTextureParameters(const Standard_Boolean theRepeatFlag,
4744                                           const Standard_Boolean theModulateFlag,
4745                                           const Graphic3d_TypeOfTextureFilter theFilter,
4746                                           const Standard_ShortReal theXScale,
4747                                           const Standard_ShortReal theYScale,
4748                                           const Standard_ShortReal theXShift,
4749                                           const Standard_ShortReal theYShift,
4750                                           const Standard_ShortReal theAngle)
4751 {
4752   myParams->SetRepeat     (theRepeatFlag);
4753   myParams->SetModulate   (theModulateFlag);
4754   myParams->SetFilter     (theFilter);
4755   myParams->SetScale      (Graphic3d_Vec2(theXScale, theYScale));
4756   myParams->SetTranslation(Graphic3d_Vec2(theXShift, theYShift));
4757   myParams->SetRotation   (theAngle);
4758 }
4759
4760 static int VTextureEnv (Draw_Interpretor& /*theDI*/, Standard_Integer theArgNb, const char** theArgVec)
4761 {
4762   // get the active view
4763   Handle(V3d_View) aView = ViewerTest::CurrentView();
4764   if (aView.IsNull())
4765   {
4766     std::cerr << "No active view. Please call vinit.\n";
4767     return 1;
4768   }
4769
4770   // Checking the input arguments
4771   Standard_Boolean anEnableFlag = Standard_False;
4772   Standard_Boolean isOk         = theArgNb >= 2;
4773   if (isOk)
4774   {
4775     TCollection_AsciiString anEnableOpt(theArgVec[1]);
4776     anEnableFlag = anEnableOpt.IsEqual("on");
4777     isOk         = anEnableFlag || anEnableOpt.IsEqual("off");
4778   }
4779   if (anEnableFlag)
4780   {
4781     isOk = (theArgNb == 3 || theArgNb == 11);
4782     if (isOk)
4783     {
4784       TCollection_AsciiString aTextureOpt(theArgVec[2]);
4785       isOk = (!aTextureOpt.IsIntegerValue() ||
4786              (aTextureOpt.IntegerValue() >= 0 && aTextureOpt.IntegerValue() < Graphic3d_NOT_ENV_UNKNOWN));
4787
4788       if (isOk && theArgNb == 11)
4789       {
4790         TCollection_AsciiString aRepeatOpt  (theArgVec[3]),
4791                                 aModulateOpt(theArgVec[4]),
4792                                 aFilterOpt  (theArgVec[5]),
4793                                 aSScaleOpt  (theArgVec[6]),
4794                                 aTScaleOpt  (theArgVec[7]),
4795                                 aSTransOpt  (theArgVec[8]),
4796                                 aTTransOpt  (theArgVec[9]),
4797                                 anAngleOpt  (theArgVec[10]);
4798         isOk = ((aRepeatOpt.  IsEqual("repeat")   || aRepeatOpt.  IsEqual("clamp")) &&
4799                 (aModulateOpt.IsEqual("modulate") || aModulateOpt.IsEqual("decal")) &&
4800                 (aFilterOpt.  IsEqual("nearest")  || aFilterOpt.  IsEqual("bilinear") || aFilterOpt.IsEqual("trilinear")) &&
4801                 aSScaleOpt.IsRealValue() && aTScaleOpt.IsRealValue() &&
4802                 aSTransOpt.IsRealValue() && aTTransOpt.IsRealValue() &&
4803                 anAngleOpt.IsRealValue());
4804       }
4805     }
4806   }
4807
4808   if (!isOk)
4809   {
4810     std::cerr << "Usage :" << std::endl;
4811     std::cerr << theArgVec[0] << " off" << std::endl;
4812     std::cerr << theArgVec[0] << " on {index_of_std_texture(0..7)|texture_file_name} [{clamp|repeat} {decal|modulate} {nearest|bilinear|trilinear} scale_s scale_t translation_s translation_t rotation_degrees]" << std::endl;
4813     return 1;
4814   }
4815
4816   if (anEnableFlag)
4817   {
4818     TCollection_AsciiString aTextureOpt(theArgVec[2]);
4819     Handle(OCC_TextureEnv) aTexEnv = aTextureOpt.IsIntegerValue() ?
4820                                      new OCC_TextureEnv((Graphic3d_NameOfTextureEnv)aTextureOpt.IntegerValue()) :
4821                                      new OCC_TextureEnv(theArgVec[2]);
4822
4823     if (theArgNb == 11)
4824     {
4825       TCollection_AsciiString aRepeatOpt(theArgVec[3]), aModulateOpt(theArgVec[4]), aFilterOpt(theArgVec[5]);
4826       aTexEnv->SetTextureParameters(
4827         aRepeatOpt.  IsEqual("repeat"),
4828         aModulateOpt.IsEqual("modulate"),
4829         aFilterOpt.  IsEqual("nearest") ? Graphic3d_TOTF_NEAREST :
4830                                           aFilterOpt.IsEqual("bilinear") ? Graphic3d_TOTF_BILINEAR :
4831                                                                            Graphic3d_TOTF_TRILINEAR,
4832         (Standard_ShortReal)Draw::Atof(theArgVec[6]),
4833         (Standard_ShortReal)Draw::Atof(theArgVec[7]),
4834         (Standard_ShortReal)Draw::Atof(theArgVec[8]),
4835         (Standard_ShortReal)Draw::Atof(theArgVec[9]),
4836         (Standard_ShortReal)Draw::Atof(theArgVec[10])
4837         );
4838     }
4839     aView->SetTextureEnv(aTexEnv);
4840     aView->SetSurfaceDetail(V3d_TEX_ENVIRONMENT);
4841   }
4842   else // Disabling environment mapping
4843   {
4844     aView->SetSurfaceDetail(V3d_TEX_NONE);
4845     Handle(Graphic3d_TextureEnv) aTexture;
4846     aView->SetTextureEnv(aTexture); // Passing null handle to clear the texture data
4847   }
4848
4849   aView->Redraw();
4850   return 0;
4851 }
4852
4853 //===============================================================================================
4854 //function : VClipPlane
4855 //purpose  :
4856 //===============================================================================================
4857 static int VClipPlane (Draw_Interpretor& theDi, Standard_Integer theArgsNb, const char** theArgVec)
4858 {
4859   // use short-cut for created clip planes map of created (or "registered by name") clip planes
4860   typedef NCollection_DataMap<TCollection_AsciiString, Handle(Graphic3d_ClipPlane)> MapOfPlanes;
4861   static MapOfPlanes aRegPlanes;
4862
4863   if (theArgsNb < 2)
4864   {
4865     theDi << theArgVec[0] << ": command argument is required. Type help for more information.\n";
4866     return 1;
4867   }
4868
4869   TCollection_AsciiString aCommand (theArgVec[1]);
4870
4871   // print maximum number of planes for current viewer
4872   if (aCommand == "maxplanes")
4873   {
4874     if (theArgsNb < 3)
4875     {
4876       theDi << theArgVec[0] << ": view name is required. Type help for more information.\n";
4877       return 1;
4878     }
4879
4880     TCollection_AsciiString aViewName (theArgVec[2]);
4881
4882     if (!ViewerTest_myViews.IsBound1 (aViewName))
4883     {
4884       theDi << theArgVec[0] << ": view is not found.\n";
4885       return 1;
4886     }
4887
4888     const Handle(V3d_View)& aView = ViewerTest_myViews.Find1 (aViewName);
4889
4890     theDi << theArgVec[0] << ": "
4891                           << aView->Viewer()->Driver()->InquirePlaneLimit()
4892                           << " plane slots provided by driver."
4893                           << " Note that 2 more planes might be used (reserved for z-clipping).\n";
4894
4895     return 0;
4896   }
4897
4898   // create / delete plane instance
4899   if (aCommand == "create" || aCommand == "delete" || aCommand == "clone")
4900   {
4901     if (theArgsNb < 3)
4902     {
4903       theDi << theArgVec[0] << ": plane name is required. Type help for more information.\n";
4904       return 1;
4905     }
4906
4907     Standard_Boolean toCreate = (aCommand == "create");
4908     Standard_Boolean toClone  = (aCommand == "clone");
4909     TCollection_AsciiString aPlane (theArgVec[2]);
4910
4911     if (toCreate)
4912     {
4913       if (aRegPlanes.IsBound (aPlane))
4914       {
4915         theDi << theArgVec[0] << ": plane name is in use.\n";
4916         return 1;
4917       }
4918
4919       aRegPlanes.Bind (aPlane, new Graphic3d_ClipPlane());
4920     }
4921     else if (toClone) // toClone
4922     {
4923       if (!aRegPlanes.IsBound (aPlane))
4924       {
4925         theDi << theArgVec[0] << ": no such plane.\n";
4926         return 1;
4927       }
4928
4929       if (theArgsNb < 4)
4930       {
4931         theDi << theArgVec[0] << ": enter name for new plane. Type help for more information.\n";
4932         return 1;
4933       }
4934
4935       TCollection_AsciiString aClone (theArgVec[3]);
4936       if (aRegPlanes.IsBound (aClone))
4937       {
4938         theDi << theArgVec[0] << ": plane name is in use.\n";
4939         return 1;
4940       }
4941
4942       const Handle(Graphic3d_ClipPlane)& aClipPlane = aRegPlanes.Find (aPlane);
4943
4944       aRegPlanes.Bind (aClone, aClipPlane->Clone());
4945     }
4946     else// toDelete
4947     {
4948       if (!aRegPlanes.IsBound (aPlane))
4949       {
4950         theDi << theArgVec[0] << ": no such plane.\n";
4951         return 1;
4952       }
4953
4954       Handle(Graphic3d_ClipPlane) aClipPlane = aRegPlanes.Find (aPlane);
4955       aRegPlanes.UnBind (aPlane);
4956
4957       ViewerTest_DoubleMapIteratorOfDoubleMapOfInteractiveAndName anIObjIt (GetMapOfAIS());
4958       for (; anIObjIt.More(); anIObjIt.Next())
4959       {
4960         Handle(PrsMgr_PresentableObject) aPrs = Handle(PrsMgr_PresentableObject)::DownCast (anIObjIt.Key1());
4961         aPrs->RemoveClipPlane(aClipPlane);
4962       }
4963
4964       NCollection_DoubleMap<TCollection_AsciiString, Handle(V3d_View)>::Iterator aViewIt(ViewerTest_myViews);
4965       for (; aViewIt.More(); aViewIt.Next())
4966       {
4967         const Handle(V3d_View)& aView = aViewIt.Key2();
4968         aView->RemoveClipPlane(aClipPlane);
4969       }
4970
4971       ViewerTest::RedrawAllViews();
4972     }
4973
4974     return 0;
4975   }
4976
4977   // set / unset plane command
4978   if (aCommand == "set" || aCommand == "unset")
4979   {
4980     if (theArgsNb < 4)
4981     {
4982       theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
4983       return 1;
4984     }
4985
4986     Standard_Boolean toSet = (aCommand == "set");
4987     TCollection_AsciiString aPlane (theArgVec [2]);
4988     if (!aRegPlanes.IsBound (aPlane))
4989     {
4990       theDi << theArgVec[0] << ": no such plane.\n";
4991       return 1;
4992     }
4993
4994     const Handle(Graphic3d_ClipPlane)& aClipPlane = aRegPlanes.Find (aPlane);
4995
4996     TCollection_AsciiString aTarget (theArgVec [3]);
4997     if (aTarget != "object" && aTarget != "view")
4998     {
4999       theDi << theArgVec[0] << ": invalid target.\n";
5000       return 1;
5001     }
5002
5003     if (aTarget == "object" || aTarget == "view")
5004     {
5005       if (theArgsNb < 5)
5006       {
5007         theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5008         return 1;
5009       }
5010
5011       Standard_Boolean isObject = (aTarget == "object");
5012
5013       for (Standard_Integer anIt = 4; anIt < theArgsNb; ++anIt)
5014       {
5015         TCollection_AsciiString anEntityName (theArgVec[anIt]);
5016         if (isObject) // to object
5017         {
5018           if (!GetMapOfAIS().IsBound2 (anEntityName))
5019           {
5020             theDi << theArgVec[0] << ": can not find IO with name " << anEntityName << ".\n";
5021             continue;
5022           }
5023
5024           Handle(AIS_InteractiveObject) aIObj =
5025             Handle(AIS_InteractiveObject)::DownCast (GetMapOfAIS().Find2 (anEntityName));
5026
5027           if (toSet)
5028             aIObj->AddClipPlane (aClipPlane);
5029           else
5030             aIObj->RemoveClipPlane (aClipPlane);
5031         }
5032         else // to view
5033         {
5034           if (!ViewerTest_myViews.IsBound1 (anEntityName))
5035           {
5036             theDi << theArgVec[0] << ": can not find View with name " << anEntityName << ".\n";
5037             continue;
5038           }
5039
5040           Handle(V3d_View) aView = ViewerTest_myViews.Find1(anEntityName);
5041           if (toSet)
5042             aView->AddClipPlane (aClipPlane);
5043           else
5044             aView->RemoveClipPlane (aClipPlane);
5045         }
5046       }
5047
5048       ViewerTest::RedrawAllViews();
5049     }
5050
5051     return 0;
5052   }
5053
5054   // change plane command
5055   if (aCommand == "change")
5056   {
5057     if (theArgsNb < 4)
5058     {
5059       theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5060       return 1;
5061     }
5062
5063     TCollection_AsciiString aPlane (theArgVec [2]);
5064     if (!aRegPlanes.IsBound (aPlane))
5065     {
5066       theDi << theArgVec[0] << ": no such plane.\n";
5067       return 1;
5068     }
5069
5070     const Handle(Graphic3d_ClipPlane)& aClipPlane = aRegPlanes.Find (aPlane);
5071
5072     TCollection_AsciiString aChangeArg (theArgVec [3]);
5073     if (aChangeArg != "on" && aChangeArg != "off" && aChangeArg != "capping" && aChangeArg != "equation")
5074     {
5075       theDi << theArgVec[0] << ": invalid arguments. Type help for more information.\n";
5076       return 1;
5077     }
5078
5079     if (aChangeArg == "on" || aChangeArg == "off") // on / off
5080     {
5081       aClipPlane->SetOn (aChangeArg == "on");
5082     }
5083     else if (aChangeArg == "equation") // change equation
5084     {
5085       if (theArgsNb < 8)
5086       {
5087         theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5088         return 1;
5089       }
5090
5091       Standard_Real aCoeffA = atof (theArgVec [4]);
5092       Standard_Real aCoeffB = atof (theArgVec [5]);
5093       Standard_Real aCoeffC = atof (theArgVec [6]);
5094       Standard_Real aCoeffD = atof (theArgVec [7]);
5095       aClipPlane->SetEquation (gp_Pln (aCoeffA, aCoeffB, aCoeffC, aCoeffD));
5096     }
5097     else if (aChangeArg == "capping") // change capping aspects
5098     {
5099       if (theArgsNb < 5)
5100       {
5101         theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5102         return 1;
5103       }
5104
5105       TCollection_AsciiString aCappingArg (theArgVec [4]);
5106       if (aCappingArg != "on" && aCappingArg != "off" &&
5107           aCappingArg != "color" && aCappingArg != "texname" &&
5108           aCappingArg != "texscale" && aCappingArg != "texorigin" &&
5109           aCappingArg != "texrotate" && aCappingArg != "hatch")
5110       {
5111         theDi << theArgVec[0] << ": invalid arguments. Type help for more information.\n";
5112         return 1;
5113       }
5114
5115       if (aCappingArg == "on" || aCappingArg == "off") // on / off capping
5116       {
5117         aClipPlane->SetCapping (aCappingArg == "on");
5118       }
5119       else if (aCappingArg == "color") // color aspect for capping
5120       {
5121         if (theArgsNb < 8)
5122         {
5123           theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5124           return 1;
5125         }
5126
5127         Standard_Real aRed = atof (theArgVec [5]);
5128         Standard_Real aGrn = atof (theArgVec [6]);
5129         Standard_Real aBlu = atof (theArgVec [7]);
5130
5131         Graphic3d_MaterialAspect aMat = aClipPlane->CappingMaterial();
5132         aMat.SetColor (Quantity_Color (aRed, aGrn, aBlu, Quantity_TOC_RGB));
5133         aClipPlane->SetCappingMaterial (aMat);
5134       }
5135       else if (aCappingArg == "texname") // texture name
5136       {
5137         if (theArgsNb < 6)
5138         {
5139           theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5140           return 1;
5141         }
5142
5143         TCollection_AsciiString aTextureName (theArgVec [5]);
5144
5145         Handle(Graphic3d_Texture2Dmanual) aTexture = new Graphic3d_Texture2Dmanual(aTextureName);
5146         if (!aTexture->IsDone ())
5147         {
5148           aClipPlane->SetCappingTexture (NULL);
5149         }
5150         else
5151         {
5152           aTexture->EnableModulate();
5153           aTexture->EnableRepeat();
5154           aClipPlane->SetCappingTexture (aTexture);
5155         }
5156       }
5157       else if (aCappingArg == "texscale") // texture scale
5158       {
5159         if (aClipPlane->CappingTexture().IsNull())
5160         {
5161           theDi << theArgVec[0] << ": no texture is set.\n";
5162           return 1;
5163         }
5164
5165         if (theArgsNb < 7)
5166         {
5167           theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5168           return 1;
5169         }
5170
5171         Standard_ShortReal aSx = (Standard_ShortReal)atof (theArgVec [5]);
5172         Standard_ShortReal aSy = (Standard_ShortReal)atof (theArgVec [6]);
5173
5174         aClipPlane->CappingTexture()->GetParams()->SetScale (Graphic3d_Vec2 (aSx, aSy));
5175       }
5176       else if (aCappingArg == "texorigin") // texture origin
5177       {
5178         if (aClipPlane->CappingTexture().IsNull())
5179         {
5180           theDi << theArgVec[0] << ": no texture is set.\n";
5181           return 1;
5182         }
5183
5184         if (theArgsNb < 7)
5185         {
5186           theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5187           return 1;
5188         }
5189
5190         Standard_ShortReal aTx = (Standard_ShortReal)atof (theArgVec [5]);
5191         Standard_ShortReal aTy = (Standard_ShortReal)atof (theArgVec [6]);
5192
5193         aClipPlane->CappingTexture()->GetParams()->SetTranslation (Graphic3d_Vec2 (aTx, aTy));
5194       }
5195       else if (aCappingArg == "texrotate") // texture rotation
5196       {
5197         if (aClipPlane->CappingTexture().IsNull())
5198         {
5199           theDi << theArgVec[0] << ": no texture is set.\n";
5200           return 1;
5201         }
5202
5203         if (theArgsNb < 6)
5204         {
5205           theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5206           return 1;
5207         }
5208
5209         Standard_ShortReal aRot = (Standard_ShortReal)atof (theArgVec[5]);
5210
5211         aClipPlane->CappingTexture()->GetParams()->SetRotation (aRot);
5212       }
5213       else if (aCappingArg == "hatch") // hatch style
5214       {
5215         if (theArgsNb < 6)
5216         {
5217           theDi << theArgVec[0] << ": need more arguments. Type help for more information.\n";
5218           return 1;
5219         }
5220
5221         TCollection_AsciiString aHatchStr (theArgVec [5]);
5222         if (aHatchStr == "on")
5223         {
5224           aClipPlane->SetCappingHatchOn();
5225         }
5226         else if (aHatchStr == "off")
5227         {
5228           aClipPlane->SetCappingHatchOff();
5229         }
5230         else
5231         {
5232           aClipPlane->SetCappingHatch ((Aspect_HatchStyle)atoi (theArgVec[5]));
5233         }
5234       }
5235     }
5236
5237     ViewerTest::RedrawAllViews();
5238
5239     return 0;
5240   }
5241
5242   theDi << theArgVec[0] << ": invalid command. Type help for more information.\n";
5243   return 1;
5244 }
5245
5246 //===============================================================================================
5247 //function : VSetTextureMode
5248 //purpose  :
5249 //===============================================================================================
5250 static int VSetTextureMode (Draw_Interpretor& theDi, Standard_Integer theArgsNb, const char** theArgVec)
5251 {
5252   if (theArgsNb < 3)
5253   {
5254     theDi << theArgVec[0] << ": insufficient command arguments. Type help for more information.\n";
5255     return 1;
5256   }
5257
5258   TCollection_AsciiString aViewName (theArgVec[1]);
5259   if (!ViewerTest_myViews.IsBound1 (aViewName))
5260   {
5261     theDi << theArgVec[0] << ": view is not found.\n";
5262     return 1;
5263   }
5264
5265   const Handle(V3d_View)& aView = ViewerTest_myViews.Find1 (aViewName);
5266   switch (atoi (theArgVec[2]))
5267   {
5268     case 0: aView->SetSurfaceDetail (V3d_TEX_NONE); break;
5269     case 1: aView->SetSurfaceDetail (V3d_TEX_ENVIRONMENT); break;
5270     case 2: aView->SetSurfaceDetail (V3d_TEX_ALL); break;
5271     default:
5272       theDi << theArgVec[0] << ": invalid mode.\n";
5273       return 1;
5274   }
5275
5276   aView->Redraw();
5277   return 0;
5278 }
5279
5280 //==============================================================================
5281 //function : VClInfo
5282 //purpose  : Prints info about active OpenCL device
5283 //==============================================================================
5284
5285 static Standard_Integer VClInfo (Draw_Interpretor& theInterpretor,
5286                                  Standard_Integer,
5287                                  const char**)
5288 {
5289 #ifndef HAVE_OPENCL
5290
5291   theInterpretor << "OCCT was compiled without OpenCL support!\n";
5292
5293 #else
5294
5295   Handle(AIS_InteractiveContext) aContextAIS = ViewerTest::GetAISContext();
5296
5297   if (aContextAIS.IsNull())
5298   {
5299     theInterpretor << "Call vinit before!\n";
5300     return 1;
5301   }
5302
5303   Handle(OpenGl_GraphicDriver) aDrv = Handle(OpenGl_GraphicDriver)::DownCast (aContextAIS->CurrentViewer()->Driver());
5304   
5305   Graphic3d_CView* aCView = (Graphic3d_CView*) ViewerTest::CurrentView()->View()->CView();
5306
5307   NCollection_DataMap<TCollection_AsciiString, TCollection_AsciiString> anInfo;
5308
5309   if (aDrv.IsNull() || aCView == NULL || !aDrv->GetOpenClDeviceInfo (*aCView, anInfo))
5310   {
5311     theInterpretor << "Cannot get OpenCL device info!\n";
5312     return 0;
5313   }
5314   
5315   theInterpretor << "OpenCL device info:\n";
5316   
5317   NCollection_DataMap<TCollection_AsciiString, TCollection_AsciiString>::Iterator anIter (anInfo);
5318
5319   for (; anIter.More(); anIter.Next())
5320   {
5321     theInterpretor << anIter.Key() << ": \t" << anIter.Value() << "\n";
5322   }
5323
5324 #endif
5325
5326   return 0;
5327 }
5328
5329 //=======================================================================
5330 //function : VRaytrace
5331 //purpose  : Enables/disables OpenCL-based ray-tracing
5332 //=======================================================================
5333
5334 #ifndef HAVE_OPENCL
5335
5336 static Standard_Integer VRaytrace (Draw_Interpretor& theInterpretor,
5337                                    Standard_Integer,
5338                                    const char**)
5339 {
5340   theInterpretor << "OCCT was compiled without OpenCL support!\n";
5341
5342   return 0;
5343 }
5344
5345 #else
5346
5347 static Standard_Integer VRaytrace (Draw_Interpretor&,
5348                                    Standard_Integer theArgNb,
5349                                    const char** theArgVec)
5350 {
5351   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
5352
5353   if (aContext.IsNull())
5354   {
5355     std::cerr << "Use 'vinit' command before " << theArgVec[0] << "\n";
5356     return 1;
5357   }
5358
5359   if (theArgNb < 2)
5360   {
5361     std::cerr << "Usage : " << theArgVec[0] << " 0|1\n";
5362     return 1;
5363   }
5364   
5365   Standard_Integer isOn = atoi(theArgVec[1]);
5366
5367   Handle(V3d_View) aView = ViewerTest::CurrentView();
5368
5369   if (isOn)
5370     aView->SetRaytracingMode();
5371   else
5372     aView->SetRasterizationMode();
5373
5374   aView->Redraw();
5375
5376   return 0;
5377 }
5378
5379 #endif
5380
5381 //=======================================================================
5382 //function : VSetRaytraceMode
5383 //purpose  : Enables/disables features of OpenCL-based ray-tracing
5384 //=======================================================================
5385
5386 #ifndef HAVE_OPENCL
5387
5388 static Standard_Integer VSetRaytraceMode (Draw_Interpretor& theInterpretor,
5389                                           Standard_Integer,
5390                                           const char**)
5391 {
5392   theInterpretor << "OCCT was compiled without OpenCL support!\n";
5393
5394   return 0;
5395 }
5396
5397 #else
5398
5399 static Standard_Integer VSetRaytraceMode (Draw_Interpretor&,
5400                                           Standard_Integer theArgNb,
5401                                           const char ** theArgVec)
5402 {
5403   Handle(AIS_InteractiveContext) aContext = ViewerTest::GetAISContext();
5404
5405   if (aContext.IsNull())
5406   {
5407     std::cerr << "Use 'vinit' command before " << theArgVec[0] << "\n";
5408     return 1;
5409   }
5410
5411   if (theArgNb < 2)
5412   {
5413     std::cerr << "Usage : " << theArgVec[0] << " [shad=0|1] [refl=0|1] [aa=0|1]\n";
5414     return 1;
5415   }
5416
5417   Handle(V3d_View) aView = ViewerTest::CurrentView();
5418
5419   for (Standard_Integer anArgIter = 1; anArgIter < theArgNb; ++anArgIter)
5420   {
5421     const TCollection_AsciiString anArg (theArgVec[anArgIter]);
5422
5423     if (anArg.Search ("shad=") > -1)
5424     {
5425       if (anArg.Token ("=", 2).IntegerValue() != 0)
5426         aView->EnableRaytracedShadows();
5427       else
5428         aView->DisableRaytracedShadows();
5429     }
5430     else if (anArg.Search ("refl=") > -1)
5431     {
5432       if (anArg.Token ("=", 2).IntegerValue() != 0)
5433         aView->EnableRaytracedReflections();
5434       else
5435         aView->DisableRaytracedReflections();
5436     }
5437     else if (anArg.Search ("aa=") > -1)
5438     {
5439       if (anArg.Token ("=", 2).IntegerValue() != 0)
5440         aView->EnableRaytracedAntialiasing();
5441       else
5442         aView->DisableRaytracedAntialiasing();
5443     }
5444     else
5445     {
5446       std::cerr << "Unknown argument: " << anArg << "\n";
5447     }
5448   }
5449
5450   aView->Redraw();
5451
5452   return 0;
5453 }
5454
5455 #endif
5456
5457 //=======================================================================
5458 //function : ViewerCommands
5459 //purpose  :
5460 //=======================================================================
5461
5462 void ViewerTest::ViewerCommands(Draw_Interpretor& theCommands)
5463 {
5464
5465   const char *group = "ZeViewer";
5466   theCommands.Add("vinit",
5467 #if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
5468     "[name=view_name] [display=display_name] [l=leftPx t=topPx] [w=widthPx h=heightPx]\n"
5469 #else
5470     "[name=view_name] [l=leftPx t=topPx] [w=widthPx h=heightPx]\n"
5471 #endif
5472     " - Creates new View window with specified name view_name.\n"
5473     "By default the new view is created in the viewer and in"
5474     " graphic driver shared with active view.\n"
5475     " - name = {driverName/viewerName/viewName | viewerName/viewName | viewName}.\n"
5476     "If driverName isn't specified the driver will be shared with active view.\n"
5477     "If viewerName isn't specified the viewer will be shared with active view.\n"
5478 #if !defined(_WIN32) && !defined(__WIN32__) && (!defined(__APPLE__) || defined(MACOSX_USE_GLX))
5479     " - display = HostName.DisplayNumber[:ScreenNumber] : if specified"
5480     "is used in creation of graphic driver\n"
5481 #endif
5482     " - l, t: pixel position of left top corner of the window\n"
5483     " - w,h: width and heigth of window respectively.\n"
5484     "Additional commands for operations with views: vclose, vactivate, vviewlist.\n",
5485     __FILE__,VInit,group);
5486   theCommands.Add("vclose" ,
5487     "[view_id [keep_context=0|1]]\n"
5488     "or vclose ALL - to remove all created views\n"
5489     " - removes view(viewer window) defined by its view_id.\n"
5490     " - keep_context: by default 0; if 1 and the last view is deleted"
5491     " the current context is not removed.",
5492     __FILE__,VClose,group);
5493   theCommands.Add("vactivate" ,
5494     "view_id"
5495     " - activates view(viewer window) defined by its view_id",
5496     __FILE__,VActivate,group);
5497   theCommands.Add("vviewlist",
5498     "vviewlist [format={tree, long}]"
5499     " - prints current list of views per viewer and graphic_driver ID shared between viewers"
5500     " - format: format of result output, if tree the output is a tree view;"
5501     "otherwise it's a list of full view names. By default format = tree",
5502     __FILE__,VViewList,group);
5503   theCommands.Add("vhelp" ,
5504     "vhelp            : display help on the viewer commands",
5505     __FILE__,VHelp,group);
5506   theCommands.Add("vtop" ,
5507     "vtop or <T>      : Top view" ,
5508     __FILE__,VTop,group);
5509   theCommands.Add("vbottom" ,
5510     "vbottom          : Bottom view" ,
5511     __FILE__,VBottom,group);
5512   theCommands.Add("vleft" ,
5513     "vleft            : Left view" ,
5514     __FILE__,VLeft,group);
5515   theCommands.Add("vright" ,
5516     "vright           : Right view" ,
5517     __FILE__,VRight,group);
5518   theCommands.Add("vaxo" ,
5519     " vaxo or <A>     : Axonometric view ",
5520     __FILE__,VAxo,group);
5521   theCommands.Add("vfront" ,
5522     "vfront           : Front view" ,
5523     __FILE__,VFront,group);
5524   theCommands.Add("vback" ,
5525     "vback            : Back view" ,
5526     __FILE__,VBack,group);
5527   theCommands.Add("vpick" ,
5528     "vpick           : vpick X Y Z [shape subshape] ( all variables as string )",
5529     VPick,group);
5530   theCommands.Add("vfit"    ,
5531     "vfit or <F>         : vfit",
5532     __FILE__,VFit,group);
5533   theCommands.Add("vzfit"    ,
5534     "vzfit",
5535     __FILE__,VZFit,group);
5536   theCommands.Add("vrepaint",
5537     "vrepaint        : vrepaint, force redraw",
5538     __FILE__,VRepaint,group);
5539   theCommands.Add("vclear",
5540     "vclear          : vclear",
5541     __FILE__,VClear,group);
5542   theCommands.Add("vsetbg",
5543     "vsetbg          : vsetbg imagefile [filltype] : Load image as background",
5544     __FILE__,VSetBg,group);
5545   theCommands.Add("vsetbgmode",
5546     "vsetbgmode      : vsetbgmode filltype : Change background image fill type",
5547     __FILE__,VSetBgMode,group);
5548   theCommands.Add("vsetgradientbg",
5549     "vsetgradientbg  : vsetgradientbg r1 g1 b1 r2 g2 b2 filltype : Mount gradient background",
5550     __FILE__,VSetGradientBg,group);
5551   theCommands.Add("vsetgrbgmode",
5552     "vsetgrbgmode    : vsetgrbgmode filltype : Change gradient background fill type",
5553     __FILE__,VSetGradientBgMode,group);
5554   theCommands.Add("vsetcolorbg",
5555     "vsetcolorbg     : vsetcolorbg r g b : Set background color",
5556     __FILE__,VSetColorBg,group);
5557   theCommands.Add("vscale",
5558     "vscale          : vscale X Y Z",
5559     __FILE__,VScale,group);
5560   theCommands.Add("vzbufftrihedron",
5561     "vzbufftrihedron [center|left_lower|left_upper|right_lower|right_upper"
5562     " textR=255 textG=255 textB=255 scale=0.1 wireframe|zbuffer]"
5563     " : Displays a V3d_ZBUFFER'ed or V3d_WIREFRAME'd trihedron",
5564     __FILE__,VTestZBuffTrihedron,group);
5565   theCommands.Add("vrotate",
5566     "vrotate         : vrotate AX AY AZ [X Y Z]",
5567     __FILE__,VRotate,group);
5568   theCommands.Add("vzoom",
5569     "vzoom           : vzoom coef",
5570     __FILE__,VZoom,group);
5571   theCommands.Add("vpan",
5572     "vpan            : vpan dx dy",
5573     __FILE__,VPan,group);
5574   theCommands.Add("vexport",
5575     "vexport         : vexport full_file_path {PS | EPS | TEX | PDF | SVG | PGF | EMF }"
5576     " : exports the view to a vector file of a given format"
5577     " : notice that EMF format requires patched gl2ps",
5578     __FILE__,VExport,group);
5579   theCommands.Add("vcolorscale",
5580     "vcolorscale     : vcolorscale [RangeMin = 0 RangeMax = 100 Intervals = 10 HeightFont = 16 Position = 2 X = 0 Y = 0]: draw color scale",
5581     __FILE__,VColorScale,group);
5582   theCommands.Add("vgraduatedtrihedron",
5583     "vgraduatedtrihedron : 1/0 (display/erase) [Xname Yname Zname [Font [isMultibyte]]]",
5584     __FILE__,VGraduatedTrihedron,group);
5585   theCommands.Add("vprintview" ,
5586     "vprintview : width height filename [algo=0] : Test print algorithm: algo = 0 - stretch, algo = 1 - tile",
5587     __FILE__,VPrintView,group);
5588   theCommands.Add("vzlayer",
5589     "vzlayer : add/del/get [id] : Z layer operations in v3d viewer: add new z layer, delete z layer, get z layer ids",
5590     __FILE__,VZLayer,group);
5591   theCommands.Add("voverlaytext",
5592     "voverlaytext : text x y [height] [font_name] [text_color: R G B] [display_type] [background_color: R G B]"
5593     " : height - pixel height of the text (default=10.0)"
5594     " : font_name - name of font (default=courier)"
5595     " : text_color - three values: RedColor GreenColor BlueColor (default = 255.0 255.0 255.0) "
5596     " : display_type = {normal/subtitle/decal/blend}, (default=normal) "
5597     " : background_color - three values: RedColor GreenColor BlueColor (default = 255.0 255.0 255.0), the parameter is defined for subtitle and decal display types ",
5598     __FILE__,VOverlayText,group);
5599   theCommands.Add("vlayerline",
5600     "vlayerline : vlayerline x1 y1 x2 y2 [linewidth=0.5] [linetype=0] [transparency=1.0]",
5601     __FILE__,VLayerLine,group);
5602   theCommands.Add ("vgrid",
5603     "vgrid [off] [Mode={r|c}] [Type={l|p}] [OriginX OriginY [StepX/StepRadius StepY/DivNb RotAngle]]"
5604     " : Mode - rectangular or circular"
5605     " : Type - lines or points",
5606     __FILE__, VGrid, group);
5607   theCommands.Add ("vfps",
5608     "vfps [framesNb=100] : estimate average frame rate for active view",
5609     __FILE__, VFps, group);
5610   theCommands.Add ("vgldebug",
5611     "vgldebug [{0|1}] : request debug GL context, should be called before vinit\n"
5612     "                : this function is implemented only for Windows\n"
5613     "                : GL_ARB_debug_output extension should be exported by OpenGL driver!",
5614     __FILE__, VGlDebug, group);
5615   theCommands.Add ("vvbo",
5616     "vvbo [{0|1}] : turn VBO usage On/Off; affects only newly displayed objects",
5617     __FILE__, VVbo, group);
5618   theCommands.Add ("vcaps",
5619     "vcaps [vbo={0|1}] [sprites={0|1}] [soft={0|1}] : modify particular graphic driver options",
5620     __FILE__, VCaps, group);
5621   theCommands.Add ("vmemgpu",
5622     "vmemgpu [f]: print system-dependent GPU memory information if available;"
5623     " with f option returns free memory in bytes",
5624     __FILE__, VMemGpu, group);
5625   theCommands.Add ("vreadpixel",
5626     "vreadpixel xPixel yPixel [{rgb|rgba|depth|hls|rgbf|rgbaf}=rgba] [name]"
5627     " : Read pixel value for active view",
5628     __FILE__, VReadPixel, group);
5629   theCommands.Add("diffimage",
5630     "diffimage     : diffimage imageFile1 imageFile2 toleranceOfColor(0..1) blackWhite(1|0) borderFilter(1|0) [diffImageFile]",
5631     __FILE__, VDiffImage, group);
5632   theCommands.Add ("vselect",
5633     "vselect x1 y1 [x2 y2 [x3 y3 ... xn yn]] [shift_selection = 0|1]\n"
5634     "- emulates different types of selection:\n"
5635     "- 1) single click selection\n"
5636     "- 2) selection with rectangle having corners at pixel positions (x1,y1) and (x2,y2)\n"
5637     "- 3) selection with polygon having corners in pixel positions (x1,y1), (x2,y2),...,(xn,yn)\n"
5638     "- 4) any of these selections with shift button pressed",
5639     __FILE__, VSelect, group);
5640   theCommands.Add ("vmoveto",
5641     "vmoveto x y"
5642     "- emulates cursor movement to pixel postion (x,y)",
5643     __FILE__, VMoveTo, group);
5644   theCommands.Add("vviewparams",
5645     "vviewparams [scale center_X center_Y proj_X proj_Y proj_Z up_X up_Y up_Z at_X at_Y at_Z]"
5646     "- gets or sets current view characteristics",
5647     __FILE__,VViewParams, group);
5648   theCommands.Add("vchangeselected",
5649     "vchangeselected shape"
5650     "- adds to shape to selection or remove one from it",
5651                 __FILE__, VChangeSelected, group);
5652   theCommands.Add("vzclipping",
5653     "vzclipping [mode] [depth width]\n"
5654     "- mode = OFF|BACK|FRONT|SLICE depth = [0..1] width = [0..1]\n"
5655     "- gets or sets ZClipping mode, width and depth",
5656     __FILE__,VZClipping,group);
5657   theCommands.Add ("vnbselected",
5658     "vnbselected", __FILE__, VNbSelected, group);
5659   theCommands.Add("vantialiasing",
5660     "vantialiasing 1|0",
5661     __FILE__,VAntialiasing,group);
5662   theCommands.Add ("vpurgedisplay",
5663     "vpurgedisplay"
5664     "- removes structures which don't belong to objects displayed in neutral point",
5665     __FILE__, VPurgeDisplay, group);
5666   theCommands.Add("vsetviewsize",
5667     "vsetviewsize size",
5668     __FILE__,VSetViewSize,group);
5669   theCommands.Add("vmoveview",
5670     "vmoveview Dx Dy Dz [Start = 1|0]",
5671     __FILE__,VMoveView,group);
5672   theCommands.Add("vtranslateview",
5673     "vtranslateview Dx Dy Dz [Start = 1|0)]",
5674     __FILE__,VTranslateView,group);
5675   theCommands.Add("vturnview",
5676     "vturnview Ax Ay Az [Start = 1|0]",
5677     __FILE__,VTurnView,group);
5678   theCommands.Add("vtextureenv",
5679     "Enables or disables environment mapping in the 3D view, loading the texture from the given standard "
5680     "or user-defined file and optionally applying texture mapping parameters\n"
5681     "                  Usage:\n"
5682     "                  vtextureenv off - disables environment mapping\n"
5683     "                  vtextureenv on {std_texture|texture_file_name} [rep mod flt ss st ts tt rot] - enables environment mapping\n"
5684     "                              std_texture = (0..7)\n"
5685     "                              rep         = {clamp|repeat}\n"
5686     "                              mod         = {decal|modulate}\n"
5687     "                              flt         = {nearest|bilinear|trilinear}\n"
5688     "                              ss, st      - scale factors for s and t texture coordinates\n"
5689     "                              ts, tt      - translation for s and t texture coordinates\n"
5690     "                              rot         - texture rotation angle in degrees",
5691     __FILE__, VTextureEnv, group);
5692   theCommands.Add("vhlr" ,
5693     "is_enabled={on|off}"
5694     " - Hidden line removal algorithm:"
5695     " - is_enabled: if is on HLR algorithm is applied\n",
5696     __FILE__,VHLR,group);
5697   theCommands.Add("vhlrtype" ,
5698     "algo_type={algo|polyalgo} [shape_1 ... shape_n]"
5699     " - Changes the type of HLR algorithm using for shapes."
5700     " - algo_type: if equals to algo, exact HLR algorithm is applied;\n"
5701     "   if equals to polyalgo, polygonal HLR algorithm is applied."
5702     "If shapes are not given HLR algoithm of given type is applied"
5703     " to all shapes in the view\n",
5704     __FILE__,VHLRType,group);
5705   theCommands.Add("vclipplane", "vclipplane usage: \n"
5706     "  maxplanes <view_name> - get plane limit for view.\n"
5707     "  create <plane_name> - create new plane.\n"
5708     "  delete <plane_name> - delete plane.\n"
5709     "  clone <source_plane> <plane_name> - clone the plane definition.\n"
5710     "  set/unset <plane_name> object <object list> - set/unset plane for IO.\n"
5711     "  set/unset <plane_name> view <view list> - set/unset plane for view.\n"
5712     "  change <plane_name> on/off - turn clipping on/off.\n"
5713     "  change <plane_name> equation <a> <b> <c> <d> - change plane equation.\n"
5714     "  change <plane_name> capping on/off - turn capping on/off.\n"
5715     "  change <plane_name> capping color <r> <g> <b> - set color.\n"
5716     "  change <plane name> capping texname <texture> - set texture.\n"
5717     "  change <plane_name> capping texscale <sx> <sy> - set tex scale.\n"
5718     "  change <plane_name> capping texorigin <tx> <ty> - set tex origin.\n"
5719     "  change <plane_name> capping texrotate <angle> - set tex rotation.\n"
5720     "  change <plane_name> capping hatch on/off/<id> - set hatching mask.\n"
5721     "  please use VSetTextureMode command to enable texture rendering in view.\n"
5722     , __FILE__, VClipPlane, group);
5723   theCommands.Add("vsettexturemode", "vsettexturemode view_name mode \n"
5724     "  mode can be:\n"
5725     "  0 - no textures enabled in view.\n"
5726     "  1 - only environment textures enabled.\n"
5727     "  2 - all textures enabled.\n"
5728     "  this command sets texture details mode for the specified view.\n"
5729     , __FILE__, VSetTextureMode, group);
5730   theCommands.Add("vraytrace",
5731     "vraytrace 0|1",
5732     __FILE__,VRaytrace,group);
5733   theCommands.Add("vclinfo",
5734     "vclinfo",
5735     __FILE__,VClInfo,group);
5736   theCommands.Add("vsetraytracemode",
5737     "vsetraytracemode [shad=0|1] [refl=0|1] [aa=0|1]",
5738     __FILE__,VSetRaytraceMode,group);
5739 }