Difference between revisions of "FOCS Scripting Details"

From FreeOrionWiki
Jump to: navigation, search
m (List: formatting)
(310 intermediate revisions by 21 users not shown)
Line 1: Line 1:
=Introduction=
+
This page augments the [[FOCS Scripting Tutorial]] (which should be reviewed first) and describes in more detail the scripting language used to describe much of the content of FreeOrion.  This language is sometimes referred to as the FreeOrion Content Script, or "FOCS".  Scripted content includes scripted descriptions of technology, buildings, and specials.  These content files are text files, but some of them include special characters and therefor when editing them a somewhat more advanced editor is necessary.  For example, on Windows, the Notepad and Wordpad editors can cause trouble, but [http://notepad-plus-plus.org/ the third party NotePad++ editor] should be fine.  An added benefit of using NotePad++ is that one of our contributors has made an [http://www.freeorion.org/forum/viewtopic.php?f=15&t=7161&hilit=focs+notepad&start=0 add-on to help with the FOCS syntax].
  
==Terminology==
+
=Content Files=
  
"Effects" are changes/modifications to game objects.
+
FreeOrion content is described in content files located in the /default subdirectory of the main FreeOrion game directory (typically 'C:\Freeorion').
  
"Game Objects" include the player-visible parts of the game simulation, such as empires, systems, planets, buildings, ships and specials. Game objects may also be invisible to the player, and be used internally by the game to simulate / maintain the gamestate.  
+
Directory                | Contents
 +
--------------------+--------------------------------------
 +
techs              | Tech Categories and Technologies
 +
buildings          | Buildings
 +
specials           | Specials
 +
  ship_hulls          | Ship Hulls
 +
  ship_parts          | Ship Parts
 +
species            | Species
 +
ship_designs        | Ship Designs
 +
monster_designs    | ShipDesigns to use as space monsters
  
Game objects also each contain a list of groups of effectsA particular game object's effects groups determine many of the ways it iteracts with the other game objectsFor example, a building might have an effects group containing an effect which alters a meter of a planetAlternatively, a special attached to a system might have an effect in a group which makes all ships in the system have nonfunctional shieldsA player-visible game object may contain no effects groups, and a player-invisible game object may contain multiple effects and groups, allowing for flexible in-game collection of effects that work together.
+
The files in these directories contain descriptions of individual entries of their respective contentsbuildings/ contains files with "BuildingType" descriptions (see below)specials/ contains "Special" descriptionstechs/ contains tech category and tech descriptions.  When there are multiple entries in a single file, the ordering of entries in the files do not matterFiles can be organized into sub-directories as needed, for example ship_parts might contain a directory for weapon entries.
  
==General Conception==
+
The primary building blocks used to specify the above types of FreeOrion content are ValueRefs (value references), Conditions, and EffectsGroups (which contain Effects and Conditions).  Effects change the game state and thereby give buildings, techs and specials their in-game purpose.  Conditions act to filter a starting set of objects to a smaller set (which might sometimes wind up being one or none).  In EffectsGroups Conditions determine if (the activation condition) and on what (the scope condition) effects act.  Conditions also have a few other uses, such as determining where buildings or ship parts or hulls can be produced, and where species focus settings can be used; they are also used within some of the more advanced ValueRefs.  ValueRefs provide values used by the other portions of the script.  Sometimes that might be a simple constant, like three, which the scripter would simply write as "3".  Other times that might be a dynamic value such as the current game turn number, scripted as "CurrentTurn".  In other cases that might be something much more complex, such as the number of monsters within two starlane jumps of a given system; the syntax for such value references is described farther below.
  
The basic goals of effects are:
+
=Scripting Format=
* To influence how the game calculates basic game functions such as production, population, ship movement (not in v0.3), etc., but not to actually calculate or impliment these results in most cases
+
* To permit additional manipulations of the game state beyond those provided by basic game functions
+
* To do both of the above in a very customizable and moddable way, using data files external to the program to define relevant game content
+
  
To achieve these goals, the effects system requirements in this document allow (and require) the creating, in XML files (or similar), of template classes of game objects in various categories, which provide all of the "content" of the gameThe specifics of the non-effects details of the content system are not relevant to the effects portion of the design, so will be described in detail elsewhere.
+
In FOCS, whitespace (spaces, tabs, and line endings) is only for the visual clarity of the script, and capitalization is ignored for everything outside of quotes.   
  
=Game Objects=
+
Words in quotes, eg. "NAME" are case-sensitive names of scripted content items such as techs, buildings, or specials.  The names of the items are defined in their description by their line:
 +
name = "NAME"
 +
These items may be referred to in other items' descriptions by "NAME".  This might typically be done when unlocking a building with a tech, or adding or checking for the presence of a special to or on an object.
  
Game objects are of a particular classThe class description of a game object is contained within an XML file (suggested)For a given class, this description indicates all the groups of effects and the effects they contain, contains all information about how the effects function, a category or "type" (eg. building, special, ship...) into which the game object falls (to enable to the game to deal with the object internally other than through effects), indicates how the object is represented to the player (if it is visible) and indicates any other necessary information about the object.  The other "necessary information" is quite substantial, and is intentended to provide the majority of the game content in XML format (see below).
+
Comments may be added to files using c/c++-style comment blocksAnything in such blocks will be ignored when parsing the content filesAnything after "/*" will be ignored until the next occurrence of "*/" (even if it occurs several lines later), and anything on a line after "//" will be ignored.
  
The "type" of an object is a general category, whereas class is a detailed, specific case of a type.  "Building" is a type, whereas a "Level 5 Farming Enhancer" would be a specific class of object, defined in an XML file, and buildable by players in the game, assuming they have the appropriate in-game prerequisites (which falls under "other necessary information").
+
In the FOCS descriptions below, the fixed portion of the FOCS specifications are in lower case or MixedCase; things written in ALLCAPS are placeholders for scripted subcontent.  That type of any such piece of scripted subcontent below is specified either as a Condition, an Effect, an EffectsGroup, a string, an int (integer), or a double (a "real" number such as 2.4).  In many cases, any such string, int or double can be provided either as a simple constant or as a more complicated scripted ValueRef.  In any situations where a plain constant is required (but not a ValueRef), we endeavor to specify those values as string_constant, int_constant and double_constant.
  
Game Object Descriptions include the following information which are relevant to the effects system (as well other necessary information):
+
==Specification Components==
 +
There are a number of specification components that are used by multiple different content types, and some that are particular to a specific kind of content.  The more common components are described first below.
  
*Type - the type of a game object determines how the object is managed by the game code in generalSpecific types may be determined by programmers, but suggestions include buildings, specials, ships, technologies, planets, systems etc. In practice, "type" may be an object property, or treated as a particular programming code-classIn either case, "type" needs to be an settable property for objects in XML files, and accessibe for effects in game (see below).
+
===ValueRef===
 +
A ValueRef is a type of FOCS construction which gets evaluated to provide a value, and which may reference various objects and which may have conditional aspects; their structure is described in more detail belowThe most common types are string (text) ValueRefs (which generally evaluate to the name of something, such as a species name "SP_HUMAN"), integer ValueRefs (which evaluate to an integer, such as 42), and double ValueRefs (which evaluate to a "double", a programming term for a "real" number, i.e., it may have a decimal point, such as 3.5)Some ValueRefs may evaluate to a kind of FO-specific value such as a PlanetEnvironment or PlanetSize; it may be helpful to think of these as a string or number for which a limited group of values are acceptable.
  
*Duration - how many turns the game object remains in the game before disappearing on its ownThis may be nonzero positive, indicating a limited duration in turns, or may be zero, indicating an infinite duration game object, that never disappears unless destroyed by an effect (of its own, or another object).
+
===Condition===
 +
A FOCS Condition acts as a kind of filter on objects in the FO universeConditions start with a set of objects, and return subsets of this set according to whether the objects meet the criteria of the condition.  Just what that starting set of objects is depends on where the Condition is used, and is discussed more below.  There are many different types of FOCS Conditions, and their structures are also explained further below.
  
*Effects Groups - a detailed list of groups of effects and information about their functionality (see below).
+
===Name Specification===
 +
  name = "NAME"
 +
Param Type:
 +
  NAME    string_constant
 +
When displayed to a user, the name will normally be used as a key/label for which a value will be looked up in a stringtable (to enable translation); the raw FOCS name strings themselves are by convention written in ALL_CAPS_WITH_UNDERSCORES.  They should generally be unique to that particular piece of content-- even if both pieces of content might be suitably translated to the same name in English, that might not be the case for other languages.  As examples, the name of the first refinement of the first tier of short range weapon parts (which is currently called "Mass Driver 1" in English) is specified as
 +
  name = "SR_WEAPON_1_1"
  
=Effects Groups=
+
===Description Specification===
 +
  description = "DESCRIPTION"
 +
Param Type:
 +
  DESCRIPTION    string_constant
 +
As with the name, the description is normally used as a key/label to be looked up in a stringtable, an example (specifically, for Mass Driver 1), would be
 +
  description = "SR_WEAPON_1_1_DESC"
  
Effects are listed in groups.  Each effects group contains one or more effects that work together on the same game objects simultaneously, subject to the same activation and scope conditions.
+
===BuildCost Specification===
 +
    buildcost = BUILDCOST
 +
Param Type:
 +
  BUILDCOST    double (ValueRef)
  
A given effects group may contain either a) effects that modify meters or b) effects that do not modify meters, but not both (a) and (b).
+
===BuildTime Specification===
 +
    buildtime = BUILDTIME
 +
Param Type:
 +
  BUILDTIME    integer (ValueRef)
  
==Effect Group Descriptions==
 
  
For each effects group for a game object, the following are indicated:
+
===Location Specification===
*Effects - a list of effect classes for the group.  Particular classes may be duplicated, optionally have different parameter values.  See below.
+
    location = LOCATION
*Scope Conditions - a list of scope building and limiting conditions that determine what game objects the effect of the group fire upon, in addition to any restrictions implied by the individual effects classes.  See below.
+
Param Type:
*Activation Conditions - a list of conditions that determine whether the effects of a group will be fired on a given turnSee below.
+
  LOCATION    Condition
*Parameters - for individual effects in a group, and for scope and acitvation conditions for the whole effects group
+
In general, the Location specification constrains where/when the respective content can be built, or in the case of a Focus, be usedMore detail is provided below for the various particular content types that use a Location specification.  For things that can be built, if the item is under construction and the Location condition ceases to evaluate to True, then progress on the construction halts until such time as the Location condition again becomes True.
**Effect Parameters - details about how each individual effect should work.  Indicates individually for each effect in the group.
+
**Scope Condition Parameters - details about how each inclusive or exclusive condition used to determine the scope of the effects group should work.
+
**Activation Condition Parameters - details about how each activation condition determines whether the effects of the group will fire during a turn
+
  
Note: In the following, the "source object" or "source" or "effect source" of an effect is the object which contains the effect in question.
+
===EnqueueLocation Specification===
 +
    EnqueueLocation = ENQUEUELOCATION
 +
Param Type:
 +
  ENQUEUELOCATION    Condition
 +
The EnqueueLocation condition sets the constraining condition under which the respective content (or a ship design using the content) may be placed on the Build Queue.  If not explicitly specified, the EnqueueLocation condition will default to be the same as the Location condition.  The EnqueueLocation is only evaluated at the time of placing the item on the queue; it need not remain true (and so, for example, may prohibit that the subject content is already enqueued at that location).
  
==Effects for v0.3==
+
===EffectsGroup Specification===
  
===Modify Planet Max Meter===
+
EffectsGroup
(Specified Amount, Specified Meter) - Adds or subtracts from a planet's max meters this turn.  Does not affect current meter values.  Aside: Max meter values are modified primarily by effects that consistently fire every turn, establishing a consistent max meter value
+
  description = "DESCRIPTION" [optional -- may be left out]
 +
  scope = CONDITION
 +
  activation = CONDITION [optional -- may be left out]
 +
  stackinggroup = "STACKINGGROUP" [optional -- may be left out]
 +
  accountinglabel = "ACCOUNTINGLABEL" [optional -- may be left out]
 +
  priority = PRIORITY [optional -- omission defaults to 100]
 +
  effects = {EFFECT|[
 +
      EFFECT
 +
      EFFECT
 +
      EFFECT
 +
  ]}
  
===Modify Planet Current Meter===
+
Param Types:
(Specified Amount, Specified Meter) - Adds or subtracts from a planet's current meter values. Does not affect max meter values. Aside: Current meter values are modified rarely compared to max meter values. Current meter modifications are also primarily by one-shot effects, rather than effects that consistently fire every turn, as this would cause the current meter value to grow very much each turn.
+
  DESCRIPTION      string_constant
 +
  SCOPE            Condition
 +
ACTIVATION      Condition
 +
STACKINGGROUP    string_constant
 +
ACCOUNTINGLABEL  string_constant
 +
PRIORITY        int_constant
 +
  EFFECT          Effect
  
===Modify Empire Stockpile===
+
Describes the mechanism by which game content such as Techs, Buildings or Specials interacts with and alters the game state.
(Specified Amount, Specified Resourse) - Adds or subtracts from one of empire's stockpiles.
+
  
===Set Planet Size===
+
* Consists primarily of:
(Specified Size) - Sets the size property of a planet to a specified value.
+
** One or more Effects
 +
** A "SCOPE" condition which indicates the objects in the scope of the Effect(s).  The scope objects are those that are acted on by the effects in the effects group, i.e., what the targets of the effects are.
 +
** An "ACTIVATION" condition (assessed specifically against the Source) which indicates whether or not the Effect(s) will be executed on the objects in scope during the current turn.  The default if the activation clause is left out, is to be on/active.
 +
For scope conditions, the entire game universe (or rather, all objects in it) are the initial set.  For activation conditions, the initial set is the source object of the effects group.  This allows an EffectsGroup to be activated or suppressed based on the source object only (the object to which the EffectsGroup is attached). If the source object meets the activation condition, the EffectsGroup will be active in the current turn.
  
===Optional: Modify Planet Size===
+
* The translated stringtable entry in "DESCRIPTION" is amended to the source objects description (at the time of this writing, only for specials and species).
(Specified Change) - Increases or decreases the size of a planet by a specified number of sizesPlanet sizes are ordered tiny, small, medium, large, huge.
+
* An EffectsGroup's stacking group determines when it should affect a specific target; if that target has already been affected by another EffectsGroup with the same stacking group, all EffectsGroups after the first have no effect on the target that turn.  For instance, if an EffectsGroup is in a stacking group "WONDER_FARM_BONUS", and executes on a target object, no other EffectsGroup in the "WONDER_FARM_BONUS" stacking group will affect it on that turn.
 +
* The presence of "ACCOUNTINGLABEL" being specified indicates this effect should be accounted for with the supplied stringtable entry.  This is typically used in providing feedback to the player, accounting for this EffectsGroup among the totals of effected meters.
 +
* "PRIORITY" is the order of the EffectsGroup processingProcessing starts from 0, with all EffectsGroups of the same priority executing before any of a later priority.  This value must be an int and is specifically NOT a ValueRef ('1 + 1' is not allowed).  Information on reference priority values, and the relative priorities of the set of population effects, can be found [[EffectsGroup_Priority_Standard_Values | at our EffectsGroup Priority Standard Values page]].
  
Optionally, asteroid belts may be placed below tiny, and gas giants above huge.
+
==Content Specifications==
  
Planet environment is normally unchanged during a size change.  In the case of growing larger than huge, or smaller than tiny, environment should be set to the appropriate environment for those types of planets, though retaining the original environoment of the planet as a property of the planet while it is an asteroid belt or gas giant would be desirable. In the case of a planet that has always been an asteroid belt growing larger, the environment of the new planet should be barren. In the case of a planet that has always been a gas giant growing smaller, the environment should be toxic.
+
===Common Params===
 +
Where noted, content specifications include these common parameters:
 +
  buildcost = BUILDCOST
 +
  buildtime = BUILDTIME              [optional -- may be left out]
 +
  {Unproducable | Producable}        [optional -- omission defaults to Producable]
 +
  tags = [ "TAG" "TAG" ... ]          [optional -- may be left out]
 +
  location = LOCATION                [optional -- omission defaults to All]
 +
  EnqueueLocation = ENQUEUE          [optional -- omission defaults to All]
 +
  Consumption = CONSUMPTION          [optional -- may be left out]
 +
  effectsgroups = {EFFECTSGROUP|[    [optional -- may be left out]
 +
        EFFECTSGROUP
 +
        EFFECTSGROUP
 +
        ...
 +
  ]}
  
===Set Planet Environment===
+
Param Types:
(Specified Environment) - Sets the environment property of a planet to a specified value.
+
BUILDCOST        double
 +
BUILDTIME        int
 +
TAG              string_constant
 +
LOCATION          Condition
 +
ENQUEUE          Condition
 +
CONSUMPTION      Consumption
 +
EFFECTSGROUP      EffectsGroup
  
===Create Object===
+
===Special Specification===
(Specified Object Class) - Creates new game object(s).  If applicable, location and empire ownership are the same as the game object being fired on by the effect.  This is obviously a rather complicated and multi-functional effect, with numerous possible variations in behaviour depending on the types and number of game objects being created.  As such, it may be more convenient to separate this effect into numerous separate effects in order to create objects of any given category (buildings, ships, specials, etc.) which appropriate parameters for each.  The specifics of this are left for programmer judgement to decide.
+
  
===Destroy Object===
+
Special
(No Parameters) - Destroys game object(s).
+
  name = "NAME"
 +
  description = "DESCRIPTION"
 +
  stealth = STEALTH                  [optional -- may be left out]
 +
  spawnrate = SPAWNRATE
 +
  spawnlimit = SPAWNLIMIT            [optional -- may be left out]
 +
  capacity = CAPACITY                [optional -- may be left out]
 +
  location = LOCATION                [optional -- may be left out]
 +
  effectsgroups = {EFFECTSGROUP|[    [optional -- may be left out]
 +
        EFFECTSGROUP
 +
        EFFECTSGROUP
 +
        ...
 +
  ]}
 +
  graphic = GRAPHICFILENAME
  
===Set Empire Tech Availability===
+
Param Types:
(Specified Technology, Specified Yes/No) - Sets a tech as available to be researched or not for empire. Implimentation note: the availability should be maintained as a property of the tech or the empire.
+
  NAME              string_constant
 +
DESCRIPTION        string_constant
 +
STEALTH            double
 +
SPAWNRATE          double
 +
SPAWNLIMIT        int
 +
CAPACITY          double
 +
LOCATION          Condition
 +
EFFECTSGROUP      EffectsGroup
 +
GRAPHICFILENAME    string_constant
  
===Set Empire Building Availability===
+
A specification for a Special, which is a definition of a predefined set of EffectsGroups with a unique name, which may be attached to an object in-game.
(Specified Building Class, Specified Buildable / Not Buildable) - Sets a building type as buildable or not for empire.  Implimentation note: the availability should be maintained as a property of the building class or the empire.
+
  
