# SquirtBot API

## Forever Script Entry and Native WoW API Calls

```lua
local abc, wow = ...
```

**For Forever scripts, receive these two arguments at the top of each Lua file that needs these interfaces. All native World of Warcraft API functions used by the script must be accessed through the injected `wow` table: use `wow.FunctionName(...)` for ordinary functions and `wow.C_Namespace.FunctionName(...)` for namespaced functions.**

**This calling convention is required only for Forever. Standard level-60, level-70, level-80, and MoP clients retain their existing client and loader conventions. The distinction concerns the game version, not the client's language.**

### What the Entry Statement Means

`...` is Lua's variable-argument expression. At this script entry point, it receives the arguments supplied by the unlocker when it loads the script. It is literal Lua syntax, not a placeholder to replace.

| Element | Meaning |
|---|---|
| `abc` | The first argument: the unlocker's own API table, providing its extension functions. |
| `wow` | The second argument: the native WoW API table supplied by the host for the current game client. |
| `local` | Keeps these variables local to the current Lua file without overwriting global variables. |

`abc` is a variable name of your choice; names such as `aa` or `host` work equally well. Keep the argument order unchanged. If you only need the WoW API, retain the first argument's position:

```lua
local _, wow = ...
```

Do not write `local wow = ...`: that assigns the first argument, the unlocker API table, to `wow`. Do not create an empty `wow = {}` table or replace the injected table with `_G`.

### Why Forever Requires This Convention

The Forever host supplies unlocker extensions and native game APIs as two separate interfaces. The injected `wow` table is the intended source of game functions for the script. A bare call such as `UnitName(...)`, `GetTime()`, or `C_QuestLog.GetInfo(...)` instead looks up a global name in the script environment. That name may be unavailable or may not refer to the interface supplied by the host.

Use the injected `wow` table consistently in Forever scripts. Even if a bare global happens to work, do not mix it with injected calls or automatically fall back to `_G` when an interface is missing or a call fails. Check and handle missing interfaces explicitly. Adding `wow.` does not create an API that the client lacks, nor does it change the function's arguments or return values.

### Calling Native APIs

The left column shows bare calls to replace; the right column shows the required Forever form. The left column is not a fallback for Forever.

| Bare call | Forever call |
|---|---|
| `UnitName("player")` | `wow.UnitName("player")` |
| `UnitHealth("player")` | `wow.UnitHealth("player")` |
| `UnitHealthMax("player")` | `wow.UnitHealthMax("player")` |
| `GetTime()` | `wow.GetTime()` |
| `GetBuildInfo()` | `wow.GetBuildInfo()` |
| `CreateFrame("Frame")` | `wow.CreateFrame("Frame")` |
| `C_QuestLog.GetInfo(index)` | `wow.C_QuestLog.GetInfo(index)` |
| `C_Spell.GetSpellInfo(spellID)` | `wow.C_Spell.GetSpellInfo(spellID)` |

Preserve the complete `C_*` namespace hierarchy: `wow.C_QuestLog.GetInfo` must not become `wow.GetInfo`. Use dot notation for these functions. Writing `wow:UnitName("player")` would pass an extra `self` argument and change the call signature.

Check that the current client provides the functions your script uses, including the namespaced APIs shown above.

### What Does Not Use the wow Prefix

- **Unlocker extension APIs** belong to the first argument's table, for example `abc.GetAppUsername()`, not `wow.GetAppUsername()`. The API signatures later in this document describe function names, arguments, and return values; access the corresponding unlocker functions through `abc` in Forever scripts.
- **Lua standard functions and libraries** retain their usual names, including `print`, `type`, `pairs`, `ipairs`, `pcall`, `tostring`, `math`, `string`, and `table`. Do not change them to `wow.print` or `wow.math`.
- **Methods on returned objects** are called on those objects. After creating a frame with `wow.CreateFrame`, use `frame:RegisterEvent(...)` and `frame:SetScript(...)`. Do not introduce `wow.frame` or remove the colon required for an object method.
- **Your own functions, variables, and modules** keep their existing calling conventions. The `wow.` rule applies to native game API functions; it is not a prefix to add to every identifier.

### Complete Example: Read Player Health and Handle an Event

Run this example after entering the game world. Player-related APIs and data are not guaranteed to be available on the login screen.

```lua
local abc, wow = ...

assert(type(abc) == "table", "Missing unlocker API argument")
assert(type(wow) == "table", "Missing WoW API argument")
assert(type(wow.UnitName) == "function", "Missing wow.UnitName")
assert(type(wow.UnitHealth) == "function", "Missing wow.UnitHealth")
assert(type(wow.UnitHealthMax) == "function", "Missing wow.UnitHealthMax")
assert(type(wow.CreateFrame) == "function", "Missing wow.CreateFrame")

local function ShowPlayerHealth()
    local name = wow.UnitName("player")
    local health = wow.UnitHealth("player")
    local maximum = wow.UnitHealthMax("player")
    print("Player:", name, "Health:", health, "/", maximum)
end

ShowPlayerHealth()

local frame = wow.CreateFrame("Frame")
frame:RegisterEvent("UNIT_HEALTH")
frame:SetScript("OnEvent", function(self, event, unit)
    if unit == "player" then
        ShowPlayerHealth()
    end
end)
```

`UnitName`, `UnitHealth`, `UnitHealthMax`, and `CreateFrame` are accessed through `wow`. `assert`, `type`, and `print` are Lua functions. `RegisterEvent` and `SetScript` are methods on the frame object.

Event callbacks can use the `wow` variable captured from the surrounding file. **Do not receive `local abc, wow = ...` again inside an event callback:** callback arguments describe the event, not the two interfaces supplied when the host loaded the script.

### Scripts with Multiple Files

A file's `local wow` is not automatically available as a local variable in another file. Each file independently loaded by the host under this convention should receive `local abc, wow = ...` if it needs these interfaces. For modules or factory functions that you call yourself, pass the interfaces explicitly; arbitrary Lua calls do not automatically receive them.

---

This is the up-to-date list of all SquirtBot API, classified into the following categories.

