classes package
This package contains helper classes and constants used in this project.
The classes from carla_originals are mostly identical to the
ones provided in the examples from the CARLA PythonAPI.
Classes Overview
GameFramework
The GameFramework is a helper-class class for a quicker setup.
It manages the game loop of the agent and takes care of:
Initialization of:
, and
interface
for other actors
The agent
Cooldowns of rules
Load the LaunchConfig via Hydra’s compose API
Interface to the CarlaDataProvider from the scenario_runner package.
Handling of special exceptions during the agent’s
run_steploopTicking of the world HUD rendering
GameFramework.render_everything(). Note: This function is the recommended way to render everything.
WorldModel
The WorldModel is a helper-class serving as a interface between the agent,
the simulator and the user. It handles the world ticks of the simulator and rendering of the pygame interface.
It is based on the World classes used in the examples from CARLA.
It is a extension of the class and provides the following functionalities:
Spawning of the ego actor (optional)
Or waits until an external script provides it. Command line argument
external_actor="hero".
Ticking (
sync=True) or waiting for the tick (sync=False) of theHUD management
Camera setup and management
Some sensors for the pygame user interface, displayed on the HUD
Toggling of
rendering
Note
GameFramework.render_everything()extends the rendering of theWorldModeland is the preferred function to call for rendering.
RSS features
Weather change
Cleanup when the program ends
HUD and Camera Manager
The HUD is a modification of the HUD classes used in the manual_control_rss.py example of Carla.
It closely combines with the classes.camera_manager.CameraManager to provide the visual human interface for the pygame window.
Rules
See the Rule documentation for details.
RssSensor and Visualization
See the RSS documentation from CARLA.
KeyboardControls
See RSSKeyboardControl API for a more details.
Constants and Enums
See contents of the classes.constants module.
carla_originals
This package contains (mostly) unmodified classes extracted from examples provided by CARLA. The classes have are imported into this package.
Driver, Vehicle, VehicleSpawner
These are classes that are deprecated or will be merged or are up to major changes.
Rule Interpreter
This class allows for an alternative way to execute rules through different interfaces (python, yaml, xml, etc). It is not yet further integrated and documented.
Exceptions Overview
AgentDoneExceptionRaised when there is no more waypoint in the queue to follow and no rule set a new destination.ContinueLoopExceptionRaise when theagent.run_stepof the agent should not be continued further. The agent then returns the currentctx.controlto the caller ofrun_step.UserInterruptionTerminate therun_steploop if user input is detected, for example or a pygame hotkey like Esc. This allows the scenario runner and leaderboard to exit gracefully.UpdatedPathExceptionShould be raised when the path has been updated and the agent should replan.Phase.DONE | ENDFor more details see the
classes.exceptionsAPI documentation.
- class classes.CustomSensorInterface
Bases:
objectThis is a mixin for classes like the
camera_manager.CameraManageror theclasses.rss_sensor.RssSensorthat either wrap around a or should have a similar interface.Attention
Not to be confused with
srunner.autoagents.sensor_interface.SensorInterface.- sensor: carla.Sensor
Subpackages
Submodules
classes.constants module
In this module defines enums and constants that are used throughout the project.
- classes.constants.AD_RSS_AVAILABLE: bool
Indicator if the
carla.admodule is available, i.e. if the current carla version was build with RSS support. As a rule of thumb: On Windows this will be always false. If this is false some objects will be missing in thecarlamodule, for example thecarla.RssSensor, likewise are some utilities of this project involving RSS not be available.
- class classes.constants.AgentState(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
FlagHigh-level states that the agent currently can be in.
Used with
LunaticAgent.current_statesandInformationManager.state_counter.- DRIVING
- STOPPED
- BLOCKED_BY_VEHICLE
- BLOCKED_RED_LIGHT
- BLOCKED_BY_STATIC
Static obstacle.
Attention
Not updated by the information manager but in the
Phase.DETECT_STATIC_OBSTACLESphase.
- BLOCKED_OTHER
- REVERSE
- OVERTAKING
- AGAINST_LANE_DIRECTION
- BLOCKED
Combination of
BLOCKED_OTHER | BLOCKED_BY_VEHICLE | BLOCKED_RED_LIGHT | BLOCKED_BY_STATIC
- class classes.constants.RulePriority(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
IntEnumPriority of a
Rule. The higher a value, the higher the priority. Rules are sorted by their priority before being applied.- NULL = 0
- LOWEST = 1
- LOW = 2
- NORMAL = 4
- HIGH = 8
- HIGHEST = 16
- class classes.constants.Phase(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
FlagA rough order of the looped through states of the agent is:
<Phases.NONE: 0>, <Phases.UPDATE_INFORMATION|BEGIN: 5>, <Phases.UPDATE_INFORMATION|END: 6>, <Phases.PLAN_PATH|BEGIN: 9>, <Phases.PLAN_PATH|END: 10>, <Phases.DETECT_TRAFFIC_LIGHTS|BEGIN: 17>, <Phases.DETECT_TRAFFIC_LIGHTS|END: 18>, <Phases.DETECT_PEDESTRIANS|BEGIN: 33>, <Phases.DETECT_PEDESTRIANS|END: 34>, <Phases.DETECT_CARS|BEGIN: 65>, <Phases.DETECT_CARS|END: 66>, <Phases.POST_DETECTION_PHASE|BEGIN: 129>, <Phases.POST_DETECTION_PHASE|END: 130>, <Phases.EXECUTION|BEGIN: 1025>, <Phases.EXECUTION|END: 1026>
Note
The above cycle list is not up to date.
- A complete list of all the main phases can be obtained by calling
Phase.get_main_phases()
- NONE = 0
- BEGIN
Indicates the beginning of a phase. Should always be combined with another phase.
- END
Indicates the end of a phase. Should always be combined with another phase.
- UPDATE_INFORMATION
Indicates the execution of the agents
update_information()methodThis is the first Phase of the agent and executed every step.
- PLAN_PATH
Indicates that the planning of a new path has started.
Attention
If the the path is replanned a
UpdatedPathExceptionshould be raised.
- DETECT_TRAFFIC_LIGHTS
Executed during the agents
detect_hazard()method. Can addHazard.TRAFFIC_LIGHT_REDorHazard.TRAFFIC_LIGHT_YELLOWto the agentsLunaticAgent.detected_hazards.
- DETECT_PEDESTRIANS
Executed during the agents
detect_hazard()method. Can addHazard.PEDESTRIANto the agentsLunaticAgent.detected_hazards.
- DETECT_STATIC_OBSTACLES
- Checks for static obstacles in the agents path with
- DETECT_CARS
- Checks for vehicles in the agents path with
Note
If a car was detected executes
Phase.CAR_DETECTED | BEGIN,Phase.DETECT_CARS | BEGINis only executed if no car was detected.
- TAKE_NORMAL_STEP
During this phase the
carla.VehicleControlis calculated by the local planner.
- RSS_EVALUATION
See also
classes.keyboard_controls.RssKeyboardControls.parse_events()
- APPLY_MANUAL_CONTROLS
Applied manually via human user interface.
- EXECUTION
Executed when the control is applied to the agent.
See also
- CAR_DETECTED
The
Phase.CAR_DETECTED | BEGINis executed when a car is detected and follows thePhase.DETECT_CARS | BEGINphase. If no car is detected thePhase.DETECT_CARS | ENDphase is executed.
- TURNING_AT_JUNCTION
Indicates that the agent is turning at a junction.
Warning
This Phase might become obsolete.
- HAZARD
Not implemented. Refer to EMERGENCY | BEGIN
- EMERGENCY = 32768
Special Phase
See also
- COLLISION
Special phase that is executed out-of-order when a
carla.Sensordetects a collision.See also
- DONE
Indicates that the agent is at the end of its path and
agent.done()isTrue.
- TERMINATING
Can be called when the agent is terminating. Must be executed by the user.
- CUSTOM_CYCLE
experimental
Can be used to indicate that the phase change is currently handled by the user.
Warning
LunaticAgent.execute_phasechecks for exact match, i.e. a phaseUPDATE_INFORMATION | BEGIN | ENDwill not be executed in the normal loop.See also
Executed in
BlockingRule.loop_agent
- DETECT_NON_CARS
Combination of
DETECT_STATIC_OBSTACLES | DETECT_TRAFFIC_LIGHTS | DETECT_PEDESTRIANS
- DETECTION_PHASE
Combination of
DETECT_STATIC_OBSTACLES | DETECT_TRAFFIC_LIGHTS | DETECT_PEDESTRIANS | DETECT_CARS
- EXCEPTIONS
Combination of
HAZARD | EMERGENCY | COLLISION | TURNING_AT_JUNCTION | CAR_DETECTED | DONE | TERMINATING
- USER_CONTROLLED
Phases that might or not be went through as they must be implemented manually by the user.
Combination of
APPLY_MANUAL_CONTROLS | EXECUTION | TERMINATING | CUSTOM_CYCLE
- NORMAL_LOOP
Combination of
UPDATE_INFORMATION | PLAN_PATH | DETECTION_PHASE | TAKE_NORMAL_STEP
- IN_LOOP
Phases that are executed in or before the inner step, EMERGENCY is executed, right after the inner step.
Combination of
NORMAL_LOOP | EMERGENCY | COLLISIONSee also
agents.substep_managers.collision_manager
- classmethod get_phases()
Get all BEGIN and END phases combination.
- class classes.constants.Hazard(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
FlagValues currently stored in the agent’s
detected_hazards. attribute.- TRAFFIC_LIGHT_RED
- TRAFFIC_LIGHT_YELLOW
- PEDESTRIAN
- CAR
- STATIC_OBSTACLE
Note
These refer to actors and not the environment barriers.
- OTHER
- JUNCTION
- OBSTACLE
Combination of
PEDESTRIAN | CAR | STATIC_OBSTACLE
- TRAFFIC_LIGHT
Combination of
TRAFFIC_LIGHT_RED | TRAFFIC_LIGHT_YELLOW
- class classes.constants.HazardSeverity(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
FlagHigh level descriptions to further weight
Hazard. TheHazardSeverityflags are stored indetected_hazards_info.- UNKNOWN = -1
- NONE = 0
Initial values for
LunaticAgent.detected_hazards_info
- WARNING = 1
- COLLISION
Special case for collision.
- class classes.constants.RoadOption(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
IntEnumRoadOption represents the possible topological configurations when moving from a segment of lane to other.
See also
RoadOptionColorfor the color representation of the road options.- VOID = -1
Indicated by green
- LEFT
Indicated by yellow
- RIGHT
Indicated by cyan
- STRAIGHT
Indicated by gray
- LANEFOLLOW
Indicated by green
- CHANGELANELEFT
Indicated by orange
- CHANGELANERIGHT
Indicated by dark cyan
- class classes.constants.RoadOptionColor(option: RoadOption)
Bases:
objectPoints to a
carla.Colorobject that represents the color of the road option.Supports
__getitem__(name)and__call__(RoadOption)for easy access.- Parameters:
option (RoadOption)
- Return type:
- VOID
Green
- LEFT
Yellow
- RIGHT
Cyan
- STRAIGHT
Gray
- LANEFOLLOW
Green
- CHANGELANELEFT
Orange
- CHANGELANERIGHT
Dark Cyan
- class classes.constants.RssLogLevelStub(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
_CarlaIntEnumEnum declaration used in carla.RssSensor to set the log level.
- trace = 0
- debug = 1
- info = 2
- warn = 3
- err = 4
- critical = 5
- off = 6
- class classes.constants.RssRoadBoundariesModeStub(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
_CarlaIntEnumEnum declaration used in carla.RssSensor to enable or disable the stay on road feature. In summary, this feature considers the road boundaries as virtual objects. The minimum safety distance check is applied to these virtual walls, in order to make sure the vehicle does not drive off the road.
- Off = 0
- On = 1
- class classes.constants.RuleResult(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
EnumSpecial
objectsthat indicate special return values aRule- NO_RESULT
Indicates the the rule returned no result, e.g. because an exception was raised.
- NOT_APPLICABLE
Object that indicates that no action was executed, e.g. because the rule is on cooldown or blocked.
- class classes.constants.StreetType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
-
Used by the
DetectionMatrixto interpret the street type.- ON_HIGHWAY = 'On highway'
- NON_HIGHWAY_STREET = 'Non highway street'
- ON_JUNCTION = 'On junction'
- ON_HIGHWAY_ENTRY = 'On highway entry'
- ON_HIGHWAY_EXIT = 'On highway exit'
- JUNCTION_AHEAD = 'Junction ahead'
- HIGHWAY_TRAFFIC_LIGHT = 'Highway traffic light'
- HIGHWAY_WITH_ENTRY_AND_EXIT = 'Highway with entry/exit'
classes.evaluation_function module
- class classes.evaluation_function.ConditionFunction(first_argument: str[name] | Callable[[Concatenate[RuleT, Context, ...]], Hashable] | Callable[[Concatenate[Context, ...]], Hashable] | None = None, name: str = 'ConditionFunction', *, truthy: bool = False, use_self: bool | None = None)
Bases:
Generic[_CP,_CH]Implements a decorator to wrap function to be used with
Ruleclasses. The function must return a hashable type, which is used to access the action to be taken by theRule.conditionfunction of the rule.Evaluation functions can be combined using the AND, OR and NOT operators to build up more complex rules from simpler ones. The operators
+, &,|and~are aliases forAND, ORandNOTrespectively. e.g. with these two functions:func1 = ConditionFunction(lambda ctx: ctx.speed > 10)func2 = ConditionFunction(lambda ctx: ctx.speed < 20)- These statements are all equivalent:
ConditionFunction(lambda ctx: 10 < ctx.speed < 20)func1 + func2func1 & func2func1.AND(func2)ConditionFunction.AND(func1, func2)
Hint
ConditionFunctions also allow for more specific returns types
Example:
@ConditionFunction def is_speeding(ctx: Context) -> Hashable: config = ctx.agent.config if config.speed > config.speed_limit+20: return "very fast" elif config.speed > config.speed_limit+5: return "fast" elif: config.speed < config.speed_limit-20: return "very slow" else: return "normal" Rule(is_speeding, action={ "very fast": lambda ctx: ctx.agent.config.follow_speed_limits(), "fast" : lambda ctx: ctx.agent.config.set_target_speed(ctx.speed_limit+5) })
- Parameters:
first_argument (str[name] | Callable[[Concatenate[RuleT, Context, ...]], Hashable] | Callable[[Concatenate[Context, ...]], Hashable] | None) – If
Noneor a string, the class will create a decorator that expects a callable as the first argument. If a string is passed it substitutes as the name argument. Otherwise a callable is expected like in the snippet used above.name (str) – The name to represent the function. Defaults to
"ConditionFunction".truthy (bool) – If True, the function will always cast the return value to a boolean value. Defaults to
False.use_self (Optional[bool]) – If
True, the function will be treated as a method and the first argument will be the instance of theRulethat uses this function. IfNone, the decision depends on the signature of the function, if it has only one argument only theContextobject is passed, if it has two or more arguments the first argument that is passed is the instance of theRule. UseFalseto not use the instance of theRuleas the first argument. Defaults toNone.
- Returns:
A
ConditionFunctionor a partially initialized version to be used as a decorator when the first_argument is not a callable.- Return type:
ConditionFunction | partial[ConditionFunction]
- Generics:
- _Rule :
Generic
Ruletype that could appear in theevaluation_function'ssignature.
_CP :
typing.ParamSpecof the passedevaluation_function._CH : The Hashable return type of the
evaluation_function.
- evaluation_function: CallableConditionT
The function that is wrapped by the
ConditionFunction. Uses the generic type hints_CP,_CHof the class.
- actions: Dict[Hashable, _ActionsDictValues] = {}
Mapping of return values to actions to be executed. If this dictionary is not empty it will be used as the
Rule.actionsdictionary.
- copy(copy_actions: bool = False)
Copies the class by creating a new instance.
- Parameters:
copy_actions (bool) – If
True, theConditionFunction.actionsdictionary is copied as well. Defaults toFalse.- Returns:
A new instance, with the same
__init__arguments.- Return type:
Warning
Be aware that when using copy_actions the actions themselves are not copied; they are identical and shared.
- register_action(key: Hashable = True, *, use_self: bool | None = None, **kwargs: ParamSpecKwargs) Callable[[CallableT], CallableT]
- register_action(action_function: CallableT, key: Hashable = True, *, use_self: bool | None = None, **kwargs: ParamSpecKwargs) CallableT
Add an action to be executed when the condition function returns a specific value.
This function can be used as a decorator or as a method:
# As decorator @ConditionFunction def is_speeding(ctx: Context) -> Literal["very fast", "fast", "normal", "slow", True]: ... @is_speeding.register_action(key="very fast") # or @is_speeding.register_action # default key is True def very_fast_action(ctx: Context): ctx.agent.set_target_speed(ctx.config.target_speed-5) # Or as function def fast_action(ctx: Context, speed: int): ctx.agent.set_target_speed(speed) is_speeding.register_action("fast", fast_action) # Custom keywords without Rule instance is_speeding.register_action("normal", use_self=False, # no Rule in the signature speed=ctx.config.target_speed) # keyword argument def custom_speed(ctx: Context, speed: int): ctx.agent.set_target_speed(speed)
- Parameters:
key (Hashable) – If the condition function returns this value, this action will be executed. Defaults to
True.action_function – (When not used as decorator) The action to be executed.
use_self (Optional[bool]) – If not
None, ause_selfattribute is set on the function to indicate if the function is a method or not.kwargs (ParamSpecKwargs) – Keyword arguments for the decorated function.
- Returns:
Decorator to be used or the decorated function as ConditionFunction.
- Return type:
_RegisterActionDecorator
Note
Only one action is allowed per key. If an action is already registered for the key, it will be overwritten.
- classmethod AND(func1: ConditionFunction[ParamSpec, _CH], func2: ConditionFunction[ParamSpec, Hashable]) ConditionFunction[ParamSpec, _CH | Hashable]
Combine two functions with
and, i.e. to return True if both return True.- Parameters:
func1 (ConditionFunction[ParamSpec, _CH])
func2 (ConditionFunction[ParamSpec, Hashable])
- Return type:
ConditionFunction[ParamSpec, _CH | Hashable]
- classmethod OR(func1: ConditionFunction[ParamSpec, _CH], func2: ConditionFunction[ParamSpec, Hashable]) ConditionFunction[ParamSpec, _CH | Hashable]
Combine two functions to return True if either returns True.
- Parameters:
func1 (ConditionFunction[ParamSpec, _CH])
func2 (ConditionFunction[ParamSpec, Hashable])
- Return type:
ConditionFunction[ParamSpec, _CH | Hashable]
- classmethod NOT(func: ConditionFunction[ParamSpec, _CH]) ConditionFunction[ParamSpec, bool]
Invert the return value of a function.
- Parameters:
func (ConditionFunction[ParamSpec, _CH])
- Return type:
- __add__(other: ConditionFunction[ParamSpec, Hashable]) ConditionFunction[ParamSpec, _CH | Hashable]
Combine with another function using
AND().- Parameters:
other (ConditionFunction[ParamSpec, Hashable])
- Return type:
ConditionFunction[ParamSpec, _CH | Hashable]
- __and__(other: ConditionFunction[ParamSpec, Hashable]) ConditionFunction[ParamSpec, _CH | Hashable]
Combine with another function using
AND().- Parameters:
other (ConditionFunction[ParamSpec, Hashable])
- Return type:
ConditionFunction[ParamSpec, _CH | Hashable]
- __or__(other: ConditionFunction[ParamSpec, Hashable]) ConditionFunction[ParamSpec, _CH | Hashable]
Combine with another function using
OR().- Parameters:
other (ConditionFunction[ParamSpec, Hashable])
- Return type:
ConditionFunction[ParamSpec, _CH | Hashable]
- __invert__() ConditionFunction[ParamSpec, bool]
Invert the return value of the function.
- Return type:
classes.exceptions module
Helper module that contains all the custom exceptions used in the project
- exception classes.exceptions.UserInterruption
Bases:
ExceptionTerminate the loop if user input is detected. Allows the scenario runner and Leaderboard to exit gracefully, if handled appropriately, e.g. by directly returning.
Thrown by
LunaticAgent.parse_keyboard_input.Note
Is not a
LunaticAgentException.
- exception classes.exceptions.LunaticAgentException
Bases:
ExceptionBase class for all custom exceptions that influence the Workflow of the
LunaticAgent.
- exception classes.exceptions.AgentDoneException
Bases:
LunaticAgentExceptionRaised when there is no more waypoint in the queue to follow and no rule set a new destination.
When the a
GameFrameworkinstance is used as context manager will setgame_framework.continue_looptoFalse.
- exception classes.exceptions.ContinueLoopException
Bases:
LunaticAgentExceptionRaise when
LunaticAgent.run_step()action of the agent should not be continued further.The agent returns the current
ctx.controlto the caller ofrun_step.Note
Handled in
LunaticAgent.run_step(), this exception should not propagate outside. It can be caught byGameFrameworkand skip the current loop and not apply any controls, an error will be logged.
- exception classes.exceptions.SkipInnerLoopException(planned_control: carla.VehicleControl, *args: object)
Bases:
LunaticAgentExceptionCan be raised in LunaticAgent._inner_step. A new control object must be provided.
- Parameters:
planned_control (carla.VehicleControl)
args (object)
- Return type:
None
- __init__(planned_control: carla.VehicleControl, *args: object) None
- Parameters:
planned_control (carla.VehicleControl)
args (object)
- Return type:
None
- planned_control: carla.VehicleControl
- exception classes.exceptions.EmergencyStopException(hazards: set[Hazard], *args: object)
Bases:
LunaticAgentException
- exception classes.exceptions.UpdatedPathException
Bases:
LunaticAgentExceptionShould be raised when the path has been updated and the agent should replan.
Rules that replan on Phase.DONE | END, should throw this exception at the end.
- exception classes.exceptions._RuleResultException(result: Any = RuleResult.NO_RESULT, *args: object)
Bases:
LunaticAgentExceptionAbstract class for exceptions that can be raised by rules, but still are able to return a result.
- exception classes.exceptions.NoFurtherRulesException(result: Any = RuleResult.NO_RESULT, *args: object)
Bases:
_RuleResultExceptionRaised when no further rules should be executed in this phase.
Caught by
LunaticAgent.execute_phase().The agent will continue at the phase where the
BlockedRulewas triggered.
- exception classes.exceptions.DoNotEvaluateChildRules(result: Any = RuleResult.NO_RESULT, *args: object)
Bases:
_RuleResultExceptionCan be raised in a
MultiRuleto prevent the evaluation of child rules.Can also be raised by child rules to prevent the evaluation of further child rules.
- exception classes.exceptions.UnblockRuleException(result: Any = RuleResult.NO_RESULT, *args: object)
Bases:
_RuleResultExceptionCan be raised in a
BlockedRuleto end it.The agent will continue at the phase where the
BlockedRulewas triggered.Note
Further rules that are in this phase can still be executed. Alternatively, consider raising a
NoFurtherRulesException.
classes.hud module
Example of automatic vehicle control from client side
Based on original CARLA example by German Ros
- classes.hud.get_actor_display_name(actor: carla.Actor, truncate: int = 250)
Method to get actor display name
- Parameters:
actor (carla.Actor)
truncate (int)
- class classes.hud.HUD(width: int, height: int, world: carla.World, help_text: str | None = RSSKeyboardControl.__doc__)
Bases:
objectClass for HUD text
- Parameters:
width (int)
height (int)
world (carla.World)
help_text (str | None)
- __init__(width: int, height: int, world: carla.World, help_text: str | None = RSSKeyboardControl.__doc__)
Constructor method
- Parameters:
width (int)
height (int)
world (carla.World)
help_text (str | None)
- on_world_tick(timestamp: carla.WorldSnapshot)
Gets informations from the world at every tick
- Parameters:
timestamp (carla.WorldSnapshot)
- tick(world: WorldModel, clock: pygame.time.Clock, obstacles: Iterable[carla.Actor] | None = None)
HUD method for every tick
If obstacles is passed these will be displayed in the HUD, if not the closest vehicles will be displayed.
- Parameters:
world (WorldModel)
clock (pygame.time.Clock)
obstacles (Iterable[carla.Actor] | None)
- toggle_info()
Toggle info on or off
- render(display: pygame.Surface)
Render for HUD class
- Parameters:
display (pygame.Surface)
- class classes.hud.FadingText(font: pygame.font.Font, dim: tuple[int, int], pos: tuple[int, int])
Bases:
objectClass for fading text
- tick(clock: pygame.time.Clock)
Fading text method for every tick
- Parameters:
clock (pygame.time.Clock)
- render(display: pygame.Surface)
Render fading text method
- Parameters:
display (pygame.Surface)
- class classes.hud.HelpText(font: pygame.font.Font, width: int, height: int, doc: str | bool | None = None)
Bases:
objectHelper class to handle text output using pygame
- Parameters:
font (pygame.font.Font)
width (int)
height (int)
- __init__(font: pygame.font.Font, width: int, height: int, doc: str | bool | None = None)
Constructor method
- Parameters:
font (pygame.font.Font)
width (int)
height (int)
- toggle()
Toggle on or off the render help
- render(display: pygame.Surface)
Render help text method
- Parameters:
display (pygame.Surface)
classes.keyboard_controls module
- class classes.keyboard_controls.KeyboardControl(world: WorldModel, help_notice=True)
Bases:
objectPrimitive base for keyboard control classes.
H/? : toggle help
- Parameters:
world (WorldModel)
- __init__(world: WorldModel, help_notice=True)
- Parameters:
world (WorldModel) – WorldModel
help_notice – bool Show a notice about the help keys.
- classmethod get_docstring()
Return the docstring of the class
- class classes.keyboard_controls.PassiveKeyboardControl(world: WorldModel, help_notice=True)
Bases:
KeyboardControlDoes not allow to control the vehicle. Only allows to quit the simulation.
ESC : quit H/? : toggle help
- Parameters:
world (WorldModel)
- parse_events()
Parse the input events and return True if the loop should end.
- __init__(world: WorldModel, help_notice=True)
- Parameters:
world (WorldModel) – WorldModel
help_notice – bool Show a notice about the help keys.
- classmethod get_docstring()
Return the docstring of the class
- class classes.keyboard_controls.RSSKeyboardControl(world_model: WorldModel, start_in_autopilot: bool, agent_controlled: bool = True, clock: pygame.time.Clock = None, config=None)
Bases:
KeyboardControlUse ARROWS, WASD keys or mouse click and drag for control.
W : throttle S : brake AD : steer Q : toggle reverse Space : hand-brake P : toggle autopilot (depends on setup)
TAB : change view Backspace : change vehicle (will unset externalActor; experimental)
R : toggle recording images to disk
F2 : toggle RSS visualization mode F3 : increase log level F4 : decrease log level F5 : increase map log level F6 : decrease map log level B : toggle RSS Road Boundaries Mode G : RSS check drop current route (experimental) S : toggle RSS (NotImplemented) T : toggle vehicle’s telemetry visualization O : open/close vehicle’s doors N : pause simulation (not in sync mode)
—Experimental, recording –
CTRL + R : toggle recording of simulation (replacing any previous) CTRL + P : start replaying last recorded simulation (untested) CTRL + + : increments the start time of the replay by 1 second (+SHIFT = 10 seconds) CTRL + - : decrements the start time of the replay by 1 second (+SHIFT = 10 seconds)
F1 : toggle HUD H/? : toggle help ESC : quit
- Parameters:
world_model (WorldModel)
start_in_autopilot (bool)
agent_controlled (bool)
clock (pygame.time.Clock)
- MOUSE_STEERING_RANGE = 150
Controls the size of steering area when using the mouse.
- __init__(world_model: WorldModel, start_in_autopilot: bool, agent_controlled: bool = True, clock: pygame.time.Clock = None, config=None)
- Parameters:
world – WorldModel
help_notice – bool Show a notice about the help keys.
world_model (WorldModel)
start_in_autopilot (bool)
agent_controlled (bool)
clock (pygame.time.Clock)
- property controlled_externally
- render(display: pygame.Surface) None
- Parameters:
display (pygame.Surface)
- Return type:
None
- classmethod get_docstring()
Return the docstring of the class
- parse_events(control: carla.VehicleControl | None = None)
Parse the input events and return True if the loop should end.
- Parameters:
control (Optional[carla.VehicleControl])
classes.rule module
- class classes.rule.Context(*args: Any, **kwargs: Any)
Bases:
CarlaDataProviderObject to be passed as the first argument (instead of self) to rules, actions and evaluation functions.
The
Contextclass derives from the scenario runner’sCarlaDataProviderto allow access to the world, map, etc.Tip
There is normally no need to initialize the context object manually. Its recommended to initialize the context object with
LunaticAgent._make_context().- Parameters:
agent (LunaticAgent)
kwargs (Any)
- last_context: 'Context' | None
The context object of the last tick. Used to access the last phase’s results.
- second_pass: bool | None = None
Whether or not the run_step function performs a second pass, i.e. after the route has been replanned.
Warning
The correctness should not be assumed. The user is responsible for setting this value to True if a second pass is required.
- PHASE_NOT_EXECUTED: object
Value in
phase_resultsto indicate thatagent.execute_phase(phase)was called for the respective phase
- agent: LunaticAgent
Backreference to the agent.
- phase_results: Dict[Phase, Any]
Stores the results of the phases the agent has been in. By default the keys are set to
Context.PHASE_NOT_EXECUTED.
- config: ContextSettings
A copy of the agents config. Overwritten by the condition’s settings.
- detected_hazards_info: Dict[Hazard, HazardSeverity | Any]
Information about the detected hazards.
add_hazard()inserts the givenHazardSeverityas value, however, note that the values are can be arbitrary if used otherwise.
- evaluation_results: Dict[Phase, Hashable]
Stores the result from the
Rule.condition()of the last rule that was evaluated in a phase.Deprecated since version in: consideration
- action_results: Dict[Phase, Any]
Stores the result from the
action()of the last rule that was applicable in a phase.Deprecated since version in: consideration
- property control: carla.VehicleControl | None
Current control the agent should use. Set by
execute_phase(update_controls=...).Note
Safeguarded to be not set to None. Setting it to
Noneis discouraged. Useset_control()if setting it toNoneis really needed.
- set_control(control: carla.VehicleControl | None)
Set the control, allows to set it to None.
- Parameters:
control (Optional[carla.VehicleControl])
- get_or_calculate_control() carla.VehicleControl
Get the control if it is set, otherwise calculate it by executing the local planner.
- Returns:
The control the agent should use.
- Return type:
Note
Use this function inside rules to acquire a control object-
Warning
This is equivalent to ending the inner step of the agent.
See also
LunaticAgent._calculate_control
- property detected_hazards: Set[Hazard]
Detected hazards in the current phase.
If not empty at the end of the inner step an EmergencyStopException is raised.
- add_hazard(hazard: Hazard, hazard_level: HazardSeverity = HazardSeverity.EMERGENCY)
Add the specified hazard to the detected hazards, in parallel the hazard_level can be set which which is stored in
detected_hazards_info.- Parameters:
hazard (Hazard)
hazard_level (HazardSeverity)
- discard_hazard(hazard: Hazard, match: Literal['exact', 'subset', 'intersection'] = 'subset')
Discards a hazard from the detected hazards.
- Parameters:
hazard (Hazard) – Hazard to remove from
detected_hazards.match (Literal['exact', 'subset', 'intersection']) –
How to match the hazard to remove.
”exact” removes if the exact
Hazardflag is present.”subset” removes if the hazard is a subset of the detected hazard, e.g.:
discard_hazard(Hazard.VEHICLE, match="subset")would removeHazard.OBSTACLE=Hazard.VEHICLE | PEDESTRIAN | STATIC_OBSTACLE.discard_hazard(Hazard.TRAFFIC_LIGHT, match="subset")would not removeHazard.TRAFFIC_LIGHT_RED.
- has_hazard(hazard: Hazard, match: Literal['exact', 'subset', 'intersection'] = 'intersection') bool
Checks if the hazard intersects with any of the detected hazards.
See
discard_hazard()for the different matching options.
- max_detection_distance(lane: Literal['same_lane', 'other_lane', 'overtaking', 'tailgating']) float
Convenience function to be used with
lunatic_agent_tools.detect_vehicles()andLunaticAgent.detect_obstacles_in_path.The max distance to consider an obstacle is calculated as:
max(obstacles.min_proximity_threshold, live_info.current_speed_limit / obstacles.speed_detection_downscale.[same|other]_lane)
- Parameters:
self (Union['Context', 'LunaticAgent']) – An object that implements the config and live_info attributes
lane (Literal['same_lane', 'other_lane', 'overtaking', 'tailgating']) – The lane to consider.
- Return type:
Note
lane must be a key in
BehaviorAgentObstacleSettings.SpeedLimitDetectionDownscale.
- property live_info: LiveInfo
- property active_blocking_rules: Set[BlockingRule]
- classes.rule.always_execute(ctx: classes.rule.Context) Literal[True]
This is an
ConditionFunctionthat always returnsTrue. It can be used to always execute an action.- Parameters:
ctx (classes.rule.Context)
- Return type:
Literal[True]
- class classes.rule.Rule(phases: Phase | Iterable[Phase] | None | 'type[Any]' | Self | str | None = None, bases: tuple[type[Any], ...] | None = None, clsdict: dict[str, Any] | None = None, **kwargs: Any)
Bases:
_GroupRule- Parameters:
- _auto_init_: ClassVar[bool] = True
If set to False the automatic
__init__creation is disabled when subclassing. This automatic__init__will fix parameters likephasesandconditionto the class.Declaring an
__init__method in the class has the same effect as setting_auto_init_to False.Note
Using
class NewRuleType(metarule=Rule)is nearly equivalent to_auto_init_=False, but is not inherited.
- NOT_APPLICABLE: ClassVar[Literal[RuleResult.NOT_APPLICABLE]]
Unique object
RuleResult.NOT_APPLICABLEthat indicates that no action was executed.Deprecated since version Use:
RuleResult.NOT_APPLICABLEdirectly
- NO_RESULT: ClassVar[Literal[RuleResult.NO_RESULT]]
Unique object
RuleResult.NO_RESULTthat indicates that the rulesaction()did not return a result, e.g. because an exception was raised.Deprecated since version Use:
RuleResult.NOT_APPLICABLEdirectly
- action: Annotated[CallableAction[Self, [], Any], 'attribute not available on instance -> merged into `actions`']
Action that should be executed if the rule is True. If actions is set, this is ignored.
- false_action: Annotated[CallableAction[Self, [], Any], 'attribute not available on instance -> merged into `actions`']
Action that should be executed if the rule is False. May not be set if actions is set.
- clone()
Create a new instance of the rule with the same settings.
Note
The current cooldown is not taken into account.
The current enabled state is taken into account.
- class CooldownFramework
Bases:
objectContext manager that can reduce all cooldowns at the end of a with statement.
- static tick()
Update all cooldowns and unblock all rules.
- DEFAULT_COOLDOWN_RESET: ClassVar[int] = 0
Value the cooldown is reset to when
reset_cooldown()is called without a value.Used only when
cooldown_reset_valueis not set.
- blocked: bool = False
Indicates if the rule is blocked for this tick only. Is reset to False after the tick.
- property cooldown: int
Cooldown of the rule in ticks until it can be executed again after its action was executed. If 0 the rule is ready to be executed.
- property enabled: bool
If
Falsethe rule will not be evaluated. Contrary toblockedthis permanently disables the rule.
- group: str | None = None
Group name of rules that should share their cooldown.
None for a rule to not share its cooldown.
- reset_cooldown(value: int | None = None)
Reset or set the cooldown; for a group rule it resets the group cooldown.
- Parameters:
value (Optional[int])
- set_active(value: bool)
Enables or disables the rule. Contrary to
blockedit will not be reset after the tick.- Parameters:
value (bool)
- classmethod set_cooldown_of_group(group: str, value: int)
Updates the cooldown of the specified group to a specific value
- set_my_group_cooldown(value: int | None = None)
Update the cooldown of the group this rule belong to
- Parameters:
value (Optional[int])
- start_cooldown: ClassVar[int] = 0
Initial
cooldownwhen initialized. if >0 the rule will not be ready for the first start_cooldown ticks.
- classmethod unblock_all_rules()
Unblocks all rules
- classmethod update_all_cooldowns()
Globally updates the cooldown of all rules.
- phases: FrozenSet[Phase]
The phase or phases in which the rule should be evaluated. For instantiation the phases attribute can be any Iterable [
Phase].
- condition: Any
The condition that determines if the rule’s actions should be executed.
- Simple Variant:
return True if the action should be executed, False otherwise. if
Rule.false_actionis defined, False will executeRule.false_action.- Advanced Variant:
return a Hashable value that is used as key in the
actionsdict.
- actions: Dict[Any, CallableAction[Self, [], Any]]
Dictionary that maps rule results to the action that should be executed.
- priority: float | int | RulePriority = 4
Rules are executed in order of their priority, from high to low.
- overwrite_settings: Dict[str, Any]
Settings that should overwrite the agent’s settings for this rule.
Note
The overwrite settings are primitive
dictobjects,omegaconf.DictConfigobjects are converted.
- self_config: RuleConfig
A custom sub-config for the rule that is not included in the agents settings. Automatically gets a instance key added with the rule instance.
Can be accessed via ctx.config.current_rule or self.config.self.
Note
Internally self.config and ctx.config is the same object, which makes interpolations to the agent’s settings possible.
Attention
The self_config object is *not* constant it is recreated each time the rule is evaluated to have the current context available.
- execute_phase(phase: Phase, *, prior_results: Any = None, update_controls: carla.VehicleControl | None = None)
Attention
Use with care to avoid loops or recursions.
If a
Contextis available prefer usingctx.agent.execute_phaseinstead.
Helper function to execute a phase from within a rule, wrapper of
agents.lunatic_agent.LunaticAgent.execute_phase().- Warns:
ReferenceError – If the weak proxy pointing to the
Contextobject has been deleted. The phase will not be executed.- Parameters:
phase (Phase)
prior_results (Any)
update_controls (Optional[carla.VehicleControl])
See also
- evaluate_children(ctx: classes.rule.Context) NoReturn
Not implemented for this rule class.
Note
This is an interface function of meta rules that is executed during
__call__()to call further rules.- Parameters:
ctx (classes.rule.Context)
- Return type:
- __call__(ctx: Context, overwrite: Dict[str, Any] | None = None, *, ignore_phase: bool = False, ignore_cooldown: bool = False)
First checks if the rule is applicable, i.e. is its
cooldown == 0, if not returnsNOT_APPLICABLE.- Afterwards evaluates the rules
condition()function. if the result is not in
actionsreturnsNOT_APPLICABLE.otherwise merges the
overwrite_settingswith the py:attr:.Context.config and executes the action.
- Afterwards evaluates the rules
- Parameters:
ctx (Context) – The context object that is passed to the condition function.
overwrite (Optional[Dict[str, Any]]) – Extends
overwrite_settingsfor this call only. Defaults toNone.ignore_phase (bool) – If
Truethe phase check is skipped. Defaults toFalse.ignore_cooldown (bool) – If True the cooldown check is skipped. Defaults to
False.
- class classes.rule.BlockingRule(phases: Phase | Iterable[Phase] | None | 'type[Any]' | Self | str | None = None, bases: tuple[type[Any], ...] | None = None, clsdict: dict[str, Any] | None = None, **kwargs: Any)
Bases:
RuleThis meta rule allows to define rules that are able to takeover the agent’s workflow and apply the
VehicleControldirectly from withhin the rule.- Parameters:
condition (Optional[ConditionFunctionLikeT])
action (Optional[Union[classes.type_protocols.CallableActionT[Self, []], Dict[Any, classes.type_protocols.CallableActionT[Self, []]]]])
false_action (Optional[classes.type_protocols.CallableActionT[Self, []]])
gameframework (Optional[GameFramework])
actions (Optional[Dict[Any, classes.type_protocols.CallableActionT[Rule, []]]])
description (str)
overwrite_settings (Optional[Dict[str, Any]])
self_config (Optional[Dict[str, Any]])
priority (RulePriority)
cooldown_reset_value (Optional[int])
group (Optional[str])
enabled (bool)
- DEFAULT_COOLDOWN_RESET: ClassVar[int] = 0
Value the cooldown is reset to when
reset_cooldown()is called without a value.Used only when
cooldown_reset_valueis not set.
- _auto_init_: ClassVar[bool] = True
If set to False the automatic
__init__creation is disabled when subclassing. This automatic__init__will fix parameters likephasesandconditionto the class.Declaring an
__init__method in the class has the same effect as setting_auto_init_to False.Note
Using
class NewRuleType(metarule=Rule)is nearly equivalent to_auto_init_=False, but is not inherited.
- blocked: bool = False
Indicates if the rule is blocked for this tick only. Is reset to False after the tick.
- property cooldown: int
Cooldown of the rule in ticks until it can be executed again after its action was executed. If 0 the rule is ready to be executed.
- property enabled: bool
If
Falsethe rule will not be evaluated. Contrary toblockedthis permanently disables the rule.
- evaluate_children(ctx: classes.rule.Context) NoReturn
Not implemented for this rule class.
Note
This is an interface function of meta rules that is executed during
__call__()to call further rules.- Parameters:
ctx (classes.rule.Context)
- Return type:
- execute_phase(phase: Phase, *, prior_results: Any = None, update_controls: carla.VehicleControl | None = None)
Attention
Use with care to avoid loops or recursions.
If a
Contextis available prefer usingctx.agent.execute_phaseinstead.
Helper function to execute a phase from within a rule, wrapper of
agents.lunatic_agent.LunaticAgent.execute_phase().- Warns:
ReferenceError – If the weak proxy pointing to the
Contextobject has been deleted. The phase will not be executed.- Parameters:
phase (Phase)
prior_results (Any)
update_controls (Optional[carla.VehicleControl])
See also
- group: str | None = None
Group name of rules that should share their cooldown.
None for a rule to not share its cooldown.
- priority: float | int | RulePriority = 4
Rules are executed in order of their priority, from high to low.
- reset_cooldown(value: int | None = None)
Reset or set the cooldown; for a group rule it resets the group cooldown.
- Parameters:
value (Optional[int])
- set_active(value: bool)
Enables or disables the rule. Contrary to
blockedit will not be reset after the tick.- Parameters:
value (bool)
- set_my_group_cooldown(value: int | None = None)
Update the cooldown of the group this rule belong to
- Parameters:
value (Optional[int])
- start_cooldown: ClassVar[int] = 0
Initial
cooldownwhen initialized. if >0 the rule will not be ready for the first start_cooldown ticks.
- phases: FrozenSet[Phase]
The phase or phases in which the rule should be evaluated. For instantiation the phases attribute can be any Iterable [
Phase].
- actions: Dict[Any, CallableAction[Self, [], Any]]
Dictionary that maps rule results to the action that should be executed.
- action: Annotated[CallableAction[Self, [], Any], 'attribute not available on instance -> merged into `actions`']
Action that should be executed if the rule is True. If actions is set, this is ignored.
- false_action: Annotated[CallableAction[Self, [], Any], 'attribute not available on instance -> merged into `actions`']
Action that should be executed if the rule is False. May not be set if actions is set.
- overwrite_settings: Dict[str, Any]
Settings that should overwrite the agent’s settings for this rule.
Note
The overwrite settings are primitive
dictobjects,omegaconf.DictConfigobjects are converted.
- self_config: RuleConfig
A custom sub-config for the rule that is not included in the agents settings. Automatically gets a instance key added with the rule instance.
Can be accessed via ctx.config.current_rule or self.config.self.
Note
Internally self.config and ctx.config is the same object, which makes interpolations to the agent’s settings possible.
Attention
The self_config object is *not* constant it is recreated each time the rule is evaluated to have the current context available.
- condition: Any
The condition that determines if the rule’s actions should be executed.
- Simple Variant:
return True if the action should be executed, False otherwise. if
Rule.false_actionis defined, False will executeRule.false_action.- Advanced Variant:
return a Hashable value that is used as key in the
actionsdict.
- MAX_TICKS = 5000
The amount of ticks that can be performed by this rule before it is automatically disabled. If the rule has looped for this amount of ticks if will then call
max_tick_callbackand raise anUnblockRuleExceptionafterwards.As a hack
max_tick_callbackcan changeticks_passedto prevent the exception and continue the rule.
- max_tick_callback: Callable[[Self, Context], Any] | None = None
An optional callback that is executed when
ticks_passedreachesMAX_TICKS.
- loop_agent(ctx: Context, control: carla.VehicleControl | None = None, *, execute_planner: bool, execute_phases: Any = True) carla.VehicleControl | None
A combination of LunaticAgent.parse_keyboard_input, LunaticAgent.apply_control, BlockingRule.update_world, and Context.get_or_calculate_control to advance agent and world.
- Parameters:
- Return type:
carla.VehicleControl | None
See also
Executes the following methods:
BlockingRule.update_world()ticks thecarla.Worldand renders everything.Context.get_or_calculate_control()to acquire thecarla.VehicleControlobject.
- static get_world() carla.World
Method to access the world object
- Return type:
- update_world(ctx: Context, *, execute_phases: bool | Container[Phase] = True) carla.VehicleControl | None
Ticks the world and takes care of the rendering.
- Will call
ctx.agent.execute_phase(Phase.CUSTOM_CYCLE | Phase.BEGIN, prior_results=<this Rule instance>)LunaticAgent.update_information(), with or without executing the phases, depending on execute_phases.
- Parameters:
- Raises:
UnblockRuleException – If the ticks passed are over
MAX_TICKS- Return type:
carla.VehicleControl | None
Attention
The usage with Leaderboard is working but experimental. The scenario expects the agent to return a control object in every step, however as this rule takes over the ticks completely an outside ScenarioManager might not work as expected.
- __call__(ctx: Context, overwrite: Dict[str, Any] | None = None, in_loop: bool = False, *, ignore_phase: bool = False, ignore_cooldown: bool = False) Any | Literal[RuleResult.NOT_APPLICABLE]
First checks if the rule is applicable, i.e. is its
cooldown == 0, if not returnsNOT_APPLICABLE.- Afterwards evaluates the rules
condition()function. if the result is not in
actionsreturnsNOT_APPLICABLE.otherwise merges the
overwrite_settingswith the py:attr:.Context.config and executes the action.
- Afterwards evaluates the rules
- Parameters:
ctx (Context) – The context object that is passed to the condition function.
overwrite (Optional[Dict[str, Any]]) – Extends
overwrite_settingsfor this call only. Defaults toNone.ignore_phase (bool) – If
Truethe phase check is skipped. Defaults toFalse.ignore_cooldown (bool) – If True the cooldown check is skipped. Defaults to
False.in_loop (bool)
- Return type:
Union[Any, Literal[RuleResult.NOT_APPLICABLE]]
- class classes.rule.MultiRule(phases: Phase | Iterable[Phase] | None | 'type[Any]' | Self | str | None = None, bases: tuple[type[Any], ...] | None = None, clsdict: dict[str, Any] | None = None, **kwargs: Any)
Bases:
Rule- Parameters:
rules (List[Rule])
condition (Optional[ConditionFunctionLikeT])
description (str)
priority (RulePriority)
sort_rules (bool)
execute_all_rules (bool)
action (Optional[Callable[[Context], Any]])
ignore_phase (bool)
overwrite_settings (Optional[Dict[str, Any]])
self_config (Optional[Dict[str, Any]])
cooldown_reset_value (Optional[int])
group (Optional[str])
enabled (bool)
- DEFAULT_COOLDOWN_RESET: ClassVar[int] = 0
Value the cooldown is reset to when
reset_cooldown()is called without a value.Used only when
cooldown_reset_valueis not set.
- __call__(ctx: Context, overwrite: Dict[str, Any] | None = None, *, ignore_phase: bool = False, ignore_cooldown: bool = False)
First checks if the rule is applicable, i.e. is its
cooldown == 0, if not returnsNOT_APPLICABLE.- Afterwards evaluates the rules
condition()function. if the result is not in
actionsreturnsNOT_APPLICABLE.otherwise merges the
overwrite_settingswith the py:attr:.Context.config and executes the action.
- Afterwards evaluates the rules
- Parameters:
ctx (Context) – The context object that is passed to the condition function.
overwrite (Optional[Dict[str, Any]]) – Extends
overwrite_settingsfor this call only. Defaults toNone.ignore_phase (bool) – If
Truethe phase check is skipped. Defaults toFalse.ignore_cooldown (bool) – If True the cooldown check is skipped. Defaults to
False.
- _auto_init_: ClassVar[bool] = True
If set to False the automatic
__init__creation is disabled when subclassing. This automatic__init__will fix parameters likephasesandconditionto the class.Declaring an
__init__method in the class has the same effect as setting_auto_init_to False.Note
Using
class NewRuleType(metarule=Rule)is nearly equivalent to_auto_init_=False, but is not inherited.
- blocked: bool = False
Indicates if the rule is blocked for this tick only. Is reset to False after the tick.
- property cooldown: int
Cooldown of the rule in ticks until it can be executed again after its action was executed. If 0 the rule is ready to be executed.
- property enabled: bool
If
Falsethe rule will not be evaluated. Contrary toblockedthis permanently disables the rule.
- execute_phase(phase: Phase, *, prior_results: Any = None, update_controls: carla.VehicleControl | None = None)
Attention
Use with care to avoid loops or recursions.
If a
Contextis available prefer usingctx.agent.execute_phaseinstead.
Helper function to execute a phase from within a rule, wrapper of
agents.lunatic_agent.LunaticAgent.execute_phase().- Warns:
ReferenceError – If the weak proxy pointing to the
Contextobject has been deleted. The phase will not be executed.- Parameters:
phase (Phase)
prior_results (Any)
update_controls (Optional[carla.VehicleControl])
See also
- group: str | None = None
Group name of rules that should share their cooldown.
None for a rule to not share its cooldown.
- priority: float | int | RulePriority = 4
Rules are executed in order of their priority, from high to low.
- reset_cooldown(value: int | None = None)
Reset or set the cooldown; for a group rule it resets the group cooldown.
- Parameters:
value (Optional[int])
- set_active(value: bool)
Enables or disables the rule. Contrary to
blockedit will not be reset after the tick.- Parameters:
value (bool)
- set_my_group_cooldown(value: int | None = None)
Update the cooldown of the group this rule belong to
- Parameters:
value (Optional[int])
- start_cooldown: ClassVar[int] = 0
Initial
cooldownwhen initialized. if >0 the rule will not be ready for the first start_cooldown ticks.
- phases: FrozenSet[Phase]
The phase or phases in which the rule should be evaluated. For instantiation the phases attribute can be any Iterable [
Phase].
- actions: Dict[Any, CallableAction[Self, [], Any]]
Dictionary that maps rule results to the action that should be executed.
- action: Annotated[CallableAction[Self, [], Any], 'attribute not available on instance -> merged into `actions`']
Action that should be executed if the rule is True. If actions is set, this is ignored.
- false_action: Annotated[CallableAction[Self, [], Any], 'attribute not available on instance -> merged into `actions`']
Action that should be executed if the rule is False. May not be set if actions is set.
- overwrite_settings: Dict[str, Any]
Settings that should overwrite the agent’s settings for this rule.
Note
The overwrite settings are primitive
dictobjects,omegaconf.DictConfigobjects are converted.
- self_config: RuleConfig
A custom sub-config for the rule that is not included in the agents settings. Automatically gets a instance key added with the rule instance.
Can be accessed via ctx.config.current_rule or self.config.self.
Note
Internally self.config and ctx.config is the same object, which makes interpolations to the agent’s settings possible.
Attention
The self_config object is *not* constant it is recreated each time the rule is evaluated to have the current context available.
- condition: Any
The condition that determines if the rule’s actions should be executed.
- Simple Variant:
return True if the action should be executed, False otherwise. if
Rule.false_actionis defined, False will executeRule.false_action.- Advanced Variant:
return a Hashable value that is used as key in the
actionsdict.
- evaluate_children(ctx: classes.rule.Context) List[Any] | Any
Evaluates the children rules of the current rule in the given context.
- Parameters:
ctx (classes.rule.Context) – The context in which the child rules are evaluated.
- Returns:
The results of evaluating the children rules. Returns a list of results if execute_all_rules is True, otherwise the result of the first rule that was applied.
- Return type:
- class classes.rule.RandomRule(phases: Phase | Iterable[Phase] | None | 'type[Any]' | Self | str | None = None, bases: tuple[type[Any], ...] | None = None, clsdict: dict[str, Any] | None = None, **kwargs: Any)
Bases:
MultiRuleA rule that selects and evaluates one or more random child rules from a set of rules.
- Parameters:
phases (Union[Phase, Iterable[Phase]]) – The phase or phases in which the rule is applicable.
rules (Union[Dict[Rule, float], List[Rule]]) – The set of rules from which to select random child rules.
repeat_if_not_applicable (bool) – If False, only one rule will be evaluated even if it is not applicable. Defaults to
True.condition (Optional[Callable[[Context], Any]]) – A callable that determines if the rule is applicable in a given context. If None and the rule does not implement a
conditionattribute the rule always executes. Defaults toNone.action (Optional[Callable[[Context], Any]]) – A callable that defines the action to be performed when the rule is applicable. Defaults to
None.ignore_phase (bool) – If True, the rule will be evaluated even if it is not in the specified phase. Defaults to
True.priority (RulePriority) – The priority of the rule.
RulePriority.NORMAL.description (str) – A description of the rule. Defaults to
"If its own condition is true calls one or more random child rules from the passed rules.".overwrite_settings (Optional[Dict[str, Any]]) – A dictionary of settings to overwrite the default settings of the rule. Defaults to
None.cooldown_reset_value (Optional[int]) – The value to reset the cooldown of the rule. Defaults to
None.group (Optional[str]) – The group to which the rule belongs. Defaults to
None.enabled (bool) – If False, the rule will not be evaluated. Defaults to
True.weights (Optional[List[float]]) – The weights associated with each rule when selecting random child rules. Defaults to
None.self_config (Optional[Dict[str, Any]])
- Raises:
ValueError – When passing rules as a dict with weights, the weights argument must be None.
- DEFAULT_COOLDOWN_RESET: ClassVar[int] = 0
Value the cooldown is reset to when
reset_cooldown()is called without a value.Used only when
cooldown_reset_valueis not set.
- __call__(ctx: Context, overwrite: Dict[str, Any] | None = None, *, ignore_phase: bool = False, ignore_cooldown: bool = False)
First checks if the rule is applicable, i.e. is its
cooldown == 0, if not returnsNOT_APPLICABLE.- Afterwards evaluates the rules
condition()function. if the result is not in
actionsreturnsNOT_APPLICABLE.otherwise merges the
overwrite_settingswith the py:attr:.Context.config and executes the action.
- Afterwards evaluates the rules
- Parameters:
ctx (Context) – The context object that is passed to the condition function.
overwrite (Optional[Dict[str, Any]]) – Extends
overwrite_settingsfor this call only. Defaults toNone.ignore_phase (bool) – If
Truethe phase check is skipped. Defaults toFalse.ignore_cooldown (bool) – If True the cooldown check is skipped. Defaults to
False.
- _auto_init_: ClassVar[bool] = True
If set to False the automatic
__init__creation is disabled when subclassing. This automatic__init__will fix parameters likephasesandconditionto the class.Declaring an
__init__method in the class has the same effect as setting_auto_init_to False.Note
Using
class NewRuleType(metarule=Rule)is nearly equivalent to_auto_init_=False, but is not inherited.
- blocked: bool = False
Indicates if the rule is blocked for this tick only. Is reset to False after the tick.
- property cooldown: int
Cooldown of the rule in ticks until it can be executed again after its action was executed. If 0 the rule is ready to be executed.
- property enabled: bool
If
Falsethe rule will not be evaluated. Contrary toblockedthis permanently disables the rule.
- execute_phase(phase: Phase, *, prior_results: Any = None, update_controls: carla.VehicleControl | None = None)
Attention
Use with care to avoid loops or recursions.
If a
Contextis available prefer usingctx.agent.execute_phaseinstead.
Helper function to execute a phase from within a rule, wrapper of
agents.lunatic_agent.LunaticAgent.execute_phase().- Warns:
ReferenceError – If the weak proxy pointing to the
Contextobject has been deleted. The phase will not be executed.- Parameters:
phase (Phase)
prior_results (Any)
update_controls (Optional[carla.VehicleControl])
See also
- group: str | None = None
Group name of rules that should share their cooldown.
None for a rule to not share its cooldown.
- priority: float | int | RulePriority = 4
Rules are executed in order of their priority, from high to low.
- reset_cooldown(value: int | None = None)
Reset or set the cooldown; for a group rule it resets the group cooldown.
- Parameters:
value (Optional[int])
- set_active(value: bool)
Enables or disables the rule. Contrary to
blockedit will not be reset after the tick.- Parameters:
value (bool)
- set_my_group_cooldown(value: int | None = None)
Update the cooldown of the group this rule belong to
- Parameters:
value (Optional[int])
- start_cooldown: ClassVar[int] = 0
Initial
cooldownwhen initialized. if >0 the rule will not be ready for the first start_cooldown ticks.
- phases: FrozenSet[Phase]
The phase or phases in which the rule should be evaluated. For instantiation the phases attribute can be any Iterable [
Phase].
- condition: Any
The condition that determines if the rule’s actions should be executed.
- Simple Variant:
return True if the action should be executed, False otherwise. if
Rule.false_actionis defined, False will executeRule.false_action.- Advanced Variant:
return a Hashable value that is used as key in the
actionsdict.
- actions: Dict[Any, CallableAction[Self, [], Any]]
Dictionary that maps rule results to the action that should be executed.
- action: Annotated[CallableAction[Self, [], Any], 'attribute not available on instance -> merged into `actions`']
Action that should be executed if the rule is True. If actions is set, this is ignored.
- false_action: Annotated[CallableAction[Self, [], Any], 'attribute not available on instance -> merged into `actions`']
Action that should be executed if the rule is False. May not be set if actions is set.
- overwrite_settings: Dict[str, Any]
Settings that should overwrite the agent’s settings for this rule.
Note
The overwrite settings are primitive
dictobjects,omegaconf.DictConfigobjects are converted.
- self_config: RuleConfig
A custom sub-config for the rule that is not included in the agents settings. Automatically gets a instance key added with the rule instance.
Can be accessed via ctx.config.current_rule or self.config.self.
Note
Internally self.config and ctx.config is the same object, which makes interpolations to the agent’s settings possible.
Attention
The self_config object is *not* constant it is recreated each time the rule is evaluated to have the current context available.
- evaluate_children(ctx: Context, overwrite: Dict[str, Any] | None = None) Any
Evaluate a random child rule. If self.repeat_if_not_applicable=False and the randomly chosen rule is not applicable, then no further rules are evaluated For self.repeat_if_not_applicable=False possible rules are evaluated in a random fashion until one rule was applicable.
classes.type_protocols module
Helper library to define type protocols for classes and functions in the project.
See also
- class classes.type_protocols.RuleT
typing.TypeVar: A type variable for aRuletype.alias of TypeVar(‘RuleT’, bound=
Rule)- has_default()
- classes.type_protocols.CallableCondition
A generic type alias for a callable condition function to be used with a
ConditionFunction. Its first arguments must accept aRuleand aContext, or only aContext, additional keyword arguments are allowed. It must return a hashable value.alias of
Callable[[Concatenate[RuleT,Context,_CP]],_CH] |Callable[[Concatenate[Context,_CP]],_CH]
- classes.type_protocols.CallableAction
A generic type alias for a callable action function to be used with a
RuleorConditionFunction.register_action(). Its first arguments must accept aRuleand aContext, or only aContext, additional keyword arguments are allowed. It can return an arbitrary value.alias of
Callable[[Concatenate[RuleT,Context,_P]],_T] |Callable[[Concatenate[Context,_P]],_T]
- class classes.type_protocols.CallableT
typing.TypeVar: A type variable for a any callable.alias of TypeVar(‘CallableT’, bound=
Callable[[…],Any])- has_default()
- class classes.type_protocols.AgentConfigT
typing.TypeVar: A type variable for aAgentConfigtype.alias of TypeVar(‘AgentConfigT’, bound=
AgentConfig)- has_default()
- classes.type_protocols.ConditionFunctionLike = ConditionFunctionLike
Callable that can be used for
Rule.condition. A callable that uses aContextobject as a single argument, or alternatively aRuleand aContextobject (in this order).The function must return a Hashable value.
- classes.type_protocols.AnyConditionFunctionLike = AnyConditionFunctionLike
A generic type alias for a callable condition function to be used with a
Rule. Its first arguments must accept aRuleand aContext, or only aContext, additional keyword arguments are allowed. It must return a hashable value.
- classes.type_protocols.AnyCallableCondition
Non generic variant of
CallableCondition, can use used astyping.TypeAlias.alias of
Callable[[Concatenate[RuleT,Context, …]],Hashable] |Callable[[Concatenate[Context, …]],Hashable]
- class classes.type_protocols.CallableConditionT
typing.TypeVarvariant ofAnyCallableCondition.alias of TypeVar(‘CallableConditionT’, bound=
Callable[[Concatenate[RuleT,Context, …]],Hashable] |Callable[[Concatenate[Context, …]],Hashable])- has_default()
- classes.type_protocols.AnyCallableAction
Non generic variant of
CallableAction, can use used astyping.TypeAlias.alias of
Callable[[Concatenate[RuleT,Context, …]],Any] |Callable[[Concatenate[Context, …]],Any]
- class classes.type_protocols.CallableActionT
typing.TypeVarvariant ofAnyCallableAction.alias of TypeVar(‘CallableActionT’, bound=
Callable[[Concatenate[RuleT,Context, …]],Any] |Callable[[Concatenate[Context, …]],Any])- has_default()
- class classes.type_protocols.ConditionFunctionLikeT
TypeVarversion ofConditionFunctionLikealias of TypeVar(‘ConditionFunctionLikeT’, bound=
ConditionFunctionLike[Rule, …,Hashable])- has_default()
- class classes.type_protocols.HasBaseSettings(*args, **kwargs)
Bases:
Protocol[AgentConfigT]- BASE_SETTINGS: type[AgentConfigT]
- class classes.type_protocols.HasConfig(*args, **kwargs)
Bases:
Protocol[AgentConfigT]- config: AgentConfigT
- class classes.type_protocols.HasPlanner(*args, **kwargs)
Bases:
Protocol[_LocalPlannerT]Uses a Local planner to calculate controls
- _local_planner: _LocalPlannerT
- _calculate_control(debug: bool = False, *args, **kwargs) carla.VehicleControl
- Parameters:
debug (bool)
- Return type:
- class classes.type_protocols.HasPlannerWithConfig(*args, **kwargs)
Bases:
HasPlanner[DynamicLocalPlanner],HasConfig[AgentConfigT]- _calculate_control(debug: bool = False, *args, **kwargs) carla.VehicleControl
- Parameters:
debug (bool)
- Return type:
- _local_planner: _LocalPlannerT
- config: AgentConfigT
classes.worldmodel module
Interface classes between CARLA, the agent, and the user interface.
- class classes.worldmodel.AccessCarlaMixin
Bases:
objectMixin class that delegates the attributes
client,map, andworldto theCarlaDataProviderto keep them in sync.Note
This mixin only works for instances, they are not class attributes.
- property client: carla.Client
- property world: carla.World
- static get_blueprint_library() carla.BlueprintLibrary
Access to a cached version of the blueprint library
Attention
The world must be setup before (
set_world()) before this can be accessed.- Return type:
- class classes.worldmodel.GameFramework(*args: Any, **kwargs: Any)
Bases:
AccessCarlaMixin,CarlaDataProvider- Parameters:
args (LaunchConfig)
worker_threads (int)
- clock: ClassVar[pygame.time.Clock] = None
- display: ClassVar[pygame.Surface] = None
- classmethod quickstart(launch_config: LaunchConfig | None = None, *, logging=False) Self
Initializes Hydra in a limited way, i.e. does not allow for command line overrides.
Sets up the
carla.Clientand related instances as well as pygame.Note
It is recommended that you use a
@hydra.maindecorated main function instead to make full use of the Hydra framework.- Parameters:
launch_config (LaunchConfig | None) – The configuration to use. If
None, will use the default configuration from./conf/launch_config.yaml.logging – If True, change the how logging is done by applying the logger settings from
./conf/config_extensions/job_logging.yaml. Default isFalse.
- Returns:
The initialized
GameFrameworkinstance.- Return type:
Self
See also
- This function uses:
- static initialize_hydra(config_dir: str = './conf', config_name: str = 'launch_config', version_base=None, *, job_name='LunaticAgentJob', logging=True, structured=True) LaunchConfig
Use this function only if no hydra.main is available.
Usage:
args = GameFramework.initialize_hydra(config_dir=<abs_path_of_conf>, config_name="launch_config") game_framework = GameFramework(args)
- Parameters:
config_dir (str) – The directory where the hydra configuration is stored.
config_name (str) – The name of the configuration file.
version_base – The version base of hydra for the configuration. Default is None.
job_name – The name of the job.
logging – If True, will set up logging.
structured – If True will create the config based on
LaunchConfig, otherwise it will be based on adict. This is useful for runtime type-checks and conversions. If the configsLaunchConfig.strict_configvalue is < 2, this parameter is ignored. Disable if you experience problems. Default isTrue.
- Return type:
See also
- Hydra functions:
hydra.initialize_config_dir()hydra.compose()
- static load_hydra_config(config_name: str = 'conf/launch_config') LaunchConfig
- Parameters:
config_name (str)
- Return type:
- __init__(args: LaunchConfig, config=None, timeout=10.0, worker_threads: int = 0, *, map_layers=carla.MapLayer.All)
- Parameters:
args (LaunchConfig)
worker_threads (int)
- controller: weakref.ProxyType[RSSKeyboardControl] | RSSKeyboardControl
- traffic_manager: carla.TrafficManager | None = None
- static init_pygame(args: LaunchConfig | None = None, recreate=False)
- Parameters:
args (LaunchConfig | None)
- static init_carla(args: LaunchConfig | None = None, timeout=10.0, worker_threads: int = 0, *, map_layers=carla.MapLayer.All)
- Parameters:
args (LaunchConfig | None)
worker_threads (int)
- init_traffic_manager(port=None) carla.TrafficManager
- Return type:
- init_agent_and_interface(ego: carla.Vehicle | None, agent_class: type[LunaticAgent], config: LunaticAgentSettings | None = None, overwrites: Dict[str, Any] | None = None) tuple[LunaticAgent, WorldModel, GlobalRoutePlanner, RSSKeyboardControl]
Quick setup for the agent and the world model.
- Among others this executes:
from agents.lunatic_agent import LunaticAgent, LunaticAgentSettings ego = world.spawn_actor(world.get_blueprint_library().find("vehicle.audi.tt")) agent, world_model, global_planner, controller = ( game_framework.init_agent_and_interface(ego, LunaticAgent) )
- Parameters:
ego (carla.Vehicle | None) – The ego vehicle. Can be
Noneif the agent is set to use an external actor (LaunchConfig.externalActor).agent_class (type[LunaticAgent]) – The agent class to instantiate.
config (LunaticAgentSettings | None) – The configuration of the agent. If
Nonethe.agent_class.BASE_SETTINGSare used.overwrites (Dict[str, Any] | None) – Additional overwrites to the configuration.
- Return type:
tuple[LunaticAgent, WorldModel, GlobalRoutePlanner, RSSKeyboardControl]
- make_world_model(config: LunaticAgentSettings, player: carla.Vehicle | None = None) WorldModel
Creates a
WorldModelwith a backreference to the GameFramework.- Parameters:
config (LunaticAgentSettings)
player (carla.Vehicle | None)
- Return type:
- make_controller(world_model: WorldModel, controller_class: type[_ControllerClass] = RSSKeyboardControl, **kwargs)
Creates a keyboard controller and attaches it to the world model.
- Parameters:
world_model (WorldModel) – The world model to attach the controller to.
controller_class (type[_ControllerClass]) – The controller class to instantiate. Defaults to
RSSKeyboardControl.**kwargs – Additional arguments to pass to the controller.
- static hydra_initialized() bool
Checks wether Hydra is initialized. This is normally only done when the
@hydra.main()decorator is used.- Return type:
- static get_hydra_config(raw: Literal[False] = False) HydraConf
- static get_hydra_config(raw: Literal[True]) hydra.core.hydra_config.HydraConfig
Retrieves the Hydra configuration object.
- Parameters:
raw – If True, returns the
hydra.conf.HydraConfdataclass, otherwise thehydra.core.hydra_config.HydraConfigsingleton. Default isFalse.- Raises:
ValueError – If the HydraConfig was not set up yet and
raw=True.
- property launch_config
LaunchConfigobject that was used for the initialization (args)
- property agent_config
The configuration of the attached agent, if it exists otherwise the agent attribute of the stored
launch_config.
- parse_rss_controller_events(final_controls: carla.VehicleControl)
- Parameters:
final_controls (carla.VehicleControl)
- render_everything()
Update render and hud
- static skip_rest_of_loop(message='GameFramework.end_loop')
Terminates the current iteration and exits the GameFramework by raising a
ContinueLoopException.Note
It is the users responsibility to manage the agent & local planner before calling this function, i.e. that the agent has a
carla.VehicleControlset.- Raises:
- static destroy_actors(actors: Iterable[carla.Actor | CustomSensorInterface])
Destroys the given actors and customs sensors implemented in this package.
Removes destroyed actors from the
CarlaDataProvideractor pool.- Parameters:
actors (Iterable[carla.Actor | CustomSensorInterface])
- classmethod cleanup(*, disable_sync: bool = True, quit_pygame: bool = True)
Cleans up resources and actors.
- Parameters:
disable_sync (bool) – If True, will disable synchronous mode. This will prevent the freezing of the Unreal Editor. Default is True.
quit_pygame (bool) – If True, will call
pygame.quit(). Default is True.
Note
When called from an instance with an attached agent, the
agent.destroy()method is called.Otherwise will call
CarlaDataProvider.cleanup().
- exceptions: ModuleType
shortcut to
exceptionsmodule containing custom exceptions.
- property client: carla.Client
- static get_blueprint_library() carla.BlueprintLibrary
Access to a cached version of the blueprint library
Attention
The world must be setup before (
set_world()) before this can be accessed.- Return type:
- property world: carla.World
- class classes.worldmodel.WorldModel(*args: Any, **kwargs: Any)
Bases:
AccessCarlaMixin,CarlaDataProviderClass representing the surrounding environment.
This class is the interface between the agent, the , the
HUD, and theKeyboardControl. It handles ticking of the simulator and rendering of the pygame interface.If
LaunchConfig.externalActoris set, it will look for an actor with the role nameLaunchConfig.rolename, if such an actor does not yet exist it will wait for its creation until the calling script continues.- Parameters:
config (LunaticAgentSettings)
args (LaunchConfig | Mapping[str, Any] | os.PathLike[str] | str)
agent (LunaticAgent | None)
carla_world (carla.World | None)
player (carla.Vehicle | None)
map_inst (carla.Map | None)
- controller: RSSKeyboardControl | weakref.ProxyType[RSSKeyboardControl] | None = None
Set when controller is created. Uses weakref.proxy as backreference. This is not a
weakrefobject, whenwith gameframework(agent)is used.
- __init__(config: LunaticAgentSettings, args: LaunchConfig | Mapping[str, Any] | os.PathLike[str] | str = './conf/launch_config.yaml', agent: LunaticAgent | None = None, *, carla_world: carla.World | None = None, player: carla.Vehicle | None = None, map_inst: carla.Map | None = None)
Constructor method
- Parameters:
config (LunaticAgentSettings)
args (LaunchConfig | Mapping[str, Any] | os.PathLike[str] | str)
agent (LunaticAgent | None)
carla_world (carla.World | None)
player (carla.Vehicle | None)
map_inst (carla.Map | None)
- property world: carla.World
- world_settings
Object containing some data about the simulation such as synchrony between client and server or rendering mode.
- hud
The
HUDthat is managed.
- sync: bool | None
Set from
LaunchConfig.sync
- external_actor: bool
Set from
LaunchConfig.externalActor
- actor_role_name: str | None
Set from
LaunchConfig.rolename
- player: carla.Vehicle
The linked actor. If
external_actoris set this will be the first actor found with that role name.
- property client: carla.Client
- static get_blueprint_library() carla.BlueprintLibrary
Access to a cached version of the blueprint library
Attention
The world must be setup before (
set_world()) before this can be accessed.- Return type:
- rss_set_road_boundaries_mode(road_boundaries_mode: RssRoadBoundariesModeAlias | carla.RssRoadBoundariesMode | bool | None = None) None
Choose wether or not to use the RSS road boundaries feature.
Toggles:
RssSettings.use_stay_on_road_feature- Parameters:
road_boundaries_mode (RssRoadBoundariesModeAlias | carla.RssRoadBoundariesMode | bool | None)
- Return type:
None
- restart()
Restart the world and sets up the
HUDsensors. Ifplayeris not set orexternal_actoris set, looks for an actor with the role name, or spawns a new actor.
- tick_server_world() int | carla.WorldSnapshot | None
When
LaunchConfig.handle_ticksisTrueuses or depending onLaunchConfig.sync.- Return type:
int | carla.WorldSnapshot | None
- tick(clock: pygame.time.Clock)
Method for every tick
- Parameters:
clock (pygame.time.Clock)
- next_weather(reverse=False)
Get next weather setting
- next_map_layer(reverse=False)
- load_map_layer(unload=False)
- toggle_recording()
Start recording images from the camera output.
Saved in
LaunchConfig.camera.recorder.output_pathwith the current frame number.
- toggle_radar()
Adds or destroys a radar sensor for the user interface
- modify_vehicle_physics(actor: carla.Vehicle)
- Parameters:
actor (carla.Vehicle)
- finalize_render(display: pygame.Surface)
Draws the HUD and saves the image if recording is enabled.
Assumes render(…, finalize=False) was called before, use this function if you want to render something in between.
- Parameters:
display (pygame.Surface)
- render(display: pygame.surface.Surface, finalize: bool = True)
Render world
Recording should be done at the end of the render method, however camera_manager.render is called first to render the camera.
Call with finalize=False to only render the camera.
Afterwards applying other render features call finalize_render to draw the HUD and save the image if recording is enabled.
- Parameters:
display (pygame.surface.Surface)
finalize (bool)
- destroy_sensors()
Destroy sensors
- destroy(destroy_ego=False)
Destroys all actors
- rss_check_control(vehicle_control: carla.VehicleControl) carla.VehicleControl | None
- Parameters:
vehicle_control (carla.VehicleControl)
- Return type:
carla.VehicleControl | None