===Set Ship Type Availability===
+
* Specials used in the game are stored within [https://github.com/freeorion/freeorion/blob/master/default/scripting/specials/ specials].
(Specified Ship Class, Specified Buildable / Not Buildable) - Sets a ship class as buildable or not buildable for empire. Implimentation note: the availability should be maintained as a property of the ship type or the empire. Future note:  In future, presumably this effect will be obsolete and replaced with effects to mark individual ship components as available or not.  This will occur after a ship design system is designed (and implimented).
+
** specials contains general specials that may be applied to objects using the AddSpecial effect.
  
===Set Star Colour===
+
===BuildingType Specification===
(Specified Star Colour) - Sets the colour of a star.
+
  
===Future: Set Target===
+
BuildingType
''For v0.3, this effect is not required.  It is largely dependent on some sort of user-interface which is capable of interacting with game objects and their effects, which is not yet specified in the requirements, and will likely be delayed until v0.4 or later.''
+
    name = "NAME"
 +
    description = "DESCRIPTION"
 +
    captureresult = CAPTURERESULT      [optional -- omission defaults to capture]
 +
    (common params)
 +
    icon = "ICONFILENAME"
  
(No XML Settable Parameters, possibly some UI/AI parameters or controls) - Sets the "target" property of a game object. "Target" would be a run-time-only settable property of a game object, which could be used to specifically and persistantly alter its behaviour and/or limit the scope of its effect(s).  
+
Param Types:
 +
  NAME            string_constant
 +
  DESCRIPTION      string_constant
 +
CAPTURERESULT    CaptureResult
 +
ICONFILENAME    string_constant
  
This would ''not'' be configurable from an XML file.  Rather it would need to bet set at run time as either part of the Create Object effect, using the Set Target effect, or by some other means.  For example, a building on a planet could fire Set Target on itself to target a particular ship with some effect every turn. Alternatively, a special space-monster controlling ship could use Set Target to cause space monsters to attack a specific enemy ship (assuming that a space monster game object's "Target" property was used to keep track of what ship it was current hunting).
+
A specification for a building of a certain type.
 +
* BuildingTypes must each have a unique name.
 +
* BuildingTypes used in the game are stored within [https://github.com/freeorion/freeorion/blob/master/default/buildings/ buildings].
 +
* The note{{CN}} about Special name and description text also applies to BuildingTypes.
 +
* ICONFILENAME should be relative to the art directory.  So it should appear in the form "foo/bar.png" instead of "default/data/art/foo/bar.png".
  
The specifics of how this effect works with scope conditions is not yet fully conceived.  A single scope is likely insufficient, as there needs to be some way to specificy both what object to fire the effect on, and what object to which to set the fired upon object's target.  Limiting objects to only firing set target only onto themselves might work, using scope to determine the new target, however this is inconsistent with the standard use of scope to determine which object(s) to fire upon.
+
===Item Specification===
  
How to decide how and when to fire Set Target is also not clear, nor is the persistance of the effect between turns (must Set Target be used every turn to maintain its effect?).
+
Item type = TYPE name = "NAME"
  
In any case, in future design versions, it is likely that some degree of user or AI interface with the effects system will be necessary. The details of "Set Target" and similar effect classes can be fleshed out and refined at that time.
+
Param Types:
 +
  TYPE            UnlockableItemType
 +
NAME            string_constant
  
==Effect Scope and Scope Conditions==
+
A specification for an unlockable item.
 +
* Item definitions appear within Tech definitions.
 +
* type defines the kind of thing to be unlocked, e.g. a Building, ShipHull, ShipPart, or Tech.
 +
* name is the name of the specific item of that kind to be unlocked, e.g. a "WonderFarm" building or a "MegaLaser" ship part.
 +
* The note{{CN}} about Special and BuildingType name and description text also applies to Items.
  
The set of game objects (planets, ships, stars, buildings, specials) that are fired upon by an effect are collectively known as the effect's scope.  Scopes are determined using scope conditions, which are described as part of an effects group (not individual effects).  All effects in an effects group share the scope of the effects group, except that some effects may be incapable of firing on certain objects in their group's scope, in which case the unfirable effects are ignored for the objects in question.  Other effects in the effects group still fire on such objects, and effects ignored for an object still fire on other objects in the scope, if they are able to do so.
+
===Tech Category===
  
The scope of an effects group is determined using conditions in two steps.  
+
  TechCategory name = "NAME" graphic = "GRAPHIC" colour = COLOUR
  
The scope is initially empty, and game objects are first put into the scope using 'inclusive' conditions. In this stage, a given game object is either included, or not yet included in the scope. Being included by more than one condition causes no further change (no multiple inclusion of a single object).  A particular inclusive condition may either add objects to the scope, or may have no effect.  
+
Param Type:
 +
  NAME string
 +
  GRAPHIC string_constant
 +
  COLOUR colour
  
After all inclusive conditions have been applied, 'exclusive' conditions are used to exclude game objects from the scope.  A given 'exclusive' condition may either exclude objects from the scope, or have no effect.
+
Specifies a technology category.
 +
* Techs are displayed by category in the UI
 +
* A category must be defined in [https://github.com/freeorion/freeorion/blob/master/default/scripting/techs/Categories.inf Categories.inf] before a tech in that category may be defined.
  
All conditions are evaluated at the time the effects of the group fire, so an object may be part of an effect's scope for one firing, but not another firing during another turn.  A given effects group may only contain meter-altering or non-meter-altering effects, so a given effects group only fires effects once per turn (see below).
+
===Colour Specification===
  
The scopes of each non-meter altering effects group is determined before any of the group's effects fire. The scope of the effects group is thus the same for all effects in the group, even if one effect in the group changes properties of a game object such that it no longer meets the group's scope conditions before all effects have fired.  A special case of this rule is the firing of effects which destroy game objects.  If an effect destoys a game object in the group's scope, then no additional modification to the destroyed game object are necessary, so the destroyed object may be removed from the scope.
+
  (RED, GREEN, BLUE, ALPHA)
  
Scope conditions are checks of various properties of game objects. Some scope conditions are based on properties of the object being checked by the condition, and others depend on other objects associated with the object being checked. For example, a building may be checked for exclusion from the scope according to a planet environment condition. The building itself has no planet environment, however the building is attached to a planet, so the environment of the planet is check for the purposes of determining whether the building is excluded from the scope of the effect. Attachments form a tree, so if the building was checked by a condition for a property that neither it nor the planet it is attached to have (such as star colour), the system in which the planet is located would be checked. If no objects in the tree of attached objects for a given potential scope object have a property being checked for, then the object is excluded by default. For example, if a ship was checked for star colour while it was not in any star system, the ship would be excluded from the scope of the effect.
+
Param Type:
 +
  RED    int_constant
 +
  GREEN int_constant
 +
  BLUE  int_constant
 +
  ALPHA int_constant
  
If a condition description (below) states that it excludes objects from the scope by some property, or "their" some property, a hierarchy is used when necessary to attempt to determine what value of the property applies to the game object.
+
Specifies a colour.
 +
* Brackets must surround the colour component numbers, which must also be separated by commas.
 +
* Colour components are specified in the range [0, 255]
 +
* Example: in a TechCategory definition, one might write:
 +
colour = (116, 225, 107, 255)
  
The hierarchy of attachment for scope condition purposes in v0.3:
+
===FocusType Specification===
  
*Buildings are attached to the planet on which they are located.
+
FocusType
*Planets are attached to the system in which they are located.
+
    name = "NAME"
*Ships are attached to the system in which they are located (if applicable), or nothing (if not in a system).
+
    description = "DESCRIPTION"
*Specials are attached to the game object they are associated with (as / if applicable)
+
    location = "CONDITION"
 +
    graphic = "GRAPHICFILENAME"
  
Note that the hierarchy described above is only used when checking for a property not specified for a given game object.  This means that the object does not have a particular property, but is distinct from some cases in which an object has a property, but that property is set to "none".  (Example: A space monster or uninhabited system are owned by no empire, but both still have the empire ownership property)  The hierarchy is thus used only when necessary to determine a property value for a game object.
+
Specifies a focus setting for a planet.
  
Note also that targetting of empires, as opposed to other game objects owned by empires, may be "loose"By this, it is meant that an effect that is described above as setting some property of a particular empire may be targetted to that empire directly, or may affect all empires that own an object that falls into the effect's scope. The specifics of how this works can be decided by programmers, but it should be possible to target an empire directly, or target all empire's that own other objects objects in an effect's scope.
+
* Within each species, each FocusType must have a unique nameTwo different species may have (the same or different) FocusTypes with the same name, however.
 +
* The location condition determines which planets on which the FocusType can be used.
 +
* The graphic determines the icon used to represent the FocusType in the UI.
  
==Scope Conditions for v0.3==
+
===Tech Specification===
  
Scope starts with no objects. Inclusive conditions are applied first, adding game objects into the scope. Exclusive conditions are then applied, removing objects from the scope, leaving a final set of objects in the scope, on which the effect is fired.
+
  Tech
 +
    name = "NAME"
 +
    description = "DESCRIPTION"
 +
    short_description = "SHORT_DESCRIPTION"
 +
    category = "CATEGORY"
 +
    researchcost = RESEARCHCOST
 +
    researchturns = RESEARCHTURNS
 +
    {Unrsearchable | Researchable}              [optional -- omission defaults to Researchable]
 +
    Tags = [ "TAG" "TAG" ... ]                  [optional -- may be left out]
 +
    prerequisites = {"NAME"|[                  [optional -- may be left out]
 +
        "NAME"
 +
        "NAME"
 +
        ...
 +
    ]}
 +
    unlock = {ITEM|[                            [optional -- may be left out]
 +
        ITEM
 +
        ITEM
 +
        ...
 +
    ]}
 +
    effectsgroups = {EFFECTSGROUP|[            [optional -- may be left out]
 +
        EFFECTSGROUP
 +
        EFFECTSGROUP
 +
        EFFECTSGROUP
 +
    ]}
 +
    graphic = "GRAPHICFILENAME"
  
An effect can have multiple exclusive and inclusive conditions.
+
Param Types:
 +
NAME              string_constant
 +
DESCRIPTION        string_constant
 +
SHORT_DESCRIPTION  string_constant
 +
CATEGORY          string_constant
 +
RESEARCHCOST      double
 +
RESEARCHTURNS      int
 +
TAG                string_constant
 +
NAME              string_constant
 +
ITEM              Item
 +
EFFECTSGROUP      EffectsGroup
  
Prefereably, any scope condition described below will be usable as both an inclusive and exclusive condition. Limits to this may be made to this by programmers, by restriction some conditions as only usable in an inclusive or exclusive capacity.
+
A specification for a technology.
 +
* Techs must each have a unique name.
 +
* Each tech may optionally have one or more EffectsGroups associated with it.
 +
** Tech EffectsGroups are use as their source object the capitol planet of the empire that researches the tech.
 +
* All of a tech's prerequisites must be known before a Tech can be researched.
 +
* The note{{CN}} about Special and BuildingType name and description text also applies to Tech names, descriptions, and category names.
 +
* GRAPHICFILENAME should be relative to the art directory.  So it should appear in the form "foo/bar.png" instead of "default/data/art/foo/bar.png".
 +
* Techs used in the game are stored within [https://github.com/freeorion/freeorion/blob/master/default/scripting/techs/ techs].  These files include examples of theory techs with no effects or unlocked items, as well as applications that unlock buildings or which have effects of their own.
 +
* The Source for all EffectsGroups in a Tech is the Empire Source (generally the Capital), as discussed in the [[#Source.2C_Target.2C_RootCandidate.2C_LocalCandidate | Source]] section.
  
==Conditions==
+
===Ship Hull Specification===
  
===All===
+
Hull
(No parameters) - Applies to all objects.
+
    name = "NAME"
 +
    description = "DESCRIPTION"
 +
    speed = BATTLESPEED
 +
    fuel = FUEL
 +
    stealth = STEALTH
 +
    structure = STRUCTURE
 +
    slots = [                                      [optional -- may be left out]
 +
        Slot type = SLOTTYPE position = (X, Y)
 +
        ...
 +
    ]
 +
    (common params)
 +
    icon = "ICONFILENAME"
 +
    graphic = "GRAPHICFILENAME"
  
===Empire Affiliation===
+
Param Types:
(Specified Empire, Specifed one of: Empire Inclusive, Empire Exclusive, Enemies Inclusive, Enemies Exclusive) - Applies to objects based on the empire they are affiliated with, if any. The specified empire may be the source object's empire, a specific empire in the game, or may be "none". For an specified empire other than none, the second parameter specifies how the condition adds objects to the scope based on their empire according to the following criteria:
+
  NAME              string_constant
*Empire Inclusive - Applies to objects owned by the specified empire (applies to objects shared by the source empire and another empire)
+
  DESCRIPTION        string_constant
*Empire Exclusive - Applies to objects owned by the specified empire only (does not apply to objects shared by the source empire and another empire)
+
BATTLESPEED        double
*Enemies Inclusive - Applies to objects owned by empires other than the source empire (applies to objects shared by the source empire)
+
FUEL              double
*Enemies Exclusive - Applies to objects owned by empires other than the source empire (does not apply to objects shared by the source empire)
+
STEALTH            double
 +
STRUCTURE          double
 +
SLOTTYPE          ShipSlotType
 +
X, Y              double, double
 +
ICONFILENAME      string_constant
 +
GRAPHICFILENAME    string_constant
  
If the specified empire is "none", the second parameter specifies how the condition adds objects to the scope  according to the following criteria:
+
A specification for a ship hull.
*Empire Inclusive - Applies to objects owned by no empire (eg. space monsters)
+
* Hulls must each have a unique name.
*Empire Exclusive - Applies to objects owned by no empire (eg. space monsters)
+
* Each hull may optionally have one or more EffectsGroups associated with it.
*Enemies Inclusive - Applies to objects owned by any empire(s)
+
** Hull EffectsGroups are use as their source object the ship in which the hull is located.
*Enemies Exclusive - Applies to objects owned by any empire(s)
+
* ShipSlotTypes are currently: External, Internal, and Core.  These can be combined within brackets and separated by a pipe ( [EXTERNAL|INTERNAL] )
 +
* X, Y are the coordinates to place the slot (overlaying the hull) in the ship design window.
 +
* The note{{CN}} about Special and BuildingType name and description text also applies to Hull names and descriptions.
 +
* ICONFILENAME and GRAPHICFILENAME should be relative to the art directory.  So it should appear in the form "foo/bar.png" instead of "default/data/art/foo/bar.png".
 +
* Hulls used in the game are stored in [https://github.com/freeorion/freeorion/blob/master/default/scripting/ship_hulls ship_hulls].
  
(An object cannot be shared between "no empire" and a particular empire, so the distinction between inclusive and exclusive does not apply if the specified empire is "none"). 
+
===Ship Part Specification===
  
The "owner" of an object is generally clear, as in a ship or planet, which is clearly owned by a particular empireIn some cases however, objects are owned by more than one empire, such as systems containing planets owned by two or more empires are owned by all empires that own planets in the system. In other cases, objects are owned by no empire (eg. space monsters), no matter who owns the system in which they are located.
+
Part
 +
    name = "NAME"
 +
    description = "DESCRIPTION"
 +
    class = CLASS
 +
    { capacity | damage } = PRIMARY    [optional -- defaults to 0.0 -- see ShipPartClass]
 +
    { damage | shots } = SECONDARY    [optional -- defaults to 1.0 -- see ShipPartClass]
 +
    NoDefaultCapacityEffect            [optional -- omission leaves the normal default capacity]
 +
    mountableSlotTypes = {SLOTTYPE|[
 +
        SLOTTYPE
 +
        ...
 +
    ]}
 +
    (common params)
 +
    icon = "ICONFILENAME"
  
===Self===
+
Param Types:
(No parameters) - Applies to the source object only.
+
NAME              string_constant
 +
DESCRIPTION        string_constant
 +
CLASS              ShipPartClass
 +
PRIMARY            double
 +
SECONDARY          double
 +
SLOTTYPE          ShipSlotType
 +
ICONFILENAME      string_constant
  
===Object Type===
 
(Specified Type) - Applies to objects if their game object type is the specified object type.  The specified type may be an actual type (eg. ship, building, special, planet), or may be set relative to the source object for the effect.  If programmers elect to do so, "empire" might be an valid object type, allowing an effect to target empires directly, as opposed to targetting other game objects owned by an empire to get at the empire itself.
 
  
===Object Class===
+
A specification for a ship part.
(Specified Class) - Applies to objects if their object class is the specified object class. The specified class may be an actual type (referenced by unique identifier and defined in an XML file), or may be set relative to the source object for the effect.
+
* Parts must each have a unique name.
 +
* Each part may optionally have one or more EffectsGroups associated with it.
 +
** Part EffectsGroups are use as their source object the ship in which the part is located.
 +
* The note{{CN}} about Special and BuildingType name and description text also applies to Part names and descriptions.
 +
* ICONFILENAME should be relative to the art directory.  So it should appear in the form "foo/bar.png" instead of "default/data/art/foo/bar.png".
 +
* Parts used in the game are stored in [https://github.com/freeorion/freeorion/blob/master/default/scripting/ship_parts/ ship_parts]].
  
===Planet Environment===
+
====Ship Part Class, Stats and PartMeters ====
(Specified Type, Range) - Applies to objects if they are within a specified range of environments types from the specified environment type.   If the specified environment is not on the EP wheel (gas, asteroids), then the specified range is ignored, and the scope objects' environments must match the specified environment exactly for the condition to apply. If the specified environment is on the wheel, but a scope object's environment is not, then the condition does not apply.
+
Each class of ship parts defines a primary stat and may also define a secondary stat. Some have associated ship part meters (One meter value per ship object and ship part meter type). Possible ship part meter types are: Capacity, MaxCapacity, SecondaryStat, and MaxSecondaryStat.  
  
===Planet Size===
+
Most parts classes ('''Armour''', '''Bombard''', '''Detection''', '''Fuel''', '''General''', '''Shield''', '''Speed''', '''Stealth''') only have a primary stat of capacity an no associated meter.<br />
(Specified Size, Range) - Applies to objects if they are within a specified range of planet sizes from the specified planet size.
+
  
===Planet Focus===
+
'''Troops''' and '''Colony''' part types have a primary capacity stat with associated Capacity meter.
(Specified Focus, Specified Primary or Secondary) - If specified Primary, applies to objects whose primary focus is set to the specified focus.  If specified Secondary, applies to objects whose primary or secondary focus is set to the specified focus.
+
  
===Star Colour===
+
'''FighterHangar''' has a primary stat of capacity and a secondary of damage (number of boats, damage of each boat's attack) and the associated MaxCapacity and MaxSecondaryStat meters.
(Specified Colour) - Applies to objects if their star colour matches the specified colour.
+
  
===Chance===
+
Direct fire weapons (which only contains '''ShortRange''' currently) have a primary stat of damage and a secondary of shots.<br />
(Specified Probability) - For each object, a uniformly distributed random number between 0 and 1 is generated and compared to the specified probability. The condition applies to objects for which the random number is less than the specified propbability.
+
shots determines how many times the weapon will fire each combat round.
  
Future Note: In future, the chance-related condtions may allow the probability of excluding an object from the scope to depend on various properties of that object.  This may involve expanding the functionality of the Current Meter Value Condition, or the creation of new conditions with specialized functions.
+
'''LaunchBay''' parts have a capacity stat with associated (Max)Capacity meters which specifies how many space boats may launch per combat turn.
  
===Meter Value===
+
The meter value for a ship can be accessed using the ShipPartMeter part = "PART_NAME" meter = METER_TYPE object = SHIP_ID double complex variable. See above for which meters exist for which part class. Also note you can use Value(ShipPartMeter) to get the immediate/non-initial value. Defaults to 0.0
(Specified Meter, Specified Value, Specified Minimum or Maximum) - Applies to objects if their applicable current meter value meets the conditions indicated by the specified values.  For Minimum, the condition applies if the specified meter value is equal to or larger than the specified value (and similarly for maximum).  If an object does not have the applicable meter, the condition does not apply.  This condition can only be used with non meter-altering effects groups. This condition could be split into "Current Meter Value" and "Max Meter Value" for the two cases of specified minimum or maximum.
+
  
===Current Stockpile Value===
+
In the source code, the ship meters and ship part meters are defined in the Ship::Ship constructor in universe/Ship.cpp
(Specified Resource, Specified Value, Specified Minimum or Maximum) - Applies to objects if their applicable resource stockpile meets the conditions indicated by the specified values.  For Minimum, the condition applies if the specified resource stockpile is equal to or larger than the specified value (and similarly for maximum).  If an object does not have a stockpile of the applicable resource (not the same as a stockpile containing 0 of a resource), the condition does not apply.
+
  
===Scope Object Visible To Source Object===
+
===Species Specification===
(Specified True / False) - Applies to objects that can or cannot be seen by the source object, as indicated by the specified true or false (true means the condition applies to objects if they are seen, false means the condition applies to objects if they are not seen).  In most cases, this will be equivalent to testing whether an objects can be seen by the source object's empire.
+
  
===Source Object Visible To Scope Object===
+
Species
(Specified True / False) - Applies to objects that can or cannot themselves see the source object, as indicated by the specified true or false (true means the condition applies to objects that can see the source object, false means the condition applies to objects that cannot see the source object). In most cases, this will be equivalent to testing whether the source empire can see the tested object.
+
    name = "NAME"
 +
    description = "DESCRIPTION"
 +
    gameplay_description = "GAMEPLAY_DESCRIPTION"
 +
    Playable                                      [optional -- defaults to not playable]
 +
    Native                                        [optional -- defaults to not native]
 +
    CanProduceShips                              [optional -- defaults to cannot produce ships]
 +
    CanColonize                                  [optional -- defaults to cannot colonize]
 +
    tags = ["TAG" "TAG" ...]                      [optional]
 +
    foci = {FOCUSTYPE|[                          [optional -- may be left out]
 +
        FOCUSTYPE
 +
        ...
 +
    ]}
 +
    preferredfocus = "FOCUS"                      [optional]
 +
    effectsgroups = {EFFECTSGROUP|[              [optional -- may be left out]
 +
        EFFECTSGROUP
 +
        EFFECTSGROUP
 +
        ...
 +
    ]}
 +
    environments = {PLANETTYPEENVIRONMENT        [optional -- may be left out]
 +
        PLANETTYPEENVIRONMENT
 +
        PLANETTYPEENVIRONMENT
 +
        ...
 +
    ]}
 +
    graphic = "GRAPHICFILENAME"
  
===Direct Distance to Source===
+
Param Types:
(Specified Distance) - Applies to objects if their physical location on the galaxy map is within a specified distance from the source object's location. If the source object does not have a physical location, then this condition does not apply to any objects. If a given scope object has no physical location, then this condition does not apply to that object. Distance can be 0, meaning the condition applies only to objects co-located with the source object (meaning in the same star system, or located at the same position on a starlane).
+
  NAME                  string_constant
 +
  DESCRIPTION            string_constant
 +
GAMEPLAY_DESCRIPTION  string_constant
 +
TAG                    string_constant
 +
FOCUSTYPE              FocusType
 +
FOCUS                  string_constant
 +
EFFECTSGROUP          EffectsGroup
 +
PLANETTYPEENVIRONMENT (see below)
 +
GRAPHICFILENAME        string_constant
  
===Starlane Jumps to Source===
+
* Species must have a unique name.
(Specified Number) - Applies to objects if their physical location is within a specified number of starlane jumps from the source object. If the source object is located at a system, then all systems connected to the source object's system by one starlane jump are at a distance 1, by two starlane jumps are at a distance 2, and so on. Objects on starlanes between systems count as being one jump away from either starlane at the end of the lane they are on.  Objects are always considered to be the shortest number of starlane jumps away from the source as possible, whether or not the starlanes involved are known to the empire(s) involved.  Distance can be 0, meaning the condition only applies to objects co-located with the source object (meaning in the same star system, or located at the same position on a starlane).
+
* PLANETTYPEENVIRONMENT has format:
 +
type = PLANETTYPE environment = ENVIRONMENT
 +
with param types:
 +
  PLANETTYPE        PlanetType
 +
  ENVIRONMENT        PlanetEnvironment
  
===Object Class===
+
===ShipDesign Specification===
(Specified Class) - Applies to objects if their object class is the specified object class.
+
  
===Direct Distance to Object of Class===
+
ShipDesign
(Specified Distance, Specified Class of Game Object) - Applies to objects if they are within the specified distance on the galaxy map to an object of the specified class. Distance may be 0, indicating the objects must be co-located.
+
    name = "NAME"
 +
    description = "DESCRIPTION"
 +
    NoStringTableLookup              [optional -- omission leaves default behavior]
 +
    hull = "HULLTYPE"
 +
    parts = [                        [see note below]
 +
        "PARTTYPE"                   
 +
        "PARTTYPE"
 +
        ...
 +
    ]
 +
    icon = "ICONFILENAME"
 +
    model = "MODELNAME"
  
===Starlane Jumps to Object of Class===
+
Param Types:
(Specified Number of Jumps, Specified Class of Game Object) - Applies to objects if they are within the specified number of starlane jumps to an object of the specified class. Distance may be 0, indicating the objects must be co-located. See "Starlane Jumps to Source" for details.
+
  NAME                string_constant
 +
DESCRIPTION        string_constant
 +
HULLTYPE            ShipHullType
 +
PARTTYPE            string_constant
 +
ICONFILENAME        string_constant
 +
  MODELNAME          string_constant
  
===Object Type===
+
* ShipDesign must have a unique name
(Specified Type) - Applies to objects if their game object type is the specified object type. If programmers elect to do so, "empire" might be an valid object type, allowing an effect to target empires directly, as opposed to targetting other game objects owned by an empire to get at the empire itself.
+
* PARTTYPE corresponds to the same ordered entry for each slot in HULLTYPE.
 +
** There must be the same number of PARTTYPEs as there are slots, but the PARTTYPE may be left empty ( "" ).
 +
** PARTTYPE must be compatible with the ShipSlotType for that slot.
 +
* ICONFILENAME and MODELNAME should be relative to the art directory.
  
===Future: Targeted Object===
+
=Types and Expressions (ValueRefs)=
See Future: Set Target effect.
+
  
==Activation Conditions==
+
In the Conditions and Effects below, there are parameters that specify details about how the condition or effect functions.  These parameters can be specified as a constant number (eg. 5) or value (Blue), or can be variables that depend on the gamestate.  Variables may refer to the Source, Target, RootCandidate or LocalCandidate objects (see below), a few independent values such as the number of the current game turn, or may refer to statistics about the gamestate that are calculated from multiple objects. 
  
Each effects group has a set of conditions that determine whether or not the effects group is "active" during a given turn.  If active, all effects in the effect group fire on all objects in the effect group's scopeIf inactive, the entire effects group is ignored for the turn.
+
==Source, Target, RootCandidate, LocalCandidate==
 +
ValueRefs, Conditions and Effects are evaluated in light of an automatically generated Scripting Context, which specifies one or more of a Source, Target, RootCandidate, and LocalCandidateThe way these get automatically generated depends on what content type is being evaluated.
  
An effect group must meet all of its activation conditions to be active during a given turn.
+
For an Effect, the Source object is the object to which the Effect is attached.  For example, a building might have an effect that increases a planet's industry meter.  When defining that building's effects, the building itself would be the Source object.  Regarding using "Source" as a Condition, as is common when specifying a scope, see [[#Conditions|the Conditions Section below]].
  
==Activation Conditions for v0.3==
+
The Target object of an Effect is the object that the Effect is modifying.  In an effect that modifies a planet's industry meter, the planet would be the Target object.
  
Many scope conditions, or small variations thereof should be usable as activation conditions. In particular, the following scope conditions should be available (in all cases, the source object is being tested by the conditions):
+
The objects being tested by Conditions are candidates, and for reference within the scripts these are broadly divided into two types relating to the potentially multi-tiered nature of Conditions. Consider the following EffectsGroup scope condition:
 +
  scope = WithinDistance distance = 5 condition = And [
 +
    Planet
 +
    OwnedBy TheEmpire RootCandidate.Owner
 +
    Construction low = 0 high = LocalCandidate.TargetConstruction / 2
 +
  ]
 +
Here there are two sets of objects being matched:
 +
1) The objects actually being matched for the scope.  These are objects within distance 5 of an object matched by the subcondition.
 +
2) The objects matched by the subcondition, which are used to evaluate the outer condition.  These are planets that are owned by the same empire that owns the object matched in the outer condition, and that have less than half their own target construction.
  
==Conditions==
+
RootCandidate refers to the object being matched in the outer-most condition - WithinDistance in this case.  This gives a way to refer to the object actually being matched by a big multi-part condition from one of the inner condition definitions, where the object being matched by a subcondition is likely not the same object being matched by the outer condition.
  
*Always Active
+
LocalCandidate refers to the object being matched in whatever condition it is directly in - the Construction meter condition in this case.  This gives a way to refer to the object being matched by the current condition, regardless of what other conditions are matching outside or inside the current condition.
*Empire Affiliation
+
*Planet Environment
+
*Planet Size
+
*Planet Focus
+
*Star Colour
+
*Chance
+
*Current Meter Value (non meter-altering effects groups only)
+
*Current Stockpile Value (non meter-altering effects groups only)
+
*Direct Distance to Object of Class
+
*Starlane Jumps to Object of Class
+
  
The following additional special activation condition should be available:
+
The RootCandidate and LocalCandidate may be used with the same types of variable references as for Source and Target.
  
===Special Activation Condition: Owned by Specfic Empire===
+
For the EffectGroups in Techs, the Location specification, BuildTime value and BuildCost value for content such as a BuildingType, ShipHull or ShipPart, the context Source is the EmpireSource for the empire currently under consideration; this is its Capital planet if it has one, otherwise some other object owned by the empire.  The Target in this context is the potential production location (planet) for which the Location, BuildTime or BuildCost is being evaluated.
  
(Run-Time Specified Empire, Specified Active / Inactive) - If specified Active, effects group is active only if the source object is owned by the specified empire.  If specified Inactive, the effects group is active only if the source object is not owned by the specified empire.
+
For the Location specification for Specials, Source and Target are not set, but the LocalCandidate and RootCandidate references may be used.
  
This condition is special in that the specified empire needs to be specified at run time, by the game engine.
+
For EmpireStatistic ValueRefs, the scripting context only has a Source, which is the EmpireSource mentioned above.
  
==Effect Parameters==
+
==Free/Independent Variables==
  
In the above lists of "Effects for v0.3", "Scope Conditions for v0.3" and "Activation Conditions for v0.3", parameters are indicated in brackets as part of the effect or condition descriptionMany of these are numeric parameters, which are discussed below under "Numeric Parameters"Others are non-numeric parameters, which are discussed below under "Non-Numeric Parameters".
+
There are some variables that may be used without referring directly to the Source, Target or candidate objects. The current free variables that may be referenced are those specifying the galaxy setup conditions, and one which provides the current game turn. These currently all provide an integer result.  For galaxy setup variables, their underlying type is generally a specialized enumeration which for this purpose gets mapped to an integer corresponding to the order they get listed in the GalaxySetup screenFor example, most galaxy setup variables work with range [None, Low, Medium, High], which gets mapped to [0, 1, 2, 3](Many of those variables drop the None value, and so have a range of 1-3.)  Current Max AI Aggressions range from 0 to 5.    The current list of free variables is:
  
Every effect also has an additional parameter not indicated in "Effects for v0.3". This is the effect "Stacking Number".
+
  Value                  (various, see below)
 +
GalaxySeed              string
 +
CurrentTurn            int
 +
GalaxyAge              int
 +
GalaxyMaxAIAggression  int
 +
GalaxyMonsterFrequency  int
 +
GalaxyNativeFrequency  int
 +
GalaxyPlanetDensity    int
 +
GalaxyShape            int
 +
GalaxySize              int
 +
GalaxySpecialFrequency  int
 +
GalaxyStarlaneFrequency int
 +
UniverseCentreX        double
 +
UniverseCentreY        double
  
Parameters are generally specified as part of exteral data files that define most object classes. Along with the specific effects, conditions an non-effects related information in the external data files, the parameter values actually determine how game objects function. In some cases, however, it may be necessary for the game engine itself to generate parameter values (see Special Activation Condition: Owned by Specfic Empire).
+
==Complex Variables==
 +
These variables are for values which need more than one parameter. These need at least one extra parameter to distinguish the right value and can not directly be accessed from an object. Instead you typically pass also the object ID (e.g. Source.ID, Target.DesignID) as parameter.
  
Future Note: In future, additional parameters may need to be specifiable by the game enging according to user input.  This may work through something like the Future: Set Target effect, or be handled directly by the game engine (for condition parameter or in general).
+
  PartsInShipDesign name = "PART_NAME" design = DESIGN_ID
 +
Returns the count of ship parts with the part name PART_NAME which are part of the ship design with the id DESIGN_ID. Will return zero if no such design exists or no such parts exist in the design.
  
==Stacking Number==
+
SpecialAddedOnTurn name = "SPECIAL_NAME" object = ID
 +
Returns the turn in the Special with the name SPECIAL_NAME was attached to the object ID. Will return zero if no such object exists or no such special was attached to the object (Note: this should be changed to a maximum turn number so SpecialAddedOnTurn <= CurrentTurn will be false if no special was attached to the object).
  
Each effect has an integer parameter known as a "Stacking Number".
+
SpecialCapacity name = "SPECIAL_NAME" object = ID
 +
Returns the capacity of the Special with the name SPECIAL_NAME attached to the object ID. Will return zero if no such object exists or no such special was attached to the object.
  
Stacking number functions similar to a scope condition, in that it determines whether an effect fires on a particular object or not, but differs in that stacking is checked for each effect individually, rather than for effects groups as a whole.
+
ShipPartMeter part = "PART_NAME" meter = METER_TYPE object = SHIP_ID
 +
Value(ShipPartMeter part = "PART_NAME" meter = METER_TYPE object = SHIP_ID)
 +
Returns the part meter value of a ship (as double). The meter value of the meter type METER_TYPE for the part with name PART_NAME of the ship with the id SHIP_ID.  
  
If the specified "Stacking Number" for an effect is 0, the effect always fires.
+
Note you can use Value(ShipPartMeter) in effects to get the immediate/non-initial value. Will return 0.0 if the ship does not exist, the ship design does not have such a part, or the part class does not have this kind of meter associated.
  
If the stacking number is nonzero, the effect does not fire on a particular game object if another effect with the same stacking number has already fired on the same game object previously during the current turn.
+
Parameter Types:
 +
METER_TYPE meter type enum - one of Capacity, MaxCapacity, SecondaryStat, or MaxSecondaryStat
 +
*NAME string_constant
 +
*ID int_constant - the object identifier
  
Terminology: Two or more effects with the same nonzero stacking number are referred to as "nonstacking effects", in that only one of the effects may be applied to a given game object in a given turn (they do not "stack").
+
==Object Attributes==
  
Future Note: As described, this condition depends on the order in which effects fire.  That is, if two different effects fire on the same object, but are nonstacking effects, then the effect which fires first will be the effect that fires, while the other effect(s) will not fire.  The order in which effects fire might be controllable within a single effects group, depending on implimentation, but currently there is no precedence or ordering between effects groups that is accessible or controllable for content designeres.  Future designs will require some way to specify which effect fires in the case of conflicting nonstacking effects.  This may involve taking the largest, smallest or an average modification in the case of numerical effects. For non-numerical effects, some other system will be necessary.
+
Object attributes are variables that are properties of the Source, Target, LocalCandidate, or RootCandidate objects. In combination these are also called "complex variables".
  
==Numeric Parameters==
+
Some of the attributes have changing values which are tracked and manipulated as a meter. Usually these attributes return the initial value of the meter (before effects are executed), but one can access the current value changed by other effects using a Value() expression, e.g. Value(Source.TargetResearch) will return the current value of the Source object's TargetResearch meter.
  
Numeric parameters for some effects and some effects group scope or activation conditions may take the form of expressions involving constants, arithmetic operations and references to meter values (max or current) of the source object and/or target (scope) object.
+
===List===
  
===Parameter Expression Operators===
+
Here is a (currently incomplete) list of the attributes available (but not necessarily currently used in-game), and their types (more on types later):
  
The arithmetic operations in parameter expressions are represented by their corresponding standard operators, and may include:
+
      Age                int            the number of turns since the object was created
* Addition, +
+
      CreationTurn        int            the turn the object was created
* Subtraction, -
+
      ID                  int +++
* Multiplication, *
+
      Name                string
 +
      LastTurnBattleHere  int            the last turn a battle was in the system or the system which contains this object
 +
      NearestSystemID    int
 +
      NumSpecials        int            the count of specials an object has
 +
      ObjectType          UniverseObjectType +!  type of an object: Building, Field, Fleet, Planet, PopulationCenter, ProductionCenter, Ship, System
 +
      Owner              int ++         the ID of the empire which owns this object
 +
      OwnerName          string        the name of the object's owning empire
 +
      OwnerLeastExpensiveEnqueuedTech    returns the object's owner's empire's least expensive enqueued technology
 +
      PropagatedSupplyDistance  double  the object's system's propagated ??supply distance??
 +
      PropagatedSupplyRange  double      the object's system's propagated ??supply range??
 +
      Stealth            double  m      the stealth value meter of an object e.g. a ship or a planet
 +
      SupplyingEmpire    int            ID of the empire which supplies the system which contains the object
 +
      System              system ref    the system of the object's containing system
 +
      SystemID            int
 +
      X                  double        X-Position of an object on the map (e.g. a field, fleet, system..)
 +
      Y                  double        Y-Position of an object on the map (e.g. a field, fleet, system..)
  
Expressions take the form of a sum of terms, (having no mathematical brackets, () ). Terms are constants, references to meter values, or products thereof. 
+
      Size                double m      Size: the size value meter of a field
 +
      Speed              double m      the starlane speed meter of a field (or ship) measured in AU distance
  
Programmers may restrict product terms to only having a single * operator each as in "5*3", or they may permit "chaining" of * operators, as in "5*3*2*5*1".  Similarly, expressions may be limited to only a signle + or - operator, as in "4 + 2", or multiple +'s and/or -'s may be chained, as in "4 + 2 - 6 + 3". 
+
      NumStarlanes        int            the count of a system's starlanes
  
Expressions are evaluated according to the standard order of operations rules, so multiplication operations (product terms) are evaluated first, then + or - operations between terms.
+
      NextOlderStarType
 +
      NextYoungerStarType
 +
      StarType            StarType +     type of a system's star
  
===Example Expressions===
+
      Construction        double  m      construction value meter of a planet.
 +
TargetConstruction        double tm      construction value target meter of a planet
 +
DistanceFromOriginalType  double        distance of the current environment of a planet to the original environment type in steps (0,1,2,3, or 4)
 +
      Focus              string        the name of a planet's focus
 +
      HabitableSize      double        the habitable size of a planet - this depends on type of a planet and galaxy rule settings
 +
      Happiness          double  m      happiness value meter of a population center (currently only planets)
 +
TargetHappiness          double tm      happiness value target meter of a population center (currently only planets)
 +
      Industry            double  m      industry value meter of a planet (not yet used for ships)
 +
TargetIndustry            double tm      industry value target meter of a planet (not yet used for ships)
 +
      LastTurnAttackedByShip  int        turn number
 +
      LastTurnConquered
 +
      Orbit              int            the orbit ID of a planet where it is orbiting the star - i think this is only used for displaying the planets
 +
      PlanetSize          PlanetSize +  size of a planet compare with SizeAsDouble and HabitableSize
 +
        ClockwiseNextPlanetType  PlanetType +
 +
CounterClockwiseNextPlanetType  PlanetType +
 +
          NextBetterPlanetType  PlanetType +  planet type with one step better environment for a planet's species
 +
NextCloserToOriginalPlanetType  PlanetType +
 +
                  OriginalType  PlanetType +
 +
                    PlanetType  PlanetType +  the type of planet
 +
      PlanetEnvironment  PlanetEnvironment +  the environmental property for the planet's species from good to hostile
 +
      Population          double  m      population value meter of a population center (currently only planets)
 +
TargetPopulation          double tm      population value target meter of a population center (currently only planets)
 +
      Research            double  m      research value meter of a planet (not yet used for ships)
 +
TargetResearch            double tm      research value target meter of a planet (not yet used for ships)
 +
      RebelTroops        double  m      RebelTroops: not used yet
 +
      SizeAsDouble        double        The size of a planet as a double value. Compare with PlanetSize, HabitableSize, and PlanetType
 +
      Stockpile          double  m      imperial stockpile value meter of a planet
 +
    MaxStockpile          double mm      imperial stockpile value max meter of a planet
 +
      Supply              double  m      supply value meter of a planet
 +
    MaxSupply              double mm      supply value max meter of a planet
 +
      Trade              double  m      Trade: not used currently
 +
TargetTrade              double tm      TargetTrade: not used currently
 +
      Troops              double  m      troop count target meter of a planet (?? maybe the count of troops on a ship ??)
 +
    MaxTroops              double mm      troop count max meter of a planet
 +
      Defense            double  m      defense value meter of a planet
 +
    MaxDefense            double mm      defense value max meter of a planet
 +
    TurnsSinceFocusChange  int            number of turns since focus was last changed
  
References to meter values may take whatever format is deemed appropriate by programmers. The format used below is for illustrative purposes only, and need not be the format actually implimented.
+
      Detection          double  m      the detection range meter of a ship or a planet
 +
      PreferredFocus      string        the preferred focus type of a ship's or a planet's species
 +
      Shield              double m      the shield value meter of a ship or a planet
 +
    MaxShield              double mm      the max shield value meter of a ship or a planet
 +
      Species            string        species' textual id of a ship's (or fighter's) crew or a planet's population
 +
      SpeciesID          int            species' numerical id of a ship's crew or a planet's population
  
Example expressions that should all be functional:
+
      ArrivedOnTurn      int
* 5 (a constant without any operators)
+
      DesignID            int ++++
* 4 + SourceObject.CurrentFarmingMeter (simple addition of constant and meter reference)
+
      Fleet              fleet ref      the ship's containing fleet. Example usage: Target.Fleet.NumShips
* 3 * SourceObject.MaxMiningMeter - 2 * TargetObject.MaxMiningMeter (multiplication of meter references by constants, subtraction)
+
      Fuel                double  m      the fuel meter of a ship measured in starlane hops
 +
    MaxFuel                double mm      the max fuel meter of a ship measured in starlane hops
 +
      Hull                string        the type name of a hull type as specified in FOCS
 +
      LastTurnActiveInBattle  int
 +
      LastTurnResupplied  int
 +
      Speed              double  m      the starlane speed meter of a ship (or field) measured in AU distance
 +
      Structure          double  m      the structure value meter of a ship
 +
    MaxStructure          double mm      the max structure value meter of a ship
  
If a referenced meter is not present on a source object, the meter value is taken to be 0.
+
      ETA                int            turn number
 +
      FinalDestinationID  int            the id of a fleet's final destination system
 +
      NextSystemID        int            the id of the system a fleet is heading to/passing next
 +
      NumShips            int
 +
      PreviousSystemID    int            the id of the system a fleet was coming from
  
===When can use Meter Values be Used as Parameters?===
+
      LaunchedFrom        int            the id of the carrier ship a fighter was launched from (only in combat)
 +
      Species            string        species' textual id of a fighter's (or ship's) crew (or a planet's population)
  
Effects may use meter values in their parameters only if:
+
      BuildingType        string        the name of a building's type as specified in FOCS
* The effect does not modify a meter value
+
      Planet              planet ref    the planet a building is located on. E.g. Source.Planet.ID
* The effect's group's scope and activation conditions do not take parameters that refer to meter values.
+
  
Scope conditions and Activation Conditions may use meter values in their parameters only if:
+
      PlanetID            int            the id of the planet a building or a ship is located
* None of the effects in the effects group modify meter values
+
      ProducedByEmpireID  int            the id of the empire which produced a building or ship
 +
      FleetID            int            the id of a fleet or the fleet a ship belongs to
  
==Non-Numeric Parameters==
+
      Attack              double        fleet damage, ship's total weapon damage, or fighter's damage
 +
      NextTurnPopGrowth  double        NextTurnPopGrowth: not used currently
  
Non-Numeric parameters for some effects and some effects group scope or activation conditions may be either constant values or references to various properties of the source object.
+
<br>+    The valid values for these types are listed after the corresponding conditions below.  These values may change however, so for the most up-to-date list, it may be necessary to consult the FreeOrion source code.
 +
<br>++  Owner will return -1 if there are no owners (such as for a roaming space monster or unexplored system)
 +
<br>+++  This is the unique integer ID used to identify an object internally within FreeOrion.
 +
<br>++++ This is the unique integer ID used to identify a ship design.
 +
<br> m  This is tracked using a meter. There might be a connected target meter or max meter
 +
<br>mm  This is tracked using a max meter.
 +
<br>tm  This is tracked using a target meter.
 +
<br>!    While the code distinguishes between ProdCenter and PopCenters there is currently no overlap it is always a Planet ~~The types returned by ObjectType have some overlap.  For instance, a Planet is also a PopCenter and a ProdCenter.  In this case, Planet is returned before PopCenter or ProdCenter, since if you see a Planet, you know it is a ProdCenter, but seeing a ProdCenter, you have no idea if it is a Planet or something else that produces goods or resources, for instance a mining outpost. This principle guides the order in which type is determined when ObjectType is used.~~
  
Non-Numeric parameters should not be able to refer to the target object's properties.
+
The reference for the attributes is the file universe/ValueRef.cpp
  
===Example Expressions===
+
==Value==
  
References to non-numeric object properties may take whatever format is deemed appropriate by programmers.  The format used below is for illustrative purposes only, and need not be the format actually implimented.
+
As a special case, there is a utility variable available that is used like a free variable, but actually refers to what is being modified by an effect:
  
Example expressions that should all be functional for objects with the relevant properties:
+
Value                double, int, string, PlanetSize, PlanetType, StarType
* PL_LARGE (constant parameter value)
+
* SourceObject.PlanetSize (reference to source object property)
+
  
If a referenced parameter value is not a property of the source object, the hierarchy of attachment should be followed to find a value, if possibleIf no value can be found after attempting to use the attachment hierarchy, a default value should be provided.
+
The value of "Value" is the initial value (before the current effect acts) of whatever is being set.  For example, in a SetStealth effect, "Value" would return the same as "Target.Stealth"For SetPlanetType, "Value" would return the same as "Target.PlanetType".
  
=Effects System=
+
The type returned by "Value" depend on the type of effect in which it is used.  For meter-setting effects Value will be a double.  For SetPlanetSize, it will be a PlanetSize, and similarly for PlanetType, PlanetEnvironment, StarType.  For setting a planet's species, Value will be a string.
  
==Turn Processing Order==
+
Do not confuse this with the Value() expression, which is used to get the current value of a meter using a complex variable. 
  
*Set all max meters to 0.  Current meter values remain unchanged from previous turn's values.
+
==Statistics==
*Fire all meter altering effects
+
*Apply current-meter growth formula
+
*Cap current meters by max meter values as applicable
+
*Fire all non-meter-altering effects
+
*Do rest of turn
+
  
Note that meter altering effects fire before ship movement, or anything else, so ship move orders given in turn N do not affect meter values in turn N+1, but do affect meter values in turn N+2.
+
Statistics are values calculated from a sampling of objects in the game universe, which may or may not include the Source and Target objects.
  
In future there may be several times during a turn when a non-meter-altering effect can fire.  This times will be before, after and between things like ship movement, production/popgrowth/research and combat.  Effects-altering meters will always happen at the very start of a turn, however, before anything else, effects or otherwise.
+
====List====
  
==Effect Processing==
+
The available statistical calculations that can be performed on the property values of objects matching the sampling condition are:
  
When processing effects during one of the effects ordering stages, the following occurs:
+
If                - Returns 1 if at least one object matches the selection condition, or 0 otherwise
*Game objects are being iterated through, and a particular game object is selected to have its effects processed during this ordering stage
+
Count              - Returns the number of objects that match the selection condition
*If the selected game object has any groups of effects containing effects that can fire during this ordering stage, it is considered further
+
UniqueCount        - Returns the number of unique values of the property are present among objects that match the selection condition
*An effect group is selected that contains effects that fire during this ordering stage
+
  Sum                - Returns the sum of property values of objects that match the selection condition
*The activation conditions for this effects group are checked. If the effects group is active this turn, it is considered further
+
Mean              - Returns the arithmetic mean of property values
*The inclusive scope conditions for this effects group are applied, building up an initial scope of game objects
+
RMS                - Returns the square root of the arithmetic mean of the squares of the property values
*The exclusive scope conditions for this effects group are applied, excluding objects from the scope
+
Mode              - Returns the most common property value
*All of the effects of the effects group are applied, in order listed, to all of the objects in the scope
+
Max                - Returns the largest property value
*The processing loops back to cover all effects groups and all game objects
+
Min                - Returns the smallest property value
 +
Spread            - Returns the difference between the largest and smallest property values
 +
STDEV              - Returns the standard deviation of the property values
 +
Product            - Returns the product of multiplying all the property values together
  
 +
Mode may be used for any type of parameter, including enumerated types like PlanetSize and double or int or string.  The other statistic types may be used only for parameters that are int or double. If and Count may be used without specifying a property value.
  
 +
===Use===
  
=The Real Effects Document=
+
====Constants====
 +
In item descriptions, parameter values such as LOW, HIGH, or NUMBER may be simple numbers, like 5 or 10, in which case all objects with the appropriate meter are treated the same by Turn.
  
Note that throughout this entire document, cas (capitalization) mattersCurrentFarming works, but
+
====Variables====
CURRENTFARMING does not.
+
Parameter values may also be defined in terms of attributes (or "properties") of the Source, RootCandidate, LocalCandidate or Target objectIn these cases, different objects may be differently matched or not, if the property used differs between them.
  
 +
Object attributes can be referenced on the source or target object, but not alone.  So "Source.ID" and "Target.PlanetSize" are legal variables, but "PlanetEnvironment" in isolation is not. 
  
==Types and Expressions==
+
Parameter values may also be defined in terms of the free variables mentioned above that are not associated with a particular object.  In this case, the variable name is used without any object reference; for example, "CurrentTurn" returns the current game turn.
  
In the Conditions and Effects below, there are references to variables and expressions of various types. Variables refer to attributes of a source or target object.  The source object is the object to which the Effect is attached, and the target object(s) is(are) the objects that are within an Effect's scope.  Here is a comprehensive list of the attributes available, and their types (more on types later):
+
Parameter values for meter-altering effects may also refer to "Value" which is equivalent to referring to the meter of the target object that is being altered, depending which meter-setting effect is being used.
  
    CurrentFarming        double
+
In addition, an object's containing object, if one exists, may be used in a variable.  For instance, if the source is a planet, "Source.System.StarType" represents the star type of the source's system.  Planet may also be used in a similar fashion, as in "Target.Planet.PlanetEnvironment".
    MaxFarming            double
+
    CurrentIndustry      double
+
    MaxIndustry          double
+
    CurrentResearch      double
+
    MaxResearch          double
+
    CurrentTrade          double
+
    MaxTrade              double
+
    CurrentMining        double
+
    MaxMining            double
+
    CurrentConstruction  double
+
    MaxConstruction      double
+
    CurrentHealth        double
+
    MaxHealth            double
+
    CurrentPopulation    double
+
    MaxPopulation        double
+
    MoneyStockpile        double
+
    MineralStockpile      double
+
    FoodStockpile        double
+
    MoneyProduction      double
+
    FoodProduction        double
+
    MineralProduction    double
+
    IndustryProduction    double
+
    ScienceProduction    double
+
    PlanetSize            PlanetSize +
+
    PlanetType            PlanetType +
+
    PlanetEnvironment     PlanetEnvironment +
+
    ObjectType            UniverseObjectType +!
+
    StarType              StarType +
+
    PrimaryFocus          FocusType +
+
    SecondaryFocus        FocusType +
+
    Owner                int ++
+
    ID                    int +++
+
  
<br>+  See the FreeOrion sources for the valid values for these enumerated types.  They are omitted here, since they may change periodically.
+
Nonsensical combinations of Target, Source, Planet, System, and the above attributes are allowed, but will always return 0 for numeric values, and a special value representing an invalid value for enumerated type values.  The special invalid value is guaranteed not to match the value of any actual object.
<br>++  Owner will return -1 (instead of 0 like all other failures for numeric types) if there are no owners, or there are more than one, since this is guaranteed not to match any actual object.
+
<br>+++ This is tbe integer numeric ID used to identify an object internally within FreeOrion.
+
<br>!  The types returned by ObjectType have some overlap.  For instance, a Planet is also a PopCenter and a ProdCenter.  In this case, Planet is returned before PopCenter or ProdCenter, since if you see a Planet, you know it is a ProdCenter, but seeing a ProdCenter, you have no idea if it is a Planet or something else that produces goods or resources, for instance a mining outpost. This principle guides the order in which type is determined when ObjectType is used.
+
  
As mentioned above, these attributes can be referenced on the source or target object, but not alone.  So "Source.ID" and "Target.PlanetSize" are legal variables, but not "PlanetEnvironment".  In addition, an object's containing object, if one exists, may be used in a variable.  For instance, if the source is a planet, "Source.System.StarType" represents the ster type of the source's system.  Planet may also be used in a similar fashion, as in "Target.Planet.PlanetEnvironment".
+
For example, if the source object is a System, Source.System.StarType will always return an invalid Star Type.
  
Nonsensical combinations of Target, Source, Planet, System, and the above attributes are allowed, but will always return 0 for numeric values, and INVALID_... for enumerated type values.  For instance, if the source is a System, Source.System.StarType will always return INVALID_STAR_TYPE, which is guaranteed not to match any actual System.  Similarly, Target.System.CurrentFarming makes no sense (since meters exist for Planets but not Systems), and so will return 0.0.
+
Similarly, Target.System.Industry makes no sense (since industry meters meters exist for Planets but not Systems), and so will return the double value 0.0.
  
Now about types.  The "double" type listed above, is a double-precision floating point number, which is more or less any real number in the range [-10^300, 10^300].  The "int" type is an integer number, which is basically any whole number in the range [-2*10^9, 2*10^9].  The other types are enumerted types, with specific values.  Each such value has a string associated with it, for instance the first valid StarType is STAR_BLUE.
+
====Statistics====
 +
Parameter values may also be defined in terms of statistics calculated from the gamestateA statistic returns a value based on the specified property, calculation and a condition to select objects in the game Universe.
 +
 
 +
In any place where a constant or variable could be specified, a statistic may be used instead.  The format for a statistic calculation is:
 +
 
 +
Statistic STATISTIC_TYPE value = VALUE condition = SAMPLING_CONDITION
 +
 
 +
For example, to calculate the sum of all planets' populations,
 +
Statistic Sum value = LocalCandidate.Population condition = Planet
 +
 
 +
The result would return a double value, which will be used just as if a constant like 42.4 had been specified, or a variable like Target.Population had been specified.
 +
 
 +
==Types==
 +
 
 +
The "double" type listed above, is a double-precision floating point number, which is more or less any real number in the range [-10^300, 10^300].  The "int" type is an integer number, which is basically any whole number in the range [-2*10^9, 2*10^9].  The other types are enumerated types, with specific values.  Each such value has a string associated with it, for instance the first valid StarType is Blue.
  
 
In the Conditions and Effects below, certain parameters have types.  It is illegal to provide a parameter of the wrong type, and it will result in a thrown exception (a purposeful crash of FreeOrion).  There is one major exceptions to this.  It is legal to provide a int value for any parameter of any type.  This is mainly to support easy expression syntax, which is the next thing that needs to be addressed.
 
In the Conditions and Effects below, certain parameters have types.  It is illegal to provide a parameter of the wrong type, and it will result in a thrown exception (a purposeful crash of FreeOrion).  There is one major exceptions to this.  It is legal to provide a int value for any parameter of any type.  This is mainly to support easy expression syntax, which is the next thing that needs to be addressed.
  
Instead of providing a singe variable or constant value (such as 3.14, 5, or STAR_BLUE), you can instead provide an arithmetic expression.  Legal expressions may contain parentheses, +, -, *, and /.  The - operator can be binary as in "3 + 4", or unary as in "-Source.MaxHealth".  Whitespace (spaces, tabs, and newlines) is ignored.  Expressions may be arbtrarily complex.  The type of the entire expression must match the type of the parameter for which it is intended.  For instance, it is illegal to supply "1 + 3.14" as a value for an int-type parameter, since 3.14 is not an int. As mentioned before, though, it is legal to supply "STAR_BLUE + 1" as a value for a StarType parameter, since integers are always ok.
+
Instead of providing a singe variable or constant value (such as 3.14, 5, or STAR_BLUE), you can instead provide an arithmetic expression.  Legal expressions may contain parentheses, +, -, *, / and ^ (for exponentiation).  The - operator can be binary as in "3 - 4", or unary as in "-Source.MaxHealth".  Whitespace (spaces, tabs, and newlines) is ignored.  Expressions may be arbitrarily complex.  The type of the entire expression must match the type of the parameter for which it is intended.  For instance, it is illegal to supply "1 + 3.14" as a value for an int-type parameter, since 3.14 is not an int. As mentioned before, though, it is legal to supply "STAR_BLUE + 1" as a value for a StarType parameter, since integers are always ok.
  
Note that since arbitrarily complex expressions are allowed in Effects, and multiple Effects may affect a single target in a single turn, the order in which the Effects are applied to the target may matter.  For instance, if Effect A is sets the current industry meter to "Target.CurrentIndustry + 20", and Effect B sets the current industry meter to "Target.CurrentIndustry * 3", the answer could be X * 3 + 20 or (X + 20) * 3, depending on the order of execution.  To minimize this, and in keeping with the guidelines for Effects in general, such Effects should have small magnitude, which will make the problem largely disappear.  For instance,  if "Target.CurrentIndustry + 3" and "Target.CurrentIndustry * 1.05" are used instead, the difference between X * 1.05 + 3 and (X + 3) * 1.05 is a negligible 0.15.
+
Note that since arbitrarily complex expressions are allowed in Effects, and multiple Effects may affect a single target in a single turn, the order in which the Effects are applied to the target may matter.  For instance, if Effect A sets the current industry meter to "Target.Industry + 20", and Effect B sets the current industry meter to "Target.Industry * 3", the answer could be X * 3 + 20 or (X + 20) * 3, depending on the order of execution.  To minimize this, and in keeping with the guidelines for Effects in general, such Effects should have small magnitude, which will make the problem largely disappear.  For instance,  if "Target.Industry + 3" and "Target.Industry * 1.05" are used instead, the difference between X * 1.05 + 3 and (X + 3) * 1.05 is a negligible 0.15.
  
Note that some of the parameters in the Conditions and Effects below ask for a certain type, sometimes a type-expression.  Those paramters that do not explicitly allow type-expressions cannot handle them.
+
Note that some of the parameters in the Conditions and Effects below ask for a certain type, sometimes a type-expression.  Those parameters that do not explicitly allow type-expressions cannot handle them.
  
Finally, note that in places below where a bool value is requested, you must enter a "1" for true or a "0" for false.  "False", "True", "T", "F", etc., are not recognized.
+
==Value==
  
 +
The Value parameter for a statistic can be practically any kind of ValueRef, including complex expressions.  The one exception that comes to mind is that attempting to use a statistic as the Value for another statistic has had parsing problems which may not yet be fully resolved.
  
 +
=Conditions=
  
==Conditions==
+
The syntax {a|b|c} below indicates a choice of values, exactly one of which must be selected.  The brackets and vertical lines are not legal to use themselves.
  
 +
{a|[a b c ...]} indicates that a single item may be specified ( a ), or multiple items in a list ( [a b c ...] ).
  
==All==
+
"low = ", "high = ", etc., indicates an *optional* parameter name.  All parameters must appear in the order indicated, so the names are not necessary to indicate which value is meant for which parameter. The name may be included, however (except for with the And, Not and Or conditions, which do not have or allow such parameter names).
<br>Descr.:    Matches all objects.
+
<br>XML format:
+
    <Condition::All/>
+
  
 +
==General==
  
==EmpireAffiliation==
+
  All
<br>Descr.:    Matches all objects that are owned (if EXCLUSIVE == false) or only owned (if EXCLUSIVE == true) by an empire that has affilitation type affilitation with Empire EMPIRE_ID.
+
<br>XML format:
+
    <Condition::EmpireAffiliation>
+
        <empire_id>EMPIRE_ID</empire_id>
+
        <affiliation>AFFILIATION</affiliation>
+
        <exclusive>EXCLUSIVE</exclusive>
+
    </Condition::EmpireAffiliation>
+
  
<br>Param Types:
+
Matches all objects.
<br>EMPIRE_ID  int-expression
+
<br>AFFILIATION EmpireAffiliationType
+
<br>EXCLUSIVE  bool
+
  
  
==Self==
+
Source
<br>Descr.:    Matches the source object only.
+
<br>XML format:
+
    <Condition::Self/>
+
  
 +
Matches the Source object.
  
==Type==
 
<br>Descr.:    Matches all objects that are of UniverseObjectType TYPE.
 
<br>XML format:
 
    <Condition::Type>TYPE</Condition::Type>
 
  
<br>Param Types:
+
Target
<br>TYPE UniverseObjectType-expression
+
  
 +
Matches the target object of an effect.  This can be used within effect definitions, but not within scope or activation condition definitions, as when those conditions are evaluated, the target object hasn't yet been determined.
  
==Building==
 
<br>Descr.:    Matches all Building objects of the sort specified by NAME.
 
<br>XML format:
 
    <Condition::Building>NAME</Condition::Building>
 
  
<br>Param Types:
+
Turn low = LOW high = HIGH
<br>NAME string
+
 
 +
Matches objects if the current game turn is greater than or equal to LOW and less than HIGH.
 +
 
 +
 
 +
NumberOf number = NUMBER condition = CONDITION
 +
 
 +
Matches at most NUMBER objects that match CONDITION.  If fewer than NUMBER objects match CONDITION, all such objects are matched.  If more than NUMBER objects match CONDITION, NUMBER such objects are randomly selected and matched.
 +
 
 +
MinimumNumberOf number = NUMBER sortkey = SORTKEY condition = CONDITION
 +
MaximumNumberOf number = NUMBER sortkey = SORTKEY condition = CONDITION
 +
ModeNumberOf    number = NUMBER sortkey = SORTKEY condition = CONDITION
 +
 
 +
These variants of NumberOf take a SORTKEY argument which is used to sort the objects matching the CONDITION before the elements get selected. The SORTKEY is a double valueref (e.g. such as LocalCandidate.Happiness).
 +
MinimumNumberOf will select and match (up to) NUMBER objects which have the smallest SORTKEY value of all matching objects.
 +
MaximumNumberOf will select and match (up to) NUMBER objects which have the highest SORTKEY value of all matching objects.
 +
ModeNumberOf will select and match (up to) NUMBER objects which have the most frequent values of all matching objects' SORTKEY values (e.g. you could a match a number of planets with the most common defense meter value).
 +
 
 +
 
 +
Number low = LOW high = HIGH condition = CONDITION
 +
 
 +
Matches all objects if the number of objects that match CONDITION is greater than or equal to LOW and less than HIGH.  Objects matched may or may not themselves match CONDITION.
 +
 
 +
 
 +
Random probability = PROB
 
   
 
   
 +
Matches objects with a probability of PROB.  That is, objects have a probability of PROB of being matched.
  
==HasSpecial==
+
==Type==
<br>Descr.:    Matches all objects that have an attached Special of the sort specified by NAME. Passing "All" for NAME will match all objects with attached Specials.
+
<br>XML format:
+
    <Condition::HasSpecial>NAME</Condition::HasSpecial>
+
  
<br>Param Types:
+
Building
<br>NAME string
+
Ship
 +
Fighter
 +
Fleet
 +
Planet
 +
PopulationCenter
 +
ProductionCenter
 +
System
 +
 +
Matches objects with the indicated type.
  
 +
==Building / Special==
  
==Contains==
+
Building name = {"NAME" | ["NAME0" "NAME1" "NAME2" ...]}
<br>Descr.:    Matches all objects that contain an object that matches Condition CONDITION. Container objects are Systems, Planets (which contain Buildings), and Fleets (which contain Ships).
+
<br>XML format:
+
    <Condition::Contains>
+
    CONDITION
+
    </Condition::Contains>
+
  
<br>Param Types:
+
Matches buildings with the indicated name(s).  NAME is as indicated in a particular building description, by: name = "NAME" or name = ["NAME0" "NAME1" "NAME2"] (etc.)
<br>CONDITION Condition
+
  
  
==PlanetType==
+
HasSpecial name = "NAME"
<br>Descr.:    Matches all Planet objects that have one of the given PlanetTypes.  Note that all Building objects which are on matching planets are also matched.
+
<br>XML format:
+
    <Condition::PlanetType>
+
        <PlanetType>TYPE0</PlanetType>
+
        <PlanetType>TYPE1</PlanetType>
+
    ...
+
        <PlanetType>TYPEN</PlanetType>
+
    </Condition::PlanetType>
+
  
<br>Param Types:
+
Matches objects that have the indicated special.
<br>TYPEX PlanetType-expression
+
  
 +
==Containing Associations==
  
==PlanetSize==
+
Contains condition = CONDITION
<br>Descr.:    Matches all Planet objects that have one of the given PlanetSizes.  Note that all Building objects which are on matching planets are also matched.
+
<br>XML format:
+
    <Condition::PlanetSize>
+
        <PlanetSize>SIZE0</PlanetSize>
+
        <PlanetSize>SIZE1</PlanetSize>
+
    ...
+
        <PlanetSize>SIZEN</PlanetSize>
+
    </Condition::PlanetSize>
+
  
<br>Param Types:
+
Matches objects that contain one or more objects that match the indicated CONDITION
<br>SIZEX PlanetSize-expression
+
  
  
==PlanetEnvironment==
+
ContainedBy condition = CONDITION
<br>Descr.:    Matches all Planet objects that have one of the given PlanetEnvironments. Note that all Building objects which are on matching planets are also matched.
+
<br>XML format:
+
    <Condition::PlanetEnvironment>
+
        <PlanetEnvironment>ENVIRONMENT0</PlanetEnvironment>
+
        <PlanetEnvironment>ENVIRONMENT1</PlanetEnvironment>
+
    ...
+
        <PlanetEnvironment>ENVIRONMENTN</PlanetEnvironment>
+
    </Condition::PlanetEnvironment>
+
  
<br>Param Types:
+
Matches objects that are contained by one or more objects that match the indicated CONDITION
<br>ENVIRONMENTX PlanetEnvironment-expression
+
  
  
==FocusType==
+
Enqueued type = {Building | Ship} name = "NAME" empire = EMPIRE low = LOW high = HIGH
<br>Descr.:    Matches all ProdCenter objects that have one of the given FocusTypes.
+
Enqueued type = Ship design = DESIGNID low = LOW
<br>XML format:
+
Enqueued type = {Building | Ship} empire = EMPIRE high = HIGH
    <Condition::Focus>
+
Enqueued low = LOW
        <FocusType>FOCUS0</FocusType>
+
        <FocusType>FOCUS1</FocusType>
+
    ...
+
        <FocusType>FOCUSN</FocusType>
+
    </Condition::FocusType>
+
  
<br>Param Types:
+
Matches objects where the empire with the indicated id EMPIRE (or any empires if none is specified) have within the indicated range (LOW to HIGH inclusive) of the indicated type of production item with the indicated name or design ID (NAME or DESIGN ID) and TYPE (Building or Ship).  The count used to assess LOW and HIGH takes into account the element blocksize.
<br>FOCUSX FocusType-expression
+
  
 +
==Planet / Star==
  
==StarType==
+
Planet type = {TYPE|[TYPE0 TYPE1 TYPE2 ...]}
<br>Descr.:    Matches all System objects that have one of the given StarTypes.  Note that all objects in matching Systems are also matched (Ships, Fleets, Buildings, Planets, etc.).
+
<br>XML format:
+
    <Condition::StarType>
+
        <StarType>TYPE0</StarType>
+
        <StarType>TYPE1</StarType>
+
    ...
+
        <StarType>TYPEN</StarType>
+
    </Condition::StarType>
+
  
<br>Param Types:
+
Matches objects that are or are contained by planets that have the indicated type.
<br>TYPEX StarType-expression
+
  
 +
Types are:
 +
Swamp
 +
Toxic
 +
Inferno
 +
Radiated
 +
Barren
 +
Tundra
 +
Desert
 +
Terran
 +
Ocean
 +
Gaia
 +
Asteroids
 +
GasGiant
  
==Chance==
 
<br>Descr.:    Matches a given object with a linearly distributed probability of CHANCE.
 
<br>XML format:
 
    <Condition::Chance>
 
        <chance>CHANCE</chance>
 
    </Condition::Chance>
 
  
<br>Param Types:
+
Planet size = {SIZE|[SIZE0 SIZE1 SIZE2 ...]}
<br>CHANCE double-expression
+
  
 +
Matches objects that are or are contained by planets that are the indicated size.
 +
 +
Sizes are:
 +
Tiny
 +
Small
 +
Medium
 +
Large
 +
Huge
 +
Asteroids
 +
GasGiant
 +
 +
 +
Planet environment = {ENV|[ENV0 ENV1 ENV2 ...]}
 +
 +
Matches objects that are or are contained by planets that have the indicated environment.
 +
 +
Environments are:
 +
Uninhabitable
 +
Hostile
 +
Poor
 +
Adequate
 +
Good
 +
 +
 +
HomeWorld
 +
    name = {SPECIES|[SPECIES0 SPECIES1 ...]}    [optional -- may be left out]
 +
 +
Matches planets that are homeworlds to playable species.  If no species are specified, the homeworld of any species will be matched.
 +
 +
SPECIES the name of a species in the game, as defined in a species definition file
 +
 +
 +
Capital
 +
 +
Matches planets that are capitols of an (any) empire.  Use in combination with OwnedBy for a specific empire's homeworld.
 +
 +
 +
Star type = {TYPE|[TYPE0 TYPE1 TYPE2 ...]}
 +
 +
Matches objects that are or are contained by systems that have the indicated star type.
 +
 +
Types are:
 +
Blue
 +
White
 +
Yellow
 +
Orange
 +
Red
 +
Neutron
 +
BlackHole
 +
 +
==Infrastructure / Focus==
 +
 +
Focus focus = {FOCUS|[FOCUS0 FOCUS1 FOCUS2 ...]}
 +
 +
Matches planets that have the indicated focus or any of the indicated foci.
 +
 +
FOCUS or FOCUS# are strings.  Each species may have a different set of foci available, but typical focus options include "FOCUS_GROWTH", "FOCUS_INDUSTRY", "FOCUS_LOGISTICS", "FOCUS_PROTECTION", "FOCUS_RESEARCH", and "FOCUS_STOCKPILE"
 +
 +
To check if a given focus (FOCUS_RESEARCH in the below example) is simply available at a planet (even if not actually selected), the following check can be used:
 +
  And [
 +
      Planet
 +
      Location type=Focus name = LocalCandidate.Species name = "FOCUS_RESEARCH"
 +
  ]
 +
 +
For reference the focus are defined in file default/scripting/species/common/focus.macros
  
 
==MeterValue==
 
==MeterValue==
<br>Descr.:    Matches all objects that have a meter of type METER, and whose current value (if MAX_METER == false) or maximum value (if MAX_METER == true) of that meter is >= LOW and    < HIGH.
 
<br>XML format:
 
    <Condition::MeterValue>
 
        <meter>METER</meter>
 
        <low>LOW</low>
 
        <high>HIGH</high>
 
        <max_meter>MAX_METER</max_meter>
 
    </Condition::MeterValue>
 
  
<br>Param Types:
+
TargetPopulation low = LOW high = HIGH
<br>METER    MeterType
+
TargetIndustry low = LOW high = HIGH
<br>LOW       double-expression
+
TargetResearch low = LOW high = HIGH
<br>HIGH     double-expression
+
TargetTrade low = LOW high = HIGH
<br>MAX_METER bool
+
TargetConstruction low = LOW high = HIGH
 +
MaxFuel low = LOW high = HIGH
 +
MaxShield low = LOW high = HIGH
 +
MaxStructure low = LOW high = HIGH
 +
MaxDefense low = LOW high = HIGH
 +
Population low = LOW high = HIGH
 +
Industry low = LOW high = HIGH
 +
Research low = LOW high = HIGH
 +
Trade low = LOW high = HIGH
 +
Construction low = LOW high = HIGH
 +
Fuel low = LOW high = HIGH
 +
Shield low = LOW high = HIGH
 +
Structure low = LOW high = HIGH
 +
Defense low = LOW high = HIGH
 +
Supply low = LOW high = HIGH
 +
Stealth low = LOW high = HIGH
 +
Detection low = LOW high = HIGH
 +
Starlanespeed low = LOW high = HIGH
 +
HasSpecialCapacity name = "SPECIAL_NAME" low = LOW high = HIGH
 +
HasSpecialSinceTurn name = "SPECIAL_NAME" low = LOW high = HIGH
  
 +
Matches objects with the appropriate meter values that are greater than or equal to LOW and less than or equal to HIGH.  That is, LOW specifies the lowest allowed value of the meter, and HIGH specifies the highest allowed value.  Either of the LOW and HIGH parameters may be omitted, in which case there is no limit on the meter value in that direction.  For example, if only LOW is specified, there is no upper limit on the allowed meter value.
  
==VisibleToEmpire==
+
The HasSpecialCapacity uses the capacity meter of the special given as string name. The HasSpecialSinceTurn queries the turn a special was first set on an object.
<br>Descr.:    Matches all objects that are visible to at least one given empire id.
+
<br>XML format:
+
    <Condition::VisibleToEmpire>
+
        <empire_id>ID0</empire_id>
+
        <empire_id>ID1</empire_id>
+
    ...
+
        <empire_id>IDN</empire_id>
+
    </Condition::VisibleToEmpire>
+
  
<br>Param Types:
+
==Object Owner / Producer==
<br>IDX int-expression
+
  
 +
OwnedBy affiliation = {EnemyOf|AllyOf|TheEmpire|AnyEmpire} [empire = EMPIRE]
  
==WithinDistance==
+
Matches objects owned by (OwnedBy) an empire with the indicated affiliation to the indicated id EMPIRE.  EMPIRE may be omitted with using AnyEmpire, which will match objects owned by any empire, regardless of what EMPIRE is specified (or not). Typically EMPIRE is specified as a function of an object, such as Source.Owner, however a constant integer such as 2 may also be specified.
<br>Descr.:    Matches all objects that are within DISTANCE units of at least one object that meets CONDITION. Warning: this Condition can slow things down considerably if overused. It is best to use Conditions that yield relatively few matches.
+
<br>XML format:
+
    <Condition::WithinDistance>
+
        <distance>DISTANCE</distance>
+
        <condition>CONDITION</condition>
+
    </Condition::WithinDistance>
+
  
<br>Param Types:
 
<br>DISTANCE double-expression
 
<br>CONDITION Condition
 
  
 +
OwnerFoodStockpile low = LOW high = HIGH
 +
OwnerMineralStockpile low = LOW high = HIGH
 +
OwnerTradeStockpile low = LOW high = HIGH
  
==WithinStarlaneJumps==
+
Matches objects with exactly one owner, whose owner's stockpile of the appropriate resource is greater than or equal to LOW and less than or equal to HIGH.
<br>Descr.:    Matches all objects that are within JUMPS starlane jumps of at least one object that meets CONDITION. Warning: this Condition can slow things down considerably if overused. It is best to use Conditions that yield relatively few matches.
+
<br>XML format:
+
    <Condition::WithinStarlaneJumps>
+
        <jumps>JUMPS</jumps>
+
        <condition>CONDITION</condition>
+
    </Condition::WithinStarlaneJumps>
+
  
<br>Param Types:
 
<br>JUMPS int-expression
 
<br>CONDITION Condition
 
  
 +
OwnerHasTech name = "NAME"
  
==And==
+
Matches objects with exactly one owner, whose owner has the tech NAME.
<br>Descr.:    Matches all objects that match every Condition in    <operands>.
+
<br>XML format:
+
    <Condition::And>
+
    OPERAND0
+
    OPERAND1
+
    ...
+
    OPERANDN
+
    </Condition::And>
+
  
<br>Param Types:
+
Note: This is useful for refinements of technologies, where a refinement tech is indicated by NAME in an effects group of the item being refined.
<br>OPERANDX Condition
+
  
  
==Or==
+
VisibleToEmpire empire = {EMPIRE|[EMPIRE0 EMPIRE1 EMPIRE2 ...]}
<br>Descr.:    Matches all objects that match at least one Condition in    <operands>.
+
<br>XML format:
+
    <Condition::Or>
+
    OPERAND0
+
    OPERAND1
+
    ...
+
    OPERANDN
+
    </Condition::Or>
+
  
<br>Param Types:
+
Matches objects that are visible to the indicated empire(s).
<br>OPERANDX Condition
+
  
  
==Not==
+
ProducedByEmpire empire = EMPIRE
<br>Descr.:    Matches all objects that do not match the Condition OPERAND.
+
<br>XML format:
+
    <Condition::Not>
+
    OPERAND
+
    </Condition::Not>
+
  
<br>Param Types:
+
Matches buildings or ships produced by the empire with id indicated by EMPIRE.  Typically EMPIRE is specified as a function of an object, such as Source.Owner, however a constant integer such as 2 may also be specified.  Note that ownership and who produced an object aren't necessary the same, particularly for buildings, which may be captured with planets from other empires.
<br>OPERAND Condition
+
  
 +
==Ship Design==
  
Note 1: Some Conditions that match an object's containing object will be returned, even though they at first seem to be nonsensical. For instance, if the target object is a Planet, StarType will match the type of the System in which the target is located.  This means that StarType will match all objects in all Systems with the given star type, and the Systems themselves. Similarly, all objects on all Planets (and the Planets themselves) that match a PlanetType, PlanetSize, or PlanetEnvironment will be matched.  This has an important implication; if you want all Systems with blue stars, you should use StarType=STAR_BLUE AND Type=OBJ_SYSTEM:
+
  Design name = "NAME"
  
    <Condition::And>
+
Matches ships that have a design generated from the predefined designs in ship_designs/ or monster_designs/.
        <Condition::StarType>
+
            <StarType>STAR_BLUE</StarType>
+
        </Condition::StarType>
+
        <Condition::Type>
+
            <type>OBJ_SYSTEM</type>
+
        </Condition::Type>
+
    </Condition::And>
+
  
If you want all Ships in Systems with blue stars, you should use StarType=STAR_BLUE AND Type=OBJ_SHIP:
+
Design design = DESIGNID
  
    <Condition::And>
+
Matches ships that have the specified ship design ID.  Most likely this would be Source.DesignID
        <Condition::StarType>
+
            <StarType>STAR_BLUE</StarType>
+
        </Condition::StarType>
+
        <Condition::Type>
+
            <type>OBJ_SHIP</type>
+
        </Condition::Type>
+
    </Condition::And>
+
  
 +
DesignHasHull name = "NAME"
  
Note 2: The And and Or Conditions are designed to work as efficiently as possible, by only searching the objects that have not already been matched.  So it is always best to put the most restrictive Condition first in an And Condition's operands.  For instance, if StarType=STAR_BLUE matches about 1000 objects, And(Self, StarType=STAR_BLUE) will be about 1000 times faster than And(StarType=STAR_BLUE, Self), since the former only has to look at the match from Self to see if it also is (or is inside of) a blue-starred System, whereas that latter has to look through the 1000 matches from StarType=STAR_BLUE to see if any of them also matches Self.
+
Matches ships that have the indicated hull in their design.
  
 +
DesignHasPart low = LOW high = HIGH name = "NAME"
  
 +
Matches ships that have >= LOW and < HIGH of the part NAME in their design.
  
 +
DesignHasPartClass low = LOW high = HIGH class = CLASS
  
==Effects==
+
Matches ships that have >= LOW and < HIGH of parts of the indicated PartClass in their design.
 +
 
 +
Armed
 +
 
 +
Matches ships that have weapons.
 +
 
 +
Monster
 +
 
 +
Matches space monsters.
 +
 
 +
==Galaxy Map Position==
 +
 
 +
WithinDistance distance = DISTANCE condition = CONDITION
 +
 
 +
Matches objects that are within the indicated Euclidean direct-line DISTANCE of any objects that matches CONDITION.  The matched objects may or may not themselves match CONDITION.
 +
 
 +
 
 +
WithinStarlaneJumps jumps = JUMPS condition = CONDITION
 +
 
 +
Matches objects that are within the indicated number of starlane jumps (crossings from one star to the next) of any objects that matches CONDITION.  The matched objects may or may not themselves match CONDITION.
 +
 
 +
 
 +
Stationary
 +
 
 +
Matches objects that are not moving.  The only objects that move are fleets and ships.  Objects are not stationary if they are going to move, so fleets ordered to move are not stationary, but fleets that arrive in a system are stationary on the turn after they arrive.
 +
 
 +
ResupplyableBy empire = EMPIRE
 +
 
 +
Matched objects should be in systems where the empire with id EMPIRE can provide fleet supply.
 +
 
 +
ResourceSupplyConnected empire = EMPIRE condition = CONDITION
 +
 
 +
Matched objects should be in systems connected by resource sharing lines for the empire with id EMPIRE to at least one object that matches the sub-condition CONDITION. Objects outside systems shouldn't be matched, regardless of whether they're on a starlane that is connected to an object that matched the sub-condition.
 +
 
 +
==Conditional==
 +
 
 +
Conditional conditions are variants of some kind of "if". The only conditional condition we have currently is OrderedAlternativesOf, in some cases one can use the If statistic in ValueRef statements to get conditional results.
 +
 
 +
The OrderedAlternativesOf provides the ability to conditionally match the objects of the first condition inside of it which matches at least one local candidate.
 +
An example from FT_HANGAR_1 (Note that COMBAT_TARGETS_VISIBLE_ENEMY has to be repeated inside each single tier condition)
 +
<pre>    combatTargets = OrderedAlternativesOf [
 +
        // Target Bombers and Heavy Bombers first
 +
        And [
 +
            [[COMBAT_TARGETS_VISIBLE_ENEMY]]
 +
            Fighter
 +
            Or [
 +
              DesignHasPart name = "FT_HANGAR_3"
 +
              DesignHasPart name = "FT_HANGAR_4"
 +
            ]
 +
        ]
 +
        And [ [[COMBAT_TARGETS_VISIBLE_ENEMY]]  Fighter ]
 +
        // if no fighters: target enemy ships
 +
        And [ [[COMBAT_TARGETS_VISIBLE_ENEMY]]  [[COMBAT_TARGETS_NOT_DESTROYED_SHIP]] ]
 +
    ]</pre>
 +
 
 +
==Logical==
 +
 
 +
Note: There are no optional "param =" indicators for And, Or, & Not.
 +
 
 +
And [CONDITION0 CONDITION1 CONDITION2 ...]
 +
And [
 +
  CONDITION0
 +
  CONDITION1
 +
  CONDITION2
 +
]
 +
 
 +
Matches objects that match all of the indicated subconditions.
 +
 
 +
 
 +
Or [CONDITION0 CONDITION1 CONDITION2 ...]
 +
Or [
 +
  CONDITION0
 +
  CONDITION1
 +
  CONDITION2
 +
]
 +
 
 +
Matches objects that match at least one, or more, of the indicated subconditions.
 +
 
 +
 
 +
Not CONDITION
 +
 
 +
Matches objects that do not match CONDITION.
 +
 
 +
==Notes==
 +
 
 +
===Implicit ContainedBy===
 +
 
 +
Some Conditions that match an object's containing object will be returned, even though they at first seem to be nonsensical.  For instance, if the target object is a Planet, StarType will match the type of the System in which the target is located.  This means that StarType will match all objects in all Systems with the given star type, and the Systems themselves. Similarly, all objects on all Planets (and the Planets themselves) that match a PlanetType, PlanetSize, or PlanetEnvironment will be matched.  This has an important implication; if you want all Systems with blue stars, you should use
 +
 
 +
And [
 +
  Star type = Blue
 +
  System
 +
]
 +
 
 +
If you want all Ships in Systems with blue stars, you should use:
 +
 
 +
And [ Ship Star type = Blue ]
 +
 
 +
===And & Or Efficiency===
 +
 
 +
The And and Or Conditions are designed to work as efficiently as possible, by only searching the objects that have not already been matched.  So it is always best to put the most restrictive Condition first in an And Condition's list of subconditions.
 +
 
 +
For instance, if "Star type = Blue" matches about 1000 objects,
 +
And [ Source Star type = Blue ]
 +
will be about 1000 times faster than
 +
And [ Star type = Blue Source ]
 +
This is because the former only has to look at the match from Source to see if it also is (or is inside of) a blue-starred System, whereas that latter has to look through the 1000 matches of objects that are or are in blue-starred systems, to see if any of them also matches Source.
 +
 
 +
=Effects=
  
 
==SetMeter==
 
==SetMeter==
<br>Descr.:    Sets the meter of the given kind to VALUE.  The max value of the meter is set if MAX == true; otherwise the current value of the meter is set.  If the target of the Effect has no meters, nothing is done.
 
<br>XML format:
 
    <Effect::SetMeter>
 
        <meter>METER</meter>
 
        <value>VALUE</value>
 
        <max>MAX</max>
 
    </Effect::SetMeter>
 
  
<br>Param Types:
+
# on planets
<br>METER MeterType
+
SetTargetConstruction value = VALUE # not really in use
<br>VALUE double-expression
+
SetTargetHappiness value = VALUE
<br>MAX  bool
+
SetTargetIndustry value = VALUE
 +
SetTargetPopulation value = VALUE
 +
SetTargetResearch value = VALUE
 +
SetTargetTrade value = VALUE # not in use
 +
SetMaxDefense value = VALUE
 +
SetMaxSupply value = VALUE
 +
SetMaxStockpile value = VALUE
 +
SetConstruction value = VALUE # not really in use
 +
SetDefense value = VALUE
 +
SetHappiness value = VALUE
 +
SetIndustry value = VALUE
 +
SetPopulation value = VALUE
 +
SetResearch value = VALUE
 +
SetSupply value = VALUE
 +
SetTrade value = VALUE # not in use
 +
SetSize value = VALUE
  
 +
# on planets and ships
 +
SetMaxShield value = VALUE
 +
SetMaxTroops value = VALUE
 +
SetDetection value = VALUE
 +
SetShield value = VALUE
 +
SetStealth value = VALUE
 +
SetTroops value = VALUE
 +
 +
# on ships
 +
SetMaxFuel value = VALUE
 +
SetMaxStructure value = VALUE
 +
SetFuel value = VALUE
 +
SetSpeed value = VALUE
 +
SetStructure value = VALUE
 +
 +
Param Type:
 +
VALUE double
 +
 +
Sets the appropriate meter to VALUE.
 +
 +
* If the target of the Effect does not have the requested meter, nothing is done.
 +
* Typically, meter-setting effects do so by adding or subtracting form the same meter value of the Target.  For example,
 +
 +
SetTargetResearch Target.TargetResearch + 5
 +
 +
or
 +
 +
SetHealth Value - 10
 +
 +
The value "Value" always refers to the present value of the meter being set, allowing incremental changes to meter values without the cumbersome use of references to the Target such as "Target.FoodConsumption" (for the Target's food consumption meter) which would instead be just "Value" when using the SetFoodConsumption effect.
 +
 +
When a "max" (eg. MaxStructure) or "target" (eg. TargetPopulation) meter value, or another meter for which there is no associated "max" or "target" meter (eg. Stealth), the change is non-persistent.  This means that every turn, the meter is reset to 0, and all effects must re-act on the meter for it to retain a consistent value.  If on a subsequent turn, the effect does not at on that target, the meter value will return to its previous value (or whatever value all other effects acting on it produce).
 +
 +
When a meter (eg. Structure) has an associated "max" or "target" meter (eg. MaxStructure), the meter value IS persistent.  Repeatedly applying the same effect every turn will accumulate.  If an effect reduced an object's Health meter by -2 every turn, the 2nd turn would have a net -4 reduction, the 3rd turn would have a net -6 reduction, etc.  If an effect alters such a meter once, then does not act again, the meter stays reduced, until other effects increase or decrease it, or it increases or decreases itself over time towards its associated target or max value.
 +
 +
==SetShipPartMeter==
 +
 +
Acting on ships:
 +
SetMaxCapacity      (set capacity max meter)
 +
SetMaxDamage        (set capacity max meter - this may do the wrong thing for hangar parts)
 +
SetMaxSecondaryStat (set secondary capacity max meter)
 +
SetCapacity        (set capacity meter)
 +
SetDamage          (set capacity meter - this may do the wrong thing for hangar parts)
 +
SetSecondaryStat    (set secondary capacity meter)
 +
 +
==SetOwnerCapitol==
 +
 +
SetOwnerCapitol
 +
 +
Sets the target object to be the capitol of its owner's empire.  If the target is not a planet, or is not owned by a single empire, nothing is done.
  
 
==SetPlanetType==
 
==SetPlanetType==
<br>Descr.:    Sets the planet type of the target to TYPE.  This has no effect on non-Planet targets.
 
<br>XML format:
 
    <Effect::SetPlanetType>TYPE</Effect::SetPlanetType>
 
  
<br>Param Types:
+
SetPlanetType type = TYPE
<br>TYPE PlanetSize-expression
+
 
 +
Param Type:
 +
TYPE PlanetType
 +
 
 +
Sets the planet type of the target to TYPE.
  
 +
* Has no effect on non-Planet targets.
 +
* Changing type from Asteroids or GasGiant to something else will also change its size to Tiny or Huge, respectively.
 +
* Changing type to Asteroids or GasGiant will also cause the size to change to Asteroids or GasGiant, respectively.
  
 
==SetPlanetSize==
 
==SetPlanetSize==
<br>Descr.:    Sets the planet size of the target to SIZE.  This has no effect on non-Planet targets.
 
<br>XML format:
 
    <Effect::SetPlanetSize>SIZE</Effect::SetPlanetSize>
 
  
<br>Param Types:
+
SetPlanetSize size = SIZE
<br>SIZE PlanetSize-expression
+
  
 +
Param Type:
 +
SIZE PlanetSize
  
==AddOwner==
+
Sets the planet size of the target to SIZE.
<br>Descr.:    Adds empire EMPIRE_ID as an owner of the target. This has no effect if EMPIRE_ID was already an owner of the target object.
+
* Has no effect on non-Planet targets.
<br>XML format:
+
* Changing the size of a Asteroids or GasGiant planet will also change its type to Barren.
    <Effect::AddOwner>EMPIRE_ID</Effect::AddOwner>
+
* Changing size to Asteroids or GasGiant will also cause the type to change to Asteroids or GasGiant, respectively.
  
<br>Param Types:
+
==SetOwner==
<br>EMPIRE_ID int-expression
+
  
 +
SetOwner empire = EMPIRE
  
==RemoveOwner==
+
Param Type:
<br>Descr.:    Removes empire EMPIRE_ID as an owner of the target. This has no effect if EMPIRE_ID was not already an owner of the target object.
+
  EMPIRE int
<br>XML format:
+
    <Effect::RemoveOwner>EMPIRE_ID</Effect::RemoveOwner>
+
  
<br>Param Types:
+
Sets empire EMPIRE_ID as the owner of the target.
<br>EMPIRE_ID int-expression
+
* Has no effect if EMPIRE_ID was already the owner of the target object.
  
 +
==CreatePlanet==
 +
 +
CreatePlanet type = TYPE size = SIZE
 +
 +
Param Types:
 +
TYPE PlanetType
 +
SIZE PlanetSize
 +
 +
Creates a new planet at the location of the target object.  If the target object is not located in a system, nothing is done.  If there are no free orbit slots at the target object's system, nothing is done.
 +
 +
==CreateBuilding==
 +
 +
CreateBuilding name = NAME
 +
 +
Param Types:
 +
NAME string
 +
 +
Creates a new building at the location indicated by the target object.  If the target object is not a planet, nothing is done.
 +
 +
==CreateShip==
 +
 +
CreateShip
 +
    designname = "NAME"
 +
    empire = EMPIREID
 +
    species = "SPECIES"
 +
 +
ParamTypes
 +
NAME string_constant
 +
EMPIREID int_constant
 +
SPECIES string_constant
 +
 +
Creates a new shipat the location of the target object.  The design of the new ship is indicated by the NAME parameter, which looks up the design in premade_ship_designs.txt in the default folder.  EMPIREID is the id of the empire who should own the newly created ship, which is probably the id of something related to the source or target objects.  SPECIES is the name of the species which should crew the newly created ship, which can be something related to target or source objects, or an explicit species name.
  
 
==Destroy==
 
==Destroy==
<br>Descr.:    Destroys the target object.
 
<br>XML format:
 
    <Effect::Destroy/>
 
  
 +
Destroy
 +
 +
Destroys the target object.
 +
 +
* The Destroy effect will not destroy a System object, although any other objects in or outside a system can be destroyed.
 +
* Destroy effects are executed after all other effects.
 +
* Destroying a fleet will destroy its ships.
 +
* Destroying all the ships in a fleet will destroy the fleet.
 +
* Destroying a planet will destroy its buildings.
  
 
==AddSpecial==
 
==AddSpecial==
<br>Descr.:    Adds the Special with the name NAME to the target object.
 
<br>XML format:
 
    <Effect::AddSpecial>NAME</Effect::AddSpecial>
 
  
<br>Param Types:
+
AddSpecial name = "NAME"
<br>NAME string
+
  
 +
Param Type:
 +
NAME string_constant
 +
 +
Adds the Special with the name NAME to the target object.
 +
* Note that using a wrong NAME/a NAME for which no special is specified is possible but will lead to strange behaviours
 +
* You can retrieve the turn a Special was added using the SpecialAddedOnTurn complex variable
  
 
==RemoveSpecial==
 
==RemoveSpecial==
<br>Descr.:    Removes the Special with the name NAME to the target object.  This has no effect if no such Special was already attached to the target object.
 
<br>XML format:
 
    <Effect::RemoveSpecial>NAME</Effect::RemoveSpecial>
 
  
<br>Param Types:
+
RemoveSpecial name = "NAME"
<br>NAME string
+
  
 +
Param Type:
 +
NAME string_constant
 +
 +
Removes the Special with the name NAME to the target object.
 +
* Has no effect if no such Special was already attached to the target object.
 +
 +
==SetSpecialCapacity==
 +
 +
SetSpecialCapacity name = "NAME" capacity = NUMBER
 +
 +
Param Type:
 +
NAME string_constant
 +
NUMBER double (ValueRef)
 +
 +
Sets the capacity of Special with the name NAME to the given NUMBER.
 +
* Adds the Special if no such Special was already attached to the target object.
 +
* If such a Special was attached, this won't change the since turn value (queried by HasSpecialSinceTurn)
 +
* Object candidates can be filtered using the HasSpecialCapacity condition
 +
* The special's capacity value can be retrieved using the SpecialCapacity complex variable
  
 
==SetStarType==
 
==SetStarType==
<br>Descr.:    Sets the star type of the target to TYPE.  This has no effect on non-System targets.
 
<br>XML format:
 
    <Effect::SetStarType>TYPE</Effect::SetStarType>
 
  
<br>Param Types:
+
SetStarType type = TYPE
<br>TYPE StarType-expression
+
  
 +
Param Type:
 +
TYPE StarType
  
==SetAvailability==
+
Sets the star type of the target to TYPE.
<br>Descr.:    Sets the availability of tech TECH_NAME to empire EMPIRE_ID.  If GRANT_TECH is true, the tech is fully available, just as if it were researched normally; otherwise, only the items that the tech grants are made available.  Note that this means this Effect is intended also to be used to unlock buildings, ships, etc. The tech and/or its items are made available if AVAILABLE is true, or unavailable otherwise.
+
* Has no effect on non-System targets.
<br>XML format:
+
    <Effect::SetAvailability>
+
        <tech_name>TECH_NAME</tech_name>
+
        <empire_id>EMPIRE_ID</empire_id>
+
        <available>AVAILABLE</available>
+
        <grant_tech>GRANT_TECH</grant_tech>
+
    </Effect::SetAvailability>
+
  
<br>Param Types:
+
==MoveTo==
<br>TECH_NAME  string
+
<br>EMPIRE_ID  int-expression
+
<br>AVAILABLE bool
+
<br>GRANT_TECH bool
+
  
 +
MoveTo location = CONDITION
  
 +
Param Type:
 +
LOCATION Condition
  
 +
Moves the target object to the location of one of the objects matched by LOCATION
 +
* If no objects match the location condition, nothing is done.
 +
* If more than one object matches the location condition, one object is chosen by the condition
 +
* If the target object is a ship and the location object is a fleet or a ship (in a fleet) owned by the same empire, the ship is inserted into the fleet.
 +
* If the target object is a ship and the location is not a fleet into which the ship can be inserted, a new fleet is created for the ship a the new location.
 +
* If the target object is a ship and its location is the same system but not a different fleet, nothing is done and the ship is left in its original fleet.
 +
* If the target object is a fleet and its location is a fleet or ship outside a system, and a fleet is moved to or created at the target location, the fleet will be moving to the same system as the taget object fleet.
 +
* If the target object is a building and the location object is a planet or a building on a planet, the building is added to the planet.
 +
* If the target object is a building and the location is not a planet or on a planet, nothing is done.
 +
* If the target object is a planet and the location object is not a system or in a system, nothing is done.
 +
* If the target object is a planet and the location system has no empty orbit slots, nothing is done.
 +
* If the target object is a system, nothing is done.
 +
* Any target object moved to the location of a system will be inserted into that system.
  
==EffectGroup==
+
==Techs==
<br>Descr.:     Contains one or more Effects, a Condition which indicates the objects in the scope of the Effect(s), and a Condition which indicates whether or not the Effect(s) will be executed on the objects in scope during the current turnSince Conditions operate on sets of objects (usually all objects in the universe), the activation condition bears some explanationIt exists to allow an EffectsGroup to be activated or suppressed based on the source object only (the object to which the EffectsGroup is attached)It does this by considering the "universe" containing only the source object. If the source object meets the activation condition, the EffectsGroup will be active in the current turn.
+
 
<br>XML format:
+
GiveEmpireTech name = "NAME"
    <EffectGroup>
+
GiveEmpireTech name = "NAME" empire = EMPIRE
        <scope>SCOPE</scope>
+
 
        <activation>ACTIVATION</activation>
+
Param Type:
        <effects>
+
NAME string_constant
        EFFECT0
+
EMPIRE integer ID of empire (such as Target.Owner which is the default if this parameter is omitted).
        EFFECT1
+
 
        ...
+
GiveEmpireTech gives the indicated empire the indicated tech. After this, the result should be the same as if the empire had researched that tech.
        EFFENTN
+
 
        </effects>
+
 
    </EffectGroup>
+
SetEmpireTechProgress name = "NAME" progress = PROGRESS
 +
SetEmpireTechProgress name = "NAME" progress = PROGRESS empire = EMPIRE
 +
 
 +
Param Type:
 +
NAME string_constant
 +
PROGRESS double
 +
EMPIRE integer ID of empire
 +
 
 +
SetEmpireTechProgress sets the amount of research points (RP) the indicated empire has accumulated towards researching the indicated tech (limited to between 0 and the total RP cost of the tech).
 +
 
 +
==Victory==
 +
 
 +
  Victory reason = "REASON"
 +
 
 +
Param Type
 +
REASON string_constant
 +
 
 +
Victory causes the owner of the target object to win the game.  Losing human players (which is any player who has not won on the turn a player wins) are ejected from the game.  The string REASON is d_constantisplayed in a popup to all players, with the name of the winning empire inserted as the %1% parameter to the string.
 +
 
 +
==AddStarlanes and RemoveStarlanes==
 +
 
 +
AddStarlanes endpoint = CONDITION
 +
RemoveStarlanes endpoint = CONDITION
 +
 
 +
Param Type
 +
CONDITION condition
 +
 
 +
AddStarlanes adds starlanes between the target system and any system containing an object that matches CONDITIONRemoveStarlanes removes starlanes between the target system and any system containing an object that matches CONDITIONS.  Adding a starlanes where one already exists, or removing a starlane wher none exists does nothing.
 +
 
 +
==MoveTo==
 +
 
 +
MoveTo destination = CONDITION
 +
 
 +
Param Type
 +
CONDITION condition
 +
 
 +
MoveTo moves the target object to the location of the / one of the objects matched by the CONDITION parameter.
 +
 
 +
==SetDestination==
 +
 
 +
SetDestination destination = CONDITION
 +
 
 +
Param Type
 +
CONDITION condition
 +
 
 +
SetDestination sets the travel route of the target fleet to be the shortest path for the target to move to an object that matches the CONDITION parameter.  If multiple objects match CONDITION, one is chosen.  If the target fleet can't move to the chosen object, nothing is doneThe shortest path for the object may depend on the empire that owns it (if any).
 +
 
 +
==SetAggression==
 +
 
 +
SetAggressive
 +
SetPassive
 +
 
 +
SetAggressive marks a fleet as aggressive, meaning it will block enemy supply, and engage any enemy fleets or planets in its system. SetPassive marks a fleet as passive, meaning it will not block supply or initiate combat. Remaining passive may be useful for staying hidden in a system (if stealthy) or to make non-aggressive monster types not attack player fleets.
 +
 
 +
==SetSpecies==
 +
 
 +
SetSpecies name = "NAME"
 +
 
 +
Param Type
 +
NAME string_constant
 +
 
 +
SetSpecies sets the species of the target ship or planet to the indicated species NAME.
 +
 
 +
==SetVisibility==
 +
 
 +
The following details for this Effect correspond to the modifications currently proposed in [https://github.com/freeorion/freeorion/pull/1764 PR 1764], please note some constraints/complications regarding priority and timing of evaluation as discussed in the PR.
 +
 
 +
SetVisibility {affilition = AFFILIATION} {empire = EMPIRE} visibility = VISIBILITY {condition = CONDITION}
 +
 
 +
Param Type
 +
AFFILIATION optionally specifies an empire affiliation. Defaults to TheEmpire if an empire ID is specified, or AnyEmpire if no empire ID is specified.
 +
EMPIRE optionally specifies an Int ValueRef specifying an empire ID, which is used with the affiliation to determine which empire's visibility/ies to set. Defaults to an invalid empire ID if none is specified, which will work with affiliations that aren't relative to a particular empire.
 +
VALUEREF A Visibility type ValueRef, can include expressions like max(Value, V) where Value refers to the current visibility
 +
CONDITION optionally condition specifies the object(s) whose visibility is to be set. If no condition is specified, the effect target object's visibility is set.
 +
 
 +
==Effect Evaluation & Application Ordering==
 +
 
 +
Effects are evaluated and then applied while processing a FreeOrion turn. When this happens, <i>all</i> EffectsGroups' activation and scope conditions are evaluated before <i>any</i> effects are applied.
 +
 
 +
The order of effects' application is determined primarily by their specified Priority (beginning at 0).  
 +
 
 +
For EffectsGroups sharing the same Priority number their secondary ordering is determined by their source/cause, as follows: effects from Species, then effects from Specials, then effects from Techs, then effects from Buildings, then effects from Ship Hulls, then effects from Ship Parts.
 +
The order of execution of Effects within these groups is deterministic, though not controllable. 
 +
 
 +
Multiple effects scripted into the same item will be evaluated in the order in which they appear.
  
<br>Param Types:
+
[[Category:Scripting]]
<br>SCOPE      Condition
+
<br>ACTIVATION Condition
+
<br>EFFECTX    Effect
+

Revision as of 23:23, 29 September 2019

This page augments the FOCS Scripting Tutorial (which should be reviewed first) and describes in more detail the scripting language used to describe much of the content of FreeOrion. This language is sometimes referred to as the FreeOrion Content Script, or "FOCS". Scripted content includes scripted descriptions of technology, buildings, and specials. These content files are text files, but some of them include special characters and therefor when editing them a somewhat more advanced editor is necessary. For example, on Windows, the Notepad and Wordpad editors can cause trouble, but the third party NotePad++ editor should be fine. An added benefit of using NotePad++ is that one of our contributors has made an add-on to help with the FOCS syntax.

Contents

Content Files

FreeOrion content is described in content files located in the /default subdirectory of the main FreeOrion game directory (typically 'C:\Freeorion').

Directory                | Contents
--------------------+--------------------------------------
techs               | Tech Categories and Technologies
buildings           | Buildings
specials            | Specials
ship_hulls          | Ship Hulls
ship_parts          | Ship Parts
species             | Species
ship_designs        | Ship Designs
monster_designs     | ShipDesigns to use as space monsters

The files in these directories contain descriptions of individual entries of their respective contents. buildings/ contains files with "BuildingType" descriptions (see below). specials/ contains "Special" descriptions. techs/ contains tech category and tech descriptions. When there are multiple entries in a single file, the ordering of entries in the files do not matter. Files can be organized into sub-directories as needed, for example ship_parts might contain a directory for weapon entries.

The primary building blocks used to specify the above types of FreeOrion content are ValueRefs (value references), Conditions, and EffectsGroups (which contain Effects and Conditions). Effects change the game state and thereby give buildings, techs and specials their in-game purpose. Conditions act to filter a starting set of objects to a smaller set (which might sometimes wind up being one or none). In EffectsGroups Conditions determine if (the activation condition) and on what (the scope condition) effects act. Conditions also have a few other uses, such as determining where buildings or ship parts or hulls can be produced, and where species focus settings can be used; they are also used within some of the more advanced ValueRefs. ValueRefs provide values used by the other portions of the script. Sometimes that might be a simple constant, like three, which the scripter would simply write as "3". Other times that might be a dynamic value such as the current game turn number, scripted as "CurrentTurn". In other cases that might be something much more complex, such as the number of monsters within two starlane jumps of a given system; the syntax for such value references is described farther below.

Scripting Format

In FOCS, whitespace (spaces, tabs, and line endings) is only for the visual clarity of the script, and capitalization is ignored for everything outside of quotes.

Words in quotes, eg. "NAME" are case-sensitive names of scripted content items such as techs, buildings, or specials. The names of the items are defined in their description by their line:

name = "NAME"

These items may be referred to in other items' descriptions by "NAME". This might typically be done when unlocking a building with a tech, or adding or checking for the presence of a special to or on an object.

Comments may be added to files using c/c++-style comment blocks. Anything in such blocks will be ignored when parsing the content files. Anything after "/*" will be ignored until the next occurrence of "*/" (even if it occurs several lines later), and anything on a line after "//" will be ignored.

In the FOCS descriptions below, the fixed portion of the FOCS specifications are in lower case or MixedCase; things written in ALLCAPS are placeholders for scripted subcontent. That type of any such piece of scripted subcontent below is specified either as a Condition, an Effect, an EffectsGroup, a string, an int (integer), or a double (a "real" number such as 2.4). In many cases, any such string, int or double can be provided either as a simple constant or as a more complicated scripted ValueRef. In any situations where a plain constant is required (but not a ValueRef), we endeavor to specify those values as string_constant, int_constant and double_constant.

Specification Components

There are a number of specification components that are used by multiple different content types, and some that are particular to a specific kind of content. The more common components are described first below.

ValueRef

A ValueRef is a type of FOCS construction which gets evaluated to provide a value, and which may reference various objects and which may have conditional aspects; their structure is described in more detail below. The most common types are string (text) ValueRefs (which generally evaluate to the name of something, such as a species name "SP_HUMAN"), integer ValueRefs (which evaluate to an integer, such as 42), and double ValueRefs (which evaluate to a "double", a programming term for a "real" number, i.e., it may have a decimal point, such as 3.5). Some ValueRefs may evaluate to a kind of FO-specific value such as a PlanetEnvironment or PlanetSize; it may be helpful to think of these as a string or number for which a limited group of values are acceptable.

Condition

A FOCS Condition acts as a kind of filter on objects in the FO universe. Conditions start with a set of objects, and return subsets of this set according to whether the objects meet the criteria of the condition. Just what that starting set of objects is depends on where the Condition is used, and is discussed more below. There are many different types of FOCS Conditions, and their structures are also explained further below.

Name Specification

  name = "NAME"

Param Type:

  NAME    string_constant

When displayed to a user, the name will normally be used as a key/label for which a value will be looked up in a stringtable (to enable translation); the raw FOCS name strings themselves are by convention written in ALL_CAPS_WITH_UNDERSCORES. They should generally be unique to that particular piece of content-- even if both pieces of content might be suitably translated to the same name in English, that might not be the case for other languages. As examples, the name of the first refinement of the first tier of short range weapon parts (which is currently called "Mass Driver 1" in English) is specified as

  name = "SR_WEAPON_1_1"

Description Specification

  description = "DESCRIPTION"

Param Type:

  DESCRIPTION    string_constant

As with the name, the description is normally used as a key/label to be looked up in a stringtable, an example (specifically, for Mass Driver 1), would be

  description = "SR_WEAPON_1_1_DESC"

BuildCost Specification

   buildcost = BUILDCOST

Param Type:

  BUILDCOST    double (ValueRef)

BuildTime Specification

   buildtime = BUILDTIME

Param Type:

  BUILDTIME    integer (ValueRef)


Location Specification

   location = LOCATION

Param Type:

  LOCATION    Condition

In general, the Location specification constrains where/when the respective content can be built, or in the case of a Focus, be used. More detail is provided below for the various particular content types that use a Location specification. For things that can be built, if the item is under construction and the Location condition ceases to evaluate to True, then progress on the construction halts until such time as the Location condition again becomes True.

EnqueueLocation Specification

   EnqueueLocation = ENQUEUELOCATION

Param Type:

  ENQUEUELOCATION    Condition

The EnqueueLocation condition sets the constraining condition under which the respective content (or a ship design using the content) may be placed on the Build Queue. If not explicitly specified, the EnqueueLocation condition will default to be the same as the Location condition. The EnqueueLocation is only evaluated at the time of placing the item on the queue; it need not remain true (and so, for example, may prohibit that the subject content is already enqueued at that location).

EffectsGroup Specification

EffectsGroup

  description = "DESCRIPTION" [optional -- may be left out]
  scope = CONDITION
  activation = CONDITION [optional -- may be left out]
  stackinggroup = "STACKINGGROUP" [optional -- may be left out]
  accountinglabel = "ACCOUNTINGLABEL" [optional -- may be left out]
  priority = PRIORITY [optional -- omission defaults to 100]
  effects = {EFFECT|[
      EFFECT
      EFFECT
      EFFECT
  ]}

Param Types:

DESCRIPTION      string_constant
SCOPE            Condition
ACTIVATION       Condition
STACKINGGROUP    string_constant
ACCOUNTINGLABEL  string_constant
PRIORITY         int_constant
EFFECT           Effect

Describes the mechanism by which game content such as Techs, Buildings or Specials interacts with and alters the game state.

  • Consists primarily of:
    • One or more Effects
    • A "SCOPE" condition which indicates the objects in the scope of the Effect(s). The scope objects are those that are acted on by the effects in the effects group, i.e., what the targets of the effects are.
    • An "ACTIVATION" condition (assessed specifically against the Source) which indicates whether or not the Effect(s) will be executed on the objects in scope during the current turn. The default if the activation clause is left out, is to be on/active.

For scope conditions, the entire game universe (or rather, all objects in it) are the initial set. For activation conditions, the initial set is the source object of the effects group. This allows an EffectsGroup to be activated or suppressed based on the source object only (the object to which the EffectsGroup is attached). If the source object meets the activation condition, the EffectsGroup will be active in the current turn.

  • The translated stringtable entry in "DESCRIPTION" is amended to the source objects description (at the time of this writing, only for specials and species).
  • An EffectsGroup's stacking group determines when it should affect a specific target; if that target has already been affected by another EffectsGroup with the same stacking group, all EffectsGroups after the first have no effect on the target that turn. For instance, if an EffectsGroup is in a stacking group "WONDER_FARM_BONUS", and executes on a target object, no other EffectsGroup in the "WONDER_FARM_BONUS" stacking group will affect it on that turn.
  • The presence of "ACCOUNTINGLABEL" being specified indicates this effect should be accounted for with the supplied stringtable entry. This is typically used in providing feedback to the player, accounting for this EffectsGroup among the totals of effected meters.
  • "PRIORITY" is the order of the EffectsGroup processing. Processing starts from 0, with all EffectsGroups of the same priority executing before any of a later priority. This value must be an int and is specifically NOT a ValueRef ('1 + 1' is not allowed). Information on reference priority values, and the relative priorities of the set of population effects, can be found at our EffectsGroup Priority Standard Values page.

Content Specifications

Common Params

Where noted, content specifications include these common parameters:

  buildcost = BUILDCOST
  buildtime = BUILDTIME               [optional -- may be left out]
  {Unproducable | Producable}         [optional -- omission defaults to Producable]
  tags = [ "TAG" "TAG" ... ]          [optional -- may be left out]
  location = LOCATION                 [optional -- omission defaults to All]
  EnqueueLocation = ENQUEUE           [optional -- omission defaults to All]
  Consumption = CONSUMPTION           [optional -- may be left out]
  effectsgroups = {EFFECTSGROUP|[     [optional -- may be left out]
       EFFECTSGROUP
       EFFECTSGROUP
       ...
  ]}

Param Types:

BUILDCOST         double
BUILDTIME         int
TAG               string_constant
LOCATION          Condition
ENQUEUE           Condition
CONSUMPTION       Consumption
EFFECTSGROUP      EffectsGroup

Special Specification

Special

  name = "NAME"
  description = "DESCRIPTION"
  stealth = STEALTH                   [optional -- may be left out]
  spawnrate = SPAWNRATE
  spawnlimit = SPAWNLIMIT             [optional -- may be left out]
  capacity = CAPACITY                 [optional -- may be left out]
  location = LOCATION                 [optional -- may be left out]
  effectsgroups = {EFFECTSGROUP|[     [optional -- may be left out]
       EFFECTSGROUP
       EFFECTSGROUP
       ...
  ]}
  graphic = GRAPHICFILENAME

Param Types:

NAME               string_constant
DESCRIPTION        string_constant
STEALTH            double
SPAWNRATE          double
SPAWNLIMIT         int
CAPACITY           double
LOCATION           Condition
EFFECTSGROUP       EffectsGroup
GRAPHICFILENAME    string_constant

A specification for a Special, which is a definition of a predefined set of EffectsGroups with a unique name, which may be attached to an object in-game.

  • Specials used in the game are stored within specials.
    • specials contains general specials that may be applied to objects using the AddSpecial effect.

BuildingType Specification

BuildingType

   name = "NAME"
   description = "DESCRIPTION"
   captureresult = CAPTURERESULT      [optional -- omission defaults to capture]
   (common params)
   icon = "ICONFILENAME"

Param Types:

NAME             string_constant
DESCRIPTION      string_constant
CAPTURERESULT    CaptureResult
ICONFILENAME     string_constant

A specification for a building of a certain type.

  • BuildingTypes must each have a unique name.
  • BuildingTypes used in the game are stored within buildings.
  • The noteTemplate:CN about Special name and description text also applies to BuildingTypes.
  • ICONFILENAME should be relative to the art directory. So it should appear in the form "foo/bar.png" instead of "default/data/art/foo/bar.png".

Item Specification

Item type = TYPE name = "NAME"

Param Types:

TYPE             UnlockableItemType
NAME             string_constant

A specification for an unlockable item.

  • Item definitions appear within Tech definitions.
  • type defines the kind of thing to be unlocked, e.g. a Building, ShipHull, ShipPart, or Tech.
  • name is the name of the specific item of that kind to be unlocked, e.g. a "WonderFarm" building or a "MegaLaser" ship part.
  • The noteTemplate:CN about Special and BuildingType name and description text also applies to Items.

Tech Category

TechCategory name = "NAME" graphic = "GRAPHIC" colour = COLOUR

Param Type:

NAME string
GRAPHIC string_constant
COLOUR colour

Specifies a technology category.

  • Techs are displayed by category in the UI
  • A category must be defined in Categories.inf before a tech in that category may be defined.

Colour Specification

(RED, GREEN, BLUE, ALPHA)

Param Type:

RED    int_constant
GREEN  int_constant
BLUE   int_constant
ALPHA  int_constant

Specifies a colour.

  • Brackets must surround the colour component numbers, which must also be separated by commas.
  • Colour components are specified in the range [0, 255]
  • Example: in a TechCategory definition, one might write:
colour = (116, 225, 107, 255)

FocusType Specification

FocusType
    name = "NAME"
    description = "DESCRIPTION"
    location = "CONDITION"
    graphic = "GRAPHICFILENAME"

Specifies a focus setting for a planet.

  • Within each species, each FocusType must have a unique name. Two different species may have (the same or different) FocusTypes with the same name, however.
  • The location condition determines which planets on which the FocusType can be used.
  • The graphic determines the icon used to represent the FocusType in the UI.

Tech Specification

Tech
   name = "NAME"
   description = "DESCRIPTION"
   short_description = "SHORT_DESCRIPTION"
   category = "CATEGORY"
   researchcost = RESEARCHCOST
   researchturns = RESEARCHTURNS
   {Unrsearchable | Researchable}              [optional -- omission defaults to Researchable]
   Tags = [ "TAG" "TAG" ... ]                  [optional -- may be left out]
   prerequisites = {"NAME"|[                   [optional -- may be left out]
       "NAME"
       "NAME"
       ...
   ]}
   unlock = {ITEM|[                            [optional -- may be left out]
       ITEM
       ITEM
       ...
   ]}
   effectsgroups = {EFFECTSGROUP|[             [optional -- may be left out]
        EFFECTSGROUP
        EFFECTSGROUP
        EFFECTSGROUP
   ]}
   graphic = "GRAPHICFILENAME"

Param Types:

NAME               string_constant
DESCRIPTION        string_constant
SHORT_DESCRIPTION  string_constant
CATEGORY           string_constant
RESEARCHCOST       double
RESEARCHTURNS      int
TAG                string_constant
NAME               string_constant
ITEM               Item
EFFECTSGROUP       EffectsGroup

A specification for a technology.

  • Techs must each have a unique name.
  • Each tech may optionally have one or more EffectsGroups associated with it.
    • Tech EffectsGroups are use as their source object the capitol planet of the empire that researches the tech.
  • All of a tech's prerequisites must be known before a Tech can be researched.
  • The noteTemplate:CN about Special and BuildingType name and description text also applies to Tech names, descriptions, and category names.
  • GRAPHICFILENAME should be relative to the art directory. So it should appear in the form "foo/bar.png" instead of "default/data/art/foo/bar.png".
  • Techs used in the game are stored within techs. These files include examples of theory techs with no effects or unlocked items, as well as applications that unlock buildings or which have effects of their own.
  • The Source for all EffectsGroups in a Tech is the Empire Source (generally the Capital), as discussed in the Source section.

Ship Hull Specification

Hull
   name = "NAME"
   description = "DESCRIPTION"
   speed = BATTLESPEED
   fuel = FUEL
   stealth = STEALTH
   structure = STRUCTURE
   slots = [                                       [optional -- may be left out]
       Slot type = SLOTTYPE position = (X, Y)
       ...
   ]
   (common params)
   icon = "ICONFILENAME"
   graphic = "GRAPHICFILENAME"

Param Types:

NAME               string_constant
DESCRIPTION        string_constant
BATTLESPEED        double
FUEL               double
STEALTH            double
STRUCTURE          double
SLOTTYPE           ShipSlotType
X, Y               double, double
ICONFILENAME       string_constant
GRAPHICFILENAME    string_constant

A specification for a ship hull.

  • Hulls must each have a unique name.
  • Each hull may optionally have one or more EffectsGroups associated with it.
    • Hull EffectsGroups are use as their source object the ship in which the hull is located.
  • ShipSlotTypes are currently: External, Internal, and Core. These can be combined within brackets and separated by a pipe ( [EXTERNAL|INTERNAL] )
  • X, Y are the coordinates to place the slot (overlaying the hull) in the ship design window.
  • The noteTemplate:CN about Special and BuildingType name and description text also applies to Hull names and descriptions.
  • ICONFILENAME and GRAPHICFILENAME should be relative to the art directory. So it should appear in the form "foo/bar.png" instead of "default/data/art/foo/bar.png".
  • Hulls used in the game are stored in ship_hulls.

Ship Part Specification

Part
   name = "NAME"
   description = "DESCRIPTION"
   class = CLASS
   { capacity | damage } = PRIMARY    [optional -- defaults to 0.0 -- see ShipPartClass]
   { damage | shots } = SECONDARY     [optional -- defaults to 1.0 -- see ShipPartClass]
   NoDefaultCapacityEffect            [optional --  omission leaves the normal default capacity]
   mountableSlotTypes = {SLOTTYPE|[
        SLOTTYPE
        ...
   ]}
   (common params)
   icon = "ICONFILENAME"

Param Types:

NAME               string_constant
DESCRIPTION        string_constant
CLASS              ShipPartClass
PRIMARY            double
SECONDARY          double
SLOTTYPE           ShipSlotType
ICONFILENAME       string_constant


A specification for a ship part.

  • Parts must each have a unique name.
  • Each part may optionally have one or more EffectsGroups associated with it.
    • Part EffectsGroups are use as their source object the ship in which the part is located.
  • The noteTemplate:CN about Special and BuildingType name and description text also applies to Part names and descriptions.
  • ICONFILENAME should be relative to the art directory. So it should appear in the form "foo/bar.png" instead of "default/data/art/foo/bar.png".
  • Parts used in the game are stored in ship_parts].

Ship Part Class, Stats and PartMeters

Each class of ship parts defines a primary stat and may also define a secondary stat. Some have associated ship part meters (One meter value per ship object and ship part meter type). Possible ship part meter types are: Capacity, MaxCapacity, SecondaryStat, and MaxSecondaryStat.

Most parts classes (Armour, Bombard, Detection, Fuel, General, Shield, Speed, Stealth) only have a primary stat of capacity an no associated meter.

Troops and Colony part types have a primary capacity stat with associated Capacity meter.

FighterHangar has a primary stat of capacity and a secondary of damage (number of boats, damage of each boat's attack) and the associated MaxCapacity and MaxSecondaryStat meters.

Direct fire weapons (which only contains ShortRange currently) have a primary stat of damage and a secondary of shots.
shots determines how many times the weapon will fire each combat round.

LaunchBay parts have a capacity stat with associated (Max)Capacity meters which specifies how many space boats may launch per combat turn.

The meter value for a ship can be accessed using the ShipPartMeter part = "PART_NAME" meter = METER_TYPE object = SHIP_ID double complex variable. See above for which meters exist for which part class. Also note you can use Value(ShipPartMeter) to get the immediate/non-initial value. Defaults to 0.0

In the source code, the ship meters and ship part meters are defined in the Ship::Ship constructor in universe/Ship.cpp

Species Specification

Species
   name = "NAME"
   description = "DESCRIPTION"
   gameplay_description = "GAMEPLAY_DESCRIPTION"
   Playable                                      [optional -- defaults to not playable]
   Native                                        [optional -- defaults to not native]
   CanProduceShips                               [optional -- defaults to cannot produce ships]
   CanColonize                                   [optional -- defaults to cannot colonize]
   tags = ["TAG" "TAG" ...]                      [optional]
   foci = {FOCUSTYPE|[                           [optional -- may be left out]
       FOCUSTYPE
       ...
   ]}
   preferredfocus = "FOCUS"                      [optional]
   effectsgroups = {EFFECTSGROUP|[               [optional -- may be left out]
        EFFECTSGROUP
        EFFECTSGROUP
        ...
   ]}
   environments = {PLANETTYPEENVIRONMENT         [optional -- may be left out]
       PLANETTYPEENVIRONMENT
       PLANETTYPEENVIRONMENT
       ...
   ]}
   graphic = "GRAPHICFILENAME"

Param Types:

NAME                   string_constant
DESCRIPTION            string_constant
GAMEPLAY_DESCRIPTION   string_constant
TAG                    string_constant
FOCUSTYPE              FocusType
FOCUS                  string_constant
EFFECTSGROUP           EffectsGroup
PLANETTYPEENVIRONMENT  (see below)
GRAPHICFILENAME        string_constant
  • Species must have a unique name.
  • PLANETTYPEENVIRONMENT has format:
type = PLANETTYPE environment = ENVIRONMENT

with param types:

PLANETTYPE         PlanetType
ENVIRONMENT        PlanetEnvironment

ShipDesign Specification

ShipDesign
   name = "NAME"
   description = "DESCRIPTION"
   NoStringTableLookup               [optional -- omission leaves default behavior]
   hull = "HULLTYPE"
   parts = [                         [see note below]
       "PARTTYPE"                    
       "PARTTYPE"
       ...
   ]
   icon = "ICONFILENAME"
   model = "MODELNAME"

Param Types:

NAME                string_constant
DESCRIPTION         string_constant
HULLTYPE            ShipHullType
PARTTYPE            string_constant
ICONFILENAME        string_constant
MODELNAME           string_constant
  • ShipDesign must have a unique name
  • PARTTYPE corresponds to the same ordered entry for each slot in HULLTYPE.
    • There must be the same number of PARTTYPEs as there are slots, but the PARTTYPE may be left empty ( "" ).
    • PARTTYPE must be compatible with the ShipSlotType for that slot.
  • ICONFILENAME and MODELNAME should be relative to the art directory.

Types and Expressions (ValueRefs)

In the Conditions and Effects below, there are parameters that specify details about how the condition or effect functions. These parameters can be specified as a constant number (eg. 5) or value (Blue), or can be variables that depend on the gamestate. Variables may refer to the Source, Target, RootCandidate or LocalCandidate objects (see below), a few independent values such as the number of the current game turn, or may refer to statistics about the gamestate that are calculated from multiple objects.

Source, Target, RootCandidate, LocalCandidate

ValueRefs, Conditions and Effects are evaluated in light of an automatically generated Scripting Context, which specifies one or more of a Source, Target, RootCandidate, and LocalCandidate. The way these get automatically generated depends on what content type is being evaluated.

For an Effect, the Source object is the object to which the Effect is attached. For example, a building might have an effect that increases a planet's industry meter. When defining that building's effects, the building itself would be the Source object. Regarding using "Source" as a Condition, as is common when specifying a scope, see the Conditions Section below.

The Target object of an Effect is the object that the Effect is modifying. In an effect that modifies a planet's industry meter, the planet would be the Target object.

The objects being tested by Conditions are candidates, and for reference within the scripts these are broadly divided into two types relating to the potentially multi-tiered nature of Conditions. Consider the following EffectsGroup scope condition:

 scope = WithinDistance distance = 5 condition = And [
   Planet
   OwnedBy TheEmpire RootCandidate.Owner
   Construction low = 0 high = LocalCandidate.TargetConstruction / 2
 ]

Here there are two sets of objects being matched: 1) The objects actually being matched for the scope. These are objects within distance 5 of an object matched by the subcondition. 2) The objects matched by the subcondition, which are used to evaluate the outer condition. These are planets that are owned by the same empire that owns the object matched in the outer condition, and that have less than half their own target construction.

RootCandidate refers to the object being matched in the outer-most condition - WithinDistance in this case. This gives a way to refer to the object actually being matched by a big multi-part condition from one of the inner condition definitions, where the object being matched by a subcondition is likely not the same object being matched by the outer condition.

LocalCandidate refers to the object being matched in whatever condition it is directly in - the Construction meter condition in this case. This gives a way to refer to the object being matched by the current condition, regardless of what other conditions are matching outside or inside the current condition.

The RootCandidate and LocalCandidate may be used with the same types of variable references as for Source and Target.

For the EffectGroups in Techs, the Location specification, BuildTime value and BuildCost value for content such as a BuildingType, ShipHull or ShipPart, the context Source is the EmpireSource for the empire currently under consideration; this is its Capital planet if it has one, otherwise some other object owned by the empire. The Target in this context is the potential production location (planet) for which the Location, BuildTime or BuildCost is being evaluated.

For the Location specification for Specials, Source and Target are not set, but the LocalCandidate and RootCandidate references may be used.

For EmpireStatistic ValueRefs, the scripting context only has a Source, which is the EmpireSource mentioned above.

Free/Independent Variables

There are some variables that may be used without referring directly to the Source, Target or candidate objects. The current free variables that may be referenced are those specifying the galaxy setup conditions, and one which provides the current game turn. These currently all provide an integer result. For galaxy setup variables, their underlying type is generally a specialized enumeration which for this purpose gets mapped to an integer corresponding to the order they get listed in the GalaxySetup screen. For example, most galaxy setup variables work with range [None, Low, Medium, High], which gets mapped to [0, 1, 2, 3]. (Many of those variables drop the None value, and so have a range of 1-3.) Current Max AI Aggressions range from 0 to 5. The current list of free variables is:

Value                   (various, see below)
GalaxySeed              string
CurrentTurn             int
GalaxyAge               int
GalaxyMaxAIAggression   int
GalaxyMonsterFrequency  int
GalaxyNativeFrequency   int
GalaxyPlanetDensity     int
GalaxyShape             int
GalaxySize              int
GalaxySpecialFrequency  int
GalaxyStarlaneFrequency int
UniverseCentreX         double
UniverseCentreY         double

Complex Variables

These variables are for values which need more than one parameter. These need at least one extra parameter to distinguish the right value and can not directly be accessed from an object. Instead you typically pass also the object ID (e.g. Source.ID, Target.DesignID) as parameter.

PartsInShipDesign name = "PART_NAME" design = DESIGN_ID

Returns the count of ship parts with the part name PART_NAME which are part of the ship design with the id DESIGN_ID. Will return zero if no such design exists or no such parts exist in the design.

SpecialAddedOnTurn name = "SPECIAL_NAME" object = ID

Returns the turn in the Special with the name SPECIAL_NAME was attached to the object ID. Will return zero if no such object exists or no such special was attached to the object (Note: this should be changed to a maximum turn number so SpecialAddedOnTurn <= CurrentTurn will be false if no special was attached to the object).

SpecialCapacity name = "SPECIAL_NAME" object = ID

Returns the capacity of the Special with the name SPECIAL_NAME attached to the object ID. Will return zero if no such object exists or no such special was attached to the object.

ShipPartMeter part = "PART_NAME" meter = METER_TYPE object = SHIP_ID 
Value(ShipPartMeter part = "PART_NAME" meter = METER_TYPE object = SHIP_ID)

Returns the part meter value of a ship (as double). The meter value of the meter type METER_TYPE for the part with name PART_NAME of the ship with the id SHIP_ID.

Note you can use Value(ShipPartMeter) in effects to get the immediate/non-initial value. Will return 0.0 if the ship does not exist, the ship design does not have such a part, or the part class does not have this kind of meter associated.

Parameter Types:

METER_TYPE meter type enum - one of Capacity, MaxCapacity, SecondaryStat, or MaxSecondaryStat
*NAME string_constant
*ID int_constant - the object identifier

Object Attributes

Object attributes are variables that are properties of the Source, Target, LocalCandidate, or RootCandidate objects. In combination these are also called "complex variables".

Some of the attributes have changing values which are tracked and manipulated as a meter. Usually these attributes return the initial value of the meter (before effects are executed), but one can access the current value changed by other effects using a Value() expression, e.g. Value(Source.TargetResearch) will return the current value of the Source object's TargetResearch meter.

List

Here is a (currently incomplete) list of the attributes available (but not necessarily currently used in-game), and their types (more on types later):

      Age                 int            the number of turns since the object was created
      CreationTurn        int            the turn the object was created
      ID                  int +++
      Name                string
      LastTurnBattleHere  int            the last turn a battle was in the system or the system which contains this object
      NearestSystemID     int
      NumSpecials         int            the count of specials an object has
      ObjectType          UniverseObjectType +!  type of an object: Building, Field, Fleet, Planet, PopulationCenter, ProductionCenter, Ship, System
      Owner               int ++         the ID of the empire which owns this object
      OwnerName           string         the name of the object's owning empire
      OwnerLeastExpensiveEnqueuedTech    returns the object's owner's empire's least expensive enqueued technology
      PropagatedSupplyDistance  double   the object's system's propagated ??supply distance??
      PropagatedSupplyRange  double      the object's system's propagated ??supply range??
      Stealth             double  m      the stealth value meter of an object e.g. a ship or a planet
      SupplyingEmpire     int            ID of the empire which supplies the system which contains the object
      System              system ref     the system of the object's containing system
      SystemID            int
      X                   double         X-Position of an object on the map (e.g. a field, fleet, system..)
      Y                   double         Y-Position of an object on the map (e.g. a field, fleet, system..)
      Size                double m       Size: the size value meter of a field
      Speed               double  m      the starlane speed meter of a field (or ship) measured in AU distance
      NumStarlanes        int            the count of a system's starlanes
      NextOlderStarType
      NextYoungerStarType
      StarType            StarType +     type of a system's star
      Construction        double  m      construction value meter of a planet.
TargetConstruction        double tm      construction value target meter of a planet
DistanceFromOriginalType  double         distance of the current environment of a planet to the original environment type in steps (0,1,2,3, or 4)
      Focus               string         the name of a planet's focus
      HabitableSize       double         the habitable size of a planet - this depends on type of a planet and galaxy rule settings
      Happiness           double  m      happiness value meter of a population center (currently only planets)
TargetHappiness           double tm      happiness value target meter of a population center (currently only planets)
      Industry            double  m      industry value meter of a planet (not yet used for ships)
TargetIndustry            double tm      industry value target meter of a planet (not yet used for ships)
      LastTurnAttackedByShip  int        turn number
      LastTurnConquered
      Orbit               int            the orbit ID of a planet where it is orbiting the star - i think this is only used for displaying the planets
      PlanetSize          PlanetSize +   size of a planet compare with SizeAsDouble and HabitableSize
       ClockwiseNextPlanetType  PlanetType +
CounterClockwiseNextPlanetType  PlanetType +
          NextBetterPlanetType  PlanetType +   planet type with one step better environment for a planet's species
NextCloserToOriginalPlanetType  PlanetType +
                  OriginalType  PlanetType +
                    PlanetType  PlanetType +   the type of planet
      PlanetEnvironment   PlanetEnvironment +  the environmental property for the planet's species from good to hostile
      Population          double  m      population value meter of a population center (currently only planets)
TargetPopulation          double tm      population value target meter of a population center (currently only planets)
      Research            double  m      research value meter of a planet (not yet used for ships)
TargetResearch            double tm      research value target meter of a planet (not yet used for ships)
      RebelTroops         double  m      RebelTroops: not used yet
      SizeAsDouble        double         The size of a planet as a double value. Compare with PlanetSize, HabitableSize, and PlanetType
      Stockpile           double  m      imperial stockpile value meter of a planet
   MaxStockpile           double mm      imperial stockpile value max meter of a planet
      Supply              double  m      supply value meter of a planet
   MaxSupply              double mm      supply value max meter of a planet
      Trade               double  m      Trade: not used currently
TargetTrade               double tm      TargetTrade: not used currently
      Troops              double  m      troop count target meter of a planet (?? maybe the count of troops on a ship ??)
   MaxTroops              double mm      troop count max meter of a planet
      Defense             double  m      defense value meter of a planet
   MaxDefense             double mm      defense value max meter of a planet
   TurnsSinceFocusChange  int            number of turns since focus was last changed
      Detection           double  m      the detection range meter of a ship or a planet
      PreferredFocus      string         the preferred focus type of a ship's or a planet's species
      Shield              double  m      the shield value meter of a ship or a planet
   MaxShield              double mm      the max shield value meter of a ship or a planet
      Species             string         species' textual id of a ship's (or fighter's) crew or a planet's population 
      SpeciesID           int            species' numerical id of a ship's crew or a planet's population 
      ArrivedOnTurn       int
      DesignID            int ++++
      Fleet               fleet ref      the ship's containing fleet. Example usage: Target.Fleet.NumShips
      Fuel                double  m      the fuel meter of a ship measured in starlane hops 
   MaxFuel                double mm      the max fuel meter of a ship measured in starlane hops 
      Hull                string         the type name of a hull type as specified in FOCS
      LastTurnActiveInBattle  int
      LastTurnResupplied  int
      Speed               double  m      the starlane speed meter of a ship (or field) measured in AU distance
      Structure           double  m      the structure value meter of a ship
   MaxStructure           double mm      the max structure value meter of a ship
      ETA                 int            turn number
      FinalDestinationID  int            the id of a fleet's final destination system
      NextSystemID        int            the id of the system a fleet is heading to/passing next
      NumShips            int
      PreviousSystemID    int            the id of the system a fleet was coming from
      LaunchedFrom        int            the id of the carrier ship a fighter was launched from (only in combat)
      Species             string         species' textual id of a fighter's (or ship's) crew (or a planet's population) 
      BuildingType        string         the name of a building's type as specified in FOCS
      Planet              planet ref     the planet a building is located on. E.g. Source.Planet.ID
      PlanetID            int            the id of the planet a building or a ship is located
      ProducedByEmpireID  int            the id of the empire which produced a building or ship
      FleetID             int            the id of a fleet or the fleet a ship belongs to
      Attack              double         fleet damage, ship's total weapon damage, or fighter's damage
      NextTurnPopGrowth   double         NextTurnPopGrowth: not used currently


+ The valid values for these types are listed after the corresponding conditions below. These values may change however, so for the most up-to-date list, it may be necessary to consult the FreeOrion source code.
++ Owner will return -1 if there are no owners (such as for a roaming space monster or unexplored system)
+++ This is the unique integer ID used to identify an object internally within FreeOrion.
++++ This is the unique integer ID used to identify a ship design.
m This is tracked using a meter. There might be a connected target meter or max meter
mm This is tracked using a max meter.
tm This is tracked using a target meter.
! While the code distinguishes between ProdCenter and PopCenters there is currently no overlap it is always a Planet ~~The types returned by ObjectType have some overlap. For instance, a Planet is also a PopCenter and a ProdCenter. In this case, Planet is returned before PopCenter or ProdCenter, since if you see a Planet, you know it is a ProdCenter, but seeing a ProdCenter, you have no idea if it is a Planet or something else that produces goods or resources, for instance a mining outpost. This principle guides the order in which type is determined when ObjectType is used.~~

The reference for the attributes is the file universe/ValueRef.cpp

Value

As a special case, there is a utility variable available that is used like a free variable, but actually refers to what is being modified by an effect:

Value                 double, int, string, PlanetSize, PlanetType, StarType

The value of "Value" is the initial value (before the current effect acts) of whatever is being set. For example, in a SetStealth effect, "Value" would return the same as "Target.Stealth". For SetPlanetType, "Value" would return the same as "Target.PlanetType".

The type returned by "Value" depend on the type of effect in which it is used. For meter-setting effects Value will be a double. For SetPlanetSize, it will be a PlanetSize, and similarly for PlanetType, PlanetEnvironment, StarType. For setting a planet's species, Value will be a string.

Do not confuse this with the Value() expression, which is used to get the current value of a meter using a complex variable.

Statistics

Statistics are values calculated from a sampling of objects in the game universe, which may or may not include the Source and Target objects.

List

The available statistical calculations that can be performed on the property values of objects matching the sampling condition are:

If                 - Returns 1 if at least one object matches the selection condition, or 0 otherwise
Count              - Returns the number of objects that match the selection condition
UniqueCount        - Returns the number of unique values of the property are present among objects that match the selection condition
Sum                - Returns the sum of property values of objects that match the selection condition
Mean               - Returns the arithmetic mean of property values
RMS                - Returns the square root of the arithmetic mean of the squares of the property values
Mode               - Returns the most common property value
Max                - Returns the largest property value
Min                - Returns the smallest property value
Spread             - Returns the difference between the largest and smallest property values
STDEV              - Returns the standard deviation of the property values
Product            - Returns the product of multiplying all the property values together

Mode may be used for any type of parameter, including enumerated types like PlanetSize and double or int or string. The other statistic types may be used only for parameters that are int or double. If and Count may be used without specifying a property value.

Use

Constants

In item descriptions, parameter values such as LOW, HIGH, or NUMBER may be simple numbers, like 5 or 10, in which case all objects with the appropriate meter are treated the same by Turn.

Variables

Parameter values may also be defined in terms of attributes (or "properties") of the Source, RootCandidate, LocalCandidate or Target object. In these cases, different objects may be differently matched or not, if the property used differs between them.

Object attributes can be referenced on the source or target object, but not alone. So "Source.ID" and "Target.PlanetSize" are legal variables, but "PlanetEnvironment" in isolation is not.

Parameter values may also be defined in terms of the free variables mentioned above that are not associated with a particular object. In this case, the variable name is used without any object reference; for example, "CurrentTurn" returns the current game turn.

Parameter values for meter-altering effects may also refer to "Value" which is equivalent to referring to the meter of the target object that is being altered, depending which meter-setting effect is being used.

In addition, an object's containing object, if one exists, may be used in a variable. For instance, if the source is a planet, "Source.System.StarType" represents the star type of the source's system. Planet may also be used in a similar fashion, as in "Target.Planet.PlanetEnvironment".

Nonsensical combinations of Target, Source, Planet, System, and the above attributes are allowed, but will always return 0 for numeric values, and a special value representing an invalid value for enumerated type values. The special invalid value is guaranteed not to match the value of any actual object.

For example, if the source object is a System, Source.System.StarType will always return an invalid Star Type.

Similarly, Target.System.Industry makes no sense (since industry meters meters exist for Planets but not Systems), and so will return the double value 0.0.

Statistics

Parameter values may also be defined in terms of statistics calculated from the gamestate. A statistic returns a value based on the specified property, calculation and a condition to select objects in the game Universe.

In any place where a constant or variable could be specified, a statistic may be used instead. The format for a statistic calculation is:

Statistic STATISTIC_TYPE value = VALUE condition = SAMPLING_CONDITION

For example, to calculate the sum of all planets' populations,

Statistic Sum value = LocalCandidate.Population condition = Planet

The result would return a double value, which will be used just as if a constant like 42.4 had been specified, or a variable like Target.Population had been specified.

Types

The "double" type listed above, is a double-precision floating point number, which is more or less any real number in the range [-10^300, 10^300]. The "int" type is an integer number, which is basically any whole number in the range [-2*10^9, 2*10^9]. The other types are enumerated types, with specific values. Each such value has a string associated with it, for instance the first valid StarType is Blue.

In the Conditions and Effects below, certain parameters have types. It is illegal to provide a parameter of the wrong type, and it will result in a thrown exception (a purposeful crash of FreeOrion). There is one major exceptions to this. It is legal to provide a int value for any parameter of any type. This is mainly to support easy expression syntax, which is the next thing that needs to be addressed.

Instead of providing a singe variable or constant value (such as 3.14, 5, or STAR_BLUE), you can instead provide an arithmetic expression. Legal expressions may contain parentheses, +, -, *, / and ^ (for exponentiation). The - operator can be binary as in "3 - 4", or unary as in "-Source.MaxHealth". Whitespace (spaces, tabs, and newlines) is ignored. Expressions may be arbitrarily complex. The type of the entire expression must match the type of the parameter for which it is intended. For instance, it is illegal to supply "1 + 3.14" as a value for an int-type parameter, since 3.14 is not an int. As mentioned before, though, it is legal to supply "STAR_BLUE + 1" as a value for a StarType parameter, since integers are always ok.

Note that since arbitrarily complex expressions are allowed in Effects, and multiple Effects may affect a single target in a single turn, the order in which the Effects are applied to the target may matter. For instance, if Effect A sets the current industry meter to "Target.Industry + 20", and Effect B sets the current industry meter to "Target.Industry * 3", the answer could be X * 3 + 20 or (X + 20) * 3, depending on the order of execution. To minimize this, and in keeping with the guidelines for Effects in general, such Effects should have small magnitude, which will make the problem largely disappear. For instance, if "Target.Industry + 3" and "Target.Industry * 1.05" are used instead, the difference between X * 1.05 + 3 and (X + 3) * 1.05 is a negligible 0.15.

Note that some of the parameters in the Conditions and Effects below ask for a certain type, sometimes a type-expression. Those parameters that do not explicitly allow type-expressions cannot handle them.

Value

The Value parameter for a statistic can be practically any kind of ValueRef, including complex expressions. The one exception that comes to mind is that attempting to use a statistic as the Value for another statistic has had parsing problems which may not yet be fully resolved.

Conditions

The syntax {a|b|c} below indicates a choice of values, exactly one of which must be selected. The brackets and vertical lines are not legal to use themselves.

{a|[a b c ...]} indicates that a single item may be specified ( a ), or multiple items in a list ( [a b c ...] ).

"low = ", "high = ", etc., indicates an *optional* parameter name. All parameters must appear in the order indicated, so the names are not necessary to indicate which value is meant for which parameter. The name may be included, however (except for with the And, Not and Or conditions, which do not have or allow such parameter names).

General

All

Matches all objects.


Source

Matches the Source object.


Target

Matches the target object of an effect. This can be used within effect definitions, but not within scope or activation condition definitions, as when those conditions are evaluated, the target object hasn't yet been determined.


Turn low = LOW high = HIGH

Matches objects if the current game turn is greater than or equal to LOW and less than HIGH.


NumberOf number = NUMBER condition = CONDITION

Matches at most NUMBER objects that match CONDITION. If fewer than NUMBER objects match CONDITION, all such objects are matched. If more than NUMBER objects match CONDITION, NUMBER such objects are randomly selected and matched.

MinimumNumberOf number = NUMBER sortkey = SORTKEY condition = CONDITION
MaximumNumberOf number = NUMBER sortkey = SORTKEY condition = CONDITION
ModeNumberOf    number = NUMBER sortkey = SORTKEY condition = CONDITION

These variants of NumberOf take a SORTKEY argument which is used to sort the objects matching the CONDITION before the elements get selected. The SORTKEY is a double valueref (e.g. such as LocalCandidate.Happiness). MinimumNumberOf will select and match (up to) NUMBER objects which have the smallest SORTKEY value of all matching objects. MaximumNumberOf will select and match (up to) NUMBER objects which have the highest SORTKEY value of all matching objects. ModeNumberOf will select and match (up to) NUMBER objects which have the most frequent values of all matching objects' SORTKEY values (e.g. you could a match a number of planets with the most common defense meter value).


Number low = LOW high = HIGH condition = CONDITION

Matches all objects if the number of objects that match CONDITION is greater than or equal to LOW and less than HIGH. Objects matched may or may not themselves match CONDITION.


Random probability = PROB

Matches objects with a probability of PROB. That is, objects have a probability of PROB of being matched.

Type

Building
Ship
Fighter
Fleet
Planet
PopulationCenter
ProductionCenter
System 

Matches objects with the indicated type.

Building / Special

Building name = {"NAME" | ["NAME0" "NAME1" "NAME2" ...]}

Matches buildings with the indicated name(s). NAME is as indicated in a particular building description, by: name = "NAME" or name = ["NAME0" "NAME1" "NAME2"] (etc.)


HasSpecial name = "NAME"

Matches objects that have the indicated special.

Containing Associations

Contains condition = CONDITION

Matches objects that contain one or more objects that match the indicated CONDITION


ContainedBy condition = CONDITION

Matches objects that are contained by one or more objects that match the indicated CONDITION


Enqueued type = {Building | Ship} name = "NAME" empire = EMPIRE low = LOW high = HIGH
Enqueued type = Ship design = DESIGNID low = LOW
Enqueued type = {Building | Ship} empire = EMPIRE high = HIGH
Enqueued low = LOW

Matches objects where the empire with the indicated id EMPIRE (or any empires if none is specified) have within the indicated range (LOW to HIGH inclusive) of the indicated type of production item with the indicated name or design ID (NAME or DESIGN ID) and TYPE (Building or Ship). The count used to assess LOW and HIGH takes into account the element blocksize.

Planet / Star

Planet type = {TYPE|[TYPE0 TYPE1 TYPE2 ...]}

Matches objects that are or are contained by planets that have the indicated type.

Types are:

Swamp
Toxic
Inferno
Radiated
Barren
Tundra
Desert
Terran
Ocean
Gaia
Asteroids
GasGiant


Planet size = {SIZE|[SIZE0 SIZE1 SIZE2 ...]}

Matches objects that are or are contained by planets that are the indicated size.

Sizes are:

Tiny
Small
Medium
Large
Huge
Asteroids
GasGiant


Planet environment = {ENV|[ENV0 ENV1 ENV2 ...]}

Matches objects that are or are contained by planets that have the indicated environment.

Environments are:

Uninhabitable
Hostile
Poor
Adequate
Good


HomeWorld
    name = {SPECIES|[SPECIES0 SPECIES1 ...]}     [optional -- may be left out]

Matches planets that are homeworlds to playable species. If no species are specified, the homeworld of any species will be matched.

SPECIES the name of a species in the game, as defined in a species definition file


Capital

Matches planets that are capitols of an (any) empire. Use in combination with OwnedBy for a specific empire's homeworld.


Star type = {TYPE|[TYPE0 TYPE1 TYPE2 ...]}

Matches objects that are or are contained by systems that have the indicated star type.

Types are:

Blue
White
Yellow
Orange
Red
Neutron
BlackHole

Infrastructure / Focus

Focus focus = {FOCUS|[FOCUS0 FOCUS1 FOCUS2 ...]}

Matches planets that have the indicated focus or any of the indicated foci.

FOCUS or FOCUS# are strings. Each species may have a different set of foci available, but typical focus options include "FOCUS_GROWTH", "FOCUS_INDUSTRY", "FOCUS_LOGISTICS", "FOCUS_PROTECTION", "FOCUS_RESEARCH", and "FOCUS_STOCKPILE"

To check if a given focus (FOCUS_RESEARCH in the below example) is simply available at a planet (even if not actually selected), the following check can be used:

 And [
     Planet
     Location type=Focus name = LocalCandidate.Species name = "FOCUS_RESEARCH"
 ]

For reference the focus are defined in file default/scripting/species/common/focus.macros

MeterValue

TargetPopulation low = LOW high = HIGH
TargetIndustry low = LOW high = HIGH
TargetResearch low = LOW high = HIGH
TargetTrade low = LOW high = HIGH
TargetConstruction low = LOW high = HIGH
MaxFuel low = LOW high = HIGH
MaxShield low = LOW high = HIGH
MaxStructure low = LOW high = HIGH
MaxDefense low = LOW high = HIGH
Population low = LOW high = HIGH
Industry low = LOW high = HIGH
Research low = LOW high = HIGH
Trade low = LOW high = HIGH
Construction low = LOW high = HIGH
Fuel low = LOW high = HIGH
Shield low = LOW high = HIGH
Structure low = LOW high = HIGH
Defense low = LOW high = HIGH
Supply low = LOW high = HIGH
Stealth low = LOW high = HIGH
Detection low = LOW high = HIGH
Starlanespeed low = LOW high = HIGH
HasSpecialCapacity name = "SPECIAL_NAME" low = LOW high = HIGH
HasSpecialSinceTurn name = "SPECIAL_NAME" low = LOW high = HIGH

Matches objects with the appropriate meter values that are greater than or equal to LOW and less than or equal to HIGH. That is, LOW specifies the lowest allowed value of the meter, and HIGH specifies the highest allowed value. Either of the LOW and HIGH parameters may be omitted, in which case there is no limit on the meter value in that direction. For example, if only LOW is specified, there is no upper limit on the allowed meter value.

The HasSpecialCapacity uses the capacity meter of the special given as string name. The HasSpecialSinceTurn queries the turn a special was first set on an object.

Object Owner / Producer

OwnedBy affiliation = {EnemyOf|AllyOf|TheEmpire|AnyEmpire} [empire = EMPIRE]

Matches objects owned by (OwnedBy) an empire with the indicated affiliation to the indicated id EMPIRE. EMPIRE may be omitted with using AnyEmpire, which will match objects owned by any empire, regardless of what EMPIRE is specified (or not). Typically EMPIRE is specified as a function of an object, such as Source.Owner, however a constant integer such as 2 may also be specified.


OwnerFoodStockpile low = LOW high = HIGH
OwnerMineralStockpile low = LOW high = HIGH
OwnerTradeStockpile low = LOW high = HIGH

Matches objects with exactly one owner, whose owner's stockpile of the appropriate resource is greater than or equal to LOW and less than or equal to HIGH.


OwnerHasTech name = "NAME"

Matches objects with exactly one owner, whose owner has the tech NAME.

Note: This is useful for refinements of technologies, where a refinement tech is indicated by NAME in an effects group of the item being refined.


VisibleToEmpire empire = {EMPIRE|[EMPIRE0 EMPIRE1 EMPIRE2 ...]}

Matches objects that are visible to the indicated empire(s).


ProducedByEmpire empire = EMPIRE

Matches buildings or ships produced by the empire with id indicated by EMPIRE. Typically EMPIRE is specified as a function of an object, such as Source.Owner, however a constant integer such as 2 may also be specified. Note that ownership and who produced an object aren't necessary the same, particularly for buildings, which may be captured with planets from other empires.

Ship Design

Design name = "NAME"

Matches ships that have a design generated from the predefined designs in ship_designs/ or monster_designs/.

Design design = DESIGNID

Matches ships that have the specified ship design ID. Most likely this would be Source.DesignID

DesignHasHull name = "NAME"

Matches ships that have the indicated hull in their design.

DesignHasPart low = LOW high = HIGH name = "NAME"

Matches ships that have >= LOW and < HIGH of the part NAME in their design.

DesignHasPartClass low = LOW high = HIGH class = CLASS

Matches ships that have >= LOW and < HIGH of parts of the indicated PartClass in their design.

Armed

Matches ships that have weapons.

Monster

Matches space monsters.

Galaxy Map Position

WithinDistance distance = DISTANCE condition = CONDITION

Matches objects that are within the indicated Euclidean direct-line DISTANCE of any objects that matches CONDITION. The matched objects may or may not themselves match CONDITION.


WithinStarlaneJumps jumps = JUMPS condition = CONDITION

Matches objects that are within the indicated number of starlane jumps (crossings from one star to the next) of any objects that matches CONDITION. The matched objects may or may not themselves match CONDITION.


Stationary

Matches objects that are not moving. The only objects that move are fleets and ships. Objects are not stationary if they are going to move, so fleets ordered to move are not stationary, but fleets that arrive in a system are stationary on the turn after they arrive.

ResupplyableBy empire = EMPIRE

Matched objects should be in systems where the empire with id EMPIRE can provide fleet supply.

ResourceSupplyConnected empire = EMPIRE condition = CONDITION

Matched objects should be in systems connected by resource sharing lines for the empire with id EMPIRE to at least one object that matches the sub-condition CONDITION. Objects outside systems shouldn't be matched, regardless of whether they're on a starlane that is connected to an object that matched the sub-condition.

Conditional

Conditional conditions are variants of some kind of "if". The only conditional condition we have currently is OrderedAlternativesOf, in some cases one can use the If statistic in ValueRef statements to get conditional results.

The OrderedAlternativesOf provides the ability to conditionally match the objects of the first condition inside of it which matches at least one local candidate. An example from FT_HANGAR_1 (Note that COMBAT_TARGETS_VISIBLE_ENEMY has to be repeated inside each single tier condition)

    combatTargets = OrderedAlternativesOf [
        // Target Bombers and Heavy Bombers first
        And [
            [[COMBAT_TARGETS_VISIBLE_ENEMY]]
            Fighter
            Or [
               DesignHasPart name = "FT_HANGAR_3"
               DesignHasPart name = "FT_HANGAR_4"
            ]
        ]
        And [ [[COMBAT_TARGETS_VISIBLE_ENEMY]]  Fighter ]
        // if no fighters: target enemy ships
        And [ [[COMBAT_TARGETS_VISIBLE_ENEMY]]  [[COMBAT_TARGETS_NOT_DESTROYED_SHIP]] ]
    ]

Logical

Note: There are no optional "param =" indicators for And, Or, & Not.

And [CONDITION0 CONDITION1 CONDITION2 ...]
And [
 CONDITION0
 CONDITION1
 CONDITION2
]

Matches objects that match all of the indicated subconditions.


Or [CONDITION0 CONDITION1 CONDITION2 ...]
Or [
 CONDITION0
 CONDITION1
 CONDITION2
]

Matches objects that match at least one, or more, of the indicated subconditions.


Not CONDITION

Matches objects that do not match CONDITION.

Notes

Implicit ContainedBy

Some Conditions that match an object's containing object will be returned, even though they at first seem to be nonsensical. For instance, if the target object is a Planet, StarType will match the type of the System in which the target is located. This means that StarType will match all objects in all Systems with the given star type, and the Systems themselves. Similarly, all objects on all Planets (and the Planets themselves) that match a PlanetType, PlanetSize, or PlanetEnvironment will be matched. This has an important implication; if you want all Systems with blue stars, you should use

And [
  Star type = Blue
  System
]

If you want all Ships in Systems with blue stars, you should use:

And [ Ship Star type = Blue ]

And & Or Efficiency

The And and Or Conditions are designed to work as efficiently as possible, by only searching the objects that have not already been matched. So it is always best to put the most restrictive Condition first in an And Condition's list of subconditions.

For instance, if "Star type = Blue" matches about 1000 objects,

And [ Source Star type = Blue ]

will be about 1000 times faster than

And [ Star type = Blue Source ]

This is because the former only has to look at the match from Source to see if it also is (or is inside of) a blue-starred System, whereas that latter has to look through the 1000 matches of objects that are or are in blue-starred systems, to see if any of them also matches Source.

Effects

SetMeter

# on planets
SetTargetConstruction value = VALUE # not really in use
SetTargetHappiness value = VALUE
SetTargetIndustry value = VALUE
SetTargetPopulation value = VALUE
SetTargetResearch value = VALUE
SetTargetTrade value = VALUE # not in use
SetMaxDefense value = VALUE
SetMaxSupply value = VALUE
SetMaxStockpile value = VALUE
SetConstruction value = VALUE # not really in use
SetDefense value = VALUE
SetHappiness value = VALUE
SetIndustry value = VALUE
SetPopulation value = VALUE
SetResearch value = VALUE
SetSupply value = VALUE
SetTrade value = VALUE # not in use
SetSize value = VALUE
# on planets and ships
SetMaxShield value = VALUE
SetMaxTroops value = VALUE
SetDetection value = VALUE
SetShield value = VALUE
SetStealth value = VALUE
SetTroops value = VALUE
# on ships
SetMaxFuel value = VALUE
SetMaxStructure value = VALUE
SetFuel value = VALUE
SetSpeed value = VALUE
SetStructure value = VALUE

Param Type:

VALUE double

Sets the appropriate meter to VALUE.

  • If the target of the Effect does not have the requested meter, nothing is done.
  • Typically, meter-setting effects do so by adding or subtracting form the same meter value of the Target. For example,
SetTargetResearch Target.TargetResearch + 5

or

SetHealth Value - 10

The value "Value" always refers to the present value of the meter being set, allowing incremental changes to meter values without the cumbersome use of references to the Target such as "Target.FoodConsumption" (for the Target's food consumption meter) which would instead be just "Value" when using the SetFoodConsumption effect.

When a "max" (eg. MaxStructure) or "target" (eg. TargetPopulation) meter value, or another meter for which there is no associated "max" or "target" meter (eg. Stealth), the change is non-persistent. This means that every turn, the meter is reset to 0, and all effects must re-act on the meter for it to retain a consistent value. If on a subsequent turn, the effect does not at on that target, the meter value will return to its previous value (or whatever value all other effects acting on it produce).

When a meter (eg. Structure) has an associated "max" or "target" meter (eg. MaxStructure), the meter value IS persistent. Repeatedly applying the same effect every turn will accumulate. If an effect reduced an object's Health meter by -2 every turn, the 2nd turn would have a net -4 reduction, the 3rd turn would have a net -6 reduction, etc. If an effect alters such a meter once, then does not act again, the meter stays reduced, until other effects increase or decrease it, or it increases or decreases itself over time towards its associated target or max value.

SetShipPartMeter

Acting on ships:

SetMaxCapacity      (set capacity max meter)
SetMaxDamage        (set capacity max meter - this may do the wrong thing for hangar parts)
SetMaxSecondaryStat (set secondary capacity max meter)
SetCapacity         (set capacity meter)
SetDamage           (set capacity meter - this may do the wrong thing for hangar parts)
SetSecondaryStat    (set secondary capacity meter)

SetOwnerCapitol

SetOwnerCapitol

Sets the target object to be the capitol of its owner's empire. If the target is not a planet, or is not owned by a single empire, nothing is done.

SetPlanetType

SetPlanetType type = TYPE

Param Type:

TYPE PlanetType

Sets the planet type of the target to TYPE.

  • Has no effect on non-Planet targets.
  • Changing type from Asteroids or GasGiant to something else will also change its size to Tiny or Huge, respectively.
  • Changing type to Asteroids or GasGiant will also cause the size to change to Asteroids or GasGiant, respectively.

SetPlanetSize

SetPlanetSize size = SIZE

Param Type:

SIZE PlanetSize

Sets the planet size of the target to SIZE.

  • Has no effect on non-Planet targets.
  • Changing the size of a Asteroids or GasGiant planet will also change its type to Barren.
  • Changing size to Asteroids or GasGiant will also cause the type to change to Asteroids or GasGiant, respectively.

SetOwner

SetOwner empire = EMPIRE

Param Type:

EMPIRE int

Sets empire EMPIRE_ID as the owner of the target.

  • Has no effect if EMPIRE_ID was already the owner of the target object.

CreatePlanet

CreatePlanet type = TYPE size = SIZE

Param Types:

TYPE PlanetType
SIZE PlanetSize

Creates a new planet at the location of the target object. If the target object is not located in a system, nothing is done. If there are no free orbit slots at the target object's system, nothing is done.

CreateBuilding

CreateBuilding name = NAME

Param Types:

NAME string

Creates a new building at the location indicated by the target object. If the target object is not a planet, nothing is done.

CreateShip

CreateShip
    designname = "NAME"
    empire = EMPIREID
    species = "SPECIES"

ParamTypes

NAME string_constant
EMPIREID int_constant
SPECIES string_constant

Creates a new shipat the location of the target object. The design of the new ship is indicated by the NAME parameter, which looks up the design in premade_ship_designs.txt in the default folder. EMPIREID is the id of the empire who should own the newly created ship, which is probably the id of something related to the source or target objects. SPECIES is the name of the species which should crew the newly created ship, which can be something related to target or source objects, or an explicit species name.

Destroy

Destroy

Destroys the target object.

  • The Destroy effect will not destroy a System object, although any other objects in or outside a system can be destroyed.
  • Destroy effects are executed after all other effects.
  • Destroying a fleet will destroy its ships.
  • Destroying all the ships in a fleet will destroy the fleet.
  • Destroying a planet will destroy its buildings.

AddSpecial

AddSpecial name = "NAME"

Param Type:

NAME string_constant

Adds the Special with the name NAME to the target object.

  • Note that using a wrong NAME/a NAME for which no special is specified is possible but will lead to strange behaviours
  • You can retrieve the turn a Special was added using the SpecialAddedOnTurn complex variable

RemoveSpecial

RemoveSpecial name = "NAME"

Param Type:

NAME string_constant

Removes the Special with the name NAME to the target object.

  • Has no effect if no such Special was already attached to the target object.

SetSpecialCapacity

SetSpecialCapacity name = "NAME" capacity = NUMBER

Param Type:

NAME string_constant
NUMBER double (ValueRef)

Sets the capacity of Special with the name NAME to the given NUMBER.

  • Adds the Special if no such Special was already attached to the target object.
  • If such a Special was attached, this won't change the since turn value (queried by HasSpecialSinceTurn)
  • Object candidates can be filtered using the HasSpecialCapacity condition
  • The special's capacity value can be retrieved using the SpecialCapacity complex variable

SetStarType

SetStarType type = TYPE

Param Type:

TYPE StarType

Sets the star type of the target to TYPE.

  • Has no effect on non-System targets.

MoveTo

MoveTo location = CONDITION

Param Type:

LOCATION Condition

Moves the target object to the location of one of the objects matched by LOCATION

  • If no objects match the location condition, nothing is done.
  • If more than one object matches the location condition, one object is chosen by the condition
  • If the target object is a ship and the location object is a fleet or a ship (in a fleet) owned by the same empire, the ship is inserted into the fleet.
  • If the target object is a ship and the location is not a fleet into which the ship can be inserted, a new fleet is created for the ship a the new location.
  • If the target object is a ship and its location is the same system but not a different fleet, nothing is done and the ship is left in its original fleet.
  • If the target object is a fleet and its location is a fleet or ship outside a system, and a fleet is moved to or created at the target location, the fleet will be moving to the same system as the taget object fleet.
  • If the target object is a building and the location object is a planet or a building on a planet, the building is added to the planet.
  • If the target object is a building and the location is not a planet or on a planet, nothing is done.
  • If the target object is a planet and the location object is not a system or in a system, nothing is done.
  • If the target object is a planet and the location system has no empty orbit slots, nothing is done.
  • If the target object is a system, nothing is done.
  • Any target object moved to the location of a system will be inserted into that system.

Techs

GiveEmpireTech name = "NAME"
GiveEmpireTech name = "NAME" empire = EMPIRE

Param Type:

NAME string_constant
EMPIRE integer ID of empire (such as Target.Owner which is the default if this parameter is omitted).

GiveEmpireTech gives the indicated empire the indicated tech. After this, the result should be the same as if the empire had researched that tech.


SetEmpireTechProgress name = "NAME" progress = PROGRESS
SetEmpireTechProgress name = "NAME" progress = PROGRESS empire = EMPIRE

Param Type:

NAME string_constant
PROGRESS double
EMPIRE integer ID of empire

SetEmpireTechProgress sets the amount of research points (RP) the indicated empire has accumulated towards researching the indicated tech (limited to between 0 and the total RP cost of the tech).

Victory

Victory reason = "REASON"

Param Type

REASON string_constant

Victory causes the owner of the target object to win the game. Losing human players (which is any player who has not won on the turn a player wins) are ejected from the game. The string REASON is d_constantisplayed in a popup to all players, with the name of the winning empire inserted as the %1% parameter to the string.

AddStarlanes and RemoveStarlanes

AddStarlanes endpoint = CONDITION
RemoveStarlanes endpoint = CONDITION

Param Type

CONDITION condition

AddStarlanes adds starlanes between the target system and any system containing an object that matches CONDITION. RemoveStarlanes removes starlanes between the target system and any system containing an object that matches CONDITIONS. Adding a starlanes where one already exists, or removing a starlane wher none exists does nothing.

MoveTo

MoveTo destination = CONDITION

Param Type

CONDITION condition

MoveTo moves the target object to the location of the / one of the objects matched by the CONDITION parameter.

SetDestination

SetDestination destination = CONDITION

Param Type

CONDITION condition

SetDestination sets the travel route of the target fleet to be the shortest path for the target to move to an object that matches the CONDITION parameter. If multiple objects match CONDITION, one is chosen. If the target fleet can't move to the chosen object, nothing is done. The shortest path for the object may depend on the empire that owns it (if any).

SetAggression

SetAggressive
SetPassive

SetAggressive marks a fleet as aggressive, meaning it will block enemy supply, and engage any enemy fleets or planets in its system. SetPassive marks a fleet as passive, meaning it will not block supply or initiate combat. Remaining passive may be useful for staying hidden in a system (if stealthy) or to make non-aggressive monster types not attack player fleets.

SetSpecies

SetSpecies name = "NAME"

Param Type

NAME string_constant

SetSpecies sets the species of the target ship or planet to the indicated species NAME.

SetVisibility

The following details for this Effect correspond to the modifications currently proposed in PR 1764, please note some constraints/complications regarding priority and timing of evaluation as discussed in the PR.

SetVisibility {affilition = AFFILIATION} {empire = EMPIRE} visibility = VISIBILITY {condition = CONDITION}

Param Type

AFFILIATION optionally specifies an empire affiliation. Defaults to TheEmpire if an empire ID is specified, or AnyEmpire if no empire ID is specified.
EMPIRE optionally specifies an Int ValueRef specifying an empire ID, which is used with the affiliation to determine which empire's visibility/ies to set. Defaults to an invalid empire ID if none is specified, which will work with affiliations that aren't relative to a particular empire.
VALUEREF A Visibility type ValueRef, can include expressions like max(Value, V) where Value refers to the current visibility 
CONDITION optionally condition specifies the object(s) whose visibility is to be set. If no condition is specified, the effect target object's visibility is set.

Effect Evaluation & Application Ordering

Effects are evaluated and then applied while processing a FreeOrion turn. When this happens, all EffectsGroups' activation and scope conditions are evaluated before any effects are applied.

The order of effects' application is determined primarily by their specified Priority (beginning at 0).

For EffectsGroups sharing the same Priority number their secondary ordering is determined by their source/cause, as follows: effects from Species, then effects from Specials, then effects from Techs, then effects from Buildings, then effects from Ship Hulls, then effects from Ship Parts. The order of execution of Effects within these groups is deterministic, though not controllable.

Multiple effects scripted into the same item will be evaluated in the order in which they appear.