Battle

The battle object is the main interface through which the state of the running battle may be queried. The interface provides a variety of methods that can be used to interrogate and modify the battle state, chiefly access to the battle_hierarchy from which objects battle_alliance, battle_army and battle_unit objects may be derived.

Loaded in Campaign Loaded in Campaign
Loaded in Battle Loaded in Battle
Loaded in Frontend Loaded in Frontend
Back to top

Creation

A battle object may be created by calling empire_battle:new(). Functions listed further down on this page may then be called on the returned battle object in the form <object_name>:<function_name>(<args>).

Example:

-- creation
battle = empire_battle:new()

-- usage
if battle:is_tutorial() then
    -- do tutorial stuff
end
Back to top

Battle and Battle Manager Objects

It is strongly recommended to create and use a battle_manager object in place of a raw battle object. The battle_manager interface provides much additional functionality and quality of life improvements on top of the raw battle interface described here. Functions provided by the battle interface may be called on a battle_manager object - the battle manager passes the call through to the underlying battle object if required.

Example - Create a battle manager instead of a battle object:

bm = battle_manager:new(empire_battle:new())
Back to top

Output

battle:out(string output)

Prints some output to the console. If this function is called on a battle_manager object then it is overridden by battle_manager:out, which prepends a timestamp to the output before printing it.

Parameters:

1

string

output

Returns:

  1. nil

battle:error(string message)

Shows an assert dialog with the supplied message.

Parameters:

1

string

message

Returns:

  1. nil
Back to top

Battle Objects

battle:alliances()

Creates and returns a battle_alliances object listing all alliances on the battlefield.

Returns:

  1. battle_alliances alliances list

battle:local_alliance()

Returns the index number of the battle_alliance that corresponds to the player on the local machine. This can be used to look up the player's battle_alliance from within the battle_alliances collection that may be retrieved with battle:alliances. In any singleplayer battle this should return 1.

Returns:

  1. number local alliance number

Example:

alliances = bm:alliances()
player_alliance = alliances:item(bm:local_alliance())

battle:local_army()

Returns the index number of the battle_army (within the relevant battle_armies collection object) that corresponds to the player on the local machine. This can be used to look up the player's battle_army

Returns:

  1. number local army number

Example:

alliances = bm:alliances()
player_alliance = alliances:item(bm:local_alliance())
player_army = player_alliance:armies():item(bm:local_army())

battle:is_spectator()

Returns whether the local game client is spectating the battle or not.

Returns:

  1. boolean is spectating

battle:buildings()

Creates and returns a battle_buildings object listing all buildings on the battlefield.

Returns:

  1. battle_buildings buildings list

battle:assault_equipment()

Creates and returns a battle_assault_equipment object listing all vehicles (such as siege towers and battering rams) on the battlefield.

Returns:

  1. battle_assault_equipment assault equipment list

battle:debug_drawing()

Creates and returns a battle_debug_drawing object, allowing the script to draw debug lines on the battlefield.

Returns:

  1. battle_debug_drawing debug drawing object

battle:capture_location_manager()

Creates and returns a battle_capture_location_manager object, which can be queried to gain handles to individual battle_capture_location objects.

Returns:

  1. battle_capture_location_manager capture location manager

battle:camera()

Creates and returns a battle_camera object.

Returns:

  1. battle_camera battle camera

battle:subtitles()

Creates and returns a battle_subtitles object.

Returns:

  1. battle_subtitles subtitles

battle:reinforcements()

Creates and returns a battle_reinforcements object.

Returns:

  1. battle_reinforcements reinforcements

battle:toggle_system()

Creates and returns a battle_toggle_system object

Returns:

  1. battle_toggle_system toggle_system

battle:composite_scenes_system()

Creates and returns a battle_composite_scenes_system object

Returns:

  1. battle_composite_scenes_system composite scenes system
Back to top

Handlers

battle:register_input_handler(string input handler function)

Registers a function (by string name) as a handler for input events. Input events are triggered when the player makes certain inputs. Valid input events are:

  • "move forward"

  • "move forward fast"

  • "move backward"

  • "move left"

  • "move right"

  • "rotate right"

  • "rotate left"

  • "move up"

  • "move down"

  • "rotate up"

  • "rotate down"

  • "edge rotate right"

  • "edge rotate left"

  • "edge move left"

  • "edge move right"

  • "edge move forward"

  • "edge move backward"

When an input event occurs, the registered function is called with the relevant input event string as a single argument. Note that the function being registered must have already been declared when register_input_handler is called.
Once registered, an input handler may be unregistered with battle:unregister_input_handler.

Parameters:

1

string

input handler function

Returns:

  1. nil

Example:

function my_input_handler(event_name)
    if event_name == "move_forward" then
        -- do something in response to the move_forward event
    end
end
bm:register_input_handler("my_input_handler")

battle:unregister_input_handler()

Unregisters the currently-registered input handler function. An input handler may be registered with battle:register_input_handler.

Returns:

  1. nil

battle:register_unit_selection_handler(string input handler function)

Registers a function (by string name) as a handler for user selection events. These events are triggered when the player selects or deselects units. When such an event occurs, the registered function is called with two arguments - the first being a battle_unit object representing the unit concerned, the second being a boolean flag indicating whether the unit is being selected or deselected. Note that the function being registered must have already been declared when register_unit_selection_handler is called.

Parameters:

1

string

input handler function

