Skip to content

Commit

Permalink
Fix windows bug
Browse files Browse the repository at this point in the history
Update tests to new rlgym
  • Loading branch information
VirxEC committed May 20, 2024
1 parent 765b3a3 commit 79e227d
Show file tree
Hide file tree
Showing 6 changed files with 62 additions and 42 deletions.
14 changes: 7 additions & 7 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "rlviser-py"
version = "0.6.7"
version = "0.6.8"
edition = "2021"
description = "Python implementation that manages a UDP connection to RLViser"
license = "MIT"
Expand Down
27 changes: 15 additions & 12 deletions gym_renderer.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Dict
from typing import Any

import rlviser_py as rlviser
import RocketSim as rsim
Expand All @@ -8,29 +8,36 @@


class RLViserRenderer(Renderer[GameState]):

def __init__(self, tick_rate=120/8):
def __init__(self, tick_rate=120 / 8):
rlviser.set_boost_pad_locations(BOOST_LOCATIONS)
self.tick_rate = tick_rate
self.packet_id = 0

def render(self, state: GameState, shared_info: Dict[str, Any]) -> Any:
def render(self, state: GameState, shared_info: dict[str, Any]) -> Any:
boost_pad_states = [bool(timer == 0) for timer in state.boost_pad_timers]

ball = rsim.BallState()
ball.pos = rsim.Vec(*state.ball.position)
ball.vel = rsim.Vec(*state.ball.linear_velocity)
ball.ang_vel = rsim.Vec(*state.ball.angular_velocity)
# ball.rot_mat = rsim.RotMat(*state.ball.rotation_mtx.transpose().flatten())
ball.rot_mat = rsim.RotMat(*state.ball.rotation_mtx.transpose().flatten())

car_data = []
for idx, car in enumerate(state.cars.values()):
car_state = self._get_car_state(car)
car_data.append((idx + 1, car.team_num, rsim.CarConfig(car.hitbox_type), car_state))
car_data.append(
(idx + 1, car.team_num, rsim.CarConfig(car.hitbox_type), car_state)
)

self.packet_id += 1
rlviser.render(tick_count=self.packet_id, tick_rate=self.tick_rate, game_mode=rsim.GameMode.SOCCAR,
boost_pad_states=boost_pad_states, ball=ball, cars=car_data)
rlviser.render(
tick_count=self.packet_id,
tick_rate=self.tick_rate,
game_mode=rsim.GameMode.SOCCAR,
boost_pad_states=boost_pad_states,
ball=ball,
cars=car_data,
)

def close(self):
rlviser.quit()
Expand All @@ -46,7 +53,6 @@ def _get_car_state(self, car: Car):
car_state.demo_respawn_timer = car.demo_respawn_timer
car_state.is_on_ground = car.on_ground
car_state.supersonic_time = car.supersonic_time
# print(car.boost_amount)
car_state.boost = car.boost_amount * 100
car_state.time_spent_boosting = car.boost_active_time
car_state.handbrake_val = car.handbrake
Expand All @@ -66,7 +72,4 @@ def _get_car_state(self, car: Car):
car_state.auto_flip_timer = car.autoflip_timer
car_state.auto_flip_torque_scale = car.autoflip_direction

if car.bump_victim_id is not None:
car_state.car_contact_id = car.bump_victim_id

return car_state
24 changes: 11 additions & 13 deletions pygymtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,15 @@
state_mutator=MutatorSequence(
FixedTeamSizeMutator(blue_size=2, orange_size=2), KickoffMutator()
),
obs_builder=DefaultObs(zero_padding=None),
action_parser=RepeatAction(LookupTableAction(), repeats=1),
obs_builder=DefaultObs(zero_padding=2),
action_parser=RepeatAction(LookupTableAction()),
reward_fn=CombinedReward((GoalReward(), 10.0), (TouchReward(), 0.1)),
termination_cond=GoalCondition(),
truncation_cond=AnyCondition(
TimeoutCondition(timeout=300.0), NoTouchTimeoutCondition(timeout=30.0)
),
transition_engine=RocketSimEngine(),
renderer=RLViserRenderer(120),
renderer=RLViserRenderer(),
)

