Scripting in Soil enables you to add extra functionality to your maps or entire gamemodes in your dataset. To add script to your map, simply create file called "<mapname>.script" inside map folder. You can also create general purpose script for scenario or multiplayer that will be used if map doesn't have its own script. To do this, create "scenario.script" or "multiplayer.script" in "scripts" folder in your dataset. You can start by copying "template.script" from "common" dataset's "scripts" folder.

Soil uses AngelScript as its scripting language. You can find most relevant AngelScript's part of documentation here. If you are familiar with C/C++ syntax, you should have no problem getting started. Otherwise, you can inspect scripts and try to figure it out, with help of above mentioned documentation, or post any questions on forums. You can also use functions and types from AngelScript add-ons string, arrays and math functions. You can use include directive with quotes to include other script files to your script. Use #include "relative.script" to include script in same directory as main script, #include "@dataset/yourfile.script" to include script in your dataset scripts folder, #include "@common/commonfile.script" to include script in common scripts folder.

Below is documentation of interfaces exposed to scripts. As a final quick note on scripting language, keep in mind that all arrays and indices start from zero! Therefore a correct way to check for boundary condition is index < numberOfElements

You can check your script's syntax using "script_validator.exe". Simply drag and drop your script file on the "script_validator.exe" to open it. This will also create logs next to your script. Those can be deleted.

Classes

Following classes are exposed to the script. vec3 is a simple 3D vector available in script as "value" type. All others are "reference" types and new instances cannot be created inside script. All except EngineInterface can be stored as global variables. Following are class hierarchies shown as class inheritance Base class > Derived class.

  • Targetable > Fighter
  • Targetable > Object
  • Object > Ship
  • Object > Subsystem
  • Object > Hardpoint
  • Object > Turret
  • Object > ResourceContainer
  • ResourceContainer > Debris

There is implicit casting from derived classes to base classes. That means that if you have reference to class, you can access properties and methods of its base classes. Remember that inheritance is transitive, so you can access methods of Targetable through reference to Debris

If you have reference to base class and want to access methods of derived class you must perform explicit cast. To determine what class object is, you use Targetable's method getObjectType(). Example:
You have Targetable@ thing; and calling thing.getObjectType() returns TYPE_SHIP. Now you can cast to Ship like this: Ship@ thing_as_ship = cast<Ship>(thing);. In this case, you could also cast to Object@. It is completely vital that you always check if you can perform cast before doing so. If possible, avoid at all.

Functions to implement by scriptback to navigation

MethodDescription
int preinitiateRemoveObject(Object@ object) This function is called before even initiate. Return non-zero if object should be removed. This should be used for adjusting difficulty, since script cannot erase objects at will
int initiate() This function is called before first step. Returns number of steps that script wishes to simulate before entering the mission. void step() is called during these as normal, only player doesn't see anything
void step() Called at the end of each game step. Game simulates STEPS_PER_SECOND steps per in-game second
string onMissionEnd() Called after last step when exiting map by script (not player action like returning to main menu or restarting) by calling EngineInterface.endMission(). Returns a name of map that should load after this. Object pools and persistent data will be available in the next map.
string getObjectives(uint isEscMenu) Returns string with writen objectives. Any "\n" will be converted to new line. If isEscMenu is non-zero, message is intended for escape menu. Technically, you don't need to make difference
bool briefing() Returns true if briefing phase should end. If mission doesn't have briefing, just return true. This function is called exactly on step number returned by initiate. Game does not run during this phase, but soil.stepNumber is still increased as normally so you can track time. Once briefing phase is over, soil.stepNumber is reset to number of presimulated frames
void onObjectCreated(Object@ object, uint warpedIn) Executes after step for all objects that were added to map on that step. warpedIn is non-zero if object was added by warping in. If ship warped in, it cannot receive orders or be targeted until it finishes warping. This takes EngineInterface.warpTime (in seconds).
void onObjectDestroyed(Object@ object) Executes after step for all objects that were destroyed on that step. You must remove all references to this object in your script. At this point, objects that were destroyed are no longer accessible through functions EngineInterface.getAll and others. So e.g. you can check if this was last ship destroyed with some tag byt checking if there are 0 ships with that tag left.
void onObjectWarpout(Ship@ ship) Same as above, but for ships that warped out. If ship warped out, onObjectDestroyed is not called
void onFighterDestroyed(Fighter@ fighter) Same as above, but for fighters. Fighters are kept in separate list to all other objects
void onButtonPressed(Player@ player, string id) Called at the end of step some time later after player pressed button added with id by script. player is here because of multiplayer scripts to identify who pressed what button, so games will be synchronized. Button press is using same mechanism as orders, so there will be delay a few frames between actual button press and this callback being executed
void logScript(string message) Writes a message to script log (and to console)
string int2str(int value) Converts integer value to string
string int2str(uint value) Converts unsigned integer value to string
string flt2str(float value, int numDecimals, bool fixedDecimals) Converts float value to string, with maximum of numDecimals. If fixedDecimals, decimals are always there, e.g "1.000"
int str2int(string integerAsString) Tries to read an integer value from string
float str2flt(string floatAsString) Tries to read a float value from string
bool str2bool(string boolAsString) Tries to read a bool value from string
uint randomUInt(uint count) Generates a random number between 0 and count (not including). E.g. "randomUInt(4)" can generate numbers 0, 1, 2, 3.
This generator is same as used for game logic, use this if you want to randomly generate something that will affect game. If you'll use ASYNC version, replays or multiplayer won't work correctly
uint randomUIntASYNC(uint count) Same as above, but uses random number generator independent of game logic. Use this for things that don't affect game, e.g. UI for one of players in multiplayer. If you use this for anything that alters the game in any way, replays won't work correctly and multiplayer will desync.

Enum functionsback to navigation

MethodDescription
string getShipTypeString(ShipType type) converts type to its string representation
string getSubsystemTypeString(SubsystemType type) converts type to its string representation
string getTurretTypeString(TurretType type) converts type to its string representation
string getTurretRoleString(TurretRole role) converts role to its string representation
string getOrderTypeString(OrderType type) converts type to its string representation
string getAbilityTypeString(AbilityType type) converts type to its string representation