Returns:

  1. nil

Example:

function my_unit_selection_handler(unit, is_selected)
    if is_selected then
        -- track selected units
    else
        -- track unselected units
    end
end
bm:register_unit_selection_handler("my_unit_selection_handler")

battle:unregister_unit_selection_handler()

Unregisters the currently-registered unit selection handler function. A unit selection handler may be registered with battle:register_unit_selection_handler.

Returns:

  1. nil

battle:register_command_handler(string command handler function)

Registers a function (by string name) as a handler for command events. Command events are triggered when the player (or script) issues certain commands. When such an event occurs, the registered function is called and passed an event object as a single argument. This object provides several methods which can be used to determine information about the issued command. These methods are listed below:

MethodDescription
event:get_name()Returns the string name of the issued command. This is provided for every event type.
event:get_bool1()Returns a boolean value related to the issued command, if any.
event:get_string1()Returns a string value related to the issued command, if any.
event:get_position()Returns a battle_vector related to the issued command, if any.
event:get_unit()Returns a battle_unit related to the issued command, if any.
event:get_building()Returns a battle_building related to the issued command, if any.
Note that each event type only provides methods that are relevant. The list of valid event types, and what methods they provide, are listed here:

Event TypeEvent DescriptionMethod ProvidedMethod Return TypeMethod Description
Group CreatedA group has been createdevent:get_name()stringName of event
Group DestroyedA group has been disbandedevent:get_name()stringName of event
Repair ModeA command to repair a ship has been issuedevent:get_name()stringName of event
MoveA movement command has been issuedevent:get_name()stringName of event
event:get_bool1()booleanIndicates whether the unit is now moving fast/running
Move Orientation WidthA movement command with orientation and width has been issuedevent:get_name()stringName of event
Move Rotation AngleA rotation command has been issuedevent:get_name()stringName of event
Change SpeedThe speed of a unit has been toggledevent:get_name()stringName of event
event:get_bool1()booleanIndicates whether the unit is now moving fast/running
Attack UnitA command to attack a unit has been issuedevent:get_name()stringName of event
event:get_bool1()booleanIndicates whether the unit is now moving fast/running
event:get_unit()battle_unitReturns the target unit
Change SkirmishSkirmish mode has been toggled on a unitevent:get_name()stringName of event
event:get_bool1()booleanIndicates whether skirmish mode is now enabled
Change MeleeMelee mode has been toggled on a unitevent:get_name()stringName of event
event:get_bool1()booleanIndicates whether melee mode is now enabled
Change FormationA command to change formation has been issuedevent:get_name()stringName of event
event:get_string1()stringReturns the name of the formation
Attack BuildingA command to attack a building has been issuedevent:get_name()stringName of event
event:get_bool1()booleanIndicates whether the unit is now moving fast/running
event:get_building()battle_buildingReturns the target building
Climb/Dock BuildingA command to climb a building has been issuedevent:get_name()stringName of event
event:get_bool1()booleanIndicates whether the unit is now moving fast/running
event:get_building()battle_buildingReturns the target building
Special AbilityA command to use a special ability has been issuedevent:get_name()stringName of event
event:get_string1()stringReturns the name of the special ability
Shot TypeA command to change shot type has been issuedevent:get_name()stringName of event
event:get_string1()stringReturns the name of the shot type
Fire At WillFire-at-will mode has been toggled on a unitevent:get_name()stringName of event
Broadside AttackA broadside attack command has been issuedevent:get_name()stringName of event
event:get_bool1()booleanReturns true if the broadside is on the left side of the ship, false otherwise
Naval Shot TypeA command to change the shot type of a ship has been issuedevent:get_name()stringName of event
event:get_string1()stringReturns the name of the shot type
RamA command to ram a ship has been issuedevent:get_name()stringName of event
WithdrawA command to withdraw a unit has been issuedevent:get_name()stringName of event
event:get_bool1()booleanIndicates whether the unit is now moving fast/running
HaltA command to halt a unit has been issuedevent:get_name()stringName of event
Double ClickThe double-click UI gesture has been issued for the selected unitsevent:get_name()stringName of event
Entity HitA unit has been hit by a projectileevent:get_name()stringName of event
event:get_bool1()booleanIndicates whether artillery fired the projectile
event:get_unit()battle_unitReturns the unit that was hit
Double Click Unit CardA unit card has been double-clicked uponevent:get_name()stringName of event
event:get_unit()battle_unitReturns the subject unit
Unit Left BattlefieldA unit has left the battlefieldevent:get_name()stringName of event
event:get_unit()battle_unitReturns the subject unit
Battle ResultsThe battle has finished and the results have been issuedevent:get_name()stringName of event
event:get_bool1()booleanIndicates whether the local alliance won the battle
Note that the function being registered must have already been declared when register_command_handler is called.

Parameters:

1

string

command handler function

Returns:

  1. nil

Example:

function my_command_handler(event)
    local event_name = event:get_name()
    if event_name == "Move" then
        -- handle move orders
    elseif event_name == "Attack Unit" then
        -- handle attack unit orders
    end
end
bm:register_command_handler("my_command_handler")

battle:unregister_command_handler()

Unregisters the currently-registered command handler function. A command handler may be registered with battle:register_command_handler.

Returns:

  1. nil

battle:register_battle_phase_handler(string function name)

