File: vtkTDxWinDevice.cxx

package info (click to toggle)
vtk6 6.3.0%2Bdfsg2-8.1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 118,972 kB
  • sloc: cpp: 1,442,790; ansic: 113,395; python: 72,383; tcl: 46,998; xml: 8,119; yacc: 4,525; java: 4,239; perl: 3,108; lex: 1,694; sh: 1,093; asm: 154; makefile: 68; objc: 17
file content (519 lines) | stat: -rw-r--r-- 15,627 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkTDxWinDevice.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

// On Visual Studio, older than VS9, CoInitializeEx() is not automatically
// defined if the minimum compatibility OS is not specified.
// The Spacenavigator is supported on Windows 2000, XP, Vista
#if defined(_MSC_VER) && (_MSC_VER<1500) // 1500=VS9(2008)
# ifndef _WIN32_WINNT
# define _WIN32_WINNT 0x501 // for CoInitializeEx(), 0x0501 means target Windows XP or later
# endif
#endif

#include "vtkTDxWinDevice.h"

// Most of the code is derived from the SDK with sample code
// Cube3dPolling.cpp from archive Cube3Dpolling.zip from 3DConnexion.

#include <cassert>

#include "vtkTDxMotionEventInfo.h"
#include "vtkCommand.h"
#include "vtkObjectFactory.h"
#include "vtkRenderWindowInteractor.h"

#include <map>

vtkStandardNewMacro(vtkTDxWinDevice);

#include <atlbase.h> // for CComPtr<> (a smart pointer)

#include <BaseTsd.h> // for UINT_PTR

// for ISensor and IKeyboard
#import "progid:TDxInput.Device.1" no_namespace

VOID CALLBACK vtkTDxWinDeviceTimerProc(HWND hwnd,
                                       UINT uMsg,
                                       UINT_PTR idEvent,
                                       DWORD dwTime);

class vtkLessThanWindowHandle
{
public:
  bool operator()(const HWND &h1, const HWND &h2) const
    {
      return h1<h2;
    }
};


// It would be better to have the following variables as member of variable
// but the SetTimer on windows is only initialized with a function pointer
// without calldata.
std::map<HWND,vtkTDxWinDevice *,vtkLessThanWindowHandle> vtkWindowHandleToDeviceObject;

std::map<HWND,vtkTDxWinDevice *,vtkLessThanWindowHandle> vtkWindowHandleToDeviceObjectConnection;

class vtkTDxWinDevicePrivate
{
public:
  vtkTDxWinDevicePrivate()
    {
      this->TimerId=0;
      this->Sensor=0;
      this->Keyboard=0;
      this->KeyStates=0;
      this->LastTimeStamp=0;
      this->Interactor=0;
    }
  UINT_PTR TimerId;
  CComPtr<ISensor> Sensor;
  CComPtr<IKeyboard> Keyboard;
  __int64 KeyStates;
  DWORD LastTimeStamp;
  vtkRenderWindowInteractor *Interactor;
};

vtkTDxWinDevicePrivate vtkTDxWinDevicePrivateObject;

HRESULT HresultCodes[13]={S_OK,
                          REGDB_E_CLASSNOTREG,
                          CLASS_E_NOAGGREGATION,
                          E_NOINTERFACE,
                          E_POINTER,
                          E_ABORT,
                          E_ACCESSDENIED,
                          E_FAIL,
                          E_HANDLE,
                          E_INVALIDARG,
                          E_NOTIMPL,
                          E_OUTOFMEMORY,
                          E_UNEXPECTED};

const char *HresultStrings[13]={"S_OK",
                                "REGDB_E_CLASSNOTREG",
                                "CLASS_E_NOAGGREGATION",
                                "E_NOINTERFACE",
                                "E_POINTER",
                                "E_ABORT",
                                "E_ACCESSDENIED",
                                "E_FAIL",
                                "E_HANDLE",
                                "E_INVALIDARG",
                                "E_NOTIMPL",
                                "E_OUTOFMEMORY",
                                "E_UNEXPECTED"};

const UINT_PTR VTK_IDT_TDX_TIMER=1664; // Random beer.

