11 #include "EngineUtils.h" 20 #include "GameFramework/CharacterMovementComponent.h" 29 #include "Misc/FileHelper.h" 34 #include <carla/Version.h> 84 template <
typename T,
typename Other>
87 return {Array.GetData(), Array.GetData() + Array.Num()};
98 FPimpl(uint16_t RPCPort, uint16_t StreamingPort, uint16_t SecondaryPort)
104 SecondaryServer = std::make_shared<carla::multigpu::Router>(SecondaryPort);
138 # define CARLA_ENSURE_GAME_THREAD() check(IsInGameThread()); 140 # define CARLA_ENSURE_GAME_THREAD() 141 #endif // WITH_EDITOR 143 #define RESPOND_ERROR(str) { \ 144 UE_LOG(LogCarlaServer, Log, TEXT("Responding error: %s"), TEXT(str)); \ 145 return carla::rpc::ResponseError(str); } 147 #define RESPOND_ERROR_FSTRING(fstr) { \ 148 UE_LOG(LogCarlaServer, Log, TEXT("Responding error: %s"), *fstr); \ 149 return carla::rpc::ResponseError(carla::rpc::FromFString(fstr)); } 151 #define REQUIRE_CARLA_EPISODE() \ 152 CARLA_ENSURE_GAME_THREAD(); \ 153 if (Episode == nullptr) { RESPOND_ERROR("episode not ready"); } 156 const FString& FuncName,
157 const FString& ErrorMessage,
158 const FString& ExtraInfo =
"")
160 FString TotalMessage =
"Responding error from function " + FuncName +
": " +
161 ErrorMessage +
". " + ExtraInfo;
162 UE_LOG(LogCarlaServer, Log, TEXT(
"%s"), *TotalMessage);
167 const FString& FuncName,
169 const FString& ExtraInfo =
"")
183 template <
typename FuncT>
188 _server.BindSync(_name, func);
192 _server.BindAsync(_name, func);
206 #define BIND_SYNC(name) auto name = ServerBinder(# name, Server, true) 207 #define BIND_ASYNC(name) auto name = ServerBinder(# name, Server, false) 226 BIND_SYNC(get_traffic_manager_running) << [
this] (uint16_t port) ->
R<std::pair<std::string, uint16_t>>
230 return std::pair<std::string, uint16_t>(it->second, it->first);
232 return std::pair<std::string, uint16_t>(
"",0);
236 BIND_SYNC(add_traffic_manager_running) << [
this] (std::pair<std::string, uint16_t> trafficManagerInfo) ->
R<bool> 238 uint16_t port = trafficManagerInfo.second;
242 std::pair<uint16_t, std::string>(port, trafficManagerInfo.first));
261 return carla::version();
276 BIND_ASYNC(get_available_maps) << [
this]() ->
R<std::vector<std::string>>
279 std::vector<std::string> result;
280 result.reserve(MapNames.Num());
281 for (
const auto &MapName : MapNames)
283 if (MapName.Contains(
"/Sublevels/"))
285 if (MapName.Contains(
"/BaseMap/"))
287 if (MapName.Contains(
"/BaseLargeMap/"))
289 if (MapName.Contains(
"_Tile_"))
292 result.emplace_back(cr::FromFString(MapName));
306 GameInstance->
SetMapLayer(static_cast<int32>(MapLayers));
310 FString Str(TEXT(
"Map '"));
311 Str += cr::ToFString(map_name);
312 Str += TEXT(
"' not found");
347 BIND_SYNC(copy_opendrive_to_file) << [
this](
const std::string &opendrive, cr::OpendriveGenerationParameters Params) ->
R<void> 357 BIND_SYNC(apply_color_texture_to_objects) << [
this](
358 const std::vector<std::string> &actors_name,
368 TArray<AActor*> ActorsToPaint;
369 for(
const std::string& actor_name : actors_name)
374 ActorsToPaint.Add(ActorToPaint);
378 if(!ActorsToPaint.Num())
385 for(
AActor* ActorToPaint : ActorsToPaint)
395 BIND_SYNC(apply_float_color_texture_to_objects) << [
this](
396 const std::vector<std::string> &actors_name,
406 TArray<AActor*> ActorsToPaint;
407 for(
const std::string& actor_name : actors_name)
412 ActorsToPaint.Add(ActorToPaint);
416 if(!ActorsToPaint.Num())
423 for(
AActor* ActorToPaint : ActorsToPaint)
433 BIND_SYNC(get_names_of_all_objects) << [
this]() ->
R<std::vector<std::string>>
442 std::vector<std::string> NamesStd;
443 for (
const FString &Name : NamesFString)
445 NamesStd.emplace_back(cr::FromFString(Name));
464 FString MapDir = FullMapPath.RightChop(FullMapPath.Find(
"Content/", ESearchCase::CaseSensitive) + 8);
467 cr::FromFString(MapDir),
468 MakeVectorFromTArray<cg::Transform>(SpawnPoints)};
477 BIND_SYNC(get_navigation_mesh) << [
this]() ->
R<std::vector<uint8_t>>
482 std::vector<uint8_t> Result(FileContents.Num());
483 memcpy(&Result[0], FileContents.GetData(), FileContents.Num());
487 BIND_SYNC(get_required_files) << [
this](std::string folder =
"") ->
R<std::vector<std::string>>
492 if (folder[folder.size() - 1] !=
'/' && folder[folder.size() - 1] !=
'\\') {
499 const auto folderDir = mapDir +
"/" + folder.c_str();
503 TArray<FString> Files;
504 IFileManager::Get().FindFilesRecursive(Files, *folderDir, *(fileName +
".xodr"),
true,
false,
false);
505 IFileManager::Get().FindFilesRecursive(Files, *folderDir, *(fileName +
".bin"),
true,
false,
false);
508 std::vector<std::string> result;
509 for (
auto File : Files) {
510 File.RemoveFromStart(FPaths::ConvertRelativePathToFull(FPaths::ProjectContentDir()));
511 result.emplace_back(TCHAR_TO_UTF8(*File));
516 BIND_SYNC(request_file) << [
this](std::string name) ->
R<std::vector<uint8_t>>
521 FString path(FPaths::ConvertRelativePathToFull(FPaths::ProjectContentDir()));
522 path.Append(name.c_str());
525 TArray<uint8_t> Content;
526 FFileHelper::LoadFileToArray(Content, *path, 0);
527 std::vector<uint8_t> Result(Content.Num());
528 memcpy(&Result[0], Content.GetData(), Content.Num());
539 BIND_SYNC(set_episode_settings) << [
this](
540 const cr::EpisodeSettings &settings) ->
R<uint64_t> 560 BIND_SYNC(get_actor_definitions) << [
this]() ->
R<std::vector<cr::ActorDefinition>>
577 BIND_SYNC(get_all_level_BBs) << [
this](uint8 QueriedTag) ->
R<std::vector<cg::BoundingBox>>
580 TArray<FBoundingBox> Result;
590 for(
auto&
Box : Result)
595 return MakeVectorFromTArray<cg::BoundingBox>(Result);
598 BIND_SYNC(get_environment_objects) << [
this](uint8 QueriedTag) ->
R<std::vector<cr::EnvironmentObject>>
610 for(
auto& Object : Result)
615 return MakeVectorFromTArray<cr::EnvironmentObject>(Result);
618 BIND_SYNC(enable_environment_objects) << [
this](std::vector<uint64_t> EnvObjectIds,
bool Enable) ->
R<void> 627 TSet<uint64> EnvObjectIdsSet;
628 for(uint64 Id : EnvObjectIds)
630 EnvObjectIdsSet.Emplace(Id);
643 if (Weather ==
nullptr)
647 return Weather->GetCurrentWeather();
650 BIND_SYNC(set_weather_parameters) << [
this](
651 const cr::WeatherParameters &weather) ->
R<void> 655 if (Weather ==
nullptr)
659 Weather->ApplyWeather(weather);
666 const std::vector<FCarlaActor::IdType> &ids) ->
R<std::vector<cr::Actor>>
669 std::vector<cr::Actor> Result;
670 Result.reserve(ids.size());
671 for (
auto &&Id : ids)
683 cr::ActorDescription Description,
690 if (Result.Key != EActorSpawnResultStatus::Success)
692 UE_LOG(LogCarla, Error, TEXT(
"Actor not Spawned"));
705 BIND_SYNC(spawn_actor_with_parent) << [
this](
706 cr::ActorDescription Description,
714 if (Result.Key != EActorSpawnResultStatus::Success)
727 if (!ParentCarlaActor)
729 RESPOND_ERROR(
"unable to attach actor: parent actor not found");
736 #if defined(WITH_ROS2) 738 if (ROS2->IsEnabled())
745 if (Attr.Key ==
"ros_name")
747 const std::string value = std::string(TCHAR_TO_UTF8(*Attr.Value.Value));
748 ROS2->AddActorParentRosName(static_cast<void*>(CarlaActor->
GetActor()), static_cast<void*>(CurrentActor->
GetActor()));
781 UE_LOG(LogCarla, Log, TEXT(
"CarlaServer destroy_actor %d"),
ActorId);
795 APlayerController* PController= UGameplayStatics::GetPlayerController(
Episode->GetWorld(), 0);
798 auto result = PController->ConsoleCommand(UTF8_TO_TCHAR(cmd.c_str()),
true);
800 result.Contains(FString(TEXT(
"Command not recognized"))) ||
801 result.Contains(FString(TEXT(
"Error")))
804 return GEngine->Exec(
Episode->GetWorld(), UTF8_TO_TCHAR(cmd.c_str()));
811 bool ForceInPrimary =
false;
816 ForceInPrimary =
true;
821 if (Desc ==
"" || Desc ==
"sensor.other.collision")
823 ForceInPrimary =
true;
829 UE_LOG(LogCarla, Log, TEXT(
"Sensor %d '%s' created in secondary server"), sensor_id, *Desc);
835 UE_LOG(LogCarla, Log, TEXT(
"Sensor %d '%s' created in primary server"), sensor_id, *Desc);
844 bool ForceInPrimary =
false;
849 ForceInPrimary =
true;
854 if (Desc ==
"" || Desc ==
"sensor.other.collision")
856 ForceInPrimary =
true;
876 bool ForceInPrimary =
false;
881 ForceInPrimary =
true;
886 if (Desc ==
"" || Desc ==
"sensor.other.collision")
888 ForceInPrimary =
true;
908 bool ForceInPrimary =
false;
913 ForceInPrimary =
true;
918 if (Desc ==
"" || Desc ==
"sensor.other.collision")
920 ForceInPrimary =
true;
946 "set_actor_location",
948 " Actor Id: " + FString::FromInt(ActorId));
952 Location, ETeleportType::TeleportPhysics);
956 BIND_SYNC(set_actor_transform) << [
this](
965 "set_actor_transform",
967 " Actor Id: " + FString::FromInt(ActorId));
971 Transform, ETeleportType::TeleportPhysics);
987 " Actor Id: " + FString::FromInt(ActorId));
995 Transform.GetForwardVector(), Speed,
false));
1001 " Actor Id: " + FString::FromInt(ActorId));
1006 BIND_SYNC(set_actor_target_velocity) << [
this](
1015 "set_actor_target_velocity",
1017 " Actor Id: " + FString::FromInt(ActorId));
1024 "set_actor_target_velocity",
1026 " Actor Id: " + FString::FromInt(ActorId));
1031 BIND_SYNC(set_actor_target_angular_velocity) << [
this](
1040 "set_actor_target_angular_velocity",
1042 " Actor Id: " + FString::FromInt(ActorId));
1049 "set_actor_target_angular_velocity",
1051 " Actor Id: " + FString::FromInt(ActorId));
1056 BIND_SYNC(enable_actor_constant_velocity) << [
this](
1065 "enable_actor_constant_velocity",
1067 " Actor Id: " + FString::FromInt(ActorId));
1075 "enable_actor_constant_velocity",
1077 " Actor Id: " + FString::FromInt(ActorId));
1083 BIND_SYNC(disable_actor_constant_velocity) << [
this](
1091 "disable_actor_constant_velocity",
1093 " Actor Id: " + FString::FromInt(ActorId));
1101 "disable_actor_constant_velocity",
1103 " Actor Id: " + FString::FromInt(ActorId));
1118 "add_actor_impulse",
1120 " Actor Id: " + FString::FromInt(ActorId));
1128 "add_actor_impulse",
1130 " Actor Id: " + FString::FromInt(ActorId));
1135 BIND_SYNC(add_actor_impulse_at_location) << [
this](
1145 "add_actor_impulse_at_location",
1147 " Actor Id: " + FString::FromInt(ActorId));
1149 FVector UELocation = location.ToCentimeters().ToFVector();
1161 "add_actor_impulse_at_location",
1163 " Actor Id: " + FString::FromInt(ActorId));
1180 " Actor Id: " + FString::FromInt(ActorId));
1183 CarlaActor->
AddActorForce(vector.ToCentimeters().ToFVector());
1189 " Actor Id: " + FString::FromInt(ActorId));
1194 BIND_SYNC(add_actor_force_at_location) << [
this](
1204 "add_actor_force_at_location",
1206 " Actor Id: " + FString::FromInt(ActorId));
1208 FVector UELocation = location.ToCentimeters().ToFVector();
1220 "add_actor_force_at_location",
1222 " Actor Id: " + FString::FromInt(ActorId));
1227 BIND_SYNC(add_actor_angular_impulse) << [
this](
1236 "add_actor_angular_impulse",
1238 " Actor Id: " + FString::FromInt(ActorId));
1245 "add_actor_angular_impulse",
1247 " Actor Id: " + FString::FromInt(ActorId));
1263 " Actor Id: " + FString::FromInt(ActorId));
1272 " Actor Id: " + FString::FromInt(ActorId));
1277 BIND_SYNC(get_physics_control) << [
this](
1285 "get_physics_control",
1287 " Actor Id: " + FString::FromInt(ActorId));
1295 "get_physics_control",
1297 " Actor Id: " + FString::FromInt(ActorId));
1299 return cr::VehiclePhysicsControl(PhysicsControl);
1302 BIND_SYNC(get_vehicle_light_state) << [
this](
1310 "get_vehicle_light_state",
1312 " Actor Id: " + FString::FromInt(ActorId));
1320 "get_vehicle_light_state",
1322 " Actor Id: " + FString::FromInt(ActorId));
1324 return cr::VehicleLightState(LightState);
1327 BIND_SYNC(apply_physics_control) << [
this](
1336 "apply_physics_control",
1338 " Actor Id: " + FString::FromInt(ActorId));
1345 "apply_physics_control",
1347 " Actor Id: " + FString::FromInt(ActorId));
1352 BIND_SYNC(set_vehicle_light_state) << [
this](
1354 cr::VehicleLightState LightState) ->
R<void> 1361 "set_vehicle_light_state",
1363 " Actor Id: " + FString::FromInt(ActorId));
1370 "set_vehicle_light_state",
1372 " Actor Id: " + FString::FromInt(ActorId));
1387 "open_vehicle_door",
1389 " Actor Id: " + FString::FromInt(ActorId));
1396 "open_vehicle_door",
1398 " Actor Id: " + FString::FromInt(ActorId));
1403 BIND_SYNC(close_vehicle_door) << [
this](
1412 "close_vehicle_door",
1414 " Actor Id: " + FString::FromInt(ActorId));
1421 "close_vehicle_door",
1423 " Actor Id: " + FString::FromInt(ActorId));
1428 BIND_SYNC(set_wheel_steer_direction) << [
this](
1437 "set_wheel_steer_direction",
1439 " Actor Id: " + FString::FromInt(ActorId));
1443 static_cast<EVehicleWheelLocation>(WheelLocation), AngleInDeg);
1447 "set_wheel_steer_direction",
1449 " Actor Id: " + FString::FromInt(ActorId));
1454 BIND_SYNC(get_wheel_steer_angle) << [
this](
1462 "get_wheel_steer_angle",
1464 " Actor Id: " + FString::FromInt(ActorId));
1469 static_cast<EVehicleWheelLocation>(WheelLocation), Angle);
1473 "get_wheel_steer_angle",
1475 " Actor Id: " + FString::FromInt(ActorId));
1480 BIND_SYNC(set_actor_simulate_physics) << [
this](
1489 "set_actor_simulate_physics",
1491 " Actor Id: " + FString::FromInt(ActorId));
1498 "set_actor_simulate_physics",
1500 " Actor Id: " + FString::FromInt(ActorId));
1505 BIND_SYNC(set_actor_collisions) << [
this](
1514 "set_actor_collisions",
1516 " Actor Id: " + FString::FromInt(ActorId));
1523 "set_actor_collisions",
1525 " Actor Id: " + FString::FromInt(ActorId));
1540 " Actor Id: " + FString::FromInt(ActorId));
1549 " Actor Id: " + FString::FromInt(ActorId));
1554 BIND_SYNC(set_actor_enable_gravity) << [
this](
1563 "set_actor_enable_gravity",
1565 " Actor Id: " + FString::FromInt(ActorId));
1572 "set_actor_enable_gravity",
1574 " Actor Id: " + FString::FromInt(ActorId));
1581 BIND_SYNC(apply_control_to_vehicle) << [
this](
1583 cr::VehicleControl Control) ->
R<void> 1590 "apply_control_to_vehicle",
1592 " Actor Id: " + FString::FromInt(ActorId));
1599 "apply_control_to_vehicle",
1601 " Actor Id: " + FString::FromInt(ActorId));
1606 BIND_SYNC(apply_ackermann_control_to_vehicle) << [
this](
1608 cr::VehicleAckermannControl Control) ->
R<void> 1615 "apply_ackermann_control_to_vehicle",
1617 " Actor Id: " + FString::FromInt(ActorId));
1624 "apply_ackermann_control_to_vehicle",
1626 " Actor Id: " + FString::FromInt(ActorId));
1631 BIND_SYNC(get_ackermann_controller_settings) << [
this](
1639 "get_ackermann_controller_settings",
1641 " Actor Id: " + FString::FromInt(ActorId));
1649 "get_ackermann_controller_settings",
1651 " Actor Id: " + FString::FromInt(ActorId));
1653 return cr::AckermannControllerSettings(Settings);
1656 BIND_SYNC(apply_ackermann_controller_settings) << [
this](
1658 cr::AckermannControllerSettings AckermannSettings) ->
R<void> 1665 "apply_ackermann_controller_settings",
1667 " Actor Id: " + FString::FromInt(ActorId));
1674 "apply_ackermann_controller_settings",
1676 " Actor Id: " + FString::FromInt(ActorId));
1681 BIND_SYNC(apply_control_to_walker) << [
this](
1683 cr::WalkerControl Control) ->
R<void> 1690 "apply_control_to_walker",
1692 " Actor Id: " + FString::FromInt(ActorId));
1699 "apply_control_to_walker",
1701 " Actor Id: " + FString::FromInt(ActorId));
1706 BIND_SYNC(get_bones_transform) << [
this](
1714 "get_bones_transform",
1716 " Actor Id: " + FString::FromInt(ActorId));
1724 "get_bones_transform",
1726 " Actor Id: " + FString::FromInt(ActorId));
1729 std::vector<carla::rpc::BoneTransformDataOut> BoneData;
1733 Data.
bone_name = std::string(TCHAR_TO_UTF8(*Bone.Get<0>()));
1738 BoneData.push_back(Data);
1743 BIND_SYNC(set_bones_transform) << [
this](
1752 "set_bones_transform",
1754 " Actor Id: " + FString::FromInt(ActorId));
1762 "set_bones_transform",
1764 " Actor Id: " + FString::FromInt(ActorId));
1781 " Actor Id: " + FString::FromInt(ActorId));
1790 " Actor Id: " + FString::FromInt(ActorId));
1796 BIND_SYNC(get_pose_from_animation) << [
this](
1804 "get_pose_from_animation",
1806 " Actor Id: " + FString::FromInt(ActorId));
1813 "get_pose_from_animation",
1815 " Actor Id: " + FString::FromInt(ActorId));
1821 BIND_SYNC(set_actor_autopilot) << [
this](
1830 "set_actor_autopilot",
1832 " Actor Id: " + FString::FromInt(ActorId));
1839 "set_actor_autopilot",
1841 " Actor Id: " + FString::FromInt(ActorId));
1846 BIND_SYNC(show_vehicle_debug_telemetry) << [
this](
1855 "show_vehicle_debug_telemetry",
1857 " Actor Id: " + FString::FromInt(ActorId));
1864 "show_vehicle_debug_telemetry",
1866 " Actor Id: " + FString::FromInt(ActorId));
1873 std::string SimfilePath) ->
R<void> 1882 " Actor Id: " + FString::FromInt(ActorId));
1885 CarlaActor->
EnableCarSim(carla::rpc::ToFString(SimfilePath));
1891 " Actor Id: " + FString::FromInt(ActorId));
1907 " Actor Id: " + FString::FromInt(ActorId));
1916 " Actor Id: " + FString::FromInt(ActorId));
1921 BIND_SYNC(enable_chrono_physics) << [
this](
1923 uint64_t MaxSubsteps,
1924 float MaxSubstepDeltaTime,
1925 std::string VehicleJSON,
1926 std::string PowertrainJSON,
1927 std::string TireJSON,
1928 std::string BaseJSONPath) ->
R<void> 1935 "enable_chrono_physics",
1937 " Actor Id: " + FString::FromInt(ActorId));
1941 MaxSubsteps, MaxSubstepDeltaTime,
1942 cr::ToFString(VehicleJSON),
1943 cr::ToFString(PowertrainJSON),
1944 cr::ToFString(TireJSON),
1945 cr::ToFString(BaseJSONPath));
1949 "enable_chrono_physics",
1951 " Actor Id: " + FString::FromInt(ActorId));
1958 BIND_SYNC(set_traffic_light_state) << [
this](
1967 "set_traffic_light_state",
1969 " Actor Id: " + FString::FromInt(ActorId));
1973 static_cast<ETrafficLightState>(trafficLightState));
1977 "set_traffic_light_state",
1979 " Actor Id: " + FString::FromInt(ActorId));
1984 BIND_SYNC(set_traffic_light_green_time) << [
this](
1993 "set_traffic_light_green_time",
1995 " Actor Id: " + FString::FromInt(ActorId));
2002 "set_traffic_light_green_time",
2004 " Actor Id: " + FString::FromInt(ActorId));
2009 BIND_SYNC(set_traffic_light_yellow_time) << [
this](
2018 "set_traffic_light_yellow_time",
2020 " Actor Id: " + FString::FromInt(ActorId));
2027 "set_traffic_light_yellow_time",
2029 " Actor Id: " + FString::FromInt(ActorId));
2034 BIND_SYNC(set_traffic_light_red_time) << [
this](
2043 "set_traffic_light_red_time",
2045 " Actor Id: " + FString::FromInt(ActorId));
2052 "set_traffic_light_red_time",
2054 " Actor Id: " + FString::FromInt(ActorId));
2059 BIND_SYNC(freeze_traffic_light) << [
this](
2068 "freeze_traffic_light",
2070 " Actor Id: " + FString::FromInt(ActorId));
2077 "freeze_traffic_light",
2079 " Actor Id: " + FString::FromInt(ActorId));
2084 BIND_SYNC(reset_traffic_light_group) << [
this](
2092 "reset_traffic_light_group",
2094 " Actor Id: " + FString::FromInt(ActorId));
2101 "reset_traffic_light_group",
2103 " Actor Id: " + FString::FromInt(ActorId));
2111 for (TActorIterator<ATrafficLightGroup> It(
Episode->GetWorld()); It; ++It)
2118 BIND_SYNC(freeze_all_traffic_lights) << [
this]
2127 auto* TraffiLightManager = GameMode->GetTrafficLightManager();
2128 TraffiLightManager->SetFrozen(frozen);
2150 if (!
Actor->IsPendingKill())
2163 BIND_SYNC(get_group_traffic_lights) << [
this](
2170 RESPOND_ERROR(
"unable to get group traffic lights: actor not found");
2175 return std::vector<cr::ActorId>();
2182 RESPOND_ERROR(
"unable to get group traffic lights: actor is not a traffic light");
2184 std::vector<cr::ActorId> Result;
2185 for (
auto* TLight :
TrafficLight->GetGroupTrafficLights())
2190 Result.push_back(View->GetActorId());
2207 " Actor Id: " + FString::FromInt(ActorId));
2214 " Actor Id: " + FString::FromInt(ActorId));
2224 " Actor Id: " + FString::FromInt(ActorId));
2226 TArray<FBoundingBox> Result;
2227 TArray<uint8> OutTag;
2229 TrafficLight, Result, OutTag,
2231 return MakeVectorFromTArray<cg::BoundingBox>(Result);
2243 "get_gbuffer_token",
2245 " Actor Id: " + FString::FromInt(ActorId));
2250 "get_gbuffer_token",
2252 " Actor Id: " + FString::FromInt(ActorId));
2258 "get_gbuffer_token",
2260 " Actor Id: " + FString::FromInt(ActorId));
2268 return std::vector<unsigned char>(std::begin(Token.data), std::end(Token.data));
2273 return std::vector<unsigned char>(std::begin(Token.data), std::end(Token.data));
2278 return std::vector<unsigned char>(std::begin(Token.data), std::end(Token.data));
2283 return std::vector<unsigned char>(std::begin(Token.data), std::end(Token.data));
2288 return std::vector<unsigned char>(std::begin(Token.data), std::end(Token.data));
2293 return std::vector<unsigned char>(std::begin(Token.data), std::end(Token.data));
2298 return std::vector<unsigned char>(std::begin(Token.data), std::end(Token.data));
2303 return std::vector<unsigned char>(std::begin(Token.data), std::end(Token.data));
2308 return std::vector<unsigned char>(std::begin(Token.data), std::end(Token.data));
2313 return std::vector<unsigned char>(std::begin(Token.data), std::end(Token.data));
2318 return std::vector<unsigned char>(std::begin(Token.data), std::end(Token.data));
2323 return std::vector<unsigned char>(std::begin(Token.data), std::end(Token.data));
2328 return std::vector<unsigned char>(std::begin(Token.data), std::end(Token.data));
2331 UE_LOG(LogCarla, Error, TEXT(
"Requested invalid GBuffer ID %u"), GBufferId);
2351 BIND_SYNC(show_recorder_file_info) << [
this](
2361 BIND_SYNC(show_recorder_collisions) << [
this](
2373 BIND_SYNC(show_recorder_actors_blocked) << [
this](
2401 BIND_SYNC(set_replayer_time_factor) << [
this](
double time_factor) ->
R<void> 2415 BIND_SYNC(set_replayer_ignore_spectator) << [
this](
bool ignore_spectator) ->
R<void> 2431 BIND_SYNC(draw_debug_shape) << [
this](
const cr::DebugShape &shape) ->
R<void> 2434 auto *World =
Episode->GetWorld();
2435 check(World !=
nullptr);
2443 using C = cr::Command;
2447 auto parse_result = [](ActorId id,
const auto &response) {
2448 return response.HasError() ? CR{response.GetError()} : CR{
id};
2451 #define MAKE_RESULT(operation) return parse_result(c.actor, operation); 2454 [=](
auto self,
const C::SpawnActor &c) -> CR {
2455 auto result = c.parent.has_value() ?
2456 spawn_actor_with_parent(
2460 cr::AttachmentType::Rigid) :
2461 spawn_actor(c.description, c.transform);
2462 if (!result.HasError())
2464 ActorId
id = result.Get().id;
2466 [](C::SpawnActor &) {},
2467 [](C::ConsoleCommand &) {},
2468 [id](
auto &s) { s.actor = id; });
2469 for (
auto command : c.do_after)
2471 boost::variant2::visit(set_id, command.command);
2472 boost::variant2::visit(
self, command.command);
2476 return result.GetError();
2478 [=](
auto,
const C::DestroyActor &c) {
MAKE_RESULT(destroy_actor(c.actor)); },
2479 [=](
auto,
const C::ApplyVehicleControl &c) {
MAKE_RESULT(apply_control_to_vehicle(c.actor, c.control)); },
2480 [=](
auto,
const C::ApplyVehicleAckermannControl &c) {
MAKE_RESULT(apply_ackermann_control_to_vehicle(c.actor, c.control)); },
2481 [=](
auto,
const C::ApplyWalkerControl &c) {
MAKE_RESULT(apply_control_to_walker(c.actor, c.control)); },
2482 [=](
auto,
const C::ApplyVehiclePhysicsControl &c) {
MAKE_RESULT(apply_physics_control(c.actor, c.physics_control)); },
2483 [=](
auto,
const C::ApplyTransform &c) {
MAKE_RESULT(set_actor_transform(c.actor, c.transform)); },
2484 [=](
auto,
const C::ApplyTargetVelocity &c) {
MAKE_RESULT(set_actor_target_velocity(c.actor, c.velocity)); },
2485 [=](
auto,
const C::ApplyTargetAngularVelocity &c) {
MAKE_RESULT(set_actor_target_angular_velocity(c.actor, c.angular_velocity)); },
2486 [=](
auto,
const C::ApplyImpulse &c) {
MAKE_RESULT(add_actor_impulse(c.actor, c.impulse)); },
2487 [=](
auto,
const C::ApplyForce &c) {
MAKE_RESULT(add_actor_force(c.actor, c.force)); },
2488 [=](
auto,
const C::ApplyAngularImpulse &c) {
MAKE_RESULT(add_actor_angular_impulse(c.actor, c.impulse)); },
2489 [=](
auto,
const C::ApplyTorque &c) {
MAKE_RESULT(add_actor_torque(c.actor, c.torque)); },
2490 [=](
auto,
const C::SetSimulatePhysics &c) {
MAKE_RESULT(set_actor_simulate_physics(c.actor, c.enabled)); },
2491 [=](
auto,
const C::SetEnableGravity &c) {
MAKE_RESULT(set_actor_enable_gravity(c.actor, c.enabled)); },
2493 [=](
auto,
const C::SetAutopilot &c) {
MAKE_RESULT(set_actor_autopilot(c.actor, c.enabled)); },
2494 [=](
auto,
const C::ShowDebugTelemetry &c) {
MAKE_RESULT(show_vehicle_debug_telemetry(c.actor, c.enabled)); },
2495 [=](
auto,
const C::SetVehicleLightState &c) {
MAKE_RESULT(set_vehicle_light_state(c.actor, c.light_state)); },
2498 [=](
auto,
const C::ApplyWalkerState &c) {
MAKE_RESULT(set_walker_state(c.actor, c.transform, c.speed)); },
2499 [=](
auto,
const C::ConsoleCommand& c) -> CR {
return console_command(c.cmd); },
2500 [=](
auto,
const C::SetTrafficLightState& c) {
MAKE_RESULT(set_traffic_light_state(c.actor, c.traffic_light_state)); },
2501 [=](
auto,
const C::ApplyLocation& c) {
MAKE_RESULT(set_actor_location(c.actor, c.location)); }
2507 const std::vector<cr::Command> &commands,
2510 std::vector<CR> result;
2511 result.reserve(commands.size());
2512 for (
const auto &command : commands)
2514 result.emplace_back(boost::variant2::visit(command_visitor, command.command));
2525 BIND_SYNC(query_lights_state) << [
this](std::string client) ->
R<std::vector<cr::LightState>>
2528 std::vector<cr::LightState> result;
2529 auto *World =
Episode->GetWorld();
2532 result = CarlaLightSubsystem->
GetLights(FString(client.c_str()));
2537 BIND_SYNC(update_lights_state) << [
this]
2538 (std::string client,
const std::vector<cr::LightState>& lights,
bool discard_client) ->
R<void> 2541 auto *World =
Episode->GetWorld();
2544 CarlaLightSubsystem->
SetLights(FString(client.c_str()), lights, discard_client);
2549 BIND_SYNC(update_day_night_cycle) << [
this]
2550 (std::string client,
const bool active) ->
R<void> 2553 auto *World =
Episode->GetWorld();
2566 ->
R<std::pair<bool,cr::LabelledPoint>>
2569 auto *World =
Episode->GetWorld();
2570 constexpr
float meter_to_centimeter = 100.0f;
2579 meter_to_centimeter * SearchDistance, World);
2584 ->
R<std::vector<cr::LabelledPoint>>
2587 auto *World =
Episode->GetWorld();
2588 FVector UEStartLocation = StartLocation;
2589 FVector UEEndLocation = EndLocation;
2595 UEEndLocation = LargeMap->GlobalToLocalLocation(UEEndLocation);
2608 #undef REQUIRE_CARLA_EPISODE 2609 #undef RESPOND_ERROR_FSTRING 2610 #undef RESPOND_ERROR 2611 #undef CARLA_ENSURE_GAME_THREAD 2625 Pimpl = MakeUnique<FPimpl>(RPCPort, StreamingPort, SecondaryPort);
2626 StreamingPort =
Pimpl->StreamingServer.GetLocalEndpoint().port();
2627 SecondaryPort =
Pimpl->SecondaryServer->GetLocalEndpoint().port();
2632 TEXT(
"Initialized CarlaServer: Ports(rpc=%d, streaming=%d, secondary=%d)"),
2636 return Pimpl->BroadcastStream;
2641 check(
Pimpl !=
nullptr);
2642 UE_LOG(LogCarlaServer, Log, TEXT(
"New episode '%s' started"), *Episode.
GetMapName());
2643 Pimpl->Episode = &Episode;
2648 check(
Pimpl !=
nullptr);
2649 Pimpl->Episode =
nullptr;
2654 check(
Pimpl !=
nullptr);
2656 int ThreadsPerServer = std::max(2u, NumberOfWorkerThreads / 3u);
2658 int32_t StreamingThreads;
2659 int32_t SecondaryThreads;
2665 RPCThreads = ThreadsPerServer;
2667 if(!FParse::Value(
FCommandLine::Get(), TEXT(
"-StreamingThreads="), StreamingThreads))
2669 StreamingThreads = ThreadsPerServer;
2671 if(!FParse::Value(
FCommandLine::Get(), TEXT(
"-SecondaryThreads="), SecondaryThreads))
2673 SecondaryThreads = ThreadsPerServer;
2676 UE_LOG(LogCarla, Log, TEXT(
"FCarlaServer AsyncRun %d, RPCThreads %d, StreamingThreads %d, SecondaryThreads %d"),
2677 NumberOfWorkerThreads, RPCThreads, StreamingThreads, SecondaryThreads);
2679 Pimpl->Server.AsyncRun(RPCThreads);
2680 Pimpl->StreamingServer.AsyncRun(StreamingThreads);
2681 Pimpl->SecondaryServer->AsyncRun(SecondaryThreads);
2686 TRACE_CPUPROFILER_EVENT_SCOPE_STR(__FUNCTION__);
2692 (void)
Pimpl->TickCuesReceived.fetch_add(1, std::memory_order_release);
2697 auto k =
Pimpl->TickCuesReceived.fetch_sub(1, std::memory_order_acquire);
2698 bool flag = (k > 0);
2700 (void)
Pimpl->TickCuesReceived.fetch_add(1, std::memory_order_release);
2708 Pimpl->Server.Stop();
2709 Pimpl->SecondaryServer->Stop();
2715 check(
Pimpl !=
nullptr);
2716 return Pimpl->StreamingServer.MakeStream();
2721 return Pimpl->GetSecondaryServer();
2726 return Pimpl->StreamingServer;
carla::streaming::Stream BroadcastStream
FCarlaActor * FindCarlaActor(FCarlaActor::IdType ActorId)
Find a Carla actor by id.
carla::streaming::Server & GetStreamingServer()
virtual ECarlaServerResponse SetVehicleLightState(const FVehicleLightState &)
TArray< FEnvironmentObject > GetEnvironmentObjects(uint8 QueriedTag=0xFF) const
void ApplyTextureToActor(AActor *Actor, UTexture2D *Texture, const carla::rpc::MaterialParameter &TextureParam)
FDataStream OpenStream() const
FCameraGBufferUint8 GBufferF
auto end() const noexcept
std::vector< carla::rpc::LightState > GetLights(FString Client)
FPimpl(uint16_t RPCPort, uint16_t StreamingPort, uint16_t SecondaryPort)
static FString StatusToString(EActorSpawnResultStatus Status)
bool LoadNewOpendriveEpisode(const FString &OpenDriveString, const carla::rpc::OpendriveGenerationParameters &Params)
Load a new map generating the mesh from OpenDRIVE data and start a new episode.
void StopReplayer(bool KeepActors=false)
void DisableForROS(stream_id sensor_id)
bool DestroyActor(AActor *Actor)
FCameraGBufferUint8 SceneDepth
virtual ECarlaServerResponse SetWheelSteerDirection(const EVehicleWheelLocation &, float)
AWeather * GetWeather() const
std::string ShowFileCollisions(std::string Name, char Type1, char Type2)
void SetDayNightCycle(const bool active)
void SetMapLayer(int32 MapLayer)
auto operator<<(FuncT func)
void ConsiderSpectatorAsEgo(bool _SpectatorAsEgo)
virtual ECarlaServerResponse SetActorEnableGravity(bool bEnabled)
FVector GlobalToLocalLocation(const FVector &InLocation) const
virtual ECarlaServerResponse SetActorCollisions(bool bEnabled)
carla::rpc::ResponseError RespondError(const FString &FuncName, const FString &ErrorMessage, const FString &ExtraInfo="")
virtual ECarlaServerResponse SetBonesTransform(const FWalkerBoneControlIn &)
The game instance contains elements that must be kept alive in between levels.
TMap< FString, FWalkerBoneControlOutData > BoneTransforms
static TArray< uint8 > Load(FString MapName)
Return the Navigation Mesh Binary associated to MapName, or empty if the such file wasn't serialized...
#define MAKE_RESULT(operation)
FCameraGBufferUint8 CustomStencil
FCameraGBufferUint8 SceneStencil
static auto MakeRecursiveOverload(FuncTs &&... fs)
auto begin() const noexcept
carla::rpc::Actor SerializeActor(FCarlaActor *CarlaActor) const
Create a serializable object describing the actor.
void SetReplayerTimeFactor(double TimeFactor)
virtual ECarlaServerResponse DisableActorConstantVelocity()
FDataMultiStream Start(uint16_t RPCPort, uint16_t StreamingPort, uint16_t SecondaryPort)
std::string ShowFileActorsBlocked(std::string Name, double MinTime=30, double MinDistance=10)
std::vector< std::pair< ActorId, VehicleLightState::flag_type > > VehicleLightStateList
TArray< FTransform > GetRecommendedSpawnPoints() const
Return the list of recommended spawn points for vehicles.
#define RESPOND_ERROR_FSTRING(fstr)
std::map< uint16_t, std::string > TrafficManagerInfo
Map of pairs < port , ip > with all the Traffic Managers active in the simulation.
auto GetToken() const
Return the token that allows subscribing to this sensor's stream.
void EnableEnvironmentObjects(const TSet< uint64 > &EnvObjectIds, bool Enable)
static TArray< FString > GetAllMapNames()
FCameraGBufferUint8 GBufferE
virtual ECarlaServerResponse BlendPose(float Blend)
void PutActorToSleep(carla::rpc::ActorId ActorId)
virtual ECarlaServerResponse GetPhysicsControl(FVehiclePhysicsControl &)
virtual ECarlaServerResponse ApplyAckermannControllerSettings(const FAckermannControllerSettings &)
void UnLoadMapLayer(int32 MapLayers)
void OnActorSpawned(const FCarlaActor &CarlaActor)
bool IsEnabledForROS(stream_id sensor_id)
virtual ECarlaServerResponse ApplyControlToVehicle(const FVehicleControl &, const EVehicleInputPriority &)
AActor * FindActorByName(const FString &ActorName)
UTexture2D * CreateUETexture(const carla::rpc::TextureColor &Texture)
static T Get(carla::rpc::Response< T > &response)
bg::model::box< Point3D > Box
virtual ECarlaServerResponse SetTrafficLightState(const ETrafficLightState &)
static ACarlaGameModeBase * GetGameMode(const UObject *WorldContextObject)
static void GetTrafficLightBoundingBox(const ATrafficLightBase *TrafficLight, TArray< FBoundingBox > &OutBB, TArray< uint8 > &OutTag, uint8 InTagQueried=0xFF)
const FString & GetMapName() const
Return the name of the map loaded in this episode.
std::atomic_size_t TickCuesReceived
static uint64_t GetFrameCounter()
token_type GetToken(stream_id sensor_id)
virtual ECarlaServerResponse EnableChronoPhysics(uint64_t, float, const FString &, const FString &, const FString &, const FString &)
void SetActorGlobalLocation(const FVector &Location, ETeleportType Teleport=ETeleportType::TeleportPhysics)
void Draw(const carla::rpc::DebugShape &Shape)
ECarlaServerResponse AddActorImpulse(const FVector &Impulse)
ECarlaServerResponse SetActorTargetAngularVelocity(const FVector &AngularVelocity)
void LoadMapLayer(int32 MapLayers)
void RunSome(uint32 Milliseconds)
const FActorRegistry & GetActorRegistry() const
virtual ECarlaServerResponse CloseVehicleDoor(const EVehicleDoor)
TMap< FString, FActorAttribute > Variations
User selected variations of the actor.
std::string StartRecorder(std::string name, bool AdditionalData)
void EnableForROS(stream_id sensor_id)
ECarlaServerResponse AddActorForceAtLocation(const FVector &Force, const FVector &Location)
ECarlaServerResponse AddActorTorque(const FVector &Torque)
static UCarlaGameInstance * GetGameInstance(const UObject *WorldContextObject)
carla::SharedPtr< cc::Actor > Actor
virtual ECarlaServerResponse FreezeTrafficLight(bool)
virtual ECarlaServerResponse EnableActorConstantVelocity(const FVector &)
std::shared_ptr< carla::multigpu::Router > SecondaryServer
An RPC server in which functions can be bind to run synchronously or asynchronously.
virtual ECarlaServerResponse GetPoseFromAnimation()
FCameraGBufferUint8 GBufferD
std::string ReplayFile(std::string Name, double TimeStart, double Duration, uint32_t FollowId, bool ReplaySensors)
TPair< EActorSpawnResultStatus, FCarlaActor * > SpawnActorWithInfo(const FTransform &Transform, FActorDescription thisActorDescription, FCarlaActor::IdType DesiredId=0)
Spawns an actor based on ActorDescription at Transform.
FCameraGBufferUint8 GBufferA
void SetActorState(carla::rpc::ActorState InState)
Response< ActorId > CommandResponse
virtual ECarlaServerResponse ResetTrafficLightGroup()
void SetAttachmentType(carla::rpc::AttachmentType InAttachmentType)
bool LoadNewEpisode(const FString &MapString, bool ResetSettings=true)
Load a new map and start a new episode.
const TArray< FActorDefinition > & GetActorDefinitions() const
Return the list of actor definitions that are available to be spawned this episode.
std::shared_ptr< carla::multigpu::Router > GetSecondaryServer()
virtual ECarlaServerResponse GetBonesTransform(FWalkerBoneControlOut &)
#define RESPOND_ERROR(str)
virtual ECarlaServerResponse ApplyControlToWalker(const FWalkerControl &)
static std::vector< T > MakeVectorFromTArray(const TArray< Other > &Array)
Token token() const
Token associated with this stream.
FCameraGBufferUint8 SceneColor
auto GetId() const
Return the unique id of this episode.
std::shared_ptr< carla::multigpu::Router > GetSecondaryServer()
void SetLights(FString Client, std::vector< carla::rpc::LightState > LightsToSet, bool DiscardClient=false)
FActorDescription Description
void SetReplayerIgnoreHero(bool IgnoreHero)
constexpr size_t milliseconds() const noexcept
virtual ECarlaServerResponse SetLightGreenTime(float)
TArray< FString > GetNamesOfAllActors()
static FString GetXODR(const UWorld *World)
Return the OpenDrive XML associated to MapName, or empty if the file is not found.
const FActorInfo * GetActorInfo() const
FCameraGBufferUint8 CustomDepth
ACarlaRecorder * GetRecorder() const
virtual ECarlaServerResponse SetLightYellowTime(float)
carla::rpc::Server Server
virtual ECarlaServerResponse SetActorDead()
virtual ECarlaServerResponse SetLightRedTime(float)
ALargeMapManager * GetLMManager() const
static auto MakeOverload(FuncTs &&... fs)
Creates an "overloaded callable object" out of one or more callable objects, each callable object wil...
Base class for sensors using a USceneCaptureComponent2D for rendering the scene.
virtual ECarlaServerResponse SetActorAutopilot(bool, bool bKeepState=false)
FString GetActorDescriptionFromStream(carla::streaming::detail::stream_id_type StreamId)
Get the description of the Carla actor (sensor) using specific stream id.
carla::rpc::Server & _server
ECarlaServerResponse SetActorTargetVelocity(const FVector &Velocity)
void SetReplayerIgnoreSpectator(bool IgnoreSpectator)
virtual ECarlaServerResponse OpenVehicleDoor(const EVehicleDoor)
virtual ECarlaServerResponse EnableCarSim(const FString &)
FTransform LocalToGlobalTransform(const FTransform &InTransform) const
TUniquePtr< FPimpl > Pimpl
FString CarlaGetStringError(ECarlaServerResponse Response)
APawn * GetSpectatorPawn() const
void AttachActors(AActor *Child, AActor *Parent, EAttachmentType InAttachmentType=EAttachmentType::Rigid)
Attach Child to Parent.
void AddChildren(IdType ChildId)
virtual ECarlaServerResponse UseCarSimRoad(bool)
static std::pair< bool, carla::rpc::LabelledPoint > ProjectPoint(FVector StartLocation, FVector Direction, float MaxDistance, UWorld *World)
std::string ShowFileInfo(std::string Name, bool bShowAll=false)
static ALargeMapManager * GetLargeMapManager(const UObject *WorldContextObject)
carla::streaming::Server StreamingServer
ECarlaServerResponse AddActorImpulseAtLocation(const FVector &Impulse, const FVector &Location)
TArray< FBoundingBox > GetAllBBsOfLevel(uint8 TagQueried=0xFF) const
FCameraGBufferUint8 GBufferC
FCameraGBufferUint8 Velocity
Base class for the CARLA Game Mode.
virtual ECarlaServerResponse SetActorSimulatePhysics(bool bEnabled)
virtual ECarlaServerResponse GetVehicleLightState(FVehicleLightState &)
const FEpisodeSettings & GetSettings() const
void SetParent(IdType InParentId)
static std::shared_ptr< ROS2 > GetInstance()
IdType GetActorId() const
virtual ECarlaServerResponse ApplyAckermannControlToVehicle(const FVehicleAckermannControl &, const EVehicleInputPriority &)
ECarlaServerResponse AddActorForce(const FVector &Force)
Texture< sensor::data::Color > TextureColor
virtual ECarlaServerResponse ApplyPhysicsControl(const FVehiclePhysicsControl &)
const FString GetFullMapPath() const
Base class for CARLA wheeled vehicles.
virtual ECarlaServerResponse GetWheelSteerAngle(const EVehicleWheelLocation &, float &)
struct ASceneCaptureSensor::@0 CameraGBuffers
Texture< FloatColor > TextureFloatColor
void AsyncRun(uint32 NumberOfWorkerThreads)
virtual ECarlaServerResponse GetAckermannControllerSettings(FAckermannControllerSettings &)
void SetActorGlobalTransform(const FTransform &Transform, ETeleportType Teleport=ETeleportType::TeleportPhysics)
FCameraGBufferUint8 GBufferB
ECarlaServerResponse AddActorAngularImpulse(const FVector &AngularInpulse)
#define REQUIRE_CARLA_EPISODE()
geom::Transform Transform
FVector LocalToGlobalLocation(const FVector &InLocation) const
constexpr ServerBinder(const char *name, carla::rpc::Server &srv, bool sync)
virtual ECarlaServerResponse ShowVehicleDebugTelemetry(bool)
virtual ECarlaServerResponse SetWalkerState(const FTransform &Transform, carla::rpc::WalkerControl WalkerControl)
ActorType GetActorType() const
A view over an actor and its properties.
FVehicleLightState GetVehicleLightState() const
void ApplySettings(const FEpisodeSettings &Settings)
void SetSynchronousMode(bool is_synchro)
static std::vector< carla::rpc::LabelledPoint > CastRay(FVector StartLocation, FVector EndLocation, UWorld *World)
void NotifyBeginEpisode(UCarlaEpisode &Episode)