Registers a function (by string name) as a handler for battle phase changes. Battle phase changes are triggered when the battle moves into various distinct phases, the most important being the deployment and deployment (combat) phases. When a battle phase occurs, the registered function is called and passed the string name of the new battle phase as a single argument. Valid phases are listed below:

Phase NameDescription
StartupThis phase change is triggered after the scripts are loaded.
PrebattleWeatherTriggered after Startup phase.
PrebattleCinematicTriggered after PrebattleWeather phase.
DeploymentDeployment phase, when both alliances get to position their troops prior to combat.
DeployedCombat phase, in which the battle is fought.
VictoryCountdownA victor for the battle has been determined, and the battle is counting down to completion.
CompleteThe battle is completed.
Note that the function being registered must have already been declared when register_unit_selection_handler is called. Furthermore, it is recommended that battle_manager:register_phase_change_callback is used in place of this function.

Parameters:

1

string

Function name to call when phase change event occurs.

Returns:

  1. nil

Example:

function my_phase_change_handler(phase_change)
    local
    if phase_change == "deployment" then
        -- handle deployment phase
    elseif phase_change == "deployed" then
        -- handle combat phase
    end
end
bm:register_phase_change_handler("my_phase_change_handler")

battle:unregister_battle_phase_handler()

Unregisters the currently-registered phase change handler function. A phase change handler may be registered with battle:register_battle_phase_handler.

Returns:

  1. nil

battle:end_current_battle_phase()

Immediately ends the current battle phase, moving on to the next phase. The main use for this function is to force deployment phase to end - calling this function has no effect in combat phase. More information about battle phases can be found in the Battle Phases section of this documentation.

Returns:

  1. nil
Back to top

Time and Timers

The functions in this section describe the raw interface to the model timer system provided in battle to script. It's strongly recommended that client scripts make use of the functionality provided by the timer_manager (and exposed through the battle_manager - see the Timer Callbacks section of this documentation), rather than calling battle:register_singleshot_timer, battle:register_repeating_timer or battle:unregister_timer functions directly.

battle:timer_exists(string function name)

Returns whether a timer exists for the specified function name. If a timer does exist, the amount of model time remaining before it triggers in ms is also returned as a second return parameter.

Parameters:

1

string

function name

Returns:

  1. boolean timer exists
  2. number model time before timer triggers

battle:register_singleshot_timer(string function name, number interval)

Registers a singleshot timer. A function name must be specified as a string, along with an interval. The battle model then calls the function with the given name after the specified interval. No arguments may be specified for the function. Only one timer instance can be registered for a given function - repeated calls to battle:register_singleshot_timer or battle:register_repeating_timer will overwrite any previous timers.
It is strongly recommended that client scripts do not call this directly but instead use the battle_manager:callback function, which allows arguments to be passed, multiple instances of timers for the same callback, and more flexible cancellation of the callback.

Parameters:

1

string

Function name.

2

number

Interval in ms.

Returns:

  1. nil

battle:register_repeating_timer(string function name, number interval)

Registers a repeating timer. A function name must be specified as a string, along with an interval. The battle model then calls the function with the given name each time the specified interval elapses. No arguments may be specified for the function. Only one timer instance can be registered for a given function. Only one timer instance can be registered for a given function - repeated calls to battle:register_singleshot_timer or battle:register_repeating_timer will overwrite any previous timers.
It is strongly recommended that client scripts do not call this directly but instead use the battle_manager:repeat_callback function, which allows arguments to be passed, multiple instances of timers for the same callback, and more flexible cancellation of the callback.

Parameters:

1

string

Function name.

2

number

Interval in ms.

Returns:

  1. nil

battle:unregister_timer(string function name)

Unegisters a timer (whether registered with battle:register_singleshot_timer or battle:register_repeating_timer), by it's string function name. In the case of a singleshot function this must be called before the function is triggered.
It is strongly recommended that client scripts use battle_manager:callback, battle_manager:repeat_callback and then battle_manager:remove_process due to ease-of-use.

Parameters:

1

string

Function name to unregister.

Returns:

  1. nil

battle:time_elapsed_ms()

Returns the amount of model time that's elapsed since the start of the battle, in milliseconds.

Returns:

  1. number time elapsed

battle:model_tick_time_ms()

Returns the model tick time in milliseconds. This is the target interval over which the battle model repeatedly updates - 100ms or 200ms.

Returns:

  1. number tick time

battle:remaining_conflict_time()

Returns the duration remaining before the battle time limit expires, in seconds. If no time limit is set then -1 is returned.

Returns:

  1. number remaining time

battle:modify_battle_speed(number battle speed)

Adjusts the game speed. The value supplied should be a unary proportion of normal speed, for example:

  • Set a speed of 1 to run the battle at normal speed.

  • Set a speed of 3 to run the battle at triple speed.

  • Set a speed of 0.5 to run the battle at half speed.

  • Set a speed of 0 to pause the battle.

Beware that pausing the battle will prevent model time from advancing, which will also affect script.
The battle speed may be restored to the value previously set by the player by calling battle:restore_battle_speed.

Parameters:

1

number

battle speed

Returns:

  1. nil

battle:current_battle_speed()

Returns the current game speed.

Returns:

  1. number battle speed

battle:restore_battle_speed()

Restores the game speed to the value that was previously set when battle:modify_battle_speed was last called.

Returns:

  1. nil

battle:change_conflict_time_update_overridden(boolean disable update)