// ----------------------------------------------------------------------------
// Description:
// Return a human readable version of an HRESULT.
const char *HresultCodeToString(HRESULT hr)
{
  int i=0;
  bool found=false;
  while(!found && i<13)
    {
    found=HresultCodes[i]==hr;
    ++i;
    }
  const char *result;
  if(found)
    {
    result=HresultStrings[i-1];
    }
  else
    {
    result="unknown";
    }
  return result;
}

// ----------------------------------------------------------------------------
// Description:
// Default constructor.
vtkTDxWinDevice::vtkTDxWinDevice()
{
  this->WindowHandle=0;
  this->Private=new vtkTDxWinDevicePrivate;
  this->IsListening=false;
  //  this->DebugOn();
}

// ----------------------------------------------------------------------------
// Description:
// Destructor. If the device is not initialized, do nothing. If the device
// is initialized, close the device.
vtkTDxWinDevice::~vtkTDxWinDevice()
{
  if(this->Initialized)
    {
    this->Close();
    }
  delete this->Private;
}

// ----------------------------------------------------------------------------
// Description:
// Get the handle of the window. Initial value is 0.
HWND vtkTDxWinDevice::GetWindowHandle() const
{
  return this->WindowHandle;
}

// ----------------------------------------------------------------------------
// Description:
// Set the handle of the window.
// \pre not_yet_initialized: !GetInitialized()
void vtkTDxWinDevice::SetWindowHandle(HWND hWnd)
{
  assert("pre: not_yet_initialized" && !this->GetInitialized());
  if(this->WindowHandle!=hWnd)
    {
    this->WindowHandle=hWnd;
    this->Modified();
    }
}

// ----------------------------------------------------------------------------
// Description:
// Initialize the device with the current display and window ids.
// It updates the value of GetInitialized().
// Initialization can fail. You must look for the value of
// GetInitialized() before processing further.
// \pre not_yet_initialized: !GetInitialized()
void vtkTDxWinDevice::Initialize()
{
  assert("pre: not_yet_initialized" && !this->GetInitialized());

  bool status=false;

  HRESULT hr=0;
  CComPtr<IUnknown> device;

  bool alreadyConnected=!vtkWindowHandleToDeviceObjectConnection.empty();

  if(alreadyConnected)
    {
      // take the first one, to copy the device information.
      std::map<HWND,vtkTDxWinDevice *,vtkLessThanWindowHandle>::iterator it=vtkWindowHandleToDeviceObjectConnection.begin();
      vtkTDxWinDevice *other=(*it).second;
      vtkTDxWinDevicePrivate *o=this->Private;
      vtkTDxWinDevicePrivate *otherO=other->Private;
      o->Sensor=otherO->Sensor;
      o->Keyboard=otherO->Keyboard;
      o->Interactor=this->Interactor;

      vtkWindowHandleToDeviceObjectConnection.insert(std::pair<const HWND,vtkTDxWinDevice *>(this->WindowHandle,this));
      this->Initialized=true;
    }
  else
    {
      hr=::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED );
      if (!SUCCEEDED(hr))
        {
          vtkWarningMacro( << "CoInitializeEx failed. hresult=0x" << hex << hr << dec << HresultCodeToString(hr));
          this->Initialized=status;
          return;
        }
      // Create the device object
      hr=device.CoCreateInstance(__uuidof(Device));
      status=SUCCEEDED(hr);
      if(status)
        {
          CComPtr<ISimpleDevice> d;

          hr=device.QueryInterface(&d);

          status=SUCCEEDED(hr);
          if(status)
            {
              vtkTDxWinDevicePrivate *o= this->Private;

              // Get the interfaces to the sensor and the keyboard;
              o->Sensor=d->Sensor;
              o->Keyboard=d->Keyboard;
              o->Interactor=this->Interactor;

              // Connect to the driver
              d->Connect();

              vtkWindowHandleToDeviceObjectConnection.insert(std::pair<const HWND,vtkTDxWinDevice *>(this->WindowHandle,this));

              vtkDebugMacro(<< "Connected to COM-object for 3dConnexion device.");
            }
          else
            {
              vtkWarningMacro(<<"Could not get the device interface. hresult=0x" << hex << hr << dec << HresultCodeToString(hr));
            }
        }
      else
        {
        // CoCreateInstance Failed.
        // It means there is no driver installed.
        // Just return silently: don't display warning message.
        }
      this->Initialized=status;
    }
}

