forked from takana-v/quest_steamvr_fbt_tool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquest_steamvr_fbt_tool.py
254 lines (223 loc) · 7.69 KB
/
quest_steamvr_fbt_tool.py
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
import argparse
import configparser
import json
import logging
import threading
import traceback
from math import asin, atan
from typing import List, Tuple, Optional
import openvr
import wx
import wx.adv
from pythonosc import udp_client
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(levelname)s:%(name)s - %(message)s")
file_handler = logging.FileHandler("qsft_log.txt", encoding="utf-8")
file_handler.setFormatter(formatter)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(stream_handler)
thread_terminate = False
def error_handling():
logger.critical(traceback.format_exc())
wx.MessageBox("Error occured:\n"+traceback.format_exc(), "Quest SteamVR FBT Tool", wx.ICON_ERROR)
global thread_terminate
thread_terminate = True
wx.Exit()
def get_all_device_serial() -> List[str]:
ret = []
i = 0
while True:
serial = openvr.IVRSystem().getStringTrackedDeviceProperty(i, openvr.Prop_SerialNumber_String)
if serial == "":
return ret
ret.append(serial)
i += 1
def get_device_index(device_name: str, ignore: bool) -> int:
i = 0
while True:
serial_num = openvr.IVRSystem().getStringTrackedDeviceProperty(i, openvr.Prop_SerialNumber_String)
if serial_num == device_name:
return i
if serial_num == "":
if ignore:
return None
raise RuntimeError("指定されたデバイスが見つかりませんでした。")
i += 1
def get_position(matrix: List[List[float]]) -> Tuple[float, float, float]:
pos_x = matrix[0][3]
pos_y = matrix[1][3]
pos_z = matrix[2][3]
return pos_x, pos_y, pos_z
def get_euler_angle(matrix: List[List[float]]) -> Tuple[float, float, float]:
rot_y = asin(matrix[0][2])
if rot_y != 0:
rot_x = atan(-matrix[1][2]/matrix[2][2])
rot_z = atan(-matrix[0][1]/matrix[0][0])
else:
rot_x = atan(matrix[2][1]/matrix[1][1])
rot_z = 0
return rot_x, rot_y, rot_z
def run_tracker_server(addr: str, port: int, use_device: List[str], ignore_not_found_device: bool, standard_device: Optional[str], delta: float):
try:
client = udp_client.SimpleUDPClient(addr, port)
poses = []
device_indexes = []
for device in use_device:
i = get_device_index(device, ignore_not_found_device)
if i is not None:
device_indexes.append(i)
assert 0 < len(device_indexes) < 9
except Exception:
error_handling()
return
if standard_device is not None:
try:
i = get_device_index(standard_device, False)
poses, _ = openvr.VRCompositor().getLastPoses(poses, None)
pose = poses[i]
y_delta = -1 * [list(l) for l in list(pose.mDeviceToAbsoluteTracking)][1][3] + delta
except Exception:
error_handling()
return
else:
y_delta = 0
while True:
if thread_terminate:
logger.info("Terminate signal received.")
wx.Exit()
return
try:
poses, _ = openvr.VRCompositor().getLastPoses(poses, None)
for i,j in enumerate(device_indexes):
pose = poses[j]
m = [list(l) for l in list(pose.mDeviceToAbsoluteTracking)]
pos_x, pos_y, pos_z = get_position(m)
rot_x, rot_y, rot_z = get_euler_angle(m)
client.send_message(
f"/tracking/trackers/{i+1}/position/x",
[
-pos_x, # マイナスにしないと向きが逆になる
]
)
client.send_message(
f"/tracking/trackers/{i+1}/position/y",
[
pos_y + y_delta,
]
)
client.send_message(
f"/tracking/trackers/{i+1}/position/z",
[
pos_z,
]
)
client.send_message(
f"/tracking/trackers/{i+1}/rotation/x",
[
rot_x,
]
)
client.send_message(
f"/tracking/trackers/{i+1}/rotation/y",
[
rot_y,
]
)
client.send_message(
f"/tracking/trackers/{i+1}/rotation/z",
[
rot_z,
]
)
except Exception:
error_handling()
return
def parse_arg_and_config():
conf = configparser.ConfigParser()
conf.read_dict(
{
"Connection": {
"addr": "127.0.0.1",
"port": "9000"
},
"Devices": {
"use_device": "[]",
"ignore_not_found_device": "False",
"delta": "0.05"
},
"Log": {
"level": "info"
}
}
)
conf.read("./qsft_config.ini", "UTF-8")
addr = conf["Connection"].get("addr")
port = conf["Connection"].getint("port")
use_device = json.loads(conf["Devices"].get("use_device"))
ignore_not_found_device = conf["Devices"].getboolean("ignore_not_found_device")
standard_device = conf["Devices"].get("standard_device")
delta = conf["Devices"].getfloat("delta")
debug = conf["Log"].getboolean("debug")
parser = argparse.ArgumentParser()
parser.add_argument("--addr", default=addr, type=str)
parser.add_argument("--port", default=port, type=int)
parser.add_argument("--use_device", default=use_device, action="append", type=str)
parser.add_argument("--ignore_not_found_device", action="store_true")
parser.add_argument("--standard_device", default=standard_device, type=str)
parser.add_argument("--delta", default=delta, type=float)
parser.add_argument("--debug", action="store_true")
args = parser.parse_args()
if args.debug or debug:
logger.setLevel(logging.DEBUG)
return (
args.addr,
args.port,
args.use_device,
args.ignore_not_found_device or ignore_not_found_device,
args.standard_device,
args.delta,
)
class TaskBar(wx.adv.TaskBarIcon):
def __init__(self):
wx.adv.TaskBarIcon.__init__(self)
icon = wx.Icon("qsft.png", wx.BITMAP_TYPE_ANY)
self.SetIcon(icon, "Quest SteamVR FBT Tool")
self.Bind(wx.adv.EVT_TASKBAR_LEFT_UP, self.on_leftclick)
def on_leftclick(self, _):
pass
def CreatePopupMenu(self):
menu = wx.Menu()
menu.Append(1, "Exit")
self.Bind(wx.EVT_MENU, self.on_click_menu)
return menu
def on_click_menu(self, event):
if event.GetId() == 1:
logger.debug("Exit called.")
global thread_terminate
thread_terminate = True
logger.debug("Joining thread...")
thread.join()
logger.debug("Thread terminate completed.")
self.Destroy()
wx.Exit()
try:
openvr.init(openvr.VRApplication_Overlay)
except Exception:
error_handling()
if __name__ == "__main__":
logger.info(f"Devices: "+ ", ".join(get_all_device_serial()))
thread_terminate = False
try:
thread = threading.Thread(
target=run_tracker_server,
args=parse_arg_and_config(),
)
except Exception:
error_handling()
thread.start()
app = wx.App()
TaskBar()
app.MainLoop()