tminterface package
Submodules
tminterface.client module
- class tminterface.client.Client
Bases:
object- on_bruteforce_evaluate(iface, info: BFEvaluationInfo) BFEvaluationResponse
Called on each bruteforce physics step iteration. This method will only be called when the bruteforce script is enabled in TMInterface. Used for implementing custom evaluation strategies. For greater control over the simulation, use the Client.on_simulation_step method instead.
- Parameters
iface (TMInterface) – the TMInterface object
info (BFEvaluationInfo) – the info about the current bruteforce settings and race time
- Returns
None if the bruteforce script should continue its builtin evaluation or a BFEvaluationResponse that signifies what the script should do.
- on_checkpoint_count_changed(iface, current: int, target: int)
Called when the current checkpoint count changed (a new checkpoint has been passed by the vehicle). The current and target parameters account for the total amount of checkpoints to be collected, taking lap count into consideration.
- Parameters
iface (TMInterface) – the TMInterface object
current (int) – the current amount of checkpoints passed
target (int) – the total amount of checkpoints on the map (including finish)
- on_client_exception(iface, exception: Exception)
Called when a client exception is thrown. This can happen if opening the shared file fails, or reading from it fails.
- Parameters
iface (TMInterface) – the TMInterface object
exception (Exception) – the exception being thrown
- on_custom_command(iface, time_from: int, time_to: int, command: str, args: list)
Called when a custom command has been executed by the user.
- Parameters
iface (TMInterface) – the TMInterface object
time_from (int) – if provided by the user, the starting time of the command, otherwise -1
time_to (int) – if provided by the user, the ending time of the command, otherwise -1
command (str) – the command name being executed
args (list) – the argument list provided by the user
- on_deregistered(iface)
A callback that the client has been deregistered from a TMInterface instance. This can be emitted when the game closes, the client does not respond in the timeout window, or the user manually deregisters the client with the deregister command.
- Parameters
iface (TMInterface) – the TMInterface object that has been deregistered
- on_laps_count_changed(iface, current: int)
Called when the current lap count changed (a new lap has been passed).
- Parameters
iface (TMInterface) – the TMInterface object
current (int) – the current amount of laps passed
- on_registered(iface)
A callback that the client has registered to a TMInterface instance.
- Parameters
iface (TMInterface) – the TMInterface object that has been registered
- on_run_step(iface, _time: int)
Called on each “run” step (physics tick). This method will be called only in normal races and not when validating a replay.
- Parameters
iface (TMInterface) – the TMInterface object
- on_shutdown(iface)
A callback that the TMInterface server is shutting down. This is emitted when the game is closed.
- Parameters
iface (TMInterface) – the TMInterface object that has been closed
- on_simulation_begin(iface)
Called when a new simulation session is started (when validating a replay).
- Parameters
iface (TMInterface) – the TMInterface object
- on_simulation_end(iface, result: int)
Called when a new simulation session is ended (when validating a replay).
- Parameters
iface (TMInterface) – the TMInterface object
- on_simulation_step(iface, _time: int)
Called on each simulation step (physics tick). This method will be called only when validating a replay.
- Parameters
iface (TMInterface) – the TMInterface object
- tminterface.client.run_client(client: Client, server_name: str = 'TMInterface0', buffer_size=65535)
Connects to a server with the specified server name and registers the client instance. The function closes the connection on SIGBREAK and SIGINT signals and will block until the client is deregistered in any way. You can set the buffer size yourself to use for the connection, by specifying the buffer_size parameter. Using a custom size requires launching TMInterface with the /serversize command line parameter: TMInterface.exe /serversize=size.
- Parameters
client (Client) – the client instance to register
server_name (str) – the server name to connect to, TMInterface0 by default
buffer_size (int) – the buffer size to use, the default size is defined by tminterface.constants.DEFAULT_SERVER_SIZE
tminterface.commandlist module
- class tminterface.commandlist.BaseCommand
Bases:
objectThe BaseCommand class is a base class for all command classes such as Command, TimedCommand and InputCommand.
- to_script() str
Converts a command to a script string line.
- Returns
the script snippet that represents this command
- Return type
str
- class tminterface.commandlist.Command(args: list)
Bases:
BaseCommandA Command represents an immediate command that is executed immediately by TMInterface whenever it’s encountered.
- args: list
- to_script() str
Converts a command to a script string line.
- Returns
the script snippet that represents this command
- Return type
str
- class tminterface.commandlist.CommandList(obj=None)
Bases:
objectA CommandList represents a list of TMInterface commands usually forming a script which can contain immediate and timed commands.
A CommandList can be loaded by providing a file handle to an existing script file or from a string. You can also construct an empty CommandList to add your own commands to then convert them into a valid TMInterface script.
If a resource is provided, the class will attempt to parse all of its contents into immediate and timed commands. You can use CommandList.to_script() to convert all the commands back into a valid TMInterface script. If any command cannot be converted, it will be commented out.
The class fully supports parsing commands with quoted arguments and inline comments and can be used to genereate new script files.
- Parameters
obj –
the resource that needs to be parsed, either:
a file handle opened with open()
a string containing the command list
None to create an empty list
- commands
the list containing all immediate commands
- Type
list
- timed_commands
the list containing all timed commands, including input commands
- Type
list
- content
the script string that was used to construct the CommandList
- Type
str
- add_command(command: BaseCommand)
Adds a command to the CommandList, converting it to an InputCommand if possible.
The command will be added to the commands list if it is of type Command. If the command is a TimedCommand, it will first be attempted to convert it to an InputCommand. If the conversion fails, it is added without any conversions. If the command is an InputCommnad, it is added to the timed_commands list.
- Parameters
command (BaseCommand) – the command to be added
- clear()
Clears all commands from the command list.
- static parse_time(time_str: str) int
Parses a singular timestamp which is either a number or a formatted time.
Parses a string like “947120” or “15:47.12” to an integer time in milliseconds.
- Parameters
time_str (str) – the time string to parse
- Returns
the time representing the string, -1 if parsing fails
- Return type
int
- static parse_time_range(range_str: str) tuple
Parses a time range.
Parses a time range or a single timestamp, returning a tuple with two elements (from, to).
If the parsed time range consists only of one timestamp, to is set to -1. If from > to, the two integers are swapped.
- Parameters
range_str (str) – the time range to parse
- Returns
a tuple of two int’s (from, to)
- Return type
tuple
- sorted_timed_commands() list
Returns all timed commands sorted in ascending order (stable).
- Returns
timed commands sorted in ascending order
- Return type
list
- to_script() str
Converts all immediate and timed commands to a valid TMInterface script.
- Returns
the string representing the TMInterface script, one command per line
- Return type
str
- class tminterface.commandlist.InputCommand(timestamp: int, input_type: InputType, state: int)
Bases:
BaseCommandThe InputCommand class specifically represents a command that is used to inject any kind of input into the game.
An input does not contain any arguments. Instead, the class defines an input with its type and state. InputCommand’s can be converted from an instance of TimedCommand.
InputCommand’s do not need to be stored to describe a TMInterface script, they are however automatically added by the CommandList for an easy access & manipulation of the input sequence.
- state: int
- timestamp: int
- to_script() str
Converts a command to a script string line.
- Returns
the script snippet that represents this command
- Return type
str
- class tminterface.commandlist.InputType(value)
Bases:
IntEnumThe InputType enum represents an input type that is coupled with its state.
- DOWN = 1
- GAS = 8
- HORN = 6
- LEFT = 2
- RESET = 5
- RESPAWN = 4
- RIGHT = 3
- STEER = 7
- UNKNOWN = 9
- UP = 0
- static from_str(s: str)
Converts a script action string into an InputType.
If the action is invalid, InputType.UNKNOWN will be returned.
- Parameters
s (str) – the string to convert
- Returns
the converted input type
- Return type
- to_str() str
- class tminterface.commandlist.TimedCommand(args: list, timestamp: int, is_ending: bool)
Bases:
CommandA TimedCommand describes any command that is executed at a specific timestamp.
The TimedCommand can represent any command, including any input commands. A command with a ranged timestamp will be always converted to two TimedCommand instances, where the earliest command will have is_ending set to False and the latest, to True.
- is_ending: bool
- timestamp: int
- to_input_command() InputCommand
Converts a TimedCommand to an InputCommand if possible.
If the conversion fails or the TimedCommand is not a valid input command, None is returned.
- Returns
the converted InputCommand, or None if the conversion failed
- Return type
- to_script() str
Converts a command to a script string line.
- Returns
the script snippet that represents this command
- Return type
str
tminterface.constants module
tminterface.eventbuffer module
- class tminterface.eventbuffer.Event(*args: Any, **kwargs: Any)
Bases:
ByteStructThe Event class represents a game event (or input) with its respective time.
Such event is stored in 8 bytes internally by the game. The first 4 bytes is the time of the event. This time is a stored time, which means it is offset by 100000ms.
The last 4 bytes contain the event data. This data contains the actual event type (e.g. whether it was acceleration, braking, steering etc.) and the value of the event.
The event type is 1 byte long and it signifes an index into an array of available event types. This array is variable based on the information contained within the replay file. As such, it is required to get index of the desired event type dynamically. You can easily get/set this property through the name_index accessors.
The event value depends on the event type and is 3 bytes long. If the event type is binary (e.g. accelerate, brake, steer left), the value can be either 0 or 1. For managing this value type, use the binary_value getter/setter.
If the event type is analog, the value is stored in a custom format. You can convert between this format and the format TMInterface uses by using util.data_to_analog_value and utils.analog_value_to_data. You can avoid using these functions simply by using the analog_value getter/setter.
- Parameters
time (int) – the stored time of the event
- time
the stored time of the event
- Type
int
- data
the final data that is written into game’s memory
- Type
int
- property analog_value: int
- property binary_value: bool
- property name_index: int
- class tminterface.eventbuffer.EventBufferData(events_duration: int)
Bases:
objectThe internal event buffer used to hold player inputs in run or simulation mode.
While simulating a race, the game loads the inputs from a replay file into an internal buffer and begins to apply “events” (inputs) from this buffer. The buffer itself consists of 8 byte values, the first 4 bytes is used for the event time and the last 4 is used for event data. See the Event class for more information.
The event time is so called a “stored” time. The stored time is defined as 100000 + race time. The stored time is saved in the replay file and is also used in the internal buffer itself.
The buffer itself is stored in decreasing order. That means that the event at index 0 in the list is the last one simulated in the race. The start and end of the race is marked by special “_FakeIsRaceRunning” and “_FakeFinishLine” events. These events mark the start and finish of the race. Note that without the presence of “_FakeIsRaceRunning” event, the race will not start at all. This event has a constant stored time of 100000.
Before the starting event, a “Respawn” event can be generated by the game, this event can also be saved in the replay file itself. The very first input that can be applied by the player happens at stored time of 100010.
- Parameters
events_duration (int) – the duration of the events, equalling the finish time, mostly ignored and does not need to be set
- events_duration
the duration of the events
- Type
int
- control_names
the list of supported event types by this buffer
- Type
list
- events
the list of events held by this buffer
- Type
list
- add(time: int, event_name: str, value: Union[int, bool])
Adds an event to the event buffer.
This is a wrapper function that provides easy API for adding new events. Depending on the event_name parameter, the method will interpret the value in different ways. If the event is an analog event, the value passed should be in the range of [-65536, 65536] where negative values represent left steering and postive, right steering.
If the event is binary, the value should be False for disabling the input and True for enabling it.
The time parameter is zero based, where 0 is the first human input that can be injected. Internally, 0 translates to stored time 100010, which is the first simulation step after the countdown.
- Parameters
time (int) – zero based timestamp when the input is injected
event_name (str) – the event name that specifies the input type
value (Union[int, bool]) – the value for the event, based on the event type
- clear()
Removes all events in the current event buffer, leaving the race running event in the buffer.
A race running event should always be present in the buffer, to make the game start the race.
- copy()
Copies the event buffer with all its events.
- Returns
a deep copy of the original event buffer
- find(**kwargs)
Finds matching events according to keyword arguments.
Any unspecified parameter will be skipped in the search and will not be compared. You may use this method to filter events based on time, event type and value.
Find all analog steering events with value -65536:
matching = event_buffer.find(event_name=structs.ANALOG_STEER_NAME, value=-65536)
Find all events that happened at input time 0:
matching = event_buffer.find(time=0)
Find the finish line event:
matching = event_buffer.find(event_name=structs.BINARY_RACE_FINISH_NAME, value=True)
Calling this method without any keyword arguments will return all events in the buffer.
- Parameters
**kwargs – the keyword arguments
- Keyword Arguments
event_name (str) – match events with this event type
time (int) – match events with this time (zero based)
value (Union[int, bool]) – match events with this value, bool if the event type is binary, int if analog, this parameter can only be filtered if event_name is provided
- Returns
the events that matched the query
- Return type
list
- sort()
Sorts the event buffer by time in decreasing order.
This is the order that events are stored internally by the game. Calling this is not needed, if you are calling set_event_buffer. The server will always take care of properly sorting the events.
- to_commands_str(all_events=False)
Converts event buffer events and constructs a string consisting of commands compatible with TMInterface’s script syntax.
By default, only events that happened in the race (signified by the race running and finish events) will be converted and appended to the final string. If you want to convert all commands that are available in the buffer, call this method with all_events set to True.
- Parameters
all_events (bool) – whether to convert all commands available in the buffer
- Returns
the string containing commands compatible with TMInterface’s script syntax
- Return type
str
tminterface.interface module
- class tminterface.interface.Message(_type: int, error_code=0)
Bases:
objectThe Message class represents a binary buffer that contains useful methods to construct a message to send to the server. A message additionally contains its type, whether it is a response to a server call, or a normal client call. It also contains an error code, if there was any failure writing the message.
- Parameters
_type (int) – the message type
error_code (int) – the error code of the message, 0 if none
- _type
the message type
- Type
int
- error_code
the error code of the message, 0 if none
- Type
int
- data
the binary data
- Type
bytearray
- to_data() bytearray
- write_buffer(buffer: bytearray)
- write_double(n: float)
- write_int(n, size)
- write_int16(n: int)
- write_int32(n: int)
- write_uint16(n: int)
- write_uint32(n: int)
- write_uint8(n)
- write_zeros(n_bytes)
- class tminterface.interface.MessageType(value)
Bases:
IntEnumAn enumeration.
- ANY = 35
- C_DEREGISTER = 13
- C_EXECUTE_COMMAND = 28
- C_GET_CHECKPOINT_STATE = 25
- C_GET_CONTEXT_MODE = 22
- C_GIVE_UP = 17
- C_HORN = 18
- C_LOG = 34
- C_PREVENT_SIMULATION_FINISH = 32
- C_PROCESSED_CALL = 14
- C_REGISTER = 12
- C_REGISTER_CUSTOM_COMMAND = 33
- C_REMOVE_STATE_VALIDATION = 31
- C_RESPAWN = 16
- C_SET_CHECKPOINT_STATE = 26
- C_SET_EXECUTE_COMMANDS = 29
- C_SET_GAME_SPEED = 27
- C_SET_INPUT_STATES = 15
- C_SET_TIMEOUT = 30
- C_SIM_GET_EVENT_BUFFER = 21
- C_SIM_GET_STATE = 20
- C_SIM_REWIND_TO_STATE = 19
- C_SIM_SET_EVENT_BUFFER = 23
- C_SIM_SET_TIME_LIMIT = 24
- S_ON_BRUTEFORCE_EVALUATE = 11
- S_ON_CHECKPOINT_COUNT_CHANGED = 8
- S_ON_CUSTOM_COMMAND = 10
- S_ON_LAPS_COUNT_CHANGED = 9
- S_ON_REGISTERED = 2
- S_ON_RUN_STEP = 4
- S_ON_SIM_BEGIN = 5
- S_ON_SIM_END = 7
- S_ON_SIM_STEP = 6
- S_RESPONSE = 1
- S_SHUTDOWN = 3
- exception tminterface.interface.ServerException
Bases:
ExceptionAn exception thrown when the server cannot perform requested operation.
- class tminterface.interface.TMInterface(server_name='TMInterface0', buffer_size=65535)
Bases:
objectTMInterface is the main class to communicate with the TMInterface server. The communication is done through memory mapping and a simple synchronous message system between the server and the client. A TMInterface server can only serve only one client at a time, it is however possible to connect to many servers from the same script.
The interface provides various functions to manipulate game state and hook to different periods of game execution.
- Parameters
server_name (str) – the server tag to connect to
buffer_size (int) – the buffer size used by the server, the default is specified by tminterface.constants.DEFAULT_BUFFER_SIZE. Using a custom size requires launching TMInterface with the /serversize command line parameter: TMInterface.exe /serversize=size.
- server_name
the server tag that’s used
- Type
str
- running
whether the client is running or not
- Type
bool
- registered
whether the client is registered
- Type
bool
- mfile
the internal mapped file used for communication
- Type
mmap.mmap
- buffer_size
the buffer size used for communication
- Type
int
- clear_event_buffer()
Clears the current event buffer used for simulation, leaving the race running event in the buffer.
A race running event should always be present in the buffer, to make the game start the race.
- close()
Closes the connection to the server by deregistering the current client and shutting down the thread for communication.
This method will send a message to the server to deregister the current client.
After a successful deregistration,
Client.on_deregistered()will be called with the instance of the TMInterface class.
- execute_command(command: str)
Adds an interface command to the internal command queue.
The command will not be immediately executed, rather, it may be executed when the current queue is processed on the next game frame.
- Parameters
command (str) – the command to execute
- get_checkpoint_state() CheckpointData
Gets the current checkpoint state of the race.
See CheckpointData for more information.
- Returns
the object that holds the two arrays representing checkpoint state
- Return type
- get_context_mode() int
Gets the context mode the TMInterface instance is currently in.
The context mode is determining if the current race is in “run” mode, that is a normal race or “simulation” mode, which is when a player validates a replay.
- Returns
MODE_SIMULATION (0) if the player is in the simulation mode, MODE_RUN (1) if in a normal race
- Return type
int
- get_event_buffer() EventBufferData
Gets the internal event buffer used to hold player inputs in run or simulation mode. If the server is in the run mode (that is, in a normal race controlled by the player), this method returns the inputs of the current race. Note that new inputs will be added to the buffer as the player or TMInterface injects inputs into the game.
See EventBufferData for more information.
- Returns
the event buffer holding all the inputs of the current simulation
- Return type
- get_simulation_state() SimStateData
Gets the current simulation state of the race.
The method can be called in on_run_step or on_simulation_step calls. See SimStateData for more information.
- Returns
the object holding the simulation state
- Return type
- give_up()
Restarts the current race.
This function does not do anything in a simulation context. To rewind to the start of the race in the simulation context, use simulation states.
- horn(sim_clear_events: bool = True)
Queues a deterministic horn at next race tick. This function will not immediately call the game to horn, as TMInterface has to call the specific function at a specific place in the game loop.
In a simulation context, the server will add a new input event to the existing event buffer such that that the car horns at the next tick. By default, all other input events are cleared. If you want to preserve existing input events, pass sim_clear_events=False.
- Parameters
sim_clear_events (bool) – whether to clear all other events in simulation mode
- log(message: str, severity='log')
Prints a message in TMInterface’s console.
You can specify the severity of the command to highlight the line in a different color.
- Parameters
message (str) – the message to print
severity (str) – one of: “log”, “success”, “warning”, “error”, the message severity
- prevent_simulation_finish()
Prevents the game from stopping the simulation after a finished race.
Calling this method in the on_checkpoint_count_changed will invalidate checkpoint state so that the game does not stop simulating the race. Internally this is simply setting the last checkpoint time to -1 and can be also done manually in the client if additional handling is required.
- register(client: Client) bool
Registers a client on the server. The server can only register one client at a time, if the client is already registered, the method will return False.
This method will initially start a new thread and send a message to the server to register a new client. After a successful registration,
Client.on_registered()will be called with the instance of the TMInterface class.- Parameters
client (Client) – a Client instance to register
- Returns
True if registration was scheduled, False if client is already registered
- register_custom_command(command: str)
Registers a custom command within the console.
This function allows you to implement a custom command that is registered within TMInterface’s console. When executing the command, the
Client.on_custom_command()method will be called with additional arguments such as the time range and processed arguments list.It is completely up to the command implementation to process the time range and additional arguments supplied in the on_custom_command hook. Quoted arguments such as filenames will be automatically joined into one argument, even if they contain spaces.
A console command is not immediately executed after submitting it to the console. TMInterface executes commands asynchronously, processing a fixed amount of commands each frame. This is done to prevent the game from hanging when loading scripts with 1000’s of commands.
Use the log() method to output any info about the execution of your command.
- Parameters
command (str) – the command to register, the command cannot contain spaces
- remove_state_validation()
Makes the game validate the replay without checking if the inputs match the states saved in the replay, as if it was validating a replay exported for validation.
Calling this method in the on_simulation_begin call will remove state validation from currently validated replay. After calling, TrackMania will not check if the simulation matches with saved states in the replay, therefore allowing for input modification without stopping the simulation prematurely.
- respawn(sim_clear_events: bool = True)
Queues a deterministic respawn at the next race tick. This function will not immediately call the game to respawn the car, as TMInterface has to call the specific function at a specific place in the game loop.
In a simulation context, the server will add a new input event to the existing event buffer such that that the car respawns at the next tick. By default, all other input events are cleared. If you want to preserve existing input events, pass sim_clear_events=False.
The function will respawn the car to the nearest respawnable checkpoint or if there was no passed checkpoints, restart the race. The behaviour of this function also depends on the start_respawn console variable set within TMInterface. If start_respawn is set to true, respawning without any passed checkpoints will not restart the race, but only respawn the car on the start block, simulating online respawn behaviour.
- Parameters
sim_clear_events (bool) – whether to clear all other events in simulation mode
- rewind_to_state(state: SimStateData)
Rewinds to the provided simulation state.
The method of restoring the simulation state slightly varies depending on the context_mode field of the SimStateData class. Some buffers may not be restored at all but are replaced with native game function calls.
The simulation state is obtainable through the get_simulation_state method. This state can also be used to write a save state compatible file for TMInterface. Note that modifying important parts of the state invalidates the current race.
To provide state restoration across game instances, TMInterface uses memory masks to omit restoring instance specific fields such as pointers or arrays.
The method can be called in on_run_step or on_simulation_step calls. Note that rewinding to a state in any of these hooks will immediately simulate the next step after the hook. For example, rewinding to a state saved at race time 0, will result in the next call to on_run_step/on_simulation_step being at time 10. If you want to apply any immediate input state, make sure to apply it in the same physics step as the call to rewind_to_state.
- Parameters
state (SimStateData) – the state to restore, obtained through get_simulation_state
- set_checkpoint_state(data: CheckpointData)
Sets the checkpoint state of the game. See get_checkpoint_state to learn more about how the game stores checkpoint information.
- Parameters
data (CheckpointData) – the checkpoint data
- set_event_buffer(data: EventBufferData)
Replaces the internal event buffer used for simulation with a new one.
If you do not modify existing inputs or do not generate all events beforehand, use TMInterface.set_input_state for dynamic input injection. See EventBufferData for more information.
The events_duration and control_names fields are ignored in this call.
- Parameters
data (EventBufferData) – the new event buffer
- set_input_state(sim_clear_buffer: bool = True, **kwargs)
Sets the game input state of the vehicle.
Sets individual input states for the car. If successfully applied, key states are guaranteed to be applied at next physics tick. If you want to apply an input state that happens at 500ms, call send this message at 490ms (one step before).
Note that it is not guaranteed that the game will actually process the input in the RUN mode. This can happen when setting the game speed to high factors (such as >100). This does not affect the simulation context.
In a simulation context, the server will add new input events to the existing event buffer such that that the next tick has the desired input state. By default, all other input events are cleared. If you want to preserve existing input state & events, pass sim_clear_buffer=False.
Arguments left, right, accelerate and brake are binary events. To disable an action pass False and to enable it, pass True.
Arguments steer and gas are analog events. Pass a value in the range of [-65536, 65536] to modify the state of these actions. You can also use the extended steer range of [-6553600, 6553600], note however that this range is not possible to achieve on physical hardware. This call is not affected by the extended_steer console variable.
- Parameters
sim_clear_buffer (bool) – whether to clear the event buffer when setting input state in simulation
**kwargs – the keyword arguments
- Keyword Arguments
left (bool) – the left binary input, False = disabled, True = enabled
right (bool) – the right binary input, False = disabled, True = enabled
accelerate (bool) – the up binary input, False = disabled, True = enabled
brake (bool) – the down binary input, False = disabled, True = enabled
steer (int) – the steer analog input, in range of [-65536, 65536]
gas (int) – the gas analog input, in range of [-65536, 65536]
- set_simulation_time_limit(time: int)
Sets the time limit of the simulation.
This allows for setting an arbitrary time limit for the running simulation, making the game stop the simulation after the provided time limit is exhausted.
By default, this limit is set to the finish time of the original replay (taken from events duration found in the events buffer).
Note that setting the limit to a large value will extend the simulation to that limit, even after the race is finished. Make sure to manage finishing the race according to your application (e.g by rewinding to a state).
To reset the time to the original limit, pass -1. This call applies only to the simulation context.
- Parameters
time (int) – the time at which the game stops simulating, pass -1 to reset to the original value
- set_speed(speed: float)
Sets the global game speed, internally this simply sets the console variable “speed” in an TMInterface instance.
All characteristics of setting the global speed apply. It is not recommended to set the speed to high factors (such as >100), which could cause the game to skip running some subsystems such as the input subsystem.
This variable does not affect simulation contexts in which debug mode is disabled. When debug mode is disabled (default), the game runs only the simulation subsystem.
- Parameters
speed (float) – the speed to set, 1 is the default normal game speed, factors <1 will slow down the game while factors >1 will speed it up
- set_timeout(timeout_ms: int)
Sets the timeout window in which the client has to respond to server calls.
The timeout specifies how long will the server wait for a response from the client. If the response does not arrive in this time frame, the server will automatically deregister the client itself.
The timeout is specified in milliseconds, by default this is 2000ms (2 seconds). Set the timeout to -1 to have the server wait forever for the response.
- Parameters
timeout_ms (int) – the timeout in milliseconds
tminterface.structs module
- class tminterface.structs.BFEvaluationDecision(value)
Bases:
IntEnumThe decision taken by the client in every bruteforce physics step. Returned in
Client.on_bruteforce_evaluate()in an BFEvaluationResponse instance.CONTINUE: run the default evaluation of the bruteforce script
DO_NOTHING: do not run any evaluation that could result in accepting or rejecting the evaluated solution
ACCEPT: accept the current solution as the new best one. Starts a new intial phase in the next physics step.
REJECT: rejects the current solution and generates a new one for next evaluation
STOP: stops the bruteforce script and lets the game simulate the race until the end
- ACCEPT = 2
- CONTINUE = 0
- DO_NOTHING = 1
- REJECT = 3
- STOP = 4
- class tminterface.structs.BFEvaluationInfo(*args: Any, **kwargs: Any)
Bases:
ByteStructThe bruteforce settings applied in the bruteforce process, including the current simulation race time.
- class tminterface.structs.BFEvaluationResponse(*args: Any, **kwargs: Any)
Bases:
ByteStructThe response object sent by
Client.on_bruteforce_evaluate().If decision is set to
BFEvaluationDecision.REJECT, you are allowed to change the inputs manually via theTMInterface.set_event_buffer()method and set the rewind_time to timestamp - 10 where timestamp is the first input that has been changed by your algorithm. Otherwise, TMInterface will automatically randomize the inputs according to the current settings itself.
- class tminterface.structs.BFPhase(value)
Bases:
IntEnumThe phase in which the bruteforce script is currently working.
The initial phase is executed at the beginning of the process and after each improvement. It is used primarily for collecting data about the race e.g: the race time, position of the car, checkpoint times etc. No state modification happens at this state and it is recommended to use this phase to collect information about the current solution.
The search phase is when TMInterface is searching for a new improvement. In this phase, the process changes inputs according to the user settings and evaluates the solution based on the current target.
- INITIAL = 0
- SEARCH = 1
- class tminterface.structs.BFTarget(value)
Bases:
IntEnumThe bruteforce metric that is being currently optimized.
- CHECKPOINT_TIME = 1
- DISTANCE_SPEED = 3
- FINISH_TIME = 0
- TRIGGER = 2
- class tminterface.structs.CachedInput(*args: Any, **kwargs: Any)
Bases:
ByteStruct- time
int
- event
Event
- class tminterface.structs.CheckpointData(*args: Any, **kwargs: Any)
Bases:
ByteStructThe CheckpointData object represents checkpoint state within the game.
The game keeps track of two arrays that contain checkpoint information. The first “state” array is an array of booleans (a boolean is 4 bytes long) and keeps track of which checkpoints were already passed. The length of the array represents the real count of the checkpoints on current the map (including finish). This does not mean that to finish the race the player has to pass through this exact count of checkpoints. A map with 3 laps and 5 checkpoints will still contain only 5 checkpoint states.
The second “times” array is an array of structures with 2 fields: time and an unknown field. This array holds the “logical” number of checkpoints that have to be passed (including finish). This means the total number of checkpoint passes, including the existence of laps.
- Parameters
cp_states (list) – the checkpoint states array
cp_times (list) – the checkpoint times array, each element is a two element tuple of (time, flags)
- read_from_file(file)
- class tminterface.structs.CheckpointTime(*args: Any, **kwargs: Any)
Bases:
ByteStruct- time
int
- stunts_score
int
- class tminterface.structs.ClassicString(*args: Any, **kwargs: Any)
Bases:
ByteStructA string sent by the client to TMInterface.
- command = None
- class tminterface.structs.Engine(*args: Any, **kwargs: Any)
Bases:
ByteStruct- max_rpm
float
- braking_factor
float
- clamped_rpm
float
- actual_rpm
float
- slide_factor
float
- rear_gear
int
- gear
int
- class tminterface.structs.HmsDynaStateStruct(*args: Any, **kwargs: Any)
Bases:
ByteStruct- quat
np.ndarray
- rotation
np.ndarray
- position
np.ndarray
- linear_speed
np.ndarray
- add_linear_speed
np.ndarray
- angular_speed
np.ndarray
- force
np.ndarray
- torque
np.ndarray
- inverse_inertia_tensor
np.ndarray
- unknown
float
- not_tweaked_linear_speed
np.ndarray
- owner
int
- property inverse_intertia_tensor
- class tminterface.structs.HmsDynaStruct(*args: Any, **kwargs: Any)
Bases:
ByteStruct- previous_state
HmsDynaStateStruct
- current_state
HmsDynaStateStruct
- temp_state
HmsDynaStateStruct
- rest
bytearray
- property prev_state
- rest = 616
- class tminterface.structs.PlayerInfoStruct(*args: Any, **kwargs: Any)
Bases:
ByteStruct- team
int
- prev_race_time
int
- race_time
int
- race_time
int
- race_best_time
int
- lap_start_time
int
- lap_time
int
- lap_best_time
int
- min_respawns
int
- nb_completed
int
- max_completed
int
- stunts_score
int
- best_stunts_score
int
- cur_checkpoint
int
- average_rank
float
- current_race_rank
int
- current_round_rank
int
- current_time
int
- race_state
int
- ready_enum
int
- round_num
int
- offset_current_cp
float
- cur_lap_cp_count
int
- cur_cp_count
int
- cur_lap
int
- race_finished
bool
- display_speed
int
- finish_not_passed
bool
- countdown_time
int
- rest
bytearray
- rest = 32
- class tminterface.structs.RealTimeState(*args: Any, **kwargs: Any)
Bases:
ByteStruct- damper_absorb
float
- field_4
float
- field_8
float
- field_12
np.ndarray
- field_48
np.ndarray
- field_84
np.ndarray
- field_108
float
- has_ground_contact
bool
- contact_material_id
int
- is_sliding
bool
- relative_rotz_axis
np.ndarray
- nb_ground_contacts
int
- field_144
np.ndarray
- rest
bytearray
- rest = 12
- class tminterface.structs.SceneVehicleCar(*args: Any, **kwargs: Any)
Bases:
ByteStruct- is_update_async
bool
- input_gas
float
- input_brake
float
- input_steer
float
- is_light_trials_set
bool
- horn_limit
int
- quality
int
- max_linear_speed
float
- gearbox_state
int
- block_flags
int
- prev_sync_vehicle_state
SceneVehicleCarState
- sync_vehicle_state
SceneVehicleCarState
- async_vehicle_state
SceneVehicleCarState
- prev_async_vehicle_state
SceneVehicleCarState
- engine
Engine
- has_any_lateral_contact
bool
- last_has_any_lateral_contact_time
int
- water_forces_applied
bool
- turning_rate
float
- turbo_boost_factor
float
- last_turbo_type_change_time
int
- last_turbo_time
int
- turbo_type
int
- roulette_value
int
- is_freewheeling
bool
- is_sliding
bool
- wheel_contact_absorb_counter
int
- burnout_state
int
- current_local_speed
np.ndarray
- total_central_force_added
np.ndarray
- is_rubber_ball
bool
- saved_state
np.ndarray
- async_vehicle_state
alias of
SceneVehicleCarState
- prev_async_vehicle_state
alias of
SceneVehicleCarState
- prev_sync_vehicle_state
alias of
SceneVehicleCarState
- sync_vehicle_state
alias of
SceneVehicleCarState
- class tminterface.structs.SceneVehicleCarState(*args: Any, **kwargs: Any)
Bases:
ByteStruct- speed_forward
float
- speed_sideward
float
- input_steer
float
- input_gas
float
- input_brake
float
- is_turbo
bool
- rpm
float
- gearbox_state
int
- rest
bytearray
- rest = 28
- class tminterface.structs.SimStateData(*args: Any, **kwargs: Any)
Bases:
ByteStructThe SimStateData object represents a full save state of the simulation state, including checkpoint and input information.
The simulation state consists of raw memory buffers representing various information about the race state. This includes the entirety of the vehicle state as well as the player info and other state variables such as current checkpoint count and input state.
The memory regions themselves are monitored by TMInterface itself and are used for functionality like save states or fast rewind in the bruteforce script. TMInterface may use additional native game methods to restore the state based on information present in some of these memory regions. It is important to note that the buffers contain instance specific fields such as pointers and array sizes. These are masked out automatically by TMInterface when restoring the state (and when calling TMInterface.rewind_to_state).
To query input state of the simulation state regardless of context, use input_* (input_accelerate, input_brake etc.) accessors.
- version
int
- context_mode
int
- flags
int
- timers
np.ndarray
- dyna
HmsDynaStruct
- scene_mobil
SceneVehicleCar
- simulation_wheels
np.ndarray
- plug_solid
bytes
- cmd_buffer_core
bytes
- player_info
PlayerInfoStruct
- internal_input_state
np.ndarray
- input_running_event
Event
- input_finish_event
Event
- input_accelerate_event
Event
- input_brake_event
Event
- input_left_event
Event
- input_right_event
Event
- input_steer_event
Event
- input_gas_event
Event
- cmd_buffer_core = 264
- cp_data
alias of
CheckpointData
- property display_speed: int
- dyna
alias of
HmsDynaStruct
- property input_accelerate: bool
- property input_brake: bool
- property input_gas: int
- property input_left: bool
- property input_right: bool
- property input_steer: int
- player_info
alias of
PlayerInfoStruct
- plug_solid = 68
- property position: list
- property race_time: int
- property rewind_time: int
- property rotation_matrix: list
- scene_mobil
alias of
SceneVehicleCar
- property time: int
- property velocity: list
- property yaw_pitch_roll: numpy.array
- class tminterface.structs.SimulationWheel(*args: Any, **kwargs: Any)
Bases:
ByteStruct- steerable
bool
- field_8
int
- surface_handler
SurfaceHandler
- field_112
np.ndarray
- field_160
int
- field_164
int
- offset_from_vehicle
np.ndarray
- real_time_state
RealTimeState
- field_348
int
- contact_relative_local_distance
np.ndarray
- prev_sync_wheel_state
WheelState
- sync_wheel_state
WheelState
- field_564
WheelState
- async_wheel_state
WheelState
- async_wheel_state
alias of
WheelState
- field_564
alias of
WheelState
- prev_sync_wheel_state
alias of
WheelState
- real_time_state
alias of
RealTimeState
- surface_handler
alias of
SurfaceHandler
- sync_wheel_state
alias of
WheelState
tminterface.util module
- tminterface.util.analog_value_to_data(value: int) int
Converts a value in [-65536, 65536] range to an internal analog state value.
The function supports values outside the normal range, that is you can convert values in the extended range as well.
- Parameters
data (int) – the value to convert
- Returns
the converted value
- Return type
int
- tminterface.util.data_to_analog_value(data: int) int
Converts an internal analog state value to a [-65536, 65536] range.
The function supports values outside the normal range, that is you can convert values in the extended range as well.
- Parameters
data (int) – the internal value, usually stored in an event buffer
- Returns
the converted value
- Return type
int
- tminterface.util.mat3_to_quat(mat: numpy.array) numpy.array
Converts a rotation matrix to a quaternion.
This function uses the internal implementation that the game uses to convert a rotation matrix to a quaternion.
The function itself is constructed from reverse engineering the code of the game. This particular implementation should be 100% compatible with the original method the game uses. Note however that this compatibility is not guaranteed.
- Parameters
mat (np.array) – a 3x3 rotation matrix to convert
- Returns
the quaternion consisting of 4 elements (x, y, z, w)
- Return type
np.array
- tminterface.util.quat_to_ypw(quat: numpy.array) numpy.array
Converts a quaternion to yaw, pitch and roll values.
This function uses the internal implementation that the game uses to convert quaternions to yaw, pitch and roll.
The function itself is constructed from reverse engineering the code of the game. Note that this particular implementation is not 100% compatible with the actual assembly code, however it should produce the same results in most cases.
- Parameters
quat (np.array) – the quaternion to convert (x, y, z, w)
- Returns
an array containing 3 elements: yaw, pitch and roll
- Return type
np.array