vec3back to navigation

MethodDescription
float x
float y
float z
void setInvalid() Sets this vector to invalid position
bool isInvalid() Returns true if this vector represents invalid position
float length2(const vec3 vector) Returns length to the power of two of vector. This is fastest way to compare length of vectors if you just need to find smaller of vectors (e.g. compare 100 vectors with length2, then sqrt to get real length)
float fastLength(const vec3 vector) Returns length of vector. Slower than "length2", faster than "length". Use if you don't need to do additional precise calculations with this
float length(const vec3) Returns length of vector. Most precise of the three, but also slowest
vec3 fastNormalize(const vec3 vector) Normalizes vector using fastLength (faster, but not as precise)
vec3 normalize(const vec3 vector) Normalizes vector using length (slower, but precise)
float dot(const vec3 a, const vec3 b) Calculates dot product of vectors
vec3 cross(const vec3 a, const vec3 b) Calculates cross product of vectors
vec3 opAdd(const vec3)
vec3 opAdd(float)
vec3 opSub(const vec3)
vec3 opSub(float)
vec3 opMul(const vec3)
vec3 opMul(float)
vec3 opDiv(const vec3)
vec3 opDiv(float)

Playerback to navigation

MethodDescription
bool isDefeated() Returns true if this player is defeated
void setDefeated() Sets player as defeated, if not already victorious
bool isVictorious() Returns true if this player is victorious
void setVictorious() Sets player as victorious, if not already defeated
vec3 getColor() Returns player's primary color. This is the color that shows up on sensors. Colors are in range [0.0,1.0]
void setColor(vec3 color) Sets player's primary color. This is the color that shows up on sensors. Colors are in range [0.0,1.0]
vec3 getColorBase() Returns player's base/secondary color. This is the color that usually represents base paint of ships. Colors are in range [0.0,1.0]
void setColorBase(vec3 color) Sets player's base/secondary color. This is the color that usually represents base paint of ships. Colors are in range [0.0,1.0]
string getName() Returns name of this player
int getPlayerIndex() Returns index of player (can be used with EngineInterface.getPlayer(index)). This does not change during the mission
bool isAlly(Player@ other) Returns true if this player and other are allies. This means that both players don't shoot at each other
bool isEnemy(Player@ other) Returns true if this player is hostile towards other player. This may not be mutual. Neutral objects are never "enemy"
bool isNeutral() Returns true if this player is "neutral". This is special player and only this one is neutral. No player can be hostile towards neutral
bool isFriendly(Player@ other) Returns true if other player is either this player, or this player is not hostile towards other. other still may be hostile towards this player
void setAlliance(Player@ other) Sets this player and other as allies
void cancelAlliance(Player@ other) Cancels this player and other's alliance
void disallowVision(Player@ other) Turns off vision sharing for this and other. These players won't share vision even if they are allies
void allowVision(Player@ other) Turns on vision sharing between this and other player. These players must be allies to share vision
bool isPlayerLocal() Returns true if this player is currently controlled by human at this computer. Do not use for anything game altering, as this will break replays and multiplayer
bool isPlayerNetwork() Returns true if player is human playing over a network. Do not use for anything game altering, as this will break replays and multiplayer
float getStatsDamageDealt() Returns how much damage this player has done
float getStatsDamageTaken() Returns how much damage this player has taken
float getStatsDamageRepaired() Returns how much damage this player has repaired
float getStatsResourcesHarvested() Returns how much resources this player harvested
void disallowResearch(string name) Prevents research with name from being researchable by this player (name is name of the file in data/stats/research/, without the extension)
void allowResearch(string name) Allows research with name to be researchable by this player (name is name of the file in data/stats/research/, without the extension)
bool isResearchDisallowed(string name) Returns true if research with name is not allowed by this player (name is name of the file in data/stats/research/, without the extension)
uint getResearchQueueLength() Returns number of researchs that are currently queued by player (including currently researching)
float getResearchEffectXPGainMultiplier() const
float getResearchEffectXPMultiplierOffensive() const
float getResearchEffectXPMultiplierDefensive() const
float getResearchEffectXPOffensiveAsDefensive() const
float getResearchEffectXPDefensiveAsOffensive() const
float getResearchEffectBuildXPOffensive() const
float getResearchEffectBuildXPDefensive() const
float getResearchEffectBuildSpeedMultiplier() const
float getResearchEffectFighterServiceSpeedMultiplier() const
float getResearchEffectBuildCostShipMultiplier() const
float getResearchEffectBuildCostFighterMultiplier() const

HardpointStatback to navigation

MethodDescription
float maxHitPoints Hitpoints at full health
float armour Maximum armour (it will be lowered by taking damage, but slowly returns to full value, this is always full value, get actual value from object)
float resourceCost How much resources this component of ship costs (e.g. useful for determining cost of repairs)

SubsystemStatback to navigation

MethodDescription
float maxHitPoints Gitpoints at full health
float armour Maximum armour (it will be lowered by taking damage, but slowly returns to full value, this is always full value, get actual value from object)
float maxSubsystemHitPoints Maximum of subsystem hitpoints
float subsystemResistance Resistance to EMP damage. Works the same as armour, but cannot be lowered
float energyProductionPerSecond How much energy this subsystem produces per second if at full subsystem hitpoints
float resourceCost How much resources this component of ship costs (e.g. useful for determining cost of repairs)
float param1 TODO: dependent on subsystem type
float param2 TODO: dependent on subsystem type
float param3 TODO: dependent on subsystem type
float param4 TODO: dependent on subsystem type

ShipStatback to navigation