Enables or disables the countdown of the conflict timer. Call with an argument of true to disable the countdown of the conflict timer, or false to enable it again. With conflict time update overridden, time can pass but the victory timer will not count down.

Parameters:

1

boolean

disable update

Returns:

  1. nil

battle:change_victory_countdown_limit(number time limit)

Change the victory countdown limit. This is the grace period that begins counting down once a victor in the battle has been determined but before the battle actually ends, and is usually ten seconds. Battle scripts can use this function to adjust the duration of this countdown in order to display outro advice or cutscene content without having it cut off.
Supply a limit of less than 0 to make the victory countdown period infinite. If the battle enters the victory countdown phase with an infinite period set, and then a limit of 0 is set with a subsequent call to this function, the battle complete phase will trigger immediately.

Parameters:

1

number

Time limit in seconds.

Returns:

  1. nil

battle:force_cant_chase_down_routers()

Force battle end to not wait for chasing routers

Returns:

  1. nil
Back to top

Cindy and Composite Scenes

battle:cindy_preload(string scene path)

Preloads a cindy scene. Calling this prior to a cindy scene being played can help prevent a noticeable stall at the start of playback.

Parameters:

1

string

Path to the cindy scene manager file, from the working data folder.

Returns:

  1. nil

battle:cindy_playback(string scene path, [number blend in], [number blend out])

Starts a cindy scene. This plays a cindy cinematic, taking control of the camera. battle:cindy_preload can be called prior to calling this function to preload the scene data.

Parameters:

1

string

Path to the cindy scene manager file, from the working data folder.

2

number

optional, default value=0

Blend in duration in seconds.

3

number

optional, default value=10

Blend out duration in seconds.

Returns:

  1. nil

battle:cindy_playback_no_camera(string scene path, boolean clear scene, [boolean save to replay])

Starts a cindy scene without a camera track. This can be run in parallel with a scene initiated with battle:cindy_playback. battle:cindy_preload can be called prior to calling this function to preload the scene data.

Parameters:

1

string

Path to the cindy scene manager file, from the working data folder.

2

boolean

Clear animated scenes on completion.

3

boolean

optional, default value=true

Saves the cindy scene into the battle replay, so if the replay is loaded the cindy scene plays again.

Returns:

  1. nil

battle:stop_cindy_playback([boolean clear animated scenes])

Stops a cindy scene that was started with battle:cindy_playback.

Parameters:

1

boolean

optional, default value=false

clear animated scenes

Returns:

  1. nil

battle:stop_cindy_playback_no_camera([boolean clear animated scenes])

Stops a cindy scene that was started with battle:cindy_playback_no_camera.

Parameters:

1

boolean

optional, default value=false

clear animated scenes

Returns:

  1. nil

battle:start_terrain_composite_scene(string scene key)

Starts a composite scene. The composite scene should be specified by its path from the working data folder.

Parameters:

1

string

Composite scene key.

Returns:

  1. nil

Example:

bm:start_terrain_composite_scene("composite_scene/seamonster/merwyrm_roar_02.csc")

battle:stop_terrain_composite_scene(string scene key)

Stops a composite scene. The composite scene should be specified by its path from the working data folder.

Parameters:

1

string

Composite scene key.

Returns:

  1. nil

Example:

bm:stop_terrain_composite_scene("composite_scene/seamonster/merwyrm_roar_02.csc")
Back to top

Advice and Audio

battle:play_adc(string adc key, number x, number y, number z, boolean for player)

Manually triggers an aide-de-camp message at a specified location on the battlefield.

Parameters:

1

string

Aide-de-camp key, from the aide_de_camp_speeches database table.

2

number

X co-ordinate of message, in m.

3

number

Y co-ordinate (altitude) of message, in m.

4

number

Z co-ordinate of message, in m.

5

boolean

Aide-de-camp message is for the player's alliance.

Returns:

  1. nil

battle:suspend_contextual_advice(boolean should suspend)

Prevents advice from being triggered with common.advance_contextual_advice_thread, which has the effect of suspending advice not triggered deliberately by battle scripts. This has been made largely redundant by changes in the way scripts trigger advice, but can still be called.

Parameters:

1

boolean

should suspend

Returns:

  1. nil

battle:close_advisor()

Dismisses the advisor, if currently shown.

Returns:

  1. nil

battle:advice_finished()

Returns whether or not any advice is currently playing. A value of true is returned if no advice is playing, false if it is.

Returns:

  1. boolean advice finished

battle:vo_finished()

Returns whether or not any voiceover sounds are currently playing. A value of true is returned if no voiceover sounds are playing, false otherwise.

Returns:

  1. boolean vo finished

battle:suppress_unit_voices(boolean should suppress)

Disables or re-enables unit voices in battle. If unit voices are suppressed, ambient voiceover related to units will not be played.

Parameters:

1

boolean

should suppress

Returns:

  1. nil

battle:suppress_unit_musicians(boolean should suppress)

Disables or re-enables unit musicians in battle.

Parameters:

1

boolean

should suppress

Returns:

  1. nil

battle:play_music(string music name)

Plays a specified piece of music. The music to play is specified by its sound event name.

Parameters:

1

string

music name

Returns:

  1. nil

battle:play_music_custom_fade(string music name, number fade time)

Plays a specified piece of music with a custom fade-in duration. The music to play is specified by its sound event name.

Parameters:

1

string

