-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathOpenVRLoader.cs
394 lines (332 loc) · 14.2 KB
/
OpenVRLoader.cs
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
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.XR;
using UnityEngine.Experimental.XR;
using UnityEngine.XR.Management;
using System.IO;
using Valve.VR;
using System.Runtime.CompilerServices;
#if UNITY_INPUT_SYSTEM
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Layouts;
using UnityEngine.InputSystem.XR;
#endif
namespace Unity.XR.OpenVR
{
#if UNITY_INPUT_SYSTEM
static class InputLayoutLoader
{
static InputLayoutLoader()
{
RegisterInputLayouts();
}
public static void RegisterInputLayouts()
{
InputSystem.RegisterLayout<XRHMD>("OpenVRHMD",
matches: new InputDeviceMatcher()
.WithInterface(XRUtilities.InterfaceMatchAnyVersion)
.WithProduct(@"^(OpenVR Headset)|^(Vive Pro)")
);
InputSystem.RegisterLayout<XRController>("OpenVRControllerWMR",
matches: new InputDeviceMatcher()
.WithInterface(XRUtilities.InterfaceMatchAnyVersion)
.WithProduct(@"^(OpenVR Controller\(WindowsMR)")
);
InputSystem.RegisterLayout<XRController>("ViveWand",
matches: new InputDeviceMatcher()
.WithInterface(XRUtilities.InterfaceMatchAnyVersion)
.WithManufacturer("HTC")
.WithProduct(@"^(OpenVR Controller\(((Vive Controller)|(VIVE Controller)))")
);
InputSystem.RegisterLayout<XRController>("OpenVRViveCosmosController",
matches: new InputDeviceMatcher()
.WithInterface(XRUtilities.InterfaceMatchAnyVersion)
.WithManufacturer("HTC")
.WithProduct(@"^(OpenVR Controller\(((VIVE Cosmos Controller)|(Vive Cosmos Controller)|(vive_cosmos_controller)))")
);
InputSystem.RegisterLayout<XRController>("OpenVRControllerIndex",
matches: new InputDeviceMatcher()
.WithInterface(XRUtilities.InterfaceMatchAnyVersion)
.WithManufacturer("Valve")
.WithProduct(@"^(OpenVR Controller\(Knuckles)")
);
InputSystem.RegisterLayout<XRController>("OpenVROculusTouchController",
matches: new InputDeviceMatcher()
.WithInterface(XRUtilities.InterfaceMatchAnyVersion)
.WithManufacturer("Oculus")
.WithProduct(@"^(OpenVR Controller\(Oculus)")
);
InputSystem.RegisterLayout<XRController>("HandedViveTracker",
matches: new InputDeviceMatcher()
.WithInterface(XRUtilities.InterfaceMatchAnyVersion)
.WithManufacturer("HTC")
.WithProduct(@"^(OpenVR Controller\(((Vive Tracker)|(VIVE Tracker)).+ - ((Left)|(Right)))")
);
InputSystem.RegisterLayout<XRController>("ViveTracker",
matches: new InputDeviceMatcher()
.WithInterface(XRUtilities.InterfaceMatchAnyVersion)
.WithManufacturer("HTC")
.WithProduct(@"^(OpenVR Controller\(((Vive Tracker)|(VIVE Tracker)).+\)(?! - Left| - Right))")
);
InputSystem.RegisterLayout<XRController>("ViveTracker",
matches: new InputDeviceMatcher()
.WithInterface(XRUtilities.InterfaceMatchAnyVersion)
.WithManufacturer("HTC")
.WithProduct(@"^(OpenVR Tracked Device\(((Vive Tracker)|(VIVE Tracker)).+\)(?! - Left| - Right))")
);
InputSystem.RegisterLayout<XRController>("LogitechStylus",
matches: new InputDeviceMatcher()
.WithInterface(XRUtilities.InterfaceMatchAnyVersion)
.WithManufacturer("Logitech")
.WithProduct(@"(OpenVR Controller\(.+stylus)")
);
InputSystem.RegisterLayout<TrackedDevice>("ViveLighthouse",
matches: new InputDeviceMatcher()
.WithInterface(XRUtilities.InterfaceMatchAnyVersion)
.WithManufacturer("HTC")
.WithProduct(@"^(OpenVR Tracking Reference\()")
);
InputSystem.RegisterLayout<TrackedDevice>("ValveLighthouse",
matches: new InputDeviceMatcher()
.WithInterface(XRUtilities.InterfaceMatchAnyVersion)
.WithManufacturer("Valve Corporation")
.WithProduct(@"^(OpenVR Tracking Reference\()")
);
}
}
#endif
public class OpenVRLoader : XRLoaderHelper
{
private static List<XRDisplaySubsystemDescriptor> s_DisplaySubsystemDescriptors = new List<XRDisplaySubsystemDescriptor>();
private static List<XRInputSubsystemDescriptor> s_InputSubsystemDescriptors = new List<XRInputSubsystemDescriptor>();
public XRDisplaySubsystem displaySubsystem
{
get
{
return GetLoadedSubsystem<XRDisplaySubsystem>();
}
}
public XRInputSubsystem inputSubsystem
{
get
{
return GetLoadedSubsystem<XRInputSubsystem>();
}
}
public override bool Initialize()
{
#if UNITY_INPUT_SYSTEM
//InputLayoutLoader.RegisterInputLayouts();
#endif
CreateSubsystem<XRDisplaySubsystemDescriptor, XRDisplaySubsystem>(s_DisplaySubsystemDescriptors, "OpenVR Display");
var result = GetInitializationResult();
if (result != EVRInitError.None)
{
DestroySubsystem<XRDisplaySubsystem>();
Debug.LogError("<b>[OpenVR]</b> Could not initialize OpenVR. Error code: " + result.ToString());
return false;
}
CreateSubsystem<XRInputSubsystemDescriptor, XRInputSubsystem>(s_InputSubsystemDescriptors, "OpenVR Input");
OpenVREvents.Initialize();
TickCallbackDelegate callback = TickCallback;
RegisterTickCallback(callback);
callback(0);
return displaySubsystem != null && inputSubsystem != null;
}
private string GetEscapedApplicationName()
{
if (string.IsNullOrEmpty(Application.productName))
return "";
return Application.productName.Replace("\\", "\\\\").Replace("\"", "\\\""); //replace \ with \\ and replace " with \" for json escaping
}
private void WatchForReload()
{
}
private void CleanupReloadWatcher()
{
}
public override bool Start()
{
running = true;
WatchForReload();
StartSubsystem<XRDisplaySubsystem>();
StartSubsystem<XRInputSubsystem>();
SetupFileSystemWatchers();
return true;
}
private void SetupFileSystemWatchers()
{
SetupFileSystemWatcher();
}
private bool running = false;
#if UNITY_METRO || ENABLE_IL2CPP
private FileInfo watcherFile;
private System.Threading.Thread watcherThread;
private void SetupFileSystemWatcher()
{
watcherThread = new System.Threading.Thread(new System.Threading.ThreadStart(ManualFileWatcherLoop));
watcherThread.Start();
}
private void ManualFileWatcherLoop()
{
watcherFile = new System.IO.FileInfo(mirrorViewPath);
long lastLength = -1;
while (running)
{
if (watcherFile.Exists)
{
long currentLength = watcherFile.Length;
if (lastLength != currentLength)
{
OnChanged(null, null);
lastLength = currentLength;
}
}
else
{
lastLength = -1;
}
System.Threading.Thread.Sleep(1000);
}
}
private void DestroyMirrorModeWatcher()
{
if (watcherThread != null)
{
watcherThread.Abort();
watcherThread = null;
}
}
#else
private FileInfo watcherFile;
private System.IO.FileSystemWatcher watcher;
private void SetupFileSystemWatcher()
{
try
{
settings = OpenVRSettings.GetSettings();
// Listen for changes in the mirror mode file
if (watcher == null && running)
{
watcherFile = new System.IO.FileInfo(mirrorViewPath);
watcher = new System.IO.FileSystemWatcher(watcherFile.DirectoryName, watcherFile.Name);
watcher.NotifyFilter = System.IO.NotifyFilters.LastWrite;
watcher.Created += OnChanged;
watcher.Changed += OnChanged;
watcher.EnableRaisingEvents = true;
if (watcherFile.Exists)
OnChanged(null, null);
}
}
catch { }
}
private void DestroyMirrorModeWatcher()
{
if (watcher != null)
{
watcher.Created -= OnChanged;
watcher.Changed -= OnChanged;
watcher.EnableRaisingEvents = false;
watcher.Dispose();
watcher = null;
}
}
#endif
private const string mirrorViewPath = "openvr_mirrorview.cfg";
private OpenVRSettings settings;
private void OnChanged(object source, System.IO.FileSystemEventArgs e)
{
ReadMirrorModeConfig();
}
/// This allows end users to switch mirror view modes at runtime with a file.
/// To use place a file called openvr_mirrorview.cfg in the same directory as the executable (or root of project).
/// The file should be one line with the following key/value:
/// MirrorViewMode=openvr
/// Acceptable values are left, right, none, and openvr. OpenVR mode is in beta but will show overlays and chaperone bounds.
private void ReadMirrorModeConfig()
{
try
{
var lines = System.IO.File.ReadAllLines(mirrorViewPath);
foreach (var line in lines)
{
var split = line.Split('=');
if (split.Length == 2)
{
var key = split[0];
if (key == "MirrorViewMode")
{
var stringMode = split[1];
var mode = OpenVRSettings.MirrorViewModes.None;
if (stringMode.Equals("left", System.StringComparison.CurrentCultureIgnoreCase))
mode = OpenVRSettings.MirrorViewModes.Left;
else if (stringMode.Equals("right", System.StringComparison.CurrentCultureIgnoreCase))
mode = OpenVRSettings.MirrorViewModes.Right;
else if (stringMode.Equals("openvr", System.StringComparison.CurrentCultureIgnoreCase))
mode = OpenVRSettings.MirrorViewModes.OpenVR;
else if (stringMode.Equals("none", System.StringComparison.CurrentCultureIgnoreCase))
mode = OpenVRSettings.MirrorViewModes.None;
else
{
Debug.LogError("<b>[OpenVR]</b> Invalid mode specified in openvr_mirrorview.cfg. Options are: Left, Right, None, and OpenVR.");
}
Debug.Log("<b>[OpenVR]</b> Mirror View Mode changed via file to: " + mode.ToString());
OpenVRSettings.SetMirrorViewMode((ushort)mode); //bypass the local set.
}
}
}
}
catch
{ }
}
private UnityEngine.Events.UnityEvent[] events;
public override bool Stop()
{
running = false;
CleanupTick();
CleanupReloadWatcher();
DestroyMirrorModeWatcher();
StopSubsystem<XRInputSubsystem>();
StopSubsystem<XRDisplaySubsystem>(); //display actually does vrshutdown
return true;
}
public override bool Deinitialize()
{
CleanupTick();
CleanupReloadWatcher();
DestroyMirrorModeWatcher();
DestroySubsystem<XRInputSubsystem>();
DestroySubsystem<XRDisplaySubsystem>();
return true;
}
private static void CleanupTick()
{
RegisterTickCallback(null);
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto )]
struct UserDefinedSettings
{
public ushort stereoRenderingMode;
public ushort initializationType;
public ushort mirrorViewMode;
[MarshalAs(UnmanagedType.LPStr)] public string editorAppKey;
[MarshalAs(UnmanagedType.LPStr)] public string actionManifestPath;
[MarshalAs(UnmanagedType.LPStr)] public string applicationName;
}
[DllImport("XRSDKOpenVR.dll", CharSet = CharSet.Auto)]
private static extern void SetUserDefinedSettings(UserDefinedSettings settings);
[DllImport("XRSDKOpenVR.dll", CharSet = CharSet.Auto)]
static extern EVRInitError GetInitializationResult();
[DllImport("XRSDKOpenVR.dll", CharSet = CharSet.Auto)]
static extern void RegisterTickCallback([MarshalAs(UnmanagedType.FunctionPtr)] TickCallbackDelegate callbackPointer);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate void TickCallbackDelegate(int value);
[AOT.MonoPInvokeCallback(typeof(TickCallbackDelegate))]
public static void TickCallback(int value)
{
OpenVREvents.Update();
}
}
}