MethodDescription
string name Name of ship stat file. This is used to identify ship in game for spawning ships etc.
string displayTypeName Name that is display to player in UI
ShipType type
float turningAcceleration
float maxTurningVelocity
float deltaThrust
float maxThrust
float maneuverAcceleration
float virtualFriction
float maxVelocity
float firingDistance Distance at which ships stops from target
float stoppingDistance Distance ship travels if ordered to stop at full spee
float targetReorientThreshold If ships is facing in direction to its target, this defines how much better new direction needs to be for it to change. Value is between [0.0,1.0], 1.0 means always change. This is useful for e.g. broadsiding ship that gets its harpoints destroyed.
float energyCapacity How much energy capacity ship has. This is increased with offensive experience
float sensorDetection
float sensorFullInfo
uint crewCost How much "crew" ship requires to be build (and portion of this is spawned as escape pods when destroyed)
bool unyielding If true, ship will ignore obstacles like other ships, assuming they will avoid it. Useful for large slow ships, so they don't waste time going around corvette or something
bool buildable True if ship can be built at regular shipyard (false for e.g. station, civilian or mission specific ships)
bool buildableSmall True if ship can be built at small shipyard
bool buildableSupport True if ship can be built at support shipyard
bool mpFleetable True for ships that can be added to fleet when starting multiplayer
bool mpShipyard True if this ship is intended to be shipyard/station for multiplayer). First ship for faction with this flag is used
string getFullDisplayName() const Returns full display name (e.g. display name of "vr_orion" is "Orion", full display name is "Orion-class heavy cruiser"
float getCost() const Returns base cost of this ship. This is used to calculate resources for scrap, repair, and debris
float getStartingResources() const Returns total starting resources when this ship is built
float getCostBuild(float researchbuildCostMultiplier) const Returns total resource cost to build this ship, including research and starting resources
uint getCrewCost() const Returns crew cost to build this ship
uint getFightergroupCapacity() const Returns how many fighter groups this ship can house (from all fighter bays)
float getCargoCapacity() const Returns total cargo capacity of this ship type
float getTotalHitpoints() const Returns total hitpoints from all subsystems and hardpoints

Targetableback to navigation

MethodDescription
bool isTargetable() Returns true if object can be targeted by turrets or orders. False is usually for ships warping out or about to explode
ObjectType getObjectType() Returns object type. Useful to find out what this object is so it can be safely cast to
Player@ getOwner() Returns player that owns this object
void setOwner(Player@ player) Sets player as owner of this object
float getArmour() Returns current armour rating for this object (is 0.0 for Ship). Will be different from armour value from stat when taken damage. It will eventually return to max value if at full health
uint getNumAttackers() Returns number of ships that recently damaged this object (use EngineInterface.getAttacker to get attacker by index). Currently 24 seconds
vec3 getPosition() Returns position of this object
void setPosition(vec3 position) Sets position of object to position. If you're animating object to be moving along a trajectory, you should set velocity as well so renderer can extrapolate position for rendering
vec3 getVelocity() Returns velocity of this object
void setVelocity(vec3 velocity) Sets velocity of this object to velocity. If you're animating object to be moving along a trajectory, you should set velocity as well so renderer can extrapolate position for rendering
vec3 getFrontDirection() Returns direction which object is pointing (default front direction is X+). This is most useful for ships
void setLookAt(vec3 position) Sets orientation of object so it points towards position
float getDistance2(const Targetable@ other) Returns squared distance to other object. This is just shortcut to getting positions and doing it yourself
bool isSensorVisible(const Player@ player) Returns true if object appears on sensors for player at least as unknown object. It returns true also if isSensorFull returns true
bool isSensorFull(const Player@ player) Returns true if object appears on sensors for player and all information about it is displayed
void setCustomColors(vec3 color, vec3 baseColor) Sets custom colors for this object. By default object has color and baseColor of its owner. This method overrides them. Useful for hero or given units. Object still appears on sensors with owner's color. Only "paint" is affected
void clearCustomColors() Resets object to use owner's colors

Objectback to navigation

inherits from Targetable
MethodDescription
DamageLevel getDamageLevel() Returns damage level of this object. For Ship, CRITICAL means that ship is currently exploding, but you should probably not base anything on damage level of Ship
void setDamageLevel(DamageLevel level) Sets damage level to level and hitpoints to maximum for that damage level. Does nothing for objects of type Ship, you need to set it to its subsystems and hardpoints. If subsystem is set to DESTROYED, all of it's hardpoints are set to DESTROYED as well
string getDesignation() returns name designated for this object by human player. E.g. ship he really likes
string getStatName() const Returns stat name of this object, e.g. "vr_frigate"
float getHitpoints() Returns current hitpoints of this object. If it is Ship you need to call Ship.getShipStatus
float getMaxHitpoints() Returns current maximum hitpoints of this object. If it is Ship you need to call Ship.getShipStatus
bool damage(Object@ aggressor, float amount, bool canApplyDamageReduction) Damages this object by amount. If canApplyDamageReduction is true, this damage is reduced by defensive experience, if you want to do exact damage, set it to false. aggressor is object that should be attributed with dealing this damage (it should be Ship, it is also added to list of attackers. Can be null. If this object is Ship damage is applied to shields first, then distributed to subsystems. Returns true if object got destroyed as a result of this damage call
void damageEMP(Object@ aggressor, float amount) Applies amount of EMP damage to this object. aggressor behaves same as for "damage", also can be null. If this object is Ship, EMP damage is first applied to shields, then distributed to subsystems
float getArmourMax() Returns maximum amount of armour for this object. Returns 0 for objects of type Ship
void setArmour(float amount) Sets armour to amount
float getGasValue() const
bool hasTag(string tag) Returns true if one of the tags of this object is tag. You can use tags to identify objects, e.g. set tags in map editor, or add tags to spawned ships so you can identify them in onObjectCreated
void addTag(string tag) Adds tag to tags of this object. If object already has tag tag nothing changes (same tag can only be on object once)
void removeTag(string tag) Removes tag tag from object's tags
void removeTags() Removes all tags from object

ResourceContainerback to navigation

inherits from Object
MethodDescription
int getResourcesLeft() Returns remaining resources
int getCrystalsLeft() Returns remaining crystals
bool isMineable(bool resources, bool crystals) Returns true if resources is true and it contains resources, or crystals is true and it contain crystals ((resources && getResourcesLeft() > 0) || (crystals && getCrystalsLeft() > 0))

Debrisback to navigation

inherits from ResourceContainer
MethodDescription

Shipback to navigation

inherits from Object
MethodDescription
ShipType getShipType() const
const ShipStat@ getStat() const
string getFullDisplayName() const Same as function on ShipStat
OrderType getOrder() const Returns current order assigned to this ship. If it has no orders, returns SHIP_ORDER_NONE
AbilityType getOrderAbility() const Returns ability ordered if ship order is SHIP_ORDER_ABILITY_CAST. For non-cast abilities, see Ship.hasActiveAbility
Object@ getTarget() const Returns target related to current order. If ship has no order and it turns itself towards nearby enemy or resource, this method still returns null because it is not target of player's order
vec3 getDestination() const Returns position related to player's order. Has meaningful value only if order is not SHIP_ORDER_NONE
float getFiringDistance() const Same method as on ShipStat
void setDisarmedStatus(bool disarmed) If disarmed is set to true, turrets from this ship are removed
bool getDisarmedStatus() const
bool canPerformOrder(OrderType order, const Object@ target) Returns true if this ship can do order of type order. If target is not null, it is additionally check if given order can be performed on this target (e.g. ship that can perform SHIP_ORDER_ATTACK will still return false if target is friendly)
bool isInoperable() Returns true if ship can operate (not scaffolded or exploding)
bool isScaffolded() Returns true if any object has scaffold on it (being repaired or scrapped)
bool isUnderConstruction() Returns true if ship is currently being built by shipyard
bool isBeingScrapped() Returns true if ship is currently being scrapped by shipyard
float getRepairCostTotal() Returns amount of resources it will take to repair this ship
float getScrapValue() Returns amount of resources that will be refunded by scrapping this ship by shipyard
uint getConstructionQueueLength() Returns number of ships that are in build queue of this ship. It does not include ships already being built
bool canBuildShip(const ShipStat@ stat, array<string>@ blockedByResearch = null)
ShipStatus getShipStatus()
float getShieldHitpoints()
float getShieldMaxHitpoints()
void setShieldHitpoints(float)
float getCargoCapacity() const
float getCargoResources() const
float getCargoCrystals() const
float getEnergy() const
float getEnergyCapacity() const
int getMaxPassengers() const Returns max number of "crew" in this ships crew quarters. Crew is used to build new ships
int getPassengers() const
uint getNumSubsystems() Returns number of subystems this ship has
Subsystem@ getSubsystem(uint index) Returns subsystem at index, or null if index is out of range
bool canCastAbilityOn(AbilityType type, Object@ target) Returns true if this ship can cast ability of type, this also includes if ship has activation energy cost. If target is not null it also tests if ability can be cast on that target. If ability is not cast (applied on self), don't provide target
bool hasActiveAbility(AbilityType type) Returns true if ship has active ability of type. For abilities cast on other ships, use Ship.getOrder and Ship.getOrderAbility
float getShipAutoTargetScore(const Object@ target) Returns targeting "score" of target for this ship. Higher score means that ship would prefer to attack this target over objects with lower score. This is only based on this ship's ship type and targets type/ship type
float getExperienceOffensive() Returns offensive experience of this ship. See EC in editor to see what this affects
float getExperienceDefensive()
void setExperienceOffensive(float experience)
void setExperienceDefensive(float experience)
void setHero(bool heroStatus) Sets heroStatus of this ship. Hero ships can use abilities without them being researched. They can also have abilities that their base ship class doesn't have (hero only)
void isHero()
bool loadCargo(float resources, float crystals) Magically loads amount of resources and crystals to this ship. If there is not enough space for this cargo, false is returned and as much cargo as fits is loaded, with crystals being loaded first
bool unloadCargo(float resources, float crystals) Magically unloads amount resources and crystals from this ship. If there is not enough of either cargo on this ship, false is returned and no cargo is removed
bool loadPassengers(int count) Magically loads count of crew into this ship. If there is not enough space, false is returned and as much passengers fit are loaded
bool unloadPassengers(int count) Magically removes count of crew from this ship. If there is not enough crew on this ship, false is returned and no crew is removed
void cheatRestoreShield()
void cheatRestoreEnergy()
void cheatFillCrewquarters()
void cheatFillCargoholds()
void cheatReloadMissiles()
void cheatServiceFighters()

Subsystemback to navigation

inherits from Object
MethodDescription
const SubsystemStat@ getStat()
float getRepairCostTotal() Returns amount of resources needed to repair this subsystem to INTACT
float getRepairCostPerDamageLevel() Returns amount of resources needed to repair this subsystem by one damage level
SubsystemType getSubsystemType()
float getSubsystemHealth() Returns value in range of [0.0,1.0] (this is from subsystem hitpoints, not from regular hitpoints)
void setSubsystemHealth(float value) Sets health of subsystem to value in range of [0.0,1.0]
uint getNumHardpoints() Returns number of hardpoints this subsystem has
Hardpoint@ getHardpoint(uint index) Returns hardpoint at index, or null if index is out of range
Ship@ getParentShip() Returns parent ship of this subsystem

Hardpointback to navigation

inherits from Object
MethodDescription
const HardpointStat@ getStat()
float getRepairCostTotal() Returns amount of resources needed to repair this hardpoint to INTACT. This does not include cost or repairing subsystem if it is destroyed
float getRepairCostPerDamageLevel() Returns amount of resources needed to repair this hardpoint by one damage level
uint getNumTurrets() Returns number of turrets this hardpoint has
Turret@ getTurret(uint) Returns turret at index, or null if index is out of range
Ship@ getParentShip() Returns parent ship of this hardpoint
Subsystem@ getParentSubsystem() Returns parent subsystem of this hardpoint

Turretback to navigation

MethodDescription
TurretType getTurretType()
TurretRole getTurretRole()
float getTargetingRange() Returns distance at which turret can lock targets
float getDamagePerMinute(float versusArmour, bool useEMPdamage) Returns damage per minute of this turret (not taking into account any damage)

Fighterback to navigation

inherits from Targetable
MethodDescription
string getStatName() const
int getAmmoLeft() Returns number of rounds this fighter has left (this applies to all types, even beams). When group average reaches too low, fighter group will return to carrier to rearm

EngineInterfaceback to navigation

MethodDescription
uint stepNumber Step number of simulation, every mission starts at 0. Script can set how many frames are simulated before first image is show to player (e.g. to wait for some explosions, ships to open fire, etc.). Game simulates STEPS_PER_SECOND steps per second (unless there were some big changes, this should be 20)
uint orderDelay When player gives orders, it takes this many frames until they are applied. Don't use this for anything other then to display it? I have no idea why it is even here
int screenWidth Screen width in pixels. Obviously use this only for UI (0 is left, screenWidth is right)
int screenHeight Screen height in pixels. Obviously use this only for UI (0 is bottom, screenHeight is top)
float uiScaling It should be applied to button sizes, offsets and font sizes. Obviously use this only for UI (default is 1.0f)
float warpTime Time in seconds it takes from when ship starts warping in/out until it is finished. Unless I fixed it, ships cannot receive orders while warping, delay any orders for them from their creation for at least this time. This is constant, it never changes
float warpWarmup Minimum time in seconds it takes from when ship is ordered to warp out until it starts warping. Ship needs to face correct direction, so it might take longer (or never happen). This does not apply for microwarp ability, that is individual for ability. This is constant, it never changes
bool lastManStanding Is true if current multiplayer match victory rule is last man standing (as opposed to based on damage done)
bool debugDraw Is true if user wants script to draw debug information (what that means is up to script). This can be turned on in script debugger (while in game, press SHIFT + F5)
uint getNumAll() Returns number of all objects of all types in map, except for fighters. Fighters are kept in separate list
Object@ getAll(uint idx) Returns object of any type at index idx, or null if out of range
uint getNumObjects() Returns number of generic objects in map (these are objects that are not Ship, Fighter, Debris, or ResourceContainer)
Object@ getObject(uint idx) Returns generic object at index idx, or null if out of range
uint getNumResourceContainers() Returns number of resource containers (generic objects that can have resource to be mined, but can also be empty) in map
ResourceContainer@ getResourceContainer(uint idx) Returns resource container at index idx, or null if out of range
uint getNumDebris() Returns number of debris in map (remnants of destroyed objects that can be mined for resources by salvages, if debris is from ship)
Debris@ getDebris(uint idx) Returns debris at index idx, or null if out of range
uint getNumShips() Returns number of ships in map (this includes stations, everything with subsystem counts as ship)
Ship@ getShip(uint idx) Returns ship at index idx, or null if out of range
uint getNumFighters() Returns number of fighers in map
Fighter@ getFighter(uint idx) Returns fighter at index idx, or null if out of range
Ship@ getAttacker(Targetable@ object, uint attackerIndex) Returns attacker of object with index attackerIndex. You can get number of attackers of object with Targetable.getNumAttackers(). Returns null if index is out of range, attacker is not of type Ship, or attacker no longer exists
Player@ getPlayerNeutral() Returns neutral player. This is a special player not included in in getNumPlayers
uint getNumPlayers() Returns number of players in this map, this does not include neutral player. Players are not added, removed, or reordered during the game
Player@ getPlayer(uint) Returns player by index. If index is out of range, returns neutral player. Players are not added, removed, or reordered during the game
Player@ getPlayer(string name) Returns player by name. This is what is set in editor or what you see on result screen. If there is no player with name, null is returned
vec3 getPointOfInterest(string name) Returns a position with name marked as point of interest in map editor. If there is no position with name, result is invalid position, you can query validity with vec3.isInvalid()
void issueOrder(Ship@ ship, OrderType order, Object@ target, vec3 position, bool queue, string additionalInfo) Issues order of type order to ship. Orders will use target or position depending on type of order (e.g. escort needs target, move needs position). If queue is true, order is placed at the end of order queue, as if player held shift key. If queue is false, current order is cancelled, queue emptied, and this order becomes current order.
additionalInfo is used dependent on order type. If it is not empty string, for SHIP_ORDER_WARP_OUT it denotes to what object pool will ship be added when warped out, for MISC_ORDER_OBJECT_DESIGNATION_SET name of this ship, for SHIP_ORDER_ADD_FIGHTERGROUP what type of fighter group to add, for SHIP_ORDER_REMOVE_FIGHTERGROUP index at which remove, for SHIP_ORDER_SCAFFOLD_CONSTRUCT what type of ship to build, and what tags to assign (e.g. "vr_cruiser" for no tags, or "vr_cruiser|tag_defense|tag_ai_made" for multiple tags)
void issueOrderArray(Ship@ ship, OrderType order, array<Object@>@ target, bool queue) issueOrder version with multiple targets. This version creates order group, ship will automatically choose/switch between targets in one group as it sees fit instead of executing them one by one
void issueOrderMisc(Player@ player, OrderType miscOrderType, string additionalInfo) Apply misc orders. (currently only documented one is MISC_ORDER_GIVE_UNITS, which changes desired game speed for player, with possible values of additionalInfo {"1","2","3","4"})
void activateAbility(Ship@ ship, AbilityType ability) Orders ship to activate ability. Technically could be done with issue order, but target, position, queue, additionalInfo is irrelevant, and you can use enum for type
void deactivateAbility(Ship@ ship, AbilityType ability) Orders ship to deactivate ability. Technically could be done with issue order, but target, position, queue, additionalInfo is irrelevant, and you can use enum for type
void castAbility(Ship@ ship, AbilityType ability, Object@ target, bool shift) Orders ship to cast ability on target. Most abilities can target only ships. Cast abilities work as regular orders when it comes to shift.
void spawnShip(string statName, uint number, Player@ owner, vec3 position, vec3 lookAtPoint, bool asWarp, string tag) Creates number of ships of of type statName, assigned to player owner, at position facing towards lookAtPoint. If asWarp is true, spawned ships will warp in at position arriving from direction so they would face lookAtPoint, if false, they magically appear at position. If tag is not empty string, it will be added as tag. To add multiple tags, separate them by '|', e.g. "tag1|tag2|tag3"
void spawnFighterGroup(string statName, uint numberOfFighters, Player@ owner, vec3 position, Ship@ parentShip) Creates fighter group of statName type of fighters with numberOfFighters at position. Fighter group is given to player owner. If parentShip is specified, it is attached to that ship if it still has empty slot in fighter bay, and owner must be same as parentShip's owner. parentShip as null is useful when you want to spawn escape pods that will return to owner's station.
uint getNumObjectsInPool(string poolName) Returns number of objects in pool called poolName
void respawnFromPoolFirst(string poolName, Player@ owner, vec3 position, vec3 lookAtPoint, string addTag, ShipSpawnMethod spawnMethod) Respawns first object in pool poolName at position facing towards lookAtPoint. Object is given to player owner and tag addTag is added to it. If object is Ship, spawnMethod dictates how it should spawn, if DEFAULT is selected, ship spawns in the fashion it despawned (disappear, warp out)
void respawnFromPoolLast(string poolName, Player@ owner, vec3 position, vec3 lookAtPoint, string addTag, ShipSpawnMethod spawnMethod) Respawns last object in pool poolName at position facing towards lookAtPoint. Object is given to player owner and tag addTag is added to it. If object is Ship, spawnMethod dictates how it should spawn, if DEFAULT is selected, ship spawns in the fashion it despawned (disappear, warp out)
void respawnFromPoolAll(string poolName, Player@ owner, vec3 position, vec3 lookAtPoint, string addTag, ShipSpawnMethod spawnMethod) Respawns all objects in pool poolName at position facing towards lookAtPoint. Objects are given to player owner and tag addTag is added to them. If object is Ship, spawnMethod dictates how it should spawn, if DEFAULT is selected, ship spawns in the fashion it despawned (disappear, warp out). Only for this method, formation spawn types make any sense
void storeObjectToPool(Object@ object, string poolName, bool saveSelectionGroup) Removes object from map and stores it to pool with name poolName. If saveSelectionGroup is true, number of selection group is remembered so it is in that group when you respawn it, e.g. in next mission. Other way how object can get into pool is by warping out, with pool name as order's additionalInfo
NOTE: this function only works when called inside of onMissionEnd()
void endMission() Ends mission, exiting current map after current step is finished (script will still run after this call). When the mission is ended this way, onMissionEnd() will be called, in which you can call EngineInterface.storeObjectToPool(), and indicate next mission if any
void addUIGroup(string groupID, string config) TODO: move stuff here from add button
void setUIGroupCorners(string groupID, int left, int bottom, int right, int top) TODO: move stuff here from add button
vec3 getUIElementCenter(string groupID, string id) TODO:
vec3 getUIElementSize(string groupID, string id) TODO:
void addButton(string groupID, string id, string text, int x, int y, int width, int height, bool enabled) TODO: update this Adds button to user interface, placed in a group with groupID, identified by id, centered at x,y. It is recommended that width and height be even numbers. enabled indicates whether or not button is clickable (it also renders differently, usually darker). config is .buttongroup styling config found in data/textures/gui that should be applied to this button. useScissor tells whether text, lines and polygons associated with this button should be clipped by its bounding box. config is only applied when button is first created, other values are updated if button exists. Button exists for single step only, and must be renewed every step as long as you wish to display this button.
void addLabel(string groupID, string id, string text, int x, int y, int width, int height, float alphaOverride = -1.0f) TODO:
void addTextArea(string groupID, string id, string text, int x, int y, int width, int height, bool enabled) TODO:
void createMessagebox(string title, string message) Creates a message box. Intended to be used for error messages or some such
void setFontStyleDefault() Sets font style to default, without outline
void setFontStyleDefaultOutline() Sets font style to default, with outline
void setFontStyle(bool outlineEnabled, vec3 outlineColor, float outlineOpacity, float outlineInner, float outlineOuter, vec3 outlineOffset) Sets style for font outline. outlineInner is distance from text where outline has full opacity, outlineOuter is distance from text where outline reaches zero opacity. outlineOffset is how much is outline offset from base text, this creates sort of drop-shadow (z is ignored). outlineColor is in range [0.0, 1.0]
void drawText(string text, int x, int y, vec3 color, float alpha, string font, int height) Draws text on screen at coordinates x, y (0,0 is at left bottom). color and alpha is in range [0.0, 1.0]. font is one of file names in data/fonts, without extension. height is approximate in pixels
uint getTextWidth(string text, string font, int height) Returns expected width in pixels of text when rendered in font with height. This does not include outline
string createColorTag(vec3 color, float alpha) Returns string that you can insert into text that you want to render to change color mid-text. color and alpha are in range [0.0, 1.0]
string createFontTag(string face, uint size) Returns string that you can insert into text that you want to render to change font mid-text.
void insertTextMessage(string message, float displayTime) Adds text message that will be display above bottom panel, such as dialog, objective related messages, or to display mission rewards
void playSound(string soundName, float gain, bool isVoice) Plays a sound. soundName is name of file to play in data/sounds/ (without extension). gain is volume multiplier at which sound will play, it is clamped to [0.0, 1.0] interval. If isVoice is true, it is added to queue of voice sounds, these play one at the time. If isVoice is false, sound plays immediately
void playUISound(string soundName, bool isPriority) Plays an UI sound. soundName is name of file to play in data/sounds/ (without extension). If isPriority is true, it is added to queue of voice sounds, these play one at the time. If isVoice is false, sound plays immediately
void drawSensorIcon(SensorIconType icon, vec3 position, vec3 color, float opacity) Draws sensor icon of type icon, placed at position in color. color is in range [0.0, 1.0]. This can be used to e.g. indicate mission objective.
void drawLine(vec3 position0, vec3 position1, vec3 color0, float alpha0, vec3 color1, float alpha1, bool is3D) Draws a line from between two positions. If is3D is true, line will be drawn in world space, if false then in screen space (in pixels). colors and alphas are in range [0.0, 1.0].
void drawLineUI(string groupID, vec3 position0, vec3 position1, vec3 color0, float alpha0, vec3 color1, float alpha1) Same as above, but line is drawn together with UI created with e.g. addButton. This will draw it to same UI layer as the group with groupID, allowing it to be drawn over other UI. This is always in 2D
void polygonPointUI(string groupID, vec3 position) Adds another point to current polygon.
void polygonFinishUI(string groupID, vec3 color, float opacity) Creates a new polygon from previous points. Only convex polygons will draw correctly. If you want to draw concave polygons, you need to break them into convex parts yourself
vec3 getProjectedPosition(vec3 worldPosition) Returns projected worldPosition to screen space (in pixels)
void setCameraCenter(vec3 position) Sets camera center to position. Center is position around which camera rotates
void setCameraView(vec3 position, vec3 center, vec3 centerVelocity, bool instantSkip) Sets camera to position, looking at center
void giveResearch(string name, Player@ player) Gives research with name to player. name is file name found in data/stats/research/ without the extension (as always)
void giveAllResearch(Player@ player) Gives all research to player
void giveAllFreeResearch(Player@ player) Gives all research that doesn't cost research crystals to player. This is preferred method when wanting the player to build anything, as it won't give research that would boost production speed, reduce costs, or increase experience of built ships
void removeResearch(string name, Player@ player) If player has already researched name, it will remove it from them. This can be useful to remove obsolete ships from being able to be built, or to temporarily allow building some ships by giving hidden research, then removing it.
void removeAllResearch(Player@ player) Removes all research from player
void allowResearch(string name, Player@ player) Allows player to research name. This can be used by disallowing all research, then allowing more as campaign or mission progresses
void allowAllResearch(Player@ player) Allows all research for player
void disallowResearch(string name, Player@ player) Disallows research name for player
void disallowAllResearch(Player@ player) Disallows all research for player
bool hasResearch(Player@ player, string name) Returns true if player has researched name
bool hasResearchForShip(Player@ player, string ship) Returns true if player has all required research to build ship
bool hasResearchForFighter(Player@ player, string fighter) Returns true if player has all required research to build fighter
array<string> @getQueuebleResearch(Player@ player) Returns all research player can currently enqueue. This is all research that is clickable in UI (not hidden, not disallowed, with prerequisities researched or queued)
void queueResearch(string name, Player@ player) Adds research name to queue for player
void queueResearchForShip(Player@ player, string ship) Adds research for player required to build ship
void queueResearchForFighter(Player@ player, string fighter) Adds research for player required to build fighter
const ShipStat@ getShipStat(string name) Returns ship stat by name. Returns null if no such ship stat exists. If you already have Ship instance, you can use Ship.getStat() to get its stat. This should be used when you don't have instance of ship.
void setPersistentData(string key, string value) Saves value under key to persistent data. This data is carried over to next missions. If you want to save ships that carry over, use object pools
string getPersistentData(string key) Returns persistent data stored under key, or empty string if there is nothing stored under that key
void logPersistentData() Dumps all persistent data to script log. This is for easier debugging of what is stored there.
void logObjectPools() Dumps info about object pools to script log. This prints all saved pool names along with number of objects in them
string getMissionParameter(string parameter) Returns value of

parameter

for this mission. These are displayed and user can select values when starting mission. Described in .config in the map's folder
bool isObjectiveHighlighted(int index) Returns value of

parameter

for this mission. These are displayed and user can select values when starting mission. Described in .config in the map's folder
void awardAchievement(string achievement) Awards achievement. These are found in data/stats/achievement/. Awarded achievement will be displayed even if it wasn't shown be showAchievement
void showAchievement(string) Achievements are hidden by default, only displayed as ???. With this you can show it without awarding it, e.g. when mission is finished in which this is awarded

ShipStatusback to navigation

MethodDescription
float damagePerMinute Damage per minute of all attack turrets that don't primarily target fighters. It is possible that not all turrets can reach single target due to layout of being out of range, it their targeting range is smaller than ship's firing distance. For missile launchers, fire rate is used, it will be lower when launcher will run out of missiles and will need to replenish them
float damagePerMinuteAlphaWeighted Same as above, but damage is multiplied by damage of single projectile (or damage per second in case of beam turrets), divided by 100. Frigate with fast firing guns can have same damagePerMinute as battleship with slow firing, but hard hitting guns (low damage projectiles can get blocked by armour). This is meant to give more meaningful value against armoured targets
float hitpoints Gets total hitpoints of all subsystems and hardpoints (shields are not included)
float hitpointsMax Gets total max hitpoints of all subsystems and hardpoints (shields are not included)
float hitpointsArmourWeighted Same as above, but hitpoints of each subsystem and hardpoint are multiplied by their armour/100
float energyPerSecond Current energy generation per second. Subsystems generate energy based on how damaged they are (subsystem hitpoints, not regular hitpoints)
float energyPerSecondMax Maximum energy generation per second (if subsystems are undamaged)
float energyLeft Current amount of energy available
float energyCapacity Maximum energy capacity. This will be higher than base value in ShipStat when ship has any experience
int getThreatLevel() const Computes default level of threat this ship represents from all of above values. You can use this for target prioritization, dynamic difficulty, etc. Or you can make your own thing

Enumsback to navigation

DamageLevel

INTACT
DAMAGE
CRITICAL
DESTROYED

ObjectType

TYPE_OBJECT
TYPE_SHIP
TYPE_SUBSYSTEM
TYPE_HARDPOINT
TYPE_TURRET
TYPE_DEBRIS
TYPE_RESOURCE_CONTAINER
TYPE_FIGHTER

ShipType

SHIP_UNKNOWN
SHIP_CORVETTE
SHIP_FRIGATE
SHIP_DESTROYER
SHIP_CRUISER
SHIP_BATTLECRUISER
SHIP_BATTLESHIP
SHIP_CARRIER
SHIP_STATION
SHIP_RESOURCE_COLLECTOR
SHIP_REPAIR
SHIP_PLATFORM
SHIP_CIVILIAN
SHIP_CARGO
SHIP_RESEARCH

SubsystemType

SUBSYSTEM_TYPE_UNKNOWN
SUBSYSTEM_TYPE_HULL
SUBSYSTEM_TYPE_ENGINE
SUBSYSTEM_TYPE_SENSORS
SUBSYSTEM_TYPE_COMMS
SUBSYSTEM_TYPE_CARGOHOLD
SUBSYSTEM_TYPE_FIGHTERBAY
SUBSYSTEM_TYPE_DROPOFF
SUBSYSTEM_TYPE_SHIPYARD
SUBSYSTEM_TYPE_REACTOR
SUBSYSTEM_TYPE_WARPCORE
SUBSYSTEM_TYPE_SHIELD_PROJECTOR
SUBSYSTEM_TYPE_GARDEN
SUBSYSTEM_TYPE_CREWQUARTERS
SUBSYSTEM_TYPE_BALAST

TurretType

TURRET_TYPE_UNKNOWN
TURRET_TYPE_GUN
TURRET_TYPE_BEAM
TURRET_TYPE_BEAM_MINER
TURRET_TYPE_BEAM_REPAIR
TURRET_TYPE_BEAM_SALVAGER
TURRET_TYPE_MISSILE_LAUNCHER
TURRET_TYPE_FLAK

TurretRole

TURRET_ROLE_UNKNOWN
TURRET_ROLE_ANTI_FIGHTER
TURRET_ROLE_ANTI_FIGHTER_SHIP
TURRET_ROLE_ANTI_SHIP_FIGHTER
TURRET_ROLE_ANTI_SHIP
TURRET_ROLE_LONG_RANGE

OrderType

SHIP_ORDER_NONE
SHIP_ORDER_CANCEL_ORDERS
SHIP_ORDER_AUTO_DECIDE
SHIP_ORDER_STOP
SHIP_ORDER_ESCORT
SHIP_ORDER_TURN
SHIP_ORDER_MOVE
SHIP_ORDER_ATTACK
SHIP_ORDER_SORTIE_FIGHTERS
SHIP_ORDER_SORTIE_FIGHTERS_ATTACK
SHIP_ORDER_SORTIE_FIGHTERS_ESCORT
SHIP_ORDER_LAUNCH_FIGHTERS
SHIP_ORDER_DOCK_FIGHTERS
SHIP_ORDER_CHANGE_BOMBER_HOLDING_ON
SHIP_ORDER_CHANGE_BOMBER_HOLDING_OFF
SHIP_ORDER_CHANGE_LAUNCH_FULL_ON
SHIP_ORDER_CHANGE_LAUNCH_FULL_OFF
SHIP_ORDER_ADD_FIGHTERGROUP
SHIP_ORDER_REMOVE_FIGHTERGROUP
SHIP_ORDER_SCAFFOLD_REPAIR
SHIP_ORDER_SCAFFOLD_SCRAP
SHIP_ORDER_SCAFFOLD_CONSTRUCT
SHIP_ORDER_CANCEL_CONSTRUCTION_QUEUE
SHIP_ORDER_HARVEST
SHIP_ORDER_HARVEST_RETURN
SHIP_ORDER_DROP_CARGO
SHIP_ORDER_PICK_CARGO
SHIP_ORDER_SELF_DESTRUCT
SHIP_ORDER_ABANDON_SHIP
SHIP_ORDER_ABILITY_ACTIVATE
SHIP_ORDER_ABILITY_DEACTIVATE
SHIP_ORDER_ABILITY_CAST
SHIP_ORDER_WARP_IN
SHIP_ORDER_WARP_OUT
SHIP_ORDER_LOOP
MISC_ORDER_ALLIANCE_CHANGE
MISC_ORDER_OBJECT_DESIGNATION_SET
MISC_ORDER_GAME_SPEED_CHANGE
MISC_ORDER_FORCE_DEFEAT_PLAYER
MISC_ORDER_SCRIPT_BUTTON_PRESSED
MISC_ORDER_RESEARCH_START
MISC_ORDER_RESEARCH_CANCEL
MISC_ORDER_RESEARCH_REFUND
MISC_ORDER_GIVE_UNITS

AbilityType

ABILITY_NONE
ABILITY_REACTOR_OVERLOAD
ABILITY_SELF_REPAIR
ABILITY_AFTERBURNERS
ABILITY_MICROWARP
ABILITY_WEAPON_OVERCHARGE
ABILITY_SHIELD_BATTERY
ABILITY_IGNITE_RESOURCES
ABILITY_SENSOR_JAM
ABILITY_TOW
ABILITY_ENERGY_TRANSFER
ABILITY_RECHARGE_SHIELD
ABILITY_ENERGY_SHIELD
ABILITY_DISABLE_ENGINE
ABILITY_ENERGY_DRAIN
ABILITY_FIGHTER_PRODUCTION_OVERLOAD
ABILITY_SPAWN_CARGO_SHIPS
ABILITY_VENT_CARGO

SensorIconType

SENSOR_ICON_TYPE_UNKNOWN
SENSOR_ICON_TYPE_FLAG
SENSOR_ICON_TYPE_CIRCLE
SENSOR_ICON_TYPE_SAVING
SENSOR_ICON_TYPE_LOADING
SENSOR_ICON_TYPE_STOPWATCH
SENSOR_ICON_MARKER_CENTER
SENSOR_ICON_MARKER_LEFT_1
SENSOR_ICON_MARKER_LEFT_2
SENSOR_ICON_MARKER_LEFT_3
SENSOR_ICON_MARKER_LEFT_4
SENSOR_ICON_MARKER_LEFT_5
SENSOR_ICON_MARKER_LEFT_6
SENSOR_ICON_MARKER_RIGHT_1
SENSOR_ICON_MARKER_RIGHT_2
SENSOR_ICON_MARKER_RIGHT_3
SENSOR_ICON_MARKER_RIGHT_4
SENSOR_ICON_MARKER_RIGHT_5
SENSOR_ICON_MARKER_RIGHT_6

ShipSpawnMethod

SHIP_SPAWN_METHOD_DEFAULT
SHIP_SPAWN_METHOD_APPEAR
SHIP_SPAWN_METHOD_WARP_IN
SHIP_SPAWN_METHOD_APPEAR_FORMATION
SHIP_SPAWN_METHOD_WARP_IN_FORMATION