Music sound event.

2

number

Fade time in seconds.

Returns:

  1. nil

battle:stop_music(boolean skipped)

Stops the currently-playing music.

Parameters:

1

boolean

whether this stop was because of a skipped cutscene

Returns:

  1. nil

battle:stop_music_custom_fade(boolean skipped, number fade time)

Stops the currently-playing music with a custom fade time.

Parameters:

1

boolean

whether this stop was because of a skipped cutscene

2

number

Fade time in seconds.

Returns:

  1. nil

battle:get_volume(number volume type)

Gets the volume level of a specific volume type. Valid volume types are given in the Volume Types section of this documentation. The volume level will be returned as a number between 0 (inaudible) and 100 (full volume).

Parameters:

1

number

volume type

Returns:

  1. number volume level

battle:set_volume(number volume type, number volume level)

Sets the volume level of a specific volume type. Valid volume types are given in the Volume Types section of this documentation. The volume level should be set as a number between 0 (inaudible) and 100 (full volume).

Parameters:

1

number

volume type

2

number

volume level

Returns:

  1. nil

battle:fade_volume(number volume type, number target level, number fade time)

Gradually fades the volume level of a specified volume type to a specified value over a specified interval. Valid volume types are given in the Volume Types section of this documentation. The volume level should be set as a number between 0 (inaudible) and 100 (full volume).

Parameters:

1

number

Volume type.

2

number

Target volume level.

3

number

Fade time in seconds.

Returns:

  1. nil

battle:set_music_vm_variable(
  
string variable name,
  boolean
or string or number The value to set the target variable to
)

Sets the value of the given music vm variable, this can be read by the battle music script

Parameters:

1

string

variable name

2

boolean

or string or number The value to set the target variable to

Returns:

  1. nil
Back to top

Objectives and Markers

battle:add_ping_icon(number x, number y, number x, [number type], [boolean is waypoint], [number rotation])

Adds a 3d ping marker model at a specified [x/y/z] position. It is sufficient just to supply the position, but a type can be used to change the model displayed - see the table below for a list of ping types.
List of ping types:
Type NumberType Name
0MPT_NONE
1MPT_STANDARD
2MPT_MOVE
3MPT_ATTACK
4MPT_DEFEND
5MPT_HELP_MOUNTABLE_ARTILLERY
6MPT_HELP_DISEMBARK
7MPT_NOTIFICATION
8MPT_SCRIPT_LOOK_AT
9MPT_SCRIPT_MOVE_TO
10MPT_SCRIPT_SELECT
11MPT_SCRIPT_POINTER
12MPT_SCRIPT_LOOK_AT_VFX
13MPT_SCRIPT_MOVE_TO_VFX
14MPT_SCRIPT_SELECT_VFX
15MPT_SCRIPT_OBJECTIVE 16MPT_SCRIPT_BATTLE_TRAP The waypoint flag can be used to link models together. The rotation flag can be used to specify a rotation for the model - the default is to just fade the camera.

Parameters:

1

number

X co-ordinate in metres.

2

number

Y co-ordinate (altitude) in metres. This parameter specifies the height above the water plane, so if mis-set the marker can appear under the ground.

3

number

X co-ordinate in metres.

4

number

optional, default value=0

Marker type - see list of valid marker types above.

5

boolean

optional, default value=false

Is waypoint.

6

number

optional, default value=nil

Rotation.

Returns:

  1. nil

battle:remove_ping_icon(number x, number y, number x)

Removes the ping marker that was previously added with battle:add_ping_icon at a specified [x/y/z] position.

Parameters:

1

number

X co-ordinate in metres.

2

number

Y co-ordinate (altitude) in metres.

3

number

X co-ordinate in metres.

Returns:

  1. nil

battle:show_objective(string objective key, number duration, number fade duration)

Shows an objective message on-screen. This is an old method of showing an objective-style message, which will fade in at the bottom-centre of the screen, remain on-screen for a specified period and then fade out.

Parameters:

1

string

Objective key, from the scripted_objectives table.

2

number

Duration that the objective should remain on-screen in ms.

3

number

Duration over which the objective should fade to transparent once its display duration has elapsed.

Returns:

  1. nil

Example - Show an objective key for 5 seconds, then fading out over 2 seconds.:

bm:show_objective("my_objective_key", 5000, 2000)

battle:add_animated_arrow(number animation time, number remain time, boolean loop, ... positions)

Adds an animated arrow on the terrain that can be used to indicate a path for the player. The arrow will animate between two or four supplied battle_vector positions.
The function returns a numeric index for the animated arrow. If necessary, this can be used to remove the arrow with battle:remove_animated_arrow.

Parameters:

1

number

Time over which the arrow animation should play, in seconds.

2

number

Time for which the arrow should remain after its animation has finished, in seconds.

3

boolean

Sets whether the animation should loop indefinitely. If this is set then battle:remove_animated_arrow is the only method of removing the arrow.

4

...

Two or four battle_vector positions can specified as co-ordinates through which the arrow animates.

Returns:

  1. number arrow index

battle:remove_animated_arrow(number arrow index)

Removes an animated arrow previously added with battle:add_animated_arrow. The arrow to remove is specified by the numeric index returned by add_animated_arrow.

Parameters:

1

number

arrow index

Returns:

  1. nil
Back to top

Fullscreen Movies

battle:play_movie(string movie path, boolean play movie audio)

