diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index a0ff582e68..a7a63658ed 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -11,7 +11,6 @@ "DISPLAY": "${localEnv:DISPLAY}", "PYTHONPATH": "${containerWorkspaceFolder}", "TERM": "xterm-256color", - "CARLA_HOST": "host.docker.internal", "force_color_prompt": "1" }, "runArgs": [ diff --git a/README.md b/README.md index 7d051ada14..d85d1e5676 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ All openpilot services can run as usual on a PC without requiring special hardwa With openpilot's tools, you can plot logs, replay drives, and watch the full-res camera streams. See [the tools README](tools/README.md) for more information. -You can also run openpilot in simulation [with the CARLA simulator](tools/sim/README.md). This allows openpilot to drive around a virtual car on your Ubuntu machine. The whole setup should only take a few minutes but does require a decent GPU. +You can also run openpilot in simulation [with the MetaDrive simulator](tools/sim/README.md). This allows openpilot to drive around a virtual car on your Ubuntu machine. The whole setup should only take a few minutes but does require a decent GPU. A PC running openpilot can also control your vehicle if it is connected to a [webcam](https://github.com/commaai/openpilot/tree/master/tools/webcam), a [black panda](https://comma.ai/shop/products/panda), and a [harness](https://comma.ai/shop/products/car-harness). diff --git a/poetry.lock b/poetry.lock index da14fcc1eb..c77d7e939b 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:e7e3be3454e2f4a74667fce67eda6068e5296f9dad824fc2ea8c21566dc77b29 -size 438272 +oid sha256:f50587d07fa2c3b8740ae7c7983bc66929baae1470cc2ce486351e4496f6d14b +size 435724 diff --git a/pyproject.toml b/pyproject.toml index c6a13c4b86..58c506e378 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -168,12 +168,6 @@ types-tabulate = "*" # this is only pinned since 5.15.11 is broken pyqt5 = { version = "==5.15.2", markers = "platform_machine == 'x86_64'" } # no aarch64 wheels for macOS/linux -[tool.poetry.group.carla] -optional = true - -[tool.poetry.group.carla.dependencies] -carla = { url = "https://github.com/commaai/carla/releases/download/3.11.4/carla-0.9.14-cp311-cp311-linux_x86_64.whl", platform = "linux", markers = "platform_machine == 'x86_64'" } - [build-system] requires = ["poetry-core"] build-backend = "poetry.core.masonry.api" diff --git a/tools/sim/README.md b/tools/sim/README.md index 0892e77736..72727f765d 100644 --- a/tools/sim/README.md +++ b/tools/sim/README.md @@ -1,7 +1,7 @@ openpilot in simulator ===================== -openpilot implements a [bridge](run_bridge.py) that allows it to run in the [MetaDrive simulator](https://github.com/metadriverse/metadrive) or [CARLA simulator](https://carla.org/). +openpilot implements a [bridge](run_bridge.py) that allows it to run in the [MetaDrive simulator](https://github.com/metadriverse/metadrive). ## Launching openpilot First, start openpilot. @@ -13,8 +13,7 @@ First, start openpilot. ## Bridge usage ``` $ ./run_bridge.py -h -usage: run_bridge.py [-h] [--joystick] [--high_quality] [--dual_camera] [--simulator SIMULATOR] [--town TOWN] [--spawn_point NUM_SELECTED_SPAWN_POINT] [--host HOST] [--port PORT] - +usage: run_bridge.py [-h] [--joystick] [--high_quality] [--dual_camera] [--simulator SIMULATOR] Bridge between the simulator and openpilot. options: @@ -23,10 +22,6 @@ options: --high_quality --dual_camera --simulator SIMULATOR - --town TOWN - --spawn_point NUM_SELECTED_SPAWN_POINT - --host HOST - --port PORT ``` #### Bridge Controls: @@ -53,32 +48,4 @@ options: Start bridge processes located in tools/sim: ``` bash ./run_bridge.py --simulator metadrive -``` - -## Carla - -CARLA is also partially supported, though the performance is not great. It needs to be manually installed with: - -```bash -poetry install --with=carla -``` - -openpilot doesn't have any extreme hardware requirements, however CARLA requires an NVIDIA graphics card and is very resource-intensive and may not run smoothly on your system. -For this case, we have the simulator in low quality by default. - -You can also check out the [CARLA python documentation](https://carla.readthedocs.io/en/latest/python_api/) to find more parameters to tune that might increase performance on your system. - -### Launching Carla -Start Carla simulator and bridge processes located in tools/sim: -``` bash -# Terminal 1 -./start_carla.sh - -# Terminal 2 -./run_bridge.py --simulator carla -``` - -## Further Reading - -The following resources contain more details and troubleshooting tips. -* [CARLA on the openpilot wiki](https://github.com/commaai/openpilot/wiki/CARLA) +``` \ No newline at end of file diff --git a/tools/sim/bridge/carla/carla_bridge.py b/tools/sim/bridge/carla/carla_bridge.py deleted file mode 100644 index fe7b34802f..0000000000 --- a/tools/sim/bridge/carla/carla_bridge.py +++ /dev/null @@ -1,22 +0,0 @@ -from openpilot.tools.sim.bridge.common import SimulatorBridge -from openpilot.tools.sim.bridge.carla.carla_world import CarlaWorld - - -class CarlaBridge(SimulatorBridge): - TICKS_PER_FRAME = 5 - - def __init__(self, arguments): - super().__init__(arguments) - self.host = arguments.host - self.port = arguments.port - self.town = arguments.town - self.num_selected_spawn_point = arguments.num_selected_spawn_point - - def spawn_world(self): - import carla - - client = carla.Client(self.host, self.port) - client.set_timeout(5) - - return CarlaWorld(client, high_quality=self.high_quality, dual_camera=self.dual_camera, - num_selected_spawn_point=self.num_selected_spawn_point, town=self.town) diff --git a/tools/sim/bridge/carla/carla_world.py b/tools/sim/bridge/carla/carla_world.py deleted file mode 100644 index 14b300ed7b..0000000000 --- a/tools/sim/bridge/carla/carla_world.py +++ /dev/null @@ -1,145 +0,0 @@ -import numpy as np - -from openpilot.common.params import Params -from openpilot.tools.sim.lib.common import SimulatorState, vec3 -from openpilot.tools.sim.bridge.common import World -from openpilot.tools.sim.lib.camerad import W, H - - -class CarlaWorld(World): - def __init__(self, client, high_quality, dual_camera, num_selected_spawn_point, town): - super().__init__(dual_camera) - import carla - - low_quality_layers = carla.MapLayer(carla.MapLayer.Ground | carla.MapLayer.Walls | carla.MapLayer.Decals) - - layers = carla.MapLayer.All if high_quality else low_quality_layers - - world = client.load_world(town, map_layers=layers) - - settings = world.get_settings() - settings.fixed_delta_seconds = 0.01 - world.apply_settings(settings) - - world.set_weather(carla.WeatherParameters.ClearSunset) - - self.world = world - world_map = world.get_map() - - blueprint_library = world.get_blueprint_library() - - vehicle_bp = blueprint_library.filter('vehicle.tesla.*')[1] - vehicle_bp.set_attribute('role_name', 'hero') - spawn_points = world_map.get_spawn_points() - assert len(spawn_points) > num_selected_spawn_point, \ - f'''No spawn point {num_selected_spawn_point}, try a value between 0 and {len(spawn_points)} for this town.''' - self.spawn_point = spawn_points[num_selected_spawn_point] - self.vehicle = world.spawn_actor(vehicle_bp, self.spawn_point) - - physics_control = self.vehicle.get_physics_control() - physics_control.mass = 2326 - physics_control.torque_curve = [[20.0, 500.0], [5000.0, 500.0]] - physics_control.gear_switch_time = 0.0 - self.vehicle.apply_physics_control(physics_control) - - self.vc: carla.VehicleControl = carla.VehicleControl(throttle=0, steer=0, brake=0, reverse=False) - self.max_steer_angle: float = self.vehicle.get_physics_control().wheels[0].max_steer_angle - self.params = Params() - - self.steer_ratio = 15 - - self.carla_objects = [] - - transform = carla.Transform(carla.Location(x=0.8, z=1.13)) - - def create_camera(fov, callback): - blueprint = blueprint_library.find('sensor.camera.rgb') - blueprint.set_attribute('image_size_x', str(W)) - blueprint.set_attribute('image_size_y', str(H)) - blueprint.set_attribute('fov', str(fov)) - blueprint.set_attribute('sensor_tick', str(1/20)) - if not high_quality: - blueprint.set_attribute('enable_postprocess_effects', 'False') - camera = world.spawn_actor(blueprint, transform, attach_to=self.vehicle) - camera.listen(callback) - return camera - - self.road_camera = create_camera(fov=40, callback=self.cam_callback_road) - if dual_camera: - self.road_wide_camera = create_camera(fov=120, callback=self.cam_callback_wide_road) # fov bigger than 120 shows unwanted artifacts - else: - self.road_wide_camera = None - - # re-enable IMU - imu_bp = blueprint_library.find('sensor.other.imu') - imu_bp.set_attribute('sensor_tick', '0.01') - self.imu = world.spawn_actor(imu_bp, transform, attach_to=self.vehicle) - - gps_bp = blueprint_library.find('sensor.other.gnss') - self.gps = world.spawn_actor(gps_bp, transform, attach_to=self.vehicle) - self.params.put_bool("UbloxAvailable", True) - - self.carla_objects = [self.imu, self.gps, self.road_camera, self.road_wide_camera, self.vehicle] - - def close(self): - for s in self.carla_objects: - if s is not None: - try: - s.destroy() - except Exception as e: - print("Failed to destroy carla object", e) - - def carla_image_to_rgb(self, image): - rgb = np.frombuffer(image.raw_data, dtype=np.dtype("uint8")) - rgb = np.reshape(rgb, (H, W, 4)) - return np.ascontiguousarray(rgb[:, :, [0, 1, 2]]) - - def cam_callback_road(self, image): - with self.image_lock: - self.road_image = self.carla_image_to_rgb(image) - - def cam_callback_wide_road(self, image): - with self.image_lock: - self.wide_road_image = self.carla_image_to_rgb(image) - - def apply_controls(self, steer_angle, throttle_out, brake_out): - self.vc.throttle = throttle_out - - steer_carla = steer_angle * -1 / (self.max_steer_angle * self.steer_ratio) - steer_carla = np.clip(steer_carla, -1, 1) - - self.vc.steer = steer_carla - self.vc.brake = brake_out - self.vehicle.apply_control(self.vc) - - def read_sensors(self, simulator_state: SimulatorState): - simulator_state.imu.bearing = self.imu.get_transform().rotation.yaw - - simulator_state.imu.accelerometer = vec3( - self.imu.get_acceleration().x, - self.imu.get_acceleration().y, - self.imu.get_acceleration().z - ) - - simulator_state.imu.gyroscope = vec3( - self.imu.get_angular_velocity().x, - self.imu.get_angular_velocity().y, - self.imu.get_angular_velocity().z - ) - - simulator_state.gps.from_xy([self.vehicle.get_location().x, self.vehicle.get_location().y]) - - simulator_state.velocity = self.vehicle.get_velocity() - simulator_state.valid = True - simulator_state.steering_angle = self.vc.steer * self.max_steer_angle - - def read_cameras(self): - pass # cameras are read within a callback for carla - - def tick(self): - self.world.tick() - - def reset(self): - import carla - self.vehicle.set_transform(self.spawn_point) - self.vehicle.set_target_velocity(carla.Vector3D()) diff --git a/tools/sim/lib/simulated_sensors.py b/tools/sim/lib/simulated_sensors.py index faa8c0691b..e85665f903 100644 --- a/tools/sim/lib/simulated_sensors.py +++ b/tools/sim/lib/simulated_sensors.py @@ -44,11 +44,10 @@ class SimulatedSensors: if not simulator_state.valid: return - # transform vel from carla to NED - # north is -Y in CARLA + # transform from vel to NED velNED = [ - -simulator_state.velocity.y, # north/south component of NED is negative when moving south - simulator_state.velocity.x, # positive when moving east, which is x in carla + -simulator_state.velocity.y, + simulator_state.velocity.x, simulator_state.velocity.z, ] diff --git a/tools/sim/run_bridge.py b/tools/sim/run_bridge.py index 99617b181e..5f0f0d5e99 100755 --- a/tools/sim/run_bridge.py +++ b/tools/sim/run_bridge.py @@ -1,12 +1,9 @@ #!/usr/bin/env python import argparse -import os from typing import Any from multiprocessing import Queue -from openpilot.tools.sim.bridge.common import SimulatorBridge -from openpilot.tools.sim.bridge.carla.carla_bridge import CarlaBridge from openpilot.tools.sim.bridge.metadrive.metadrive_bridge import MetaDriveBridge @@ -15,13 +12,6 @@ def parse_args(add_args=None): parser.add_argument('--joystick', action='store_true') parser.add_argument('--high_quality', action='store_true') parser.add_argument('--dual_camera', action='store_true') - parser.add_argument('--simulator', dest='simulator', type=str, default='metadrive') - - # Carla specific - parser.add_argument('--town', type=str, default='Town04_Opt') - parser.add_argument('--spawn_point', dest='num_selected_spawn_point', type=int, default=16) - parser.add_argument('--host', dest='host', type=str, default=os.environ.get("CARLA_HOST", '127.0.0.1')) - parser.add_argument('--port', dest='port', type=int, default=2000) return parser.parse_args(add_args) @@ -29,13 +19,7 @@ if __name__ == "__main__": q: Any = Queue() args = parse_args() - simulator_bridge: SimulatorBridge - if args.simulator == "carla": - simulator_bridge = CarlaBridge(args) - elif args.simulator == "metadrive": - simulator_bridge = MetaDriveBridge(args) - else: - raise AssertionError("simulator type not supported") + simulator_bridge = MetaDriveBridge(args) p = simulator_bridge.run(q) if args.joystick: diff --git a/tools/sim/start_carla.sh b/tools/sim/start_carla.sh deleted file mode 100755 index f14e0efd16..0000000000 --- a/tools/sim/start_carla.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/bin/bash - -# Requires nvidia docker - https://github.com/NVIDIA/nvidia-docker -if ! $(apt list --installed | grep -q nvidia-container-toolkit); then - read -p "Nvidia docker is required. Do you want to install it now? (y/n)"; - if [ "${REPLY}" == "y" ]; then - distribution=$(. /etc/os-release;echo $ID$VERSION_ID) - echo $distribution - curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add - - curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list - sudo apt-get update && sudo apt-get install -y nvidia-docker2 # Also installs docker-ce and nvidia-container-toolkit - sudo systemctl restart docker - else - exit 0 - fi -fi - -docker pull carlasim/carla:0.9.14 - -EXTRA_ARGS="-it" -if [[ "$DETACH" ]]; then - EXTRA_ARGS="-d" -fi - -docker kill carla_sim || true -docker run \ - --name carla_sim \ - --rm \ - --gpus all \ - --net=host \ - -v /tmp/.X11-unix:/tmp/.X11-unix:rw \ - $EXTRA_ARGS \ - carlasim/carla:0.9.14 \ - /bin/bash ./CarlaUE4.sh -opengl -nosound -RenderOffScreen -benchmark -fps=20 -quality-level=Low diff --git a/tools/sim/start_openpilot_docker.sh b/tools/sim/start_openpilot_docker.sh index 54f4995e45..3dce660579 100755 --- a/tools/sim/start_openpilot_docker.sh +++ b/tools/sim/start_openpilot_docker.sh @@ -10,7 +10,7 @@ if ! [[ -z "$MOUNT_OPENPILOT" ]]; then fi if [[ "$CI" ]]; then - CMD="CI=1 ${OPENPILOT_DIR}/tools/sim/tests/test_carla_integration.py" + CMD="CI=1 ${OPENPILOT_DIR}/tools/sim/tests/test_metadrive_integration.py" else # expose X to the container xhost +local:root diff --git a/tools/sim/tests/test_carla_bridge.py b/tools/sim/tests/test_carla_bridge.py deleted file mode 100755 index 3a654c993a..0000000000 --- a/tools/sim/tests/test_carla_bridge.py +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env python3 -import subprocess -import time -import unittest -from subprocess import Popen - -from openpilot.selfdrive.manager.helpers import unblock_stdout -from openpilot.tools.sim.run_bridge import parse_args -from openpilot.tools.sim.bridge.carla.carla_bridge import CarlaBridge -from openpilot.tools.sim.tests.test_sim_bridge import SIM_DIR, TestSimBridgeBase - -from typing import Optional - -class TestCarlaBridge(TestSimBridgeBase): - """ - Tests need Carla simulator to run - """ - carla_process: Optional[Popen] = None - - def setUp(self): - super().setUp() - - # We want to make sure that carla_sim docker isn't still running. - subprocess.run("docker rm -f carla_sim", shell=True, stderr=subprocess.PIPE, check=False) - self.carla_process = subprocess.Popen("./start_carla.sh", cwd=SIM_DIR) - - # Too many lagging messages in bridge.py can cause a crash. This prevents it. - unblock_stdout() - # Wait 10 seconds to startup carla - time.sleep(10) - - def create_bridge(self): - return CarlaBridge(parse_args([])) - - def tearDown(self): - super().tearDown() - - # Stop carla simulator by removing docker container - subprocess.run("docker rm -f carla_sim", shell=True, stderr=subprocess.PIPE, check=False) - if self.carla_process is not None: - self.carla_process.wait() - - -if __name__ == "__main__": - unittest.main() diff --git a/tools/sim/tests/test_sim_bridge.py b/tools/sim/tests/test_sim_bridge.py index 2654526fa8..2a12ef791a 100644 --- a/tools/sim/tests/test_sim_bridge.py +++ b/tools/sim/tests/test_sim_bridge.py @@ -14,7 +14,7 @@ class TestSimBridgeBase(unittest.TestCase): @classmethod def setUpClass(cls): if cls is TestSimBridgeBase: - raise unittest.SkipTest("Don't run this base class, run test_carla_bridge.py instead") + raise unittest.SkipTest("Don't run this base class, run test_metadrive_bridge.py instead") def setUp(self): self.processes = [] @@ -26,15 +26,15 @@ class TestSimBridgeBase(unittest.TestCase): sm = messaging.SubMaster(['controlsState', 'onroadEvents', 'managerState']) q = Queue() - carla_bridge = self.create_bridge() - p_bridge = carla_bridge.run(q, retries=10) + bridge = self.create_bridge() + p_bridge = bridge.run(q, retries=10) self.processes.append(p_bridge) max_time_per_step = 60 # Wait for bridge to startup start_waiting = time.monotonic() - while not carla_bridge.started and time.monotonic() < start_waiting + max_time_per_step: + while not bridge.started and time.monotonic() < start_waiting + max_time_per_step: time.sleep(0.1) self.assertEqual(p_bridge.exitcode, None, f"Bridge process should be running, but exited with code {p_bridge.exitcode}") diff --git a/tools/sim/tmux_script.sh b/tools/sim/tmux_script.sh deleted file mode 100755 index 2a1e74958a..0000000000 --- a/tools/sim/tmux_script.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash -tmux new -d -s carla-sim -tmux send-keys "./launch_openpilot.sh" ENTER -tmux neww -tmux send-keys "./run_bridge.py $*" ENTER -tmux a -t carla-sim