# simulate 2 episodes
Expand All @@ -48,17 +48,15 @@
t0 = time.time()
while True:
actions = {}
for agent_id, action_space in env.action_spaces.items():
# agent.act(obs) | Your agent should go here
actions[agent_id] = np.random.randint(action_space, size=(1,))
for agent_id, (type, action_spaces) in env.action_spaces.items():
actions[agent_id] = np.random.randint(action_spaces, size=(1,))

for _ in range(8):
obs_dict, reward_dict, terminated_dict, truncated_dict = env.step(
actions
)
env.render()
time.sleep(max(0, t0 + steps / (120 * game_speed) - time.time()))
steps += 1
obs_dict, reward_dict, terminated_dict, truncated_dict = env.step(
actions
)
env.render()
time.sleep(15 / 120 / game_speed)
steps += 1

for agent_id, reward in reward_dict.items():
ep_reward[agent_id] += reward
Expand Down
21 changes: 13 additions & 8 deletions rlviser_py.pyi
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
from typing import Sequence, Optional, Tuple
from typing import Sequence, Optional

from RocketSim import BallState, CarState, GameMode
from RocketSim import BallState, CarState, GameMode, CarConfig

type TVec3 = Tuple[float, float, float]
type TVec3 = tuple[float, float, float]
"""
The items are (X, Y, Z) respectively
"""
type TRotmat = Tuple[TVec3, TVec3, TVec3]
type TRotmat = tuple[TVec3, TVec3, TVec3]
"""
The items are (forward, right, up) respectively
"""
type TBall = Tuple[TVec3, TRotmat, TVec3, TVec3]
type TBall = tuple[TVec3, TRotmat, TVec3, TVec3]
"""
The items are (location, rotation, velocity, angular velocity) respectively
"""
type TCar = Tuple[int, TVec3, TRotmat, TVec3, TVec3, float, bool, bool, bool, float]
type TCar = tuple[int, TVec3, TRotmat, TVec3, TVec3, float, bool, bool, bool, float]
"""
The items are (car_id, location, rotation, velocity, angular velocity, boost, has jumped, has double jumped, has flipped, demo respawn timer) respectively
"""

def set_boost_pad_locations(locations: Sequence[TVec3]) -> ...:
pass

def get_state_set() -> Optional[Tuple[Sequence[float], TBall, Sequence[TCar]]]:
def get_state_set() -> Optional[tuple[Sequence[float], TBall, Sequence[TCar]]]:
"""
Sequence[float] - Boost pad states, 0 for full and some positive value for the time in seconds until it respawns
TBall - Ball state
Expand Down Expand Up @@ -61,7 +61,12 @@ def report_game_paused(paused: bool) -> ...:
"""
pass

def render(tick_count: int, tick_rate: float, game_mode: GameMode, boost_pad_states: Sequence[bool], ball: BallState, cars: Sequence[Tuple[int, CarState]]) -> ...:
type CarData = tuple[int, int, CarConfig, CarState]
"""
The items are (car_id, team, car_config, car_state) respectively
"""

def render(tick_count: int, tick_rate: float, game_mode: GameMode, boost_pad_states: Sequence[bool], ball: BallState, cars: Sequence[CarData]) -> ...:
pass

def quit() -> ...:
Expand Down
16 changes: 15 additions & 1 deletion src/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,21 @@ impl SocketHandler {

match packet_type {
UdpPacketTypes::GameState => {
self.socket.peek_from(&mut min_game_state_buf)?;
#[cfg(windows)]
{
while let Err(e) = self.socket.peek_from(&mut min_game_state_buf) {
if let Some(code) = e.raw_os_error() {
if code == 10040 {
break;
}
}
}
}

#[cfg(not(windows))]
{
while self.socket.peek_from(&mut min_game_state_buf).is_err() {}
}

let num_bytes = GameState::get_num_bytes(&min_game_state_buf);
game_state_buffer.resize(num_bytes, 0);
Expand Down

0 comments on commit 79e227d

Please sign in to comment.