-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodels.py
460 lines (395 loc) · 13.8 KB
/
models.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
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
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = ''
import pygame
from dataclasses import dataclass
from enum import Enum
from io import TextIOWrapper
import math
# Base classes
@dataclass
class Vector:
'''Represents a vector in 3D space'''
x: float
y: float
z: float
@staticmethod
def from_json(data: list[float]) -> 'Vector':
'''Creates a vector from a list of 3 floats'''
return Vector(data[0], data[1], data[2])
def rotate(self, angle: float) -> 'Vector':
angle = math.radians(angle)
return Vector(
(math.cos(angle) * self.x - math.sin(angle) * self.z),
self.y,
-(math.sin(angle) * self.x + math.cos(angle) * self.z)
)
def __str__(self) -> str:
return f"<{self.x:.3f}, {self.y:.3f}, {self.z:.3f}>"
def __add__(self, other: 'Vector') -> 'Vector':
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other: 'Vector') -> 'Vector':
return Vector(self.x - other.x, self.y - other.y, self.z - other.z)
def __truediv__(self, other: float) -> 'Vector':
return Vector(self.x / other, self.y / other, self.z / other)
def __pos__(self) -> 'Vector':
return Vector(+self.x, +self.y, +self.z)
def __neg__(self) -> 'Vector':
return Vector(-self.x, -self.y, -self.z)
def __abs__(self) -> float:
return (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5
class Alliance(Enum):
'''Represents the alliance of the robot'''
RED = 0
BLUE = 1
class DriverstationPosition(Enum):
'''Represents the driverstation position'''
LEFT = 0
CENTER = 1
RIGHT = 2
@dataclass
class RobotInfo:
alliance: Alliance
position: DriverstationPosition
robot: str
counter: int
@dataclass
class Element:
'''Represents a game element'''
identifier: int
element_type: int
name: str
global_position: Vector
global_rotation: Vector
local_position: Vector
local_rotation: Vector
velocity: Vector | None
angular_velocity: Vector | None
@staticmethod
def from_json(data: dict[str, any]) -> 'Element | RobotInfo':
'''Creates a game element from a JSON dictionary'''
identifier = None
element_type = None
name = None
global_position = None
global_rotation = None
local_position = None
local_rotation = None
velocity = None
angular_velocity = None
try:
identifier = data['id']
except KeyError:
pass
try:
element_type = data['type']
except KeyError:
pass
try:
name = data['name']
except KeyError:
pass
if name == 'INFO':
alliance = None
position = None
robot = None
counter = None
try:
position = data['Position']
position = position.split(' ')
match(position[0]):
case 'Red': alliance = Alliance.RED
case 'Blue': alliance = Alliance.BLUE
case _: pass
match(position[1]):
case 'Left': position = DriverstationPosition.LEFT
case 'Center': position = DriverstationPosition.CENTER
case 'Right': position = DriverstationPosition.RIGHT
case _: pass
except KeyError:
pass
try:
robot = data['Model']
except KeyError:
pass
try:
counter = int(data['Counter'])
except (KeyError, ValueError):
pass
return RobotInfo(alliance, position, robot, counter)
try:
global_position = Vector.from_json(data['global pos'])
except KeyError:
pass
try:
global_rotation = Vector.from_json(data['global rot'])
global_rotation.x = Util.fix_angle(global_rotation.x)
global_rotation.y = Util.fix_angle(global_rotation.y)
global_rotation.z = Util.fix_angle(global_rotation.z)
except KeyError:
pass
try:
local_position = Vector.from_json(data['local pos'])
except KeyError:
pass
try:
local_rotation = Vector.from_json(data['local rot'])
local_rotation.x = Util.fix_angle(local_rotation.x)
local_rotation.y = Util.fix_angle(local_rotation.y)
local_rotation.z = Util.fix_angle(local_rotation.z)
except KeyError:
pass
try:
velocity = Vector.from_json(data['velocity'])
except KeyError:
pass
try:
angular_velocity = Vector.from_json(data['rot velocity'])
except KeyError:
pass
return Element(identifier, element_type, name,
global_position, global_rotation, local_position, local_rotation,
velocity, angular_velocity)
def __str__(self) -> str:
return f"{self.name} @ {self.global_position}"
class GamePhase(Enum):
'''Represents the current phase of the game'''
READY = 0
AUTO = 1
TELEOP = 2
ENDGAME = 3
FINISHED = 4
@staticmethod
def from_str(string: str) -> 'GamePhase':
'''Returns the GamePhase corresponding to the given string'''
match(string.strip()):
case 'READY': return GamePhase.READY
case 'AUTO': return GamePhase.AUTO
case 'TELEOP': return GamePhase.TELEOP
case 'ENDGAME': return GamePhase.ENDGAME
case 'FINISHED': return GamePhase.FINISHED
case _: raise ValueError(f"{string} is not a valid GamePhase")
@dataclass
class GameState:
'''Represents the current state of the game'''
phase: GamePhase
time_left: float
@staticmethod
def read(file: TextIOWrapper) -> 'GameState':
'''Returns the current state of the game'''
phase = file.readline()
timestamp = file.readline()
phase = GamePhase.from_str(phase)
timestamp = timestamp.split('=')[1].strip()
timestamp = float(timestamp)
return GameState(phase, timestamp)
def __str__(self) -> str:
return f"{self.phase} {self.time_left}"
@dataclass
class GamepadState:
'''Represents the current state of the gamepad'''
a: bool
b: bool
x: bool
y: bool
dpad_down: bool
dpad_up: bool
dpad_left: bool
dpad_right: bool
bumper_right: bool
bumper_left: bool
back: bool
start: bool
right_y: float
right_x: float
left_y: float
left_x: float
trigger_left: float
trigger_right: float
class Gamepad:
'''Represents the gamepad'''
def __init__(self, stick: int = 0):
try:
pygame.init()
pygame.joystick.init()
self.__joystick = pygame.joystick.Joystick(stick)
print(f"Detected '{self.__joystick.get_name()}'")
except pygame.error:
print("No gamepad detected")
self.__joystick = None
def read(self) -> GamepadState:
'''Reads the current state from a joystick'''
if self.__joystick is None:
return GamepadState(
False, False, False, False,
False, False, False, False,
False, False, False, False,
0, 0,
0, 0,
0, 0
)
pygame.event.pump()
dpad = self.__joystick.get_hat(0)
return GamepadState(
a=self.__joystick.get_button(0),
b=self.__joystick.get_button(1),
x=self.__joystick.get_button(2),
y=self.__joystick.get_button(3),
dpad_down=dpad[1] == -1,
dpad_up=dpad[1] == 1,
dpad_left=dpad[0] == -1,
dpad_right=dpad[0] == 1,
bumper_right=self.__joystick.get_button(5),
bumper_left=self.__joystick.get_button(4),
back=self.__joystick.get_button(6),
start=self.__joystick.get_button(7),
right_y=self.__joystick.get_axis(3),
right_x=self.__joystick.get_axis(2),
left_y=self.__joystick.get_axis(1),
left_x=self.__joystick.get_axis(0),
trigger_left=(self.__joystick.get_axis(4) + 1) / 2,
trigger_right=(self.__joystick.get_axis(5) + 1) / 2
)
@dataclass
class ControlOutput:
'''Represents the control outputs to the game'''
a: bool
b: bool
x: bool
y: bool
dpad_down: bool
dpad_up: bool
dpad_left: bool
dpad_right: bool
bumper_l: bool
bumper_r: bool
stop: bool
restart: bool
right_y: float
right_x: float
left_y: float
left_x: float
trigger_l: float
trigger_r: float
precision: float
def write(self) -> None:
'''Writes the current output to the game'''
with open('Controls.txt', 'w', encoding='UTF+8') as file:
file.write(f"a={1 if self.a else 0}\n")
file.write(f"b={1 if self.b else 0}\n")
file.write(f"x={1 if self.x else 0}\n")
file.write(f"y={1 if self.y else 0}\n")
file.write(f"dpad_down={1 if self.dpad_down else 0}\n")
file.write(f"dpad_up={1 if self.dpad_up else 0}\n")
file.write(f"dpad_left={1 if self.dpad_left else 0}\n")
file.write(f"dpad_right={1 if self.dpad_right else 0}\n")
file.write(f"bumper_l={1 if self.bumper_l else 0}\n")
file.write(f"bumper_r={1 if self.bumper_r else 0}\n")
file.write(f"stop={1 if self.stop else 0}\n")
file.write(f"restart={1 if self.restart else 0}\n")
file.write(f"right_y={self.right_y}\n")
file.write(f"right_x={self.right_x}\n")
file.write(f"left_y={self.left_y}\n")
file.write(f"left_x={self.left_x}\n")
file.write(f"trigger_l={self.trigger_l}\n")
file.write(f"trigger_r={self.trigger_r}\n")
file.write(f"precision={self.precision}\n")
# Generic classes
@dataclass
class GameElementState:
'''Represents the current state of the game'''
@staticmethod
def read(file: TextIOWrapper) -> 'GameElementState':
'''Returns the current state of the game'''
return GameElementState()
@dataclass
class RobotState:
'''Represents the current state of a robot'''
@staticmethod
def read(file: TextIOWrapper) -> tuple['RobotState', RobotInfo]:
'''Returns the current state of the robot'''
return RobotState(), RobotInfo(None, None, None, None)
@dataclass
class State:
'''Represents the current state of everything'''
robot: RobotState
elements: GameElementState
game: GameState
gamepad: GamepadState
robot_info: RobotInfo
@staticmethod
def read(game_file: TextIOWrapper, element_file: TextIOWrapper,
robot_file: TextIOWrapper, gamepad: Gamepad) -> 'State':
'''Reads the current state from the files'''
return State(None, None, None, None, None)
@dataclass
class Controls:
'''Represents the current controls for a robot'''
@staticmethod
def from_gamepad_state(gamepad: GamepadState) -> 'Controls':
'''Returns the default controls'''
return Controls()
def write(self) -> None:
'''Default controls for the robot'''
class Command:
'''Represents a command to modify the controls for the robot'''
def __call__(self, state: State, controls: Controls) -> Controls:
'''Executes the command'''
return controls
class AutomationProvider:
'''Abstract class to represent a full automation system'''
def __call__(self,
game_file: TextIOWrapper, element_file: TextIOWrapper,
robot_file: TextIOWrapper, gamepad: Gamepad) -> None:
'''Applies automation to the current game'''
# Utility classes
class Util:
'''Utility class'''
@staticmethod
def fix_angle(angle: float) -> float:
'''Fixes the angle to be between -180 and 180'''
while angle < -180:
angle += 360
while angle > 180:
angle -= 360
return angle
@staticmethod
def nearest_element(position: Vector, elements: list[Element],
min_distance: float = 0, max_y: float = 0) -> Element:
'''Returns the nearest element to the position'''
nearest = None
nearest_distance = float('inf')
for element in elements:
difference = position - element.global_position
distance = math.hypot(difference.x, difference.y, difference.z)
if distance < min_distance:
pass # Element is too close
elif difference.y < max_y:
pass # Element is too high
elif distance < nearest_distance:
nearest = element
nearest_distance = distance
return nearest
@staticmethod
def elements_within(position: Vector, elements: list[Element],
distance: float) -> list[Element]:
'''Returns the elements within the distance'''
result = []
for element in elements:
difference = position - element.global_position
if math.hypot(difference.x, difference.y, difference.z) < distance:
result.append(element)
return result
class Logger:
'''Logger'''
__lines: list[str] = []
@staticmethod
def log(message: str) -> None:
'''Logs a message'''
Logger.__lines.append(message)
@staticmethod
def save(filename: str) -> None:
'''Saves the log to a file'''
with open(filename, 'w', encoding='UTF+8') as file:
for line in Logger.__lines:
file.write(line + '\n')
Logger.__lines = []