- **Common** (API functions exist in both GLUE and GAME WORLD)
    - [Arguments](#common-arguments)
        - [GetAppDirectory](#getappdirectory)
        - [GetAppSessionCount](#getappsessioncount)
        - [GetAppSessionIndex](#getappsessionindex)
        - [GetAppSessionToken](#getappsessiontoken)
        - [GetAppUsername](#getappusername)
        - [GetSystemErrorCode](#getsystemerrorcode)
        - [GetSystemVar and SetSystemVar](#getsystemvar-and-setsystemvar)
        - [GetWoWDirectory](#getwowdirectory)
    - [Constants](#common-constants)
        - [GetStringEncodingsTable](#getstringencodingstable)
        - [GetValueTypesTable](#getvaluetypestable)
    - [Encryption](#common-encryption)
        - [Aes256Encrypt and Aes256Decrypt](#aes256encrypt-and-aes256decrypt)
        - [EncodeDecode](#encodedecode)
        - [Sha256](#sha256)
    - [File](#common-file)
        - [CreateDirectory](#createdirectory)
        - [DirectoryExists](#directoryexists)
        - [FileExists](#fileexists)
        - [GetDirectoryFiles](#getdirectoryfiles)
        - [GetDirectoryFolders](#getdirectoryfolders)
        - [ReadFile](#readfile)
        - [WriteFile](#writefile)
    - [Lua](#common-lua)
        - [EnableUnlocker](#enableunlocker)
        - [LoadScript](#loadscript)
        - [LoadScriptAesEncrypted](#loadscriptaesencrypted)
        - [RunScript](#runscript)
        - [RunScriptAesEncrypted](#runscriptaesencrypted)
        - [SetCustomScript](#setcustomscript)
    - [Maths](#common-maths)
        - [GetAllSpanningCircles](#getallspanningcircles)
    - [Network](#common-network)
        - [DisconnectFromServer](#disconnectfromserver)
        - [SendHttpRequest and ReceiveHttpResponse](#sendhttprequest-and-receivehttpresponse)
    - [State](#common-state)
        - [ResetAfk](#resetafk)
    - [Win32](#common-win32)
        - [GetKeyState](#getkeystate)
        - [GetMemoryOffset](#getmemoryoffset)
        - [IsCurrentWindow](#iscurrentwindow)
        - [PlaySoundFile](#playsoundfile)
        - [ReadMemory](#readmemory)
        - [ShellExecute](#shellexecute)
        - [TerminateCurrentProcess](#terminatecurrentprocess)
- **In-World** (API functions only exist in GAME WORLD)
    - [Action](#in-world-action)
        - [ClickPosition](#clickposition)
        - [FaceDirection](#facedirection)
        - [FaceDirectionSmoothly](#facedirectionsmoothly)
        - [GetLastClickedPosition](#getlastclickedposition)
        - [IsFacingSmoothly](#isfacingsmoothly)
        - [MoveTo](#moveto)
        - [SetPitch](#setpitch)
    - [Black Technology](#in-world-black-technology)
        - [EnableClimbing](#enableclimbing)
        - [EnableFlying](#enableflying)
        - [EnableNoclip](#enablenoclip)
        - [IgnoreWater](#ignorewater)
        - [SetCameraDistanceMax](#setcameradistancemax)
        - [SetClimbAngle](#setclimbangle)
        - [SetCVarEx](#setcvarex)
        - [SetNameplateDistanceMax](#setnameplatedistancemax)
        - [StopFalling](#stopfalling)
    - [Constants](#in-world-constants)
        - [GetObjectDescriptorsTable](#getobjectdescriptorstable)
        - [GetObjectFieldsTable](#getobjectfieldstable)
        - [GetObjectQuestGiverStatusesTable](#getobjectquestgiverstatusestable)
        - [GetObjectTypeFlagsTable](#getobjecttypeflagstable)
        - [GetUnitMovementFlagsTable](#getunitmovementflagstable)
    - [Navigation](#in-world-navigation)
        - [AddOffmeshConnection](#addoffmeshconnection)
        - [FindPath](#findpath)
        - [GetClosestMeshPolygon](#getclosestmeshpolygon)
        - [GetCurrentMapInfo](#getcurrentmapinfo)
        - [GetMeshAreaCost](#getmeshareacost)
        - [GetMeshPolygons](#getmeshpolygons)
        - [GetMeshPolygonArea](#getmeshpolygonarea)
        - [GetMeshPolygonFlags](#getmeshpolygonflags)
        - [GetMeshPolygonVertices](#getmeshpolygonvertices)
        - [GetMeshTile](#getmeshtile)
        - [GetOffmeshConnectionDetails](#getoffmeshconnectiondetails)
        - [GetOffmeshConnections](#getoffmeshconnections)
        - [IsMapLoaded](#ismaploaded)
        - [LoadMap](#loadmap)
        - [MapExists](#mapexists)
        - [RemoveOffmeshConnection](#removeoffmeshconnection)
        - [SetMeshAreaCost](#setmeshareacost)
        - [SetMeshPolygonArea](#setmeshpolygonarea)
        - [SetMeshPolygonFlags](#setmeshpolygonflags)
        - [UnloadMap](#unloadmap)
    - [Object](#in-world-object)
        - [GameObjectIsUsable](#gameobjectisusable)
        - [GameObjectType](#gameobjecttype)
        - [GetActiveMover](#getactivemover)
        - [GetAnglesBetweenObjects](#getanglesbetweenobjects)
        - [GetCorpsePosition](#getcorpseposition)
        - [GetDistanceBetweenObjects](#getdistancebetweenobjects)
        - [GetDistanceBetweenPositions](#getdistancebetweenpositions)
        - [GetObject](#getobject)
        - [GetObjectWithGUID](#getobjectwithguid)
        - [GetPositionBetweenObjects](#getpositionbetweenobjects)
        - [GetPositionBetweenPositions](#getpositionbetweenpositions)
        - [GetPositionFromPosition](#getpositionfromposition)
        - [SetMouseoverObject](#setmouseoverobject)
        - [ObjectAnimationState](#objectanimationstate)
        - [ObjectCreator (aka UnitCreator)](#objectcreator-aka-unitcreator)
        - [ObjectDynamicFlags](#objectdynamicflags)
        - [ObjectExists](#objectexists)
        - [ObjectFacing](#objectfacing)
        - [ObjectField (aka ObjectDescriptor)](#objectfield-aka-objectdescriptor)
        - [ObjectHeight](#objectheight)
        - [ObjectId](#objectid)
        - [ObjectIsBehind](#objectisbehind)
        - [ObjectIsFacing](#objectisfacing)
        - [ObjectIsQuestObjective](#objectisquestobjective)
        - [ObjectIsType](#objectistype)
        - [ObjectPosition](#objectposition)
        - [ObjectQuestGiverStatus](#objectquestgiverstatus)
        - [ObjectQuests](#objectquests)
        - [ObjectRelativePosition](#objectrelativeposition)
        - [ObjectRelativeFacing](#objectrelativefacing)
        - [ObjectScale](#objectscale)
        - [ObjectTypeFlags](#objecttypeflags)
        - [UnitBoundingRadius](#unitboundingradius)
        - [UnitCasting](#unitcasting)
        - [UnitCastingTarget](#unitcastingtarget)
        - [UnitChannel](#unitchannel)
        - [UnitCombatReach](#unitcombatreach)
        - [UnitCreatureTypeId](#unitcreaturetypeid)
        - [UnitCreatureFamilyId](#unitcreaturefamilyid)
        - [UnitCreatureField](#unitcreaturefield)
        - [UnitFlags](#unitflags)
        - [UnitIsLootable](#unitislootable)
        - [UnitIsMounted](#unitismounted)
        - [UnitIsSkinnable](#unitisskinnable)
        - [UnitMovementField](#unitmovementfield)
        - [UnitMovementFlags](#unitmovementflags)
        - [UnitPitch](#unitpitch)
        - [UnitSkinningType](#unitskinningtype)
        - [UnitTarget](#unittarget)
        - [UnitTransport](#unittransport)
    - [Object Manager](#in-world-object-manager)
        - [GetAreaTriggerCount](#getareatriggercount)
        - [GetAreaTriggerWithIndex](#getareatriggerwithindex)
        - [GetDynamicObjectCount](#getdynamicobjectcount)
        - [GetDynamicObjectWithIndex](#getdynamicobjectwithindex)
        - [GetGameObjectCount](#getgameobjectcount)
        - [GetGameObjectWithIndex](#getgameobjectwithindex)
        - [GetNpcCount](#getnpccount)
        - [GetNpcWithIndex](#getnpcwithindex)
        - [GetObjectCount](#getobjectcount)
        - [GetObjectWithIndex](#getobjectwithindex)
        - [GetPlayerCount](#getplayercount)
        - [GetPlayerWithIndex](#getplayerwithindex)
    - [Spell](#in-world-spell)
        - [CancelPendingSpell](#cancelpendingspell)
        - [GetActiveSpellCount](#getactivespellcount)
        - [GetActiveSpellWithIndex](#getactivespellwithindex)
        - [GetAuraCount](#getauracount)
        - [GetAuraWithIndex](#getaurawithindex)
        - [GetMissileCount](#getmissilecount)
        - [GetMissileWithIndex](#getmissilewithindex)
        - [GetPendingSpell](#getpendingspell)
    - [State](#in-world-state)
        - [GetCurrentAccount](#getcurrentaccount)
        - [GetCurrentTime](#getcurrenttime)
    - [Vision](#in-world-vision)
        - [GetCameraPosition](#getcameraposition)
        - [ScreenToWorld](#screentoworld)
        - [TraceLine](#traceline)
        - [WorldToScreen](#worldtoscreen)

# Common (Arguments)
The following common API functions deal with SquirtBot related arguments.

[Back to Table of Contents](#squirtbot-api)

## GetAppDirectory
Gets the working directory path of SquirtBot client, where the subfolder `navmeshes` reside.
```lua
result = GetAppDirectory()
-- result (string): The result directory path
```
[Back to Category](#common-arguments)

## GetAppSessionCount
Gets the total session count of the current SquirtBot launch.
```lua
result = GetAppSessionCount()
-- result (number): The result count
```
[Back to Category](#common-arguments)

## GetAppSessionId
Gets the server ID of the current SquirtBot session, starting from 1. This ID is unique among all sessions, even across computers.
```lua
result = GetAppSessionId()
-- result (number): The result ID
```
[Back to Category](#common-arguments)

## GetAppSessionIndex
Gets the client index of the current SquirtBot session, starting from 1. This index is unique on the local computer.
```lua
result = GetAppSessionIndex()
-- result (number): The result index
```
[Back to Category](#common-arguments)

## GetAppSessionToken
Gets the token of the current SquirtBot session.
```lua
result = GetAppSessionToken()
-- result (string): The result token
```
[Back to Category](#common-arguments)

## GetAppUsername
Gets the username of the current SquirtBot session.
```lua
result = GetAppUsername()
-- result (string): The result username
```
[Back to Category](#common-arguments)

## GetSystemErrorCode
Gets the current error code of the SquirtBot system. It returns 0 if the system has no errors. Notice that if any non-zero error code pops up, the engine will stay alive for at most 5 minutes followed by process termination. Such a 5-min grace period should be used to prepare for game exit. Once ready, you could opt to call [TerminateCurrentProcess](#terminatecurrentprocess) in advance to avoid security concerns as much as possible.
```lua
errorCode[, secondsToTermination] = GetSystemErrorCode()
-- errorCode (number): The result error code, which can be one of the followings
{
    SubscriptionExpired = 1,
    RunTooLong = 2,
    HeartbeatFailure = 3,
    SessionInvalidated = 4,
    SecurityRelated = 5
}
-- secondsToTermination (number): The remaining seconds to termination if errorCode is non-zero.
```
[Back to Category](#common-arguments)

## GetSystemVar and SetSystemVar
These API allow you to reads or writes a system-wide global variable that will never go out of scope until the game process is terminated.
```lua
value = GetSystemVar(name)
-- name (string): The name of the global variable
-- value (string): The current value of the global variable (nil if it does not exist)
```
```lua
SetSystemVar(name, value)
-- name (string): The name of the global variable
-- value (string): The value of the global variable (nil to remove it)
```
[Back to Category](#common-arguments)

## GetWoWDirectory
Gets the directory path of WoW.exe.
```lua
result = GetWoWDirectory()
-- result (string): The result directory path
```
[Back to Category](#common-arguments)

---

# Common (Constants)
The following common API functions return SquirtBot defined constants.

[Back to Table of Contents](#squirtbot-api)

## GetStringEncodingsTable
Gets the table of supported string encodings.
```lua
encodings = GetStringEncodingsTable()
-- encodings (table): The table that contains the following string encodings
{
    Plain = 0,  -- The original data in as-is form (including binary data)
    Base64 = 1, -- Base-64 encoding of the original data
    Hex = 2,    -- Hex encoding of the original data, always in lower case
}
```
[Back to Category](#common-constants)

## GetValueTypesTable
Gets the table of all value types to read from memory.
```lua
types = GetValueTypesTable()
-- types (table): The table that contains the following memory value types
{
    Bool = 1,
    Char = 2,
    Byte = 3,
    Short = 4,
    UShort = 5,
    Int = 6,
    UInt = 7,
    Long = 8,
    ULong = 9,
    Float = 10,
    Double = 11,
    String = 12,
    IntPtr = 13,
    UIntPtr = 14,
    GUID = 15,
}
```
[Back to Category](#common-constants)

# Common (Encryption)
The following common API functions handle encryptions and encodings.

[Back to Table of Contents](#squirtbot-api)

## Aes256Encrypt and Aes256Decrypt
Encrypts or decrypts a string by AES-256 CBC with padding.
```lua
output = Aes256Encrypt(input, key, iv[, padding = "zero", output_encoding = encodings.Plain])
-- input (string): The input string to be encrypted
-- key (string): The key for encryption (must be 32 bytes)
-- iv (string): The IV for encryption (must be 16 bytes)
-- padding (string)：The padding method, which can be either "pkcs7" or "zero"
-- output_encoding (number): The encoding for the encrypted result, from GetStringEncodingsTable()
-- output (string): The output string encrypted
```
```lua
output = Aes256Decrypt(input, key, iv[, padding = "zero", input_encoding = encodings.Plain])
-- input (string): The input string to be decrypted
-- key (string): The key for decryption (must be 32 bytes)
-- iv (string): The IV for decryption (must be 16 bytes)
-- padding (string)：The padding method, which can be either "pkcs7" or "zero"
-- input_encoding (number): The encoding of the input, from GetStringEncodingsTable()
-- output (string): The output string decrypted
```
In order to make sure your own AES encryption matches the API above, the test vector is given below:
```lua
local test = "test";
local encodings = GetStringEncodingsTable();
local encrypted_string = Aes256Encrypt(test, "01234567890123456789012345678901", "0123456789012345", "pkcs7", encodings.Hex);
local decrypted_string = Aes256Decrypt(encrypted_string, "01234567890123456789012345678901", "0123456789012345", "pkcs7", encodings.Hex);
print("result:", encrypted_string, decrypted_string, test == decrypted_string); -- result: a68c23c38693a8ebd1d6276fbb90e5e1 test true
```
[Back to Category](#common-encryption)

## EncodeDecode
Transforms the encoding of an input string from one to another.
```lua
output = EncodeDecode(input, input_encoding, output_encoding)
-- input (string): The input string
-- input_encoding (number): The encoding of the input string, from GetStringEncodingsTable()
-- output_encoding (number): The encoding of the output string, from GetStringEncodingsTable()
-- output (string): The output string
```
[Back to Category](#common-encryption)

## Sha256
Computes the hash digest of a plain string by SHA-256.
```lua
output = Sha256(input)
-- input (string): The plain string
-- output (string): The digest string
```
In order to make sure your own SHA256 digest matches the API above, the test vector is given below:
```lua
local test = "The quick brown fox jumps over the lazy dog";
local digest = Sha256(test);
print("result:", digest); -- result: d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592
```
[Back to Category](#common-encryption)

---

# Common (File)
The following common API functions provide file system operations.

[Back to Table of Contents](#squirtbot-api)

## CreateDirectory
Creates a new directory.
```lua
success = CreateDirectory(path)
-- path (string): The directory path
-- success (boolean): Whether the directory is created successfully.
```
[Back to Category](#common-file)

## DirectoryExists
Checks if a directory exists.
```lua
existence = DirectoryExists(path)
-- path (string): The directory path
-- existence (boolean): Whether the directory exists
```
[Back to Category](#common-file)

## FileExists
Checks if a file exists.
```lua
existence = FileExists(path)
-- path (string): The file path
-- existence (boolean): Whether the file exists
```
[Back to Category](#common-file)

## GetDirectoryFiles
Gets the names of all files in a specific directory.
```lua
fileNames = GetDirectoryFiles(path)
-- path (string): The directory path
-- fileNames (table): The file name array
```
[Back to Category](#common-file)

## GetDirectoryFolders
Gets the names of all subfolders in a specific directory.
```lua
folderNames = GetDirectoryFolders(path)
-- path (string): The directory path
-- folderNames (table): The folder name array
```
[Back to Category](#common-file)

## ReadFile
Reads the content of a file.
```lua
content = ReadFile(path[, encoding = encodings.Plain])
-- path (string): The file path
-- encoding (number): The encoding to encode the file content, from GetStringEncodingsTable()
-- content (string): The file content
```
[Back to Category](#common-file)

## WriteFile
Writes the content of a file.
```lua
success = WriteFile(path, content[, append = false])
-- path (string): The file path
-- content (string): The file content
-- append (boolean): Whether to append or overwrite the file
-- success (boolean): Whether the content is successfully written to the file
```
[Back to Category](#common-file)

# Common (Lua)
The following common API functions give you some additional features of Lua engine.

[Back to Table of Contents](#squirtbot-api)

## EnableUnlocker
Enables the unlocker for all Blizzard API functions. It is disabled by default and you should enable it when you need to call protected API.
```lua
enabled = EnableUnlocker([enable])
-- enable (boolean): Whether to enable or disable the unlocker (none/nil to only get the current enable status)
-- enabled (boolean): The current enable status of the unlocker
```
[Back to Category](#common-lua)

## LoadScript
Loads a Lua script as a function. It behaves similar to `loadstring` but provides an additional layer against API hooking.
```lua
script | error = LoadScript(name, content)
-- name (string): The name of the script (shown in Lua error messages if any)
-- content (string): The content of the script
-- script (function): The loaded function if compilation succeeds
-- error (string): The syntax error message if compilation fails
```
[Back to Category](#common-lua)

## LoadScriptAesEncrypted
Loads a Lua script as a function, whose content is encrypted with AES-256 CBC. It behaves similar to `loadstring` but provides an additional layer against API hooking and brute-force memory scanning.
```lua
script | error = LoadScriptAesEncrypted(name, content, key, iv[, padding = "zero", encoding = encodings.Plain])
-- name (string): The script name (shown in Lua error messages if any)
-- content (string): The encrypted script content
-- key (string): The key for decrypt the script content (must be 32 bytes)
-- iv (string): The IV for decrypt the script content (must be 16 bytes)
-- padding (string)：The padding method, which can be either "pkcs7" or "zero"
-- encoding (number): The encoding of encrypted script content, from GetStringEncodingsTable()
-- script (function): The loaded function if compilation succeeds
-- error (string): The syntax error message if compilation fails
```
[Back to Category](#common-lua)

## RunScript
Runs a Lua script. Any syntax/runtime error results in an error popup. Any return values from the script will be discarded. It behaves similar to `RunScript` but provides an additional layer against API hooking. If you wish to stay silent or grab the return values, use `LoadScript` followed by manual `pcall`.
```lua
RunScript(name, content)
-- name (string): The name of the script (shown in Lua error messages if any)
-- content (string): The content of the script
```
[Back to Category](#common-lua)

## RunScriptAesEncrypted
Runs a Lua script, whose content is encrypted with AES-256 CBC. Notice that any decryption failures might cause the system to crash. Any return values from the script will be discarded. It behaves similar to `RunScript` but provides an additional layer against API hooking and brute-force memory scanning. If you wish to stay silent or grab the return values, use `LoadScriptAesEncrypted` followed by manual `pcall`.
```lua
RunScriptAesEncrypted(name, content, key, iv[, padding = "zero", encoding] = encodings.Plain)
-- name (string): The script name, shown in any Lua error message
-- content (string): The encrypted script content
-- key (string): The key for decrypt the script content (must be 32 bytes)
-- iv (string): The IV for decrypt the script content (must be 16 bytes)
-- padding (string)：The padding method, which can be either "pkcs7" or "zero"
-- encoding (number): The encoding of encrypted script content, from GetStringEncodingsTable()
```
[Back to Category](#common-lua)

## SetCustomScript
Adds/Updates a custom script that gets loaded side by side with the plugin scripts (usually after game init). Notice that there will be a popup if there are any Lua syntax or runtime errors in the script content.
```lua
SetCustomScript(name, content)
-- name (string): The script name, shown in any Lua error message
-- content (string): The script content
```
[Back to Category](#common-lua)

# Common (Maths)
The following common API functions add more math helpers.

[Back to Table of Contents](#squirtbot-api)

## GetAllSpanningCircles
Gets all spanning circles of a specific radius over certain weighted points. This is usually useful if you need to calculate the landing position of an AoE spell.
```lua
centers = GetAllSpanningCircles(radius, minWeight, points)
-- radius (number): The circle radius
-- minWeight (number): The minimum weight in total of the points that the circle should cover
-- points (table): The weighted position array, in which each element should look like {x, y, z[, w = 1]}
-- centers (table): The center positions of all result circles, in which each element should look like {x, y, z}. The circles are sorted according to the total weight in descending order
```
[Back to Category](#common-maths)

# Common (Network)
The following common API functions provide network functionalities.

[Back to Table of Contents](#squirtbot-api)

## DisconnectFromServer
Disconnects the currently connected WoW session from the Blizzard server.
```lua
DisconnectFromServer()
```
[Back to Category](#common-network)

## SendHttpRequest and ReceiveHttpResponse
Sends a HTTP request asynchronously and receives the response later. SendHttpRequest() will return immediately after the request is sent without waiting for the response. ReceiveHttpResponse() will clear the request from memory if it is finalized.
```lua
request = SendHttpRequest(info)
-- info (table): The request info, which looks like:
{
    Agent = "SquirtBot", -- [OPTIONAL] string: The request agent.
    Body = "{\"test\": 123}", -- [OPTIONAL] string: The request body, only used Method is "POST" or "PUT".
    Callback = function(request, status[, bodySize]) ... end, -- [OPTIONAL] function: The callback function when the status of the request is updated.
    Certificate = "PINNED CERTIFICATE", -- [OPTIONAL] string: The pinned HTTPs server certificate as a protection for packet sniffing. If provided, the server certificate must match it or the HTTP request would fail with status "INVALID_CERTIFICATE".
    Headers = "Content-Type: application/json\r\nX-Custom: test", -- [OPTIONAL] string: The additional request headers
    Method = "POST", -- [OPTIONAL] string: The request method, which can be "GET", "POST", "PUT" or "DELETE"
    Url = "https://www.microsoft.com/", -- string: The request URL
}
-- request (string): The HTTP request ID if sent successfully, for querying HTTP response later
```
```lua
status[, body | bodySize] = ReceiveHttpResponse(request[, encoding = encodings.Plain])
-- request (string): The HTTP request ID previously returned from SendHttpRequest().
-- encoding (number): The encoding to encode the response body, from GetStringEncodingsTable().
-- status (string): The current status of the HTTP request, which can be one of the followings:
    -- "REQUESTING": The request is still on the way
    -- "REDIRECTING": The request is being redirected to another URL (HTTP 301/302)
    -- "RESPONDING": Downloading response after the request is sent
    -- "SUCCESS": The response is well received and everything about the HTTP request is finalized
    -- "REQUEST_FAILED": The request is terminated due to failures
    -- "INVALID_CERTIFICATE": The request is terminated due to invalid HTTPs certificate
    -- "RESPONSE_HEADERS_FAILED": The response is terminated while fetching response headers
    -- "RESPONSE_BODY_FAILED": The response is terminated while fetching response body
-- body (table): The response data, available only if status is "SUCCESS", which looks like:
{
    Body = "...", -- string: The HTTP response body
    BodySize = 1024, -- number: The total size of Body, in bytes
    Certificate = "SERVER CERTIFICATE", -- string: The actual server certificate if the request is HTTPs, which can be used for pinning
    Code = 200, -- number: The HTTP response status code
    Headers = "HTTP/1.1 200 OK...", -- string: The HTTP response headers
}
-- bodySize (number): The size of response data received so far, in bytes, only available if status is "RESPONDING"
```
Given the nature of async programming model, a simple example to send and receive HTTP is given as below, leveraging the callback function.
```lua
SendHttpRequest({
    Url = "https://www.microsoft.com",
    Method = "GET",
    Callback = function(request, status, bodySize)
        -- Deal with the current status and response of the HTTP request here.
        if (status == "RESPONDING") then
            print("receiving response:", bodySize)
        elseif (status == "SUCCESS") then
            local _, response = ReceiveHttpResponse(request);
            print("all done! body:", response.Body);
        end
    end
});
```
Another example to send and receive HTTP is given as below, leveraging frame updates.
```lua
local http_frame = CreateFrame("FRAME");
local http_request;
http_frame:SetScript("OnUpdate", function()
    if (not http_request) then
        local info = {...}; -- Fill your actual info here.
        http_request = SendHttpRequest(info);
    else
        local http_status, http_response = ReceiveHttpResponse(http_request)
        if (not http_status) then
            -- The HTTP request has been fulfiled.
            http_frame:SetScript("OnUpdate", nil);
            http_frame = nil;
            return;
        end
        -- Deal with the current status and response of the HTTP request here.
        if (status == "RESPONDING") then
            print("receiving response:", bodySize)
        if (http_status == "SUCCESS") then
            print("response body:", http_response.Body);
        end
    end
end);
```
[Back to Category](#common-network)

# Common (State)
The following common API functions manage game engine states.

[Back to Table of Contents](#squirtbot-api)

## ResetAfk
Resets the game engine AFK countdown timer.
```lua
ResetAfk()
```
[Back to Category](#common-state)

# Common (Win32)
The following common API functions give you power to access certain Win32 capabilities.

[Back to Table of Contents](#squirtbot-api)

## GetKeyState
Gets the pressed state of a specific key.
```lua
down, toggled = GetKeyState(key)
-- key (number): The key code, from https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
-- down (boolean): Whether the key is pressed down
-- toggled (boolean): Whether the key is being toggled (such as CapsLock)
```
[Back to Category](#common-win32)

## GetMemoryOffset
Gets the offset/rva of a specific memory address in a specific memory module.
```lua
offset = GetMemoryOffset(module, address)
-- module (string): The name of the memory module (nil for "Wow.exe" aka the main module)
-- address (number): The absolute memory address
-- offset (number): The result offset *nil if the memory address is not found)
```
[Back to Category](#common-win32)

## IsCurrentWindow
Checks whether the game window is at foreground.
```lua
result = IsCurrentWindow()
-- result (boolean): Whether the game window is at foreground
```
[Back to Category](#common-win32)

## PlaySoundFile
Plays a specific sound WAV/MP3 file once.
```lua
success = PlaySoundFile(path)
-- path (string): The file path of the WAV/MP3 file
-- success (boolean): Whether the sound file is played successfully
```
[Back to Category](#common-win32)

## ReadMemory
Reads a value at a specific memory offset/rva in a specific memory module.
```lua
value = ReadMemory(module, offset, type)
-- module (string): The name of the memory module (nil for "Wow.exe" aka the main module)
-- offset (number): The offset/rva in the memory module to read
-- type (number): The type of the value, from GetValueTypesTable()
-- value (number): The result value (nil if the memory address is not found)
```
[Back to Category](#common-win32)

## ShellExecute
Executes a command of Win32 shell (DOS command).
```lua
success = ShellExecute(command)
-- command (string): The shell command
-- success (boolean): Whether the shell command is executed successfully
```
[Back to Category](#common-win32)

## TerminateCurrentProcess
Terminates the current process, aka WoW game process.
```lua
TerminateCurrentProcess()
```
[Back to Category](#common-win32)

# In-World (Action)
The following in-world API functions extends the character action controls.

[Back to Table of Contents](#squirtbot-api)

## ClickPosition
Click a world position.
```lua
ClickPosition(x, y, z[, right = false])
-- x, y, z (number): The position co-ordinate.
-- right (boolean): Whether it is left-click (true) or right-click (false).
```
[Back to Category](#in-world-action)

## FaceDirection
Sets the facing (horizontal) of the currently controlled unit, in radian (from 0 to 2 * PI). The angle value is relative instead of absolute, if the player is on a transport.
```lua
success = FaceDirection(angle[, update = true])
-- angle (number): The facing/rotation in radian.
-- update (boolean): Whether to update the facing immediately (with an instant turn animation).
-- success (boolean): Whether the facing is changed.
```
[Back to Category](#in-world-action)

## FaceDirectionSmoothly
Sets the horizontal facing of the currently controlled unit smoothly instead of instantly, in radian (from 0 to 2 * PI). The angle value is relative instead of absolute, if the player is on a transport.
```lua
success = FaceDirectionSmoothly(angle, duration[, isRandom = false])
-- angle (number): The horizontal facing, in radian.
-- duration (number): The duration of the smooth facing takes, in seconds.
-- isRandom (boolean): Whether the rotation speed is random.
-- success (boolean): Whether the smooth facing is started.
```
[Back to Category](#in-world-action)

## GetLastClickedPosition
Gets the last world position clicked.
```lua
x, y, z = GetLastClickedPosition()
-- x, y, z (number): The position co-ordinate.
```
[Back to Category](#in-world-action)

## IsFacingSmoothly
Gets whether a smooth facing is ongoing.
```lua
ongoing = IsFacingSmoothly()
-- ongoing (boolean): Whether the smooth facing is in progress.
```
[Back to Category](#in-world-action)

## MoveTo
Moves the player to a specific position, using Click-To-Move. You must enable the system CVar [autoInteract](https://wow.gamepedia.com/CVar_autoInteract) to make this work, which is the same as enabling "Click To Move" in game settings.
```lua
MoveTo(x, y, z[, instantTurn = false])
-- x, y, z (number): The position co-ordinate.
-- instantTurn (boolean): Whether to instantly face to the destination before moving.
```
[Back to Category](#in-world-action)

## SetPitch
Sets the vertical pitch of the currently controlled unit, in radian (from -PI/2 to +PI/2).
```lua
SetPitch(angle)
-- angle (number): The pitch in radian.
```
[Back to Category](#in-world-action)

# In-World (Black Technology)
The following in-world API functions gives you some super power of character actions.

[Back to Table of Contents](#squirtbot-api)

## EnableClimbing
Grants/Revokes the power of climbing to the currently controlled unit. Notice that the standard power of this can only allow you to climb up to 90 degree slopes. You can opt to enable super power that allows you to continue go straight up when an obstacle with larger than 90 degree slope is collided. In the super mode, your character may go straight into the obstacle and can lead to unexpected result. This API is considered to be a replacement over the deprecated [SetClimbAngle](#setclimbangle), and you shouldn't mix-use them both.
```lua
enabled, isSuper = EnableClimbing([enable, isSuper = false])
-- enable (boolean): Whether to enable climbing (none/nil to only get the current enable status)
-- isSuper (boolean): Whether to enable super climbing
-- enabled (boolean): Whether climbing is currently enabled.
```
[Back to Category](#in-world-black-technology)

## EnableFlying
Grants/Revokes the power of flying to the currently controlled unit. When flying power is on, you can use `SetPitch` to move the unit vertically anywhere.
```lua
enabled = EnableFlying([enable])
-- enable (boolean): Whether to enable flying (none/nil to only get the current enable status)
-- enabled (boolean): Whether flying is currently enabled.
```
[Back to Category](#in-world-black-technology)

## EnableNoclip
Grants/Revokes the power of noclip to the currently controlled unit against certain obstacles.
```lua
currentModes = EnableNoclip([modes])
-- modes (number): The modes of noclip which can be a sum of any of the following flags (none/nil to only get the current modes):
0 = none
1 = building
2 = static object
4 = dynamic object
8 = terrain (be careful!)
-- currentModes (number): The current modes of noclip.
```
[Back to Category](#in-world-black-technology)

## IgnoreWater
Ignore water bodies while moving.
```lua
currentMode = IgnoreWater([mode])
-- mode (number): Water ignorance mode, which can be one of the followings (none/nil to only get the current mode)
0 = Normal mode
1 = Treat water as ground (walk above water)
2 = Ignore the presence of water (walk under water)
-- currentMode(number): The current water ignorance mode
```
[Back to Category](#in-world-black-technology)

## SetCameraDistanceMax
Sets the maximum distance of the game camera to any value, in yards. This distance will override the game setting if applied.
```lua
SetCameraDistanceMax([distance])
-- distance (number): The maximum distance (none/nil to restore game setting)
```
[Back to Category](#in-world-black-technology)

## SetClimbAngle
Sets the maximum angle to climb, in radian.
```lua
SetClimbAngle([angle])
-- distance (number): The maximum angle (none/nil to restore game engine allowance)
```
[Back to Category](#in-world-black-technology)

## SetCVarEx
Forcibly sets the value of a CVar. Similar as the Blizzard API `SetCVar`, but this one could bypass the game engine limitation.
```lua
success = SetCVarEx(name, value)
-- name (string): The name of the CVar
-- value (string | number): The value of the CVar
-- success (boolean): Whether the CVar is set successfully
```
[Back to Category](#in-world-black-technology)

## SetNameplateDistanceMax
Sets the maximum distance of a visible nameplate, in yards.
```lua
SetNameplateDistanceMax([distance])
-- distance (number): The nameplate distance maximum (none/nil to restore default setting)
```
[Back to Category](#in-world-black-technology)

## StopFalling
Stops the character falling.
```lua
StopFalling()
```
[Back to Category](#in-world-black-technology)

# In-World (Constants)
The following in-world API functions return SquirtBot defined constants.

[Back to Table of Contents](#squirtbot-api)

## GetObjectDescriptorsTable
Gets the table of all object descriptor offsets.
```lua
descriptors = GetObjectDescriptorsTable()
-- encodings (table): The table that contains the following descriptors, which looks like:
{
    ["CGObjectData__m_guid"] = 0,
    ["CGObjectData__m_entryID"] = 8,
    ...
}
```
[Back to Category](#in-world-constants)

## GetObjectFieldsTable
Gets the table of all object field offsets.
```lua
fields = GetObjectFieldsTable()
-- fields (table): The table of all object field offsets, which looks like:
{
    ["AnimationState"] = 123,
    ...
}
```
[Back to Category](#in-world-constants)

## GetObjectQuestGiverStatusesTable
Gets the table of all quest giver statuses.
```lua
statuses = GetObjectQuestGiverStatusesTable()
-- statuses (table): The table of all quest giver statuses, which looks like:
{
    ["None"] = 0,
    ["Unavailable"] = 1,
    ...
}
```
[Back to Category](#in-world-constants)

## GetObjectTypeFlagsTable
Gets the table of all object type flags.
```lua
flags = GetObjectTypeFlagsTable()
-- flags (table): The table of all all object type flags, which looks like:
{
    Object = 1,
    Item = 2,
    Container = 4,
    AzeriteEmpoweredItem = 8,
    AzeriteItem = 16,
    ...
}
```
[Back to Category](#in-world-constants)

## GetUnitMovementFlagsTable
Gets the table of all unit movement flags.
```lua
flags = GetUnitMovementFlagsTable()
-- flags (table): The table of all unit movement flags, which looks like:
{
    Forward = 1,
    Backward = 2,
    StrafeLeft = 4,
    StrafeRight = 8,
    TurnLeft = 16,
    ...  
}
```
[Back to Category](#in-world-constants)

# In-World (Navigation)
The following in-world API functions provide navmesh calculations. Notice that the map must be loaded beforehand for the rest calculation to work properly (see [LoadMap](#loadmap)). Regarding the special terms referred, check below:
- [Offmesh Connection](https://docs.unity3d.com/2020.2/Documentation/Manual/class-OffMeshLink.html)
- `Polygon Flags` are a type attribute of polygons. It is used to indicate certain types of polygons passability.
- `Polygon Area` is just another type attribute of polygons. It is used to apply different costs for shortest path calculation. But unlike polygon flags, which are a combination of various flag values, a polygon can only have one type of area.

[Back to Table of Contents](#squirtbot-api)

## AddOffmeshConnection
Adds a new offmesh connection to a map on the fly. Notice:
1. There might be pre-compiled offmesh connections in the map files.
2. The added offmesh connection only applies before you unload the map.
3. The start and end position must be within the same tile or the API will fail and return nil.
4. There is a system limit for the maximum of offmesh connections on a single map tile, which is 128.
```lua
connection = AddOffmeshConnection(mapId, x1, y1, z1, x2, y2, z2, isBidirectional[, polygonFlags = 1])
-- mapId (number): The map ID of the offmesh connection (this is the raw map ID when it comes to map phases)
-- x1, y1, z1 (number): The start position of the offmesh connection
-- x2, y2, z2 (number): The end position of the offmesh connection
-- isBidirectional (boolean): Whether the offmesh connection is a two-way road
-- polygonFlags (number): The polygon flags of the offmesh connection (Ground? Water?)
-- connection (string): The result offmesh connection ID
```
[Back to Category](#in-world-navigation)

## FindPath
Calculates a path to navigate from one position to another.
```lua
pointPath, polygonPath = FindPath(mapId, x1, y1, z1, x2, y2, z2[, ignoreWater = true|ignoreFlags = NAV_WATER, searchCapacity = 1024, agentRadius = 0, searchDeviation = 3, isSmooth = false])
-- mapId (number): The map ID
-- x1, y1, z1 (number): The start position
-- x2, y2, z2 (number): The end position
-- ignoreWater (boolean): Whether to avoid walking into water terrain
-- ignoreFlags (number): Alternatively, if you pass a number in place of ignoreWater, you can specify the flags of a navmesh polygon to be ignored
-- searchCapacity (number): This is a combined value to specify the maximum count of waypoints and the size of search node pool. Increase the number if you wish to find longer path, but meanwhile it will also take longer time due to more navmesh polygons to traverse
-- agentRadius (number): The radius of the navigation agent (your character), in yards. To avoid wall collision, you should set the value accordingly. This value can only take 5 in maximum, and any number > 5 will lead to ignorance
-- searchDeviation (number): The deviation to search for the actual position on mesh for start and end positions, in yards
-- isSmooth (boolean): Whether smooth calculation is used
-- pointPath (table): The array of navigation points of the found path. NIL if path is not found
-- polygonPath (table): The array of navigation mesh polygons of the found path. NIL if path is not found
```
[Back to Category](#in-world-navigation)

## GetClosestMeshPolygon
Searches for the closest polygon on mesh in a certain cube with a specific center position.
```lua
polygon[, polygonX, polygonY, polygonZ, polygonDistance] = GetClosestMeshPolygon(mapId, x, y, z, dX, dY, dZ[, ignoreWater = true|ignoreFlags = NAV_WATER])
-- mapId (number): The map ID
-- x, y, z (number): The center position
-- dX, dY, dZ (number): The cube dimensions
-- ignoreWater (boolean): Whether to ignore water areas
-- ignoreFlags (number): Alternatively, if you pass a number in place of ignoreWater, you can specify the flags of a navmesh polygon to be ignored
-- polygon (string): The closest polygon found. NIL if none
-- polygonX, polygonY, polygonZ (number): The closest position on polygon. NIL if none
-- polygonDistance (number): The distance between {x, y, z} and {polygonX, polygonY, polygonZ}
```
[Back to Category](#in-world-navigation)

## GetCurrentMapInfo
Gets the map information of the current player's location.
```lua
mapId, zoneId, subzoneId[, swapIds] = GetCurrentMapInfo()
-- mapId (number): The map ID.
-- zoneId (number): The map zone ID.
-- subzoneId (number): The map subzone ID.
-- swapIds (table - number[]): The array of map IDs that are active swaps of the current map (none if there isn't any)
```
[Back to Category](#in-world-navigation)

## GetMeshAreaCost
Gets the cost of a specific mesh area for polygons in a certain map. By default all polygon areas have the same cost of 1. To get the area of a polygon, see [GetMeshPolygonArea](#getmeshpolygonarea).
```lua
cost = GetMeshAreaCost(mapId, area)
-- mapId (number): The map ID
-- area (number): The polygon area
-- cost (number): The cost of the polygon area
```
[Back to Category](#in-world-navigation)

## GetMeshPolygons
Searches for adjacent mesh polygons starting from a certain polygon, within a certain sphere. Notice that only adjacent polygons that intersect with the sphere will be included.
```lua
polygons = GetMeshPolygons(mapId, startPolygon, x, y, z, radius[, ignoreWater = true|ignoreFlags = NAV_WATER, resultCountMax = 1024])
-- mapId (number): The map ID
-- startPolygon (string): The navigation mesh polygon to start with
-- x, y, z (number): The center position
-- radius (number): The search range, in yards
-- ignoreWater (boolean): Whether to ignore water areas
-- ignoreFlags (number): Alternatively, if you pass a number in place of ignoreWater, you can specify the flags of a navmesh polygon to be ignored
-- resultCountMax (number): The maximum count of polygons to search
-- polygons (table): The found polygons
```
[Back to Category](#in-world-navigation)

## GetMeshPolygonArea
Gets the area of a certain mesh polygon.
```lua
area = GetMeshPolygonArea(mapId, polygon)
-- mapId (number): The map ID
-- polygon (string): The mesh polygon
-- area (number): The area of the polygon (nil if the polygon does not exist)
```
[Back to Category](#in-world-navigation)

## GetMeshPolygonFlags
Gets the flags of a certain mesh polygon. Flags are a combination of terrain flag, passed into other API arguments to indicate that certain polygons are unpassable.
```lua
flags = GetMeshPolygonFlags(mapId, polygon)
-- mapId (number): The map ID
-- polygon (string): The mesh polygon
-- flags (number): The flags of the polygon
```
[Back to Category](#in-world-navigation)

## GetMeshPolygonVertices
Gets the vertices of a certain mesh polygon.
```lua
vertices = GetMeshPolygonVertices(mapId, polygon)
-- mapId (number): The map ID
-- polygon (string): The mesh polygon
-- vertices (table - {x, y, z}[]): The array of vertex positions of the polygon (nil if the polygon does not exist)
```
[Back to Category](#in-world-navigation)

## GetMeshTile
Gets the mesh tile co-ordinate of a certain position. It helps you to locate the corresponding `.mmtile` file in `navmeshes` folder, whose name follows the format "MMMMYYXX.mmtile". e.g. The tile at (31,41) of map 1 should correspond to the map file "00014131.mmtile".
```lua
tileX, tileY[, phaseMapId] = GetMeshTile(mapId, x, y, z)
-- mapId (number): The map ID
-- x, y, z (number): The world position on the map
-- tileX, tileY (number): The corresponding map tile coords (nil if the position is not on the map)
-- phaseMapId (number): The current phase map ID of the tile (nil if there is no phase map applied to the tile)
```
[Back to Category](#in-world-navigation)

## GetOffmeshConnectionDetails
Gets the details of a specific offmesh connection.
```lua
mapId, tileX, tileY, x1, y1, z1, x2, y2, z2, isBidirectional, polygonFlags[, polygon] = GetOffmeshConnectionDetails(connection)
-- connection (string): The offmesh connection ID
-- mapId (number): The map ID of the offmesh connection (Notice that this is the raw map ID when it comes to map phases)
-- tileX, tileY (number): The map tile coords of the offmesh connection (Read more in about this in GetMeshTile())
-- x1, y1, z1 (number): The start position of the offmesh connection
-- x2, y2, z2 (number): The end position of the offmesh connection
-- isBidirectional (boolean): Whether the offmesh connection is a two-way road
-- polygonFlags (number): The polygon flags of the offmesh connection (Ground? Water?)
-- polygon (string): The actual polygon loaded in mesh (nil if the offmesh connection is not loaded in mesh)
```
[Back to Category](#in-world-navigation)

## GetOffmeshConnections
Gets all offmesh connections of a certain map.
```lua
connections = GetOffmeshConnections(mapId)
-- mapId (number): The map ID (it could be the ID of a phase map)
-- connections (table - string[]): The array of offmesh connection IDs
```
[Back to Category](#in-world-navigation)

## IsMapLoaded
Checks if a navigation map is loaded.
```lua
isLoaded = IsMapLoaded(mapId)
-- mapId (number): The map ID
-- isLoaded (boolean): Whether the map is loaded
```
[Back to Category](#in-world-navigation)

## LoadMap
Loads a navigation map. Notice that map loading is synchronous hence may freeze the game for a while.
```lua
success = LoadMap(mapId)
-- mapId (number): The map ID
-- success (boolean): Whether the map is loaded
```
[Back to Category](#in-world-navigation)

## MapExists
Checks whether the files in `navmeshes` for a navigation map exist.
```lua
existence = MapExists(mapId)
-- mapId (number): The map ID
-- existence (boolean): Whether the map files exist
```
[Back to Category](#in-world-navigation)

## RemoveOffmeshConnection
Removes an existing offmesh connection.
```lua
success = RemoveOffmeshConnection(connection)
-- connection (string): The offmesh connection ID
-- success (boolean): Whether the offmesh connection is removed successfully
```
[Back to Category](#in-world-navigation)

## SetMeshAreaCost
Sets the cost of a specific mesh area for polygons.
```lua
success = SetMeshAreaCost(mapId, area, cost)
-- mapId (number): The map ID
-- area (number): The polygon area
-- cost (number): The cost of the polygon area
-- success (boolean): Whether the polygon area cost is updated
```
[Back to Category](#in-world-navigation)

## SetMeshPolygonArea
Sets the area of a certain mesh polygon.
```lua
success = SetMeshPolygonArea(mapId, polygon, area)
-- mapId (number): The map ID
-- polygon (string): The mesh polygon
-- area (number): The area to set
-- success (boolean): Whether the polygon area is updated
```
[Back to Category](#in-world-navigation)

## SetMeshPolygonFlags
Sets the flags of a certain mesh polygon.
```lua
success = SetMeshPolygonFlags(mapId, polygon, flags)
-- mapId (number): The map ID
-- polygon (string): The mesh polygon
-- flags (number): The flags of the polygon
-- success (boolean): Whether the polygon flags are updated
```
[Back to Category](#in-world-navigation)

## UnloadMap
Unloads a navigation map. This is useful to free up more memory when you don't need the map data.
```lua
success = UnloadMap(mapId)
-- mapId (number): The map ID
-- success (boolean): Whether the map is unloaded
```
[Back to Category](#in-world-navigation)

# In-World (Object)
The following in-world API functions read information from a WoW object. Our engine assigns a unique ID (string) for each of them, wbich can be passed in as another API's argument. Any API arguments that require [UnitId](https://wowpedia.fandom.com/wiki/UnitId) can also take our object ID, and vice versa. Different types of object follow the inheritance model as below.
- object: The base type of any WoW object
    - unit: A living object with health bar
        - player: A character
    - gameObject: A world object rendered from server
    - dynamicObject: A world object that is usually short-lived rendered from server

[Back to Table of Contents](#squirtbot-api)

## GameObjectIsUsable
Checks if a game object is usable (right-clickable).
```lua
usable = GameObjectIsUsable(gameObject, checkDistance)
-- gameObject (string): The object ID
-- checkDistance (boolean): Whether to check the interaction distance
-- usable (boolean)
```
[Back to Category](#in-world-object)

## GameObjectType
Gets the sub type of a game object.
```lua
typeId, typeName = GameObjectType(gameObject)
-- gameObject (string): The object ID
-- typeId (number): The ID of the sub type.
-- typeName (string): The name of the sub type.
```
[Back to Category](#in-world-object)

## GetActiveMover
Gets the currently controlled unit.
```lua
activeMover = GetActiveMover()
-- activeMover (string): The object ID of the currently controlled unit (nil if there is none)
```
[Back to Category](#in-world-object)

## GetAnglesBetweenObjects
Gets the angles (facing & pitch) between two objects.
```lua
facing, pitch = GetAnglesBetweenObjects(object1, object2)
-- object1 (string): The ID of object 1
-- object2 (string): The ID of object 2
-- facing (number): The horizontal angle from object 1 to object 2, in radian
-- pitch (number): The vertical angle from object 1 to object 2, in radian
```
[Back to Category](#in-world-object)

## GetCorpsePosition
Gets the position of the corpse if the current character is dead.
```lua
x, y, z = GetCorpsePosition()
-- x, y, z (number): The co-ordinate of the current character's corpse (nil if not dead)
```
[Back to Category](#in-world-object)

## GetDistanceBetweenObjects
Gets the 3D distance between two objects.
```lua
distance = GetDistanceBetweenObjects(object1, object2)
-- object1 (string): The ID of object 1
-- object2 (string): The ID of object 2
-- distance (number): The distance in between (nil if either object does not exist)
```
[Back to Category](#in-world-object)

## GetDistanceBetweenPositions
Gets the 3D distance between two positions.
```lua
distance = GetDistanceBetweenPositions(x1, y1, z1, x2, y2, z2)
-- x1, y1, z1 (number): The co-ordinate of position 1
-- x2, y2, z2 (number): The co-ordinate of position 2
-- distance (number): The distance in between
```
[Back to Category](#in-world-object)

## GetObject
Gets the ID of a specific object.
```lua
id = GetObject(object)
-- object (string): The object ID or unit ID
-- id (string): The object ID (nil if the object does not exist)
```
[Back to Category](#in-world-object)

## GetObjectWithGUID
Gets the ID of a specific object by its [GUID](https://wowpedia.fandom.com/wiki/GUID).
```lua
id = GetObjectWithGUID(guid)
-- guid (string): The object's GUID
-- id (string): The object's ID (nil if the object with GUID does not exist)
```
[Back to Category](#in-world-object)

## GetPositionBetweenObjects
Gets the position at a certain distance from object 1 to object 2.
```lua
x, y, z = GetPositionBetweenObjects(object1, object2, distance)
-- object1 (string): The ID of object 1
-- object2 (string): The ID of object 2
-- distance (number): The distance
-- x, y, z (number): The position co-ordinate
```
[Back to Category](#in-world-object)

## GetPositionBetweenPositions
Gets the position at a certain distance from position 1 to position 2.
```lua
x, y, z = GetPositionBetweenPositions(x1, y1, z1, x2, y2, z2, distance)
-- x1, y1, z1 (number): The co-ordinate of position 1
-- x2, y2, z2 (number): The co-ordinate of position 2
-- distance (number): The distance
-- x, y, z (number): The position co-ordinate
```
[Back to Category](#in-world-object)

## GetPositionFromPosition
Gets the position from a specific position.
```lua
x, y, z = GetPositionFromPosition(x1, y1, z1, distance, facing, pitch)
-- x1, y1, z1 (number): The co-ordinate of the start position
-- distance (number): The distance from the start position
-- facing (number): The horizontal angle from the start position, in radian
-- pitch (number): The vertical angle from the start position, in radian
-- x, y, z (number): The target position co-ordinate
```
[Back to Category](#in-world-object)

## SetMouseoverObject
Sets the object of mouseover, pointed by mouse cursor.
```lua
SetMouseoverObject(object)
-- object (string): The ID of the mouseover object
```
[Back to Category](#in-world-object)

## ObjectAnimationState
Gets the animation state of an object.
```lua
state = ObjectAnimationState(object)
-- object (string): The ID of the object
-- state (number): The animation state, usually representing "bobbing" (nil if the object does not exist)
``` 
[Back to Category](#in-world-object)

## ObjectCreator (aka UnitCreator)
Gets the creator of an object.
```lua
creator = ObjectCreator(object)
-- object (string): The ID of the object
-- creator (string): The ID of the object creator (nil if the object or its creator does not exist)
```
[Back to Category](#in-world-object)

## ObjectDynamicFlags
Gets the dynamic flags of an object, which is actually the "CGObjectData__m_dynamicFlags" offset.
```lua
flags = ObjectDynamicFlags(object)
-- object (string): The ID of the object
-- flags (number): The dynamic flags of the object (nil if the object does not exist)
```
[Back to Category](#in-world-object)

## ObjectExists
Checks whether an object exists in memory.
```lua
existence = ObjectExists(object)
-- object (string): The ID of the object
-- existence (boolean): Whether the object exists
```
[Back to Category](#in-world-object)

## ObjectFacing
Gets the horizontal rotation of an object, in radian.
```lua
facing = ObjectFacing(object)
-- object (string): The ID of the object
-- facing (number): The horizontal rotation of the object, in radian (nil if the object does not exist)
```
[Back to Category](#in-world-object)

## ObjectField (aka ObjectDescriptor)
Gets the value of a specific field (previously descriptor) of an object.
```lua
value = ObjectField(object, offset, type)
-- object (string): The ID of the object
-- offset (number): The memory offset of the field, in bytes (see GetObjectDescriptorsTable() and GetObjectFieldsTable())
-- type (number): The field value type (see GetValueTypesTable())
-- value (boolean | number | string): The field value (nil if the object does not exist)
```
[Back to Category](#in-world-object)

## ObjectHeight
Gets the display height of the object.
```lua
height = ObjectHeight(object)
-- object (string): The ID of the object
-- height (number): The display height of the object (nil if the object does not exist)
```
[Back to Category](#in-world-object)

## ObjectId
Gets the numeric ID of an object, which is part of the object GUID.
```lua
id = ObjectId(object)
-- object (string): The ID of the object.
-- id (number): The number ID of the object (nil if the object does not exist)
```
[Back to Category](#in-world-object)

## ObjectIsBehind
Checks if an object is behind another object.
```lua
isBehind = ObjectIsBehind(object1, object2)
-- object1 (string): The ID of object 1
-- object2 (string): The ID of object 2
-- isBehind (number): Whether object 1 is behind object 2 (nil if either of the objects does not exist)
```
[Back to Category](#in-world-object)

## ObjectIsFacing
Checks if an object is facing another object.
```lua
isFacing = ObjectIsFacing(object1, object2[, tolerance = PI/2])
-- object1 (string): The ID of object 1
-- object2 (string): The ID of object 2
-- tolerance (number): The facing check tolerance, in radian (if the angle in between goes beyond that, the API returns false)
-- isFacing (boolean): Whether object 1 is facing object 2
```
[Back to Category](#in-world-object)

## ObjectIsQuestObjective
Checks whether an object is tracked in current quests (usually glowing). This is a RETAIL-only API.
```lua
isInQuestCache = ObjectIsQuestObjective(object, unknown)
-- object (string): The ID of the object
-- unknown (boolean): An unknown flag
-- isInQuestCache (boolean): Whether the object is tracked in the quest cache
```
[Back to Category](#in-world-object)

## ObjectIsType
Checks if an object is of a specific type, which can be a value from [GetObjectTypeFlagsTable](#getobjecttypeflagstable).
```lua
isOrNot = ObjectIsType(object, type)
-- object (string): The ID of the object
-- type (number): The object type to check
-- isOrNot (boolean): Whether the object is of the type
```
[Back to Category](#in-world-object)

## ObjectPosition
Gets the world position of an object.
```lua
x, y, z = ObjectPosition(object)
-- object (string): The ID of the object
-- x, y, z (number): The position co-ordinate of the object
```
[Back to Category](#in-world-object)

## ObjectQuestGiverStatus
Gets the quest giver status of a specific object, which can be a value from [GetObjectQuestGiverStatusesTable](#getobjectquestgiverstatusestable).
```lua
status = ObjectQuestGiverStatus(object)
-- object (string): The ID of the object
-- status (number): The status of the object
```
[Back to Category](#in-world-object)

## ObjectQuests
Gets the IDs of the related quests of an object. This is a RETAIL-only API.
```lua
id1, id2, ... = ObjectQuests(object)
-- object (string): The ID of the object
-- id ... (number): The IDs of the related quests
```
[Back to Category](#in-world-object)

## ObjectRelativePosition
Gets the relative world position of an object to its "carrier".
```lua
x, y, z = ObjectRelativePosition(object)
-- object (string): The ID of the object
-- x, y, z (number): The relative position co-ordinate of the object
```
[Back to Category](#in-world-object)

## ObjectRelativeFacing
Gets the relative rotation of an object to its "carrier", in radian.
```lua
facing = ObjectRelativeFacing(object)
-- object (string): The ID of the object
-- facing (number): The relative facing of the object, in radian
```
[Back to Category](#in-world-object)

## ObjectScale
Gets the scale of an object.
```lua
scale = ObjectScale(object)
-- object (string): The ID of the object
-- scale (number): The scale of the object
```
[Back to Category](#in-world-object)

## ObjectTypeFlags
Gets the type flags of an object, which should be one of [GetObjectTypeFlagsTable](#getobjecttypeflagstable).
```lua
typeFlags = ObjectTypeFlags(object)
-- object (string): The ID of the object
-- typeFlags (number): The type flags of the object
```
[Back to Category](#in-world-object)

## UnitBoundingRadius
Gets the bounding radius of an unit.
```lua
radius = UnitBoundingRadius(unit)
-- unit (string): The ID of the unit object
-- radius (number): The bounding radius of the object, in yards
```
[Back to Category](#in-world-object)

## UnitCasting
Gets the casting spell info of a specific unit. Similar to Blizzard's `UnitCastingInfo` but it adds additional information about the spell target.
```lua
spellId, target, startTime, endTime = UnitCasting(unit)
-- unit (string): The ID of the unit object
-- spellId (number): The casting spell ID (nil if the unit or spell does not exist)
-- target (string): The ID of the casting target unit
-- startTime (number): The start time of the casting spell
-- endTime (number): The end time of the casting spell
```
[Back to Category](#in-world-object)

## UnitCastingTarget
Gets the casting spell target of a specific unit.
```lua
target = UnitCastingTarget(unit)
-- unit (string): The ID of the unit object
-- target (string): The ID of the casting target unit (nil if the unit or casting spell does not exist)
```
[Back to Category](#in-world-object)

## UnitChannel
Gets the channel spell info of a unit. Similar to Blizzard's `UnitChannelInfo` but it adds additional information about the spell target.
```lua
spellId, target, startTime, endTime = UnitChannel(unit)
-- unit (string): The ID of the unit object
-- spellId (number): The channel spell ID (nil if the unit or spell does not exist)
-- target (string): The ID of the casting target unit
-- startTime (number): The start time of the casting spell
-- endTime (number): The end time of the casting spell
```
[Back to Category](#in-world-object)

## UnitCombatReach
Gets the combat reach of a unit.
```lua
combatReach = UnitCombatReach(unit)
-- unit (string): The ID of the unit object
-- combatReach (number): The combat reach of the unit, in yards (nil if the unit does not exist)
```
[Back to Category](#in-world-object)

## UnitCreatureTypeId
Gets the ID of the creature type of a specific unit.
```lua
typeId = UnitCreatureTypeId(unit)
-- unit (string): The ID of the unit object
-- typeId (number): The ID of the unit's creature type (nil if the unit does not exist)
```
[Back to Category](#in-world-object)

## UnitCreatureFamilyId
Gets the ID of the family of a specific unit.
```lua
familyId = UnitCreatureFamilyId(unit)
-- unit (string): The ID of the unit object
-- familyId (number): The ID of the unit's creature family (nil if the unit does not exist)
```
[Back to Category](#in-world-object)

## UnitCreatureField
Gets a field value of the creature cache struct of a specific unit.
```lua
value = UnitCreatureField(unit, offset, type)
-- unit (string): The ID of the unit object
-- offset (number): The offset of the field in creature cache, in bytes
-- type (number): The field value type (see GetValueTypesTable())
-- value (boolean | number | string): The actual field value (nil if the unit does not exist)
```
[Back to Category](#in-world-object)

## UnitFlags
Gets the flags of a specific unit, which is located at the descriptor "CGUnitData__flags".
```lua
flags = UnitFlags(unit)
-- unit (string): The ID of the unit object
-- flags (number): The flags value (nil if the unit does not exist)
```
[Back to Category](#in-world-object)

## UnitIsLootable
Checks whether a unit is lootable.
```lua
lootable = UnitIsLootable(unit)
-- unit (string): The ID of the unit object
-- lootable (boolean): Whether the unit is lootable
```
[Back to Category](#in-world-object)

## UnitIsMounted
Checks whether a unit is mounted.
```lua
mounted = UnitIsMounted(unit)
-- unit (string): The ID of the unit object
-- mounted (boolean): Whether the unit is mounted
```
[Back to Category](#in-world-object)

## UnitIsSkinnable
Checks whether a unit is skinnable.
```lua
mounted = UnitIsSkinnable(unit)
-- unit (string): The ID of the unit object
-- mounted (boolean): Whether the unit is skinnable
```
[Back to Category](#in-world-object)

## UnitMovementField
Gets a field value of the movement struct of a specific unit.
```lua
value = UnitMovementField(unit, offset, type)
-- unit (string): The ID of the unit object
-- offset (number): The offset of the field in movement struct, in bytes
-- type (number): The field value type (see GetValueTypesTable())
-- value (boolean | number | string): The actual field value (nil if the unit does not exist)
```
[Back to Category](#in-world-object)

## UnitMovementFlags
Gets the flags in the movement struct of a specific unit, which indicates its movement status.
```lua
flags = UnitMovementFlags(unit)
-- unit (string): The ID of the unit object
-- flags (number): The movement flags of the unit (nil if the unit does not exist)
```
[Back to Category](#in-world-object)

## UnitPitch
Gets the pitch (vertical angle) of a unit, in radian.
```lua
pitch = UnitPitch(unit)
-- unit (string): The ID of the unit object
-- pitch (number): The pitch of the unit (nil if the unit does not exist)
```
[Back to Category](#in-world-object)

## UnitSkinningType
Gets the type of a skinnable unit.
```lua
skinningType = UnitSkinningType(unit)
-- unit (string): The ID of the unit object
-- skinningType (number): The type ID of the skinnable unit (nil if the unit does not exist)
```
[Back to Category](#in-world-object)

## UnitTarget
Gets the target unit of a specific unit.
```lua
target = UnitTarget(object)
-- unit (string): The ID of the unit object
-- target (string): The ID of the unit's target unit object (nil if the unit or its target unit does not exist)
```
[Back to Category](#in-world-object)

## UnitTransport
Gets the transport object on which a specific unit stands.
```lua
transport = UnitTransport(unit)
-- unit (string): The ID of the unit object
-- transport (string): The ID of the unit's transport object (nil if the unit or its transport does not exist)
```
[Back to Category](#in-world-object)

# In-World (Object Manager)
The following in-world API functions read all WoW objects living in memory. The functions are implemented in pairs, of which one is GetXXXCount() that needs to be called first upon each frame to cache all current objects and another is GetXXXWithIndex() that is used to retrieve any one of them.

[Back to Table of Contents](#squirtbot-api)

## GetAreaTriggerCount
Gets the count of specific area triggers, optionally within a certain range.
```lua
count = GetAreaTriggerCount([center | x, y, z][, range])
-- center (string): The ID of the center object
-- x, y, z (number): The co-ordinate of the center position
-- range (number): The radius of the range, in yards
-- count (number): The count of area triggers within the range
```
[Back to Category](#in-world-object-manager)

## GetAreaTriggerWithIndex
Gets a specific area trigger in the previously saved cached objects from [GetAreaTriggerCount](#getareatriggercount).
```lua
areaTrigger = GetAreaTriggerWithIndex(index)
-- index (number): The index of the cached area trigger, starting from 1
-- areaTrigger (string): The ID of the area trigger
```
[Back to Category](#in-world-object-manager)

## GetDynamicObjectCount
Gets the count of specific dynamic objects, optionally within a certain range.
```lua
count = GetDynamicObjectCount([center | x, y, z][, range])
-- center (string): The ID of the center object
-- x, y, z (number): The co-ordinate of the center position
-- range (number): The radius of the range, in yards
-- count (number): The count of dynamic objects within the range
```
[Back to Category](#in-world-object-manager)

## GetDynamicObjectWithIndex
Gets a specific dynamic object in the previously saved cached objects from [GetDynamicObjectCount](#getdynamicobjectcount).
```lua
dynamicObject = GetDynamicObjectWithIndex(index)
-- index (number): The index of the cached dynamic object, starting from 1
-- dynamicObject (string): The ID of the dynamic object
```
[Back to Category](#in-world-object-manager)

## GetGameObjectCount
Gets the count of specific game objects, optionally within a certain range.
```lua
count = GetGameObjectCount([center | x, y, z][, range])
-- center (string): The ID of the center object
-- x, y, z (number): The co-ordinate of the center position
-- range (number): The radius of the range, in yards
-- count (number): The count of game objects within the range
```
[Back to Category](#in-world-object-manager)

## GetGameObjectWithIndex
Gets a specific game object in the previously saved cached objects from [GetGameObjectCount](#getgameobjectcount).
```lua
gameObject = GetGameObjectWithIndex(index)
-- index (number): The index of the cached game object, starting from 1
-- gameObject (string): The ID of the game object
```
[Back to Category](#in-world-object-manager)

## GetNpcCount
Gets the count of specific NPCs (non-player unit), optionally within a certain range.
```lua
count = GetNpcCount([center | x, y, z][, range][, rangeOption])
-- center (string): The ID of the center object
-- x, y, z (number): The co-ordinate of the center position
-- range (number): The radius of the range, in yards
-- rangeOption (number): Specifies the meaning of range, which is one of the several values given below
{
    direct = 0; -- raw distance between myself and the unit
    target_reach_only = 1; -- consider only the unit reach on top of the range
    both_reaches = 2; -- consider both reaches of myself and the unit on top of the range
    both_melee_reaches = 3; -- consider the unit as a melee target on top of the range
    both_melee_reaches_with_movement = 4; -- consider the unit as a moving melee target on top of the range
}
-- count (number): The count of NPCs within the range
```
[Back to Category](#in-world-object-manager)

## GetNpcWithIndex
Gets a specific NPC (non-player unit) in the previously saved cached objects from [GetNpcCount](#getnpccount).
```lua
npc = GetNpcWithIndex(index)
-- index (number): The index of the cached NPC, starting from 1
-- npc (string): The ID of the NPC
```
[Back to Category](#in-world-object-manager)

## GetObjectCount
Gets the count of all WoW objects as well as the changes compared to the last call. Notice that a better performance is given when you refer to a more filtered version such as [GetNpcCount](#getnpccount).
```lua
count, isUpdated, addedObjects, removedObjects = GetObjectCount()
-- count (number): The count of all WoW objects
-- isUpdated (boolean): Whether the WoW objects experience any changes from the last call
-- addedObjects (table): The IDs of added WoW objects
-- removedObjects (table): The IDs of removed WoW objects
```
[Back to Category](#in-world-object-manager)

## GetObjectWithIndex
Gets a specific WoW object by its index in the previously saved cached objects from [GetObjectCount](#getobjectcount).
```lua
object = GetObjectWithIndex(index)
-- index (number): The index of the cached object, starting from 1
-- object (string): The ID of the object
```
[Back to Category](#in-world-object-manager)

## GetPlayerCount
Gets the count of specific players, optionally within a certain range.
```lua
count = GetPlayerCount([center | x, y, z][, range][, rangeOption])
-- center (string): The ID of the center object
-- x, y, z (number): The co-ordinate of the center position
-- range (number): The radius of the range, in yards
-- rangeOption (number): Specifies the meaning of range, which is one of the several values given below
{
    direct = 0; -- raw distance between myself and the unit
    target_reach_only = 1; -- consider only the unit reach on top of the range
    both_reaches = 2; -- consider both reaches of myself and the unit on top of the range
    both_melee_reaches = 3; -- consider the unit as a melee target on top of the range
    both_melee_reaches_with_movement = 4; -- consider the unit as a moving melee target on top of the range
}
-- count (number): The count of players within the range
```
[Back to Category](#in-world-object-manager)

## GetPlayerWithIndex
Gets a specific player in the previously saved cached objects from [GetPlayerCount](#getplayercount).
```lua
player = GetPlayerWithIndex(index)
-- index (number): The index of the cached player, starting from 1
-- player (string): The ID of the player
```
[Back to Category](#in-world-object-manager)

# In-World (Spell)
The following in-world API functions provide extensions for spells.

[Back to Table of Contents](#squirtbot-api)

## CancelPendingSpell
Cancels the pending spell on the cursor.
```lua
CancelPendingSpell()
```
[Back to Category](#in-world-spell)

## GetActiveSpellCount
Gets the count of active spells, which will be cached in memory in the current frame.
```lua
count = GetActiveSpellCount()
-- count (number): The count of active spells
```
[Back to Category](#in-world-spell)

## GetActiveSpellWithIndex
Gets the details of a specific active spell, previously stored by [GetActiveSpellCount](#getactivespellcount)
```lua
spellId, auraId, caster, sourceX, sourceY, sourceZ, targetX, targetY, targetZ, facing = GetActiveSpellWithIndex(index)
-- index (number): The index of the cached active spell, starting from 1
-- spellId (number): The ID of the spell
-- auraId (number): The ID of the aura spell
-- caster (string): The ID of the caster unit
-- sourceX, sourceY, sourceZ (number): The source position co-ordinate of the spell cast
-- targetX, targetY, targetZ (number): The target position co-ordinate of the spell cast
-- facing (number): The horizontal angle of the spell object, in radian
```
[Back to Category](#in-world-spell)

## GetAuraCount
Gets the count of the auras on a unit, which will be cached in memory in the current frame.
```lua
count = GetAuraCount(unit, [spellId])
-- unit (string): The ID of the unit
-- spellId (number): Specifies the ID of the aura spell
-- count (number): The count of auras found
```
[Back to Category](#in-world-spell)

## GetAuraWithIndex
Gets the spell ID of a specific aura, previously stored by [GetAuraCount](#getauracount).
```lua
spellId = GetAuraWithIndex(index)
-- index (number): The index of the cached aura, starting from 1
-- spellId (number): The ID of the aura spell when detailed is false
```
[Back to Category](#in-world-spell)

## GetMissileCount
Gets the count of missile spells around, which will be cached in memory in the current frame.
```lua
count = GetMissileCount()
-- count (number): The missile count
```
[Back to Category](#in-world-spell)

## GetMissileWithIndex
Gets the details of a specific missile spells, previously stored by [GetMissileCount](#getmissilecount).
```lua
spellId, spellVisualId, x, y, z, sourceObject, sourceX, sourceY, sourceZ, targetObject, targetX, targetY, targetZ = GetMissileWithIndex(index)
-- spellId (number): The ID of the missile spell
-- spellVisualId (number): The visual ID of the missile spell
-- x, y, z (number): The co-ordinate of the current missile position
-- sourceObject (string): The ID of the source object
-- sourceX, sourceY, sourceY (number): The co-ordinate of the source position
-- targetObject (string): The ID of the target object
-- targetX, targetY, targetY (number): The co-ordinate of the target position
```
[Back to Category](#in-world-spell)

## GetPendingSpell
Gets the ID of the pending spell.
```lua
spellId = GetPendingSpell()
-- spellId (number): The ID of the pending spell (nil if no spell is pending)
```
[Back to Category](#in-world-spell)

# In-World (State)
The following in-world API functions read world states.

[Back to Table of Contents](#squirtbot-api)

## GetCurrentAccount
Gets the current WoW account name, which is the same as the WTF sub folder name.
```lua
account = GetCurrentAccount()
-- account (string): The account name
```
[Back to Category](#in-world-state)

## GetCurrentTime
Gets the current WoW calendar time.
```lua
time1, time2, time3, time4, time5, time6 = GetCurrentTime()
-- time1-6 (number): The number segments of the calendar time
```
[Back to Category](#in-world-state)

# In-World (Vision)
The following in-world API functions provide vision information.

[Back to Table of Contents](#squirtbot-api)

## GetCameraPosition
Gets the position of the camera.
```lua
x, y, z = GetCameraPosition()
-- x, y, z (number): The co-ordinate of the camera position
```
[Back to Category](#in-world-vision)

## ScreenToWorld
Projects a screen NDC position to a world position, along with a world object if any.
```lua
x, y, z[, object] = ScreenToWorld(screenX, screenY)
-- screenX, screenY (number): The co-ordinate of the screen NDC position (ranging from 0.0 to 1.0)
-- x, y, z (number): The co-ordinate of the world position
-- object (string): The ID of the world object at the position, if any
```
[Back to Category](#in-world-vision)

## TraceLine
Checks ray cast intersection from a certain position to another.
```lua
x, y, z = TraceLine(x1, y1, z1, x2, y2, z2, flags)
-- x1, y1, z1 (number): The co-ordinate of position 1
-- x2, y2, z2 (number): The co-ordinate of position 2
-- flags (number): The flags of surface facets the ray cast should be considered as "intersected", which can be any sum of the followings:
{
    None                = 0x00000000,
    DoodadCollision     = 0x00000001,
    DoodadRender        = 0x00000002,
    WmoCollision        = 0x00000010,
    WmoRender           = 0x00000020,
    WmoNoCamCollision   = 0x00000040,
    Terrain             = 0x00000100,
    IgnoreWmoDoodad     = 0x00002000,
    LiquidWaterWalkable = 0x00010000,
    LiquidAll           = 0x00020000,
    Cull                = 0x00080000,
    EntityCollision     = 0x00100000,
    EntityRender        = 0x00200000,
    Collision           = DoodadCollision | WmoCollision | Terrain | EntityCollision,
    LineOfSight         = WmoCollision | EntityCollision
}
-- x, y, z (number): The co-ordinate of the first intersection position of the ray cast (nil if no intersection is found)
```
[Back to Category](#in-world-vision)

## WorldToScreen
Projects a world position to the screen NDC position.
```lua
isOnScreen, screenX, screenY = WorldToScreen(object | x, y, z)
-- object (string): The ID of an object whose position will be projected
-- x, y, z (number): The co-ordinate of the world position
-- isOnScreen (boolean): Whether the object is within the screen frame
-- screenX, screenY (number): The screen NDC position
```
[Back to Category](#in-world-vision)
