--[[
=============================================================================================================================================================
Antares' Limitless Interaction Caller Engine
A Lua system to easily create highly performant checks and interactions, between any type of objects.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
=============================================================================================================================================================
Overview
=============================================================================================================================================================
To install this library, copy it into an empty script file in your map.
To enable debug mode, import "CustomTooltip.toc" and "CustomTooltip.fdf".
There are only few values to be set in the config. First, change the MAP_CREATORS field to your name.
The main work is creating actors and their interaction functions. Let's say we want to create a new spell. It should create multiple orbs at different locations
that each have an aura around them. In normal GUI/JASS/Lua, we would need a periodic timer, loop over our orbs, GroupEnumUnitsInRange to find units affected,
filter out the units that aren't eligible, and then run our code. ALICE takes care of the entire control structure of our code with a network of its main
internal object, the actor. The task of writing the correct control structure then transforms into assigning the actors the correct properties on creation.
=============================================================================================================================================================
What is an actor?
=============================================================================================================================================================
An actor is a class that is attached to any type of object and interacts with other actors that were added to the system. Two actors form a pair. Actors carry
identifiers and function interfaces determining their interactions and with which other actors they form a pair.
When two actors in a pair interact, an interaction function that you can specify will be called. After the pair's interaction is calculated, the next
interaction is placed in the queue. It is up to you to set the time interval between the two interactions. This is done via the return value of the
interactionFunc. The interactionFunc uses two input arguments which specify the "hosts" of the two actors; the objects the actors are attached to. Hosts can
be any type of object - a unit, an item, a class, a player - whatever thing you want the actor to represent. A host can also be a string, an integer, or nil,
which could represent some kind of global effect.
Actors can both receive and initiate pairs. When a new actor is created, it checks if it should initiate a pair with each already existing actor and all
existing actors will check if they should initiate a pair themselves. Two-way pairs are not possible.
ALICE will automatically retrieve the position of an actor, if it's applicable. If it can't, it will create it as a global actor.
=============================================================================================================================================================
Schematic
=============================================================================================================================================================
PairingCheck β Identifier
Identifier β PairingCheck
β β β
Object A β Actor A Pair Actor B β Object B
β
*InteractionFunc β β
β β β
Object A β Object B β
β β
Time until next call β
*inherited from the actor initiating the pair.
=============================================================================================================================================================
How to create an actor
=============================================================================================================================================================
To create an actor, do ALICE_Create(host, identifier, interactionFunc). There are additional values you can set, but they're not important for getting started.
-----host-----
Any type of object which the actor is supposed to represent. You can create multiple actors for one host.
-----identifier-----
A string or string sequence that can be used in a filter to identify different types of actors. Examples: "hero", "missile", or {"unit", "hero", "human", "Hpal"}.
-----interactionFunc-----
A function or table that specifies the function that is called when this object interacts with another object. If a function is passed, the actor will pair with
everything (not recommended!). With a table, you can specify different interaction functions for different types of objects. For example: {milk = Drink, apple = Eat},
will use the Drink function for all actors with the "milk" identifier and the Eat function for all actors with the "apple" identifier.
Actors will only pair with other actors for which an interactionFunc exists, but you can use the "other" keyword to declare an interactionFunc that is used for
all actors not included in your list.
-----flags-----
Flags are an optional fourth input argument. They are discussed in the advanced tutorial.
-----ALICE_CreateFromClass-----
ALICE_CreateFromClass(class) creates an actor for a class and retrieves all input arguments directly from that class.
=============================================================================================================================================================
How to create an interaction function
=============================================================================================================================================================
An interactionFunc must have two input arguments of any type, specifying the objects (not the actors), and one return value of type number, specifying the time
until the next interaction (in seconds). The object that is the source of the interaction func will always be passed as the first argument.
Within the interaction func, you have access to the Pair API.
Example:
function Explode(whichMine, whichUnit)
local dist = ALICE_PairGetDistance()
if dist < 100 then
whichMine:destroy()
KillUnit(whichUnit)
end
return (dist - 100)/300
end
]]
Name | Type | is_array | initial_value |
---@diagnostic disable: undefined-global
if Debug then Debug.beginFile 'TotalInitialization' end
--[[ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Total Initialization version 5.3.1
Created by: Bribe
Contributors: Eikonium, HerlySQR, Tasyen, Luashine, Forsakn
Inspiration: Almia, ScorpioT1000, Troll-Brain
Hosted at: https://github.com/BribeFromTheHive/Lua/blob/master/TotalInitialization.lua
Debug library hosted at: https://www.hiveworkshop.com/threads/debug-utils-ingame-console-etc.330758/
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ]]
---Calls the user's initialization function during the map's loading process. The first argument should either be the init function,
---or it should be the string to give the initializer a name (works similarly to a module name/identically to a vJass library name).
---
---To use requirements, call `Require.strict 'LibraryName'` or `Require.optional 'LibraryName'`. Alternatively, the OnInit callback
---function can take the `Require` table as a single parameter: `OnInit(function(import) import.strict 'ThisIsTheSameAsRequire' end)`.
---
-- - `OnInit.global` or just `OnInit` is called after InitGlobals and is the standard point to initialize.
-- - `OnInit.trig` is called after InitCustomTriggers, and is useful for removing hooks that should only apply to GUI events.
-- - `OnInit.map` is the last point in initialization before the loading screen is completed.
-- - `OnInit.final` occurs immediately after the loading screen has disappeared, and the game has started.
---@class OnInit
--
--Simple Initialization without declaring a library name:
---@overload async fun(initCallback: Initializer.Callback)
--
--Advanced initialization with a library name and an optional third argument to signal to Eikonium's DebugUtils that the file has ended.
---@overload async fun(libraryName: string, initCallback: Initializer.Callback, debugLineNum?: integer)
--
--A way to yield your library to allow other libraries in the same initialization sequence to load, then resume once they have loaded.
---@overload async fun(customInitializerName: string)
OnInit = {}
---@alias Initializer.Callback fun(require?: Requirement | {[string]: Requirement}):...?
---@alias Requirement async fun(reqName: string, source?: table): unknown
-- `Require` will yield the calling `OnInit` initialization function until the requirement (referenced as a string) exists. It will check the
-- global API (for example, does 'GlobalRemap' exist) and then check for any named OnInit resources which might use that same string as its name.
--
-- Due to the way Sumneko's syntax highlighter works, the return value will only be linted for defined @class objects (and doesn't work for regular
-- globals like `TimerStart`). I tried to request the functionality here: https://github.com/sumneko/lua-language-server/issues/1792 , however it
-- was closed. Presumably, there are other requests asking for it, but I wouldn't count on it.
--
-- To declare a requirement, use: `Require.strict 'SomeLibrary'` or (if you don't care about the missing linting functionality) `Require 'SomeLibrary'`
--
-- To optionally require something, use any other suffix (such as `.optionally` or `.nonstrict`): `Require.optional 'SomeLibrary'`
--
---@class Require: { [string]: Requirement }
---@overload async fun(reqName: string, source?: table): string
Require = {}
do
local library = {} --You can change this to false if you don't use `Require` nor the `OnInit.library` API.
--CONFIGURABLE LEGACY API FUNCTION:
---@param _ENV table
---@param OnInit any
local function assignLegacyAPI(_ENV, OnInit)
OnGlobalInit = OnInit; OnTrigInit = OnInit.trig; OnMapInit = OnInit.map; OnGameStart = OnInit.final --Global Initialization Lite API
--OnMainInit = OnInit.main; OnLibraryInit = OnInit.library; OnGameInit = OnInit.final --short-lived experimental API
--onGlobalInit = OnInit; onTriggerInit = OnInit.trig; onInitialization = OnInit.map; onGameStart = OnInit.final --original Global Initialization API
--OnTriggerInit = OnInit.trig; OnInitialization = OnInit.map --Forsakn's Ordered Indices API
end
--END CONFIGURABLES
local _G, rawget, insert =
_G, rawget, table.insert
local initFuncQueue = {}
---@param name string
---@param continue? function
local function runInitializers(name, continue)
--print('running:', name, tostring(initFuncQueue[name]))
if initFuncQueue[name] then
for _,func in ipairs(initFuncQueue[name]) do
coroutine.wrap(func)(Require)
end
initFuncQueue[name] = nil
end
if library then
library:resume()
end
if continue then
continue()
end
end
local function initEverything()
---@param hookName string
---@param continue? function
local function hook(hookName, continue)
local hookedFunc = rawget(_G, hookName)
if hookedFunc then
rawset(_G, hookName,
function()
hookedFunc()
runInitializers(hookName, continue)
end
)
else
runInitializers(hookName, continue)
end
end
hook(
'InitGlobals',
function()
hook(
'InitCustomTriggers',
function()
hook('RunInitializationTriggers')
end
)
end
)
hook(
'MarkGameStarted',
function()
if library then
for _,func in ipairs(library.queuedInitializerList) do
func(nil, true) --run errors for missing requirements.
end
for _,func in pairs(library.yieldedModuleMatrix) do
func(true) --run errors for modules that aren't required.
end
end
OnInit = nil
Require = nil
end
)
end
---@param initName string
---@param libraryName string | Initializer.Callback
---@param func? Initializer.Callback
---@param debugLineNum? integer
---@param incDebugLevel? boolean
local function addUserFunc(initName, libraryName, func, debugLineNum, incDebugLevel)
if not func then
---@cast libraryName Initializer.Callback
func = libraryName
else
assert(type(libraryName) == 'string')
if debugLineNum and Debug then
Debug.beginFile(libraryName, incDebugLevel and 3 or 2)
Debug.data.sourceMap[#Debug.data.sourceMap].lastLine = debugLineNum
end
if library then
func = library:create(libraryName, func)
end
end
assert(type(func) == 'function')
--print('adding user func: ' , initName , libraryName, debugLineNum, incDebugLevel)
initFuncQueue[initName] = initFuncQueue[initName] or {}
insert(initFuncQueue[initName], func)
if initName == 'root' or initName == 'module' then
runInitializers(initName)
end
end
---@param name string
local function createInit(name)
---@async
---@param libraryName string --Assign your callback a unique name, allowing other OnInit callbacks can use it as a requirement.
---@param userInitFunc Initializer.Callback --Define a function to be called at the chosen point in the initialization process. It can optionally take the `Require` object as a parameter. Its optional return value(s) are passed to a requiring library via the `Require` object (defaults to `true`).
---@param debugLineNum? integer --If the Debug library is present, you can call Debug.getLine() for this parameter (which should coincide with the last line of your script file). This will neatly tie-in with OnInit's built-in Debug library functionality to define a starting line and an ending line for your module.
---@overload async fun(userInitFunc: Initializer.Callback)
return function(libraryName, userInitFunc, debugLineNum)
addUserFunc(name, libraryName, userInitFunc, debugLineNum)
end
end
OnInit.global = createInit 'InitGlobals' -- Called after InitGlobals, and is the standard point to initialize.
OnInit.trig = createInit 'InitCustomTriggers' -- Called after InitCustomTriggers, and is useful for removing hooks that should only apply to GUI events.
OnInit.map = createInit 'RunInitializationTriggers' -- Called last in the script's loading screen sequence. Runs after the GUI "Map Initialization" events have run.
OnInit.final = createInit 'MarkGameStarted' -- Called immediately after the loading screen has disappeared, and the game has started.
do
---@param self table
---@param libraryNameOrInitFunc function | string
---@param userInitFunc function
---@param debugLineNum number
local function __call(
self,
libraryNameOrInitFunc,
userInitFunc,
debugLineNum
)
if userInitFunc or type(libraryNameOrInitFunc) == 'function' then
addUserFunc(
'InitGlobals', --Calling OnInit directly defaults to OnInit.global (AKA OnGlobalInit)
libraryNameOrInitFunc,
userInitFunc,
debugLineNum,
true
)
elseif library then
library:declare(libraryNameOrInitFunc) --API handler for OnInit "Custom initializer"
else
error(
"Bad OnInit args: "..
tostring(libraryNameOrInitFunc) .. ", " ..
tostring(userInitFunc)
)
end
end
setmetatable(OnInit --[[@as table]], { __call = __call })
end
do --if you don't need the initializers for 'root', 'config' and 'main', you can delete this do...end block.
local gmt = getmetatable(_G) or
getmetatable(setmetatable(_G, {}))
local rawIndex = gmt.__newindex or rawset
local hookMainAndConfig
---@param _G table
---@param key string
---@param fnOrDiscard unknown
function hookMainAndConfig(_G, key, fnOrDiscard)
if key == 'main' or key == 'config' then
---@cast fnOrDiscard function
if key == 'main' then
runInitializers 'root'
end
rawIndex(_G, key, function()
if key == 'config' then
fnOrDiscard()
elseif gmt.__newindex == hookMainAndConfig then
gmt.__newindex = rawIndex --restore the original __newindex if no further hooks on __newindex exist.
end
runInitializers(key)
if key == 'main' then
fnOrDiscard()
end
end)
else
rawIndex(_G, key, fnOrDiscard)
end
end
gmt.__newindex = hookMainAndConfig
OnInit.root = createInit 'root' -- Runs immediately during the Lua root, but is yieldable (allowing requirements) and pcalled.
OnInit.config = createInit 'config' -- Runs when `config` is called. Credit to @Luashine: https://www.hiveworkshop.com/threads/inject-main-config-from-we-trigger-code-like-jasshelper.338201/
OnInit.main = createInit 'main' -- Runs when `main` is called. Idea from @Tasyen: https://www.hiveworkshop.com/threads/global-initialization.317099/post-3374063
end
if library then
library.queuedInitializerList = {}
library.customDeclarationList = {}
library.yieldedModuleMatrix = {}
library.moduleValueMatrix = {}
function library:pack(name, ...)
self.moduleValueMatrix[name] = table.pack(...)
end
function library:resume()
if self.queuedInitializerList[1] then
local continue, tempQueue, forceOptional
::initLibraries::
repeat
continue=false
self.queuedInitializerList, tempQueue =
{}, self.queuedInitializerList
for _,func in ipairs(tempQueue) do
if func(forceOptional) then
continue=true --Something was initialized; therefore further systems might be able to initialize.
else
insert(self.queuedInitializerList, func) --If the queued initializer returns false, that means its requirement wasn't met, so we re-queue it.
end
end
until not continue or not self.queuedInitializerList[1]
if self.customDeclarationList[1] then
self.customDeclarationList, tempQueue =
{}, self.customDeclarationList
for _,func in ipairs(tempQueue) do
func() --unfreeze any custom initializers.
end
elseif not forceOptional then
forceOptional = true
else
return
end
goto initLibraries
end
end
local function declareName(name, initialValue)
assert(type(name) == 'string')
assert(library.moduleValueMatrix[name] == nil)
library.moduleValueMatrix[name] =
initialValue and { true, n = 1 }
end
function library:create(name, userFunc)
assert(type(userFunc) == 'function')
declareName(name, false) --declare itself as a non-loaded library.
return function()
self:pack(name, userFunc(Require)) --pack return values to allow multiple values to be communicated.
if self.moduleValueMatrix[name].n == 0 then
self:pack(name, true) --No values were returned; therefore simply package the value as `true`
end
end
end
---@async
function library:declare(name)
declareName(name, true) --declare itself as a loaded library.
local co = coroutine.running()
insert(
self.customDeclarationList,
function()
coroutine.resume(co)
end
)
coroutine.yield() --yields the calling function until after all currently-queued initializers have run.
end
local processRequirement
---@async
function processRequirement(
optional,
requirement,
explicitSource
)
if type(optional) == 'string' then
optional, requirement, explicitSource =
true, optional, requirement --optional requirement (processed by the __index method)
else
optional = false --strict requirement (processed by the __call method)
end
local source = explicitSource or _G
assert(type(source)=='table')
assert(type(requirement)=='string')
::reindex::
local subSource, subReq =
requirement:match("([\x25w_]+)\x25.(.+)") --Check if user is requiring using "table.property" syntax
if subSource and subReq then
source,
requirement =
processRequirement(subSource, source), --If the container is nil, yield until it is not.
subReq
if type(source)=='table' then
explicitSource = source
goto reindex --check for further nested properties ("table.property.subProperty.anyOthers").
else
return --The source table for the requirement wasn't found, so disregard the rest (this only happens with optional requirements).
end
end
local function loadRequirement(unpack)
local package = rawget(source, requirement) --check if the requirement exists in the host table.
if not package and not explicitSource then
if library.yieldedModuleMatrix[requirement] then
library.yieldedModuleMatrix[requirement]() --load module if it exists
end
package = library.moduleValueMatrix[requirement] --retrieve the return value from the module.
if unpack and type(package)=='table' then
return table.unpack(package, 1, package.n) --using unpack allows any number of values to be returned by the required library.
end
end
return package
end
local co, loaded
local function checkReqs(forceOptional, printErrors)
if not loaded then
loaded = loadRequirement()
loaded = loaded or optional and
(loaded==nil or forceOptional)
if loaded then
if co then coroutine.resume(co) end --resume only if it was yielded in the first place.
return loaded
elseif printErrors then
coroutine.resume(co, true)
end
end
end
if not checkReqs() then --only yield if the requirement doesn't already exist.
co = coroutine.running()
insert(library.queuedInitializerList, checkReqs)
if coroutine.yield() then
error("Missing Requirement: "..requirement) --handle the error within the user's function to get an accurate stack trace via the `try` function.
end
end
return loadRequirement(true)
end
---@type Requirement
function Require.strict(name, explicitSource)
return processRequirement(nil, name, explicitSource)
end
setmetatable(Require --[[@as table]], {
__call = processRequirement,
__index = function()
return processRequirement
end
})
local module = createInit 'module'
--- `OnInit.module` will only call the OnInit function if the module is required by another resource, rather than being called at a pre-
--- specified point in the loading process. It works similarly to Go, in that including modules in your map that are not actually being
--- required will throw an error message.
---@param name string
---@param func fun(require?: Initializer.Callback):any
---@param debugLineNum? integer
OnInit.module = function(name, func, debugLineNum)
if func then
local userFunc = func
func = function(require)
local co = coroutine.running()
library.yieldedModuleMatrix[name] =
function(failure)
library.yieldedModuleMatrix[name] = nil
coroutine.resume(co, failure)
end
if coroutine.yield() then
error("Module declared but not required: "..name)
end
return userFunc(require)
end
end
module(name, func, debugLineNum)
end
end
if assignLegacyAPI then --This block handles legacy code.
---Allows packaging multiple requirements into one table and queues the initialization for later.
---@deprecated
---@param initList string | table
---@param userFunc function
function OnInit.library(initList, userFunc)
local typeOf = type(initList)
assert(typeOf=='table' or typeOf=='string')
assert(type(userFunc) == 'function')
local function caller(use)
if typeOf=='string' then
use(initList)
else
for _,initName in ipairs(initList) do
use(initName)
end
if initList.optional then
for _,initName in ipairs(initList.optional) do
use.lazily(initName)
end
end
end
end
if initList.name then
OnInit(initList.name, caller)
else
OnInit(caller)
end
end
local legacyTable = {}
assignLegacyAPI(legacyTable, OnInit)
for key,func in pairs(legacyTable) do
rawset(_G, key, func)
end
OnInit.final(function()
for key in pairs(legacyTable) do
rawset(_G, key, nil)
end
end)
end
initEverything()
end
if Debug then Debug.endFile() end
do; local _, codeLoc = pcall(error, "", 2) --get line number where DebugUtils begins.
--[[
--------------------------
-- | Debug Utils 2.0a | --
--------------------------
--> https://www.hiveworkshop.com/threads/debug-utils-ingame-console-etc.330758/
- by Eikonium, with special thanks to:
- @Bribe, for pretty table print, showing that xpcall's message handler executes before the stack unwinds and useful suggestions like name caching and stack trace improvements.
- @Jampion, for useful suggestions like print caching and applying Debug.try to all code entry points
- @Luashine, for useful feedback and building "WC3 Debug Console Paste Helperβ" (https://github.com/Luashine/wc3-debug-console-paste-helper#readme)
- @HerlySQR, for showing a way to get a stack trace in Wc3 (https://www.hiveworkshop.com/threads/lua-getstacktrace.340841/)
- @Macadamia, for showing a way to print warnings upon accessing undeclared globals, where this all started with (https://www.hiveworkshop.com/threads/lua-very-simply-trick-to-help-lua-users-track-syntax-errors.326266/)
-----------------------------------------------------------------------------------------------------------------------------
| Provides debugging utility for Wc3-maps using Lua. |
| |
| Including: |
| 1. Automatic ingame error messages upon running erroneous code from triggers or timers. |
| 2. Ingame Console that allows you to execute code via Wc3 ingame chat. |
| 3. Automatic warnings upon reading undeclared globals (which also triggers after misspelling globals) |
| 4. Debug-Library functions for manual error handling. |
| 5. Caching of loading screen print messages until game start (which simplifies error handling during loading screen) |
| 6. Overwritten tostring/print-functions to show the actual string-name of an object instead of the memory position. |
| 7. Conversion of war3map.lua-error messages to local file error messages. |
| 8. Other useful debug utility (table.print and Debug.wc3Type) |
-----------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Installation: |
| |
| 1. Copy the code (DebugUtils.lua, StringWidth.lua and IngameConsole.lua) into your map. Use script files (Ctrl+U) in your trigger editor, not text-based triggers! |
| 2. Order the files: DebugUtils above StringWidth above IngameConsole. Make sure they are above ALL other scripts (crucial for local line number feature). |
| 3. Adjust the settings in the settings-section further below to receive the debug environment that fits your needs. |
| |
| Deinstallation: |
| |
| - Debug Utils is meant to provide debugging utility and as such, shall be removed or invalidated from the map closely before release. |
| - Optimally delete the whole Debug library. If that isn't suitable (because you have used library functions at too many places), you can instead replace Debug Utils |
| by the following line of code that will invalidate all Debug functionality (without breaking your code): |
| Debug = setmetatable({try = function(...) return select(2,pcall(...)) end}, {__index = function(t,k) return DoNothing end}); try = Debug.try |
| - If that is also not suitable for you (because your systems rely on the Debug functionality to some degree), at least set ALLOW_INGAME_CODE_EXECUTION to false. |
| - Be sure to test your map thoroughly after removing Debug Utils. |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
* Documentation and API-Functions:
*
* - All automatic functionality provided by Debug Utils can be deactivated using the settings directly below the documentation.
*
* -------------------------
* | Ingame Code Execution |
* -------------------------
* - Debug Utils provides the ability to run code via chat command from within Wc3, if you have conducted step 3 from the installation section.
* - You can either open the ingame console by typing "-console" into the chat, or directly execute code by typing "-exec <code>".
* - See IngameConsole script for further documentation.
*
* ------------------
* | Error Handling |
* ------------------
* - Debug Utils automatically applies error handling (i.e. Debug.try) to code executed by your triggers and timers (error handling means that error messages are printed on screen, if anything doesn't run properly).
* - You can still use the below library functions for manual debugging.
*
* Debug.try(funcToExecute, ...) / try(funcToExecute, ...) -> ...
* - Calls the specified function with the specified parameters in protected mode (i.e. code after Debug.try will continue to run even if the function fails to execute).
* - If the call is successful, returns the specified function's original return values (so p1 = Debug.try(Player, 0) will work fine).
* - If the call is unsuccessful, prints an error message on screen (including stack trace and parameters you have potentially logged before the error occured)
* - By default, the error message consists of a line-reference to war3map.lua (which you can look into by forcing a syntax error in WE or by exporting it from your map via File -> Export Script).
* You can get more helpful references to local script files instead, see section about "Local script references".
* - Example: Assume you have a code line like "func(param1,param2)", which doesn't work and you want to know why.
* Option 1: Change it to "Debug.try(func, param1, param2)", i.e. separate the function from the parameters.
* Option 2: Change it to "Debug.try(function() return func(param1, param2) end)", i.e. pack it into an anonymous function (optionally skip the return statement).
* Debug.log(...)
* - Logs the specified parameters to the Debug-log. The Debug-log will be printed upon the next error being catched by Debug.try, Debug.assert or Debug.throwError.
* - The Debug-log will only hold one set of parameters per code-location. That means, if you call Debug.log() inside any function, only the params saved within the latest call of that function will be kept.
* Debug.throwError(...)
* - Prints an error message including document, line number, stack trace, previously logged parameters and all specified parameters on screen. Parameters can have any type.
* - In contrast to Lua's native error function, this can be called outside of protected mode and doesn't halt code execution.
* Debug.assert(condition:boolean, errorMsg:string, ...) -> ...
* - Prints the specified error message including document, line number, stack trace and previously logged parameters on screen, IF the specified condition fails (i.e. resolves to false/nil).
* - Returns ..., IF the specified condition holds.
* - This works exactly like Lua's native assert, except that it also works outside of protected mode and does not halt code execution.
* Debug.traceback() -> string
* - Returns the stack trace at the position where this is called. You need to manually print it.
* Debug.getLine([depth: integer]) -> integer?
* - Returns the line in war3map.lua, where this function is executed.
* - You can specify a depth d >= 1 to instead return the line, where the d-th function in the stack trace was called. I.e. depth = 2 will return the line of execution of the function that calls Debug.getLine.
* - Due to Wc3's limited stack trace ability, this might sometimes return nil for depth >= 3, so better apply nil-checks on the result.
* Debug.getLocalErrorMsg(errorMsg:string) -> string
* - Takes an error message containing a file and a linenumber and converts war3map.lua-lines to local document lines as defined by uses of Debug.beginFile() and Debug.endFile().
* - Error Msg must be formatted like "<document>:<linenumber><Rest>".
*
* -----------------------------------
* | Warnings for undeclared globals |
* -----------------------------------
* - DebugUtils will print warnings on screen, if you read an undeclared global variable.
* - This is technically the case, when you misspelled on a function name, like calling CraeteUnit instead of CreateUnit.
* - Keep in mind though that the same warning will pop up after reading a global that was intentionally nilled. If you don't like this, turn of this feature in the settings.
*
* -----------------
* | Print Caching |
* -----------------
* - DebugUtils caches print()-calls occuring during loading screen and delays them to after game start.
* - This also applies to loading screen error messages, so you can wrap erroneous parts of your Lua root in Debug.try-blocks and see the message after game start.
*
* -------------------------
* | Local File Stacktrace |
* -------------------------
* - By default, error messages and stack traces printed by the error handling functionality of Debug Utils contain references to war3map.lua (a big file just appending all your local scripts).
* - The Debug-library provides the two functions below to index your local scripts, activating local file names and line numbers (matching those in your IDE) instead of the war3map.lua ones.
* - This allows you to inspect errors within your IDE (VSCode) instead of the World Editor.
*
* Debug.beginFile(fileName: string [, depth: integer])
* - Tells the Debug library that the specified file begins exactly here (i.e. in the line, where this is called).
* - Using this improves stack traces of error messages. "war3map.lua"-references between <here> and the next Debug.endFile() will be converted to file-specific references.
* - All war3map.lua-lines located between the call of Debug.beginFile(fileName) and the next call of Debug.beginFile OR Debug.endFile are treated to be part of "fileName".
* - !!! To be called in the Lua root in Line 1 of every document you wish to track. Line 1 means exactly line 1, before any comment! This way, the line shown in the trace will exactly match your IDE.
* - Depth can be ignored, except if you want to use a custom wrapper around Debug.beginFile(), in which case you need to set the depth parameter to 1 to record the line of the wrapper instead of the line of Debug.beginFile().
* Debug.endFile([depth: integer])
* - Ends the current file that was previously begun by using Debug.beginFile(). War3map.lua-lines after this will not be converted until the next instance of Debug.beginFile().
* - The next call of Debug.beginFile() will also end the previous one, so using Debug.endFile() is optional. Mainly recommended to use, if you prefer to have war3map.lua-references in a certain part of your script (such as within GUI triggers).
* - Depth can be ignored, except if you want to use a custom wrapper around Debug.endFile(), you need to increase the depth parameter to 1 to record the line of the wrapper instead of the line of Debug.endFile().
*
* ----------------
* | Name Caching |
* ----------------
* - DebugUtils overwrites the tostring-function so that it prints the name of a non-primitive object (if available) instead of its memory position. The same applies to print().
* - For instance, print(CreateUnit) will show "function: CreateUnit" on screen instead of "function: 0063A698".
* - The table holding all those names is referred to as "Name Cache".
* - All names of objects in global scope will automatically be added to the Name Cache both within Lua root and again at game start (to get names for overwritten natives and your own objects).
* - New names entering global scope will also automatically be added, even after game start. The same applies to subtables of _G up to a depth of Debug.settings.NAME_CACHE_DEPTH.
* - Objects within subtables will be named after their parent tables and keys. For instance, the name of the function within T = {{bla = function() end}} is "T[1].bla".
* - The automatic adding doesn't work for objects saved into existing variables/keys after game start (because it's based on __newindex metamethod which simply doesn't trigger)
* - You can manually add names to the name cache by using the following API-functions:
*
* Debug.registerName(whichObject:any, name:string)
* - Adds the specified object under the specified name to the name cache, letting tostring and print output "<type>: <name>" going foward.
* - The object must be non-primitive, i.e. this won't work on strings, numbers and booleans.
* - This will overwrite existing names for the specified object with the specified name.
* Debug.registerNamesFrom(parentTable:table [, parentTableName:string] [, depth])
* - Adds names for all values from within the specified parentTable to the name cache.
* - Names for entries will be like "<parentTableName>.<key>" or "<parentTableName>[<key>]" (depending on the key type), using the existing name of the parentTable from the name cache.
* - You can optionally specify a parentTableName to use that for the entry naming instead of the existing name. Doing so will also register that name for the parentTable, if it doesn't already has one.
* - Specifying the empty string as parentTableName will suppress it in the naming and just register all values as "<key>". Note that only string keys will be considered this way.
* - In contrast to Debug.registerName(), this function will NOT overwrite existing names, but just add names for new objects.
* Debug.oldTostring(object:any) -> string
* - The old tostring-function in case you still need outputs like "function: 0063A698".
*
* -----------------
* | Other Utility |
* -----------------
*
* Debug.wc3Type(object:any) -> string
* - Returns the Warcraft3-type of the input object. E.g. Debug.wc3Type(Player(0)) will return "player".
* - Returns type(object), if used on Lua-objects.
* table.tostring(whichTable [, depth:integer] [, pretty_yn:boolean])
* - Creates a list of all (key,value)-pairs from the specified table. Also lists subtable entries up to the specified depth (unlimited, if not specified).
* - E.g. for T = {"a", 5, {7}}, table.tostring(T) would output '{(1, "a"), (2, 5), (3, {(1, 7)})}' (if using concise style, i.e. pretty_yn being nil or false).
* - Not specifying a depth can potentially lead to a stack overflow for self-referential tables (e.g X = {}; X[1] = X). Choose a sensible depth to prevent this (in doubt start with 1 and test upwards).
* - Supports pretty style by setting pretty_yn to true. Pretty style is linebreak-separated, uses indentations and has other visual improvements. Use it on small tables only, because Wc3 can't show that many linebreaks at once.
* - All of the following is valid syntax: table.tostring(T), table.tostring(T, depth), table.tostring(T, pretty_yn) or table.tostring(T, depth, pretty_yn).
* - table.tostring is not multiplayer-synced.
* table.print(whichTable [, depth:integer] [, pretty_yn:boolean])
* - Prints table.tostring(...).
*
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------]]
----------------
--| Settings |--
----------------
Debug = {
--BEGIN OF SETTINGS--
settings = {
SHOW_TRACE_ON_ERROR = true ---Set to true to show a stack trace on every error in addition to the regular message (msg sources: automatic error handling, Debug.try, Debug.throwError, ...)
, USE_TRY_ON_TRIGGERADDACTION = true ---Set to true for automatic error handling on TriggerAddAction (applies Debug.try on every trigger action).
, USE_TRY_ON_CONDITION = true ---Set to true for automatic error handling on boolexpressions created via Condition() or Filter() (essentially applies Debug.try on every trigger condition).
, USE_TRY_ON_TIMERSTART = true ---Set to true for automatic error handling on TimerStart (applies Debug.try on every timer callback).
, USE_TRY_ON_COROUTINES = true ---Set to true for improved stack traces on errors within coroutines (applies Debug.try on coroutine.create and coroutine.wrap). This lets stack traces point to the erroneous function executed within the coroutine (instead of the function creating the coroutine).
, ALLOW_INGAME_CODE_EXECUTION = true ---Set to true to enable IngameConsole and -exec command.
, WARNING_FOR_UNDECLARED_GLOBALS = true ---Set to true to print warnings upon accessing undeclared globals (i.e. globals with nil-value). This is technically the case after having misspelled on a function name (like CraeteUnit instead of CreateUnit).
, SHOW_TRACE_FOR_UNDECLARED_GLOBALS = false ---Set to true to include a stack trace into undeclared global warnings. Only takes effect, if WARNING_FOR_UNDECLARED_GLOBALS is also true.
, USE_PRINT_CACHE = true ---Set to true to let print()-calls during loading screen be cached until the game starts.
, PRINT_DURATION = nil ---Adjust the duration in seconds that values printed by print() last on screen. Set to nil to use default duration (which depends on string length).
, USE_NAME_CACHE = true ---Set to true to let tostring/print output the string-name of an object instead of its memory location (except for booleans/numbers/strings). E.g. print(CreateUnit) will output "function: CreateUnit" instead of "function: 0063A698".
, AUTO_REGISTER_NEW_NAMES = true ---Automatically adds new names from global scope (and subtables of _G up to NAME_CACHE_DEPTH) to the name cache by adding metatables with the __newindex metamethod to ALL tables accessible from global scope.
, NAME_CACHE_DEPTH = 0 ---Set to 0 to only affect globals. Experimental feature: Set to an integer > 0 to also cache names for subtables of _G (up to the specified depth). Warning: This will alter the __newindex metamethod of subtables of _G (but not break existing functionality).
}
--END OF SETTINGS--
--START OF CODE--
, data = {
nameCache = {} ---@type table<any,string> contains the string names of any object in global scope (random for objects that have multiple names)
, nameCacheMirror = {} ---@type table<string,any> contains the (name,object)-pairs of all objects in the name cache. Used to prevent name duplicates that might otherwise occur upon reassigning globals.
, nameDepths = {} ---@type table<any,integer> contains the depth of the name used by by any object in the name cache (i.e. the depth within the parentTable).
, autoIndexedTables = {} ---@type table<table,boolean> contains (t,true), if DebugUtils already set a __newindex metamethod for name caching in t. Prevents double application.
, paramLog = {} ---@type table<string,string> saves logged information per code location. to be filled by Debug.log(), to be printed by Debug.try()
, sourceMap = {{firstLine= 1,file='DebugUtils'}} ---@type table<integer,{firstLine:integer,file:string,lastLine?:integer}> saves lines and file names of all documents registered via Debug.beginFile().
, printCache = {n=0} ---@type string[] contains the strings that were attempted to print during loading screen.
}
}
--localization
local settings, paramLog, nameCache, nameDepths, autoIndexedTables, nameCacheMirror, sourceMap, printCache = Debug.settings, Debug.data.paramLog, Debug.data.nameCache, Debug.data.nameDepths, Debug.data.autoIndexedTables, Debug.data.nameCacheMirror, Debug.data.sourceMap, Debug.data.printCache
--Write DebugUtils first line number to sourceMap:
---@diagnostic disable-next-line: need-check-nil
Debug.data.sourceMap[1].firstLine = tonumber(codeLoc:match(":\x25d+"):sub(2,-1))
-------------------------------------------------
--| File Indexing for local Error Msg Support |--
-------------------------------------------------
-- Functions for war3map.lua -> local file conversion for error messages.
---Returns the line number in war3map.lua, where this is called (for depth = 0).
---Choose a depth > 0 to instead return the line, where the corresponding function in the stack leading to this call is executed.
---@param depth? integer default: 0.
---@return number?
function Debug.getLine(depth)
depth = depth or 0
local _, location = pcall(error, "", depth + 3) ---@diagnostic disable-next-line: need-check-nil
local line = location:match(":\x25d+") --extracts ":1000" from "war3map.lua:1000:..."
return tonumber(line and line:sub(2,-1)) --check if line is nil before applying string.sub to prevent errors (nil can result from string.match above, although it should never do so in our case)
end
---Tells the Debug library that the specified file begins exactly here (i.e. in the line, where this is called).
---
---Using this improves stack traces of error messages. Stack trace will have "war3map.lua"-references between this and the next Debug.endFile() converted to file-specific references.
---
---To be called in the Lua root in Line 1 of every file you wish to track! Line 1 means exactly line 1, before any comment! This way, the line shown in the trace will exactly match your IDE.
---
---If you want to use a custom wrapper around Debug.beginFile(), you need to increase the depth parameter to 1 to record the line of the wrapper instead of the line of Debug.beginFile().
---@param fileName string
---@param depth? integer default: 0. Set to 1, if you call this from a wrapper (and use the wrapper in line 1 of every document).
---@param lastLine? integer Ignore this. For compatibility with Total Initialization.
function Debug.beginFile(fileName, depth, lastLine)
depth, fileName = depth or 0, fileName or '' --filename is not actually optional, we just default to '' to prevent crashes.
local line = Debug.getLine(depth + 1)
if line then --for safety reasons. we don't want to add a non-existing line to the sourceMap
table.insert(sourceMap, {firstLine = line, file = fileName, lastLine = lastLine}) --automatically sorted list, because calls of Debug.beginFile happen logically in the order of the map script.
end
end
---Tells the Debug library that the file previously started with Debug.beginFile() ends here.
---This is in theory optional to use, as the next call of Debug.beginFile will also end the previous. Still good practice to always use this in the last line of every file.
---If you want to use a custom wrapper around Debug.endFile(), you need to increase the depth parameter to 1 to record the line of the wrapper instead of the line of Debug.endFile().
---@param depth? integer
function Debug.endFile(depth)
depth = depth or 0
local line = Debug.getLine(depth + 1)
sourceMap[#sourceMap].lastLine = line
end
---Takes an error message containing a file and a linenumber and converts both to local file and line as saved to Debug.sourceMap.
---@param errorMsg string must be formatted like "<document>:<linenumber><RestOfMsg>".
---@return string convertedMsg a string of the form "<localDocument>:<localLinenumber><RestOfMsg>"
function Debug.getLocalErrorMsg(errorMsg)
local startPos, endPos = errorMsg:find(":\x25d*") --start and end position of line number. The part before that is the document, part after the error msg.
if startPos and endPos then --can be nil, if input string was not of the desired form "<document>:<linenumber><RestOfMsg>".
local document, line, rest = errorMsg:sub(1, startPos), tonumber(errorMsg:sub(startPos+1, endPos)), errorMsg:sub(endPos+1, -1) --get error line in war3map.lua
if document == 'war3map.lua:' and line then --only convert war3map.lua-references to local position. Other files such as Blizzard.j.lua are not converted (obiously).
for i = #sourceMap, 1, -1 do --find local file containing the war3map.lua error line.
if line >= sourceMap[i].firstLine then --war3map.lua line is part of sourceMap[i].file
if not sourceMap[i].lastLine or line <= sourceMap[i].lastLine then --if lastLine is given, we must also check for it
return sourceMap[i].file .. ":" .. (line - sourceMap[i].firstLine + 1) .. rest
else --if line is larger than firstLine and lastLine of sourceMap[i], it is not part of a tracked file -> return global war3map.lua position.
break --prevent return within next step of the loop ("line >= sourceMap[i].firstLine" would be true again, but wrong file)
end
end
end
end
end
return errorMsg
end
local convertToLocalErrorMsg = Debug.getLocalErrorMsg
----------------------
--| Error Handling |--
----------------------
local concat
---Applies tostring() on all input params and concatenates them 4-space-separated.
---@param firstParam any
---@param ... any
---@return string
concat = function(firstParam, ...)
if select('#', ...) == 0 then
return tostring(firstParam)
end
return tostring(firstParam) .. ' ' .. concat(...)
end
---Returns the stack trace between the specified startDepth and endDepth.
---The trace lists file names and line numbers. File name is only listed, if it has changed from the previous traced line.
---The previous file can also be specified as an input parameter to suppress the first file name in case it's identical.
---@param startDepth integer
---@param endDepth integer
---@return string trace
local function getStackTrace(startDepth, endDepth)
local trace, separator = "", ""
local _, lastFile, tracePiece, lastTracePiece
for loopDepth = startDepth, endDepth do --get trace on different depth level
_, tracePiece = pcall(error, "", loopDepth) ---@type boolean, string
tracePiece = convertToLocalErrorMsg(tracePiece)
if #tracePiece > 0 and lastTracePiece ~= tracePiece then --some trace pieces can be empty, but there can still be valid ones beyond that
trace = trace .. separator .. ((tracePiece:match("^.-:") == lastFile) and tracePiece:match(":\x25d+"):sub(2,-1) or tracePiece:match("^.-:\x25d+"))
lastFile, lastTracePiece, separator = tracePiece:match("^.-:"), tracePiece, " <- "
end
end
return trace
end
---Message Handler to be used by the try-function below.
---Adds stack trace plus formatting to the message and prints it.
---@param errorMsg string
---@param startDepth? integer default: 4 for use in xpcall
local function errorHandler(errorMsg, startDepth)
startDepth = startDepth or 4 --xpcall doesn't specify this param, so it defaults to 4 in this case
errorMsg = convertToLocalErrorMsg(errorMsg)
--Print original error message and stack trace.
print("|cffff5555ERROR at " .. errorMsg .. "|r")
if settings.SHOW_TRACE_ON_ERROR then
print("|cffff5555Traceback (most recent call first):|r")
print("|cffff5555" .. getStackTrace(startDepth,200) .. "|r")
end
--Also print entries from param log, if there are any.
for location, loggedParams in pairs(paramLog) do
print("|cff888888Logged at " .. convertToLocalErrorMsg(location) .. loggedParams .. "|r")
paramLog[location] = nil
end
end
---Tries to execute the specified function with the specified parameters in protected mode and prints an error message (including stack trace), if unsuccessful.
---
---Example use: Assume you have a code line like "CreateUnit(0,1,2)", which doesn't work and you want to know why.
---* Option 1: Change it to "Debug.try(CreateUnit, 0, 1, 2)", i.e. separate the function from the parameters.
---* Option 2: Change it to "Debug.try(function() return CreateUnit(0,1,2) end)", i.e. pack it into an anonymous function. You can skip the "return", if you don't need the return values.
---When no error occured, the try-function will return all values returned by the input function.
---When an error occurs, try will print the resulting error and stack trace.
---@param funcToExecute function the function to call in protected mode
---@param ... any params for the input-function
---@return ... any
function Debug.try(funcToExecute, ...)
return select(2, xpcall(funcToExecute, errorHandler,...))
end
try = Debug.try
---Prints "ERROR:" and the specified error objects on the Screen. Also prints the stack trace leading to the error. You can specify as many arguments as you wish.
---
---In contrast to Lua's native error function, this can be called outside of protected mode and doesn't halt code execution.
---@param ... any objects/errormessages to be printed (doesn't have to be strings)
function Debug.throwError(...)
errorHandler(getStackTrace(4,4) .. ": " .. concat(...), 5)
end
---Prints the specified error message, if the specified condition fails (i.e. if it resolves to false or nil).
---
---Returns all specified arguments after the errorMsg, if the condition holds.
---
---In contrast to Lua's native assert function, this can be called outside of protected mode and doesn't halt code execution (even in case of condition failure).
---@param condition any actually a boolean, but you can use any object as a boolean.
---@param errorMsg string the message to be printed, if the condition fails
---@param ... any will be returned, if the condition holds
function Debug.assert(condition, errorMsg, ...)
if condition then
return ...
else
errorHandler(getStackTrace(4,4) .. ": " .. errorMsg, 5)
end
end
---Returns the stack trace at the code position where this function is called.
---The returned string includes war3map.lua/blizzard.j.lua code positions of all functions from the stack trace in the order of execution (most recent call last). It does NOT include function names.
---@return string
function Debug.traceback()
return getStackTrace(3,200)
end
---Saves the specified parameters to the debug log at the location where this function is called. The Debug-log will be printed for all affected locations upon the try-function catching an error.
---The log is unique per code location: Parameters logged at code line x will overwrite the previous ones logged at x. Parameters logged at different locations will all persist and be printed.
---@param ... any save any information, for instance the parameters of the function call that you are logging.
function Debug.log(...)
local _, location = pcall(error, "", 3) ---@diagnostic disable-next-line: need-check-nil
paramLog[location or ''] = concat(...)
end
------------------------------------
--| Name Caching (API-functions) |--
------------------------------------
--Help-table. The registerName-functions below shall not work on call-by-value-types, i.e. booleans, strings and numbers (renaming a value of any primitive type doesn't make sense).
local skipType = {boolean = true, string = true, number = true, ['nil'] = true}
--Set weak keys to nameCache and nameDepths and weak values for nameCacheMirror to prevent garbage collection issues
setmetatable(nameCache, {__mode = 'k'})
setmetatable(nameDepths, getmetatable(nameCache))
setmetatable(nameCacheMirror, {__mode = 'v'})
---Removes the name from the name cache, if already used for any object (freeing it for the new object). This makes sure that a name is always unique.
---This doesn't solve the
---@param name string
local function removeNameIfNecessary(name)
if nameCacheMirror[name] then
nameCache[nameCacheMirror[name]] = nil
nameCacheMirror[name] = nil
end
end
---Registers a name for the specified object, which will be the future output for tostring(whichObject).
---You can overwrite existing names for whichObject by using this.
---@param whichObject any
---@param name string
function Debug.registerName(whichObject, name)
if not skipType[type(whichObject)] then
removeNameIfNecessary(name)
nameCache[whichObject] = name
nameCacheMirror[name] = whichObject
nameDepths[name] = 0
end
end
---Registers a new name to the nameCache as either just <key> (if parentTableName is the empty string), <table>.<key> (if parentTableName is given and string key doesn't contain whitespace) or <name>[<key>] notation (for other keys in existing tables).
---Only string keys without whitespace support <key>- and <table>.<key>-notation. All other keys require a parentTableName.
---@param parentTableName string | '""' empty string suppresses <table>-affix.
---@param key any
---@param object any only call-be-ref types allowed
---@param parentTableDepth? integer
local function addNameToCache(parentTableName, key, object, parentTableDepth)
parentTableDepth = parentTableDepth or -1
--Don't overwrite existing names for the same object, don't add names for primitive types.
if nameCache[object] or skipType[type(object)] then
return
end
local name
--apply dot-syntax for string keys without whitespace
if type(key) == 'string' and not string.find(key, "\x25s") then
if parentTableName == "" then
name = key
nameDepths[object] = 0
else
name = parentTableName .. "." .. key
nameDepths[object] = parentTableDepth + 1
end
--apply bracket-syntax for all other keys. This requires a parentTableName.
elseif parentTableName ~= "" then
name = type(key) == 'string' and ('"' .. key .. '"') or key
name = parentTableName .. "[" .. tostring(name) .. "]"
nameDepths[object] = parentTableDepth + 1
end
--Stop in cases without valid name (like parentTableName = "" and key = [1])
if name then
removeNameIfNecessary(name)
nameCache[object] = name
nameCacheMirror[name] = object
end
end
---Registers all call-by-reference objects in the given parentTable to the nameCache.
---Automatically filters out primitive objects and already registed Objects.
---@param parentTable table
---@param parentTableName? string
local function registerAllObjectsInTable(parentTable, parentTableName)
parentTableName = parentTableName or nameCache[parentTable] or ""
--Register all call-by-ref-objects in parentTable
for key, object in pairs(parentTable) do
addNameToCache(parentTableName, key, object, nameDepths[parentTable])
end
end
---Adds names for all values of the specified parentTable to the name cache. Names will be "<parentTableName>.<key>" or "<parentTableName>[<key>]", depending on the key type.
---
---Example: Given a table T = {f = function() end, [1] = {}}, tostring(T.f) and tostring(T[1]) will output "function: T.f" and "table: T[1]" respectively after running Debug.registerNamesFrom(T).
---The name of T itself must either be specified as an input parameter OR have previously been registered. It can also be suppressed by inputting the empty string (so objects will just display by their own names).
---The names of objects in global scope are automatically registered during loading screen.
---@param parentTable table base table of which all entries shall be registered (in the Form parentTableName.objectName).
---@param parentTableName? string|'""' Nil: takes <parentTableName> as previously registered. Empty String: Skips <parentTableName> completely. String <s>: Objects will show up as "<s>.<objectName>".
---@param depth? integer objects within sub-tables up to the specified depth will also be added. Default: 1 (only elements of whichTable). Must be >= 1.
---@overload fun(parentTable:table, depth:integer)
function Debug.registerNamesFrom(parentTable, parentTableName, depth)
--Support overloaded definition fun(parentTable:table, depth:integer)
if type(parentTableName) == 'number' then
depth = parentTableName
parentTableName = nil
end
--Apply default values
depth = depth or 1
parentTableName = parentTableName or nameCache[parentTable] or ""
--add name of T in case it hasn't already
if not nameCache[parentTable] and parentTableName ~= "" then
Debug.registerName(parentTable, parentTableName)
end
--Register all call-by-ref-objects in parentTable. To be preferred over simple recursive approach to ensure that top level names are preferred.
registerAllObjectsInTable(parentTable, parentTableName)
--if depth > 1 was specified, also register Names from subtables.
if depth > 1 then
for _, object in pairs(parentTable) do
if type(object) == 'table' then
Debug.registerNamesFrom(object, nil, depth - 1)
end
end
end
end
-------------------------------------------
--| Name Caching (Loading Screen setup) |--
-------------------------------------------
---Registers all existing object names from global scope and Lua incorporated libraries to be used by tostring() overwrite below.
local function registerNamesFromGlobalScope()
--Add all names from global scope to the name cache.
Debug.registerNamesFrom(_G, "")
--Add all names of Warcraft-enabled Lua libraries as well:
--Could instead add a depth to the function call above, but we want to ensure that these libraries are added even if the user has chosen depth 0.
for _, lib in ipairs({coroutine, math, os, string, table, utf8, Debug}) do
Debug.registerNamesFrom(lib)
end
--Add further names that are not accessible from global scope:
--Player(i)
for i = 0, GetBJMaxPlayerSlots() - 1 do
Debug.registerName(Player(i), "Player(" .. i .. ")")
end
end
--Set empty metatable to _G. __index is added when game starts (for "attempt to read undeclared global"-errors), __newindex is added right below (for building the name cache).
setmetatable(_G, getmetatable(_G) or {}) --getmetatable(_G) should always return nil provided that DebugUtils is the topmost script file in the trigger editor, but we still include this for safety-
-- Save old tostring into Debug Library before overwriting it.
Debug.oldTostring = tostring
if settings.USE_NAME_CACHE then
local oldTostring = tostring
tostring = function(obj) --new tostring(CreateUnit) prints "function: CreateUnit"
--tostring of non-primitive object is NOT guaranteed to be like "<type>:<hex>", because it might have been changed by some __tostring-metamethod.
if settings.USE_NAME_CACHE then --return names from name cache only if setting is enabled. This allows turning it off during runtime (via Ingame Console) to revert to old tostring.
return nameCache[obj] and ((oldTostring(obj):match("^.-: ") or (oldTostring(obj) .. ": ")) .. nameCache[obj]) or oldTostring(obj)
end
return Debug.oldTostring(obj)
end
--Add names to Debug.data.objectNames within Lua root. Called below the other Debug-stuff to get the overwritten versions instead of the original ones.
registerNamesFromGlobalScope()
--Prepare __newindex-metamethod to automatically add new names to the name cache
if settings.AUTO_REGISTER_NEW_NAMES then
local nameRegisterNewIndex
---__newindex to be used for _G (and subtables up to a certain depth) to automatically register new names to the nameCache.
---Tables in global scope will use their own name. Subtables of them will use <parentName>.<childName> syntax.
---Global names don't support container[key]-notation (because "_G[...]" is probably not desired), so we only register string type keys instead of using prettyTostring.
---@param t table
---@param k any
---@param v any
---@param skipRawset? boolean set this to true when combined with another __newindex. Suppresses rawset(t,k,v) (because the other __newindex is responsible for that).
nameRegisterNewIndex = function(t,k,v, skipRawset)
local parentDepth = nameDepths[t] or 0
--Make sure the parent table has an existing name before using it as part of the child name
if t == _G or nameCache[t] then
local existingName = nameCache[v]
if not existingName then
addNameToCache((t == _G and "") or nameCache[t], k, v, parentDepth)
end
--If v is a table and the parent table has a valid name, inherit __newindex to v's existing metatable (or create a new one), if that wasn't already done.
if type(v) == 'table' and nameDepths[v] < settings.NAME_CACHE_DEPTH then
if not existingName then
--If v didn't have a name before, also add names for elements contained in v by construction (like v = {x = function() end} ).
Debug.registerNamesFrom(v, settings.NAME_CACHE_DEPTH - nameDepths[v])
end
--Apply __newindex to new tables.
if not autoIndexedTables[v] then
autoIndexedTables[v] = true
local mt = getmetatable(v)
if not mt then
mt = {}
setmetatable(v, mt) --only use setmetatable when we are sure there wasn't any before to prevent issues with "__metatable"-metamethod.
end
local existingNewIndex = mt.__newindex
local isTable_yn = (type(existingNewIndex) == 'table')
--If mt has an existing __newindex, add the name-register effect to it (effectively create a new __newindex using the old)
if existingNewIndex then
mt.__newindex = function(t,k,v)
nameRegisterNewIndex(t,k,v, true) --setting t[k] = v might not be desired in case of existing newindex. Skip it and let existingNewIndex make the decision.
if isTable_yn then
existingNewIndex[k] = v
else
return existingNewIndex(t,k,v)
end
end
else
--If mt doesn't have an existing __newindex, add one that adds the object to the name cache.
mt.__newindex = nameRegisterNewIndex
end
end
end
end
--Set t[k] = v.
if not skipRawset then
rawset(t,k,v)
end
end
--Apply metamethod to _G.
local existingNewIndex = getmetatable(_G).__newindex --should always be nil provided that DebugUtils is the topmost script in your trigger editor. Still included for safety.
local isTable_yn = (type(existingNewIndex) == 'table')
if existingNewIndex then
getmetatable(_G).__newindex = function(t,k,v)
nameRegisterNewIndex(t,k,v, true)
if isTable_yn then
existingNewIndex[k] = v
else
existingNewIndex(t,k,v)
end
end
else
getmetatable(_G).__newindex = nameRegisterNewIndex
end
end
end
------------------------------------------------------
--| Native Overwrite for Automatic Error Handling |--
------------------------------------------------------
--A table to store the try-wrapper for each function. This avoids endless re-creation of wrapper functions within the hooks below.
--Weak keys ensure that garbage collection continues as normal.
local tryWrappers = setmetatable({}, {__mode = 'k'}) ---@type table<function,function>
local try = Debug.try
---Takes a function and returns a wrapper executing the same function within Debug.try.
---Wrappers are permanently stored (until the original function is garbage collected) to ensure that they don't have to be created twice for the same function.
---@param func? function
---@return function
local function getTryWrapper(func)
if func then
tryWrappers[func] = tryWrappers[func] or function(...) return try(func, ...) end
end
return tryWrappers[func] --returns nil for func = nil (important for TimerStart overwrite below)
end
--Overwrite TriggerAddAction, TimerStart, Condition and Filter natives to let them automatically apply Debug.try.
--Also overwrites coroutine.create and coroutine.wrap to let stack traces point to the function executed within instead of the function creating the coroutine.
if settings.USE_TRY_ON_TRIGGERADDACTION then
local originalTriggerAddAction = TriggerAddAction
TriggerAddAction = function(whichTrigger, actionFunc)
return originalTriggerAddAction(whichTrigger, getTryWrapper(actionFunc))
end
end
if settings.USE_TRY_ON_TIMERSTART then
local originalTimerStart = TimerStart
TimerStart = function(whichTimer, timeout, periodic, handlerFunc)
originalTimerStart(whichTimer, timeout, periodic, getTryWrapper(handlerFunc))
end
end
if settings.USE_TRY_ON_CONDITION then
local originalCondition = Condition
Condition = function(func)
return originalCondition(getTryWrapper(func))
end
Filter = Condition
end
if settings.USE_TRY_ON_COROUTINES then
local originalCoroutineCreate = coroutine.create
---@diagnostic disable-next-line: duplicate-set-field
coroutine.create = function(f)
return originalCoroutineCreate(getTryWrapper(f))
end
local originalCoroutineWrap = coroutine.wrap
---@diagnostic disable-next-line: duplicate-set-field
coroutine.wrap = function(f)
return originalCoroutineWrap(getTryWrapper(f))
end
end
------------------------------------------
--| Cache prints during Loading Screen |--
------------------------------------------
-- Apply the duration as specified in the settings.
if settings.PRINT_DURATION then
local display, getLocalPlayer, dur = DisplayTimedTextToPlayer, GetLocalPlayer, settings.PRINT_DURATION
print = function(...)
display(getLocalPlayer(), 0, 0, dur, concat(...))
end
end
-- Delay loading screen prints to after game start.
if settings.USE_PRINT_CACHE then
local oldPrint = print
--loading screen print will write the values into the printCache
print = function(...)
if bj_gameStarted then
oldPrint(...)
else --during loading screen only: concatenate input arguments 4-space-separated, implicitely apply tostring on each, cache to table
printCache.n = printCache.n + 1
printCache[printCache.n] = concat(...)
end
end
end
-------------------------
--| Modify Game Start |--
-------------------------
local originalMarkGameStarted = MarkGameStarted
--Hook certain actions into the start of the game.
MarkGameStarted = function()
originalMarkGameStarted()
if settings.WARNING_FOR_UNDECLARED_GLOBALS then
local existingIndex = getmetatable(_G).__index
local isTable_yn = (type(existingIndex) == 'table')
getmetatable(_G).__index = function(t, k) --we made sure that _G has a metatable further above.
--if string.sub(tostring(k),1,3) ~= 'bj_' then
print("Trying to read undeclared global at " .. getStackTrace(4,4) .. ": " .. tostring(k)
.. (settings.SHOW_TRACE_FOR_UNDECLARED_GLOBALS and "\nTraceback (most recent call first):\n" .. getStackTrace(4,200) or ""))
--end
if existingIndex then
if isTable_yn then
return existingIndex[k]
end
return existingIndex(t,k)
end
return rawget(t,k)
end
end
--Add names to Debug.data.objectNames again to ensure that overwritten natives also make it to the name cache.
--Overwritten natives have a new value, but the old key, so __newindex didn't trigger. But we can be sure that objectNames[v] doesn't yet exist, so adding again is safe.
if settings.USE_NAME_CACHE then
for _,v in pairs(_G) do
nameCache[v] = nil
end
registerNamesFromGlobalScope()
end
--Print messages that have been cached during loading screen.
if settings.USE_PRINT_CACHE then
--Note that we don't restore the old print. The overwritten variant only applies caching behaviour to loading screen prints anyway and "unhooking" always adds other risks.
for _, str in ipairs(printCache) do
print(str)
end
printCache = nil --frees reference for the garbage collector
end
--Create triggers listening to "-console" and "-exec" chat input.
if settings.ALLOW_INGAME_CODE_EXECUTION and IngameConsole then
IngameConsole.createTriggers()
end
end
---------------------
--| Other Utility |--
---------------------
do
---Returns the type of a warcraft object as string, e.g. "unit" upon inputting a unit.
---@param input any
---@return string
function Debug.wc3Type(input)
local typeString = type(input)
if typeString == 'userdata' then
typeString = tostring(input) --tostring returns the warcraft type plus a colon and some hashstuff.
return typeString:sub(1, (typeString:find(":", nil, true) or 0) -1) --string.find returns nil, if the argument is not found, which would break string.sub. So we need to replace by 0.
else
return typeString
end
end
Wc3Type = Debug.wc3Type --for backwards compatibility
local conciseTostring, prettyTostring
---Translates a table into a comma-separated list of its (key,value)-pairs. Also translates subtables up to the specified depth.
---E.g. {"a", 5, {7}} will display as '{(1, "a"), (2, 5), (3, {(1, 7)})}'.
---@param object any
---@param depth? integer default: unlimited. Unlimited depth will throw a stack overflow error on self-referential tables.
---@return string
conciseTostring = function (object, depth)
depth = depth or -1
if type(object) == 'string' then
return '"' .. object .. '"'
elseif depth ~= 0 and type(object) == 'table' then
local elementArray = {}
local keyAsString
for k,v in pairs(object) do
keyAsString = type(k) == 'string' and ('"' .. tostring(k) .. '"') or tostring(k)
table.insert(elementArray, '(' .. keyAsString .. ', ' .. conciseTostring(v, depth -1) .. ')')
end
return '{' .. table.concat(elementArray, ', ') .. '}'
end
return tostring(object)
end
---Creates a list of all (key,value)-pairs from the specified table. Also lists subtable entries up to the specified depth.
---Major differences to concise print are:
--- * Format: Linebreak-formatted instead of one-liner, uses "[key] = value" instead of "(key,value)"
--- * Will also unpack tables used as keys
--- * Also includes the table's memory position as returned by tostring(table).
--- * Tables referenced multiple times will only be unpacked upon first encounter and abbreviated on subsequent encounters
--- * As a consequence, pretty version can be executed with unlimited depth on self-referential tables.
---@param object any
---@param depth? integer default: unlimited.
---@param constTable table
---@param indent string
---@return string
prettyTostring = function(object, depth, constTable, indent)
depth = depth or -1
local objType = type(object)
if objType == "string" then
return '"'..object..'"' --wrap the string in quotes.
elseif objType == 'table' and depth ~= 0 then
if not constTable[object] then
constTable[object] = tostring(object):gsub(":","")
if next(object)==nil then
return constTable[object]..": {}"
else
local mappedKV = {}
for k,v in pairs(object) do
table.insert(mappedKV, '\n ' .. indent ..'[' .. prettyTostring(k, depth - 1, constTable, indent .. " ") .. '] = ' .. prettyTostring(v, depth - 1, constTable, indent .. " "))
end
return constTable[object]..': {'.. table.concat(mappedKV, ',') .. '\n'..indent..'}'
end
end
end
return constTable[object] or tostring(object)
end
---Creates a list of all (key,value)-pairs from the specified table. Also lists subtable entries up to the specified depth.
---Supports concise style and pretty style.
---Concise will display {"a", 5, {7}} as '{(1, "a"), (2, 5), (3, {(1, 7)})}'.
---Pretty is linebreak-separated, so consider table size before converting. Pretty also abbreviates tables referenced multiple times.
---Can be called like table.tostring(T), table.tostring(T, depth), table.tostring(T, pretty_yn) or table.tostring(T, depth, pretty_yn).
---table.tostring is not multiplayer-synced.
---@param whichTable table
---@param depth? integer default: unlimited
---@param pretty_yn? boolean default: false (concise)
---@return string
---@overload fun(whichTable:table, pretty_yn?:boolean):string
function table.tostring(whichTable, depth, pretty_yn)
--reassign input params, if function was called as table.tostring(whichTable, pretty_yn)
if type(depth) == 'boolean' then
pretty_yn = depth
depth = -1
end
return pretty_yn and prettyTostring(whichTable, depth, {}, "") or conciseTostring(whichTable, depth)
end
---Prints a list of (key,value)-pairs contained in the specified table and its subtables up to the specified depth.
---Supports concise style and pretty style. Pretty is linebreak-separated, so consider table size before printing.
---Can be called like table.print(T), table.print(T, depth), table.print(T, pretty_yn) or table.print(T, depth, pretty_yn).
---@param whichTable table
---@param depth? integer default: unlimited
---@param pretty_yn? boolean default: false (concise)
---@overload fun(whichTable:table, pretty_yn?:boolean)
function table.print(whichTable, depth, pretty_yn)
print(table.tostring(whichTable, depth, pretty_yn))
end
end
end
Debug.endFile()
------------------------
----| String Width |----
------------------------
--[[
offers functions to measure the width of a string (i.e. the space it takes on screen, not the number of chars). Wc3 font is not monospace, so the system below has protocolled every char width and simply sums up all chars in a string.
output measures are:
1. Multiboard-width (i.e. 1-based screen share used in Multiboards column functions)
2. Line-width for screen prints
every unknown char will be treated as having default width (see constants below)
--]]
do
----------------------------
----| String Width API |----
----------------------------
local multiboardCharTable = {} ---@type table -- saves the width in screen percent (on 1920 pixel width resolutions) that each char takes up, when displayed in a multiboard.
local DEFAULT_MULTIBOARD_CHAR_WIDTH = 1. / 128. ---@type number -- used for unknown chars (where we didn't define a width in the char table)
local MULTIBOARD_TO_PRINT_FACTOR = 1. / 36. ---@type number -- 36 is actually the lower border (longest width of a non-breaking string only consisting of the letter "i")
---Returns the width of a char in a multiboard, when inputting a char (string of length 1) and 0 otherwise.
---also returns 0 for non-recorded chars (like ` and Β΄ and Γ and Β§ and β¬)
---@param char string | integer integer bytecode representations of chars are also allowed, i.e. the results of string.byte().
---@param textlanguage? '"ger"'| '"eng"' (default: 'eng'), depending on the text language in the Warcraft 3 installation settings.
---@return number
function string.charMultiboardWidth(char, textlanguage)
return multiboardCharTable[textlanguage or 'eng'][char] or DEFAULT_MULTIBOARD_CHAR_WIDTH
end
---returns the width of a string in a multiboard (i.e. output is in screen percent)
---unknown chars will be measured with default width (see constants above)
---@param multichar string
---@param textlanguage? '"ger"'| '"eng"' (default: 'eng'), depending on the text language in the Warcraft 3 installation settings.
---@return number
function string.multiboardWidth(multichar, textlanguage)
local chartable = table.pack(multichar:byte(1,-1)) --packs all bytecode char representations into a table
local charWidth = 0.
for i = 1, chartable.n do
charWidth = charWidth + string.charMultiboardWidth(chartable[i], textlanguage)
end
return charWidth
end
---The function should match the following criteria: If the value returned by this function is smaller than 1.0, than the string fits into a single line on screen.
---The opposite is not necessarily true (but should be true in the majority of cases): If the function returns bigger than 1.0, the string doesn't necessarily break.
---@param char string | integer integer bytecode representations of chars are also allowed, i.e. the results of string.byte().
---@param textlanguage? '"ger"'| '"eng"' (default: 'eng'), depending on the text language in the Warcraft 3 installation settings.
---@return number
function string.charPrintWidth(char, textlanguage)
return string.charMultiboardWidth(char, textlanguage) * MULTIBOARD_TO_PRINT_FACTOR
end
---The function should match the following criteria: If the value returned by this function is smaller than 1.0, than the string fits into a single line on screen.
---The opposite is not necessarily true (but should be true in the majority of cases): If the function returns bigger than 1.0, the string doesn't necessarily break.
---@param multichar string
---@param textlanguage? '"ger"'| '"eng"' (default: 'eng'), depending on the text language in the Warcraft 3 installation settings.
---@return number
function string.printWidth(multichar, textlanguage)
return string.multiboardWidth(multichar, textlanguage) * MULTIBOARD_TO_PRINT_FACTOR
end
----------------------------------
----| String Width Internals |----
----------------------------------
---@param charset '"ger"'| '"eng"' (default: 'eng'), depending on the text language in the Warcraft 3 installation settings.
---@param char string|integer either the char or its bytecode
---@param lengthInScreenWidth number
local function setMultiboardCharWidth(charset, char, lengthInScreenWidth)
multiboardCharTable[charset] = multiboardCharTable[charset] or {}
multiboardCharTable[charset][char] = lengthInScreenWidth
end
---numberPlacements says how often the char can be placed in a multiboard column, before reaching into the right bound.
---@param charset '"ger"'| '"eng"' (default: 'eng'), depending on the text language in the Warcraft 3 installation settings.
---@param char string|integer either the char or its bytecode
---@param numberPlacements integer
local function setMultiboardCharWidthBase80(charset, char, numberPlacements)
setMultiboardCharWidth(charset, char, 0.8 / numberPlacements) --1-based measure. 80./numberPlacements would result in Screen Percent.
setMultiboardCharWidth(charset, char:byte(1,-1), 0.8 / numberPlacements)
end
-- Set Char Width for all printable ascii chars in screen width (1920 pixels). Measured on a 80percent screen width multiboard column by counting the number of chars that fit into it.
-- Font size differs by text install language and patch (1.32- vs. 1.33+)
if BlzGetUnitOrderCount then --identifies patch 1.33+
--German font size for patch 1.33+
setMultiboardCharWidthBase80('ger', "a", 144)
setMultiboardCharWidthBase80('ger', "b", 131)
setMultiboardCharWidthBase80('ger', "c", 144)
setMultiboardCharWidthBase80('ger', "d", 120)
setMultiboardCharWidthBase80('ger', "e", 131)
setMultiboardCharWidthBase80('ger', "f", 240)
setMultiboardCharWidthBase80('ger', "g", 120)
setMultiboardCharWidthBase80('ger', "h", 131)
setMultiboardCharWidthBase80('ger', "i", 288)
setMultiboardCharWidthBase80('ger', "j", 288)
setMultiboardCharWidthBase80('ger', "k", 144)
setMultiboardCharWidthBase80('ger', "l", 288)
setMultiboardCharWidthBase80('ger', "m", 85)
setMultiboardCharWidthBase80('ger', "n", 131)
setMultiboardCharWidthBase80('ger', "o", 120)
setMultiboardCharWidthBase80('ger', "p", 120)
setMultiboardCharWidthBase80('ger', "q", 120)
setMultiboardCharWidthBase80('ger', "r", 206)
setMultiboardCharWidthBase80('ger', "s", 160)
setMultiboardCharWidthBase80('ger', "t", 206)
setMultiboardCharWidthBase80('ger', "u", 131)
setMultiboardCharWidthBase80('ger', "v", 131)
setMultiboardCharWidthBase80('ger', "w", 96)
setMultiboardCharWidthBase80('ger', "x", 144)
setMultiboardCharWidthBase80('ger', "y", 131)
setMultiboardCharWidthBase80('ger', "z", 144)
setMultiboardCharWidthBase80('ger', "A", 103)
setMultiboardCharWidthBase80('ger', "B", 120)
setMultiboardCharWidthBase80('ger', "C", 111)
setMultiboardCharWidthBase80('ger', "D", 103)
setMultiboardCharWidthBase80('ger', "E", 144)
setMultiboardCharWidthBase80('ger', "F", 160)
setMultiboardCharWidthBase80('ger', "G", 96)
setMultiboardCharWidthBase80('ger', "H", 96)
setMultiboardCharWidthBase80('ger', "I", 240)
setMultiboardCharWidthBase80('ger', "J", 240)
setMultiboardCharWidthBase80('ger', "K", 120)
setMultiboardCharWidthBase80('ger', "L", 144)
setMultiboardCharWidthBase80('ger', "M", 76)
setMultiboardCharWidthBase80('ger', "N", 96)
setMultiboardCharWidthBase80('ger', "O", 90)
setMultiboardCharWidthBase80('ger', "P", 131)
setMultiboardCharWidthBase80('ger', "Q", 90)
setMultiboardCharWidthBase80('ger', "R", 120)
setMultiboardCharWidthBase80('ger', "S", 131)
setMultiboardCharWidthBase80('ger', "T", 144)
setMultiboardCharWidthBase80('ger', "U", 103)
setMultiboardCharWidthBase80('ger', "V", 120)
setMultiboardCharWidthBase80('ger', "W", 76)
setMultiboardCharWidthBase80('ger', "X", 111)
setMultiboardCharWidthBase80('ger', "Y", 120)
setMultiboardCharWidthBase80('ger', "Z", 120)
setMultiboardCharWidthBase80('ger', "1", 144)
setMultiboardCharWidthBase80('ger', "2", 120)
setMultiboardCharWidthBase80('ger', "3", 120)
setMultiboardCharWidthBase80('ger', "4", 120)
setMultiboardCharWidthBase80('ger', "5", 120)
setMultiboardCharWidthBase80('ger', "6", 120)
setMultiboardCharWidthBase80('ger', "7", 131)
setMultiboardCharWidthBase80('ger', "8", 120)
setMultiboardCharWidthBase80('ger', "9", 120)
setMultiboardCharWidthBase80('ger', "0", 120)
setMultiboardCharWidthBase80('ger', ":", 288)
setMultiboardCharWidthBase80('ger', ";", 288)
setMultiboardCharWidthBase80('ger', ".", 288)
setMultiboardCharWidthBase80('ger', "#", 120)
setMultiboardCharWidthBase80('ger', ",", 288)
setMultiboardCharWidthBase80('ger', " ", 286) --space
setMultiboardCharWidthBase80('ger', "'", 180)
setMultiboardCharWidthBase80('ger', "!", 180)
setMultiboardCharWidthBase80('ger', "$", 131)
setMultiboardCharWidthBase80('ger', "&", 90)
setMultiboardCharWidthBase80('ger', "/", 180)
setMultiboardCharWidthBase80('ger', "(", 240)
setMultiboardCharWidthBase80('ger', ")", 240)
setMultiboardCharWidthBase80('ger', "=", 120)
setMultiboardCharWidthBase80('ger', "?", 144)
setMultiboardCharWidthBase80('ger', "^", 144)
setMultiboardCharWidthBase80('ger', "<", 144)
setMultiboardCharWidthBase80('ger', ">", 144)
setMultiboardCharWidthBase80('ger', "-", 180)
setMultiboardCharWidthBase80('ger', "+", 120)
setMultiboardCharWidthBase80('ger', "*", 180)
setMultiboardCharWidthBase80('ger', "|", 287) --2 vertical bars in a row escape to one. So you could print 960 ones in a line, 480 would display. Maybe need to adapt to this before calculating string width.
setMultiboardCharWidthBase80('ger', "~", 111)
setMultiboardCharWidthBase80('ger', "{", 240)
setMultiboardCharWidthBase80('ger', "}", 240)
setMultiboardCharWidthBase80('ger', "[", 240)
setMultiboardCharWidthBase80('ger', "]", 240)
setMultiboardCharWidthBase80('ger', "_", 144)
setMultiboardCharWidthBase80('ger', "\x25", 103) --percent
setMultiboardCharWidthBase80('ger', "\x5C", 205) --backslash
setMultiboardCharWidthBase80('ger', "\x22", 120) --double quotation mark
setMultiboardCharWidthBase80('ger', "\x40", 90) --at sign
setMultiboardCharWidthBase80('ger', "\x60", 144) --Gravis (Accent)
--English font size for patch 1.33+
setMultiboardCharWidthBase80('eng', "a", 144)
setMultiboardCharWidthBase80('eng', "b", 120)
setMultiboardCharWidthBase80('eng', "c", 131)
setMultiboardCharWidthBase80('eng', "d", 120)
setMultiboardCharWidthBase80('eng', "e", 120)
setMultiboardCharWidthBase80('eng', "f", 240)
setMultiboardCharWidthBase80('eng', "g", 120)
setMultiboardCharWidthBase80('eng', "h", 120)
setMultiboardCharWidthBase80('eng', "i", 288)
setMultiboardCharWidthBase80('eng', "j", 288)
setMultiboardCharWidthBase80('eng', "k", 144)
setMultiboardCharWidthBase80('eng', "l", 288)
setMultiboardCharWidthBase80('eng', "m", 80)
setMultiboardCharWidthBase80('eng', "n", 120)
setMultiboardCharWidthBase80('eng', "o", 111)
setMultiboardCharWidthBase80('eng', "p", 111)
setMultiboardCharWidthBase80('eng', "q", 111)
setMultiboardCharWidthBase80('eng', "r", 206)
setMultiboardCharWidthBase80('eng', "s", 160)
setMultiboardCharWidthBase80('eng', "t", 206)
setMultiboardCharWidthBase80('eng', "u", 120)
setMultiboardCharWidthBase80('eng', "v", 144)
setMultiboardCharWidthBase80('eng', "w", 90)
setMultiboardCharWidthBase80('eng', "x", 131)
setMultiboardCharWidthBase80('eng', "y", 144)
setMultiboardCharWidthBase80('eng', "z", 144)
setMultiboardCharWidthBase80('eng', "A", 103)
setMultiboardCharWidthBase80('eng', "B", 120)
setMultiboardCharWidthBase80('eng', "C", 103)
setMultiboardCharWidthBase80('eng', "D", 96)
setMultiboardCharWidthBase80('eng', "E", 131)
setMultiboardCharWidthBase80('eng', "F", 160)
setMultiboardCharWidthBase80('eng', "G", 96)
setMultiboardCharWidthBase80('eng', "H", 90)
setMultiboardCharWidthBase80('eng', "I", 240)
setMultiboardCharWidthBase80('eng', "J", 240)
setMultiboardCharWidthBase80('eng', "K", 120)
setMultiboardCharWidthBase80('eng', "L", 131)
setMultiboardCharWidthBase80('eng', "M", 76)
setMultiboardCharWidthBase80('eng', "N", 90)
setMultiboardCharWidthBase80('eng', "O", 85)
setMultiboardCharWidthBase80('eng', "P", 120)
setMultiboardCharWidthBase80('eng', "Q", 85)
setMultiboardCharWidthBase80('eng', "R", 120)
setMultiboardCharWidthBase80('eng', "S", 131)
setMultiboardCharWidthBase80('eng', "T", 144)
setMultiboardCharWidthBase80('eng', "U", 96)
setMultiboardCharWidthBase80('eng', "V", 120)
setMultiboardCharWidthBase80('eng', "W", 76)
setMultiboardCharWidthBase80('eng', "X", 111)
setMultiboardCharWidthBase80('eng', "Y", 120)
setMultiboardCharWidthBase80('eng', "Z", 111)
setMultiboardCharWidthBase80('eng', "1", 103)
setMultiboardCharWidthBase80('eng', "2", 111)
setMultiboardCharWidthBase80('eng', "3", 111)
setMultiboardCharWidthBase80('eng', "4", 111)
setMultiboardCharWidthBase80('eng', "5", 111)
setMultiboardCharWidthBase80('eng', "6", 111)
setMultiboardCharWidthBase80('eng', "7", 111)
setMultiboardCharWidthBase80('eng', "8", 111)
setMultiboardCharWidthBase80('eng', "9", 111)
setMultiboardCharWidthBase80('eng', "0", 111)
setMultiboardCharWidthBase80('eng', ":", 288)
setMultiboardCharWidthBase80('eng', ";", 288)
setMultiboardCharWidthBase80('eng', ".", 288)
setMultiboardCharWidthBase80('eng', "#", 103)
setMultiboardCharWidthBase80('eng', ",", 288)
setMultiboardCharWidthBase80('eng', " ", 286) --space
setMultiboardCharWidthBase80('eng', "'", 360)
setMultiboardCharWidthBase80('eng', "!", 288)
setMultiboardCharWidthBase80('eng', "$", 131)
setMultiboardCharWidthBase80('eng', "&", 120)
setMultiboardCharWidthBase80('eng', "/", 180)
setMultiboardCharWidthBase80('eng', "(", 206)
setMultiboardCharWidthBase80('eng', ")", 206)
setMultiboardCharWidthBase80('eng', "=", 111)
setMultiboardCharWidthBase80('eng', "?", 180)
setMultiboardCharWidthBase80('eng', "^", 144)
setMultiboardCharWidthBase80('eng', "<", 111)
setMultiboardCharWidthBase80('eng', ">", 111)
setMultiboardCharWidthBase80('eng', "-", 160)
setMultiboardCharWidthBase80('eng', "+", 111)
setMultiboardCharWidthBase80('eng', "*", 144)
setMultiboardCharWidthBase80('eng', "|", 479) --2 vertical bars in a row escape to one. So you could print 960 ones in a line, 480 would display. Maybe need to adapt to this before calculating string width.
setMultiboardCharWidthBase80('eng', "~", 144)
setMultiboardCharWidthBase80('eng', "{", 160)
setMultiboardCharWidthBase80('eng', "}", 160)
setMultiboardCharWidthBase80('eng', "[", 206)
setMultiboardCharWidthBase80('eng', "]", 206)
setMultiboardCharWidthBase80('eng', "_", 120)
setMultiboardCharWidthBase80('eng', "\x25", 103) --percent
setMultiboardCharWidthBase80('eng', "\x5C", 180) --backslash
setMultiboardCharWidthBase80('eng', "\x22", 180) --double quotation mark
setMultiboardCharWidthBase80('eng', "\x40", 85) --at sign
setMultiboardCharWidthBase80('eng', "\x60", 206) --Gravis (Accent)
else
--German font size up to patch 1.32
setMultiboardCharWidthBase80('ger', "a", 144)
setMultiboardCharWidthBase80('ger', "b", 144)
setMultiboardCharWidthBase80('ger', "c", 144)
setMultiboardCharWidthBase80('ger', "d", 131)
setMultiboardCharWidthBase80('ger', "e", 144)
setMultiboardCharWidthBase80('ger', "f", 240)
setMultiboardCharWidthBase80('ger', "g", 120)
setMultiboardCharWidthBase80('ger', "h", 144)
setMultiboardCharWidthBase80('ger', "i", 360)
setMultiboardCharWidthBase80('ger', "j", 288)
setMultiboardCharWidthBase80('ger', "k", 144)
setMultiboardCharWidthBase80('ger', "l", 360)
setMultiboardCharWidthBase80('ger', "m", 90)
setMultiboardCharWidthBase80('ger', "n", 144)
setMultiboardCharWidthBase80('ger', "o", 131)
setMultiboardCharWidthBase80('ger', "p", 131)
setMultiboardCharWidthBase80('ger', "q", 131)
setMultiboardCharWidthBase80('ger', "r", 206)
setMultiboardCharWidthBase80('ger', "s", 180)
setMultiboardCharWidthBase80('ger', "t", 206)
setMultiboardCharWidthBase80('ger', "u", 144)
setMultiboardCharWidthBase80('ger', "v", 131)
setMultiboardCharWidthBase80('ger', "w", 96)
setMultiboardCharWidthBase80('ger', "x", 144)
setMultiboardCharWidthBase80('ger', "y", 131)
setMultiboardCharWidthBase80('ger', "z", 144)
setMultiboardCharWidthBase80('ger', "A", 103)
setMultiboardCharWidthBase80('ger', "B", 131)
setMultiboardCharWidthBase80('ger', "C", 120)
setMultiboardCharWidthBase80('ger', "D", 111)
setMultiboardCharWidthBase80('ger', "E", 144)
setMultiboardCharWidthBase80('ger', "F", 180)
setMultiboardCharWidthBase80('ger', "G", 103)
setMultiboardCharWidthBase80('ger', "H", 103)
setMultiboardCharWidthBase80('ger', "I", 288)
setMultiboardCharWidthBase80('ger', "J", 240)
setMultiboardCharWidthBase80('ger', "K", 120)
setMultiboardCharWidthBase80('ger', "L", 144)
setMultiboardCharWidthBase80('ger', "M", 80)
setMultiboardCharWidthBase80('ger', "N", 103)
setMultiboardCharWidthBase80('ger', "O", 96)
setMultiboardCharWidthBase80('ger', "P", 144)
setMultiboardCharWidthBase80('ger', "Q", 90)
setMultiboardCharWidthBase80('ger', "R", 120)
setMultiboardCharWidthBase80('ger', "S", 144)
setMultiboardCharWidthBase80('ger', "T", 144)
setMultiboardCharWidthBase80('ger', "U", 111)
setMultiboardCharWidthBase80('ger', "V", 120)
setMultiboardCharWidthBase80('ger', "W", 76)
setMultiboardCharWidthBase80('ger', "X", 111)
setMultiboardCharWidthBase80('ger', "Y", 120)
setMultiboardCharWidthBase80('ger', "Z", 120)
setMultiboardCharWidthBase80('ger', "1", 288)
setMultiboardCharWidthBase80('ger', "2", 131)
setMultiboardCharWidthBase80('ger', "3", 144)
setMultiboardCharWidthBase80('ger', "4", 120)
setMultiboardCharWidthBase80('ger', "5", 144)
setMultiboardCharWidthBase80('ger', "6", 131)
setMultiboardCharWidthBase80('ger', "7", 144)
setMultiboardCharWidthBase80('ger', "8", 131)
setMultiboardCharWidthBase80('ger', "9", 131)
setMultiboardCharWidthBase80('ger', "0", 131)
setMultiboardCharWidthBase80('ger', ":", 480)
setMultiboardCharWidthBase80('ger', ";", 360)
setMultiboardCharWidthBase80('ger', ".", 480)
setMultiboardCharWidthBase80('ger', "#", 120)
setMultiboardCharWidthBase80('ger', ",", 360)
setMultiboardCharWidthBase80('ger', " ", 288) --space
setMultiboardCharWidthBase80('ger', "'", 480)
setMultiboardCharWidthBase80('ger', "!", 360)
setMultiboardCharWidthBase80('ger', "$", 160)
setMultiboardCharWidthBase80('ger', "&", 96)
setMultiboardCharWidthBase80('ger', "/", 180)
setMultiboardCharWidthBase80('ger', "(", 288)
setMultiboardCharWidthBase80('ger', ")", 288)
setMultiboardCharWidthBase80('ger', "=", 160)
setMultiboardCharWidthBase80('ger', "?", 180)
setMultiboardCharWidthBase80('ger', "^", 144)
setMultiboardCharWidthBase80('ger', "<", 160)
setMultiboardCharWidthBase80('ger', ">", 160)
setMultiboardCharWidthBase80('ger', "-", 144)
setMultiboardCharWidthBase80('ger', "+", 160)
setMultiboardCharWidthBase80('ger', "*", 206)
setMultiboardCharWidthBase80('ger', "|", 480) --2 vertical bars in a row escape to one. So you could print 960 ones in a line, 480 would display. Maybe need to adapt to this before calculating string width.
setMultiboardCharWidthBase80('ger', "~", 144)
setMultiboardCharWidthBase80('ger', "{", 240)
setMultiboardCharWidthBase80('ger', "}", 240)
setMultiboardCharWidthBase80('ger', "[", 240)
setMultiboardCharWidthBase80('ger', "]", 288)
setMultiboardCharWidthBase80('ger', "_", 144)
setMultiboardCharWidthBase80('ger', "\x25", 111) --percent
setMultiboardCharWidthBase80('ger', "\x5C", 206) --backslash
setMultiboardCharWidthBase80('ger', "\x22", 240) --double quotation mark
setMultiboardCharWidthBase80('ger', "\x40", 103) --at sign
setMultiboardCharWidthBase80('ger', "\x60", 240) --Gravis (Accent)
--English Font size up to patch 1.32
setMultiboardCharWidthBase80('eng', "a", 144)
setMultiboardCharWidthBase80('eng', "b", 120)
setMultiboardCharWidthBase80('eng', "c", 131)
setMultiboardCharWidthBase80('eng', "d", 120)
setMultiboardCharWidthBase80('eng', "e", 131)
setMultiboardCharWidthBase80('eng', "f", 240)
setMultiboardCharWidthBase80('eng', "g", 120)
setMultiboardCharWidthBase80('eng', "h", 131)
setMultiboardCharWidthBase80('eng', "i", 360)
setMultiboardCharWidthBase80('eng', "j", 288)
setMultiboardCharWidthBase80('eng', "k", 144)
setMultiboardCharWidthBase80('eng', "l", 360)
setMultiboardCharWidthBase80('eng', "m", 80)
setMultiboardCharWidthBase80('eng', "n", 131)
setMultiboardCharWidthBase80('eng', "o", 120)
setMultiboardCharWidthBase80('eng', "p", 120)
setMultiboardCharWidthBase80('eng', "q", 120)
setMultiboardCharWidthBase80('eng', "r", 206)
setMultiboardCharWidthBase80('eng', "s", 160)
setMultiboardCharWidthBase80('eng', "t", 206)
setMultiboardCharWidthBase80('eng', "u", 131)
setMultiboardCharWidthBase80('eng', "v", 144)
setMultiboardCharWidthBase80('eng', "w", 90)
setMultiboardCharWidthBase80('eng', "x", 131)
setMultiboardCharWidthBase80('eng', "y", 144)
setMultiboardCharWidthBase80('eng', "z", 144)
setMultiboardCharWidthBase80('eng', "A", 103)
setMultiboardCharWidthBase80('eng', "B", 120)
setMultiboardCharWidthBase80('eng', "C", 103)
setMultiboardCharWidthBase80('eng', "D", 103)
setMultiboardCharWidthBase80('eng', "E", 131)
setMultiboardCharWidthBase80('eng', "F", 160)
setMultiboardCharWidthBase80('eng', "G", 103)
setMultiboardCharWidthBase80('eng', "H", 96)
setMultiboardCharWidthBase80('eng', "I", 288)
setMultiboardCharWidthBase80('eng', "J", 240)
setMultiboardCharWidthBase80('eng', "K", 120)
setMultiboardCharWidthBase80('eng', "L", 131)
setMultiboardCharWidthBase80('eng', "M", 76)
setMultiboardCharWidthBase80('eng', "N", 96)
setMultiboardCharWidthBase80('eng', "O", 85)
setMultiboardCharWidthBase80('eng', "P", 131)
setMultiboardCharWidthBase80('eng', "Q", 85)
setMultiboardCharWidthBase80('eng', "R", 120)
setMultiboardCharWidthBase80('eng', "S", 131)
setMultiboardCharWidthBase80('eng', "T", 144)
setMultiboardCharWidthBase80('eng', "U", 103)
setMultiboardCharWidthBase80('eng', "V", 120)
setMultiboardCharWidthBase80('eng', "W", 76)
setMultiboardCharWidthBase80('eng', "X", 111)
setMultiboardCharWidthBase80('eng', "Y", 120)
setMultiboardCharWidthBase80('eng', "Z", 111)
setMultiboardCharWidthBase80('eng', "1", 206)
setMultiboardCharWidthBase80('eng', "2", 131)
setMultiboardCharWidthBase80('eng', "3", 131)
setMultiboardCharWidthBase80('eng', "4", 111)
setMultiboardCharWidthBase80('eng', "5", 131)
setMultiboardCharWidthBase80('eng', "6", 120)
setMultiboardCharWidthBase80('eng', "7", 131)
setMultiboardCharWidthBase80('eng', "8", 111)
setMultiboardCharWidthBase80('eng', "9", 120)
setMultiboardCharWidthBase80('eng', "0", 111)
setMultiboardCharWidthBase80('eng', ":", 360)
setMultiboardCharWidthBase80('eng', ";", 360)
setMultiboardCharWidthBase80('eng', ".", 360)
setMultiboardCharWidthBase80('eng', "#", 103)
setMultiboardCharWidthBase80('eng', ",", 360)
setMultiboardCharWidthBase80('eng', " ", 288) --space
setMultiboardCharWidthBase80('eng', "'", 480)
setMultiboardCharWidthBase80('eng', "!", 360)
setMultiboardCharWidthBase80('eng', "$", 131)
setMultiboardCharWidthBase80('eng', "&", 120)
setMultiboardCharWidthBase80('eng', "/", 180)
setMultiboardCharWidthBase80('eng', "(", 240)
setMultiboardCharWidthBase80('eng', ")", 240)
setMultiboardCharWidthBase80('eng', "=", 111)
setMultiboardCharWidthBase80('eng', "?", 180)
setMultiboardCharWidthBase80('eng', "^", 144)
setMultiboardCharWidthBase80('eng', "<", 131)
setMultiboardCharWidthBase80('eng', ">", 131)
setMultiboardCharWidthBase80('eng', "-", 180)
setMultiboardCharWidthBase80('eng', "+", 111)
setMultiboardCharWidthBase80('eng', "*", 180)
setMultiboardCharWidthBase80('eng', "|", 480) --2 vertical bars in a row escape to one. So you could print 960 ones in a line, 480 would display. Maybe need to adapt to this before calculating string width.
setMultiboardCharWidthBase80('eng', "~", 144)
setMultiboardCharWidthBase80('eng', "{", 240)
setMultiboardCharWidthBase80('eng', "}", 240)
setMultiboardCharWidthBase80('eng', "[", 240)
setMultiboardCharWidthBase80('eng', "]", 240)
setMultiboardCharWidthBase80('eng', "_", 120)
setMultiboardCharWidthBase80('eng', "\x25", 103) --percent
setMultiboardCharWidthBase80('eng', "\x5C", 180) --backslash
setMultiboardCharWidthBase80('eng', "\x22", 206) --double quotation mark
setMultiboardCharWidthBase80('eng', "\x40", 96) --at sign
setMultiboardCharWidthBase80('eng', "\x60", 206) --Gravis (Accent)
end
end
Debug.beginFile("IngameConsole")
--[[
--------------------------
----| Ingame Console |----
--------------------------
/**********************************************
* Allows you to use the following ingame commands:
* "-exec <code>" to execute any code ingame.
* "-console" to start an ingame console interpreting any further chat input as code and showing both return values of function calls and error messages. Furthermore, the print function will print
* directly to the console after it got started. You can still look up all print messages in the F12-log.
***********************
* -------------------
* |Using the console|
* -------------------
* Any (well, most) chat input by any player after starting the console is interpreted as code and directly executed. You can enter terms (like 4+5 or just any variable name), function calls (like print("bla"))
* and set-statements (like y = 5). If the code has any return values, all of them are printed to the console. Erroneous code will print an error message.
* Chat input starting with a hyphen is being ignored by the console, i.e. neither executed as code nor printed to the console. This allows you to still use other chat commands like "-exec" without prompting errors.
***********************
* ------------------
* |Multiline-Inputs|
* ------------------
* You can prevent a chat input from being immediately executed by preceeding it with the '>' character. All lines entered this way are halted, until any line not starting with '>' is being entered.
* The first input without '>' will execute all halted lines (and itself) in one chunk.
* Example of a chat input (the console will add an additional '>' to every line):
* >function a(x)
* >return x
* end
***********************
* Note that multiline inputs don't accept pure term evaluations, e.g. the following input is not supported and will prompt an error, while the same lines would have worked as two single-line inputs:
* >x = 5
* x
***********************
* -------------------
* |Reserved Keywords|
* -------------------
* The following keywords have a reserved functionality, i.e. are direct commands for the console and will not be interpreted as code:
* - 'help' - will show a list of all reserved keywords along very short explanations.
* - 'exit' - will shut down the console
* - 'share' - will share the players console with every other player, allowing others to read and write into it. Will force-close other players consoles, if they have one active.
* - 'clear' - will clear all text from the console, except the word 'clear'
* - 'lasttrace' - will show the stack trace of the latest error that occured within IngameConsole
* - 'show' - will show the console, after it was accidently hidden (you can accidently hide it by showing another multiboard, while the console functionality is still up and running).
* - 'printtochat' - will let the print function return to normal behaviour (i.e. print to the chat instead of the console).
* - 'printtoconsole'- will let the print function print to the console (which is default behaviour).
* - 'autosize on' - will enable automatic console resize depending on the longest string in the display. This is turned on by default.
* - 'autosize off' - will disable automatic console resize and instead linebreak long strings into multiple lines.
* - 'textlang eng' - lets the console use english Wc3 text language font size to compute linebreaks (look in your Blizzard launcher settings to find out)
* - 'textlang ger' - lets the console use german Wc3 text language font size to compute linebreaks (look in your Blizzard launcher settings to find out)
***********************
* --------------
* |Paste Helper|
* --------------
* @Luashine has created a tool that simplifies pasting multiple lines of code from outside Wc3 into the IngameConsole.
* This is particularly useful, when you want to execute a large chunk of testcode containing several linebreaks.
* Goto: https://github.com/Luashine/wc3-debug-console-paste-helper#readme
*
*************************************************/
--]]
----------------
--| Settings |--
----------------
---@class IngameConsole
IngameConsole = {
--Settings
numRows = 20 ---@type integer Number of Rows of the console (multiboard), excluding the title row. So putting 20 here will show 21 rows, first being the title row.
, autosize = true ---@type boolean Defines, whether the width of the main Column automatically adjusts with the longest string in the display.
, currentWidth = 0.5 ---@type number Current and starting Screen Share of the console main column.
, mainColMinWidth = 0.3 ---@type number Minimum Screen share of the console main column.
, mainColMaxWidth = 0.8 ---@type number Maximum Scren share of the console main column.
, tsColumnWidth = 0.06 ---@type number Screen Share of the Timestamp Column
, linebreakBuffer = 0.008 ---@type number Screen Share that is added to longest string in display to calculate the screen share for the console main column. Compensates for the small inaccuracy of the String Width function.
, maxLinebreaks = 8 ---@type integer Defines the maximum amount of linebreaks, before the remaining output string will be cut and not further displayed.
, printToConsole = true ---@type boolean defines, if the print function should print to the console or to the chat
, sharedConsole = false ---@type boolean defines, if the console is displayed to each player at the same time (accepting all players input) or if all players much start their own console.
, showTraceOnError = false ---@type boolean defines, if the console shows a trace upon printing errors. Usually not too useful within console, because you have just initiated the erroneous call.
, textLanguage = 'eng' ---@type string text language of your Wc3 installation, which influences font size (look in the settings of your Blizzard launcher). Currently only supports 'eng' and 'ger'.
, colors = {
timestamp = "bbbbbb" ---@type string Timestamp Color
, singleLineInput = "ffffaa" ---@type string Color to be applied to single line console inputs
, multiLineInput = "ffcc55" ---@type string Color to be applied to multi line console inputs
, returnValue = "00ffff" ---@type string Color applied to return values
, error = "ff5555" ---@type string Color to be applied to errors resulting of function calls
, keywordInput = "ff00ff" ---@type string Color to be applied to reserved keyword inputs (console reserved keywords)
, info = "bbbbbb" ---@type string Color to be applied to info messages from the console itself (for instance after creation or after printrestore)
}
--Privates
, numCols = 2 ---@type integer Number of Columns of the console (multiboard). Adjusting this requires further changes on code base.
, player = nil ---@type player player for whom the console is being created
, currentLine = 0 ---@type integer Current Output Line of the console.
, inputload = '' ---@type string Input Holder for multi-line-inputs
, output = {} ---@type string[] Array of all output strings
, outputTimestamps = {} ---@type string[] Array of all output string timestamps
, outputWidths = {} ---@type number[] remembers all string widths to allow for multiboard resize
, trigger = nil ---@type trigger trigger processing all inputs during console lifetime
, multiboard = nil ---@type multiboard
, timer = nil ---@type timer gets started upon console creation to measure timestamps
, errorHandler = nil ---@type fun(errorMsg:string):string error handler to be used within xpcall. We create one per console to make it compatible with console-specific settings.
, lastTrace = '' ---@type string trace of last error occured within console. To be printed via reserved keyword "lasttrace"
--Statics
, keywords = {} ---@type table<string,function> saves functions to be executed for all reserved keywords
, playerConsoles = {} ---@type table<player,IngameConsole> Consoles currently being active. up to one per player.
, originalPrint = print ---@type function original print function to restore, after the console gets closed.
}
IngameConsole.__index = IngameConsole
IngameConsole.__name = 'IngameConsole'
------------------------
--| Console Creation |--
------------------------
---Creates and opens up a new console.
---@param consolePlayer player player for whom the console is being created
---@return IngameConsole
function IngameConsole.create(consolePlayer)
local new = {} ---@type IngameConsole
setmetatable(new, IngameConsole)
---setup Object data
new.player = consolePlayer
new.output = {}
new.outputTimestamps = {}
new.outputWidths = {}
--Timer
new.timer = CreateTimer()
TimerStart(new.timer, 3600., true, nil) --just to get TimeElapsed for printing Timestamps.
--Trigger to be created after short delay, because otherwise it would fire on "-console" input immediately and lead to stack overflow.
new:setupTrigger()
--Multiboard
new:setupMultiboard()
--Create own error handler per console to be compatible with console-specific settings
new:setupErrorHandler()
--Share, if settings say so
if IngameConsole.sharedConsole then
new:makeShared() --we don't have to exit other players consoles, because we look for the setting directly in the class and there just logically can't be other active consoles.
end
--Welcome Message
new:out('info', 0, false, "Console started. Any further chat input will be executed as code, except when beginning with \x22-\x22.")
return new
end
---Creates the multiboard used for console display.
function IngameConsole:setupMultiboard()
self.multiboard = CreateMultiboard()
MultiboardSetRowCount(self.multiboard, self.numRows + 1) --title row adds 1
MultiboardSetColumnCount(self.multiboard, self.numCols)
MultiboardSetTitleText(self.multiboard, "Console")
local mbitem
for col = 1, self.numCols do
for row = 1, self.numRows + 1 do --Title row adds 1
mbitem = MultiboardGetItem(self.multiboard, row -1, col -1)
MultiboardSetItemStyle(mbitem, true, false)
MultiboardSetItemValueColor(mbitem, 255, 255, 255, 255) -- Colors get applied via text color code
MultiboardSetItemWidth(mbitem, (col == 1 and self.tsColumnWidth) or self.currentWidth )
MultiboardReleaseItem(mbitem)
end
end
mbitem = MultiboardGetItem(self.multiboard, 0, 0)
MultiboardSetItemValue(mbitem, "|cffffcc00Timestamp|r")
MultiboardReleaseItem(mbitem)
mbitem = MultiboardGetItem(self.multiboard, 0, 1)
MultiboardSetItemValue(mbitem, "|cffffcc00Line|r")
MultiboardReleaseItem(mbitem)
self:showToOwners()
end
---Creates the trigger that responds to chat events.
function IngameConsole:setupTrigger()
self.trigger = CreateTrigger()
TriggerRegisterPlayerChatEvent(self.trigger, self.player, "", false) --triggers on any input of self.player
TriggerAddCondition(self.trigger, Condition(function() return string.sub(GetEventPlayerChatString(),1,1) ~= '-' end)) --console will not react to entered stuff starting with '-'. This still allows to use other chat orders like "-exec".
TriggerAddAction(self.trigger, function() self:processInput(GetEventPlayerChatString()) end)
end
---Creates an Error Handler to be used by xpcall below.
---Adds stack trace plus formatting to the message.
function IngameConsole:setupErrorHandler()
self.errorHandler = function(errorMsg)
errorMsg = Debug.getLocalErrorMsg(errorMsg)
local _, tracePiece, lastFile = nil, "", errorMsg:match("^.-:") or "<unknown>" -- errors on objects created within Ingame Console don't have a file and linenumber. Consider "x = {}; x[nil] = 5".
local fullMsg = errorMsg .. "\nTraceback (most recent call first):\n" .. (errorMsg:match("^.-:\x25d+") or "<unknown>")
--Get Stack Trace. Starting at depth 5 ensures that "error", "messageHandler", "xpcall" and the input error message are not included.
for loopDepth = 5, 50 do --get trace on depth levels up to 50
---@diagnostic disable-next-line: cast-local-type, assign-type-mismatch
_, tracePiece = pcall(error, "", loopDepth) ---@type boolean, string
tracePiece = Debug.getLocalErrorMsg(tracePiece)
if #tracePiece > 0 then --some trace pieces can be empty, but there can still be valid ones beyond that
fullMsg = fullMsg .. " <- " .. ((tracePiece:match("^.-:") == lastFile) and tracePiece:match(":\x25d+"):sub(2,-1) or tracePiece:match("^.-:\x25d+"))
lastFile = tracePiece:match("^.-:")
end
end
self.lastTrace = fullMsg
return "ERROR: " .. (self.showTraceOnError and fullMsg or errorMsg)
end
end
---Shares this console with all players.
function IngameConsole:makeShared()
local player
for i = 0, GetBJMaxPlayers() -1 do
player = Player(i)
if (GetPlayerSlotState(player) == PLAYER_SLOT_STATE_PLAYING) and (IngameConsole.playerConsoles[player] ~= self) then --second condition ensures that the player chat event is not added twice for the same player.
IngameConsole.playerConsoles[player] = self
TriggerRegisterPlayerChatEvent(self.trigger, player, "", false) --triggers on any input
end
end
self.sharedConsole = true
end
---------------------
--| In |--
---------------------
---Processes a chat string. Each input will be printed. Incomplete multiline-inputs will be halted until completion. Completed inputs will be converted to a function and executed. If they have an output, it will be printed.
---@param inputString string
function IngameConsole:processInput(inputString)
--if the input is a reserved keyword, conduct respective actions and skip remaining actions.
if IngameConsole.keywords[inputString] then --if the input string is a reserved keyword
self:out('keywordInput', 1, false, inputString)
IngameConsole.keywords[inputString](self) --then call the method with the same name. IngameConsole.keywords["exit"](self) is just self.keywords:exit().
return
end
--if the input is a multi-line-input, queue it into the string buffer (inputLoad), but don't yet execute anything
if string.sub(inputString, 1, 1) == '>' then --multiLineInput
inputString = string.sub(inputString, 2, -1)
self:out('multiLineInput',2, false, inputString)
self.inputload = self.inputload .. inputString .. '\r' --carriage return
else --if the input is either singleLineInput OR the last line of multiLineInput, execute the whole thing.
self:out(self.inputload == '' and 'singleLineInput' or 'multiLineInput', 1, false, inputString)
self.inputload = self.inputload .. inputString
local loadedFunc, errorMsg = load("return " .. self.inputload) --adds return statements, if possible (works for term statements)
if loadedFunc == nil then
loadedFunc, errorMsg = load(self.inputload)
end
self.inputload = '' --empty inputload before execution of pcall. pcall can break (rare case, can for example be provoked with metatable.__tostring = {}), which would corrupt future console inputs.
--manually catch case, where the input did not define a proper Lua statement (i.e. loadfunc is nil)
local results = loadedFunc and table.pack(xpcall(loadedFunc, self.errorHandler)) or {false, "Input is not a valid Lua-statement: " .. errorMsg}
--output error message (unsuccessful case) or return values (successful case)
if not results[1] then --results[1] is the error status that pcall always returns. False stands for: error occured.
self:out('error', 0, true, results[2]) -- second result of pcall is the error message in case an error occured
elseif results.n > 1 then --Check, if there was at least one valid output argument. We check results.n instead of results[2], because we also get nil as a proper return value this way.
self:out('returnValue', 0, true, table.unpack(results, 2, results.n))
end
end
end
----------------------
--| Out |--
----------------------
-- split color codes, split linebreaks, print lines separately, print load-errors, update string width, update text, error handling with stack trace.
---Duplicates Color coding around linebreaks to make each line printable separately.
---Operates incorrectly on lookalike color codes invalidated by preceeding escaped vertical bar (like "||cffffcc00bla|r").
---Also operates incorrectly on multiple color codes, where the first is missing the end sequence (like "|cffffcc00Hello |cff0000ffWorld|r")
---@param inputString string
---@return string, integer
function IngameConsole.spreadColorCodes(inputString)
local replacementTable = {} --remembers all substrings to be replaced and their replacements.
for foundInstance, color in inputString:gmatch("((|c\x25x\x25x\x25x\x25x\x25x\x25x\x25x\x25x).-|r)") do
replacementTable[foundInstance] = foundInstance:gsub("(\r?\n)", "|r\x251" .. color)
end
return inputString:gsub("((|c\x25x\x25x\x25x\x25x\x25x\x25x\x25x\x25x).-|r)", replacementTable)
end
---Concatenates all inputs to one string, spreads color codes around line breaks and prints each line to the console separately.
---@param colorTheme? '"timestamp"'| '"singleLineInput"' | '"multiLineInput"' | '"result"' | '"keywordInput"' | '"info"' | '"error"' | '"returnValue"' Decides about the color to be applied. Currently accepted: 'timestamp', 'singleLineInput', 'multiLineInput', 'result', nil. (nil equals no colorTheme, i.e. white color)
---@param numIndentations integer Number of '>' chars that shall preceed the output
---@param hideTimestamp boolean Set to false to hide the timestamp column and instead show a "->" symbol.
---@param ... any the things to be printed in the console.
function IngameConsole:out(colorTheme, numIndentations, hideTimestamp, ...)
local inputs = table.pack(...)
for i = 1, inputs.n do
inputs[i] = tostring(inputs[i]) --apply tostring on every input param in preparation for table.concat
end
--Concatenate all inputs (4-space-separated)
local printOutput = table.concat(inputs, ' ', 1, inputs.n)
printOutput = printOutput:find("(\r?\n)") and IngameConsole.spreadColorCodes(printOutput) or printOutput
local substrStart, substrEnd = 1, 1
local numLinebreaks, completePrint = 0, true
repeat
substrEnd = (printOutput:find("(\r?\n)", substrStart) or 0) - 1
numLinebreaks, completePrint = self:lineOut(colorTheme, numIndentations, hideTimestamp, numLinebreaks, printOutput:sub(substrStart, substrEnd))
hideTimestamp = true
substrStart = substrEnd + 2
until substrEnd == -1 or numLinebreaks > self.maxLinebreaks
if substrEnd ~= -1 or not completePrint then
self:lineOut('info', 0, false, 0, "Previous value not entirely printed after exceeding maximum number of linebreaks. Consider adjusting 'IngameConsole.maxLinebreaks'.")
end
self:updateMultiboard()
end
---Prints the given string to the console with the specified colorTheme and the specified number of indentations.
---Only supports one-liners (no \n) due to how multiboards work. Will add linebreaks though, if the one-liner doesn't fit into the given multiboard space.
---@param colorTheme? '"timestamp"'| '"singleLineInput"' | '"multiLineInput"' | '"result"' | '"keywordInput"' | '"info"' | '"error"' | '"returnValue"' Decides about the color to be applied. Currently accepted: 'timestamp', 'singleLineInput', 'multiLineInput', 'result', nil. (nil equals no colorTheme, i.e. white color)
---@param numIndentations integer Number of greater '>' chars that shall preceed the output
---@param hideTimestamp boolean Set to false to hide the timestamp column and instead show a "->" symbol.
---@param numLinebreaks integer
---@param printOutput string the line to be printed in the console.
---@return integer numLinebreaks, boolean hasPrintedEverything returns true, if everything could be printed. Returns false otherwise (can happen for very long strings).
function IngameConsole:lineOut(colorTheme, numIndentations, hideTimestamp, numLinebreaks, printOutput)
--add preceeding greater chars
printOutput = ('>'):rep(numIndentations) .. printOutput
--Print a space instead of the empty string. This allows the console to identify, if the string has already been fully printed (see while-loop below).
if printOutput == '' then
printOutput = ' '
end
--Compute Linebreaks.
local linebreakWidth = ((self.autosize and self.mainColMaxWidth) or self.currentWidth )
local partialOutput = nil
local maxPrintableCharPosition
local printWidth
while string.len(printOutput) > 0 and numLinebreaks <= self.maxLinebreaks do --break, if the input string has reached length 0 OR when the maximum number of linebreaks would be surpassed.
--compute max printable substring (in one multiboard line)
maxPrintableCharPosition, printWidth = IngameConsole.getLinebreakData(printOutput, linebreakWidth - self.linebreakBuffer, self.textLanguage)
--adds timestamp to the first line of any output
if numLinebreaks == 0 then
partialOutput = printOutput:sub(1, numIndentations) .. ((IngameConsole.colors[colorTheme] and "|cff" .. IngameConsole.colors[colorTheme] .. printOutput:sub(numIndentations + 1, maxPrintableCharPosition) .. "|r") or printOutput:sub(numIndentations + 1, maxPrintableCharPosition)) --Colorize the output string, if a color theme was specified. IngameConsole.colors[colorTheme] can be nil.
table.insert(self.outputTimestamps, "|cff" .. IngameConsole.colors['timestamp'] .. ((hideTimestamp and ' ->') or IngameConsole.formatTimerElapsed(TimerGetElapsed(self.timer))) .. "|r")
else
partialOutput = (IngameConsole.colors[colorTheme] and "|cff" .. IngameConsole.colors[colorTheme] .. printOutput:sub(1, maxPrintableCharPosition) .. "|r") or printOutput:sub(1, maxPrintableCharPosition) --Colorize the output string, if a color theme was specified. IngameConsole.colors[colorTheme] can be nil.
table.insert(self.outputTimestamps, ' ..') --need a dummy entry in the timestamp list to make it line-progress with the normal output.
end
numLinebreaks = numLinebreaks + 1
--writes output string and width to the console tables.
table.insert(self.output, partialOutput)
table.insert(self.outputWidths, printWidth + self.linebreakBuffer) --remember the Width of this printed string to adjust the multiboard size in case. 0.5 percent is added to avoid the case, where the multiboard width is too small by a tiny bit, thus not showing some string without spaces.
--compute remaining string to print
printOutput = string.sub(printOutput, maxPrintableCharPosition + 1, -1) --remaining string until the end. Returns empty string, if there is nothing left
end
self.currentLine = #self.output
return numLinebreaks, string.len(printOutput) == 0 --printOutput is the empty string, if and only if everything has been printed
end
---Lets the multiboard show the recently printed lines.
function IngameConsole:updateMultiboard()
local startIndex = math.max(self.currentLine - self.numRows, 0) --to be added to loop counter to get to the index of output table to print
local outputIndex = 0
local maxWidth = 0.
local mbitem
for i = 1, self.numRows do --doesn't include title row (index 0)
outputIndex = i + startIndex
mbitem = MultiboardGetItem(self.multiboard, i, 0)
MultiboardSetItemValue(mbitem, self.outputTimestamps[outputIndex] or '')
MultiboardReleaseItem(mbitem)
mbitem = MultiboardGetItem(self.multiboard, i, 1)
MultiboardSetItemValue(mbitem, self.output[outputIndex] or '')
MultiboardReleaseItem(mbitem)
maxWidth = math.max(maxWidth, self.outputWidths[outputIndex] or 0.) --looping through non-defined widths, so need to coalesce with 0
end
--Adjust Multiboard Width, if necessary.
maxWidth = math.min(math.max(maxWidth, self.mainColMinWidth), self.mainColMaxWidth)
if self.autosize and self.currentWidth ~= maxWidth then
self.currentWidth = maxWidth
for i = 1, self.numRows +1 do
mbitem = MultiboardGetItem(self.multiboard, i-1, 1)
MultiboardSetItemWidth(mbitem, maxWidth)
MultiboardReleaseItem(mbitem)
end
self:showToOwners() --reshow multiboard to update item widths on the frontend
end
end
---Shows the multiboard to all owners (one or all players)
function IngameConsole:showToOwners()
if self.sharedConsole or GetLocalPlayer() == self.player then
MultiboardDisplay(self.multiboard, true)
MultiboardMinimize(self.multiboard, false)
end
end
---Formats the elapsed time as "mm: ss. hh" (h being a hundreds of a sec)
function IngameConsole.formatTimerElapsed(elapsedInSeconds)
return string.format("\x2502d: \x2502.f. \x2502.f", elapsedInSeconds // 60, math.fmod(elapsedInSeconds, 60.) // 1, math.fmod(elapsedInSeconds, 1) * 100)
end
---Computes the max printable substring for a given string and a given linebreakWidth (regarding a single line of console).
---Returns both the substrings last char position and its total width in the multiboard.
---@param stringToPrint string the string supposed to be printed in the multiboard console.
---@param linebreakWidth number the maximum allowed width in one line of the console, before a string must linebreak
---@param textLanguage string 'ger' or 'eng'
---@return integer maxPrintableCharPosition, number printWidth
function IngameConsole.getLinebreakData(stringToPrint, linebreakWidth, textLanguage)
local loopWidth = 0.
local bytecodes = table.pack(string.byte(stringToPrint, 1, -1))
for i = 1, bytecodes.n do
loopWidth = loopWidth + string.charMultiboardWidth(bytecodes[i], textLanguage)
if loopWidth > linebreakWidth then
return i-1, loopWidth - string.charMultiboardWidth(bytecodes[i], textLanguage)
end
end
return bytecodes.n, loopWidth
end
-------------------------
--| Reserved Keywords |--
-------------------------
---Exits the Console
---@param self IngameConsole
function IngameConsole.keywords.exit(self)
DestroyMultiboard(self.multiboard)
DestroyTrigger(self.trigger)
DestroyTimer(self.timer)
IngameConsole.playerConsoles[self.player] = nil
if next(IngameConsole.playerConsoles) == nil then --set print function back to original, when no one has an active console left.
print = IngameConsole.originalPrint
end
end
---Lets the console print to chat
---@param self IngameConsole
function IngameConsole.keywords.printtochat(self)
self.printToConsole = false
self:out('info', 0, false, "The print function will print to the normal chat.")
end
---Lets the console print to itself (default)
---@param self IngameConsole
function IngameConsole.keywords.printtoconsole(self)
self.printToConsole = true
self:out('info', 0, false, "The print function will print to the console.")
end
---Shows the console in case it was hidden by another multiboard before
---@param self IngameConsole
function IngameConsole.keywords.show(self)
self:showToOwners() --might be necessary to do, if another multiboard has shown up and thereby hidden the console.
self:out('info', 0, false, "Console is showing.")
end
---Prints all available reserved keywords plus explanations.
---@param self IngameConsole
function IngameConsole.keywords.help(self)
self:out('info', 0, false, "The Console currently reserves the following keywords:")
self:out('info', 0, false, "'help' shows the text you are currently reading.")
self:out('info', 0, false, "'exit' closes the console.")
self:out('info', 0, false, "'lasttrace' shows the stack trace of the latest error that occured within IngameConsole.")
self:out('info', 0, false, "'share' allows other players to read and write into your console, but also force-closes their own consoles.")
self:out('info', 0, false, "'clear' clears all text from the console.")
self:out('info', 0, false, "'show' shows the console. Sensible to use, when displaced by another multiboard.")
self:out('info', 0, false, "'printtochat' lets Wc3 print text to normal chat again.")
self:out('info', 0, false, "'printtoconsole' lets Wc3 print text to the console (default).")
self:out('info', 0, false, "'autosize on' enables automatic console resize depending on the longest line in the display.")
self:out('info', 0, false, "'autosize off' retains the current console size.")
self:out('info', 0, false, "'textlang eng' will use english text installation font size to compute linebreaks (default).")
self:out('info', 0, false, "'textlang ger' will use german text installation font size to compute linebreaks.")
self:out('info', 0, false, "Preceeding a line with '>' prevents immediate execution, until a line not starting with '>' has been entered.")
end
---Clears the display of the console.
---@param self IngameConsole
function IngameConsole.keywords.clear(self)
self.output = {}
self.outputTimestamps = {}
self.outputWidths = {}
self.currentLine = 0
self:out('keywordInput', 1, false, 'clear') --we print 'clear' again. The keyword was already printed by self:processInput, but cleared immediately after.
end
---Shares the console with other players in the same game.
---@param self IngameConsole
function IngameConsole.keywords.share(self)
for _, console in pairs(IngameConsole.playerConsoles) do
if console ~= self then
IngameConsole.keywords['exit'](console) --share was triggered during console runtime, so there potentially are active consoles of others players that need to exit.
end
end
self:makeShared()
self:showToOwners() --showing it to the other players.
self:out('info', 0,false, "The console of player " .. GetConvertedPlayerId(self.player) .. " is now shared with all players.")
end
---Enables auto-sizing of console (will grow and shrink together with text size)
---@param self IngameConsole
IngameConsole.keywords["autosize on"] = function(self)
self.autosize = true
self:out('info', 0,false, "The console will now change size depending on its content.")
end
---Disables auto-sizing of console
---@param self IngameConsole
IngameConsole.keywords["autosize off"] = function(self)
self.autosize = false
self:out('info', 0,false, "The console will retain the width that it currently has.")
end
---Lets linebreaks be computed by german font size
---@param self IngameConsole
IngameConsole.keywords["textlang ger"] = function(self)
self.textLanguage = 'ger'
self:out('info', 0,false, "Linebreaks will now compute with respect to german text installation font size.")
end
---Lets linebreaks be computed by english font size
---@param self IngameConsole
IngameConsole.keywords["textlang eng"] = function(self)
self.textLanguage = 'eng'
self:out('info', 0,false, "Linebreaks will now compute with respect to english text installation font size.")
end
---Prints the stack trace of the latest error that occured within IngameConsole.
---@param self IngameConsole
IngameConsole.keywords["lasttrace"] = function(self)
self:out('error', 0,false, self.lastTrace)
end
--------------------
--| Main Trigger |--
--------------------
do
--Actions to be executed upon typing -exec
local function execCommand_Actions()
local input = string.sub(GetEventPlayerChatString(),7,-1)
print("Executing input: |cffffff44" .. input .. "|r")
--try preceeding the input by a return statement (preparation for printing below)
local loadedFunc, errorMsg = load("return ".. input)
if not loadedFunc then --if that doesn't produce valid code, try without return statement
loadedFunc, errorMsg = load(input)
end
--execute loaded function in case the string defined a valid function. Otherwise print error.
if errorMsg then
print("|cffff5555Invalid Lua-statement: " .. Debug.getLocalErrorMsg(errorMsg) .. "|r")
else
---@diagnostic disable-next-line: param-type-mismatch
local results = table.pack(Debug.try(loadedFunc))
if results[1] ~= nil or results.n > 1 then
for i = 1, results.n do
results[i] = tostring(results[i])
end
--concatenate all function return values to one colorized string
print("|cff00ffff" .. table.concat(results, ' ', 1, results.n) .. "|r")
end
end
end
local function execCommand_Condition()
return string.sub(GetEventPlayerChatString(), 1, 6) == "-exec "
end
local function startIngameConsole()
--if the triggering player already has a console, show that console and stop executing further actions
if IngameConsole.playerConsoles[GetTriggerPlayer()] then
IngameConsole.playerConsoles[GetTriggerPlayer()]:showToOwners()
return
end
--create Ingame Console object
IngameConsole.playerConsoles[GetTriggerPlayer()] = IngameConsole.create(GetTriggerPlayer())
--overwrite print function
print = function(...)
IngameConsole.originalPrint(...) --the new print function will also print "normally", but clear the text immediately after. This is to add the message to the F12-log.
if IngameConsole.playerConsoles[GetLocalPlayer()] and IngameConsole.playerConsoles[GetLocalPlayer()].printToConsole then
ClearTextMessages() --clear text messages for all players having an active console
end
for player, console in pairs(IngameConsole.playerConsoles) do
if console.printToConsole and (player == console.player) then --player == console.player ensures that the console only prints once, even if the console was shared among all players
console:out(nil, 0, false, ...)
end
end
end
end
---Creates the triggers listening to "-console" and "-exec" chat input.
---Being executed within DebugUtils (MarkGameStart overwrite).
function IngameConsole.createTriggers()
--Exec
local execTrigger = CreateTrigger()
TriggerAddCondition(execTrigger, Condition(execCommand_Condition))
TriggerAddAction(execTrigger, execCommand_Actions)
--Real Console
local consoleTrigger = CreateTrigger()
TriggerAddAction(consoleTrigger, startIngameConsole)
--Events
for i = 0, GetBJMaxPlayers() -1 do
TriggerRegisterPlayerChatEvent(execTrigger, Player(i), "-exec ", false)
TriggerRegisterPlayerChatEvent(consoleTrigger, Player(i), "-console", true)
end
end
end
Debug.endFile()
if Debug then Debug.beginFile "Hook" end
--ββββββββββββββββββββββββββββββββββββββ
-- Hook version 7.1.0.1
-- Created by: Bribe
-- Contributors: Eikonium, Jampion, MyPad, Wrda
--βββββββββββββββββββββββββββββββββββββββββββββ
---@class Hook.property
---@field next function|Hook.property --Call the next/native function. Also works with any given name (old/native/original/etc.). The args and return values align with the original function.
---@field remove fun(all?: boolean) --Remove the hook. Pass the boolean "true" to remove all hooks.
---@field package tree HookTree --Reference to the tree storing each hook on that particular key in that particular host.
---@field package priority number
---@field package index integer
---@field package hookAsBasicFn? function
----@field package debugId? string
----@field package debugNext? string
---@class Hook: {[integer]: Hook.property, [string]: function}
Hook = {}
do
local looseValuesMT = { __mode = "v" }
local hostKeyTreeMatrix = ---@type table<table, table<any, HookTree>>
setmetatable({
--Already add a hook matrix for _G right away.
[_G] = setmetatable({}, looseValuesMT)
}, looseValuesMT)
---@class HookTree: { [number]: Hook.property }
---@field host table
---@field key unknown --What the function was indexed to (_G items are typically indexed via strings)
---@field hasHookAsBasicFn boolean
---Reindexes a HookTree, inserting or removing a hook and updating the properties of each hook.
---@param tree HookTree
---@param index integer
---@param newHook? table
local function reindexTree(tree, index, newHook)
if newHook then
table.insert(tree, index, newHook)
else
table.remove(tree, index)
end
local top = #tree
local prevHook = tree[index - 1]
-- `table.insert` and `table.remove` shift the elements upwards or downwards,
-- so this loop manually aligns the tree elements with this shift.
for i = index, top do
local currentHook = tree[i]
currentHook.index = i
currentHook.next = (i > 1) and
rawget(prevHook, 'hookAsBasicFn') or
prevHook
--currentHook.debugNext = tostring(currentHook.next)
prevHook = currentHook
end
local topHookBasicFn = rawget(tree[top], 'hookAsBasicFn')
if topHookBasicFn then
if not tree.hasHookAsBasicFn or rawget(tree.host, tree.key) ~= topHookBasicFn then
tree.hasHookAsBasicFn = true
--a different basic function should be called for this hook
--instead of the one that was previously there.
tree.host[tree.key] = topHookBasicFn
end
else
--The below comparison rules out 'nil' and 'true'.
--Q: Why rule out nil?
--A: There is no need to reassign a host hook handler if there is already one in place.
if tree.hasHookAsBasicFn ~= false then
tree.host[tree.key] = function(...)
return tree[#tree](...)
end
end
tree.hasHookAsBasicFn = false
end
end
---@param hookProperty Hook.property
---@param deleteAllHooks? boolean
function Hook.delete(hookProperty, deleteAllHooks)
local tree = hookProperty.tree
hookProperty.tree = nil
if deleteAllHooks or #tree == 1 then
--Reset the host table's native behavior for the hooked key.
tree.host[tree.key] =
(tree[0] ~= DoNothing) and
tree[0] or
nil
hostKeyTreeMatrix[tree.host][tree.key] = nil
else
reindexTree(tree, hookProperty.index)
end
end
---@param hostTableToHook? table
---@param defaultNativeBehavior? function
---@param hookedTableIsMetaTable? boolean
local function setupHostTable(hostTableToHook, defaultNativeBehavior, hookedTableIsMetaTable)
hostTableToHook = hostTableToHook or _G
if hookedTableIsMetaTable or
(defaultNativeBehavior and hookedTableIsMetaTable == nil)
then
hostTableToHook = getmetatable(hostTableToHook) or
getmetatable(setmetatable(hostTableToHook, {}))
end
return hostTableToHook
end
---@param tree HookTree
---@param priority number
local function huntThroughPriorityList(tree, priority)
local index = 1
local topIndex = #tree
repeat
if priority <= tree[index].priority then
break
end
index = index + 1
until index > topIndex
return index
end
---@param hostTableToHook table
---@param key unknown
---@param defaultNativeBehavior? function
---@return HookTree | nil
local function createHookTree(hostTableToHook, key, defaultNativeBehavior)
local nativeFn = rawget(hostTableToHook, key) or
defaultNativeBehavior or
((hostTableToHook ~= _G or type(key) ~= "string") and
DoNothing)
if not nativeFn then
--Logging is used here instead of directly throwing an error, because
--no one can be sure that we're running within a debug-friendly thread.
(Debug and Debug.throwError or print)("Hook Error: No value found for key: " .. tostring(key))
return
end
---@class HookTree
local tree = {
host = hostTableToHook,
key = key,
[0] = nativeFn,
--debugNativeId = tostring(nativeFn)
}
hostKeyTreeMatrix[hostTableToHook][key] = tree
return tree
end
---@param self Hook.property
local function __index(self)
return self.next
end
---@param key unknown Usually `string` (the name of the native you wish to hook)
---@param callbackFn fun(Hook, ...):any The function you want to run when the native is called. The first parameter is type "Hook", and the remaining parameters (and return value(s)) align with the original function.
---@param priority? number Defaults to 0. Hooks are called in order of highest priority down to lowest priority. The native itself has the lowest priority.
---@param hostTableToHook? table Defaults to _G (the table that stores all global variables).
---@param defaultNativeBehavior? function If the native does not exist in the host table, use this default instead.
---@param hookedTableIsMetaTable? boolean Whether to store into the host's metatable instead. Defaults to true if the "default" parameter is given.
---@param hookAsBasicFn? boolean When adding a hook instance, the default behavior is to use the __call metamethod in metatables to govern callbacks. If this is `true`, it will instead use normal function callbacks.
---@return Hook.property
function Hook.add(
key,
callbackFn,
priority,
hostTableToHook,
defaultNativeBehavior,
hookedTableIsMetaTable,
hookAsBasicFn
)
priority = priority or 0
hostTableToHook = setupHostTable(hostTableToHook, defaultNativeBehavior, hookedTableIsMetaTable)
hostKeyTreeMatrix[hostTableToHook] =
hostKeyTreeMatrix[hostTableToHook] or
setmetatable({}, looseValuesMT)
local index = 1
local tree = hostKeyTreeMatrix[hostTableToHook][key]
if tree then
index = huntThroughPriorityList(tree, priority)
else
---@diagnostic disable-next-line: cast-local-type
tree = createHookTree(hostTableToHook, key, defaultNativeBehavior)
if not tree then
return ---@diagnostic disable-line: missing-return-value
end
end
local new = {
priority = priority,
tree = tree
}
function new.remove(deleteAllHooks)
Hook.delete(new, deleteAllHooks)
end
--new.debugId = tostring(callbackFn) .. ' and ' .. tostring(new)
if hookAsBasicFn then
new.hookAsBasicFn = callbackFn
else
setmetatable(new, {
__call = callbackFn,
__index = __index
})
end
reindexTree(tree, index, new)
return new
end
end
---Hook.basic avoids creating a metatable for the hook.
---This is necessary for adding hooks to metatable methods such as __index.
---The main difference versus Hook.add is in the parameters passed to callbackFn;
---Hook.add has a 'self' argument which points to the hook, whereas Hook.basic does not.
---@param key unknown
---@param callbackFn fun(Hook, ...):any
---@param priority? number
---@param hostTableToHook? table
---@param defaultNativeBehavior? function
---@param hookedTableIsMetaTable? boolean
function Hook.basic(key, callbackFn, priority, hostTableToHook, defaultNativeBehavior, hookedTableIsMetaTable)
return Hook.add(key, callbackFn, priority, hostTableToHook, defaultNativeBehavior, hookedTableIsMetaTable, true)
end
---@deprecated
---@see Hook.add for args
function AddHook(...)
local new = Hook.basic(...)
return function(...)
return new.next(...)
end, new.remove
end
setmetatable(Hook, {
__newindex = function(_, key, callback)
Hook.add(key, callback)
end
})
if Debug then Debug.endFile() end
--[[
=============================================================================================================================================================
Antares' Limitless Interaction Caller Engine
A Lua system to easily create highly performant checks and interactions, between any type of objects.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
=============================================================================================================================================================
Overview
=============================================================================================================================================================
To install this library, copy it into an empty script file in your map.
To enable debug mode, import "CustomTooltip.toc" and "CustomTooltip.fdf".
There are only few values to be set in the config. First, change the MAP_CREATORS field to your name.
The main work is creating actors and their interaction functions. Let's say we want to create a new spell. It should create multiple orbs at different locations
that each have an aura around them. In normal GUI/JASS/Lua, we would need a periodic timer, loop over our orbs, GroupEnumUnitsInRange to find units affected,
filter out the units that aren't eligible, and then run our code. ALICE takes care of the entire control structure of our code with a network of its main
internal object, the actor. The task of writing the correct control structure then transforms into assigning the actors the correct properties on creation.
=============================================================================================================================================================
What is an actor?
=============================================================================================================================================================
An actor is a class that is attached to any type of object and interacts with other actors that were added to the system. Two actors form a pair. Actors carry
identifiers and function interfaces determining their interactions and with which other actors they form a pair.
When two actors in a pair interact, an interaction function that you can specify will be called. After the pair's interaction is calculated, the next
interaction is placed in the queue. It is up to you to set the time interval between the two interactions. This is done via the return value of the
interactionFunc. The interactionFunc uses two input arguments which specify the "hosts" of the two actors; the objects the actors are attached to. Hosts can
be any type of object - a unit, an item, a class, a player - whatever thing you want the actor to represent. A host can also be a string, an integer, or nil,
which could represent some kind of global effect.
Actors can both receive and initiate pairs. When a new actor is created, it checks if it should initiate a pair with each already existing actor and all
existing actors will check if they should initiate a pair themselves. Two-way pairs are not possible.
ALICE will automatically retrieve the position of an actor, if it's applicable. If it can't, it will create it as a global actor.
=============================================================================================================================================================
Schematic
=============================================================================================================================================================
PairingCheck β Identifier
Identifier β PairingCheck
β β β
Object A β Actor A Pair Actor B β Object B
β
*InteractionFunc β β
β β β
Object A β Object B β
β β
Time until next call β
*inherited from the actor initiating the pair.
=============================================================================================================================================================
How to create an actor
=============================================================================================================================================================
To create an actor, do ALICE_Create(host, identifier, interactionFunc). There are additional values you can set, but they're not important for getting started.
-----host-----
Any type of object which the actor is supposed to represent. You can create multiple actors for one host.
-----identifier-----
A string or string sequence that can be used in a filter to identify different types of actors. Examples: "hero", "missile", or {"unit", "hero", "human", "Hpal"}.
-----interactionFunc-----
A function or table that specifies the function that is called when this object interacts with another object. If a function is passed, the actor will pair with
everything (not recommended!). With a table, you can specify different interaction functions for different types of objects. For example: {milk = Drink, apple = Eat},
will use the Drink function for all actors with the "milk" identifier and the Eat function for all actors with the "apple" identifier.
Actors will only pair with other actors for which an interactionFunc exists, but you can use the "other" keyword to declare an interactionFunc that is used for
all actors not included in your list.
-----flags-----
Flags are an optional fourth input argument. They are discussed in the advanced tutorial.
-----ALICE_CreateFromClass-----
ALICE_CreateFromClass(class) creates an actor for a class and retrieves all input arguments directly from that class.
=============================================================================================================================================================
How to create an interaction function
=============================================================================================================================================================
An interactionFunc must have two input arguments of any type, specifying the objects (not the actors), and one return value of type number, specifying the time
until the next interaction (in seconds). The object that is the source of the interaction func will always be passed as the first argument.
Within the interaction func, you have access to the Pair API.
Example:
function Explode(whichMine, whichUnit)
local dist = ALICE_PairGetDistance()
if dist < 100 then
whichMine:destroy()
KillUnit(whichUnit)
end
return (dist - 100)/300
end
]]
--[[
=============================================================================================================================================================
Self-Interaction Functions
=============================================================================================================================================================
Self-interaction is a convenient way to execute code that affects only one actor. By default, actors will never pair with themselves or another actor with the
same host, but you can use the "self" keyword in an interactionFunc table to declare a self-interaction function. In the self-interaction function, the actor's
host is passed as both arguments.
Example:
interactionFunc = {missile = DestroyMissile, self = Move}
function Move(blast, __)
blast.x = blast.x + blast.vx
blast.y = blast.y + blast.vy
BlzSetSpecialEffectPosition(blast.specialEffect, blast.x, blast.y, 0)
end
This creates a projectile that moves itself every step and presumably destroys missiles on contact.
You can pass a table to define multiple self-interaction functions. Example:
interactionFunc = {missile = DestroyMissile, self = {Move, Accelerate}}
=============================================================================================================================================================
EveryStep Functions
=============================================================================================================================================================
You can define an interactionFunc as an everyStep function. If you do, the interactions evaluated by that function will be executed every step instead of at a
variable interval. This reduces the overhead required and improves performance. The interactionFunc no longer requires a return value. EveryStep functions are
recommended for moving/accelerating objects.
To declare a function as an everyStep function, do ALICE_SetEveryStep(myFunction).
=============================================================================================================================================================
Flags
=============================================================================================================================================================
Flags are a table that contains additional parameters that allow you to control the behavior of actors much more than what is possible with just the standard
input arguments.
The possible flags are (ordered by increasing niche-ness):
radius
pairsWith
destroyOnDeath
isStationary
bindToBuff
bindToOrder
onActorDestroy
cellCheckInterval
priority
anchor
randomDelay
isIndestructible
Example: {isStationary = true, radius = 200}
-----radius-----
Overwrite the default object radius. The radius determines which cells the object is in. Objects can only interact with other objects with which they share
at least one cell, so the radius should be at least the object's interaction range. Some additional leeway is recommended, since cells are not updated on
every iteration.
-----pairsWith-----
A string, string sequence, or function that specifies which other actors the newly created actor has interactions with. For example: "unit" will pair with all
actors that have the "unit" identifier. By default, an actor will pair with all other actors for which an interaction function exists, but the pairsWith flag
adds another restriction. Using tables for interactionFuncs or using the pairsWith flag can achieve similar results, but the level of control with pairsWith
is much higher. Example:
ALICE_Create(host, "killer", {unit = KillUnit})
ALICE_Create(host, "killer", KillUnit, {pairsWith = "unit"})
are identical.
How to create a pairsWith flag is explained under actor filters.
-----destroyOnDeath-----
Destroy the actor automatically when its host is destroyed. Works only for widgets.
-----isStationary-----
Disables cell checks for this object if it is stationary and cannot move to improve performance. Automatically enabled for destructables.
-----bindToBuff / bindToOrder-----
Automatically destroy the actor when the host unit no longer has the buff with the bindToBuff string or when its current order is no longer the string bindToOrder.
-----onActorDestroy------
A function that is executed when the actor is destroyed. Passes the host as the argument.
-----cellCheckInterval-----
Overwrite the default cell check interval and set how often it should be checked if the object has left a cell it was previously in. A fast-moving object
should be checked more often than a slow-moving object.
-----priority-----
Determines which actor takes priority over the other when deciding which interactionFunc is called in a case where it would be ambiguous otherwise. If both
actors pair with the other, the interactionFunc of the one with the higher priority is called. The default priority is 0.
You can shroud an actor from other actors initiating pairs with it and only pair using its own pairing behavior by setting its priority to NO_INCOMING_PAIRS.
-----anchor-----
Overwrites the host as the source of the actor coordinates with the object provided in anchor. Also reroutes the destroyOnDeath trigger to the anchor and
prevents actors anchored to the same object from paring. Useful if you want to pass as the host a class attached to a unit. Then you can anchor the actor to
the unit directly.
-----randomDelay-----
If this flag is set, the first interaction will be delayed by a random amount between 0 and the specified number.
-----isIndestructible-----
If set to true, attempts to destroy this actor will throw an error. In addition, ALICE will never isolate this actor if it is causing crashes (it will still
isolate the other actor in the pair).
=============================================================================================================================================================
How to create Actor Filters
=============================================================================================================================================================
Actor filters are used in enum functions, in ALICE_HasIdentifier and in the pairsWith flag. Actor filters can be strings, tables, or functions.
A string will filter all actors that possess the identifier.
In a table, every entry has to be a string except for the optional last entry, which is a parameter to specifiy how the list should be interpreted.
{"A", "B", ..., MATCHING_TYPE_ANY} Filter all actors that have at least one of the listed identifiers. Default if not specified.
{"A", "B", ..., MATCHING_TYPE_ALL} Filter all actors that have all the listed identifiers.
{"A", "B", ..., MATCHING_TYPE_EXACT} Filter all actors that have exactly the listed identifiers.
{"A", "B", ..., MATCHING_TYPE_EXCLUDE} Filter all actors that have none of the listed identifiers.
A function must have one input argument that references the filtered actor's host and a boolean return value. Example: A newly created actor should only
pair with nonhero, undead units. The filter function could be:
function FilterNonheroUndead(filterHost)
--Prevent calling natives on a non-unit host.
if not ALICE_HasIdentifier(filterHost, "unit") then
return false
end
if IsUnitType(filterHost, UNIT_TYPE_HERO) then
return false
end
return IsUnitType(filterHost, UNIT_TYPE_UNDEAD)
end
This could of course also be achieved by setting all the necessary flags for each actor and using the table {"unit", "nonhero", "undead", MATCHING_TYPE_ALL}.
-----Owner filter-----
An actor created for a host that has an owner (a unit-type host or a class-type host with a CLASS_FIELD_OWNER field) can be filtered by table-type filters
based on its owner. This is done by inserting an additional value at the end of the table. Valid arguments are:
PLAYER_FILTER_TYPE_ALLY Pairs with all objects owned by an ally of the object's owner.
PLAYER_FILTER_TYPE_ENEMY Pairs with all objects owned by an enemy of the object's owner.
PLAYER_FILTER_TYPE_OWNER Pairs with all objects owned by the object's owner.
PLAYER_FILTER_TYPE_NOT_OWNER Pairs with all objects not owned by the object's owner.
Player Pairs with all objects owned by the specified player.
Example: {"unit", "ground", MATCHING_TYPE_ALL, PLAYER_FILTER_TYPE_ENEMY}
will pair with all ground units that are owned by an enemy of the new object's owner.
Note that the owner does not get updated automatically when a unit switches sides, but you can do it manually with ALICE_UpdateOwner(). However, in those
situations, it might be better to pair with all units regardless of their owner and simply put the owner check inside the interaction function.
=============================================================================================================================================================
]]
--[[
=============================================================================================================================================================
A P I
=============================================================================================================================================================
All object functions work with either a host or an actor as the input argument. Keyword
parameter is optional and only needed if you create multiple actors for one host. It
searches for the actor that has that keyword in its identifier.
-----Main API------
ALICE_Create(host, identifier, interactionFunc, flags) Create an actor for the object host and add it to the cycle.
ALICE_CreateFromClass(whichClass) Create an actor for a table host and retrieve all input arguments from that table.
ALICE_Destroy(whichObject) Destroy the actor of the object and remove it from the cycle.
-----Pair API-----
ALICE_PairSetInteractionFunc(whichFunc) Changes the interactionFunc of the pair currently being evaluated.
ALICE_PairDisable() Disables interactions between the actors of the current pair after this one. Changing
the properties of one of the actors will reset.
ALICE_PairLoadData() Returns a table unique to the pair currently being evaluated, which can be used to
read and write data. Optimal argument to initialize values from the specified class.
ALICE_PairGetDistance() Returns the distance between the objects of the pair currently being evaluated in two
dimensions.
ALICE_PairGetDistance3D() The same, but takes z into account.
ALICE_PairGetAngle() Returns the angle from object A to object B of the pair currently being evaluated.
ALICE_PairGetAngle3D() Returns the horizontal and vertical angles from object A to object B.
ALICE_PairOnDestroy(callback) Executes the function callback(objectA, objectB, pairData) when either of the actors in
the current pair are destroyed. Note: Only one callback. Pair API is not accessible
within callback function. Avoid inlining callback function to avoid garbage build-up.
ALICE_PairIsFirstContact() Returns true if this is the first time this function was invoked for the current pair,
otherwise false.
ALICE_PairIsUnoccupied() Returns false if this function was invoked for another pair that has the same
interactionFunc and the same receiving actor. Otherwise, returns true. In other words,
only one pair can execute the code within an ALICE_PairIsUnoccupied() block. Useful for
creating non-stacking effects.
ALICE_PairPersist() Changes the behavior of the current pair so that the interactions don't break when the
two objects leave their interaction range.
ALICE_PairForget() Purge pair data, call onDestroy method and reset ALICE_PairIsFirstContact,
ALICE_PairPersist and ALICE_IsUnoccupied functions.
Enum functions return a table with all objects that are in included in filter. If the filter
specifies a player filter, you need to specify the whoFilters player. Example:
ALICE_EnumObjects({"unit", PLAYER_FILTER_TYPE_ALLY}, Player(0)) will return all units that are
owned by an ally of red.
-----Enum API-----
ALICE_EnumObjects(filter, whoFilters)
ALICE_EnumObjectsInRange(x, y, range, filter, whoFilters)
ALICE_EnumObjectsInRect(minx, miny, maxx, maxy, filter, whoFilters)
ALICE_ForAllObjectsDo(filter, whoFilters, action)
ALICE_ForAllObjectsInRangeDo(x, y, range, filter, whoFilters, action)
ALICE_ForAllObjectsInRectDo(minx, miny, maxx, maxy, filter, whoFilters, action)
-----Object API------
ALICE_HasActor(whichObject) Checks if an actor already exists with the object as its host.
ALICE_GetActor(whichObject) Returns the actor stored to a host.
ALICE_UpdateOwner(whichObject) Update owner of object if it has changed and reevaluate all pairings.
ALICE_SetInteractionFunc(whichObject, identifier, func) Sets the interactionFunc of the object towards actors with the specified identifier.
ALICE_Kill(whichObject) Calls the appropriate function to destroy the object. If the object is a table, the
whichObject:destroy() method will be called.
-----Identifier API------
ALICE_AddIdentifier(whichObject, whichIdentifier) Add identifier(s) to an object and pair it with all other objects it is now eligible
to be paired with. Slow function!
ALICE_RemoveIdentifier(whichObject, whichIdentifier) Remove identifier(s) from an object and remove all pairings with objects it is no
longer eligible to be paired with. Slow function!
ALICE_SetIdentifier(whichObject, newIdentifier) Sets the object's identifier to a string or string sequence. Slow function!
ALICE_HasIdentifier(whichObject, identifier) Checks if the object toCheck contains the identifier toMatch. ToMatch can be a string
or a string sequence with optional matching type entry (see under Pairing Logic).
ALICE_PairsWith(objectA, objectB) Checks if the objectA would pair with the objectB.
ALICE_GetIdentifier(whichObject) Compiles the identifiers of an object into a table.
-----Misc API------
ALICE_MIN_INTERVAL
ALICE_MAX_INTERVAL
Type "downtherabbithole" in-game to enable debug mode. In debug mode, you can click near an
object to visualize its actor, its interactions, and see all attributes of that actor.
-----Debug API------
ALICE_ListGlobals() List all global actors.
ALICE_GetFromUnique(number) Returns the actor with the specified unique number.
ALICE_Select(whichActor) Select the specified actor. Pass integer to select by unique number. Requires debug
mode.
ALICE_PairVisualize(duration) Create a lightning effect between the objects of the current pair. Useful to check
if objects are interacting as intended. Optional lightning type argument.
ALICE_VisualizeCells(whichObject, enable) Enable/disable visualization of the cells the object is currently in.
ALICE_PrintIdentifier(whichObject) Prints out the identifiers of an object.
ALICE_Pause() Pause the entire cycle.
ALICE_SlowMotion(factor) Slow down the ALICE cycle by the specified factor. Use ALICE_TimeScale to refer to
the slow motion factor in external functions.
ALICE_Resume() Resume the entire cycle.
ALICE_Statistics() Prints out statistics showing which actors are occupying which percentage of the
calculations.
ALICE_PrintCounts() Continuously prints the number of actors, pair interactions and cell checks until
disabled.
ALICE_VisualizeAllCells() Create lightning effects around all cells.
ALICE_VisualizeAllActors() Creates arrows above all non-global actors.
-----Optimization API-----
ALICE_SetEveryStep(whichFunction) Defines an interactionFunc as an everyStep function, which requires no return value.
ALICE_SetMaxRange(whichFunction, maxRange) All pairs using this function will get automatically disabled if both objects are
stationary and their distance is greater than the max range.
ALICE_SetRadius(whichObject, newRadius) Changes the radius of the object.
ALICE_SetStationary(whichObject, enable) Sets an object to stationary/not stationary.
ALICE_SetCellCheckInterval(whichObject, newInterval) Changes how often ALICE checks if the object has entered a new cell.
=============================================================================================================================================================
]]
--[[
=============================================================================================================================================================
Troubleshooting
=============================================================================================================================================================
-----downtherabbithole-----
In-game, you can type "downtherabbithole" to enable debug mode. While in debug mode, you can left-click on objects to select their actor and receive information
about their attributes. In addition, their current cells and interactions will be visualized. You can combine debug mode with Eikonium's IngameConsole to execute
code directly on misbehaving actors. Requires "CustomTooltip.toc" and "CustomTooltip.fdf". Set your interactionFuncs to global so that their names can get
displayed.
ALICE_GetActor() without an input argument will return the currently selected actor. ALICE_GetFromUnique(number) will return an actor with the specified unique
number. The number is displayed in the tooltip. Example:
ALICE_PairsWith(ALICE_GetActor(), ALICE_GetFromUnique(562))
Global actors cannot be selected by clicking on them, but you can select them with ALICE_ListGlobals() and then ALICE_Select(number), where number is the unique
number listed for that actor.
-----Actors not interacting-----
This can be due to actors not having the intended pairing behavior, because of interaction misses, or because of the an actor's radius being too small.
To check if the pairing behavior is correct, check the actor tooltip in debug mode or do ALICE_PairsWith.
An interaction miss occurs when two objects get into proximity with each other and should interact, but do not because the interval calculated during their
last interaction was too long and they're still in the queue. To avoid interaction misses, set the interaction length sufficiently low, especially during
debugging, even to 0 (the interval will be ceiled to MIN_INTERVAL).
If you set the radius of an actor too low or forget to change it from its default value, the actors will interact, but only at short range. The radius should be
set to the maximum interaction distance plus some leeway. The leeway should be equal to the maximum distance the object can travel during two cell checks
(CELL_CHECK_INTERVAL). Select the actor in debug mode to see the cells the system thinks it's currently in.
You can add lightnings with ALICE_PairVisualize(duration) in the interaction func. This will create a lightning between the hosts of two interacting actors
whenever their interaction function is called. This does not work for global actors.
-----Actors interacting when they shouldn't-----
If you create a new actor, it will not only pair with other actors based on its own pairing logic, but other actors will also check if the new actor is included
in their logic. For example, you place a few units on the map, then create an effect that should affect those units. Because there are no other actors on the
map at that moment, you might not restrict how it pairs in any way. However, that actor will not only pair with those units but will continue to pair with every
new actor that gets created.
-----Attempting to do arithmetic on a nil value-----
This error must likely means that you forgot the interactionFunc's return value.
-----Thread crash-----
If your custom code crashes the thread, ALICE will remove the pair that caused the crash and prevent the two actors from pairing again, then on the second crash
caused by the same actor isolate that actor completely.
-----Never edit actor class fields-----
ALICE_GetActor gives you access to the interal actor class, but you should still only edit its class fields with the API functions. Editing class fields can lead
to all kinds of unforeseeable effects.
-----Forgetting to destroy an actor-----
Forgetting to destroy an actor when the associated host is destroyed will keep the pairs attached to that actor inside the cycle indefinitely. The pairs will
continue to be evaluated, clogging up the system. Because the reference to the host is lost, depending on the interactionFunc you wrote, it might crash the
function.
You can also put checks into your interaction functions and destroy actors if any of their hosts are removed from the game. Keep in mind that functions still
needs a return value, even if it's the last time they're executed.
=============================================================================================================================================================
]]
if Debug then Debug.beginFile "ALICE" end
do
--[[
=============================================================================================================================================================
Antares' Limitless Interaction Caller Engine
A Lua system to easily create highly performant checks and interactions, between any type of objects.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
local MAP_CREATORS = {"Antares", "WorldEdit"} ---@type string[]
--Print out warnings, errors, and enable the "downtherabbithole" cheat code for the players with these names. #XXXX not required.
--Class Interface (important if you want to use tables as hosts, tells ALICE which fields it should look out for to retrieve information from your classes).
local CLASS_FIELD_X = "x" ---@type string
local CLASS_FIELD_Y = "y" ---@type string
local CLASS_FIELD_Z = "z" ---@type string
--The label of the coordinates of class-type hosts. When an actor is created with a table as a host, ALICE searches for these fields to get the object's
--position. If the fields are not present, the actor is created as a global actor.
local CLASS_FIELD_OWNER = "owner" ---@type string
--(Niche) The label of the owner of class-type hosts. If the field is not present, the actor will have no owner.
--Debugging
local FREEZE_PROTECTION_LIMIT = 10000 ---@type integer
--If a number of pairs greater than this limit is evaluated each step for a longer period of time, something clearly went wrong and the cycle will terminate,
--preventing the game from freezing. You can then enable debug mode and better gather information about what caused the crash.
--Optimization
ALICE_MIN_INTERVAL = 0.02 ---@type number
--Minimum interval between interactions in seconds. Sets the time step of the timer. All interaction intervals are an integer multiple of this value.
ALICE_MAX_INTERVAL = 5.0 ---@type number
--(Not important) Maximum interval between interactions in seconds.
local NUM_CELLS_X = 35 ---@type integer
local NUM_CELLS_Y = 35 ---@type integer
--The playable map area is partitioned into this many cells. Objects only interact with other objects that share a cell with them. Larger maps require more
--cells.
local DEFAULT_CELL_CHECK_INTERVAL = 0.1 ---@type number
--How often the system checks if objects left their current cell. Can be overwritten during actor creation.
local DEFAULT_OBJECT_RADIUS = 75 ---@type number
--How large an actor is when it comes to determining in which cells it is in. Can be overwritten during actor creation.
--===========================================================================================================================================================
local ceil = math.ceil
local floor = math.floor
local max = math.max
local min = math.min
local sqrt = math.sqrt
local atan = math.atan
local MASTER_TIMER = nil ---@type timer
local MAX_STEPS = 0 ---@type integer
local CYCLE_LENGTH = 0 ---@type integer
local DO_NOT_EVALUATE = 0 ---@type integer
local USE_CELLS = NUM_CELLS_X > 0 and NUM_CELLS_Y > 0 ---@type boolean
local MAP_MIN_X ---@type number
local MAP_MAX_X ---@type number
local MAP_MIN_Y ---@type number
local MAP_MAX_Y ---@type number
local CELL_MIN_X = {} ---@type number[]
local CELL_MIN_Y = {} ---@type number[]
local CELL_MAX_X = {} ---@type number[]
local CELL_MAX_Y = {} ---@type number[]
local CELL_LIST = {} ---@type table[]
for i = 1, NUM_CELLS_X do
CELL_LIST[i] = {}
end
local counter = 0 ---@type integer
local currentPair = nil ---@type Pair | nil
local totalActors = 0 ---@type integer
local freezeCounter = 0 ---@type number
local numPairs = nil ---@type integer[]
local whichPairs = nil ---@type table[]
local numFixedPairs = 0 ---@type integer
local fixedPairs = nil ---@type Pair[]
local actorList = nil ---@type Actor[]
local globalActorList = nil ---@type Actor[]
local pairList = {} ---@type Pair[]
local pairingExcluded = {} ---@type table[]
local numCellChecks = nil ---@type integer[]
local cellCheckedActors = {} ---@type Actor[]
local unusedPairs = {} ---@type Pair[]
local unusedActors = {} ---@type Actor[]
local unusedTables = {} ---@type table[]
local destroyedActors = {} ---@type Actor[]
local actorOf = {} ---@type Actor[]
local bindChecks = {} ---@type Actor[]
local isEveryStepFunction = {} ---@type boolean[]
local functionMaxRange = {} ---@type number
local selfInteractionActor = nil ---@type Actor
local INV_MIN_INTERVAL = 1/ALICE_MIN_INTERVAL - 0.001 ---@type number
ALICE_TimeScale = 1.0 ---@type number
NO_INCOMING_PAIRS = 2147483647 ---@type integer
NO_OUTGOING_PAIRS = -2147483648 ---@type integer
MATCHING_TYPE_ANY = 0 ---@type integer
MATCHING_TYPE_ALL = 1 ---@type integer
MATCHING_TYPE_EXACT = 2 ---@type integer
MATCHING_TYPE_EXCLUDE = 3 ---@type integer
HIGHEST_MATCHING_TYPE = 3 ---@type integer
PLAYER_FILTER_TYPE_ALLY = 4 ---@type integer
PLAYER_FILTER_TYPE_ENEMY = 5 ---@type integer
PLAYER_FILTER_TYPE_OWNER = 6 ---@type integer
PLAYER_FILTER_TYPE_NOT_OWNER = 7 ---@type integer
PLAYER_FILTER_TYPE_ANY = 8 ---@type integer
local RECOGNIZED_FIELDS = { ---@type boolean[]
pairsWith = true,
priority = true,
anchor = true,
cellCheckInterval = true,
isStationary = true,
radius = true,
destroyOnDeath = true,
bindToBuff = true,
bindToOrder = true,
onActorDestroy = true,
randomDelay = true,
isIndestructible = true
}
local ActorA = 1 ---@type integer
local ActorB = 2 ---@type integer
local IndexA = 3 ---@type integer
local IndexB = 4 ---@type integer
local InteractionFunc = 5 ---@type integer
local CurrentPosition = 6 ---@type integer
local PositionInStep = 7 ---@type integer
local DestructionQueued = 8 ---@type integer
local HostA = 9 ---@type integer
local HostB = 10 ---@type integer
local EveryStep = 11 ---@type integer
local UserData = 12 ---@type integer
local Persists = 13 ---@type integer
local debugModeEnabled = false ---@type boolean
local mouseClickTrigger = nil ---@type trigger
local cycleSelectTrigger = nil ---@type trigger
local selectedActor = nil ---@type Actor | nil
local debugTooltip = nil ---@type framehandle
local debugTooltipText = nil ---@type framehandle
local debugTooltipTitle = nil ---@type framehandle
local moveableLoc = nil ---@type location
local printCounts = false ---@type boolean
local visualizeAllActors = false ---@type boolean
local visualizeAllCells = false ---@type boolean
local hash = InitHashtable()
--===========================================================================================================================================================
local function Warning(whichWarning)
for __, name in ipairs(MAP_CREATORS) do
if string.find(GetPlayerName(GetLocalPlayer()), name) then
print(whichWarning)
end
end
end
--===========================================================================================================================================================
--Filter Functions
--===========================================================================================================================================================
---@param whichIdentifier string | string[] | nil
local function Identifier2String(whichIdentifier)
if whichIdentifier == nil then
return "()"
elseif type(whichIdentifier) == "string" then
return whichIdentifier
elseif type(whichIdentifier) == "table" then
local toString = "("
local i = 1
for key, __ in pairs(whichIdentifier) do
if i > 1 then
toString = toString .. ", "
end
toString = toString .. key
i = i + 1
end
toString = toString .. ")"
return toString
end
return nil
end
---@param toCheck table
---@param toMatch table
---@return boolean
local function CheckIdentifierOverlap(toCheck, toMatch)
local identifier = toCheck.identifier
if identifier.noIdentifier then
return false
end
local pairsWith = toMatch.pairsWith
local matchingType = toMatch.matchingType
if matchingType == MATCHING_TYPE_ANY then
for key, __ in pairs(pairsWith) do
if identifier[key] then
return true
end
end
return false
elseif matchingType == MATCHING_TYPE_ALL then
for key, __ in pairs(pairsWith) do
if not identifier[key] then
return false
end
end
return true
elseif matchingType == MATCHING_TYPE_EXACT then
for key, __ in pairs(pairsWith) do
if not identifier[key] then
return false
end
end
for key, __ in pairs(identifier) do
if not pairsWith[key] then
return false
end
end
return true
elseif matchingType == MATCHING_TYPE_EXCLUDE then
for key, __ in pairs(pairsWith) do
if identifier[key] then
return false
end
end
return true
else
Warning("|cffff0000Warning:|r Invalid matching type specified...")
return false
end
end
---@param toMatch any
---@param toCheck any
---@return boolean
local function HasExactIdentifier(toMatch, toCheck)
for key, __ in pairs(toMatch) do
if not toCheck[key] then
return false
end
end
for key, __ in pairs(toCheck) do
if not toMatch[key] then
return false
end
end
return true
end
---@param whichPlayer player
---@param whichFilter integer
---@return boolean
local function IsInPlayerFilter(whichPlayer, whichFilter, whoFilters)
if whichPlayer == nil then
return whichFilter == PLAYER_FILTER_TYPE_ANY
elseif whichFilter == PLAYER_FILTER_TYPE_ANY then
return true
elseif type(whichFilter) == "userdata" then
return whichPlayer == whichFilter
elseif whoFilters == nil then
return true
elseif whichFilter == PLAYER_FILTER_TYPE_ALLY then
return IsPlayerAlly(whichPlayer, whoFilters)
elseif whichFilter == PLAYER_FILTER_TYPE_ENEMY then
return IsPlayerEnemy(whichPlayer, whoFilters)
elseif whichFilter == PLAYER_FILTER_TYPE_OWNER then
return whichPlayer == whoFilters
elseif whichFilter == PLAYER_FILTER_TYPE_NOT_OWNER then
return whichPlayer ~= whoFilters
end
Warning("|cffff0000Warning:|r Unrecognized player filter type...")
return true
end
--===========================================================================================================================================================
--Utility
--===========================================================================================================================================================
local function GetUnusedTable()
if #unusedTables == 0 then
return {}
else
local returnTable = unusedTables[#unusedTables]
unusedTables[#unusedTables] = nil
return returnTable
end
end
local function ReturnTable(whichTable)
for key, __ in pairs(whichTable) do
whichTable[key] = nil
end
unusedTables[#unusedTables + 1] = whichTable
setmetatable(whichTable, nil)
end
---@param object agent
---@return boolean
local function IsWidget(object)
SaveAgentHandle(hash, 0, 0, object)
return LoadWidgetHandle(hash, 0, 0) ~= nil
end
---@param object agent
---@return boolean
local function IsUnit(object)
SaveAgentHandle(hash, 0, 0, object)
return LoadUnitHandle(hash, 0, 0) ~= nil
end
---@param object agent
---@return boolean
local function IsDestructable(object)
SaveAgentHandle(hash, 0, 0, object)
return LoadDestructableHandle(hash, 0, 0) ~= nil
end
---@param object agent
---@return boolean
local function IsItem(object)
SaveAgentHandle(hash, 0, 0, object)
return LoadItemHandle(hash, 0, 0) ~= nil
end
---@param object agent
---@return boolean
local function IsPlayer(object)
SaveAgentHandle(hash, 0, 0, object)
return LoadPlayerHandle(hash, 0, 0) ~= nil
end
---@param object agent
---@return boolean
local function IsEffect(object)
SaveAgentHandle(hash, 0, 0, object)
return LoadEffectHandle(hash, 0, 0) ~= nil
end
---@param func function
---@return string
local function FunctionToString(func)
local string = string.gsub(tostring(func), "function: ", "")
if string.sub(string,1,1) == "0" then
return string.sub(string, string.len(string) - 3, string.len(string))
else
return string
end
end
---@param whichFunction function
local function ExecuteInNewThread(whichFunction)
--Certain functions must not be called from within interactionFuncs. This postpones their call until the loop is over.
TimerStart(CreateTimer(), 0.0, false, function()
whichFunction()
DestroyTimer(GetExpiredTimer())
end)
end
---@param whichPair Pair
---@param duration number
---@param lightningType string
local function VisualizationLightning(whichPair, duration, lightningType)
local A = whichPair[ActorA]
local B = whichPair[ActorB]
if A.isGlobal or B.isGlobal then
return
end
local xa = A.getX(A.anchor)
local ya = A.getY(A.anchor)
local za = A.getZ(A.anchor, xa, ya)
local xb = B.getX(B.anchor)
local yb = B.getY(B.anchor)
local zb = B.getZ(B.anchor, xb, yb)
local visLight
if za and zb then
visLight = AddLightningEx(lightningType, true, xa, ya, za, xb, yb, zb)
else
visLight = AddLightning(lightningType, true, xa, ya, xb, yb)
end
TimerStart(CreateTimer(), duration*ALICE_TimeScale, false, function()
DestroyLightning(visLight)
DestroyTimer(GetExpiredTimer())
end)
end
---@param currentPairList table
---@return string
local function GetPairStatistics(currentPairList)
if #currentPairList == 0 then
return "\nThere are no pairs currently being evaluated."
end
local countActivePairs = 0
local pairTypes = {}
for __, pair in ipairs(currentPairList) do
if not pair[DestructionQueued] then
local idA = pair[ActorA].identifier
local idB = pair[ActorB].identifier
local recognized = false
for __, pairType in ipairs(pairTypes) do
if HasExactIdentifier(pairType[1], idA) and HasExactIdentifier(pairType[2], idB) then
recognized = true
pairType[3] = pairType[3] + 1
break
end
end
if not recognized then
table.insert(pairTypes, {idA, idB, 1})
end
countActivePairs = countActivePairs + 1
end
end
local statistic = ""
if countActivePairs == 0 then
return "\nThere are no pairs currently being evaluated."
end
table.sort(pairTypes, function(a, b) return a[3] > b[3] end)
for __, pairType in ipairs(pairTypes) do
if floor(100*pairType[3]/countActivePairs) > 1 then
statistic = statistic .. "\n" .. floor(100*pairType[3]/countActivePairs) .. "\x25 |cffffcc00" .. Identifier2String(pairType[1]) .. "|r, |cffaaaaff" .. Identifier2String(pairType[2]) .. "|r"
end
end
return statistic
end
local function WillAlwaysBeOutOfRange(actorA, actorB, maxRange)
if actorA.isGlobal or actorB.isGlobal then
return false
end
if not actorA.isStationary or not actorB.isStationary then
return false
end
local dx = actorA.getX(actorA.anchor) - actorB.getX(actorB.anchor)
local dy = actorA.getY(actorA.anchor) - actorB.getY(actorB.anchor)
return dx*dx + dy*dy > maxRange*maxRange
end
local function DoNothing(__,__)
--Dummy function if correct interactionFunc could not be determined.
return ALICE_MAX_INTERVAL
end
--===========================================================================================================================================================
--Coordinate funcs
--===========================================================================================================================================================
---@param x number
---@param y number
---@return number
local function GetLocZ(x, y)
MoveLocation(moveableLoc, x, y)
return GetLocationZ(moveableLoc)
end
---@param host table
---@return number
local function GetClassX(host)
return host[CLASS_FIELD_X]
end
---@param host table
---@return number
local function GetClassY(host)
return host[CLASS_FIELD_Y]
end
---@param host table
---@return number
local function GetClassZ(host, __, __)
return host[CLASS_FIELD_Z]
end
---@param host unit
---@param x number
---@param y number
---@return number
local function GetUnitZ(host, x, y)
return GetLocZ(x, y) + GetUnitFlyHeight(host)
end
---@param x number
---@param y number
---@return number
local function GetItemZ(__, x, y)
return GetLocZ(x, y)
end
--Enables actors as hosts (for whatever reason that is necessary).
---@param actor Actor
---@return function
local function GetActorX(actor)
return actor.getX
end
---@param actor Actor
---@return function
local function GetActorY(actor)
return actor.getY
end
---@param actor Actor
---@return function
local function GetActorZ(actor)
return actor.getZ
end
--===========================================================================================================================================================
--Pair Class
--===========================================================================================================================================================
---@class Pair
local Pair = {
[ActorA] = nil, ---@type Actor
[ActorB] = nil, ---@type Actor
[IndexA] = 0, ---@type integer
[IndexB] = 0, ---@type integer
[InteractionFunc] = nil, ---@type function
[CurrentPosition] = 0, ---@type integer
[PositionInStep] = 0, ---@type integer
[DestructionQueued] = nil, ---@type boolean
[HostA] = nil, ---@type any
[HostB] = nil, ---@type any
[EveryStep] = nil, ---@type boolean
[UserData] = nil, ---@type table
[Persists] = nil, ---@type boolean
}
--Removed class fields and integer keys to reduce memory usage.
local function PairUserDataOnDestroy(self)
if self[UserData].onDestroy ~= nil then
self[UserData].onDestroy(self[HostA], self[HostB], self[UserData])
end
ReturnTable(self[UserData])
self[UserData] = nil
end
---@param actorA Actor
---@param actorB Actor
---@param interactionFunc function
local function CreatePair(actorA, actorB, interactionFunc)
if interactionFunc == nil or actorA.isIsolated or actorB.isIsolated or actorA.host == actorB.host or actorA.anchor == actorB.anchor or (functionMaxRange[interactionFunc] ~= nil and WillAlwaysBeOutOfRange(actorA, actorB, functionMaxRange[interactionFunc])) then
pairingExcluded[actorA][actorB] = true
pairingExcluded[actorB][actorA] = true
return
end
local self ---@type Pair
if #unusedPairs == 0 then
self = {} ---@type Pair
else
self = unusedPairs[#unusedPairs]
unusedPairs[#unusedPairs] = nil
end
self[ActorA] = actorA
self[ActorB] = actorB
self[HostA] = actorA.host
if actorB == selfInteractionActor then
self[HostB] = actorA.host
else
self[HostB] = actorB.host
end
self[InteractionFunc] = interactionFunc
self[IndexA] = #actorA.pairs + 1
self[IndexB] = #actorB.pairs + 1
actorA.pairs[self[IndexA]] = self
actorB.pairs[self[IndexB]] = self
self[DestructionQueued] = false
self[UserData] = nil
actorA.isPairedWith[actorB] = true
actorB.isPairedWith[actorA] = true
pairList[actorA][actorB] = self
if isEveryStepFunction[interactionFunc] then
numFixedPairs = numFixedPairs + 1
fixedPairs[numFixedPairs] = self
self[PositionInStep] = numFixedPairs
self[EveryStep] = true
else
local firstStep
if actorA.randomDelay == nil then
firstStep = counter + 1
else
firstStep = counter + min(MAX_STEPS, ceil(actorA.randomDelay*math.random()*INV_MIN_INTERVAL))
end
if firstStep > CYCLE_LENGTH then
firstStep = firstStep - CYCLE_LENGTH
end
numPairs[firstStep] = numPairs[firstStep] + 1
whichPairs[firstStep][numPairs[firstStep]] = self
self[CurrentPosition] = firstStep
self[PositionInStep] = numPairs[firstStep]
self[EveryStep] = nil
end
end
local function DestroyPair(self)
if self[EveryStep] then
fixedPairs[numFixedPairs][PositionInStep] = self[PositionInStep]
fixedPairs[self[PositionInStep]] = fixedPairs[numFixedPairs]
numFixedPairs = numFixedPairs - 1
else
local currentPosition = self[CurrentPosition] ---@type integer
local pairAtHighestPosition = whichPairs[currentPosition][numPairs[currentPosition]]
whichPairs[currentPosition][self[PositionInStep]] = pairAtHighestPosition
pairAtHighestPosition[PositionInStep] = self[PositionInStep]
numPairs[currentPosition] = numPairs[currentPosition] - 1
end
local A = self[ActorA] ---@type Actor
local B = self[ActorB] ---@type Actor
if self[UserData] ~= nil then
PairUserDataOnDestroy(self)
end
if self[ActorB][self[InteractionFunc]] == self then
self[ActorB][self[InteractionFunc]] = nil
end
local pairAtHighestPosition = B.pairs[#B.pairs]
if pairAtHighestPosition[ActorB] == B then
pairAtHighestPosition[IndexB] = self[IndexB]
else
pairAtHighestPosition[IndexA] = self[IndexB]
end
B.pairs[self[IndexB]] = pairAtHighestPosition
B.pairs[#B.pairs] = nil
pairAtHighestPosition = A.pairs[#A.pairs]
if pairAtHighestPosition[ActorA] == A then
pairAtHighestPosition[IndexA] = self[IndexA]
else
pairAtHighestPosition[IndexB] = self[IndexA]
end
A.pairs[self[IndexA]] = pairAtHighestPosition
A.pairs[#A.pairs] = nil
unusedPairs[#unusedPairs + 1] = self
A.isPairedWith[B] = nil
B.isPairedWith[A] = nil
pairList[A][B] = nil
pairList[B][A] = nil
end
---@param actorA Actor
---@param actorB Actor
---@param tryAgain boolean
---@return Actor, Actor, function | nil
local function GetPairParameters(actorA, actorB, tryAgain)
--First tries to find the interactionFunc from the actor with the higher priority,
--then, if unsuccessful, calls itself with reversed argument order.
--Returns interactionFunc and order of actors.
local interactionFunc = actorA.interactionFunc
if type(interactionFunc) == "table" then
local foundFunc = nil
for keyword, func in pairs(interactionFunc) do
if actorB.identifier[keyword] then
if foundFunc == nil then
foundFunc = func
else
Warning("|cffff0000Warning:|r Interaction func ambiguous for actors with " .. Identifier2String(actorA.identifier) .. " and actors with identifier " .. Identifier2String(actorB.identifier) .. " ...")
return actorA, actorB, DoNothing
end
end
end
if foundFunc ~= nil then
return actorA, actorB, foundFunc
end
if interactionFunc.other ~= nil then
return actorA, actorB, interactionFunc.other
elseif tryAgain then
return GetPairParameters(actorB, actorA, false)
else
return actorA, actorB, nil
end
else
---@diagnostic disable-next-line: return-type-mismatch
if interactionFunc ~= nil then
return actorA, actorB, interactionFunc
elseif tryAgain then
return GetPairParameters(actorB, actorA, false)
else
return actorA, actorB, nil
end
end
end
local pairingEvaluator = {}
pairingEvaluator["boolean"] = function(__, actorB) return actorB.pairsWith end
pairingEvaluator["string"] = function(actorA, actorB) return actorA.identifier[actorB.pairsWith] end
pairingEvaluator["table"] = function(actorA, actorB) return CheckIdentifierOverlap(actorA, actorB) and IsInPlayerFilter(actorA.owner, actorB.playerFilterType, actorB.owner) end
pairingEvaluator["function"] = function(actorA, actorB) return actorB.pairsWith(actorA.host) end
pairingEvaluator["nil"] = function(__, __) return false end
--===========================================================================================================================================================
--Actor Class
--===========================================================================================================================================================
---@class Actor
local Actor = {
host = nil, ---@type any
anchor = nil, ---@type any
owner = nil, ---@type player | nil
identifier = nil, ---@type table
priority = nil, ---@type integer
pairsWith = nil, ---@type string | table | function | boolean
matchingType = nil, ---@type integer | nil
playerFilterType = nil, ---@type integer | player | nil
evaluator = nil, ---@type function
interactionFunc = nil, ---@type function | table | nil
pairs = nil, ---@type Pair[]
index = nil, ---@type integer
alreadyDestroyed = nil, ---@type boolean
isStationary = nil, ---@type boolean | nil
unique = nil, ---@type integer
isPairedWith = nil, ---@type boolean[]
visualizer = nil, ---@type effect
everyStep = nil, ---@type boolean | boolean[]
bindToBuff = nil, ---@type string | nil
unit = nil, ---@type unit | nil
waitingForBuff = nil, ---@type boolean | nil
bindToOrder = nil, ---@type integer | nil
onDestroy = nil, ---@type function | nil
causedCrash = nil, ---@type boolean | nil
isIsolated = nil, ---@type boolean
randomDelay = nil, ---@type number | nil
isIndestructible = nil, ---@type boolean
--Coordinates:
getX = nil, ---@type function
getY = nil, ---@type function
getZ = nil, ---@type function
--Cell interaction:
isGlobal = nil, ---@type boolean
radius = nil, ---@type number
minX = nil, ---@type integer
minY = nil, ---@type integer
maxX = nil, ---@type integer
maxY = nil, ---@type integer
cellCheckInterval = nil, ---@type integer
nextCellCheck = nil, ---@type integer
positionInCellCheck = nil, ---@type integer
cells = nil, ---@type Cell[]
cellIndex = nil, ---@type integer[]
cellsVisualized = nil, ---@type boolean
cellVisualizers = nil, ---@type lightning[]
}
ActorMetatable = {__index = Actor} --Global because fuck no forward declaration.
---@param host any
---@param identifier string | string[] | nil
---@param interactionFunc function | table | nil
---@param pairsWith function | string | table | nil
---@param priority number | nil
---@param radius number | nil
---@param cellCheckInterval number | nil
---@param isStationary boolean | nil
---@param destroyOnDeath boolean | nil
---@param anchor any
---@param bindToBuff string | nil
---@param bindToOrder string | nil
---@param onActorDestroy function | nil
---@param randomDelay number | nil
---@param isIndestructible boolean | nil
---@return Actor | nil
function Actor.create(host, identifier, interactionFunc, pairsWith, priority, radius, cellCheckInterval, isStationary, destroyOnDeath, anchor, bindToBuff, bindToOrder, onActorDestroy, randomDelay, isIndestructible)
if type(identifier) ~= "string" and type(identifier) ~= "table" and identifier ~= nil then
Warning("|cffff0000Error:|r Invalid actor identifier...")
return nil
end
local self ---@type Actor
if #unusedActors == 0 then
self = {}
setmetatable(self, ActorMetatable)
self.identifier = {}
self.isPairedWith = {}
self.pairs = {}
self.cells = {}
self.cellIndex = {}
pairList[self] = {}
pairingExcluded[self] = {}
else
self = unusedActors[#unusedActors]
unusedActors[#unusedActors] = nil
end
totalActors = totalActors + 1
self.unique = totalActors
self.causedCrash = nil
if type(identifier) == "string" then
self.identifier[identifier] = true
elseif type(identifier) == "table" then
for i = 1, #identifier do
self.identifier[identifier[i]] = true
end
elseif identifier == nil then
self.identifier.noIdentifier = true
end
if type(interactionFunc) == "table" then
self.interactionFunc = GetUnusedTable()
for keyword, func in pairs(interactionFunc) do
self.interactionFunc[keyword] = func
end
else
self.interactionFunc = interactionFunc
end
self:initPairingLogic(pairsWith)
self.evaluator = pairingEvaluator[type(self.pairsWith)]
self.host = host
self.anchor = anchor or host
self:setOwner()
self.isStationary = isStationary --overwritten if host is destructable
if self.anchor ~= nil then
self:setCoordinateFuncs()
end
self.isGlobal = self.getX == nil
priority = priority or 0
self.priority = priority
self.randomDelay = randomDelay
local actorPairs
local selfPairs
for __, actor in ipairs(globalActorList) do
if self.anchor ~= actor.anchor then
selfPairs = actor.priority ~= NO_INCOMING_PAIRS and self.evaluator(actor, self)
actorPairs = self.priority ~= NO_INCOMING_PAIRS and actor.evaluator(self, actor)
if selfPairs and actorPairs then
if self.priority < actor.priority then
CreatePair(GetPairParameters(actor, self, true))
else
CreatePair(GetPairParameters(self, actor, true))
end
elseif selfPairs then
CreatePair(GetPairParameters(self, actor, false))
elseif actorPairs then
CreatePair(GetPairParameters(actor, self, false))
end
end
end
if type(self.interactionFunc) == "table" and self.interactionFunc.self ~= nil then
if type(self.interactionFunc.self) == "table" then
for __, func in ipairs(self.interactionFunc.self) do
CreatePair(self, selfInteractionActor, func)
end
else
CreatePair(self, selfInteractionActor, self.interactionFunc.self)
end
end
if not self.isGlobal then
self.radius = radius or DEFAULT_OBJECT_RADIUS
self:initCells()
if self.isStationary then
self.nextCellCheck = DO_NOT_EVALUATE
else
self:initCellChecks(cellCheckInterval or DEFAULT_CELL_CHECK_INTERVAL)
end
end
if self.host ~= nil then
self:createReference()
end
self.isIndestructible = isIndestructible == true
if destroyOnDeath then
self:createOnDeathTrigger()
end
if bindToBuff ~= nil then
self:createBinds(bindToBuff, nil)
elseif bindToOrder ~= nil then
self:createBinds(nil, bindToOrder)
end
self.onDestroy = onActorDestroy
if visualizeAllActors and not self.isGlobal then
self:createVisualizer()
end
self.alreadyDestroyed = false
actorList[#actorList + 1] = self
if self.isGlobal then
globalActorList[#globalActorList + 1] = self
end
self.index = #actorList
return self
end
function Actor:destroy()
if self == nil or self.alreadyDestroyed then
return
end
self.alreadyDestroyed = true
destroyedActors[#destroyedActors + 1] = self
if self.onDestroy ~= nil then
self.onDestroy(self.host)
self.onDestroy = nil
end
actorList[#actorList].index = self.index
actorList[self.index] = actorList[#actorList]
actorList[#actorList] = nil
if self.isGlobal then
for i, actor in ipairs(globalActorList) do
if self == actor then
globalActorList[i] = globalActorList[#globalActorList]
globalActorList[#globalActorList] = nil
break
end
end
end
if type(self.pairsWith) == "table" then
ReturnTable(self.pairsWith)
end
if type(self.interactionFunc) == "table" then
ReturnTable(self.interactionFunc)
end
for key, __ in pairs(self.identifier) do
self.identifier[key] = nil
end
for __, pair in ipairs(self.pairs) do
pair[DestructionQueued] = true
end
for key, __ in pairs(pairingExcluded[self]) do
pairingExcluded[self][key] = nil
pairingExcluded[key][self] = nil
end
if not self.isGlobal then
if not self.isStationary then
local nextCheck = self.nextCellCheck
local actorAtHighestPosition = cellCheckedActors[nextCheck][numCellChecks[nextCheck]]
actorAtHighestPosition.positionInCellCheck = self.positionInCellCheck
cellCheckedActors[nextCheck][self.positionInCellCheck] = actorAtHighestPosition
numCellChecks[nextCheck] = numCellChecks[nextCheck] - 1
end
for i = #self.cells, 1, -1 do
self.cells[i]:remove(self)
end
end
if self.host ~= nil then
self:removeReference(self.host)
if self.host ~= self.anchor then
self:removeReference(self.anchor)
end
self.host = nil
self.anchor = nil
end
if type(self.everyStep) == "table" then
ReturnTable(self.everyStep)
end
self.everyStep = nil
if self.cellsVisualized then
for __, bolt in ipairs(self.cellVisualizers) do
DestroyLightning(bolt)
end
self.cellsVisualized = nil
end
if visualizeAllActors and not self.isGlobal then
DestroyEffect(self.visualizer)
end
if self == selectedActor then
DestroyEffect(self.visualizer)
selectedActor = nil
end
self.getX = nil
self.getY = nil
self.getZ = nil
self.bindToBuff = nil
self.bindToOrder = nil
self.isIsolated = nil
end
function Actor:createReference()
if actorOf[self.host] == nil then
actorOf[self.host] = self
elseif getmetatable(actorOf[self.host]) == ActorMetatable then
actorOf[self.host] = {actorOf[self.host], self}
else
table.insert(actorOf[self.host], self)
end
if self.host ~= self.anchor then
if actorOf[self.anchor] == nil then
actorOf[self.anchor] = self
elseif getmetatable(actorOf[self.anchor]) == ActorMetatable then
actorOf[self.anchor] = {actorOf[self.anchor], self}
else
table.insert(actorOf[self.anchor], self)
end
end
end
function Actor:removeReference(object)
if getmetatable(actorOf[object]) == ActorMetatable then
actorOf[object] = nil
else
for j, v in ipairs(actorOf[object]) do
if self == v then
table.remove(actorOf[object], j)
end
end
if #actorOf[object] == 1 then
actorOf[object] = actorOf[object][1]
end
end
end
function Actor:setCoordinateFuncs()
if type(self.anchor) == "userdata" then
if IsUnit(self.anchor) then
self.getX = GetUnitX
self.getY = GetUnitY
self.getZ = GetUnitZ
elseif IsItem(self.anchor) then
self.getX = GetItemX
self.getY = GetItemY
self.getZ = GetItemZ
elseif IsDestructable(self.anchor) then
local x = GetDestructableX(self.anchor)
local y = GetDestructableY(self.anchor)
local z = GetLocZ(x, y)
self.getX = function() return x end
self.getY = function() return y end
self.getZ = function() return z end
self.isStationary = true
end
elseif type(self.anchor) == "table" then
if self.anchor[CLASS_FIELD_X] ~= nil and self.anchor[CLASS_FIELD_Y] ~= nil then
self.getX = GetClassX
self.getY = GetClassY
self.getZ = GetClassZ
elseif getmetatable(self.anchor) == ActorMetatable then
self.getX = GetActorX(self.anchor)
self.getY = GetActorY(self.anchor)
self.getZ = GetActorZ(self.anchor)
end
end
end
function Actor:setOwner()
if type(self.host) == "userdata" then
if IsUnit(self.host) then
self.owner = GetOwningPlayer(self.host)
elseif IsPlayer(self.host) then
self.owner = self.host
else
self.owner = nil
end
elseif type(self.host) == "table" then
self.owner = self.host[CLASS_FIELD_OWNER]
end
end
function Actor:createOnDeathTrigger()
if IsWidget(self.host) then
local trig = CreateTrigger()
TriggerRegisterDeathEvent(trig, self.host)
TriggerAddAction(trig, function() self:destroy() end)
elseif IsWidget(self.anchor) then
local trig = CreateTrigger()
TriggerRegisterDeathEvent(trig, self.anchor)
TriggerAddAction(trig, function() self:destroy() end)
else
Warning("|cffff0000Warning:|r Cannot use automatic onDeath clean-up with non-widget hosts...")
end
end
---@param pairsWith table
function Actor:initPairingLogic(pairsWith)
--Transforms pairingLogic into form that can be used by internal functions.
--From string sequence to boolean table with string keys.
if type(pairsWith) == "table" then
--Determine pairing logic from pairsWith.
self.pairsWith = GetUnusedTable()
local j = 1
while type(pairsWith[j]) == "string" do
self.pairsWith[pairsWith[j]] = true
j = j + 1
end
for i = j, #pairsWith do
if type(pairsWith[i]) == "number" then
if pairsWith[i] <= HIGHEST_MATCHING_TYPE then
self.matchingType = pairsWith[i]
else
self.playerFilterType = pairsWith[i]
end
elseif type(pairsWith[i]) == "userdata" then
self.playerFilterType = pairsWith[i]
end
end
if self.matchingType == nil then
self.matchingType = MATCHING_TYPE_ANY
end
if self.playerFilterType == nil then
self.playerFilterType = PLAYER_FILTER_TYPE_ANY
end
if self.interactionFunc == nil then
Warning("|cffff0000Warning:|r No interaction func set for actor with identifiers " .. Identifier2String(self.identifier) .. "...")
end
elseif pairsWith == nil then
--Determine pairing logic from interactionFunc.
if type(self.interactionFunc) == "table" then
if self.interactionFunc.other then
self.pairsWith = true
else
self.pairsWith = GetUnusedTable()
for key, __ in pairs(self.interactionFunc) do
self.pairsWith[key] = true
end
self.matchingType = MATCHING_TYPE_ANY
self.playerFilterType = PLAYER_FILTER_TYPE_ANY
end
else
self.pairsWith = self.interactionFunc ~= nil
end
else
self.pairsWith = pairsWith
end
end
function Actor:initCells()
local x = self.getX(self.anchor)
local y = self.getY(self.anchor)
self.minX = min(NUM_CELLS_X, max(1, ceil(NUM_CELLS_X*(x - self.radius - MAP_MIN_X)/(MAP_MAX_X - MAP_MIN_X))))
self.minY = min(NUM_CELLS_Y, max(1, ceil(NUM_CELLS_Y*(y - self.radius - MAP_MIN_Y)/(MAP_MAX_Y - MAP_MIN_Y))))
self.maxX = min(NUM_CELLS_X, max(1, ceil(NUM_CELLS_X*(x + self.radius - MAP_MIN_X)/(MAP_MAX_X - MAP_MIN_X))))
self.maxY = min(NUM_CELLS_Y, max(1, ceil(NUM_CELLS_Y*(y + self.radius - MAP_MIN_Y)/(MAP_MAX_Y - MAP_MIN_Y))))
for X = self.minX, self.maxX do
for Y = self.minY, self.maxY do
CELL_LIST[X][Y]:enter(self)
end
end
end
---@param interval number
function Actor:initCellChecks(interval)
self.cellCheckInterval = min(MAX_STEPS, max(1, ceil((interval - 0.001)*INV_MIN_INTERVAL)))
local nextStep = counter + self.cellCheckInterval
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numCellChecks[nextStep] = numCellChecks[nextStep] + 1
cellCheckedActors[nextStep][numCellChecks[nextStep]] = self
self.nextCellCheck = nextStep
self.positionInCellCheck = numCellChecks[nextStep]
end
---@param x number
---@param y number
function Actor:teleport(x, y)
--Actor has left current cell but is not in adjacent cell.
for i = #self.cells, 1, -1 do
self.cells[i]:leave(self)
end
self.minX = min(NUM_CELLS_X, max(1, ceil(NUM_CELLS_X*(x - self.radius - MAP_MIN_X)/(MAP_MAX_X - MAP_MIN_X))))
self.minY = min(NUM_CELLS_Y, max(1, ceil(NUM_CELLS_Y*(y - self.radius - MAP_MIN_Y)/(MAP_MAX_Y - MAP_MIN_Y))))
self.maxX = min(NUM_CELLS_X, max(1, ceil(NUM_CELLS_X*(x + self.radius - MAP_MIN_X)/(MAP_MAX_X - MAP_MIN_X))))
self.maxY = min(NUM_CELLS_Y, max(1, ceil(NUM_CELLS_Y*(y + self.radius - MAP_MIN_Y)/(MAP_MAX_Y - MAP_MIN_Y))))
for X = self.minX, self.maxX do
for Y = self.minY, self.maxY do
CELL_LIST[X][Y]:enter(self, true)
end
end
end
---@param actor Actor
---@return boolean
function Actor:sharesCellWith(actor)
for __, cellA in ipairs(self.cells) do
for __, cellB in ipairs(actor.cells) do
if cellA == cellB then
return true
end
end
end
return false
end
---@param bindToBuff string | nil
---@param bindToOrder string | nil
function Actor:createBinds(bindToBuff, bindToOrder)
if bindToBuff ~= nil then
self.bindToBuff = bindToBuff
self.waitingForBuff = true
table.insert(bindChecks, self)
elseif bindToOrder ~= nil then
self.bindToOrder = OrderId(bindToOrder)
table.insert(bindChecks, self)
end
if type(self.host) == "userdata" and IsUnit(self.host) then
self.unit = self.host
elseif type(self.anchor) == "userdata" and IsUnit(self.anchor) then
self.unit = self.anchor
else
Warning("|cffff0000Warning:|r Attempted to bind actor with identifier " .. Identifier2String(self.identifier) .. " to a buff or order, but that actor doesn't have a unit host...")
end
end
function Actor:reevaluatePairings()
local selfPairs
local actorPairs
for __, actor in ipairs(actorList) do
if self ~= actor then
if not self.isPairedWith[actor] then
pairingExcluded[self][actor] = nil
pairingExcluded[actor][self] = nil
if (self.isGlobal or actor.isGlobal or self:sharesCellWith(actor)) then
selfPairs = actor.priority ~= NO_INCOMING_PAIRS and self.evaluator(actor, self)
actorPairs = self.priority ~= NO_INCOMING_PAIRS and actor.evaluator(self, actor)
if selfPairs and actorPairs then
if self.priority < actor.priority then
CreatePair(GetPairParameters(actor, self, true))
else
CreatePair(GetPairParameters(self, actor, true))
end
elseif selfPairs then
CreatePair(GetPairParameters(self, actor, false))
elseif actorPairs then
CreatePair(GetPairParameters(actor, self, false))
end
end
elseif not ((actor.priority ~= NO_INCOMING_PAIRS and self.evaluator(actor, self)) or (self.priority ~= NO_INCOMING_PAIRS and actor.evaluator(self, actor))) then
DestroyPair(pairList[self][actor] or pairList[actor][self])
end
end
end
end
---@param newIdentifier string | string[]
function Actor:addIdentifier(newIdentifier)
if type(newIdentifier) == "string" then
self.identifier[newIdentifier] = true
else
for __, keyword in ipairs(newIdentifier) do
self.identifier[keyword] = true
end
end
for i = 1, #self.identifier do
for j = i + 1, #self.identifier do
if self.identifier[i] == self.identifier[j] then
table.remove(self.identifier, j)
end
end
end
ExecuteInNewThread(function() self:reevaluatePairings() end)
end
---@param toRemove string | string[]
function Actor:removeIdentifier(toRemove)
if type(toRemove) == "string" then
self.identifier[toRemove] = nil
else
for __, keyword in ipairs(toRemove) do
self.identifier[keyword] = nil
end
end
ExecuteInNewThread(function() self:reevaluatePairings() end)
end
---@param newIdentifier string | string[] | nil
function Actor:setIdentifier(newIdentifier)
for keyword, __ in pairs(self.identifier) do
self.identifier[keyword] = nil
end
for __, keyword in ipairs(newIdentifier) do
self.identifier[keyword] = true
end
ExecuteInNewThread(function() self:reevaluatePairings() end)
end
---@param enable boolean
function Actor:visualizeCells(enable)
if enable == self.cellsVisualized then
return
end
if self.cellsVisualized then
self.cellsVisualized = false
DestroyLightning(self.cellVisualizers[1])
DestroyLightning(self.cellVisualizers[2])
DestroyLightning(self.cellVisualizers[3])
DestroyLightning(self.cellVisualizers[4])
else
self.cellVisualizers = {}
self.cellsVisualized = true
local minx = CELL_MIN_X[self.minX]
local miny = CELL_MIN_Y[self.minY]
local maxx = CELL_MAX_X[self.maxX]
local maxy = CELL_MAX_Y[self.maxY]
self.cellVisualizers[1] = AddLightning("LEAS", false, maxx, miny, maxx, maxy)
self.cellVisualizers[2] = AddLightning("LEAS", false, maxx, maxy, minx, maxy)
self.cellVisualizers[3] = AddLightning("LEAS", false, minx, maxy, minx, miny)
self.cellVisualizers[4] = AddLightning("LEAS", false, minx, miny, maxx, miny)
end
end
function Actor:redrawCellVisualizers()
local minx = CELL_MIN_X[self.minX]
local miny = CELL_MIN_Y[self.minY]
local maxx = CELL_MAX_X[self.maxX]
local maxy = CELL_MAX_Y[self.maxY]
MoveLightning(self.cellVisualizers[1], false, maxx, miny, maxx, maxy)
MoveLightning(self.cellVisualizers[2], false, maxx, maxy, minx, maxy)
MoveLightning(self.cellVisualizers[3], false, minx, maxy, minx, miny)
MoveLightning(self.cellVisualizers[4], false, minx, miny, maxx, miny)
end
function Actor:isolate()
for __, actor in ipairs(actorList) do
if pairList[actor][self] or pairList[self][actor] then
DestroyPair(pairList[actor][self] or pairList[self][actor])
end
end
self.isIsolated = true
for __, actor in ipairs(actorList) do
pairingExcluded[self][actor] = true
pairingExcluded[actor][self] = true
end
end
function Actor:deselect()
selectedActor = nil
if not visualizeAllActors then
DestroyEffect(self.visualizer)
end
ALICE_VisualizeCells(self, false)
BlzFrameSetVisible(debugTooltip, false)
end
---@return string, string
function Actor:getDescription()
local description = "|cffffcc00Host:|r " .. tostring(self.host)
if self.anchor ~= self.host then
description = description .. "\n|cffffcc00Anchor:|r " .. tostring(self.anchor)
end
description = description .. "\n|cffffcc00InteractionFuncs:|r "
if type(self.interactionFunc) == "table" then
local first = true
for key, func in pairs(self.interactionFunc) do
if key ~= "self" then
if not first then
description = description .. ", "
end
description = description .. key .. " - " .. FunctionToString(func)
first = false
end
end
if self.interactionFunc.self ~= nil then
description = description .. "\n|cffffcc00Self-Interaction:|r "
if type(self.interactionFunc.self) == "function" then
description = description .. FunctionToString(self.interactionFunc.self)
elseif type(self.interactionFunc.self) == "table" then
local first = true
for __, func in ipairs(self.interactionFunc.self) do
if not first then
description = description .. ", "
end
description = description .. FunctionToString(func)
first = false
end
else
description = description .. "|cffff0000Invalid type!|r"
end
end
else
description = description .. tostring(self.interactionFunc)
end
description = description .. "\n|cffffcc00Pairs with:|r "
if type(self.pairsWith) == "table" then
local count = 0
for key, __ in pairs(self.pairsWith) do
if key ~= "self" then
count = count + 1
end
end
if count > 1 then
if self.matchingType == MATCHING_TYPE_ANY then
description = description .. "Any of "
elseif self.matchingType == MATCHING_TYPE_ALL then
description = description .. "All of "
elseif self.matchingType == MATCHING_TYPE_EXACT then
description = description .. "Exactly "
elseif self.matchingType == MATCHING_TYPE_EXCLUDE then
description = description .. "None of "
end
end
local first = true
for key, __ in pairs(self.pairsWith) do
if key ~= "self" then
if not first then
description = description .. ", "
end
description = description .. key
if type(self.interactionFunc) == "table" and self.interactionFunc.other == nil and self.interactionFunc[key] == nil then
description = description .. " |cffaaaaaa(interactionFunc must exist)|r"
end
first = false
end
end
if type(self.playerFilterType) == "userdata" then
description = description .. " (all actors owned by player " .. GetPlayerId(self.playerFilterType) + 1 .. ")"
elseif self.playerFilterType ~= PLAYER_FILTER_TYPE_ANY then
if self.owner == nil then
description = description .. " |cffff0000(player filter requires owner!)|r"
elseif self.playerFilterType == PLAYER_FILTER_TYPE_ENEMY then
description = description .. " (actor must be enemy)"
elseif self.playerFilterType == PLAYER_FILTER_TYPE_OWNER then
description = description .. " (actor must have the same owner)"
elseif self.playerFilterType == PLAYER_FILTER_TYPE_NOT_OWNER then
description = description .. " (actor must have a different owner)"
end
end
elseif self.pairsWith == false or self.pairsWith == nil then
description = description .. "Nothing"
elseif self.pairsWith == true then
if self.playerFilterType == PLAYER_FILTER_TYPE_ANY then
description = description .. "Everything"
elseif self.playerFilterType == PLAYER_FILTER_TYPE_ALLY then
description = description .. "All allied actors."
elseif self.playerFilterType == PLAYER_FILTER_TYPE_ENEMY then
description = description .. "All enemy actors."
elseif self.playerFilterType == PLAYER_FILTER_TYPE_OWNER then
description = description .. "All actors with the same owner."
elseif self.playerFilterType == PLAYER_FILTER_TYPE_NOT_OWNER then
description = description .. "All actors with a different owner."
elseif type(self.playerFilterType) == "userdata" then
description = description .. "All actors owned by player " .. GetPlayerId(self.playerFilterType) + 1
end
elseif type(self.pairsWith) == "function" then
description = description .. tostring(self.pairsWith)
end
if self.priority ~= 0 then
description = description .. "\n|cffffcc00Priority:|r " .. self.priority
end
if self.cellCheckInterval ~= nil then
if math.abs(self.cellCheckInterval*ALICE_MIN_INTERVAL - DEFAULT_CELL_CHECK_INTERVAL) > 0.001 then
description = description .. "\n|cffffcc00Cell Check Interval:|r " .. self.cellCheckInterval*ALICE_MIN_INTERVAL
end
elseif not self.isGlobal then
description = description .. "\n|cffffcc00Stationary:|r true"
end
if self.radius ~= nil and self.radius ~= DEFAULT_OBJECT_RADIUS then
description = description .. "\n|cffffcc00Radius:|r " .. self.radius
end
if self.owner ~= nil then
description = description .. "\n|cffffcc00Owner:|r Player " .. GetPlayerId(self.owner) + 1
end
if self.bindToBuff ~= nil then
description = description .. "\n|cffffcc00Bound to buff:|r " .. self.bindToBuff
if self.waitingForBuff then
description = description .. " |cffaaaaaa(waiting for buff to be applied)|r"
end
end
if self.bindToOrder ~= nil then
description = description .. "\n|cffffcc00Bound to order:|r " .. self.bindToOrder .. " |cffaaaaaa(current order " .. GetUnitCurrentOrder(self.host)
end
if self.onDestroy ~= nil then
description = description .. "\n|cffffcc00On Destroy:|r " .. FunctionToString(self.onDestroy)
end
description = description .. "\n\n|cffffcc00Unique Number:|r " .. self.unique
local numOutgoing = 0
local numIncoming = 0
local hasError = false
local outgoingFuncs = {}
local incomingFuncs = {}
for __, pair in ipairs(self.pairs) do
if pair[ActorB] ~= selfInteractionActor then
if pair[ActorA] == self then
numOutgoing = numOutgoing + 1
outgoingFuncs[pair[InteractionFunc]] = (outgoingFuncs[pair[InteractionFunc]] or 0) + 1
elseif pair[ActorB] == self then
numIncoming = numIncoming + 1
incomingFuncs[pair[InteractionFunc]] = (incomingFuncs[pair[InteractionFunc]] or 0) + 1
else
hasError = true
end
end
end
description = description .. "\n|cffffcc00Outgoing pairs:|r " .. numOutgoing
if numOutgoing > 0 then
local first = true
description = description .. "|cffaaaaaa ("
for key, number in pairs(outgoingFuncs) do
if not first then
description = description .. ", |r"
end
description = description .. "|cffffcc00" .. number .. "|r |cffaaaaaa" .. FunctionToString(key)
first = false
end
description = description .. ")|r"
end
description = description .. "\n|cffffcc00Incoming pairs:|r " .. numIncoming
if numIncoming > 0 then
local first = true
description = description .. "|cffaaaaaa ("
for key, number in pairs(incomingFuncs) do
if not first then
description = description .. ", |r"
end
description = description .. "|cffffcc00" .. number .. "|r |cffaaaaaa" .. FunctionToString(key)
first = false
end
description = description .. ")|r"
end
if hasError then
description = description .. "\n\n|cffff0000DESYNCED PAIR DETECTED!|r"
end
if self.causedCrash then
description = description .. "\n\n|cffff0000CAUSED CRASH!|r"
end
if self.isGlobal then
return description, "|cff00bb00Global Actor|r: " .. Identifier2String(self.identifier)
else
if numOutgoing == 0 and numIncoming == 0 then
return description, "|cffaaaaaaUnpaired Actor:|r " .. Identifier2String(self.identifier)
else
return description, "|cffffff00Actor|r: " .. Identifier2String(self.identifier)
end
end
end
function Actor:select()
selectedActor = self
local description, title = self:getDescription()
BlzFrameSetText(debugTooltipText, description)
BlzFrameSetText(debugTooltipTitle, title )
BlzFrameSetSize(debugTooltipText, 0.28, 0.0)
BlzFrameSetSize(debugTooltip, 0.29, BlzFrameGetHeight(debugTooltipText) + 0.0315)
BlzFrameSetVisible(debugTooltip, true)
if not self.isGlobal then
ALICE_VisualizeCells(self, true)
if not visualizeAllActors then
self:createVisualizer()
end
end
end
function Actor:createVisualizer()
local x = self.getX(self.anchor)
local y = self.getY(self.anchor)
self.visualizer = AddSpecialEffect("Abilities\\Spells\\Other\\Aneu\\AneuTarget.mdl", x, y)
if self.owner ~= nil then
BlzSetSpecialEffectColorByPlayer(self.visualizer, self.owner)
else
BlzSetSpecialEffectColorByPlayer(self.visualizer, Player(21))
end
if type(self.host) == "userdata" and IsWidget(self.host) then
BlzSetSpecialEffectZ(self.visualizer, self.getZ(self.anchor, x, y) + 150)
elseif self.getZ(self.anchor) == nil then
BlzSetSpecialEffectZ(self.visualizer, (self.getZ(self.anchor, x, y) or GetLocZ(x, y)) + 75)
end
end
--===========================================================================================================================================================
--Cell Class
--===========================================================================================================================================================
---@class Cell
local Cell = {
actors = nil, ---@type Actor[]
horizontalLightning = nil, ---@type lightning
verticalLightning = nil ---@type lightning
}
local cellMt = {__index = Cell}
---@param X integer
---@param Y integer
function Cell.create(X, Y)
local new = {}
setmetatable(new, cellMt)
new.actors = {}
CELL_LIST[X][Y] = new
return new
end
function Cell:enter(actorA, wasTeleport)
local aPairs
local bPairs
actorA.cells[#actorA.cells + 1] = self
self.actors[#self.actors + 1] = actorA
actorA.cellIndex[self] = #self.actors
for __, actorB in ipairs(self.actors) do
if actorA ~= actorB then
local thisPair = pairList[actorA][actorB] or pairList[actorB][actorA]
if thisPair ~= nil then
if thisPair[EveryStep] then
if thisPair[PositionInStep] == 0 then
numFixedPairs = numFixedPairs + 1
fixedPairs[numFixedPairs] = thisPair
thisPair[PositionInStep] = numFixedPairs
end
else
--If an actor enters a new cell, it doesn't need to force an immediate interaction with another
--actor if their pair is already enabled. Unless it's a teleport.
if (thisPair[CurrentPosition] == DO_NOT_EVALUATE or wasTeleport) then
local currentPosition = thisPair[CurrentPosition]
local nextStep = counter + 1
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
local pairAtHighestPosition = whichPairs[currentPosition][numPairs[currentPosition]]
pairAtHighestPosition[PositionInStep] = thisPair[PositionInStep]
whichPairs[currentPosition][thisPair[PositionInStep]] = pairAtHighestPosition
numPairs[currentPosition] = numPairs[currentPosition] - 1
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = thisPair
thisPair[CurrentPosition] = nextStep
thisPair[PositionInStep] = numPairs[nextStep]
end
end
elseif not pairingExcluded[actorA][actorB] then
if actorA.anchor ~= actorB.anchor then
aPairs = (actorB.priority ~= NO_INCOMING_PAIRS and actorA.evaluator(actorB, actorA))
bPairs = (actorA.priority ~= NO_INCOMING_PAIRS and actorB.evaluator(actorA, actorB))
if aPairs and bPairs then
if actorA.priority < actorB.priority then
CreatePair(GetPairParameters(actorB, actorA, true))
else
CreatePair(GetPairParameters(actorA, actorB, true))
end
elseif aPairs then
CreatePair(GetPairParameters(actorA, actorB, false))
elseif bPairs then
CreatePair(GetPairParameters(actorB, actorA, false))
else
pairingExcluded[actorA][actorB] = true
pairingExcluded[actorB][actorA] = true
end
end
end
end
end
end
function Cell:remove(actorA)
for i, cell in ipairs(actorA.cells) do
if self == cell then
actorA.cells[i] = actorA.cells[#actorA.cells]
actorA.cells[#actorA.cells] = nil
break
end
end
local actors = self.actors
actors[#actors].cellIndex[self] = actorA.cellIndex[self]
actors[actorA.cellIndex[self]] = actors[#actors]
actors[#actors] = nil
end
function Cell:leave(actorA)
self:remove(actorA)
for __, actorB in ipairs(self.actors) do
if actorA ~= actorB then
local thisPair = pairList[actorA][actorB] or pairList[actorB][actorA]
if thisPair ~= nil then
if thisPair[EveryStep] then
if thisPair[PositionInStep] ~= 0 and (actorA.maxX < actorB.minX or actorA.minX > actorB.maxX or actorA.maxY < actorB.minY or actorA.minY > actorB.maxY) and not thisPair[Persists] then
fixedPairs[thisPair[PositionInStep]] = fixedPairs[numFixedPairs]
numFixedPairs = numFixedPairs - 1
thisPair[PositionInStep] = 0
end
elseif thisPair[CurrentPosition] ~= DO_NOT_EVALUATE and (actorA.maxX < actorB.minX or actorA.minX > actorB.maxX or actorA.maxY < actorB.minY or actorA.minY > actorB.maxY) and not thisPair[Persists] then
local currentPosition = thisPair[CurrentPosition]
local nextStep = DO_NOT_EVALUATE
local pairAtHighestPosition = whichPairs[currentPosition][numPairs[currentPosition]]
pairAtHighestPosition[PositionInStep] = thisPair[PositionInStep]
whichPairs[currentPosition][thisPair[PositionInStep]] = pairAtHighestPosition
numPairs[currentPosition] = numPairs[currentPosition] - 1
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = thisPair
thisPair[CurrentPosition] = nextStep
thisPair[PositionInStep] = numPairs[nextStep]
end
end
end
end
end
--===========================================================================================================================================================
--Repair
--===========================================================================================================================================================
local function WipeCycle()
Warning("\n|cffff0000Error:|r ALICE Cycle desynced. Attempting to repair...")
for i = 1, DO_NOT_EVALUATE do
numPairs[i] = 0
end
local nextStep = counter + 1
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
for __, actor in ipairs(actorList) do
for __, pair in ipairs(actor.pairs) do
if actor == pair[ActorA] then
if pair[CurrentPosition] ~= DO_NOT_EVALUATE then
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = pair
pair[CurrentPosition] = nextStep
pair[PositionInStep] = numPairs[nextStep]
else
numPairs[DO_NOT_EVALUATE] = numPairs[DO_NOT_EVALUATE] + 1
whichPairs[DO_NOT_EVALUATE][numPairs[DO_NOT_EVALUATE]] = pair
pair[CurrentPosition] = DO_NOT_EVALUATE
pair[PositionInStep] = numPairs[DO_NOT_EVALUATE]
end
end
end
end
end
local function CheckCycleIntegrity()
for i = 1, CYCLE_LENGTH do
if numPairs[i] < 0 then
WipeCycle()
return
end
for j = 1, numPairs[i] do
local pair = whichPairs[i][j]
if not pair[DestructionQueued] and (pair[CurrentPosition] ~= i or pair[PositionInStep] ~= j) then
WipeCycle()
return
end
end
end
end
local function RepairCycle(firstPosition)
local numSteps
local nextStep
for i = firstPosition, numPairs[counter] do
currentPair = whichPairs[counter][i]
if currentPair[DestructionQueued] then
numSteps = MAX_STEPS
else
numSteps = (currentPair[InteractionFunc](currentPair[HostA], currentPair[HostB])*INV_MIN_INTERVAL + 1) // 1
if numSteps < 1 then
numSteps = 1
elseif numSteps > MAX_STEPS then
numSteps = MAX_STEPS
end
end
nextStep = counter + numSteps
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = currentPair
currentPair[CurrentPosition] = nextStep
currentPair[PositionInStep] = numPairs[nextStep]
end
numPairs[counter] = 0
for i = 1, numFixedPairs do
currentPair = fixedPairs[i]
currentPair[InteractionFunc](currentPair[HostA], currentPair[HostB])
end
currentPair = nil
end
local function OnCrash()
local crashingPair = currentPair
if crashingPair == nil then --Just to shut up the diagnostics.
return
end
--Remove pair and continue with cycle on the first crash. On the second crash, isolate actor completely.
local A = crashingPair[ActorA]
local B = crashingPair[ActorB]
pairingExcluded[A][B] = true
pairingExcluded[B][A] = true
if not crashingPair[EveryStep] then
Warning("\n|cffff0000Error:|r ALICE Cycle crashed during last execution. The identifiers of the actors responsible are "
.. "|cffffcc00" .. Identifier2String(A.identifier) .. "|r and |cffaaaaff" .. Identifier2String(B.identifier) .. "|r. Unique numbers: " .. A.unique .. ", " .. B.unique .. ". The pair has been removed from the cycle...")
local nextPosition = crashingPair[PositionInStep] + 1
numPairs[DO_NOT_EVALUATE] = numPairs[DO_NOT_EVALUATE] + 1
whichPairs[DO_NOT_EVALUATE][numPairs[DO_NOT_EVALUATE]] = crashingPair
crashingPair[CurrentPosition] = DO_NOT_EVALUATE
crashingPair[PositionInStep] = numPairs[DO_NOT_EVALUATE]
DestroyPair(crashingPair)
RepairCycle(nextPosition)
else
Warning("|cffff0000Error:|r ALICE Cycle crashed during last execution. The identifiers of the actors responsible are "
.. "|cffffcc00" .. Identifier2String(A.identifier) .. "|r and |cffaaaaff" .. Identifier2String(B.identifier) .. "|r. Unique numbers: " .. A.unique .. ", " .. B.unique .. ". The pair has been removed from the cycle...")
DestroyPair(crashingPair)
end
if A.causedCrash and not A.isIndestructible then
Warning("\nActor with identifier " .. Identifier2String(A.identifier) .. ", unique number: " .. A.unique .. " is repeatedly causing crashes. Isolating...")
A:isolate()
elseif B.causedCrash and not B.isIndestructible then
Warning("\nActor with identifier " .. Identifier2String(B.identifier) .. ", unique number: " .. B.unique .. " is repeatedly causing crashes. Isolating...")
B:isolate()
end
A.causedCrash = true
B.causedCrash = true
CheckCycleIntegrity()
end
--===========================================================================================================================================================
--Main Functions
--===========================================================================================================================================================
local function BindChecks()
for i = #bindChecks, 1, -1 do
local actor = bindChecks[i]
if actor.bindToBuff ~= nil then
if actor.waitingForBuff then
if GetUnitAbilityLevel(actor.unit, FourCC(actor.bindToBuff)) > 0 then
actor.waitingForBuff = nil
end
elseif GetUnitAbilityLevel(actor.unit, FourCC(actor.bindToBuff)) == 0 then
ALICE_Destroy(actor)
bindChecks[i] = bindChecks[#bindChecks]
bindChecks[#bindChecks] = nil
end
elseif actor.bindToOrder ~= nil then
if GetUnitCurrentOrder(actor.unit) ~= actor.bindToOrder then
ALICE_Destroy(actor)
bindChecks[i] = bindChecks[#bindChecks]
bindChecks[#bindChecks] = nil
end
end
end
end
local function RemovePairsFromCycle()
for i = #destroyedActors, 1, -1 do
local actor = destroyedActors[i]
if actor ~= nil then
local pairs = actor.pairs
for j = #pairs, 1, -1 do
DestroyPair(pairs[j])
end
unusedActors[#unusedActors + 1] = actor
end
destroyedActors[i] = nil
end
end
local function CellCheck()
local x
local y
local radius
local minx
local miny
local maxx
local maxy
local actor
local actorsThisStep = cellCheckedActors[counter]
local nextStep
for i = 1, numCellChecks[counter] do
actor = actorsThisStep[i]
x = actor.getX(actor.anchor)
y = actor.getY(actor.anchor)
radius = actor.radius
minx = x - radius
miny = y - radius
maxx = x + radius
maxy = y + radius
if minx < CELL_MIN_X[actor.minX] and actor.minX > 1 then
actor.minX = actor.minX - 1
if minx < CELL_MIN_X[actor.minX] then
actor:teleport(x, y)
else
for Y = actor.minY, actor.maxY do
CELL_LIST[actor.minX][Y]:enter(actor, false)
end
end
if actor.cellsVisualized then
actor:redrawCellVisualizers()
end
elseif minx > CELL_MAX_X[actor.minX] and actor.minX < NUM_CELLS_X then
actor.minX = actor.minX + 1
if minx > CELL_MAX_X[actor.minX] then
actor:teleport(x, y)
else
for Y = actor.minY, actor.maxY do
CELL_LIST[actor.minX - 1][Y]:leave(actor)
end
end
if actor.cellsVisualized then
actor:redrawCellVisualizers()
end
end
if miny < CELL_MIN_Y[actor.minY] and actor.minY > 1 then
actor.minY = actor.minY - 1
if miny < CELL_MIN_Y[actor.minY] then
actor:teleport(x, y)
else
for X = actor.minX, actor.maxX do
CELL_LIST[X][actor.minY]:enter(actor, false)
end
end
if actor.cellsVisualized then
actor:redrawCellVisualizers()
end
elseif miny > CELL_MAX_Y[actor.minY] and actor.minY < NUM_CELLS_Y then
actor.minY = actor.minY + 1
if miny > CELL_MAX_Y[actor.minY] then
actor:teleport(x, y)
else
for X = actor.minX, actor.maxX do
CELL_LIST[X][actor.minY - 1]:leave(actor)
end
end
if actor.cellsVisualized then
actor:redrawCellVisualizers()
end
end
if maxx > CELL_MAX_X[actor.maxX] and actor.maxX < NUM_CELLS_X then
actor.maxX = actor.maxX + 1
if maxx > CELL_MAX_X[actor.maxX] then
actor:teleport(x, y)
else
for Y = actor.minY, actor.maxY do
CELL_LIST[actor.maxX][Y]:enter(actor, false)
end
end
if actor.cellsVisualized then
actor:redrawCellVisualizers()
end
elseif maxx < CELL_MIN_X[actor.maxX] and actor.maxX > 1 then
actor.maxX = actor.maxX - 1
if maxx < CELL_MIN_X[actor.maxX] then
actor:teleport(x, y)
else
for Y = actor.minY, actor.maxY do
CELL_LIST[actor.maxX + 1][Y]:leave(actor)
end
end
if actor.cellsVisualized then
actor:redrawCellVisualizers()
end
end
if maxy > CELL_MAX_Y[actor.maxY] and actor.maxY < NUM_CELLS_Y then
actor.maxY = actor.maxY + 1
if maxy > CELL_MAX_Y[actor.maxY] then
actor:teleport(x, y)
else
for X = actor.minX, actor.maxX do
CELL_LIST[X][actor.maxY]:enter(actor, false)
end
end
if actor.cellsVisualized then
actor:redrawCellVisualizers()
end
elseif maxy < CELL_MIN_Y[actor.maxY] and actor.maxY > 1 then
actor.maxY = actor.maxY - 1
if maxy < CELL_MIN_Y[actor.maxY] then
actor:teleport(x, y)
else
for X = actor.minX, actor.maxX do
CELL_LIST[X][actor.maxY + 1]:leave(actor)
end
end
if actor.cellsVisualized then
actor:redrawCellVisualizers()
end
end
nextStep = counter + actor.cellCheckInterval
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numCellChecks[nextStep] = numCellChecks[nextStep] + 1
cellCheckedActors[nextStep][numCellChecks[nextStep]] = actor
actor.nextCellCheck = nextStep
actor.positionInCellCheck = numCellChecks[nextStep]
if visualizeAllActors then
if type(actor.host) == "userdata" and IsWidget(actor.host) then
BlzSetSpecialEffectPosition(actor.visualizer, x, y, actor.getZ(actor.anchor, x, y) + 150)
else
BlzSetSpecialEffectPosition(actor.visualizer, x, y, (actor.getZ(actor.anchor, x, y) or GetLocZ(x, y)) + 75)
end
end
end
end
local function UpdateSelectedActor()
if selectedActor ~= nil then
if not selectedActor.isGlobal then
local x = selectedActor.getX(selectedActor.anchor)
local y = selectedActor.getY(selectedActor.anchor)
if type(selectedActor.host) == "userdata" and IsWidget(selectedActor.host) then
BlzSetSpecialEffectPosition(selectedActor.visualizer, x, y, selectedActor.getZ(selectedActor.anchor, x, y) + 150)
else
BlzSetSpecialEffectPosition(selectedActor.visualizer, x, y, (selectedActor.getZ(selectedActor.anchor, x, y) or GetLocZ(x, y)) + 75)
end
for __, pair in ipairs(selectedActor.pairs) do
if pair[EveryStep] or pair[CurrentPosition] == counter then
VisualizationLightning(pair, 0.03, "DRAL")
end
end
end
local description, title = selectedActor:getDescription()
BlzFrameSetText(debugTooltipText, description)
BlzFrameSetText(debugTooltipTitle, title )
BlzFrameSetSize(debugTooltipText, 0.28, 0.0)
BlzFrameSetSize(debugTooltip, 0.29, BlzFrameGetHeight(debugTooltipText) + 0.0315)
end
end
local function FreezeProtection()
freezeCounter = freezeCounter + math.min(2*FREEZE_PROTECTION_LIMIT, (numPairs[counter] + numFixedPairs - FREEZE_PROTECTION_LIMIT))/10
if freezeCounter < 0 then
freezeCounter = 0
elseif freezeCounter >= FREEZE_PROTECTION_LIMIT then
Warning("|cffff0000Error:|r ALICE Cycle terminated due to load exceeding the specified freeze protection limit. The identifiers of the actors in the pairs responsible for the overload are:\n" .. GetPairStatistics(whichPairs[counter]))
PauseTimer(MASTER_TIMER)
end
end
--===========================================================================================================================================================
--Main
--===========================================================================================================================================================
local function Main()
local numSteps
local nextStep
if currentPair ~= nil then
OnCrash()
end
BindChecks()
RemovePairsFromCycle()
counter = counter + 1
if counter > CYCLE_LENGTH then
counter = 1
end
CellCheck()
if printCounts then
print("actors: " .. #actorList .. ", pairs: " .. numPairs[counter] + numFixedPairs .. ", cell checks: " .. numCellChecks[counter])
end
numCellChecks[counter] = 0
FreezeProtection()
if debugModeEnabled then
UpdateSelectedActor()
end
--Main
for i = 1, numPairs[counter] do
currentPair = whichPairs[counter][i]
if currentPair[DestructionQueued] then
numSteps = MAX_STEPS
else
numSteps = (currentPair[InteractionFunc](currentPair[HostA], currentPair[HostB])*INV_MIN_INTERVAL + 1) // 1 --convert seconds to steps, then ceil.
if numSteps < 1 then
numSteps = 1
elseif numSteps > MAX_STEPS then
numSteps = MAX_STEPS
end
end
nextStep = counter + numSteps
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = currentPair
currentPair[CurrentPosition] = nextStep
currentPair[PositionInStep] = numPairs[nextStep]
end
numPairs[counter] = 0
--Every Step Cycle
for i = 1, numFixedPairs do
currentPair = fixedPairs[i]
currentPair[InteractionFunc](currentPair[HostA], currentPair[HostB])
end
currentPair = nil
end
--===========================================================================================================================================================
--Debug Mode
--===========================================================================================================================================================
local function OnMouseClick()
if BlzGetTriggerPlayerMouseButton() ~= MOUSE_BUTTON_TYPE_LEFT then
return
end
if selectedActor ~= nil then
selectedActor:deselect()
end
local x = BlzGetTriggerPlayerMouseX()
local y = BlzGetTriggerPlayerMouseY()
local objects = ALICE_EnumObjectsInRange(x, y, 100, true, nil)
local closestDist = 100
local closestObject = nil
for __, object in ipairs(objects) do
local actor = ALICE_GetActor(object)
---@diagnostic disable-next-line: need-check-nil
local dx = actor.getX(actor.anchor) - x
---@diagnostic disable-next-line: need-check-nil
local dy = actor.getY(actor.anchor) - y
local dist = sqrt(dx*dx + dy*dy)
if dist < closestDist then
closestDist = dist
---@diagnostic disable-next-line: need-check-nil
closestObject = actor.host
end
end
if closestObject ~= nil then
if getmetatable(actorOf[closestObject]) == ActorMetatable then
actorOf[closestObject]:select()
else
print("Multiple actors exist for this object. Press |cffffcc00(C)|r to cycle through.")
actorOf[closestObject][1]:select()
end
end
end
local function OnCKey()
if selectedActor == nil then
return
end
local selectedObject = selectedActor.anchor
if getmetatable(actorOf[selectedObject]) == ActorMetatable then
return
end
for index, actor in ipairs(actorOf[selectedObject]) do
if selectedActor == actor then
selectedActor:deselect()
if actorOf[selectedObject][index + 1] ~= nil then
actorOf[selectedObject][index + 1]:select()
return
else
actorOf[selectedObject][1]:select()
return
end
end
end
end
local function EnableDebugMode()
if not debugModeEnabled then
Warning("\nDebug mode enabled. Left-click near an actor to display attributes and enable visualization. \n\nYou can use the Eikonium's IngameConsole to execute code on the selected actor. You refer to it with ALICE_GetActor().")
debugModeEnabled = true
BlzLoadTOCFile("CustomTooltip.toc")
debugTooltip = BlzCreateFrame("CustomTooltip", BlzGetOriginFrame(ORIGIN_FRAME_WORLD_FRAME, 0), 0, 0)
BlzFrameSetAbsPoint( debugTooltip , FRAMEPOINT_BOTTOMRIGHT , 0.8 , 0.165 )
BlzFrameSetSize( debugTooltip , 0.32 , 0.0 )
debugTooltipTitle = BlzFrameGetChild(debugTooltip,0)
debugTooltipText = BlzFrameGetChild(debugTooltip,1)
mouseClickTrigger = CreateTrigger()
TriggerRegisterPlayerEvent(mouseClickTrigger, GetTriggerPlayer(), EVENT_PLAYER_MOUSE_DOWN)
TriggerAddAction(mouseClickTrigger, OnMouseClick)
cycleSelectTrigger = CreateTrigger()
BlzTriggerRegisterPlayerKeyEvent(cycleSelectTrigger, GetTriggerPlayer(), OSKEY_C, 0, true)
TriggerAddAction(cycleSelectTrigger, OnCKey)
else
Warning("\nDebug mode has been disabled.")
if selectedActor ~= nil then
selectedActor:deselect()
end
debugModeEnabled = false
DestroyTrigger(mouseClickTrigger)
DestroyTrigger(cycleSelectTrigger)
BlzDestroyFrame(debugTooltip)
end
end
--===========================================================================================================================================================
--Init
--===========================================================================================================================================================
OnInit.main(function()
MASTER_TIMER = CreateTimer()
MAX_STEPS = floor(ALICE_MAX_INTERVAL/ALICE_MIN_INTERVAL)
CYCLE_LENGTH = MAX_STEPS + 1
DO_NOT_EVALUATE = CYCLE_LENGTH + 1
numPairs = {}
whichPairs = {}
actorList = {}
globalActorList = {}
for i = 1, DO_NOT_EVALUATE do
numPairs[i] = 0
whichPairs[i] = {}
end
fixedPairs = {}
numCellChecks = {}
for i = 1, CYCLE_LENGTH do
numCellChecks[i] = 0
cellCheckedActors[i] = {}
end
if USE_CELLS then
local worldBounds = GetWorldBounds()
MAP_MIN_X = GetRectMinX(worldBounds)
MAP_MAX_X = GetRectMaxX(worldBounds)
MAP_MIN_Y = GetRectMinY(worldBounds)
MAP_MAX_Y = GetRectMaxY(worldBounds)
for x = 1, NUM_CELLS_X do
for y = 1, NUM_CELLS_Y do
Cell.create(x,y)
end
end
for x = 1, NUM_CELLS_X do
CELL_MIN_X[x] = MAP_MIN_X + (x-1)/NUM_CELLS_X*(MAP_MAX_X - MAP_MIN_X)
CELL_MAX_X[x] = MAP_MIN_X + x/NUM_CELLS_X*(MAP_MAX_X - MAP_MIN_X)
end
for y = 1, NUM_CELLS_Y do
CELL_MIN_Y[y] = MAP_MIN_Y + (y-1)/NUM_CELLS_Y*(MAP_MAX_Y - MAP_MIN_Y)
CELL_MAX_Y[y] = MAP_MIN_Y + y/NUM_CELLS_Y*(MAP_MAX_Y - MAP_MIN_Y)
end
end
local trig = CreateTrigger()
for i = 0, 23 do
for __, name in ipairs(MAP_CREATORS) do
if string.find(GetPlayerName(Player(i)), name) then
TriggerRegisterPlayerChatEvent(trig, Player(i), "downtherabbithole", true)
TriggerRegisterPlayerChatEvent(trig, Player(i), "-downtherabbithole", true)
end
end
end
TriggerAddAction(trig, EnableDebugMode)
moveableLoc = Location(0,0)
selfInteractionActor = ALICE_Create(nil, "selfInteraction", nil, {isIndestructible = true})
actorList[#actorList] = nil
globalActorList[#globalActorList] = nil
totalActors = totalActors - 1
selfInteractionActor.unique = 0
TimerStart(MASTER_TIMER, ALICE_MIN_INTERVAL, true, Main)
end)
--===========================================================================================================================================================
--API
--===========================================================================================================================================================
---@type Actor
local actorDummy = {
pairsWith = {},
interactionFunc = DoNothing
}
setmetatable(actorDummy, ActorMetatable)
--Main API
--===========================================================================================================================================================
---@param host any
---@param identifier string | string[] | nil
---@param interactionFunc function | table | nil
---@param flags? table
---@return Actor | nil
function ALICE_Create(host, identifier, interactionFunc, flags)
if flags == nil then
return Actor.create(host, identifier, interactionFunc)
else
for key, __ in pairs(flags) do
if not RECOGNIZED_FIELDS[key] then
Warning("|cffff0000Warning:|r Unrecognized field |cffffcc00" .. key .. "|r in flags passed to function ALICE_Create...")
end
end
return Actor.create(
host,
identifier,
interactionFunc,
flags.pairsWith,
flags.priority,
flags.radius,
flags.cellCheckInterval,
flags.isStationary,
flags.destroyOnDeath,
flags.anchor,
flags.bindToBuff,
flags.bindToOrder,
flags.onActorDestroy,
flags.randomDelay,
flags.isIndestructible
)
end
end
---@param whichClass table
---@return Actor | nil
function ALICE_CreateFromClass(whichClass)
return Actor.create(
whichClass,
whichClass.identifier,
whichClass.interactionFunc,
whichClass.pairsWith,
whichClass.priority,
whichClass.radius,
whichClass.cellCheckInterval,
whichClass.isStationary,
whichClass.destroyOnDeath,
whichClass.anchor,
whichClass.bindToBuff,
whichClass.bindToOrder,
whichClass.onActorDestroy,
whichClass.randomDelay,
whichClass.isIndestructible
)
end
---@param object any
---@param keyword? string
function ALICE_Destroy(object, keyword)
object = ALICE_GetActor(object, keyword)
if object ~= nil then
if object.isIndestructible then
Warning("|cffff0000Warning:|r Attempted to destroy indestructible actor with identifiers " .. Identifier2String(object) .. ", unique number: " .. object.unique)
end
object:destroy()
end
end
--Object API
--===========================================================================================================================================================
---@param object any
---@param keyword? string
---@return boolean
function ALICE_HasActor(object, keyword)
return ALICE_GetActor(object, keyword) ~= nil
end
---@param object any
---@param keyword? string
---@return Actor | nil
function ALICE_GetActor(object, keyword)
if object == nil then
if selectedActor ~= nil then
return selectedActor
end
return nil
end
if getmetatable(object) == ActorMetatable then
return object
elseif actorOf[object] ~= nil then
if getmetatable(actorOf[object]) == ActorMetatable then
if keyword == nil or actorOf[object].identifier[keyword] then
return actorOf[object]
else
return nil
end
elseif keyword == nil then
return actorOf[object][1]
else
for __, actor in ipairs(actorOf[object]) do
if actor.identifier[keyword] then
return actor
end
end
return nil
end
else
return nil
end
end
---@param object any
function ALICE_UpdateOwner(object)
if actorOf[object] ~= nil then
if getmetatable(actorOf[object]) == ActorMetatable then
actorOf[object]:setOwner()
ExecuteInNewThread(function() actorOf[object]:reevaluatePairings() end)
else
for __, actor in ipairs(actorOf[object]) do
actor:setOwner()
ExecuteInNewThread(function() actor:reevaluatePairings() end)
end
end
elseif getmetatable(actorOf[object]) == ActorMetatable then
object:setOwner()
ExecuteInNewThread(function() object:reevaluatePairings() end)
end
end
---@param object any
---@param identifier string
---@param newFunc function
---@param keyword? string
function ALICE_SetInteractionFunc(object, identifier, newFunc, keyword)
object = ALICE_GetActor(object,keyword)
if object == nil then
return
end
object.interactionFunc[identifier] = newFunc
for __, pair in ipairs(object.pairs) do
if object == pair[ActorA] then
pair[InteractionFunc] = newFunc
end
end
end
---@param object any
function ALICE_Kill(object)
object = ALICE_GetActor(object)
if object == nil then
Warning("|cffff0000Warning:|r Attempted to kill object without an actor...")
return
end
if type(object.host) == "table" then
if type(object.host.destroy) == "function" then
object.host:destroy()
else
Warning("|cffff0000Warning:|r Attempted to destroy class that does not have a destroy method...")
end
elseif type(object.host) == "userdata" then
if IsUnit(object.host) then
KillUnit(object.host)
elseif IsDestructable(object.host) then
KillDestructable(object.host)
elseif IsItem(object.host) then
RemoveItem(object.host)
elseif IsEffect(object.host) then
DestroyEffect(object.host)
else
Warning("|cffff0000Warning:|r Attempted to kill host of a type for which no kill function was set yet...")
end
else
Warning("|cffff0000Warning:|r Attempted to kill host of a type that cannot be killed...")
end
end
--Identifier API
--===========================================================================================================================================================
---@param object any
---@param newIdentifier string | string[]
---@param keyword? string
function ALICE_AddIdentifier(object, newIdentifier, keyword)
object = ALICE_GetActor(object,keyword)
if object == nil then
return
end
object:addIdentifier(newIdentifier)
end
---@param object any
---@param toRemove string | string[]
---@param keyword? string
function ALICE_RemoveIdentifier(object, toRemove, keyword)
object = ALICE_GetActor(object,keyword)
if object == nil then
return
end
object:removeIdentifier(toRemove)
end
---@param object any
---@param newIdentifier string | string[] | nil
---@param keyword? string
function ALICE_SetIdentifier(object, newIdentifier, keyword)
object = ALICE_GetActor(object,keyword)
if object == nil then
return
end
object:setIdentifier(newIdentifier)
end
---@param whichObject any
---@param identifier string | table
---@param keyword? string
---@return boolean
function ALICE_HasIdentifier(whichObject, identifier, keyword)
whichObject = ALICE_GetActor(whichObject, keyword)
if whichObject == nil then
return false
end
if type(identifier) == "table" then
for key, __ in pairs(actorDummy.pairsWith) do
actorDummy.pairsWith[key] = nil
end
actorDummy:initPairingLogic(identifier)
return CheckIdentifierOverlap(whichObject, actorDummy)
else
return whichObject.identifier[identifier]
end
end
---@param objectA any
---@param objectB any
---@return boolean
function ALICE_PairsWith(objectA, objectB)
objectA = ALICE_GetActor(objectA)
if objectA == nil then
return false
end
objectB = ALICE_GetActor(objectB)
if objectB == nil then
return false
end
return (objectB.priority ~= NO_INCOMING_PAIRS and objectA.evaluator(objectB, objectA)) or (objectA.priority ~= NO_INCOMING_PAIRS and objectB.evaluator(objectA, objectB))
end
---@param object any
---@param keyword? string
function ALICE_GetIdentifier(object, keyword)
object = ALICE_GetActor(object,keyword)
if object == nil then
return
end
local returnTable = {}
for key, __ in pairs(object.identifier) do
table.insert(returnTable, key)
end
table.sort(returnTable, function(a, b) return tostring(a) < tostring(b) end)
return returnTable
end
--Pair API
--===========================================================================================================================================================
---@param whichFunc function
function ALICE_PairSetInteractionFunc(whichFunc)
if currentPair == nil then
Warning("|cffff0000Error:|r Cannot call Pair API functions from outside of interaction func...")
return
end
currentPair[InteractionFunc] = whichFunc
end
function ALICE_PairDisable()
if currentPair == nil then
Warning("|cffff0000Error:|r Cannot call Pair API functions from outside of interaction func...")
return
end
local thisPair = currentPair
pairingExcluded[thisPair[ActorA]][thisPair[ActorB]] = true
pairingExcluded[thisPair[ActorB]][thisPair[ActorA]] = true
ExecuteInNewThread(function()
DestroyPair(thisPair)
end)
end
---@param whichClass? table
---@return table
function ALICE_PairLoadData(whichClass)
if currentPair == nil then
Warning("|cffff0000Error:|r Cannot call Pair API functions from outside of interaction func...")
return {}
end
if currentPair[UserData] == nil then
currentPair[UserData] = GetUnusedTable()
setmetatable(currentPair[UserData], whichClass)
end
return currentPair[UserData]
end
function ALICE_PairOnDestroy(callback)
if currentPair == nil then
Warning("|cffff0000Error:|r Cannot call Pair API functions from outside of interaction func...")
return {}
end
if currentPair[UserData] == nil then
currentPair[UserData] = GetUnusedTable()
end
currentPair[UserData].onDestroy = callback
end
---@return number
function ALICE_PairGetDistance()
if currentPair == nil then
Warning("|cffff0000Error:|r Cannot call Pair API functions from outside of interaction func...")
return 0
end
local objectA = currentPair[ActorA]
local objectB = currentPair[ActorB]
if objectA ~= nil and objectB == selfInteractionActor then
return 0
end
if objectA.isGlobal or objectB.isGlobal then
Warning("|cffff0000Error:|r Attempted to call ALICE_PairGetDistance on a pair with a global actor...")
return 0
end
local dx = objectA.getX(objectA.anchor) - objectB.getX(objectB.anchor)
local dy = objectA.getY(objectA.anchor) - objectB.getY(objectB.anchor)
return sqrt(dx*dx + dy*dy)
end
---@return number
function ALICE_PairGetDistance3D()
if currentPair == nil then
Warning("|cffff0000Error:|r Cannot call Pair API functions from outside of interaction func...")
return 0
end
local objectA = currentPair[ActorA]
local objectB = currentPair[ActorB]
if objectA ~= nil and objectB == selfInteractionActor then
return 0
end
if objectA.isGlobal or objectB.isGlobal then
Warning("|cffff0000Error:|r Attempted to call ALICE_PairGetDistance3D on a pair with a global actor...")
return 0
end
local xa = objectA.getX(objectA.anchor)
local ya = objectA.getY(objectA.anchor)
local xb = objectA.getX(objectB.anchor)
local yb = objectB.getY(objectB.anchor)
local dz = objectA.getZ(objectA.anchor, xa, ya) - objectB.getZ(objectB.anchor, xb, yb)
return sqrt((xa - xb)^2 + (ya - yb)^2 + dz*dz)
end
---@return number
function ALICE_PairGetAngle()
if currentPair == nil then
Warning("|cffff0000Error:|r Cannot call Pair API functions from outside of interaction func...")
return 0
end
local objectA = currentPair[ActorA]
local objectB = currentPair[ActorB]
if objectA ~= nil and objectB == selfInteractionActor then
return 0
end
if objectA.isGlobal or objectB.isGlobal then
Warning("|cffff0000Error:|r Attempted to call ALICE_PairGetAngle on a pair with a global actor...")
return 0
end
local dx = objectB.getX(objectB.anchor) - objectA.getX(objectA.anchor)
local dy = objectB.getY(objectB.anchor) - objectA.getY(objectA.anchor)
return atan(dy, dx)
end
---@return number, number
function ALICE_PairGetAngle3D()
if currentPair == nil then
Warning("|cffff0000Error:|r Cannot call Pair API functions from outside of interaction func...")
return 0, 0
end
local objectA = currentPair[ActorA]
local objectB = currentPair[ActorB]
if objectA ~= nil and objectB == selfInteractionActor then
return 0, 0
end
if objectA.isGlobal or objectB.isGlobal then
Warning("|cffff0000Error:|r Attempted to call ALICE_PairGetAngle3D on a pair with a global actor...")
return 0, 0
end
local xa = objectA.getX(objectA.anchor)
local ya = objectA.getY(objectA.anchor)
local xb = objectA.getX(objectB.anchor)
local yb = objectB.getY(objectB.anchor)
local dx = xb - xa
local dy = yb - ya
local dz = objectB.getZ(objectB.anchor, xb, yb) - objectA.getZ(objectA.anchor, xa, ya)
return atan(dy, dx), atan(dz, sqrt(dx*dx + dy*dy))
end
---@return boolean
function ALICE_PairIsFirstContact()
if currentPair == nil then
Warning("|cffff0000Error:|r Cannot call Pair API functions from outside of interaction func...")
return false
end
if currentPair[UserData] == nil then
ALICE_PairLoadData()
currentPair[UserData].hadContact = true
return true
elseif currentPair[UserData].hadContact then
return false
else
currentPair[UserData].hadContact = true
return true
end
end
function ALICE_PairForget()
if currentPair == nil then
Warning("|cffff0000Error:|r Cannot call Pair API functions from outside of interaction func...")
return false
end
if currentPair[ActorB][currentPair[InteractionFunc]] == currentPair then
currentPair[ActorB][currentPair[InteractionFunc]] = nil
end
if currentPair[UserData] ~= nil then
PairUserDataOnDestroy(currentPair)
end
end
function ALICE_PairPersist()
if currentPair == nil then
Warning("|cffff0000Error:|r Cannot call Pair API functions from outside of interaction func...")
return {}
end
currentPair[Persists] = true
end
function ALICE_PairIsUnoccupied()
if currentPair == nil then
Warning("|cffff0000Error:|r Cannot call Pair API functions from outside of interaction func...")
return false
end
if currentPair[ActorB][currentPair[InteractionFunc]] ~= nil and currentPair[ActorB][currentPair[InteractionFunc]] ~= currentPair then
return false
else
--Store for the receiving actor at the key of the interaction func the current pair as occupying that slot, blocking other pairs.
currentPair[ActorB][currentPair[InteractionFunc]] = currentPair
return true
end
end
--Enum API
--===========================================================================================================================================================
local enumExceptions = {}
---@param filter function | boolean | string | table | nil
---@param whoFilters player | nil
---@return table
function ALICE_EnumObjects(filter, whoFilters)
local returnTable = {}
if filter == nil then
filter = true
end
if type(filter) == "table" then
actorDummy:initPairingLogic(filter)
else
actorDummy.pairsWith = filter
end
actorDummy.owner = whoFilters
local evaluator = pairingEvaluator[type(filter)]
for __, actor in ipairs(actorList) do
if evaluator(actor, actorDummy) and not enumExceptions[actor.host] then
returnTable[#returnTable + 1] = actor.host
enumExceptions[actor.host] = true
end
end
for key, __ in pairs(enumExceptions) do
enumExceptions[key] = nil
end
return returnTable
end
---@param filter function | boolean | string | table | nil
---@param whoFilters player | nil
---@param action function
function ALICE_ForAllObjectsDo(filter, whoFilters, action)
local list = ALICE_EnumObjects(filter, whoFilters)
for __, object in ipairs(list) do
action(object)
end
end
---@param x number
---@param y number
---@param range number
---@param filter function | boolean | string | table | nil
---@param whoFilters player | nil
---@return table
function ALICE_EnumObjectsInRange(x, y, range, filter, whoFilters)
local returnTable = {}
if filter == nil then
filter = true
end
local minX = min(NUM_CELLS_X, max(1, ceil(NUM_CELLS_X*(x - range - MAP_MIN_X)/(MAP_MAX_X - MAP_MIN_X))))
local minY = min(NUM_CELLS_Y, max(1, ceil(NUM_CELLS_Y*(y - range - MAP_MIN_Y)/(MAP_MAX_Y - MAP_MIN_Y))))
local maxX = min(NUM_CELLS_X, max(1, ceil(NUM_CELLS_X*(x + range - MAP_MIN_X)/(MAP_MAX_X - MAP_MIN_X))))
local maxY = min(NUM_CELLS_Y, max(1, ceil(NUM_CELLS_Y*(y + range - MAP_MIN_Y)/(MAP_MAX_Y - MAP_MIN_Y))))
local dx
local dy
local rangeSquared = range*range
if type(filter) == "table" then
actorDummy:initPairingLogic(filter)
else
actorDummy.pairsWith = filter
end
actorDummy.owner = whoFilters
local evaluator = pairingEvaluator[type(filter)]
for X = minX, maxX do
for Y = minY, maxY do
for __, actor in ipairs(CELL_LIST[X][Y].actors) do
if not enumExceptions[actor.host] then
if evaluator(actor, actorDummy) then
enumExceptions[actor.host] = true
dx = actor.getX(actor.anchor) - x
dy = actor.getY(actor.anchor) - y
if dx*dx + dy*dy < rangeSquared then
returnTable[#returnTable + 1] = actor.host
end
end
end
end
end
end
for key, __ in pairs(enumExceptions) do
enumExceptions[key] = nil
end
return returnTable
end
---@param x number
---@param y number
---@param range number
---@param filter function | boolean | string | table | nil
---@param whoFilters player | nil
---@param action function
function ALICE_ForAllObjectsInRangeDo(x, y, range, filter, whoFilters, action)
local list = ALICE_EnumObjectsInRange(x, y, range, filter, whoFilters)
for __, object in ipairs(list) do
action(object)
end
end
---@param minx number
---@param miny number
---@param maxx number
---@param maxy number
---@param filter function | boolean | string | table | nil
---@param whoFilters? player | nil
---@return table
function ALICE_EnumObjectsInRect(minx, miny, maxx, maxy, filter, whoFilters)
local returnTable = {}
if filter == nil then
filter = true
end
local minX = min(NUM_CELLS_X, max(1, ceil(NUM_CELLS_X*(minx - MAP_MIN_X)/(MAP_MAX_X - MAP_MIN_X))))
local minY = min(NUM_CELLS_Y, max(1, ceil(NUM_CELLS_Y*(miny - MAP_MIN_Y)/(MAP_MAX_Y - MAP_MIN_Y))))
local maxX = min(NUM_CELLS_X, max(1, ceil(NUM_CELLS_X*(maxx - MAP_MIN_X)/(MAP_MAX_X - MAP_MIN_X))))
local maxY = min(NUM_CELLS_Y, max(1, ceil(NUM_CELLS_Y*(maxy - MAP_MIN_Y)/(MAP_MAX_Y - MAP_MIN_Y))))
local x
local y
if type(filter) == "table" then
actorDummy:initPairingLogic(filter)
else
actorDummy.pairsWith = filter
end
actorDummy.owner = whoFilters
local evaluator = pairingEvaluator[type(filter)]
for X = minX, maxX do
for Y = minY, maxY do
for __, actor in ipairs(CELL_LIST[X][Y].actors) do
if not enumExceptions[actor.host] then
if evaluator(actor, actorDummy) then
enumExceptions[actor.host] = true
x = actor.getX(actor.anchor)
y = actor.getY(actor.anchor)
if x > minx and x < maxx and y > miny and y < maxy then
returnTable[#returnTable + 1] = actor.host
end
end
end
end
end
end
for key, __ in pairs(enumExceptions) do
enumExceptions[key] = nil
end
return returnTable
end
---@param minx number
---@param miny number
---@param maxx number
---@param maxy number
---@param filter function | boolean | string | table | nil
---@param whoFilters player | nil
---@param action function
function ALICE_ForAllObjectsInRectDo(minx, miny, maxx, maxy, filter, whoFilters, action)
local list = ALICE_EnumObjectsInRect(minx, miny, maxx, maxy, filter, whoFilters)
for __, object in ipairs(list) do
action(object)
end
end
--Debug API
--===========================================================================================================================================================
function ALICE_Pause()
PauseTimer(MASTER_TIMER)
end
---@param factor number
function ALICE_SlowMotion(factor)
ALICE_TimeScale = factor
TimerStart(MASTER_TIMER, ALICE_MIN_INTERVAL*factor, true, Main)
end
function ALICE_Resume()
ALICE_TimeScale = 1
TimerStart(MASTER_TIMER, ALICE_MIN_INTERVAL, true, Main)
end
---@param duration? number
---@param lightningType? string
function ALICE_PairVisualize(duration, lightningType)
if currentPair == nil then
Warning("|cffff0000Error:|r Cannot call Pair API functions from outside of interaction func...")
return
end
local objectA = currentPair[ActorA]
local objectB = currentPair[ActorB]
local xa = objectA.getX(objectA.anchor)
local ya = objectA.getY(objectA.anchor)
local xb = objectB.getX(objectB.anchor)
local yb = objectB.getY(objectB.anchor)
if xa and ya and xb and yb then
local visLight = AddLightning(lightningType or "DRAL", true, xa, ya, xb, yb)
TimerStart(CreateTimer(), duration or 0.03, false, function()
DestroyLightning(visLight)
DestroyTimer(GetExpiredTimer())
end)
end
end
---@param whichObject any
---@param enable? boolean
---@param keyword? string
function ALICE_VisualizeCells(whichObject, enable, keyword)
whichObject = ALICE_GetActor(whichObject,keyword)
if whichObject == nil then
Warning("|cffff0000Warning:|r Could not find actor of argument in ALICE_VisualizeCells...")
return
end
whichObject:visualizeCells((enable == nil) or enable)
end
function ALICE_Statistics()
Warning("|cffffcc00Statistics:|r The identifiers of the actors in the pairs currently being evaluated are:\n" .. GetPairStatistics(whichPairs[counter+1]))
end
function ALICE_ListGlobals()
local message = "List of all global actors:"
for __, actor in ipairs(globalActorList) do
message = message .. "\n" .. Identifier2String(actor.identifier) .. ", Unique: " .. actor.unique
end
Warning(message)
end
---@param whichActor Actor | integer
function ALICE_Select(whichActor)
if not debugModeEnabled then
Warning("|cffff0000Error:|r ALICE_Select only available in debug mode...")
return
end
if type(whichActor) == "table" then
whichActor:select()
else
ALICE_GetFromUnique(whichActor):select()
end
end
---@param number integer
---@return Actor | nil
function ALICE_GetFromUnique(number)
for __, actor in ipairs(actorList) do
if actor.unique == number then
return actor
end
end
return nil
end
function ALICE_PrintCounts()
printCounts = not printCounts
end
function ALICE_VisualizeAllCells()
visualizeAllCells = not visualizeAllCells
if visualizeAllCells then
for X = 1, NUM_CELLS_X do
for Y = 1, NUM_CELLS_Y do
local minx = MAP_MIN_X + (X-1)/NUM_CELLS_X*(MAP_MAX_X - MAP_MIN_X)
local miny = MAP_MIN_Y + (Y-1)/NUM_CELLS_Y*(MAP_MAX_Y - MAP_MIN_Y)
local maxx = MAP_MIN_X + X/NUM_CELLS_X*(MAP_MAX_X - MAP_MIN_X)
local maxy = MAP_MIN_Y + Y/NUM_CELLS_Y*(MAP_MAX_Y - MAP_MIN_Y)
CELL_LIST[X][Y].horizontalLightning = AddLightning("DRAM", false, minx, miny, maxx, miny)
SetLightningColor(CELL_LIST[X][Y].horizontalLightning, 1, 1, 1, 0.35)
CELL_LIST[X][Y].verticalLightning = AddLightning("DRAM", false, maxx, miny, maxx, maxy)
SetLightningColor(CELL_LIST[X][Y].verticalLightning, 1, 1, 1, 0.35)
end
end
else
for X = 1, NUM_CELLS_X do
for Y = 1, NUM_CELLS_Y do
DestroyLightning(CELL_LIST[X][Y].horizontalLightning)
DestroyLightning(CELL_LIST[X][Y].verticalLightning)
end
end
end
end
function ALICE_VisualizeAllActors()
visualizeAllActors = not visualizeAllActors
if visualizeAllActors then
for __, actor in ipairs(actorList) do
if not actor.isGlobal and not actor ~= selectedActor then
actor:createVisualizer()
end
end
else
for __, actor in ipairs(actorList) do
if not actor.isGlobal and not actor ~= selectedActor then
DestroyEffect(actor.visualizer)
end
end
end
end
--Optimization API
--===========================================================================================================================================================
---@param whichFunc function
function ALICE_SetEveryStep(whichFunc)
isEveryStepFunction[whichFunc] = true
end
---@param whichFunc function
---@param maxRange number
function ALICE_SetMaxRange(whichFunc, maxRange)
functionMaxRange[whichFunc] = maxRange
end
---@param object any
---@param newRadius number
---@param keyword? string
function ALICE_SetRadius(object, newRadius, keyword)
object = ALICE_GetActor(object,keyword)
if object == nil then
return
end
object.radius = newRadius
end
---@param object any
---@param enable boolean
---@param keyword? string
function ALICE_SetStationary(object, enable, keyword)
object = ALICE_GetActor(object,keyword)
if object == nil then
return
end
if object.isStationary == enable then
return
end
object.isStationary = enable
if enable then
local nextCheck = object.nextCellCheck
local actorAtHighestPosition = cellCheckedActors[nextCheck][numCellChecks[nextCheck]]
actorAtHighestPosition.positionInCellCheck = object.positionInCellCheck
cellCheckedActors[nextCheck][object.positionInCellCheck] = actorAtHighestPosition
numCellChecks[nextCheck] = numCellChecks[nextCheck] - 1
object.nextCellCheck = DO_NOT_EVALUATE
else
local nextStep = counter + 1
numCellChecks[nextStep] = numCellChecks[nextStep] + 1
cellCheckedActors[nextStep][numCellChecks[nextStep]] = object
object.nextCellCheck = nextStep
object.positionInCellCheck = numCellChecks[nextStep]
end
end
---@param object any
---@param newInterval number
---@param keyword? string
function ALICE_SetCellCheckInterval(object, newInterval, keyword)
object = ALICE_GetActor(object,keyword)
if object == nil then
return
end
object.cellCheckInterval = min(MAX_STEPS, max(1, ceil((newInterval - 0.001)*INV_MIN_INTERVAL)))
end
end
if Debug then Debug.beginFile "CAT Shared Functions" end
do
--[[
=============================================================================================================================================================
Complementary Actor Template
Functions required for units, items, and destructables CAT
=============================================================================================================================================================
]]
CAT_ExceptionList = {}
CAT_WidgetIdRadius = {}
CAT_WidgetIdIsStationary = {}
CAT_WidgetIdCellCheckInterval = {}
---@param whichString string
---@return string
function CAT_ToCamelCase(whichString)
whichString = whichString:gsub("(\x25s)(\x25a)", function(__, letter) return letter:upper() end)
return string.lower(string.sub(whichString,1,1)) .. string.sub(whichString,2)
end
---@param widgetId integer
---@param whichList table
---@return boolean
function CAT_IsWidgetIdInList(widgetId, whichList)
for __, v in ipairs(whichList) do
if v == widgetId then
return true
end
end
return false
end
---@param widgetId integer
function CAT_AddException(widgetId)
if not CAT_IsWidgetIdInList(widgetId, CAT_ExceptionList) then
table.insert(CAT_ExceptionList, widgetId)
end
end
---@param widgetId integer
---@param radius number
function CAT_SetWidgetIdRadius(widgetId, radius)
CAT_WidgetIdRadius[widgetId] = radius
end
---@param widgetId integer
---@param interval number
function CAT_SetWidgetCellCheckInterval(widgetId, interval)
CAT_WidgetIdCellCheckInterval[widgetId] = interval
end
---@param widgetId integer
function CAT_SetWidgetIdStationary(widgetId)
CAT_WidgetIdIsStationary[widgetId] = true
end
end
if Debug then Debug.beginFile "CAT Units" end
do
--[[
=============================================================================================================================================================
Complementary Actor Template
by Antares
Requires:
ALICE https://www.hiveworkshop.com/threads/a-l-i-c-e-interaction-engine.353126/
CAT Shared Functions
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
Hook https://www.hiveworkshop.com/threads/hook.339153/
=============================================================================================================================================================
U N I T S
=============================================================================================================================================================
This template automatically creates an actor for each unit that enters the map (units with Locust are excluded). A unit actor will get the identifiers "unit"
and "<unitName>" (transformed to camelCase formatting to be consistent with other identifiers). You can choose to add "hero"/"nonhero" and unit classifications
to the identifiers.
These actors will not initiate any pairs themselves. They will be destroyed on the unit's death.
You can add exceptions with CAT_AddException(unitId). Units with ids that were added to the exception list will not get an actor.
Customization of this library for your specific needs is encouraged.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
local IGNORE_UNIT_UNLESS_IN_LIST = false ---@type boolean
--If set to true, no actor will be created unless it has been enabled for that unit type with CAT_AddUnitException.
local DO_REVIVE_CHECK = false ---@type boolean
--After a nonhero unit dies, periodically check if it has been revived until it is removed from the game. Revive checks can be added manually with
--CAT_AddReviveCheck(whichUnit) (while the unit is still alive).
local REVIVE_CHECK_INTERVAL = 0.25 ---@type number
--How often the revive check is done on each unit.
local ADD_HERO_CLASSIFICATION = true ---@type boolean
--Add "hero"/"nonhero" identifier to the actor.
local ADD_UNIT_CLASSIFICATIONS = false ---@type boolean
--Add identifiers such as "mechanical"/"nonmechanical" to the actor.
--[[
=============================================================================================================================================================
A P I
=============================================================================================================================================================
CAT_AddUnitActor(whichUnit)
CAT_AddException(unitId)
CAT_AddReviveCheck(whichUnit)
CAT_SetWidgetIdRadius(unitId, radius)
CAT_SetWidgetCellCheckInterval(unitId, interval)
CAT_SetWidgetIdStationary(unitId)
=============================================================================================================================================================
]]
local reviveCheckList = {}
local actorFlags = {}
local identifiers = {}
---@param u unit
---@param ignoreExceptions boolean
local function CreateUnitActor(u, ignoreExceptions)
local id = GetUnitTypeId(u)
if not ignoreExceptions then
if GetUnitAbilityLevel(u, FourCC("Aloc")) > 0 then --Locust
return
end
if CAT_IsWidgetIdInList(id, CAT_ExceptionList) ~= IGNORE_UNIT_UNLESS_IN_LIST then
return
end
end
for key, __ in pairs(identifiers) do
identifiers[key] = nil
end
table.insert(identifiers, "CAT")
table.insert(identifiers, "unit")
table.insert(identifiers, CAT_ToCamelCase(GetUnitName(u)))
if ADD_HERO_CLASSIFICATION then
if IsUnitType(u, UNIT_TYPE_HERO) then
table.insert(identifiers, "hero")
else
table.insert(identifiers, "nonhero")
end
end
if ADD_UNIT_CLASSIFICATIONS then
if IsUnitType(u, UNIT_TYPE_UNDEAD) then
table.insert(identifiers, "undead")
else
table.insert(identifiers, "nonundead")
end
if IsUnitType(u, UNIT_TYPE_MECHANICAL) then
table.insert(identifiers, "mechanical")
else
table.insert(identifiers, "nonmechanical")
end
if IsUnitType(u, UNIT_TYPE_FLYING) then
table.insert(identifiers, "flying")
else
table.insert(identifiers, "ground")
end
if IsUnitType(u, UNIT_TYPE_STRUCTURE) then
table.insert(identifiers, "structure")
else
table.insert(identifiers, "nonstructure")
end
if IsUnitType(u, UNIT_TYPE_ANCIENT) then
table.insert(identifiers, "ancient")
else
table.insert(identifiers, "nonancient")
end
if IsUnitType(u, UNIT_TYPE_SAPPER) then
table.insert(identifiers, "sapper")
else
table.insert(identifiers, "nonsapper")
end
end
actorFlags.isStationary = CAT_WidgetIdIsStationary[id]
actorFlags.radius = CAT_WidgetIdRadius[id]
actorFlags.cellCheckInterval = CAT_WidgetIdCellCheckInterval[id]
ALICE_Create(u, identifiers, nil, actorFlags)
end
local function CAT_ReviveCheck(u)
if GetUnitTypeId(u) == 0 then
reviveCheckList[u] = nil
ALICE_Destroy(u, "CAT")
elseif UnitAlive(u) then
ALICE_Destroy(u, "CAT")
CreateUnitActor(u, false)
end
return REVIVE_CHECK_INTERVAL
end
local function OnUnitDeath()
local u = GetTriggerUnit()
if not ALICE_HasActor(u, "CAT") then
return
end
ALICE_Destroy(u, "CAT")
if (DO_REVIVE_CHECK and not IsUnitType(u, UNIT_TYPE_HERO)) or reviveCheckList[u] then
ALICE_Create(u, {"CAT", "corpse"}, {self = CAT_ReviveCheck}, {isStationary = true})
end
end
local function OnUnitEnter()
CreateUnitActor(GetTriggerUnit(), false)
end
function Hook:RemoveUnit(whichUnit)
ALICE_Destroy(whichUnit)
self.old(whichUnit)
end
function Hook:SetUnitOwner(whichUnit, newOwner)
self.old(whichUnit, newOwner)
ALICE_UpdateOwner(whichUnit)
end
local function InitCAT()
local reg = CreateRegion()
RegionAddRect(reg, GetWorldBounds())
local trig = CreateTrigger()
TriggerRegisterEnterRegion(trig, reg, nil)
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_HERO_REVIVE_FINISH)
TriggerAddAction(trig, OnUnitEnter)
trig = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_DEATH)
TriggerAddAction(trig, OnUnitDeath)
local G = CreateGroup()
GroupEnumUnitsInRect(G, GetPlayableMapRect(), nil)
ForGroup(G, function() CreateUnitActor(GetEnumUnit(), false) end)
DestroyGroup(G)
local reviveCheckerClass = {
identifier = "reviveChecker",
interactionFunc = {revivableCorpse = CAT_ReviveCheck},
isIndestructible = true
}
ALICE_CreateFromClass(reviveCheckerClass)
end
OnInit.final(InitCAT)
--===========================================================================================================================================================
---@param unitId integer
function CAT_AddUnitException(unitId)
if not CAT_IsWidgetIdInList(unitId, CAT_ExceptionList) then
table.insert(CAT_ExceptionList, unitId)
end
end
---@param whichUnit unit
function CAT_AddReviveCheck(whichUnit)
reviveCheckList[whichUnit] = true
end
---@param whichUnit unit
function CAT_AddUnitActor(whichUnit)
CreateUnitActor(whichUnit, true)
end
end
if Debug then Debug.beginFile "CAT Items" end
do
--[[
=============================================================================================================================================================
Complementary Actor Template
by Antares
Requires:
ALICE https://www.hiveworkshop.com/threads/a-l-i-c-e-interaction-engine.353126/
CAT Shared Functions
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
Hook https://www.hiveworkshop.com/threads/hook.339153/
=============================================================================================================================================================
I T E M S
=============================================================================================================================================================
This template automatically creates an actor for each item. An item actor will get the identifiers "item" and <itemName> (transformed to camelCase formatting
to be consistent with other identifiers).
These actors will not initiate any pairs themselves. They will be destroyed on the item's death.
You can add exceptions with CAT_AddException(itemId). Items with ids that were added to the exception list will not get an actor.
Customization of this library for your specific needs is encouraged.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
local IGNORE_ITEM_UNLESS_IN_LIST = false ---@type boolean
--If set to true, no actor will be created unless it has been enabled for that item type with CAT_AddException.
--[[
=============================================================================================================================================================
A P I
=============================================================================================================================================================
CAT_AddItemActor(whichItem)
CAT_AddException(itemId)
CAT_SetWidgetIdRadius(itemId, radius)
CAT_SetWidgetCellCheckInterval(itemId, interval)
--===========================================================================================================================================================
]]
local actorFlags = {destroyOnDeath = true}
local identifiers = {}
---@param i item
---@param ignoreExceptions boolean
local function CreateItemActor(i, ignoreExceptions)
local id = GetItemTypeId(i)
if not ignoreExceptions then
if CAT_IsWidgetIdInList(id, CAT_ExceptionList) ~= IGNORE_ITEM_UNLESS_IN_LIST then
return
end
end
for key, __ in pairs(identifiers) do
identifiers[key] = nil
end
table.insert(identifiers, "CAT")
table.insert(identifiers, "item")
local name = GetItemName(i)
table.insert(identifiers, CAT_ToCamelCase(name))
actorFlags.radius = CAT_WidgetIdRadius[id]
ALICE_Create(i, identifiers, nil, actorFlags)
end
if Hook then
function Hook:CreateItem(...)
local newItem
newItem = self.old(...)
CreateItemActor(newItem, false)
return newItem
end
end
local function OnItemPickup()
ALICE_Destroy(GetManipulatedItem(), "CAT")
end
local function OnItemDrop()
CreateItemActor(GetManipulatedItem(), false)
end
function InitCAT()
EnumItemsInRect(GetPlayableMapRect(), nil, function() CreateItemActor(GetEnumItem(), false) end)
local trig = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_DROP_ITEM)
TriggerAddAction(trig, OnItemDrop)
trig = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_PICKUP_ITEM)
TriggerAddAction(trig, OnItemPickup)
end
OnInit.final(InitCAT)
---@param whichItem item
function CAT_AddItemActor(whichItem)
CreateItemActor(whichItem, true)
end
end
if Debug then Debug.beginFile "CAT Destructables" end
do
--[[
=============================================================================================================================================================
Complementary Actor Template
by Antares
Requires:
ALICE https://www.hiveworkshop.com/threads/a-l-i-c-e-interaction-engine.353126/
CAT Shared Functions
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
Hook https://www.hiveworkshop.com/threads/hook.339153/
=============================================================================================================================================================
D E S T R U C T A B L E S
=============================================================================================================================================================
This template automatically creates an actor for each destructable. A destructable actor will get the identifiers "destructable" and <destructableName>
(transformed to camelCase formatting to be consistent with other identifiers). CAT also searches for "Tree", "Rock", "Gate", "Bridge", and "Blocker" in its
name and adds those identifiers if it finds them.
These actors will not initiate any pairs themselves. They will be destroyed on the destructable's death.
You can add exceptions with CAT_AddException(destructableId). Destructables with ids that were added to the exception list will not get an actor.
Customization of this library for your specific needs is encouraged.
Limitations: Revived destructables do not get an actor.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
local IGNORE_DESTRUCTABLE_UNLESS_IN_LIST = false ---@type boolean
--If set to true, no actor will be created unless it has been enabled for that destructable type with CAT_AddException.
--[[
=============================================================================================================================================================
A P I
=============================================================================================================================================================
CAT_AddDestructableActor(whichDestructable)
CAT_AddException(destructableId)
CAT_SetWidgetIdRadius(destructableId, radius)
--===========================================================================================================================================================
]]
local actorFlags = {destroyOnDeath = true}
local identifiers = {}
---@param d destructable
---@param ignoreExceptions boolean
local function CreateDestructableActor(d, ignoreExceptions)
local id = GetDestructableTypeId(d)
if not ignoreExceptions then
if CAT_IsWidgetIdInList(id, CAT_ExceptionList) ~= IGNORE_DESTRUCTABLE_UNLESS_IN_LIST then
return
end
end
for key, __ in pairs(identifiers) do
identifiers[key] = nil
end
table.insert(identifiers, "CAT")
table.insert(identifiers, "destructable")
local name = GetDestructableName(d)
table.insert(identifiers, CAT_ToCamelCase(name))
if string.find(name, "Tree") then
table.insert(identifiers, "tree")
elseif string.find(name, "Rock") then
table.insert(identifiers, "rock")
elseif string.find(name, "Blocker") then
table.insert(identifiers, "blocker")
elseif string.find(name, "Gate") then
table.insert(identifiers, "gate")
elseif string.find(name, "Bridge") then
table.insert(identifiers, "bridge")
end
actorFlags.radius = CAT_WidgetIdRadius[id]
ALICE_Create(d, identifiers, nil, actorFlags)
end
if Hook then
function Hook:CreateDestructable(...)
local newDestructable
newDestructable = self.old(...)
CreateDestructableActor(newDestructable, false)
return newDestructable
end
function Hook:CreateDestructableZ(...)
local newDestructable
newDestructable = self.old(...)
CreateDestructableActor(newDestructable, false)
return newDestructable
end
function Hook:BlzCreateDestructableWithSkin(...)
local newDestructable
newDestructable = self.old(...)
CreateDestructableActor(newDestructable, false)
return newDestructable
end
function Hook:BlzCreateDestructableZWithSkin(...)
local newDestructable
newDestructable = self.old(...)
CreateDestructableActor(newDestructable, false)
return newDestructable
end
end
function InitCAT()
EnumDestructablesInRect(GetPlayableMapRect(), nil, function() CreateDestructableActor(GetEnumDestructable(), false) end)
end
OnInit.final(InitCAT)
---@param whichDestructable destructable
function CAT_AddDestructableActor(whichDestructable)
CreateDestructableActor(whichDestructable, true)
end
end
do
local SCOPE_PREFIX = "InterpolatedMouse_" ---@type string
local REDUCE_MOUSE_LAG = 0.5 ---@type number
local UPDATE_INTERVAL = 0.01 ---@type number
local MAX_INTERP_COUNTER = math.floor(0.1/UPDATE_INTERVAL) ---@type integer
local numRegisteredPlayers = 0 ---@type integer
local registeredPlayers = {} ---@type integer[]
local x1 = {} ---@type number[]
local y1 = {} ---@type number[]
local x2 = {} ---@type number[]
local y2 = {} ---@type number[]
local interpCounter = {} ---@type integer[]
MouseX = {} ---@type number[]
MouseY = {} ---@type number[]
InterpMouseX = {} ---@type number[]
InterpMouseY = {} ---@type number[]
local function Interpolate()
local i = 1 ---@type integer
local r ---@type number
local P ---@type integer
for i = 1, numRegisteredPlayers do
P = registeredPlayers[i]
if interpCounter[P] == -1 then
x1[P] = x2[P]
y1[P] = y2[P]
InterpMouseX[P] = x2[P]
InterpMouseY[P] = y2[P]
else
interpCounter[P] = interpCounter[P] + 1
r = interpCounter[P]/MAX_INTERP_COUNTER
InterpMouseX[P] = (1 - REDUCE_MOUSE_LAG - r)*x1[P] + (REDUCE_MOUSE_LAG + r)*x2[P]
InterpMouseY[P] = (1 - REDUCE_MOUSE_LAG - r)*y1[P] + (REDUCE_MOUSE_LAG + r)*y2[P]
if interpCounter[P] == MAX_INTERP_COUNTER then
interpCounter[P] = -1
end
end
end
end
local function OnMouseMove()
local whichPlayer = GetTriggerPlayer() ---@type player
local P = GetPlayerId(whichPlayer) + 1 ---@type integer
local mX = BlzGetTriggerPlayerMouseX() ---@type number
local mY = BlzGetTriggerPlayerMouseY() ---@type number
if not (mX == 0 and mY == 0) then
if interpCounter[P] ~= 0 then
x1[P] = x2[P]
y1[P] = y2[P]
end
x2[P] = mX
y2[P] = mY
MouseX[P] = x2[P]
MouseY[P] = y2[P]
interpCounter[P] = 0
end
end
local function Init()
local i = 0 ---@type integer
local trig = CreateTrigger() ---@type trigger
for i = 0, 23 do
if GetPlayerSlotState(Player(i)) == PLAYER_SLOT_STATE_PLAYING and GetPlayerController(Player(i)) == MAP_CONTROL_USER then
numRegisteredPlayers = numRegisteredPlayers + 1
registeredPlayers[numRegisteredPlayers] = i+1
interpCounter[i+1] = 0
x1[i+1] = 0
y1[i+1] = 0
x2[i+1] = 0
y2[i+1] = 0
TriggerRegisterPlayerEvent(trig, Player(i), EVENT_PLAYER_MOUSE_MOVE)
end
end
TimerStart(CreateTimer(), UPDATE_INTERVAL, true, Interpolate)
TriggerAddAction(trig, OnMouseMove)
end
OnInit.final(Init)
end
--[[ mapbounds.lua v1.0.0 |
Description:
Nestharus's WorldBounds ported into Lua, with few simple but useful
additions. Aside from providing map boundary data thru variables,
also provides premade functions for checking whether a coordinate
is inside map boundaries, getting a random coordinate within
map boundaries, and getting a bounded coordinate value.
Requirements:
- None
API:
Prefixes:
MapBounds
- Refers to initial playable map bounds
WorldBounds
- Refers to world bounds
Variables:
number: <Prefix>.centerX
number: <Prefix>.centerY
number: <Prefix>.minX
number: <Prefix>.minY
number: <Prefix>.maxX
number: <Prefix>.maxY
rect: <Prefix>.rect
region: <Prefix>.region
- These variables are intended to be READONLY
Functions:
function <Prefix>:getRandomX() -> number
function <Prefix>:getRandomY() -> number
- Returns a random coordinate inside the bounds
function <Prefix>:getBoundedX(number: x, number: margin=0.00) -> number
function <Prefix>:getBoundedY(number: y, number: margin=0.00) -> number
- Returns a coordinate that is inside the bounds
function <Prefix>:containsX(number: x) -> boolean
function <Prefix>:containsY(number: y) -> boolean
- Checks if the bounds contain the input coordinate
]]--
MapBounds = setmetatable({}, {})
WorldBounds = setmetatable({}, getmetatable(MapBounds))
do
local mt = getmetatable(MapBounds)
mt.__index = mt
function mt:getRandomX()
return GetRandomReal(self.minX, self.maxX)
end
function mt:getRandomY()
return GetRandomReal(self.minY, self.maxY)
end
local function GetBoundedValue(bounds, v, minV, maxV, margin)
margin = margin or 0.00
if v < (bounds[minV] + margin) then
return bounds[minV] + margin
elseif v > (bounds[maxV] - margin) then
return bounds[maxV] - margin
end
return v
end
function mt:getBoundedX(x, margin)
return GetBoundedValue(self, x, "minX", "maxX", margin)
end
function mt:getBoundedY(y, margin)
return GetBoundedValue(self, y, "minY", "maxY", margin)
end
function mt:containsX(x)
return self:getBoundedX(x) == x
end
function mt:containsY(y)
return self:getBoundedY(y) == y
end
local function InitData(bounds)
bounds.region = CreateRegion()
bounds.minX = GetRectMinX(bounds.rect)
bounds.minY = GetRectMinY(bounds.rect)
bounds.maxX = GetRectMaxX(bounds.rect)
bounds.maxY = GetRectMaxY(bounds.rect)
bounds.centerX = (bounds.minX + bounds.maxX) / 2.00
bounds.centerY = (bounds.minY + bounds.maxY) / 2.00
RegionAddRect(bounds.region, bounds.rect)
end
local oldInit = InitGlobals
function InitGlobals()
oldInit()
MapBounds.rect = bj_mapInitialPlayableArea
WorldBounds.rect = GetWorldBounds()
InitData(MapBounds)
InitData(WorldBounds)
end
end
do
local NumParticles = 0
local ParticleList = {}
local COLLISION_RANGE = 50
local MAX_PARTICLES = 2750
local PARTICLE_CLASS = nil
local PARTICLE_CLASS_RED = nil
--================================================================================================================
--Interaction functions
function Collision(A,B)
local comx = (A.x + B.x)/2
local comy = (A.y + B.y)/2
local comvx = (A.vx + B.vx)/2
local comvy = (A.vy + B.vy)/2
local dx = A.x - comx
local dy = A.y - comy
local dvx = A.vx - comvx
local dvy = A.vy - comvy
local angle = math.atan( dy , dx )
local cosAngle = math.cos(angle)
local sinAngle = math.sin(angle)
local dxPrime = cosAngle*dx + sinAngle*dy
local dyPrime = -sinAngle*dx + cosAngle*dy
local dvxPrime = cosAngle*dvx + sinAngle*dvy
local dvyPrime = -sinAngle*dvx + cosAngle*dvy
dxPrime = COLLISION_RANGE - dxPrime
dx = cosAngle*dxPrime - sinAngle*dyPrime
dy = sinAngle*dxPrime + cosAngle*dyPrime
dvxPrime = -dvxPrime
dvx = cosAngle*dvxPrime - sinAngle*dvyPrime
dvy = sinAngle*dvxPrime + cosAngle*dvyPrime
A.x = dx + comx
A.y = dy + comy
A.vx = dvx + comvx
A.vy = dvy + comvy
B.x = -dx + comx
B.y = -dy + comy
B.vx = -dvx + comvx
B.vy = -dvy + comvy
end
local sqrt = math.sqrt
function ParticleCollision(A,B)
local dx = A.x - B.x
local dy = A.y - B.y
local dist = sqrt(dx*dx + dy*dy)
if dist < COLLISION_RANGE then
Collision(A,B)
end
return (dist - 75)*0.0007
end
function ParticleCollisionRed(A,B)
local dx = A.x - B.x
local dy = A.y - B.y
local dist = sqrt(dx*dx + dy*dy)
if dist < COLLISION_RANGE then
Collision(A,B)
end
ALICE_PairVisualize(0.03)
return (dist - 75)*0.0007
end
--Because particles have a lower priority, theyΒ΄re passed as the second argument.
function ParticleLeftWallCollision(__,particle)
if particle.x < wallMinX then
particle.x = 2*wallMinX - particle.x
particle.vx = -particle.vx
end
return (particle.x - wallMinX)*0.001
end
function ParticleRightWallCollision(__,particle)
if particle.x > wallMaxX then
particle.x = 2*wallMaxX - particle.x
particle.vx = -particle.vx
end
return (wallMaxX - particle.x)*0.001
end
function ParticleBottomWallCollision(__,particle)
if particle.y < wallMinY then
particle.y = 2*wallMinY - particle.y
particle.vy = -particle.vy
end
return (particle.y - wallMinY)*0.001
end
function ParticleTopWallCollision(__,particle)
if particle.y > wallMaxY then
particle.y = 2*wallMaxY - particle.y
particle.vy = -particle.vy
end
return (wallMaxY - particle.y)*0.001
end
--================================================================================================================
--Particle Class
--================================================================================================================
---@class Particle
Particle ={
x = nil,
y = nil,
vx = nil,
vy = nil,
visual = nil,
--ALICE
identifier = nil,
interactionFunc = nil,
priority = nil
}
local particleMt = {__index = Particle}
---@return Particle
function Particle.create()
local new = {}
setmetatable(new, particleMt)
new.x = wallMinX + math.random()*(wallMaxX - wallMinX)
new.y = wallMinY + math.random()*(wallMaxY - wallMinY)
new.vx = (2*math.random() - 1)*10
new.vy = (2*math.random() - 1)*10
if NumParticles == 1 then
new.identifier = {"particle", "red"}
new.interactionFunc = {particle = ParticleCollisionRed}
new.priority = 1 --Overwrite particle interaction func.
new.visual = AddSpecialEffect("Abilities\\Weapons\\VengeanceMissile\\VengeanceMissile.mdl", new.x, new.y)
else
new.identifier = {"particle"}
new.interactionFunc = {particle = ParticleCollision}
new.visual = AddSpecialEffect("Abilities\\Weapons\\SpiritOfVengeanceMissile\\SpiritOfVengeanceMissile.mdl", new.x, new.y)
end
----------------------------------------------------------------------------------
ALICE_CreateFromClass(new)
----------------------------------------------------------------------------------
if ALICE_HasIdentifier(new, "red") then
ALICE_VisualizeCells(new)
end
return new
end
function Particle:destroy()
DestroyEffect(self.visual)
----------------------------------------------------------------------------------
ALICE_Destroy(self)
----------------------------------------------------------------------------------
end
local function Loop()
--This loop moves all the particles every 0.02 seconds. It is not executed with ALICE.
--Doing so is possible, but it would be slower because there would be a function call
--for every particle instead of one for all. How to move objects with ALICE is shown
--in the missile defense example.
for __, thisParticle in ipairs(ParticleList) do
thisParticle.x = thisParticle.x + thisParticle.vx
thisParticle.y = thisParticle.y + thisParticle.vy
BlzSetSpecialEffectPosition(thisParticle.visual, thisParticle.x, thisParticle.y, 690)
end
end
--================================================================================================================
local function CreateParticles()
NumParticles = NumParticles + 1
ParticleList[NumParticles] = Particle.create()
if NumParticles >= MAX_PARTICLES then
DestroyTimer(GetExpiredTimer())
end
end
function InitParticles()
wallMinX = MapBounds.minX + 100
wallMaxX = MapBounds.maxX - 100
wallMinY = MapBounds.minY + 100
wallMaxY = MapBounds.maxY - 100
print([[The red particle displays its interactions and the cells it is currently in.
Memory usage will continually increase. This is expected due to ALICE's first-contact creation of pairs and not due to memory leaks. Memory usage in any realistic situation will be much less.
StarSphere by ILH]])
CreateFogModifierRectBJ( true, Player(0), FOG_OF_WAR_VISIBLE, GetPlayableMapRect() )
SetSkyModel("StarSphere.mdx")
for x = -5600, 2600, 128 do
for y = -4100, 4100, 128 do
SetTerrainType(x, y, FourCC('Lgrd'), 0, 1, 1)
end
end
TimerStart(CreateTimer(), 0.0003, true, CreateParticles)
TimerStart(CreateTimer(), 0.02, true, Loop)
----------------------------------------------------------------------------------
--Because we donΒ΄t need a host for the walls, we pass nil.
ALICE_Create(nil, "wall", {particle = ParticleLeftWallCollision})
ALICE_Create(nil, "wall", {particle = ParticleRightWallCollision})
ALICE_Create(nil, "wall", {particle = ParticleBottomWallCollision})
ALICE_Create(nil, "wall", {particle = ParticleTopWallCollision})
----------------------------------------------------------------------------------
end
end
do
Trees = {} ---@type table[]
local TreeClass = nil
local MIN_ALPHA = 40 ---@type number
local BORDER_THICKNESS = 150 ---@type number
local MAX_SPEED = 522 ---@type number
local TREE_WIDTH = 475
local TREE_HEIGHT = 900
local TREE_Y_OFFSET = 375
local FIRE_X = -500
local FIRE_Y = 0
function FireDamage(whichFire, whichUnit)
local dist = ALICE_PairGetDistance()
local data = ALICE_PairLoadData()
if dist < 90 then
data.damageTaken = (data.damageTaken or 0) + 5
UnitDamageTarget(whichFire, whichUnit, data.damageTaken, false, false, ATTACK_TYPE_HERO, DAMAGE_TYPE_MAGIC, WEAPON_TYPE_WHOKNOWS)
DestroyEffect(AddSpecialEffectTarget("Abilities\\Spells\\Items\\AIfb\\AIfbSpecialArt.mdl", whichUnit, "origin"))
--Return a constant number so that the damage interval is always the same.
return 0.5
else
data.damageTaken = 0
return (dist - 90)/MAX_SPEED
end
end
--================================================================================
function TreeCheck(whichTree, whichHero)
local dx = GetUnitX(whichHero) - whichTree.x
local dy = GetUnitY(whichHero) - whichTree.y
local dist = math.sqrt(dx^2 + dy^2)
local angle = math.atan(dy, dx)
local ellipsisDist = math.sqrt((TREE_WIDTH/2*Cos(angle))^2 + (TREE_HEIGHT/2*Sin(angle))^2)
local borderDist = dist - ellipsisDist
--Uncomment to visualize all interactions.
--ALICE_PairVisualize(0.03)
if borderDist < 0 then
BlzSetSpecialEffectAlpha(whichTree.visual, MIN_ALPHA)
elseif borderDist < BORDER_THICKNESS then
BlzSetSpecialEffectAlpha(whichTree.visual, math.floor(255*borderDist/BORDER_THICKNESS + (1-borderDist/BORDER_THICKNESS)*MIN_ALPHA))
else
BlzSetSpecialEffectAlpha(whichTree.visual , 255)
end
return (borderDist - 100)/MAX_SPEED
end
--================================================================================
---@class Tree
Tree = {
x = nil,
y = nil,
visual = nil,
identifier = "tree",
interactionFunc = {hero = TreeCheck},
radius = TREE_HEIGHT/2 + BORDER_THICKNESS,
isStationary = true
}
local treeMt = {__index = Tree}
---@param x number
---@param y number
---@return Tree
function Tree.create(x, y)
local new = {} ---@class Tree
setmetatable(new, treeMt)
new.x = x
new.y = y + TREE_Y_OFFSET
new.visual = AddSpecialEffect("war3mapImported\\NewOak" .. math.random(0,2) .. ".mdx", x, y)
BlzSetSpecialEffectYaw(new.visual, 2*bj_PI*math.random())
BlzSetSpecialEffectScale(new.visual, 2 + 0.3*(math.random() + math.random() - 1))
BlzSetSpecialEffectTimeScale(new.visual, 0.5)
CreateDestructable(FourCC("YTpc"), x, y, 0, 1, 0)
--======================================================
ALICE_CreateFromClass(new)
--======================================================
return new
end
function InitTrees()
local treeList = {}
CreateFogModifierRectBJ( true, Player(0), FOG_OF_WAR_VISIBLE, GetPlayableMapRect() )
SetSkyModel("StarSphere.mdx")
for x = -5600, 2600, 128 do
for y = -4100, 4100, 128 do
SetTerrainType(x, y, FourCC('Adrt'), 0, 1, 1)
end
end
--======================================================
Fire = CreateUnit(Player(PLAYER_NEUTRAL_PASSIVE), FourCC('e000'), FIRE_X, FIRE_Y, 0)
ALICE_Create(Fire, "fire", {unit = FireDamage})
--======================================================
Hero = CreateUnit(Player(0), FourCC('Ewar'), 0, 0, 0)
SetCameraTargetController(Hero, 0, 0, false)
CreateFogModifierRectBJ( true, Player(0), FOG_OF_WAR_VISIBLE, GetPlayableMapRect() )
print([[Trees will become transparent if Warden moves below them. Fire will deal increasing damage. Lightning effects on interaction can be enabled in TreeCheck function.
Trees by Fingolfin]])
for __ = 1, 2000 do
local x = math.random(-5000, 2400)
local y = math.random(-4000, 4000)
local canPlaceTree = true
if math.sqrt((FIRE_X - x)^2 + (FIRE_Y - y)^2) > 700 then
for j = 1, #treeList do
local distSquared = (x - treeList[j].x)^2 + (y - treeList[j].y + TREE_Y_OFFSET)^2
if distSquared < 384*384 then
canPlaceTree = false
break
end
end
if canPlaceTree then
treeList[#treeList + 1] = Tree.create(x,y)
end
end
end
end
end
do
local hero = nil ---@type unit
local counter = 0
--================================================================================
function Explode(landmine, zombie)
local dist = ALICE_PairGetDistance()
if dist < 100 then
landmine:destroy()
end
return (dist - 100)/300
end
--================================================================================
---@class LandMine
LandMine = {
x = nil,
y = nil,
visual = nil,
owner = nil,
identifier = "landmine",
interactionFunc = Explode,
pairsWith = {"unit", PLAYER_FILTER_TYPE_ENEMY},
isStationary = true
}
local landmineMt = {__index = LandMine}
---@param x number
---@param y number
---@return LandMine
function LandMine.create(x,y)
local new = {}
setmetatable(new, landmineMt)
new.x = x
new.y = y
new.visual = AddSpecialEffect("units\\creeps\\GoblinLandMine\\GoblinLandMine", x, y)
new.owner = Player(0)
--================================================================================
ALICE_CreateFromClass(new)
--================================================================================
return new
end
function LandMine:destroy()
DestroyEffect(self.visual)
UnitDamagePoint(hero, 0, 250, self.x, self.y, 50, false, false, ATTACK_TYPE_NORMAL, DAMAGE_TYPE_MAGIC, WEAPON_TYPE_WHOKNOWS)
DestroyEffect(AddSpecialEffect("Objects\\Spawnmodels\\Other\\NeutralBuildingExplosion\\NeutralBuildingExplosion.mdl", self.x, self.y))
--================================================================================
ALICE_Destroy(self)
--================================================================================
end
function CreateLandMines()
for x = -4000, 0, 80 do
for y = -2000, 2000, 80 do
local landmine = LandMine.create(x,y)
end
end
end
function CreateZombies()
counter = counter + 1
local angle = 2*bj_PI*math.random()
local x = -2000 + 4000*math.cos(angle)
local y = 4000*math.sin(angle)
local zombie = CreateUnit(Player(1), FourCC("nzom"), x, y, Rad2Deg(angle) + 180)
IssueTargetOrder(zombie, "attack", hero)
if counter == 600 then
print("That's enough zombies! (the Blizzard AI is starting to bug out...)")
DestroyTimer(GetExpiredTimer())
end
end
function InitLandMines()
hero = CreateUnit(Player(0), FourCC("Hpal"), -2000, 0, 0)
SetHeroLevel(hero, 10, false)
for i = 1, 3 do
SelectHeroSkill(hero, FourCC("AHhb"))
SelectHeroSkill(hero, FourCC("AHds"))
SelectHeroSkill(hero, FourCC("AHad"))
end
SelectHeroSkill(hero, FourCC("AHre"))
local knight
for i = 1, 12 do
knight = CreateUnit(Player(0), FourCC("hkni"), -2000 + 500*math.cos(2*bj_PI*i/12), 500*math.sin(2*bj_PI*i/12), 360*i/12)
CAT_AddReviveCheck(knight)
end
CreateFogModifierRectBJ( true, Player(0), FOG_OF_WAR_VISIBLE, GetPlayableMapRect() )
CreateLandMines()
TimerStart(CreateTimer(), 0.08, true, CreateZombies)
end
end
do
Battlecruiser = nil ---@type unit
Carrier = nil ---@type unit
local BATTLECRUISER_X = -3975
local BLAST_LAUNCH_X = -3925
local MISSILE_LAUNCH_X = -2000
local PLASMA_BLAST_INTERVAL = 0
local DAMAGE_MULTIPLIER
--================================================================================
--These are the interaction functions. They execute the code you want to run when the objects interact.
function DestroyMissile(plasmaBlast, missile)
local dist = ALICE_PairGetDistance()
if dist < 50 then
missile:destroy() --These are not ALICE objects, but the user-defined objects they are attached to.
plasmaBlast:destroy()
end
return (dist - 100)*0.0005 --The return value determines the time until the next collision check.
end
function CarrierHit(plasmaBlast, carrier)
local dist = ALICE_PairGetDistance()
if dist < 75 then
plasmaBlast:destroy()
UnitDamageTarget(Battlecruiser, carrier, 4*DAMAGE_MULTIPLIER, false, false, ATTACK_TYPE_HERO, DAMAGE_TYPE_NORMAL, WEAPON_TYPE_WHOKNOWS)
end
return (dist - 100)*0.0005
end
function BattlecruiserHit(missile, battlecruiser)
local dist = ALICE_PairGetDistance()
if dist < 75 then
missile:destroy()
DestroyEffect(AddSpecialEffect("Abilities\\Weapons\\CannonTowerMissile\\CannonTowerMissile.mdl", missile.x, missile.y))
UnitDamageTarget(Carrier, battlecruiser, 20*DAMAGE_MULTIPLIER, false, false, ATTACK_TYPE_HERO, DAMAGE_TYPE_NORMAL, WEAPON_TYPE_WHOKNOWS)
end
return (dist - 100)*0.0025
end
--This could be done in a single function, but it would be 0.0629 percent less efficient kekw.
local function LeftWallCollision(__,plasmaBlast)
if plasmaBlast.x < MapBounds.minX then
plasmaBlast:destroy()
end
return (plasmaBlast.x - MapBounds.minX)*0.0005
end
local function RightWallCollision(__,plasmaBlast)
if plasmaBlast.x > MapBounds.maxX then
plasmaBlast:destroy()
end
return (MapBounds.maxX - plasmaBlast.x)*0.0005
end
local function BottomWallCollision(__,plasmaBlast)
if plasmaBlast.y < MapBounds.minY then
plasmaBlast:destroy()
end
return (plasmaBlast.y - MapBounds.minY)*0.0005
end
local function TopWallCollision(__,plasmaBlast)
if plasmaBlast.y > MapBounds.maxY then
plasmaBlast:destroy()
end
return (MapBounds.maxY - plasmaBlast.y)*0.0005
end
--================================================================================
--Missile Class
--================================================================================
function Cosh(x)
return (math.exp(x) + math.exp(-x))/2
end
function Sinh(x)
return (math.exp(x) - math.exp(-x))/2
end
function MoveMissile(missile)
missile.p = missile.p + 0.0035/missile.timeDilation
missile.x = MISSILE_LAUNCH_X + (BATTLECRUISER_X - MISSILE_LAUNCH_X)*(missile.p + 1)/2
missile.y = missile.sign*(BATTLECRUISER_X - MISSILE_LAUNCH_X)*(Cosh(missile.arc*missile.p) - Cosh(missile.arc))
BlzSetSpecialEffectPosition(missile.visual, missile.x, missile.y, 680)
end
function SetMissileParameters(missile)
--We don't need to update these variables every step. Thil will make moving the missiles
--more performant.
local dydx = 2*missile.arc*Sinh(missile.p)
missile.timeDilation = math.sqrt(1 + dydx^2)
BlzSetSpecialEffectYaw(missile.visual, -missile.sign*math.atan(dydx, -1))
return 0.25*(2 - missile.arc)
end
---@class Missile
Missile = {
x = nil,
y = nil,
p = nil,
arc = nil,
sign = nil,
visual = nil,
timeDilation = nil,
--ALICE
identifier = "missile",
interactionFunc = {battlecruiser = BattlecruiserHit, self = {MoveMissile, SetMissileParameters}},
cellCheckInterval = 0.25,
}
local missileMt = {__index = Missile}
function Missile.create()
local new = {}
setmetatable(new, missileMt)
new.arc = 1.5*math.random()
new.p = -1 + 0.1/(1+new.arc)
new.sign = 2*math.random(0,1) - 1
new.x = MISSILE_LAUNCH_X + (BATTLECRUISER_X - MISSILE_LAUNCH_X)*(new.p + 1)/2
new.y = new.sign*(BATTLECRUISER_X - MISSILE_LAUNCH_X)*(Cosh(new.arc*new.p) - Cosh(new.arc))
new.visual = AddSpecialEffect("RunicRocket", new.x, new.y)
BlzSetSpecialEffectScale(new.visual, 0.75)
new.timeDilation = 1
----------------------------------------------------------------------------------
ALICE_CreateFromClass(new)
----------------------------------------------------------------------------------
return new
end
function Missile:destroy()
DestroyEffect(self.visual)
----------------------------------------------------------------------------------
ALICE_Destroy(self)
----------------------------------------------------------------------------------
end
--================================================================================
--Plasma Blast Class
--================================================================================
function MovePlasmaBlast(blast)
blast.x = blast.x + blast.vx*ALICE_MIN_INTERVAL
blast.y = blast.y + blast.vy*ALICE_MIN_INTERVAL
BlzSetSpecialEffectPosition(blast.visual, blast.x, blast.y, 680)
end
---@class PlasmaBlast
PlasmaBlast = {
x = nil,
y = nil,
vx = nil,
vy = nil,
visual = nil,
--ALICE
identifier = {"plasmaBlast"},
interactionFunc = {carrier = CarrierHit, missile = DestroyMissile, self = MovePlasmaBlast},
cellCheckInterval = 0.06,
}
local blastMt = {__index = PlasmaBlast}
function PlasmaBlast.create()
local new = {}
setmetatable(new, blastMt)
new.x = BLAST_LAUNCH_X
new.y = 0
local angle = math.atan(InterpMouseY[1], InterpMouseX[1] - BLAST_LAUNCH_X)
new.vx = 1750*math.cos(angle)
new.vy = 1750*math.sin(angle)
new.arc = math.random()
new.visual = AddSpecialEffect("war3mapImported\\BeamMissile.mdx", new.x, new.y)
BlzSetSpecialEffectYaw(new.visual, angle)
BlzSetSpecialEffectScale(new.visual, 0.25)
----------------------------------------------------------------------------------
ALICE_CreateFromClass(new)
----------------------------------------------------------------------------------
return new
end
function PlasmaBlast:destroy()
DestroyEffect(self.visual)
----------------------------------------------------------------------------------
ALICE_Destroy(self)
----------------------------------------------------------------------------------
end
--================================================================================
local function CreateMissiles()
if UnitAlive(Carrier) and UnitAlive(Battlecruiser) then
Missile.create()
end
TimerStart(GetExpiredTimer(), 1.5*PLASMA_BLAST_INTERVAL*ALICE_TimeScale, false, CreateMissiles)
end
local function CreatePlasmaBlasts()
if UnitAlive(Carrier) and UnitAlive(Battlecruiser) then
PlasmaBlast.create()
end
TimerStart(GetExpiredTimer(), PLASMA_BLAST_INTERVAL*ALICE_TimeScale, false, CreatePlasmaBlasts)
end
function InitMissileDefense()
BlzHideOriginFrames(true)
BlzFrameSetVisible(BlzGetFrameByName("ConsoleUIBackdrop",0), false)
----------------------------------------------------------------------------------
ALICE_Create(nil, "wall", {plasmaBlast = LeftWallCollision})
ALICE_Create(nil, "wall", {plasmaBlast = RightWallCollision})
ALICE_Create(nil, "wall", {plasmaBlast = BottomWallCollision})
ALICE_Create(nil, "wall", {plasmaBlast = TopWallCollision})
----------------------------------------------------------------------------------
ALICE_SetEveryStep(MovePlasmaBlast)
ALICE_SetEveryStep(MoveMissile)
print([[Destroy the enemy ship before you yourself are destroyed to win!
StarSphere by ILH
Missiles by Vinz
Plasma Blast model by nGy
Battlecruiser / Carrier model ports by Daratrix]])
SetSkyModel("StarSphere.mdx")
for x = -5600, 2600, 128 do
for y = -4100, 4100, 128 do
SetTerrainType(x, y, FourCC('Lgrd'), 0, 1, 1)
end
end
Battlecruiser = CreateUnit(Player(0), FourCC('Hamg'), BATTLECRUISER_X - 25, 0, 0)
local trig = CreateTrigger()
TriggerRegisterUnitEvent(trig, Battlecruiser, EVENT_UNIT_DEATH)
TriggerAddAction(trig, function() ALICE_ForAllObjectsDo("missile", nil, function(missile) missile:destroy() end) end)
Carrier = CreateUnit(Player(PLAYER_NEUTRAL_AGGRESSIVE), FourCC('Hmkg'), MISSILE_LAUNCH_X, 0 , 180)
local trig = CreateTrigger()
TriggerRegisterUnitEvent(trig, Carrier, EVENT_UNIT_DEATH)
TriggerAddAction(trig, function() ALICE_ForAllObjectsDo("missile", nil, function(missile) missile:destroy() end) end)
local dummy = CreateUnit(Player(0), FourCC('ewsp'), (BATTLECRUISER_X + MISSILE_LAUNCH_X)/2, 0, 0)
SetCameraTargetController(dummy, 0, 0, false)
CreateFogModifierRectBJ( true, Player(0), FOG_OF_WAR_VISIBLE, GetPlayableMapRect() )
TimerStart(CreateTimer(), 1.5*PLASMA_BLAST_INTERVAL, false, CreateMissiles)
TimerStart(CreateTimer(), PLASMA_BLAST_INTERVAL, false, CreatePlasmaBlasts)
end
function MissileDefenseDialog()
local newDialog = DialogCreate()
local noButton = DialogAddButton(newDialog, "Normal", 0)
local yesButton = DialogAddButton(newDialog, "Yes", 0)
DialogSetMessage(newDialog, "How many missiles do you want?")
DialogDisplay(Player(0), newDialog, true)
local trig = CreateTrigger()
TriggerRegisterDialogButtonEvent(trig, noButton)
TriggerAddAction(trig, function() PLASMA_BLAST_INTERVAL = 0.05 DAMAGE_MULTIPLIER = 2.0 InitMissileDefense() end)
trig = CreateTrigger()
TriggerRegisterDialogButtonEvent(trig, yesButton)
TriggerAddAction(trig, function() PLASMA_BLAST_INTERVAL = 0.01 DAMAGE_MULTIPLIER = 0.6 InitMissileDefense() end)
end
end
do
local function LightningChainOnDestroy(__, __, data)
DestroyLightning(data.lightning)
end
function LightningChain(source, target)
local dist = ALICE_PairGetDistance()
local data = ALICE_PairLoadData()
if dist < 250 then
if ALICE_PairIsFirstContact() then
data.counter = 0
data.lightning = AddLightningEx( "AFOD", false, GetUnitX(source), GetUnitY(source), 680, GetUnitX(target), GetUnitY(target), 680)
ALICE_PairOnDestroy(LightningChainOnDestroy) --When a unit dies or when the pair forgets, destroy the lightning effect.
else
data.counter = data.counter - 1
MoveLightningEx(data.lightning, false, GetUnitX(source), GetUnitY(source), 680, GetUnitX(target), GetUnitY(target), 680)
end
if data.counter == 0 then --Need to move lightning every step, but damage only once every 0.5 seconds.
data.counter = 25
UnitDamageTarget(source, target, 5, false, false, ATTACK_TYPE_HERO, DAMAGE_TYPE_NORMAL, WEAPON_TYPE_WHOKNOWS)
DestroyEffect(AddSpecialEffectTarget("Abilities\\Spells\\Demon\\DemonBoltImpact\\DemonBoltImpact.mdl", target, "origin"))
end
return ALICE_MIN_INTERVAL --As long as the chain is active, we need a constant interaction interval.
else
ALICE_PairForget() --Purge data and call onDestroy function.
return (dist - 300)/500 --As long as there isn't a chain, this function is just doing a distance check that can have a variable interval. Or just return min interval. Who cares.
end
end
function InitLightningChains()
print("Move the peasants closer together to start the fun.")
for i = 1, 6 do
local peasant = CreateUnit(Player(0), FourCC("hpea"), 300*math.cos(i*2*bj_PI/6), 300*math.sin(i*2*bj_PI/6), 0)
--Create a second actor for the peasant on top of the one created by CAT. The peasant's two actors cannot pair. But both peasants' CAT actors will pair with the other's lightning chain actor, creating two chains.
ALICE_Create(peasant, "lightningChain", {unit = LightningChain}, {radius = 250, destroyOnDeath = true})
peasant = CreateUnit(Player(0), FourCC("hpea"), 600*math.cos((i+0.5)*2*bj_PI/6), 600*math.sin((i+0.5)*2*bj_PI/6), 0)
ALICE_Create(peasant, "lightningChain", {unit = LightningChain}, {radius = 250, destroyOnDeath = true})
peasant = CreateUnit(Player(0), FourCC("hpea"), 900*math.cos(i*2*bj_PI/6), 900*math.sin(i*2*bj_PI/6), 0)
ALICE_Create(peasant, "lightningChain", {unit = LightningChain}, {radius = 250, destroyOnDeath = true})
end
CreateFogModifierRectBJ( true, Player(0), FOG_OF_WAR_VISIBLE, GetPlayableMapRect() )
end
end
do
function HealingAuraAndVisualize(orb, unit)
ALICE_PairVisualize(ALICE_MIN_INTERVAL)
local data = ALICE_PairLoadData()
local dist = ALICE_PairGetDistance()
if dist < orb.radius and GetUnitState(unit, UNIT_STATE_LIFE) < BlzGetUnitMaxHP(unit) then
if ALICE_PairIsUnoccupied() then --Makes the effect non-stacking by blocking other pairs.
if ALICE_PairIsFirstContact() then
data.effect = AddSpecialEffectTarget("Abilities\\Spells\\Other\\ANrm\\ANrmTarget.mdl", unit, "origin")
ALICE_PairOnDestroy(function(__, __, data) DestroyEffect(data.effect) end)
end
SetUnitState(unit, UNIT_STATE_LIFE, GetUnitState(unit, UNIT_STATE_LIFE) + 0.5)
end
else
ALICE_PairForget()
end
return ALICE_MIN_INTERVAL
end
function InitCellVisualization()
print([[This example shows how cells work. The orb's radius has been set to a higher value during creation, allowing them to interact at a greater range. The interaction can happen only when cells overlap and you see the green lightning.
Once the footmen get into the healing range (which is smaller), they will get healed.
The healing auras of the two orbs do not stack.]])
ALICE_VisualizeAllCells()
for i = 1, 10 do
local footman = CreateUnit(Player(0), FourCC("hfoo"), math.random(-2000,2000), math.random(-1500,1500), 0)
SetUnitState(footman, UNIT_STATE_LIFE, 1)
TimerStart(CreateTimer(), 0.0, false, function() ALICE_VisualizeCells(footman) end) --Unfortunately, the actor created by CAT is not available immediately.
end
local orb = {
x = -800,
y = 0,
angle = -bj_PI,
visual = AddSpecialEffect("Doodads\\Cinematic\\EyeOfSargeras\\EyeOfSargeras.mdx", -800, 0),
--ALICE
identifier = "orb",
interactionFunc = {unit = HealingAuraAndVisualize},
radius = 450,
}
ALICE_CreateFromClass(orb)
ALICE_VisualizeCells(orb)
TimerStart(CreateTimer(), ALICE_MIN_INTERVAL, true, function()
orb.angle = ModuloReal(orb.angle - bj_PI/300, 2*bj_PI)
orb.x = 800*math.cos(orb.angle)
orb.y = 800*math.sin(orb.angle)
BlzSetSpecialEffectPosition(orb.visual, orb.x, orb.y, 600)
end)
local orb2 = {
x = 0,
y = -1200,
angle = -bj_PI,
visual = AddSpecialEffect("Doodads\\Cinematic\\EyeOfSargeras\\EyeOfSargeras.mdx", 0, -1200),
--ALICE
identifier = "orb",
interactionFunc = {unit = HealingAuraAndVisualize},
radius = 450,
}
ALICE_CreateFromClass(orb2)
ALICE_VisualizeCells(orb2)
CreateFogModifierRectBJ( true, Player(0), FOG_OF_WAR_VISIBLE, GetPlayableMapRect() )
end
end
do
local FIRE_MAX_RANGE = 225
--Fires have a chance to increase the strength of other nearby fires.
function Inflame(fireA, fireB)
local dist = ALICE_PairGetDistance()
if math.random() < 0.02*fireB.strength*(FIRE_MAX_RANGE - dist)/FIRE_MAX_RANGE then
fireA:increaseStrength()
end
if math.random() < 0.02*fireA.strength*(FIRE_MAX_RANGE - dist)/FIRE_MAX_RANGE then
fireB:increaseStrength()
end
return 1.0
end
ALICE_SetMaxRange(Inflame, FIRE_MAX_RANGE)
--Fires have a chance to spread to other trees. The chance increases with their strength.
function SpreadFire(fire, tree)
if ALICE_HasIdentifier(tree, "isBurning") then
return 1.0
end
local dist = ALICE_PairGetDistance()
local spreadChance = 0.1*(fire.strength - 1)*(FIRE_MAX_RANGE - dist)/FIRE_MAX_RANGE
if math.random() < spreadChance then
Fire.create(tree)
end
return 1.0
end
ALICE_SetMaxRange(SpreadFire, FIRE_MAX_RANGE)
--Fires damage their tree. They have a chance to grow in strength. When the tree dies, they will fizzle out.
function BurnDown(fire)
SetDestructableLife(fire.tree, GetDestructableLife(fire.tree) - 0.5*fire.strength)
if GetDestructableLife(fire.tree) <= 0 then
if math.random() < 0.25 then
fire:decreaseStrength()
end
else
if math.random() < 0.1 then
fire:increaseStrength()
end
end
return 1.0
end
function FireDamage(fire, unit)
local dist = ALICE_PairGetDistance()
if dist < FIRE_MAX_RANGE and fire.strength > 1 then
UnitDamageTarget(unit, unit, 25*(fire.strength - 1)*(FIRE_MAX_RANGE-dist)/FIRE_MAX_RANGE, false, false, ATTACK_TYPE_HERO, DAMAGE_TYPE_MAGIC, WEAPON_TYPE_WHOKNOWS)
DestroyEffect(AddSpecialEffectTarget("Abilities\\Spells\\Items\\AIfb\\AIfbSpecialArt.mdl", unit, "origin"))
end
return 1.0
end
--================================================================================
---@class Fire
Fire = {
tree = nil,
visual = nil,
strength = 1,
--ALICE
interactionFunc = {unit = FireDamage, tree = SpreadFire, fire = Inflame, self = BurnDown},
identifier = "fire",
radius = 225,
randomDelay = 1,
anchor = nil
}
local fireMt = {__index = Fire}
function Fire.create(tree)
local new = {}
setmetatable(new, fireMt)
new.tree = tree
new.anchor = tree
new.visual = AddSpecialEffect("Doodads\\Cinematic\\FireRockSmall\\FireRockSmall", GetDestructableX(tree), GetDestructableY(tree))
ALICE_CreateFromClass(new)
ALICE_AddIdentifier(tree, "isBurning")
end
function Fire:increaseStrength()
if self.strength == 3 then
return
end
self.strength = self.strength + 1
DestroyEffect(self.visual)
if self.strength == 2 then
self.visual = AddSpecialEffect("Doodads\\Cinematic\\TownBurningFireEmitter\\TownBurningFireEmitter.mdl", GetDestructableX(self.tree), GetDestructableY(self.tree))
elseif self.strength == 3 then
SetTerrainType(GetDestructableX(self.tree), GetDestructableY(self.tree), FourCC("Adrd"), -1, 1, 0)
self.visual = AddSpecialEffect("war3mapImported\\flames.mdx", GetDestructableX(self.tree), GetDestructableY(self.tree))
end
end
function Fire:decreaseStrength()
self.strength = self.strength - 1
if self.strength == 2 then
BlzSetSpecialEffectPosition(self.visual, WorldBounds.minX, WorldBounds.minY, 0)
DestroyEffect(self.visual)
self.visual = AddSpecialEffect("Doodads\\Cinematic\\TownBurningFireEmitter\\TownBurningFireEmitter.mdl", GetDestructableX(self.tree), GetDestructableY(self.tree))
elseif self.strength == 1 then
DestroyEffect(self.visual)
self.visual = AddSpecialEffect("Doodads\\Cinematic\\FireRockSmall\\FireRockSmall", GetDestructableX(self.tree), GetDestructableY(self.tree))
elseif self.strength == 0 then
DestroyEffect(self.visual)
ALICE_Destroy(self)
end
end
--================================================================================
function ExtinguishFire(wave, fire)
local dist = ALICE_PairGetDistance()
local angle = ALICE_PairGetAngle()
local waveAngle = math.atan(wave.vy, wave.vx)
if dist < wave.width*(0.75 - 0.25*math.cos(angle - waveAngle)) then --Makes the interaction zone wider and less long.
fire:decreaseStrength()
fire:decreaseStrength()
ALICE_PairDisable() --Only one interaction per fire per wave.
end
return (dist - 300)/600
end
function Propagate(wave)
wave.x = wave.x + wave.vx*ALICE_MIN_INTERVAL
wave.y = wave.y + wave.vy*ALICE_MIN_INTERVAL
wave.lifetime = wave.lifetime - ALICE_MIN_INTERVAL
wave.width = wave.width + 150*ALICE_MIN_INTERVAL
if wave.lifetime <= 0 then
DestroyEffect(wave.visual)
ALICE_Destroy(wave)
else
BlzSetSpecialEffectPosition(wave.visual, wave.x, wave.y, 670)
end
end
ALICE_SetEveryStep(Propagate)
function Splash(wave, tree)
local dist = ALICE_PairGetDistance()
local angle = ALICE_PairGetAngle()
local waveAngle = math.atan(wave.vy, wave.vx)
if dist < wave.width*(0.75 - 0.25*math.cos(angle - waveAngle)) then --Makes the interaction zone wider and less long.
DestroyEffect(AddSpecialEffect("Abilities\\Spells\\Other\\CrushingWave\\CrushingWaveDamage.mdl", GetDestructableX(tree), GetDestructableY(tree)))
ALICE_PairDisable() --Only one splash per tree per wave.
end
return (dist - 300)/600
end
function CrushingWave()
local caster = GetSpellAbilityUnit()
local angle = math.atan(GetSpellTargetY() - GetUnitY(caster), GetSpellTargetX() - GetUnitX(caster))
local x = GetUnitX(caster) + 100*math.cos(angle)
local y = GetUnitY(caster) + 100*math.sin(angle)
local wave = {
x = x,
y = y,
vx = 600*math.cos(angle),
vy = 600*math.sin(angle),
visual = AddSpecialEffect("Abilities\\Spells\\Other\\CrushingWave\\CrushingWaveMissile.mdl", x, y),
width = 150,
lifetime = 1.0,
--ALICE
identifier = "wave",
interactionFunc = {fire = ExtinguishFire, tree = Splash, self = Propagate},
}
BlzSetSpecialEffectYaw(wave.visual, angle)
ALICE_CreateFromClass(wave)
end
--================================================================================
local flamethrowerTimer = nil ---@type timer
function Flamethrower()
local u = GetOrderedUnit()
if GetIssuedOrderId() == OrderId("defend") then
TimerStart(flamethrowerTimer, 0.05, true, function()
local angle = Deg2Rad(GetUnitFacing(u))
local x = GetUnitX(u) + 45*math.cos(angle) + 15*math.cos(angle - bj_PI/2)
local y = GetUnitY(u) + 45*math.sin(angle) + 15*math.sin(angle - bj_PI/2)
local muzzle = AddSpecialEffect("war3mapImported\\Flamethrower.mdx", x, y)
BlzSetSpecialEffectYaw(muzzle, angle)
BlzSetSpecialEffectScale(muzzle, 1)
BlzSetSpecialEffectZ(muzzle, 690)
BlzSetSpecialEffectTimeScale(muzzle, 1)
TimerStart(CreateTimer(), 0.1, false, function() DestroyEffect(muzzle) DestroyTimer(GetExpiredTimer()) end)
local xFire = x + 150*math.cos(angle)
local yFire = y + 150*math.sin(angle)
ALICE_ForAllObjectsInRangeDo(xFire, yFire, 100, "tree", nil, function(object)
if not ALICE_HasIdentifier(object, "burning") and math.random() < 0.025 then
Fire.create(object)
end
end)
ALICE_ForAllObjectsInRangeDo(xFire, yFire, 100, "fire", nil, function(object)
if math.random() < 0.025 then
object:increaseStrength()
end
end)
ALICE_ForAllObjectsInRangeDo(xFire, yFire, 100, "unit", nil, function(object)
UnitDamageTarget(u, object, 1, false, false, ATTACK_TYPE_HERO, DAMAGE_TYPE_MAGIC, WEAPON_TYPE_WHOKNOWS)
end)
end)
else
PauseTimer(flamethrowerTimer)
end
end
--================================================================================
function InitWildfire()
print("Dwarf model by Maximal\nFlamethrower model by Vinz")
for x = WorldBounds.minX, WorldBounds.maxX, 128 do
for y = WorldBounds.minY, WorldBounds.maxY, 128 do
if (x + 2000)^2 + y^2 > 800^2 then
CreateDestructable(FourCC("ATtr"), x + math.random(-1,1)*64, y + math.random(-1,1)*64, 2*bj_PI*math.random(), 1, math.random(0,4))
end
end
end
local turtle = CreateUnit(Player(0), FourCC("utur"), -2000, 0, 0)
local trig = CreateTrigger()
TriggerAddAction(trig, CrushingWave)
TriggerRegisterUnitEvent(trig, turtle, EVENT_UNIT_SPELL_CAST)
TriggerAddCondition(trig, Condition(function() return true end))
local arsonist = CreateUnit(Player(0), FourCC("udwa"), -1700, 0, 0)
AddSpecialEffectTarget("war3mapImported\\Attachment_Flamethrower.mdx", arsonist, "hand")
local trig = CreateTrigger()
TriggerAddAction(trig, Flamethrower)
TriggerRegisterUnitEvent(trig, arsonist, EVENT_UNIT_ISSUED_ORDER)
TriggerAddCondition(trig, Condition(function() return GetIssuedOrderId() == OrderId("defend") or GetIssuedOrderId() == OrderId("undefend") end))
flamethrowerTimer = CreateTimer()
CreateFogModifierRectBJ( true, Player(0), FOG_OF_WAR_VISIBLE, GetPlayableMapRect() )
end
end
do
OnInit.final(function()
local newDialog = DialogCreate()
local particleButton = DialogAddButton(newDialog, "Collision Check Stress Test", 0)
local missileButton = DialogAddButton(newDialog, "Missile Defense Minigame", 0)
local wildfireButton = DialogAddButton(newDialog, "Spreading Wildfire", 0)
local mineButton = DialogAddButton(newDialog, "Land Mines and Zombies", 0)
local lightningButton = DialogAddButton(newDialog, "Lightning Chains", 0)
local cellVisualizationButton = DialogAddButton(newDialog, "Healing Aura and Cells", 0)
DialogSetMessage(newDialog, "Which test?")
DialogDisplay(Player(0), newDialog, true)
local trig = CreateTrigger()
TriggerRegisterDialogButtonEvent(trig, particleButton)
TriggerAddAction(trig, InitParticles)
trig = CreateTrigger()
TriggerRegisterDialogButtonEvent(trig, wildfireButton)
TriggerAddAction(trig, InitWildfire)
trig = CreateTrigger()
TriggerRegisterDialogButtonEvent(trig, mineButton)
TriggerAddAction(trig, InitLandMines)
trig = CreateTrigger()
TriggerRegisterDialogButtonEvent(trig, missileButton)
TriggerAddAction(trig, MissileDefenseDialog)
trig = CreateTrigger()
TriggerRegisterDialogButtonEvent(trig, lightningButton)
TriggerAddAction(trig, InitLightningChains)
trig = CreateTrigger()
TriggerRegisterDialogButtonEvent(trig, cellVisualizationButton)
TriggerAddAction(trig, InitCellVisualization)
end)
end