-
Notifications
You must be signed in to change notification settings - Fork 1
/
OpenVRTrackersDriver.cpp
446 lines (368 loc) · 13 KB
/
OpenVRTrackersDriver.cpp
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
/*
* Copyright (C) 2021 Fondazione Istituto Italiano di Tecnologia
*
* Licensed under either the GNU Lesser General Public License v3.0 :
* https://www.gnu.org/licenses/lgpl-3.0.html
* or the GNU Lesser General Public License v2.1 :
* https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* at your option.
*/
#include "OpenVRTrackersDriver.h"
#include <openvr.h>
#include <yarp/os/LogStream.h>
#include <algorithm>
#include <iostream>
#include <mutex>
#include <thread>
#include <unordered_map>
// ====================
// DevicesManager::Impl
// ====================
class openvr::DevicesManager::Impl
{
public:
using TrackedDeviceSerialNumber = std::string;
std::unordered_map<TrackedDeviceSerialNumber, TrackedDevice> devices;
vr::IVRSystem* vr = nullptr;
TrackingUniverseOrigin origin;
std::thread detector;
mutable std::recursive_mutex mutex;
static bool DeviceTypeIsSupported(const TrackedDeviceType type)
{
switch (type) {
case TrackedDeviceType::HMD:
case TrackedDeviceType::Controller:
case TrackedDeviceType::GenericTracker:
return true;
default:
return false;
}
}
static std::string
GetStringProperty(vr::IVRSystem& vr,
const uint32_t index,
const vr::ETrackedDeviceProperty property)
{
// Allocate the buffer using the maximum allowed size
char buffer[vr::k_unMaxPropertyStringSize];
// Get the string property
vr.GetStringTrackedDeviceProperty( //
index,
property,
buffer,
vr::k_unMaxPropertyStringSize);
// Convert to std::string
return std::string(buffer);
};
};
// ==============
// DevicesManager
// ==============
openvr::DevicesManager::DevicesManager(const TrackingUniverseOrigin origin)
: pImpl{std::make_unique<Impl>()}
{
pImpl->origin = origin;
}
openvr::DevicesManager::~DevicesManager()
{
if (this->initialized()) {
// Tear down the runtime
pImpl->vr = nullptr;
vr::VR_Shutdown();
// Wait the processor thread to terminate
pImpl->detector.join();
}
}
bool openvr::DevicesManager::initialized() const
{
const auto lock = std::unique_lock(pImpl->mutex);
return pImpl->vr && !std::string(pImpl->vr->GetRuntimeVersion()).empty();
}
bool openvr::DevicesManager::initialize()
{
if (this->initialized()) {
yError() << "Already initialized";
return false;
}
const auto lock = std::unique_lock(pImpl->mutex);
// =================================
// Detect and track existing devices
// =================================
yDebug() << "Initializing OpenVR DeviceManager";
vr::EVRInitError eError = vr::VRInitError_None;
// Start the application in Background:
//
// The application will not start SteamVR.
// If it is not already running the call with VR_Init will fail
// with VRInitError_Init_NoServerForBackgroundApp.
//
// https://github.com/ValveSoftware/openvr/wiki/API-Documentation#initialization-and-cleanup
//
if (pImpl->vr = vr::VR_Init(&eError, vr::VRApplication_Background);
!pImpl->vr) {
pImpl->vr = nullptr;
yError() << "Failed to initialize VR runtime";
yError() << vr::VR_GetVRInitErrorAsEnglishDescription(eError);
return false;
}
yDebug() << "OpenVR runtime correctly started";
yDebug() << "Scanning for existing devices";
// Get the indices of all the connected devices
const auto connectedDevicesIndices = [&]() -> std::vector<size_t> {
std::vector<size_t> indices = {};
for (size_t i = 0; i < vr::k_unMaxTrackedDeviceCount; ++i) {
if (pImpl->vr->IsTrackedDeviceConnected(i)) {
indices.push_back(i);
}
}
return indices;
}();
yDebug() << "Found" << connectedDevicesIndices.size() << "devices";
// Add all the devices with supported types
for (const auto deviceIndex : connectedDevicesIndices) {
yDebug() << "Inserting device with index" << deviceIndex;
if (!this->addDevice(deviceIndex)) {
yError() << "Failed to add device with index" << deviceIndex;
return false;
}
}
// ==================================
// Execute a thread to process events
// ==================================
// Create the detector thread
auto detectorLoop = [this]() {
yDebug() << "Detector thread: starting";
this->clearEvents();
while (this->initialized()) {
this->processEvents();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
yDebug() << "Detector thread: exiting";
};
// Start the thread waiting initialization
pImpl->detector = std::thread(detectorLoop);
yInfo("VR runtime succesfully initialized");
return true;
}
bool openvr::DevicesManager::addDevice(const size_t index)
{
const auto lock = std::unique_lock(pImpl->mutex);
// Make sure the device is connected
yDebug() << "Checking if device is connected";
if (!pImpl->vr->IsTrackedDeviceConnected(index)) {
yError() << "Failed to add unconnected device with index" << index;
return false;
}
// Get the serial number of the device, used as key in the map where
// devices are stored
std::string serialNumber = Impl::GetStringProperty(
*pImpl->vr, index, vr::Prop_SerialNumber_String);
// Get the type of the device
const TrackedDeviceType type =
TrackedDeviceType(pImpl->vr->GetTrackedDeviceClass(index));
if (!Impl::DeviceTypeIsSupported(type)) {
yInfo() << "The device" << serialNumber << "has unsupported type";
return true;
}
// Create the device
yDebug() << "Adding device" << serialNumber << " (index =" << index
<< ", type =" << int(type) << ")";
const auto device = [&]() {
TrackedDevice device;
device.type = type;
device.index = index;
device.serialNumber = serialNumber;
return device;
}();
// Make sure the device is not already there
if (pImpl->devices.find(device.serialNumber) != pImpl->devices.end()) {
yError() << "Failed to insert device" << device.serialNumber
<< ". It was already inserted previously.";
return false;
}
// Insert the new device
pImpl->devices.insert(std::make_pair(device.serialNumber, device));
yInfo() << "Device " << device.serialNumber << "inserted (index=" << index
<< ")";
return true;
}
bool openvr::DevicesManager::removeDevice(const std::string& serialNumber)
{
const auto lock = std::unique_lock(pImpl->mutex);
const auto& device = pImpl->devices.extract(serialNumber);
if (device.empty()) {
yError() << "Device with serial" << serialNumber << "not found";
return false;
}
yDebug() << "Removing device with serial" << serialNumber;
return true;
}
std::vector<std::string> openvr::DevicesManager::managedDevices() const
{
std::vector<std::string> managedDevicesSerials;
managedDevicesSerials.reserve(pImpl->devices.size());
// Return the serial numbers of the managed devices, stored as
// keys in the unordered map {serial -> TrackedDevice}
for (const auto& [serial, _] : pImpl->devices) {
managedDevicesSerials.push_back(serial);
}
return managedDevicesSerials;
}
openvr::TrackedDeviceType
openvr::DevicesManager::type(const std::string& serialNumber) const
{
if (!this->initialized()) {
yError() << "Failed to read data from the runtime, the manager is "
<< "not initialized";
return TrackedDeviceType::Invalid;
}
const auto lock = std::unique_lock(pImpl->mutex);
// Make sure the device is tracked
if (pImpl->devices.find(serialNumber) == pImpl->devices.end()) {
yError();
return TrackedDeviceType::Invalid;
}
return pImpl->devices[serialNumber].type;
}
std::optional<openvr::Pose>
openvr::DevicesManager::pose(const std::string& serialNumber) const
{
if (!this->initialized()) {
yError() << "Failed to read data from the runtime, the manager is "
<< "not initialized";
return std::nullopt;
}
const auto lock = std::unique_lock(pImpl->mutex);
// Make sure the device is tracked
if (pImpl->devices.find(serialNumber) == pImpl->devices.end()) {
yError();
return std::nullopt;
}
// Make sure the device is connected
if (!pImpl->vr->IsTrackedDeviceConnected(
pImpl->devices[serialNumber].index)) {
yError();
return std::nullopt;
}
vr::TrackedDevicePose_t pose;
vr::VRControllerState_t state;
// Get the device pose
pImpl->vr->GetControllerStateWithPose(
vr::ETrackingUniverseOrigin(pImpl->origin),
pImpl->devices[serialNumber].index,
&state,
sizeof(state),
&pose);
// Check whether the whole received state is valid
if (pose.eTrackingResult
!= vr::ETrackingResult::TrackingResult_Running_OK) {
yError() << "The state of the output of device" << serialNumber
<< "is not ok";
return std::nullopt;
}
// Check pose validity
if (!pose.bPoseIsValid) {
yWarning() << "The pose of device" << serialNumber << "is not valid";
return std::nullopt;
}
// Build and return the pose
return [&pose]() -> const Pose {
Pose out;
out.position = {
pose.mDeviceToAbsoluteTracking.m[0][3],
pose.mDeviceToAbsoluteTracking.m[1][3],
pose.mDeviceToAbsoluteTracking.m[2][3],
};
out.rotationRowMajor = {
pose.mDeviceToAbsoluteTracking.m[0][0],
pose.mDeviceToAbsoluteTracking.m[0][1],
pose.mDeviceToAbsoluteTracking.m[0][2],
pose.mDeviceToAbsoluteTracking.m[1][0],
pose.mDeviceToAbsoluteTracking.m[1][1],
pose.mDeviceToAbsoluteTracking.m[1][2],
pose.mDeviceToAbsoluteTracking.m[2][0],
pose.mDeviceToAbsoluteTracking.m[2][1],
pose.mDeviceToAbsoluteTracking.m[2][2],
};
return out;
}();
}
bool openvr::DevicesManager::resetSeatedPosition()
{
if (!this->initialized()) {
yError() << "Failed to read data from the runtime, the manager is "
<< "not initialized";
return false;
}
const auto lock = std::unique_lock(pImpl->mutex);
vr::VRChaperone()->ResetZeroPose(vr::ETrackingUniverseOrigin::TrackingUniverseSeated);
return true;
}
// ===============
// Private methods
// ===============
void openvr::DevicesManager::clearEvents()
{
size_t number = 0;
vr::VREvent_t event;
const auto lock = std::unique_lock(pImpl->mutex);
while (pImpl->vr->PollNextEvent(&event, sizeof(event))) {
number++;
}
yDebug() << "Cleared" << number << "events";
}
void openvr::DevicesManager::processEvents()
{
vr::VREvent_t event;
const auto lock = std::unique_lock(pImpl->mutex);
if (!this->initialized()) {
yError() << "Manager not initialized";
return;
}
while (pImpl->vr->PollNextEvent(&event, sizeof(event))) {
// yDebug() << "Received event:"
// << pImpl->vr->GetEventTypeNameFromEnum(
// vr::EVREventType(event.eventType));
// yDebug() << event.trackedDeviceIndex;
switch (event.eventType) {
case vr::VREvent_TrackedDeviceActivated: {
this->addDevice(event.trackedDeviceIndex);
break;
}
case vr::VREvent_TrackedDeviceDeactivated: {
for (const auto& [sn, device] : pImpl->devices) {
if (device.index == event.trackedDeviceIndex)
this->removeDevice(sn);
}
break;
}
case vr::VREvent_TrackedDeviceUpdated:
case vr::VREvent_TrackedDeviceRoleChanged:
case vr::VREvent_TrackedDeviceUserInteractionStarted:
case vr::VREvent_TrackedDeviceUserInteractionEnded:
break;
case vr::VREvent_Quit: {
// Notify we need to do some work before quitting
pImpl->vr->AcknowledgeQuit_Exiting();
// Remove all the tracked devices
for (const auto& serial : this->managedDevices()) {
if (!this->removeDevice(serial)) {
yWarning()
<< "Failed to remove device with serial" << serial;
}
}
// Shutdown the runtime
pImpl->vr = nullptr;
vr::VR_Shutdown();
break;
}
default:
break;
}
// Break early when attempting to process events after
// the Quit event has been received
if (!pImpl->vr) {
break;
}
}
}