Plays a fullscreen movie during a battle. The movie should be specified by a file path from the Movies folder in working data (see the videos table for examples of valid paths).

Parameters:

1

string

Path to movie file. The file extension may be omitted.

2

boolean

Play movie audio - if false is supplied then game audio is heard instead.

Returns:

  1. nil

Example:

bm:play_movie("startup_movie_01", true)

battle:is_movie_playing()

Returns whether or not a fullscreen movie is currently playing.

Returns:

  1. boolean is movie playing
Back to top

UI and UI Suppression

battle:ui_component(string uicomponent name)

Searches from the root uicomponent for a uicomponent with the specified name, returning the first that matches. It is encouraged that find_uicomponent is used in place of this function.

Parameters:

1

string

uicomponent name

Returns:

  1. uicomponent uicomponent, or nil if no component found

battle:enable_cinematic_ui(
  
boolean enable cinematic ui,
  [boolean
show cursor],
  [boolean
enable cinematic bars]
)

Enables or disables a script lock on the state of the cinematic UI. Additional parameters may be used to enable/disable the mouse cursor and cinematic bars respectively.
Note that it is rare for clients scripts to need to call this directly - consider using the cutscene functionality provided by the script libraries.

Parameters:

1

boolean

Enable or disables the script lock on the cinematic UI. By setting this, the script will lock the state of the cinematic UI (whether the cursor is shown, or the cinematic bars are visible). If this is set the wider UI will not be able to show/unshow the cursor or cinematic bars until the lock is disabled again.

2

boolean

optional, default value=nil

Shows or hides the cursor. If this flag is not supplied then the state of the cursor will remain unchanged.

3

boolean

optional, default value=nil

Enables the cinematic bars. If this flag is not supplied then the state of the cinematic bars will remain unchanged.

Returns:

  1. nil

Example - Enable the cinematic UI, disabling the mouse cursor and showing cinematic borders:

By enabling the cinematic UI with the first argument, the UI will know not to re-enable the mouse cursor or hide the cinematic borders.
bm:enable_cinematic_ui(true, false, true)

Example - Disable the cinematic UI, re-enable the mouse and hide the cinematic borders afterwards:

bm:enable_cinematic_ui(false, true, false)

battle:enable_unit_ids(boolean show ids)

Enables or disables the unit IDs - the flags or icons floating above each unit in battle. This provides exactly the same functionality as battle:set_banners_enabled, except the removal/reinstatement of banners in this case will be preserved in replays.
Note that the cutscene functionality provided by the script libraries automatically disables unit ids while the cutscene is playing - use cutscene:set_should_disable_unit_ids to disable this for a given cutscene rather than calling this function directly.

Parameters:

1

boolean

show ids

Returns:

  1. nil

battle:enable_cinematic_camera(boolean enable cinematic camera)

Enables or disables the cinematic camera. The cinematic camera is not limited by altitude or proximity to the player's army - it can be positioned anywhere on the battlefield, including below the ground. This can be enabled for cutscenes but should be disabled for live gameplay.
Note that it is rare for clients scripts to need to call this directly - consider using the cutscene functionality provided by the script libraries. A cutscene can be prevented from enabling the cinematic camera with cutscene:set_should_enable_cinematic_camera.

Parameters:

1

boolean

enable cinematic camera

Returns:

  1. nil

battle:enable_tooltips(boolean enable tooltips)

Enables or disables tooltips.

Parameters:

1

boolean

enable tooltips

Returns:

  1. nil

battle:force_minimised_tooltips(boolean set minimised tooltips)

Forces tooltips into minimised mode.

Parameters:

1

boolean

set minimised tooltips

Returns:

  1. nil

battle:disable_groups(boolean disable grouping)

Disables or enables grouping functionality.

Parameters:

1

boolean

disable grouping

Returns:

  1. nil

battle:disable_formations(boolean disable formations)

Disables or enables formations functionality.

Parameters:

1

boolean

disable formations

Returns:

  1. nil

battle:disable_orders(boolean disable orders)

Disables or enables the giving of any orders at all.

Parameters:

1

boolean

disable orders

Returns:

  1. nil

battle:steal_escape_key()

Steals the escape key from the UI. This prevents the UI from intercepting ESC key presses and allows script to detect and process them instead. When the escape key is stolen, a script function called Esc_Key_Pressed will be called when the escape key is pressed by the player.
Note that the escape key will remain stolen from the UI until battle:release_escape_key is called.

Returns:

  1. nil

battle:release_escape_key()

Releases the stolen escape key from the script, allows the UI to intercepting ESC key presses again. This must be called at some point after battle:steal_escape_key is called.

Returns:

  1. nil

battle:steal_input_focus()

Steals all keyboard input from the UI, effectively disabling the keyboard in the game. After input focus is stolen by a call to this function, it must be released again with battle:release_input_focus at some point.

Returns:

  1. nil

battle:release_input_focus()

Releases keyboard input back to the UI after its theft with battle:steal_input_focus.

Returns:

  1. nil

battle:disable_shortcut(string shortcut name, boolean should disable)

Disables or re-enables a keyboard shortcut by name. A list of keyboard shortcuts is available from the UI team.

Parameters:

1

string

shortcut name

2

boolean

should disable

Returns:

  1. nil

battle:set_banners_enabled(boolean show ids)