// ----------------------------------------------------------------------------
bool vtkTDxWinDevice::GetIsListening() const
{
  return this->IsListening;
}

// ----------------------------------------------------------------------------
// \pre initialized: GetInitialized()
// \pre not_yet: !GetIsListening()
void vtkTDxWinDevice::StartListening()
{
  assert("pre: initialized" && this->GetInitialized());
  assert("pre: not_yet" && !this->GetIsListening());

  // Create timer used to poll the 3dconnexion device
  this->Private->TimerId =::SetTimer(this->WindowHandle,VTK_IDT_TDX_TIMER,25,
                                     vtkTDxWinDeviceTimerProc);

  vtkWindowHandleToDeviceObject.insert(
    std::pair<const HWND,vtkTDxWinDevice *>(this->WindowHandle,this));

  this->IsListening=true;

  vtkDebugMacro(<< "Start listening on window="  << this->WindowHandle);
}

// ----------------------------------------------------------------------------
// \pre initialized: GetInitialized()
// \pre is_listening: GetIsListening()
void vtkTDxWinDevice::StopListening()
{
  assert("pre: initialized" && this->GetInitialized());
  assert("pre: is_listening" && this->GetIsListening());

  const UINT_PTR uIDEvent = this->WindowHandle != 0 ?
    VTK_IDT_TDX_TIMER : this->Private->TimerId;
  // Kill the timer used to poll the sensor and keyboard
  ::KillTimer(this->WindowHandle, uIDEvent);
  this->Private->TimerId=0;
  this->IsListening=false;

  std::map<HWND,vtkTDxWinDevice *,vtkLessThanWindowHandle>::iterator it=vtkWindowHandleToDeviceObject.find(this->WindowHandle);

  if(it==vtkWindowHandleToDeviceObject.end())
    {
    vtkErrorMacro(<< "No matching vtkTDxWinDevice object for window hwnd=" << this->WindowHandle);
    }
  else
    {
    vtkWindowHandleToDeviceObject.erase(it);
    }
  vtkDebugMacro(<< "Stop listening on  window=" << this->WindowHandle);
}

// ----------------------------------------------------------------------------
// Description:
// Close the device. This is called by the destructor.
// You don't have to close the device explicitly, as the destructor do it
// automatically, but you can.
// \pre initialized: GetInitialized().
// \post restored: !GetInitialized()
void vtkTDxWinDevice::Close()
{
  assert("pre: initialized" && this->GetInitialized());

  vtkDebugMacro(<< "Close()" );

  CComPtr<ISimpleDevice> d;

  if(this->IsListening)
    {
    this->StopListening();
    }

  std::map<HWND,vtkTDxWinDevice *,vtkLessThanWindowHandle>::iterator it=vtkWindowHandleToDeviceObjectConnection.find(this->WindowHandle);

  if(it==vtkWindowHandleToDeviceObjectConnection.end())
    {
    vtkErrorMacro(<< "No matching vtkTDxWinDevice object for window hwnd=" << this->WindowHandle);
    }
  else
    {
    vtkWindowHandleToDeviceObjectConnection.erase(it);
    }

  if(vtkWindowHandleToDeviceObjectConnection.empty())
    {
      // Release the sensor and keyboard interfaces
      vtkTDxWinDevicePrivate *o=this->Private;
      if(o->Sensor!=0)
        {
          o->Sensor->get_Device(reinterpret_cast<IDispatch**>(&d));
          o->Sensor.Release();
        }

      if(o->Keyboard!=0)
        {
          o->Keyboard.Release();
        }

      if(d!=0)
        {
          // Disconnect it from the driver
          d->Disconnect();
          d.Release();
        }
    }

  this->Initialized=false;

  assert("post: restored" && !this->GetInitialized());
}

// ----------------------------------------------------------------------------
void vtkTDxWinDevice::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}

// ----------------------------------------------------------------------------
void vtkTDxWinDevice::ProcessEvent(void)
{
  vtkTDxWinDevicePrivate *o=this->Private;
  if(o->Keyboard!=0)
    {
    // Check if any change to the keyboard state
    try
      {
      long nKeys;
      nKeys = o->Keyboard->Keys;
      long i;
      for (i=1; i<=nKeys; i++)
        {
        __int64 mask = (__int64)1<<(i-1);
        VARIANT_BOOL isPressed;
        isPressed = o->Keyboard->IsKeyDown(i);
        if (isPressed == VARIANT_TRUE)
          {
          if (!(o->KeyStates & mask))
            {
            o->KeyStates |= mask;
            int buttonInfo=static_cast<int>(i);
            vtkDebugMacro(<<"button press event:"<< buttonInfo);
            o->Interactor->InvokeEvent(vtkCommand::TDxButtonPressEvent,
                                       &buttonInfo);
            }
          }
        else
          {
          o->KeyStates &= ~mask;
          }
        }
      // Test the special keys
      for (i=30; i<=31; i++)
        {
        __int64 mask = (__int64)1<<(i-1);
        VARIANT_BOOL isPressed;
        isPressed = o->Keyboard->IsKeyDown(i);
        if (isPressed == VARIANT_TRUE)
          {
          if (!(o->KeyStates & mask))
            {
            o->KeyStates |= mask;
            int buttonInfo=static_cast<int>(i);
            vtkDebugMacro(<<"button press event (special):"<< buttonInfo);
            o->Interactor->InvokeEvent(vtkCommand::TDxButtonPressEvent,
                                       &buttonInfo);
            }
          }
        else
          {
          o->KeyStates &= ~mask;
          }
        }
      }
    catch (...)
      {
      // Some sort of exception handling
      }
    }
  if(o->Sensor!=0)
    {
    try
      {
      CComPtr<IAngleAxis> r=o->Sensor->Rotation;
      CComPtr<IVector3D> t=o->Sensor->Translation;

      // On Windows, The angle/axis object is
      // the instant rotation with the vector of rotation+one angle.
      // which is different from the Mac and Unix API...

      // Check if the cap is still displaced
      if(r->Angle > 0. || t->Length > 0.)
        {
        double timeFactor=1.0;
        DWORD currentTime=::GetTickCount();
        if(o->LastTimeStamp!=0)
          {
          timeFactor=static_cast<double>(currentTime-o->LastTimeStamp)
            /o->Sensor->Period;
          }
        o->LastTimeStamp=currentTime;

        vtkTDxMotionEventInfo motionInfo;
        motionInfo.X=t->X;
        motionInfo.Y=t->Y;
        motionInfo.Z=t->Z;
        motionInfo.Angle=r->Angle;
        motionInfo.AxisX=r->X;
        motionInfo.AxisY=r->Y;
        motionInfo.AxisZ=r->Z;
        o->Interactor->InvokeEvent(vtkCommand::TDxMotionEvent,
                                   &motionInfo);
        }
      else
        {
        o->LastTimeStamp=0;
        }
      r.Release();
      t.Release();
      }
    catch (...)
      {
      // Some sort of exception handling
      }
    }
}

// ----------------------------------------------------------------------------
// The timer callback is used to poll the 3d input device for change of
// keystates and the cap displacement values.
VOID CALLBACK vtkTDxWinDeviceTimerProc(HWND hwnd,
                                       UINT vtkNotUsed(uMsg),
                                       UINT_PTR vtkNotUsed(idEvent),
                                       DWORD vtkNotUsed(dwTime))
{
  std::map<HWND,vtkTDxWinDevice *,vtkLessThanWindowHandle>::iterator it=vtkWindowHandleToDeviceObject.find(hwnd);

  if(it==vtkWindowHandleToDeviceObject.end())
    {
    //vtkGenericWarningMacro(<< "No matching vtkTDxWinDevice object for window hwnd=" << hwnd);
    return;
    }
  vtkTDxWinDevice *device=(*it).second;
  device->ProcessEvent();
}