Enables or disables the unit IDs - the flags or icons floating above each unit in battle. This provides exactly the same functionality as battle:enable_unit_ids, except the removal/reinstatement of banners in this case will be not preserved in replays.
Note that the cutscene functionality provided by the script libraries automatically disables unit ids while the cutscene is playing - use cutscene:set_should_disable_unit_ids to disable this for a given cutscene rather than calling this function directly.

Parameters:

1

boolean

show ids

Returns:

  1. nil
Back to top

Querying

battle:is_replay()

Returns whether this battle is a replay.

Returns:

  1. boolean is replay

battle:is_tutorial()

Returns the value of the is_tutorial flag. This can be set in the battle setup to activate certain behaviours.

Returns:

  1. boolean is_tutorial flag

battle:is_multiplayer()

Returns whether this battle is running in multiplayer mode.

Returns:

  1. boolean is multiplayer

battle:is_from_campaign()

Returns whether this is a battle fought from campaign.

Returns:

  1. boolean is from campaign

battle:is_quest_battle()

Returns whether this battle is a quest battle.

Returns:

  1. boolean is quest battle

battle:prepare_for_fade_in()

Returns the value of the prepare_for_fade_in flag. This can be set in the battle setup to show a black screen when the battle starts up.

Returns:

  1. boolean prepare_for_fade_in flag

battle:battle_outcome_decided()

Returns whether a victor has been decided in the battle, or whether the battle has been determined to be a draw. This happens when the VictoryCountdown phase change occurs.

Returns:

  1. boolean outcome decided

battle:victorious_alliance()

Returns the id of the alliance which has won the battle. If battle results are not finalised then 0 is returned. If the battle result is drawn then -1 is returned.

Returns:

  1. number alliance id

battle:is_draw()

Returns true if the battle result has been finalised and is a draw, or false otherwise.

Returns:

  1. boolean is draw

battle:is_siege_battle()

Returns whether or not the battle is a siege battle.

Returns:

  1. boolean is siege battle

battle:is_ambush_battle()

Returns whether or not the battle is an ambush battle.

Returns:

  1. boolean is ambush battle

battle:is_storm_of_magic_battle()

Returns whether this is a storm of magic battle.

Returns:

  1. boolean is storm of magic battle

battle:battle_type()

Returns the battle type as a string.

Returns:

  1. string battle type

battle:unit_scale_factor()

Returns the unit scale factor as a multiplier. The value returned is a multiplier of the unit size if the scale is set to ultra, so the multiplier should be greater than 0 and less than or equal to 1.

Returns:

  1. number unit scale factor

battle:unit_scale_factor_index()

Returns the unit scale factor index. This is 0 for small unit sizes, 1 for normal unit sizes, 2 for large unit sizes and 3 for ultra unit sizes.

Returns:

  1. number unit scale factor index

battle:get_terrain_height(number x, number y)

Returns the height of the terrain at the specified x/y co-ordinates. This is intended for use to calculate camera and ping marker positions.

Parameters:

1

number

X co-ordinate in m.

2

number

Y co-ordinate in m.

Returns:

  1. number height in m.

battle:is_area_clear(battle_vector position, number bearing, number width, number depth, [boolean is naval])

Returns whether an area is clear of pathfinding restrictions. The area is specified by a position, a bearing, and the width/depth of a bounding box centred at that position and drawn at that bearing.

Parameters:

1

battle_vector

Position.

2

number

Bearing in degrees.

3

number

Width of oriented-bounding box in metres.

4

number

Depth of oriented-bounding box in metres.

5

boolean

optional, default value=false

Is the area on sea.

Returns:

  1. boolean area is clear

Example:

-- Checks if an area of 40m x 60m is clear of pathfinding restrictions.
-- The source position is [100, 100] and the area is drawn at a bearing of 90 degrees (i.e. east).
-- The corners of the area being checked would be at [70, 120], [130, 120], [130, 80], [70, 80]
return bm:is_area_clear(v(100, 100), 90, 40, 60);

battle:ground_type(battle_vector position)

Returns the ground type at a supplied position.

Parameters:

1

battle_vector

position

Returns:

  1. string ground type

battle:random_number()

Generate a battle-synchronised random number between 0 and 1.

Returns:

  1. number random number
Back to top

Benchmarking and Autotesting

battle:is_benchmarking_mode()

Returns whether this battle has been loaded in benchmarking mode or not. This should only return true if the battle was loaded through the benchmark menu on the frontend.

Returns:

  1. boolean is benchmarking mode

battle:end_benchmark()

Ends a currently-running benchmark, showing benchmarking statistics and ending the battle.

Returns:

  1. nil

battle:quit_to_windows_from_script()

Causes the game to completely shut down.

Returns:

  1. nil

battle:appdata_screenshots()

Returns a path to the screenshots directory. This is used by the autotest system.

Returns:

  1. string screenshot directory
Back to top

Global Attributes and Abilities

battle:set_stat_attribute(string attribute key, boolean enable/disable)

Enables or disables a unit attribute for all units on the battlefield. Attribute keys are listed in the Unit Attributes section of this documentation.

Parameters:

1

string

attribute key

2

boolean

enable/disable

Returns:

  1. nil

battle:set_special_abilities_flags(string flag key, boolean enable/disable)

Activates or deactivates a special ability flag for all units on the battlefield. Valid special ability flags are listed in the Special Ability Flags section of this documentation.

Parameters:

1

string

flag key

2

boolean

enable/disable

Returns:

  1. nil

battle:disable_all_abilities()

Disable all abilities on the battle

Returns:

  1. nil

battle:enable_all_abilities()

Disable all abilities on the battle

Returns:

  1. nil
Back to top

Survival Battles

battle:notify_survival_started()

Notifies the game that a survival battle has started.

Returns:

  1. nil

battle:notify_survival_total_waves(number total number of waves.)

Notifies the game how many total waves there are in a survival battle.

Parameters:

1

number

total number of waves.

Returns:

  1. nil

battle:notify_wave_state_changed(number wave index, string new state, boolean is final wave)

Instructs the game that a survival battle wave has changed state. This function is used to create a new survival battle wave, or update the state of an existing wave. Waves are specified a numeric index, starting from 0 - if a wave index is specified that the system has not seen before, then a new wave is started.
A survival battle wave can occupy one of three states - incoming, in_progress or defeated. The new state of the wave must be specified as a string.

Parameters:

1

number

Index of survival battle wave to update (or create, if index has not been used before).

2

string

New state of survival battle wave, either incoming, in_progress or defeated.

3

boolean

Is this wave the final wave in the battle.

Returns:

  1. nil

battle:notify_wave_units_changed(number wave index, string new state, boolean is final wave)

Instructs the game that a survival battle wave unit composition has been changed on a specific wave id.
A survival battle wave can occupy one of three states - incoming, in_progress or defeated. The new state of the wave must be specified as a string.

Parameters:

1

number

Index of survival battle wave to update (or create, if index has not been used before).

2

string

New state of survival battle wave, either incoming, in_progress or defeated.

3

boolean

Is this wave the final wave in the battle.

Returns:

  1. nil

battle:notify_wave_progress_changed(number wave index, number progress)

Updates the progress bar on the UI of the specified survival battle wave. This gives the player an indication of how far through the wave they are.

Parameters:

1

number

Index of survival battle wave to update. This should match the index of the wave previously specified to battle:notify_wave_state_changed.

2

number

Progress of the survival battle wave, specified as a unary (0-1) value.

Returns:

  1. nil

battle:notify_survival_completion()

Notifies the game that all survival battle waves are completed. This informs battle victory conditions related to survival battle waves that the survival battle has been successfully completed.

Returns:

  1. nil
Back to top

Battle Results

battle:force_battle_end(
  
number winning alliance number,
  string
reason,
  [boolean
immediate],
  [boolean
force winner]
)

Ends the battle in favour of one side or the other. A draw may also be specified.
A reason string must be specified from the following list:
  • none

  • timeout

  • kill_or_rout

  • kill_enemy

  • capture_settlement

  • capture_locations

  • sink_or_surrender_fleet

  • autoresolve

  • surrender

  • mp_disconnected

  • scripted

  • capture_baggage_train

  • avatar_autoresolve

  • mp_insufficient_human_players

  • scored_resoultion

  • tug_of_war

  • capture_location_score

  • wave_completion

  • capture_tickets

  • kill_or_rout_ignore_reinforcements

  • kill_or_rout_no_support_available

  • decision

Parameters:

1

number

Winning alliance number. If 0 is supplied then the battle will end as a draw.

2

string

Reason why the battle is ending - see list above.

3

boolean

optional, default value=true

End the battle immediately. If false the battle will end in the next conflict phase update.

4

boolean

optional, default value=true

Force the winning alliance value. If false is supplied the winning alliance will only be set if the battle has not already decided on a victor.

Returns:

  1. nil

battle:force_custom_battle_result(string result key, boolean for winner)

Forces a particular result for the battle being fought, for either the winner or the loser of the battle.

Parameters:

1

string

Result key, from the battle_result_types database table.

2

boolean

Is the result for the battle winner - supply false to apply the result for the loser instead.

Returns:

  1. nil
Back to top

Miscellaneous

battle:trigger_projectile_launch(
  
string projectile key,
  battle_vector
launch position,
  battle_vector
target position
)

Trigger a projectile launch from one position to another. Be careful to shoot downwards if you have artillery projectiles, as they are designed to be lobbed.

Parameters:

1

string

Projectile key from the projectiles table.

2

battle_vector

Launch position.

3

battle_vector

Target position.

Returns:

  1. nil

battle:spawn_vortex(string vortex key, battle_vector spawn position, battle_vector movement direction)

Spawn a vortex

Parameters:

1

string

2

battle_vector

spawn position

3

battle_vector

movement direction

Returns:

  1. nil

battle:unlock_achievement(string achievement key)

Unlocks a steam achievement by string key. Achievements have to be set up elsewhere to be unlockable with this function.

Parameters:

1

string

achievement key

Returns:

  1. nil

battle:output_battle_xml(string filename)

Writes out a battle xml file with the supplied filename containing the current battle setup. This can be useful for creating scripted battles.

Parameters:

1

string

filename

Returns:

  1. boolean operation succeeded

battle:save_unit_pair_balance_data(battle_unit unit_1, battle_unit unit_2, number engagement_winner)

Called by the unit balance tests. Saves the unit pair battle statistics and stats in DBLOG. (text file or SQL database depending of build the configuration.

Parameters:

1

battle_unit

unit_1

2

battle_unit

unit_2

3

number

Alliance of the winner of this engagement, 0 to draw

Returns:

  1. nil
Last updated 7/9/2024 11:45:05 AM