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): any
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
if type(libraryName) ~= 'string' then
return
end
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
if type(func) ~= 'function' then
return
end
--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)
if type(name) ~= 'string' then
print("|cffff5555ERROR in TotalInitialization: Library name must be of type string.")
return
end
if library.moduleValueMatrix[name] ~= nil then
print("|cffff5555ERROR in TotalInitialization: Library name " .. name .. " multiply declared.")
return
end
library.moduleValueMatrix[name] =
initialValue and { true, n = 1 }
end
function library:create(name, userFunc)
if type(userFunc) ~= 'function' then
print("|cffff5555ERROR in TotalInitialization: Initializer function must be of type function.")
return
end
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: ")
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.3 | --
-------------------------
--> https://www.hiveworkshop.com/threads/lua-debug-utils-incl-ingame-console.353720/
- 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 nil 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 nil 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, ...) -> ...
* - Help function for debugging another function (funcToExecute) that prints error messages on screen, if funcToExecute fails to execute.
* - DebugUtils will automatically apply this to all code run by your triggers and timers, so you rarely need to apply this manually (maybe on code run in the Lua root).
* - Calls funcToExecute with the specified parameters (...) in protected mode (which means that following code will continue to run even if funcToExecute 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.first()
* - Re-prints the very first error on screen that was thrown during map runtime and prevents further error messages and nil-warnings from being printed afterwards.
* - Useful, if a constant stream of error messages hinders you from reading any of them.
* - IngameConsole will still output error messages afterwards for code executed in it.
* 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 nil-globals |
* ----------------------------
* - DebugUtils will print warnings on screen, if you read any global variable in your code that contains nil.
* - This feature is meant to spot any case where you forgot to initialize a variable with a value or misspelled a variable or function name, such as calling CraeteUnit instead of CreateUnit.
* - By default, warnings are disabled for globals that have been initialized with any value (including nil). I.e. you can disable nil-warnings by explicitly setting MyGlobalVariable = nil. This behaviour can be changed in the settings.
*
* Debug.disableNilWarningsFor(variableName:string)
* - Manually disables nil-warnings for the specified global variable.
* - Variable must be inputted as string, e.g. Debug.disableNilWarningsFor("MyGlobalVariable").
*
* -----------------
* | 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(...).
*
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------]]
-- disable sumneko extension warnings for imported resource
---@diagnostic disable
----------------
--| Settings |--
----------------
Debug = {
--BEGIN OF SETTINGS--
settings = {
--Ingame Error Messages
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, ...)
, INCLUDE_DEBUGUTILS_INTO_TRACE = true ---Set to true to include lines from Debug Utils into the stack trace. Those show the source of error handling, which you might consider redundant.
, 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_ENUMFUNCS = true ---Set to true for automatic error handling on ForGroup, ForForce, EnumItemsInRect and EnumDestructablesInRect (applies Debug.try on every enum 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).
--Ingame Console and -exec
, ALLOW_INGAME_CODE_EXECUTION = true ---Set to true to enable IngameConsole and -exec command.
--Warnings for nil globals
, WARNING_FOR_NIL_GLOBALS = true ---Set to true to print warnings upon accessing nil-globals (i.e. globals containing no value).
, SHOW_TRACE_FOR_NIL_WARNINGS = false ---Set to true to include a stack trace into nil-warnings.
, EXCLUDE_BJ_GLOBALS_FROM_NIL_WARNINGS = false ---Set to true to exclude bj_ variables from nil-warnings.
, EXCLUDE_INITIALIZED_GLOBALS_FROM_NIL_WARNINGS = true ---Set to true to disable warnings for initialized globals, (i.e. nil globals that held a value at some point will be treated intentionally nilled and no longer prompt warnings).
--Print Caching
, USE_PRINT_CACHE = true ---Set to true to let print()-calls during loading screen be cached until the game starts.
, PRINT_DURATION = nil ---@type float Adjusts the duration in seconds that values printed by print() last on screen. Set to nil to use default duration (which depends on string length).
--Name Caching
, 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 = 4 ---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).
--Colors
, colors = {
error = 'ff5555' ---@type string Color to be applied to error messages
, log = '888888' ---@type string Color to be applied to logged messages through Debug.log().
, nilWarning = 'ffffff' ---@type string Color to be applied to nil-warnings.
}
}
--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.
, globalWarningExclusions = {} ---@type table<string,boolean> contains global variable names that should be excluded from warnings.
, printErrors_yn = true ---@type boolean Set to false to disable error messages. Used by Debug.first.
, firstError = nil ---@type string? contains the first error that was thrown. Used by Debug.first.
}
}
--localization
local settings, paramLog, nameCache, nameDepths, autoIndexedTables, nameCacheMirror, sourceMap, printCache, data = Debug.settings, Debug.data.paramLog, Debug.data.nameCache, Debug.data.nameDepths, Debug.data.autoIndexedTables, Debug.data.nameCacheMirror, Debug.data.sourceMap, Debug.data.printCache, Debug.data
--Write DebugUtils first line number to sourceMap:
---@diagnostic disable-next-line
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 d > 0 to instead return the line, where the d-th 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
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 _, currentFile, 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
currentFile = tracePiece:match("^.-:")
--Hide DebugUtils in the stack trace (except main reference), if settings.INCLUDE_DEBUGUTILS_INTO_TRACE is set to true.
if settings.INCLUDE_DEBUGUTILS_INTO_TRACE or (loopDepth == startDepth) or currentFile ~= "DebugUtils:" then
trace = trace .. separator .. ((currentFile == lastFile) and tracePiece:match(":\x25d+"):sub(2,-1) or tracePiece:match("^.-:\x25d+"))
lastFile, lastTracePiece, separator = currentFile, tracePiece, " <- "
end
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 must default to 4 for this case
errorMsg = convertToLocalErrorMsg(errorMsg)
--Original error message and stack trace.
local toPrint = "|cff" .. settings.colors.error .. "ERROR at " .. errorMsg .. "|r"
if settings.SHOW_TRACE_ON_ERROR then
toPrint = toPrint .. "\n|cff" .. settings.colors.error .. "Traceback (most recent call first):|r\n|cff" .. settings.colors.error .. getStackTrace(startDepth,200) .. "|r"
end
--Also print entries from param log, if there are any.
for location, loggedParams in pairs(paramLog) do
toPrint = toPrint .. "\n|cff" .. settings.colors.log .. "Logged at " .. convertToLocalErrorMsg(location) .. loggedParams .. "|r"
paramLog[location] = nil
end
data.firstError = data.firstError or toPrint
if data.printErrors_yn then --don't print error, if execution of Debug.firstError() has disabled it.
print(toPrint)
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
---@diagnostic disable-next-line lowercase-global
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
---Re-prints the very first error that occured during map runtime and prevents any further error messages and nil-warnings from being printed afterwards (for the rest of the game).
---Use this, if a constant stream of error messages hinders you from reading any of them.
---IngameConsole will still output error messages afterwards for code executed in it.
function Debug.first()
data.printErrors_yn = false
print(data.firstError)
end
----------------------------------
--| Undeclared Global Warnings |--
----------------------------------
--Utility function here. _G metatable behaviour is defined in Gamestart section further below.
local globalWarningExclusions = Debug.data.globalWarningExclusions
---Disables nil-warnings for the specified variable.
---@param variableName string
function Debug.disableNilWarningsFor(variableName)
globalWarningExclusions[variableName] = true
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 nil-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
---@diagnostic disable-next-line: assign-type-mismatch
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, Filter and Enum 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_ENUMFUNCS then
local originalForGroup = ForGroup
ForGroup = function(whichGroup, callback)
originalForGroup(whichGroup, getTryWrapper(callback))
end
local originalForForce = ForForce
ForForce = function(whichForce, callback)
originalForForce(whichForce, getTryWrapper(callback))
end
local originalEnumItemsInRect = EnumItemsInRect
EnumItemsInRect = function(r, filter, actionfunc)
originalEnumItemsInRect(r, filter, getTryWrapper(actionfunc))
end
local originalEnumDestructablesInRect = EnumDestructablesInRect
EnumDestructablesInRect = function(r, filter, actionFunc)
originalEnumDestructablesInRect(r, filter, getTryWrapper(actionFunc))
end
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(...) ---@diagnostic disable-next-line: param-type-mismatch
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
---@diagnostic disable-next-line
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_NIL_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.
--Don't show warning, if the variable name has been actively excluded or if it's a bj_ variable (and those are excluded).
if data.printErrors_yn and (not globalWarningExclusions[k]) and ((not settings.EXCLUDE_BJ_GLOBALS_FROM_NIL_WARNINGS) or string.sub(tostring(k),1,3) ~= 'bj_') then --prevents intentionally nilled bj-variables from triggering the check within Blizzard.j-functions, like bj_cineFadeFinishTimer.
print("|cff" .. settings.colors.nilWarning .. "Trying to read nil global at " .. getStackTrace(4,4) .. ": " .. tostring(k) .. "|r"
.. (settings.SHOW_TRACE_FOR_NIL_WARNINGS and "\n|cff" .. settings.colors.nilWarning .. "Traceback (most recent call first):|r\n|cff" .. settings.colors.nilWarning .. getStackTrace(4,200) .. "|r" or ""))
end
if existingIndex then
if isTable_yn then
return existingIndex[k]
end
return existingIndex(t,k)
end
return rawget(t,k)
end
if settings.EXCLUDE_INITIALIZED_GLOBALS_FROM_NIL_WARNINGS then
local existingNewIndex = getmetatable(_G).__newindex
local isTable_yn = (type(existingNewIndex) == 'table')
getmetatable(_G).__newindex = function(t,k,v)
--First, exclude the initialized global from future warnings
globalWarningExclusions[k] = true
--Second, execute existing newindex, if there is one in place.
if existingNewIndex then
if isTable_yn then
existingNewIndex[k] = v
else
existingNewIndex(t,k,v)
end
else
rawset(t,k,v)
end
end
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 ---@diagnostic disable-next-line: cast-local-type
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()
if Debug and Debug.beginFile then Debug.beginFile("IngameConsole") end
--[[
--------------------------
----| 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 .. '\n'
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
--[[
used by Ingame Console to determine multiboard size
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
if Debug and Debug.endFile then Debug.endFile() end
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
if Debug then Debug.beginFile "PrecomputedHeightMap" end ---@diagnostic disable: param-type-mismatch
do LIBRARY_PrecomputedHeightMap = true
--[[
===============================================================================================================================================================
Precomputed Height Map
by Antares
===============================================================================================================================================================
GetTerrainZ(x, y) Replaces GetLocZ(x, y).
GetUnitZ(whichUnit) Replaces BlzGetUnitZ(whichUnit).
GetUnitCoordinates(whichUnit) Returns x, y, and z-coordinates of a unit.
GetCliffAdjustedZ(x, y) Returns a value in tiles neighboring cliffs that is more aligned with the visual effect. Requires STORE_CLIFF_DATA.
===============================================================================================================================================================
Computes the terrain height of your map on map initialization for later use. To get the terrain height at any location, use GetTerrainZ, replacing GetLocZ:
function GetLocZ(x, y)
MoveLocation(moveableLoc, x, y)
return GetLocationZ(moveableLoc)
end
GetTerrainZ is less prone to cause desyncs and is approximately twice as fast.
You have the option to save the height map to a file on map initialization. You can then reimport the data into the map to load the height map from that data.
This will make the use of Z-coordinates completely safe, as all clients are guaranteed to use exactly the same data. It is recommended to do this once for the
release version of your map.
To do this, set the flag for WRITE_HEIGHT_MAP and launch your map. The terrain height map will be generated on map initialization and saved to a file in your
Warcraft III\CustomMapData\ folder. Open that file in a text editor, then remove all occurances of
call Preload( "
" )
with find and replace (including the quotation marks and tab space). Then, remove
function PreloadFiles takes nothing returns nothing
call PreloadStart()
at the beginning of the file and
call PreloadEnd( 0.0 )
endfunction
at the end of the file. Finally, remove all line breaks by removing \n and \r. The result should be something like
HeightMapCode = "|pk44mM-b+b1-dr|krjdhWcy1aa1|eWcyaa"
except much longer.
Copy the entire string and paste it anywhere into the Lua root in your map, for example into the Config section of this library. Now, every time your map is
launched, the height map will be read from the string instead of being generated, making it guaranteed to be synced.
To check if the code has been generated correctly, launch your map one more time in single-player. The height map generated from the code will be checked against
one generated in the traditional way.
--=============================================================================================================================================================
Config
--=============================================================================================================================================================
]]
local SUBFOLDER = "PrecomputedHeightMap"
local STORE_CLIFF_DATA = true
local WRITE_HEIGHT_MAP = false
local VALIDATE_HEIGHT_MAP = true
local VISUALIZE_HEIGHT_MAP = false
--=============================================================================================================================================================
local heightMap = {} ---@type table[]
local terrainHasCliffs = {} ---@type table[]
local moveableLoc = nil ---@type location
local MINIMUM_Z = -256 ---@type number
local worldMinX
local worldMinY
local worldMaxX
local worldMaxY
local iMax
local jMax
local chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
local NUMBER_OF_CHARS = 52
local function GetLocZ(x, y)
MoveLocation(moveableLoc, x, y)
return GetLocationZ(moveableLoc)
end
GetTerrainZ = GetLocZ
---@param whichUnit unit
---@return number
function GetUnitZ(whichUnit)
return GetTerrainZ(GetUnitX(whichUnit), GetUnitY(whichUnit)) + GetUnitFlyHeight(whichUnit)
end
---@param whichUnit unit
---@return number, number, number
function GetUnitCoordinates(whichUnit)
local x = GetUnitX(whichUnit)
local y = GetUnitY(whichUnit)
return x, y, GetTerrainZ(x, y) + GetUnitFlyHeight(whichUnit)
end
local function CreateHeightMap()
local xMin = (worldMinX // 128)*128
local yMin = (worldMinY // 128)*128
local xMax = (worldMaxX // 128)*128 + 1
local yMax = (worldMaxY // 128)*128 + 1
local x = xMin
local y
local i = 1
local j
while x <= xMax do
heightMap[i] = {}
terrainHasCliffs[i] = {}
y = yMin
j = 1
while y <= yMax do
heightMap[i][j] = GetLocZ(x,y)
if VISUALIZE_HEIGHT_MAP then
BlzSetSpecialEffectZ(AddSpecialEffect("Doodads\\Cinematic\\GlowingRunes\\GlowingRunes0", x, y), heightMap[i][j] - 40)
end
if STORE_CLIFF_DATA then
local level1 = GetTerrainCliffLevel(x, y)
local level2 = GetTerrainCliffLevel(x, y + 128)
local level3 = GetTerrainCliffLevel(x + 128, y)
local level4 = GetTerrainCliffLevel(x, y + 128)
if level1 ~= level2 or level1 ~= level3 or level1 ~= level4 then
terrainHasCliffs[i][j] = true
end
end
j = j + 1
y = y + 128
end
i = i + 1
x = x + 128
end
iMax = i - 2
jMax = j - 2
---@param x number
---@param y number
---@return number
GetTerrainZ = function(x, y)
local rx = (x - worldMinX)/128 + 1
local ry = (y - worldMinY)/128 + 1
local i = rx // 1
local j = ry // 1
rx = rx - i
ry = ry - j
if i < 1 then
i = 1
rx = 0
elseif i > iMax then
i = iMax
rx = 1
end
if j < 1 then
j = 1
ry = 0
elseif j > jMax then
j = jMax
ry = 1
end
if rx + ry > 1 then --In top-right triangle
return (rx + ry - 1)*heightMap[i+1][j+1] + ((1 - rx)*heightMap[i][j+1] + (1 - ry)*heightMap[i+1][j])
else
return (1 - rx - ry)*heightMap[i][j] + (rx*heightMap[i+1][j] + ry*heightMap[i][j+1])
end
end
if not STORE_CLIFF_DATA then
GetCliffAdjustedZ = GetTerrainZ
end
end
---@param x number
---@param y number
---@return number
function GetCliffAdjustedZ(x, y)
local rx = (x - worldMinX)/128 + 1
local ry = (y - worldMinY)/128 + 1
local i = rx // 1
local j = ry // 1
rx = rx - i
ry = ry - j
if i < 1 then
i = 1
rx = 0
elseif i > iMax then
i = iMax
rx = 1
end
if j < 1 then
j = 1
ry = 0
elseif j > jMax then
j = jMax
ry = 1
end
if terrainHasCliffs[i][j] then
if rx < 0.5 then
if ry < 0.5 then
return heightMap[i][j]
else
return heightMap[i][j+1]
end
elseif ry < 0.5 then
return heightMap[i+1][j]
else
return heightMap[i+1][j+1]
end
else
if rx + ry > 1 then --In top-right triangle
return (rx + ry - 1)*heightMap[i+1][j+1] + ((1 - rx)*heightMap[i][j+1] + (1 - ry)*heightMap[i+1][j])
else
return (1 - rx - ry)*heightMap[i][j] + (rx*heightMap[i+1][j] + ry*heightMap[i][j+1])
end
end
end
local function ValidateHeightMap()
local xMin = (worldMinX // 128)*128
local yMin = (worldMinY // 128)*128
local xMax = (worldMaxX // 128)*128 + 1
local yMax = (worldMaxY // 128)*128 + 1
local numOutdated = 0
local x = xMin
local y
local i = 1
local j
while x <= xMax do
y = yMin
j = 1
while y <= yMax do
if heightMap[i][j] then
if VISUALIZE_HEIGHT_MAP then
BlzSetSpecialEffectZ(AddSpecialEffect("Doodads\\Cinematic\\GlowingRunes\\GlowingRunes0", x, y), heightMap[i][j] - 40)
end
if bj_isSinglePlayer and math.abs(heightMap[i][j] - GetLocZ(x, y)) > 1 then
numOutdated = numOutdated + 1
end
else
print("Height Map nil at x = " .. x .. ", y = " .. y)
end
j = j + 1
y = y + 128
end
i = i + 1
x = x + 128
end
if numOutdated > 0 then
print("|cffff0000Warning:|r Height Map is outdated at " .. numOutdated .. " locations...")
end
end
local function ReadHeightMap()
local charPos = 0
local numRepetitions = 0
local charValues = {}
for i = 1, string.len(chars) do
charValues[string.sub(chars, i, i)] = i - 1
end
local firstChar = nil
local PLUS = 0
local MINUS = 1
local ABS = 2
local segmentType = ABS
for i = 1, #heightMap do
for j = 1, #heightMap[i] do
if numRepetitions > 0 then
heightMap[i][j] = heightMap[i][j-1]
numRepetitions = numRepetitions - 1
else
local valueDetermined = false
while not valueDetermined do
charPos = charPos + 1
local char = string.sub(HeightMapCode, charPos, charPos)
if char == "+" then
segmentType = PLUS
charPos = charPos + 1
char = string.sub(HeightMapCode, charPos, charPos)
elseif char == "-" then
segmentType = MINUS
charPos = charPos + 1
char = string.sub(HeightMapCode, charPos, charPos)
elseif char == "|" then
segmentType = ABS
charPos = charPos + 1
char = string.sub(HeightMapCode, charPos, charPos)
end
if tonumber(char) then
local k = 0
while tonumber(string.sub(HeightMapCode, charPos + k + 1, charPos + k + 1)) do
k = k + 1
end
numRepetitions = tonumber(string.sub(HeightMapCode, charPos, charPos + k)) - 1
charPos = charPos + k
valueDetermined = true
heightMap[i][j] = heightMap[i][j-1]
else
if segmentType == PLUS then
heightMap[i][j] = heightMap[i][j-1] + charValues[char]
valueDetermined = true
elseif segmentType == MINUS then
heightMap[i][j] = heightMap[i][j-1] - charValues[char]
valueDetermined = true
elseif firstChar then
if charValues[firstChar] and charValues[char] then
heightMap[i][j] = charValues[firstChar]*NUMBER_OF_CHARS + charValues[char] + MINIMUM_Z
else
heightMap[i][j] = 0
end
firstChar = nil
valueDetermined = true
else
firstChar = char
end
end
end
end
end
end
HeightMapCode = nil
end
local function WriteHeightMap(subfolder)
PreloadGenClear()
PreloadGenStart()
local numRepetitions = 0
local firstChar
local secondChar
local stringLength = 0
local lastValue = 0
local PLUS = 0
local MINUS = 1
local ABS = 2
local segmentType = ABS
local preloadString = {'HeightMapCode = "'}
for i = 1, #heightMap do
for j = 1, #heightMap[i] do
if j > 1 then
local diff = (heightMap[i][j] - lastValue)//1
if diff == 0 then
numRepetitions = numRepetitions + 1
else
if numRepetitions > 0 then
table.insert(preloadString, numRepetitions)
end
numRepetitions = 0
if diff > 0 and diff < NUMBER_OF_CHARS then
if segmentType ~= PLUS then
segmentType = PLUS
table.insert(preloadString, "+")
end
elseif diff < 0 and diff > -NUMBER_OF_CHARS then
if segmentType ~= MINUS then
segmentType = MINUS
table.insert(preloadString, "-")
end
else
if segmentType ~= ABS then
segmentType = ABS
table.insert(preloadString, "|")
end
end
if segmentType == ABS then
firstChar = (heightMap[i][j] - MINIMUM_Z) // NUMBER_OF_CHARS + 1
secondChar = heightMap[i][j]//1 - MINIMUM_Z - (heightMap[i][j]//1 - MINIMUM_Z)//NUMBER_OF_CHARS*NUMBER_OF_CHARS + 1
table.insert(preloadString, string.sub(chars, firstChar, firstChar) .. string.sub(chars, secondChar, secondChar))
elseif segmentType == PLUS then
firstChar = diff//1 + 1
table.insert(preloadString, string.sub(chars, firstChar, firstChar))
elseif segmentType == MINUS then
firstChar = -diff//1 + 1
table.insert(preloadString, string.sub(chars, firstChar, firstChar))
end
end
else
if numRepetitions > 0 then
table.insert(preloadString, numRepetitions)
end
segmentType = ABS
table.insert(preloadString, "|")
numRepetitions = 0
firstChar = (heightMap[i][j] - MINIMUM_Z) // NUMBER_OF_CHARS + 1
secondChar = heightMap[i][j]//1 - MINIMUM_Z - (heightMap[i][j]//1 - MINIMUM_Z)//NUMBER_OF_CHARS*NUMBER_OF_CHARS + 1
table.insert(preloadString, string.sub(chars, firstChar, firstChar) .. string.sub(chars, secondChar, secondChar))
end
lastValue = heightMap[i][j]//1
stringLength = stringLength + 1
if stringLength == 100 then
Preload(table.concat(preloadString))
stringLength = 0
for k, __ in ipairs(preloadString) do
preloadString[k] = nil
end
end
end
end
if numRepetitions > 0 then
table.insert(preloadString, numRepetitions)
end
table.insert(preloadString, '"')
Preload(table.concat(preloadString))
PreloadGenEnd(subfolder .. "\\heightMap.txt")
print("Written Height Map to CustomMapData\\" .. subfolder .. "\\heightMap.txt")
end
local function InitHeightMap()
local xMin = (worldMinX // 128)*128
local yMin = (worldMinY // 128)*128
local xMax = (worldMaxX // 128)*128 + 1
local yMax = (worldMaxY // 128)*128 + 1
local x = xMin
local y
local i = 1
local j
while x <= xMax do
heightMap[i] = {}
terrainHasCliffs[i] = {}
y = yMin
j = 1
while y <= yMax do
heightMap[i][j] = 0
if STORE_CLIFF_DATA then
local level1 = GetTerrainCliffLevel(x, y)
local level2 = GetTerrainCliffLevel(x, y + 128)
local level3 = GetTerrainCliffLevel(x + 128, y)
local level4 = GetTerrainCliffLevel(x, y + 128)
if level1 ~= level2 or level1 ~= level3 or level1 ~= level4 then
terrainHasCliffs[i][j] = true
end
end
j = j + 1
y = y + 128
end
i = i + 1
x = x + 128
end
end
OnInit.global("PrecomputedHeightMap", function()
local worldBounds = GetWorldBounds()
worldMinX = GetRectMinX(worldBounds)
worldMinY = GetRectMinY(worldBounds)
worldMaxX = GetRectMaxX(worldBounds)
worldMaxY = GetRectMaxY(worldBounds)
moveableLoc = Location(0, 0)
if HeightMapCode then
InitHeightMap()
ReadHeightMap()
if VALIDATE_HEIGHT_MAP then
ValidateHeightMap()
end
else
CreateHeightMap()
if WRITE_HEIGHT_MAP then
WriteHeightMap(SUBFOLDER)
end
end
end)
end
if Debug then Debug.beginFile("HandleType") end
do
--[[
===============================================================================================================================================================
Handle Type
by Antares
===============================================================================================================================================================
Determine the type of a Wacraft 3 object (handle). The result is stored in a table on the first execution to increase performance.
HandleType[whichHandle] -> string Returns an empty string if variable is not a handle.
IsHandle[whichHandle] -> boolean
IsWidget[whichHandle] -> boolean
IsUnit[whichHandle] -> boolean
These can also be called as a function, which has a nil-check, but is slower than the table-lookup.
===============================================================================================================================================================
]]
local widgetTypes = {
unit = true,
destructable = true,
item = true
}
HandleType = setmetatable({}, {
__mode = "k",
__index = function(self, key)
if type(key) == "userdata" then
local str = tostring(key)
self[key] = str:sub(1, (str:find(":", nil, true) or 0) - 1)
return self[key]
else
self[key] = ""
return ""
end
end,
__call = function(self, key)
if key then
return self[key]
else
return ""
end
end
})
IsHandle = setmetatable({}, {
__mode = "k",
__index = function(self, key)
self[key] = HandleType[key] ~= ""
return self[key]
end,
__call = function(self, key)
if key then
return self[key]
else
return false
end
end
})
IsWidget = setmetatable({}, {
__mode = "k",
__index = function(self, key)
self[key] = widgetTypes[HandleType[key]] == true
return self[key]
end,
__call = function(self, key)
if key then
return self[key]
else
return false
end
end
})
IsUnit = setmetatable({}, {
__mode = "k",
__index = function(self, key)
self[key] = HandleType[key] == "unit"
return self[key]
end,
__call = function(self, key)
if key then
return self[key]
else
return false
end
end
})
end
if Debug then Debug.endFile() end
--[[
====================================================================================================================================================================
B A S I C A P I
====================================================================================================================================================================
• All object functions use keyword as an optional parameter. This parameter is only needed if
you create multiple actors for one host. It searches for the actor that has that keyword in
its identifier.
• All functions starting with ALICE_Pair are only accessible within user-defined functions
called by ALICE.
• All functions starting with ALICE_Func can be called from the Lua root, as long as ALICE is
above.
• All functions other than debug functions are async-safe as long as the code executed with
them is also async-safe.
-----CORE API------
ALICE_Create(host, identifier, interactions, flags) Create an actor for the object host and add it to the cycle. If the host is a table and is
provided as the only input argument, all other arguments will be retrieved directly from
that table.
ALICE_Destroy(whichObject) Destroy the actor of the specified object.
ALICE_Kill(whichObject) Calls the appropriate function to destroy the object, then destroys all actors attached to
it. If the object is a table, the object:destroy() method will be called. If no destroy
function exists, it will try to destroy the table's visual, which can be an effect, a unit,
or an image.
-----MATH API-----
ALICE_PairGetDistance2D() 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_PairGetAngle2D() 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_PairGetCoordinates2D() Returns the coordinates of the objects in the pair currently being evaluated in the order
x1, y1, x2, y2.
ALICE_PairGetCoordinates3D() Returns the coordinates of the objects in the pair currently being evaluated in the order
x1, y1, z1, x2, y2, z2.
ALICE_GetCoordinates2D(whichObject) Returns the coordinates x, y of an object.
ALICE_GetCoordinates3D(whichObject) Returns the coordinates x, y, z of an object.
• Enum functions return a table with all objects that have the specified identifier. Identifier
can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or
MATCHING_TYPE_ALL. Optional condition function to further filter out objects with additional
arguments passed to enum function being passed to condition function. For example, this will
return all flying units that are owned by red:
function IsOwnedByPlayer(object, whichPlayer)
return GetOwningPlayer(object) == whichPlayer
end
ALICE_EnumObjects({"unit", "flying", MATCHING_TYPE_ALL}, IsOwnedByPlayer, Player(0))
-----ENUM API-----
ALICE_EnumObjects(identifier, condition)
ALICE_EnumObjectsInRange(x, y, range, identifier, condition)
ALICE_EnumObjectsInRect(minx, miny, maxx, maxy, identifier, condition)
ALICE_EnumObjectsInLineSegment(x1, y1, x2, y2, halfWidth, condition)
ALICE_ForAllObjectsDo(action, identifier, condition)
ALICE_ForAllObjectsInRangeDo(action, x, y, range, identifier, condition)
ALICE_ForAllObjectsInRectDo(action, minx, miny, maxx, maxy, identifier, condition)
ALICE_ForAllObjectsInLineSegmentDo(action, x1, y1, x2, y2, halfWidth, condition)
ALICE_GetClosestObject(x, y, identifier, cutOffDistance, condition)
• The Callback API allows for convenient creation of delayed callbacks of any kind, with the
added benefit that callbacks will be delayed if ALICE is paused or slowed down. This allows
the pausing of the entire game for debugging or other purposes.
-----CALLBACK API-----
ALICE_CallDelayed(callback, delay) Invokes the callback function after the specified delay, passing additional arguments into
the callback function.
ALICE_PairCallDelayed(callback, delay) Invokes the callback function after the specified delay, passing the hosts of the current
pair as arguments. A third parameter is passed into the callback, specifying whether you
have access to the ALICE_Pair functions. You will not if the current pair has been
destroyed after the callback was queued up.
ALICE_CallPeriodic(callback, delay) Periodically invokes the callback function. Optional delay parameter to delay the first
execution. Additional arguments are passed into the callback function. The return value of
the callback function specifies the interval until next execution.
ALICE_CallRepeated(callback, howOften, delay) Periodically invokes the callback function up to howOften times. Optional delay parameter to
delay the first execution. The arguments passed into the callback function are the current
iteration, followed by any additional arguments. The return value of the callback function
specifies the interval until next execution.
ALICE_DisablePeriodic(callback) Disables a periodic callback returned by ALICE_CallPeriodic or ALICE_CallRepeated. If called
from within the callback function itself, the parameter can be omitted.
====================================================================================================================================================================
A D V A N C E D A P I
====================================================================================================================================================================
• 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. The
actor tooltips require CustomTooltip.fdf and CustomTooltip.toc
-----DEBUG API------
ALICE_RecognizeFields(whichFields) Add fields that ALICE recognizes on actor creation for UNRECOGNIZED_FIELD_WARNINGS.
ALICE_Debug() Enable or disable debug mode.
ALICE_ListGlobals() List all global actors.
ALICE_Select(whichActor) Select the specified actor. Pass integer to select by unique number. Requires debug
mode.
ALICE_PairIsSelected() Returns true if one of the actors in the current pair is selected.
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 parameter.
ALICE_Halt(pauseGame) Halt the entire cycle. Optional pauseGame parameter to pause all units on the map.
ALICE_Resume() Resume the entire cycle.
ALICE_Statistics() Prints out statistics showing which functions are occupying which percentage of the
calculations.
ALICE_Benchmark() Continuously prints the cycle evaluation time and the number of actors, pair interactions,
and cell checks until disabled.
ALICE_TrackVariables(whichVar) Prints the values of _G.whichVar[host], if _G.whichVar exists, as well as host.whichVar,
if the host is a table, in the actor tooltips in debug mode. You can list multiple
variables.
ALICE_GetPairState(objectA, objectB) Attempts to find the pair of the specified objects and prints the state of that pair.
Pass integers to access actors by unique numbers. Possible return values are "active",
"paused", "outofrange", "disabled", and "uninitialized".
ALICE_VisualizeAllCells() Create lightning effects around all cells.
ALICE_VisualizeAllActors() Creates arrows above all non-global actors.
ALICE_FuncRequireFields(whichFunc, requireMale, requireFemale, whichFields) Throws a warning when a pair is initialized with the specified function and the listed
fields are not present in the host table of the initiating (male) actor and/or the
receiving (female) actor. For REQUIRED_FIELD_WARNINGS.
ALICE_FuncSetName(whichFunc, name) Sets the name of a function when displayed in debug mode.
-----PAIR UTILITY API-----
ALICE_PairIsFriend() Returns true if the owners of the objects in the current pair are allies.
ALICE_PairIsEnemy() Returns true if the owners of the objects in the current pair are enemies.
ALICE_PairDisable() Disables interactions between the actors of the current pair after this one.
ALICE_PairPreciseInterval(number) Modifies the return value of an interactionFunc so that, on average, the interval is the
specified value, even if it isn't an integer multiple of the minimum interval.
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_PairCooldown(duration) Returns the remaining cooldown for this pair, then invokes a cooldown of the specified
duration. Optional cooldownType parameter to create and differentiate between multiple
separate cooldowns.
ALICE_PairLoadData() Returns a table unique to the pair currently being evaluated, which can be used to read
and write data. Optional argument to set a metatable for the data table.
ALICE_PairIsFirstContact() Returns true if this is the first time this function was invoked for the current pair,
otherwise false. Resets when the objects in the pair leave the interaction range.
ALICE_FuncSetInit(whichFunc, initFunc) Calls the initFunc(hostA, hostB) whenever a pair is created with the specified
interactionFunc.
ALICE_FuncSetOnDestroy(whichFunc, onDestroyFunc) Executes the function onDestroyFunc(objectA, objectB, pairData) when a pair using the
specified function is destroyed. Only one callback per function.
ALICE_FuncSetOnBreak(whichFunc, onBreakFunc) Executes the function onBreakFunc(objectA, objectB, pairData, wasDestroyed) when a pair
using the specified function is destroyed or the actors leave interaction range. Only one
callback per function.
ALICE_FuncSetOnReset(whichFunc, onResetFunc) Executes the function onResetFunc(objectA, objectB, pairData, wasDestroyed) when a pair
using the specified function is destroyed, the actors leave interaction range, or the
ALICE_PairReset function is called, but only if ALICE_PairIsFirstContact has been called
previously. Only one callback per function.
ALICE_PairReset() Resets ALICE_PairIsFirstContact and calls the onReset function if it was reset. Also
resets the ALICE_IsUnoccupied function.
------WIDGET API-----
ALICE_IncludeTypes(whichType) Widgets with the specified fourCC codes will always receive actors, indepedent of the config.
ALICE_ExcludeTypes(whichType) Widgets with the specified fourCC codes will not receive actors, indepedent of the config.
ALICE_OnWidgetEvent(hookTable) Injects the functions listed in the hookTable into the hooks created by ALICE. The hookTable
can have the following keys: onUnitEnter - The listed function is called for all preplaced
units and whenever a unit enters the map or a hero is revived. onUnitDeath - The listed
function is called when a unit dies. onUnitRevive - The listed function is called when a
nonhero unit is revived. onUnitRemove - The listed function is called when a unit is removed
from the game or its corpse decays fully. onDestructableEnter - The listed function is called
for all preplaced destructables and whenever a destructable is created.
onDestructableDestroy - The listed function is called when a destructable dies or is removed.
onItemEnter - The listed function is called for all preplaced items and whenever an item first
appears on the map. onItemDestroy - The listed function is called when an item is destroyed
or removed.
-----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.
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.
ALICE_SwapIdentifier(whichObject, oldIdentifier, newIdentifier) Exchanges one of the object's identifier with another. If the old identifier is not found,
the new one won't be added.
ALICE_SetIdentifier(whichObject, newIdentifier) Sets the object's identifier to a string or string sequence.
ALICE_HasIdentifier(whichObject, identifier) Checks if the object has the specified identifiers. Identifier can be a string or a table.
If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL.
ALICE_GetIdentifier(whichObject) Compiles the identifiers of an object into the provided table or a new table.
ALICE_FindField(table, object) If table is a table with identifier keys, returns the field that matches with the specified
object's identifier. If no match is found, returns table.other. If table is not a table,
returns the variable itself.
-----INTERACTION API-----
ALICE_SetInteractionFunc(whichObject, target, interactionFunc) Changes the interaction function of the specified object towards the target identifier to
the specified function or removes it. Pairs already established will not be affected.
ALICE_AddSelfInteraction(whichObject, whichFunc) Adds a self-interaction with the specified function to the object. If a self-interaction
with that function already exists, nothing happens.
ALICE_RemoveSelfInteraction(whichObject, whichFunc) Removes the self-interaction with the specified function from the object.
ALICE_HasSelfInteraction(whichObject, whichFunc) Checks if the object has a self-interaction with the specified function.
ALICE_PairSetInteractionFunc(whichFunc) Changes the interactionFunc of the pair currently being evaluated. You cannot replace a
function with a return value with one that has no return value and vice versa.
-----MISC API-----
ALICE_FuncSetDelay(whichFunc, delay) The first interaction of all pairs using this function will be delayed by the specified
number.
ALICE_FuncSetUnbreakable(whichFunc) Changes the behavior of pairs using the specified function so that the interactions
continue to be evaluated when the two objects leave their interaction range. Also changes
the behavior of ALICE_PairDisable to not prevent the two object from pairing again.
ALICE_HasActor(object, identifier) Checks if an actor exists with the specified identifier for the specified object. Optional
strict flag to exclude actors that are anchored to that object.
ALICE_GetAnchor(object) Returns the object the specified object is anchored to or itself if there is no anchor.
ALICE_GetFlag(object, whichFlag) Returns the value stored for the specified flag of the specified actor.
ALICE_SetFlag(object, whichFlag, value) Sets the value of a flag for the actor of an object to the specified value. To change the
isStationary flag, use ALICE_SetStationary instead. Cannot change hasInfiniteRange flag.
ALICE_GetAnchoredObject(object, identifier) Accesses all objects anchored to the specified object and returns the one with the
specified identifier.
ALICE_GetOwner(object) Returns the owner of the specified object. Faster than GetOwningPlayer.
ALICE_TimeElapsed The time elapsed since the start of the game. Useful to store the time of the last
interaction between two objects.
ALICE_CPULoad The fraction of time the game is occupied running the ALICE cycle. Asynchronous!
====================================================================================================================================================================
S U P E R A D V A N C E D A P I
====================================================================================================================================================================
-----OPTIMIZATION API-----
ALICE_PairPause() Pauses interactions of the current pair after this one. Resume with ALICE_Unpause.
ALICE_Unpause(whichObject, whichFunctions) Unpauses all paused interactions of the object. Optional whichFunctions parameter, which
can be a function or a function sequence, to limit unpausing to pairs using those functions.
ALICE_FuncPauseOnStationary(whichFunc) Automatically pauses and unpauses all pairs using the specified function whenever the
initiating (male) actor is set to stationary/not stationary.
ALICE_SetStationary(whichObject, enable) Sets an object to stationary/not stationary. Will affect all actors attached to the object.
ALICE_IsStationary(whichObject) Returns whether the specified object is set to stationary.
ALICE_FuncDistribute(whichFunc, interval) The first interaction of all pairs using this function will be delayed by up to the specified
number, distributing individual calls over the interval to prevent computation spikes.
• The Modular API allows libraries to change the behavior of existing libraries, including
the in-built widget libraries and add new functionality. Functions must be called before
OnInit.final to affect preplaced widgets.
• OnCreation hooks are executed in the order OnCreation -> OnCreationAddFlag ->
OnCreationAddIdentifier -> OnCreationAddInteraction, OnCreationAddSelfInteraction,
taking into account the changes made by previous hooks.
-----MODULAR API-----
ALICE_OnCreation(matchingIdentifier, whichFunc) Executes the specified function before an object with the specified identifier is created.
The function is called with the host as the parameter.
ALICE_OnCreationAddFlag(matchingIdentifier, flag, value) Add a flag with the specified value to objects with matchingIdentifier as they are created.
Flags that can be modified are radius, cellCheckInterval, radius, isStationary, priority,
onActorDestroy, and zOffset. If a function is set for value, the function will be called
with the host as the argument and the return value used for the flag. If a function is
provided for value, the returned value of the function will be added.
ALICE_OnCreationAddIdentifier(matchingIdentifier, additionalIdentifier) Adds an additional identifier to objects with matchingIdentifier as they are created.
If a function is provided for value, the returned string of the function will be added.
ALICE_OnCreationAddInteraction(matchingIdentifier, keyword, interactionFunc) Adds an interaction to all objects with matchingIdentifier as they are created towards
objects with the specified keyword in their identifier. To add a self-interaction, use
ALICE_OnCreationAddSelfInteraction instead.
ALICE_OnCreationAddSelfInteraction(matchingIdentifier, selfInteractionFunc) Adds a self-interaction to all objects with matchingIdentifier as they are created.
• The Pair Access API allows external functions to influence pairs and to access pair data.
-----PAIR ACCESS API-----
ALICE_Enable(objectA, objectB) Restore a pair that has been previously destroyed with ALICE_PairDisable. Returns two
booleans. The first denotes whether a pair now exists and the second if it was just created.
ALICE_AccessData(objectA, objectB) Access the pair for objects A and B and, if it exists, return the data table stored for that
pair. If objectB is a function, returns the data of the self-interaction of objectA using the
specified function.
ALICE_UnpausePair(objectA, objectB) Access the pair for objects A and B and, if it is paused, unpause it. If objectB is a function,
unpauses the self-interaction of objectA using the specified function.
ALICE_GetPairAndDo(action, objectA, objectB) Access the pair for objects A and B and, if it exists, perform the specified action. Returns
the return value of the action function. The hosts of the pair as well as any additional
parameters are passed into the action function. If objectB is a function, accesses the
self-interaction of objectA using the specified function.
ALICE_ForAllPairsDo(action, object, whichFunc) Access all pairs active for the object using the specified interactionFunc and perform the
specified action. The hosts of the pairs as well as any additional parameters are passed into
the action function.
====================================================================================================================================================================
]]
if Debug then Debug.beginFile "ALICE" end
---@diagnostic disable: need-check-nil
do
--[[
=============================================================================================================================================================
A Limitless Interaction Caller Engine
by Antares
v2.5.2
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/
Hook https://www.hiveworkshop.com/threads/hook.339153/
HandleType https://www.hiveworkshop.com/threads/get-handle-type.354436/
PrecomputedHeightMap (optional) https://www.hiveworkshop.com/threads/precomputed-synchronized-terrain-height-map.353477/
For tutorials & documentation, see here:
https://www.hiveworkshop.com/threads/.353126/
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
ALICE_Config = {
--Print out warnings, errors, and enable the "downtherabbithole" cheat code for the players with these names. #XXXX not required.
MAP_CREATORS = { ---@constant string[]
"Antares",
"WorldEdit"
}
--Minimum interval between interactions in seconds. Sets the time step of the timer. All interaction intervals are an integer multiple of this value.
,MIN_INTERVAL = 0.02 ---@constant number
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--Debugging
--Abort the cycle the first time it crashes. Makes it easier to identify a bug if downstream errors are prevented. Disable for release version.
,HALT_ON_FIRST_CRASH = true ---@constant boolean
--Warn the user when a host table holds an unrecognized field on actor creation, for example "itneractions". New fields can be added with ALICE_RecognizeFields.
--You may want to disable this when you're building your own systems.
,UNRECOGNIZED_FIELD_WARNINGS = true ---@constant boolean
--Warn the user when a host table is missing required fields for an interaction function upon pair creation. Disable for release version to improve performance.
,REQUIRED_FIELD_WARNINGS = false ---@constant boolean
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--Optimization
--Maximum interval between interactions in seconds.
,MAX_INTERVAL = 10.0 ---@constant number
--The playable map area is divided into cells of this size. Objects only interact with other objects that share a cell with them. Smaller cells increase the
--efficiency of interactions at the cost of increased memory usage and overhead.
,CELL_SIZE = 256 ---@constant number
--How often the system checks if objects left their current cell. Should be overwritten with the cellCheckInterval flag for fast-moving objects.
,DEFAULT_CELL_CHECK_INTERVAL = 0.1 ---@constant number
--How large an actor is when it comes to determining in which cells it is in and its maximum interaction range. Should be overwritten with the radius flag for
--objects with a larger interaction range.
,DEFAULT_OBJECT_RADIUS = 75 ---@constant number
--You can integrate ALICE's internal table recycling system into your own by setting the GetTable and ReturnTable functions here.
,TABLE_RECYCLER_GET = nil ---@constant function
,TABLE_RECYCLER_RETURN = nil ---@constant function
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--Automatic actor creation for widgets
--Actor creation for user-defined objects is up to you. For widgets, ALICE offers automatic actor creation and destruction.
--Determine which widget types will automatically receive actors and be registered with ALICE. The created actors are passive and only receive pairs. You can
--add exceptions with ALICE_IncludeType and ALICE_ExcludeType.
,NO_UNIT_ACTOR = false ---@constant boolean
,NO_DESTRUCTABLE_ACTOR = false ---@constant boolean
,NO_ITEM_ACTOR = false ---@constant boolean
--Disable to destroy unit actors on death. Units will not regain an actor when revived.
,UNITS_LEAVE_BEHIND_CORPSES = true ---@constant boolean
--Disable if corpses are relevant and you're moving them around.
,UNIT_CORPSES_ARE_STATIONARY = true ---@constant boolean
--Add identifiers such as "hero" or "mechanical" to units if they have the corresponding classification and "nonhero", "nonmechanical" etc. if they do not.
--The identifiers will not get updated automatically when a unit gains or loses classifications and you must update them manually with ALICE_SwapIdentifier.
,UNIT_ADDED_CLASSIFICATIONS = { ---@constant unittype[]
UNIT_TYPE_HERO,
UNIT_TYPE_STRUCTURE
}
--The radius of the unit actors. Set to nil to use DEFAULT_OBJECT_RADIUS.
,DEFAULT_UNIT_RADIUS = nil ---@constant number
--Searches for these keywords in the destructable's name and adds those keywords to the actor's identifier if it finds them.
,DESTRUCTABLE_KEYWORDS = { ---@constant string[]
"Tree",
"Bridge",
"Rock",
"Gate"
}
--The radius of the destructable actors. Set to nil to use DEFAULT_OBJECT_RADIUS.
,DEFAULT_DESTRUCTABLE_RADIUS = nil ---@constant number
--Disable if items are relevant and you're moving them around.
,ITEMS_ARE_STATIONARY = true ---@constant boolean
--The radius of the item actors. Set to nil to use DEFAULT_OBJECT_RADIUS.
,DEFAULT_ITEM_RADIUS = nil ---@constant number
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--For EmmyLua annotations. If you're passing any types into object functions other than these types, add them here to disable warnings.
---@alias Object unit | destructable | item | table
--[[
=============================================================================================================================================================
E N D O F C O N F I G
=============================================================================================================================================================
]]
--#region Variables
ALICE_TimeElapsed = 0.0 ---@type number
ALICE_CPULoad = 0 ---@type number
MATCHING_TYPE_ANY = {} ---@constant table
MATCHING_TYPE_ALL = {} ---@constant table
local max = math.max
local min = math.min
local sqrt = math.sqrt
local atan = math.atan
local insert = table.insert
local concat = table.concat
local sort = table.sort
local pack = table.pack
local unpack = table.unpack
local config = ALICE_Config
local MASTER_TIMER ---@type timer
local MAX_STEPS = 0 ---@type integer
local CYCLE_LENGTH = 0 ---@type integer
local DO_NOT_EVALUATE = 0 ---@type integer
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 MAP_SIZE_X ---@type number
local MAP_SIZE_Y ---@type number
local NUM_CELLS_X ---@type integer
local NUM_CELLS_Y ---@type integer
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 Cell[][]
--Array indices for pair fields. Storing as a sequence up to 8 reduces memory usage.
local ACTOR_A = 1 ---@constant integer
local ACTOR_B = 2 ---@constant integer
local HOST_A = 3 ---@constant integer
local HOST_B = 4 ---@constant integer
local CURRENT_POSITION = 5 ---@constant integer
local POSITION_IN_STEP = 6 ---@constant integer
local NEXT = 5 ---@constant integer
local PREVIOUS = 6 ---@constant integer
local EVERY_STEP = 7 ---@constant integer
local INTERACTION_FUNC = 8 ---@constant integer
local DESTRUCTION_QUEUED = "DQ" ---@constant string
local HAD_CONTACT = "HC" ---@constant string
local COOLDOWN = "CD" ---@constant string
local PAUSED = "PA" ---@constant string
local USER_DATA = "UD" ---@constant string
local EMPTY_TABLE = {} ---@constant table
local SELF_INTERACTION_ACTOR ---@type Actor
local DUMMY_PAIR ---@constant Pair
= {[DESTRUCTION_QUEUED] = true}
local OUTSIDE_OF_CYCLE = ---@constant Pair
setmetatable({}, {__index = function()
error("Attempted to call Pair API function from outside of allowed functions.")
end})
local cycle = {
counter = 0, ---@type integer
unboundCounter = 0, ---@type integer
isHalted = false, ---@type boolean
isCrash = false, ---@type boolean
freezeCounter = 0, ---@type number
}
local currentPair = OUTSIDE_OF_CYCLE ---@type Pair | nil
local totalActors = 0 ---@type integer
local moveableLoc ---@type location
local numPairs = {} ---@type integer[]
local whichPairs = {} ---@type table[]
local firstEveryStepPair = DUMMY_PAIR ---@type Pair
local lastEveryStepPair = DUMMY_PAIR ---@type Pair
local numEveryStepPairs = 0 ---@type integer
local actorList = {} ---@type Actor[]
local celllessActorList = {} ---@type Actor[]
local pairList = {} ---@type Pair[]
local pairingExcluded = {} ---@type table[]
local numCellChecks = {} ---@type integer[]
local cellCheckedActors = {} ---@type Actor[]
local actorAlreadyChecked = {} ---@type boolean[]
local unusedPairs = {} ---@type Pair[]
local unusedActors = {} ---@type Actor[]
local unusedTables = {} ---@type table[]
local additionalFlags = {} ---@type table
local destroyedActors = {} ---@type Actor[]
local actorOf = {} ---@type Actor[]
local functionIsEveryStep = {} ---@type table<function,boolean>
local functionIsUnbreakable = {} ---@type table<function,boolean>
local functionIsUnsuspendable = {} ---@type table<function,boolean>
local functionInitializer = {} ---@type table<function,function>
local functionDelay = {} ---@type table<function,number>
local functionDelayIsDistributed = {} ---@type table<function,boolean>
local functionDelayCurrent = {} ---@type table<function,number>
local functionOnDestroy = {} ---@type table<function,function>
local functionOnBreak = {} ---@type table<function,function>
local functionOnReset = {} ---@type table<function,function>
local functionPauseOnStationary = {} ---@type table<function,boolean>
local functionRequiredFields = {} ---@type table<function,table>
local functionName = {} ---@type table<function,string>
local functionKey = {} ---@type table<function,integer>
local highestFunctionKey = 0 ---@type integer
local requiredFieldWarningGiven = {} ---@type table<string,boolean>
local delayedCallbackFunctions = {} ---@type function[]
local delayedCallbackArgs = {} ---@type table[]
local enumExceptions = {} ---@type any[]
local unitOwnerFunc = {} ---@type function[]
local userCallbacks = {} ---@type table[]
local pairingFunctions = {} ---@type table[]
local objectIsStationary ---@type table<any,boolean>
= setmetatable({}, {__mode = "k"})
local widgets = {
bindChecks = {}, ---@type Actor[]
deathTriggers ---@type table<destructable|item,trigger>
= setmetatable({}, {__mode = "k"}),
reviveTriggers = {}, ---@type table<unit,trigger>
idExclusions = {}, ---@type table<integer,boolean>
idInclusions = {}, ---@type table<integer,boolean>
hash = nil ---@type hashtable
}
local onCreation = { ---@type table
flags = {}, ---@type table<string,table>
funcs = {}, ---@type table<string,table>
identifiers = {}, ---@type table<string,table>
interactions = {}, ---@type table<string,table>
selfInteractions = {} ---@type table<string,table>
}
local INV_MIN_INTERVAL ---@constant number
= 1/config.MIN_INTERVAL - 0.001
local OVERWRITEABLE_FLAGS = { ---@constant table<string,boolean>
priority = true,
zOffset = true,
cellCheckInterval = true,
isStationary = true,
radius = true,
persistOnDeath = true,
onActorDestroy = true,
hasInfiniteRange = true,
isUnselectable = true,
}
--Will warn you if you pass a flag or table field in ALICE_Create that's not in this list.
local recognizedFields = { ---@type table<string,boolean>
identifier = true,
interactions = true,
selfInteractions = true,
priority = true,
anchor = true,
zOffset = true,
cellCheckInterval = true,
isStationary = true,
radius = true,
persistOnDeath = true,
width = true,
height = true,
bindToBuff = true,
bindToOrder = true,
onActorDestroy = true,
hasInfiniteRange = true,
isGlobal = true,
isUnselectable = true,
x = true,
y = true,
z = true,
visual = true,
owner = true,
create = true,
destroy = true,
__index = true,
__newindex = true,
__mode = true,
__tostring = true,
__name = true
}
local UNIT_CLASSIFICATION_NAMES = { ---@constant table<unittype,string>
[UNIT_TYPE_HERO] = "hero",
[UNIT_TYPE_STRUCTURE] = "structure",
[UNIT_TYPE_MECHANICAL] = "mechanical",
[UNIT_TYPE_UNDEAD] = "undead",
[UNIT_TYPE_TAUREN] = "tauren",
[UNIT_TYPE_ANCIENT] = "ancient",
[UNIT_TYPE_SAPPER] = "sapper",
[UNIT_TYPE_PEON] = "worker",
[UNIT_TYPE_FLYING] = "flying",
[UNIT_TYPE_GIANT] = "giant",
[UNIT_TYPE_SUMMONED] = "summoned",
[UNIT_TYPE_TOWNHALL] = "townhall",
}
local GetTable ---@type function
local ReturnTable ---@type function
local Create ---@type function
local Destroy ---@type function
local CreateReference ---@type function
local RemoveReference ---@type function
local SetCoordinateFuncs ---@type function
local SetOwnerFunc ---@type function
local InitCells ---@type function
local InitCellChecks ---@type function
local AssignActorClass ---@type function
local Flicker ---@type function
local SharesCellWith ---@type function
local CreateBinds ---@type function
local DestroyObsoletePairs ---@type function
local Unpause ---@type function
local SetStationary ---@type function
local VisualizeCells ---@type function
local RedrawCellVisualizers ---@type function
local Suspend ---@type function
local Deselect ---@type function
local Select ---@type function
local GetDescription ---@type function
local CreateVisualizer ---@type function
local EnterCell ---@type function
local RemoveCell ---@type function
local LeaveCell ---@type function
local VisualizationLightning ---@type function
local GetTerrainZ ---@type function
local GetActor ---@type function
local EnableDebugMode ---@type function
local UpdateSelectedActor ---@type function
local OnDestructableDeath ---@type function
local OnItemDeath ---@type function
local debug = {} ---@type table
debug.enabled = false ---@type boolean
debug.mouseClickTrigger = nil ---@type trigger
debug.cycleSelectTrigger = nil ---@type trigger
debug.nextStepTrigger = nil ---@type trigger
debug.lockSelectionTrigger = nil ---@type trigger
debug.haltTrigger = nil ---@type trigger
debug.printFunctionsTrigger = nil ---@type trigger
debug.selectedActor = nil ---@type Actor | nil
debug.tooltip = nil ---@type framehandle
debug.tooltipText = nil ---@type framehandle
debug.tooltipTitle = nil ---@type framehandle
debug.visualizationLightnings = {} ---@type lightning[]
debug.selectionLocked = false ---@type boolean
debug.benchmark = false ---@type boolean
debug.visualizeAllActors = false ---@type boolean
debug.visualizeAllCells = false ---@type boolean
debug.printFunctionNames = false ---@type boolean
debug.evaluationTime = {} ---@type table
debug.gameIsPaused = nil ---@type boolean
debug.trackedVariables = {} ---@type table<string,boolean>
local eventHooks = { ---@type table[]
onUnitEnter = {},
onUnitDeath = {},
onUnitRevive = {},
onUnitRemove = {},
onUnitChangeOwner = {},
onDestructableEnter = {},
onDestructableDestroy = {},
onItemEnter = {},
onItemDestroy = {}
}
--#endregion
--===========================================================================================================================================================
--Filter Functions
--===========================================================================================================================================================
--#region Filter Functions
---For debug functions.
---@param whichIdentifier string | string[] | nil
local function Identifier2String(whichIdentifier)
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
local function HasIdentifierFromTable(actor, whichIdentifier)
if whichIdentifier[#whichIdentifier] == MATCHING_TYPE_ANY then
for i = 1, #whichIdentifier - 1 do
if actor.identifier[whichIdentifier[i]] then
return true
end
end
return false
elseif whichIdentifier[#whichIdentifier] == MATCHING_TYPE_ALL then
for i = 1, #whichIdentifier - 1 do
if not actor.identifier[whichIdentifier[i]] then
return false
end
end
return true
elseif type(whichIdentifier[#whichIdentifier]) == "string" then
error("Matching type missing in identifier table.")
else
error("Invalid matching type specified in identifier table.")
end
end
--#endregion
--===========================================================================================================================================================
--Utility
--===========================================================================================================================================================
--#region Utility
local function Warning(whichWarning)
for __, name in ipairs(config.MAP_CREATORS) do
if string.find(GetPlayerName(GetLocalPlayer()), name) then
print(whichWarning)
end
end
end
local function AddDelayedCallback(func, arg1, arg2, arg3)
local index = #delayedCallbackFunctions + 1
delayedCallbackFunctions[index] = func
local args = delayedCallbackArgs[index] or {}
args[1], args[2], args[3] = arg1, arg2, arg3
delayedCallbackArgs[index] = args
end
local function ExecuteUserCallback(self)
if self.pair then
if self.pair[HOST_A] == self.hostA and self.pair[HOST_B] == self.hostB then
currentPair = self.pair
self.callback(self.hostA, self.hostB, true)
else
self.callback(self.hostA, self.hostB, false)
end
elseif self.args then
if type(self.args) == "table" and self.args.unpack then
self.callback(unpack(self.args))
ReturnTable(self.args)
else
self.callback(self.args)
end
else
self.callback()
end
if self == userCallbacks.first then
if self.next then
self.next.previous = nil
else
userCallbacks.last = nil
end
userCallbacks.first = self.next
elseif self == userCallbacks.last then
userCallbacks.last = self.previous
self.previous.next = nil
else
self.previous.next = self.next
self.next.previous = self.previous
end
ReturnTable(self)
end
local function AddUserCallback(self)
if userCallbacks.first == nil then
userCallbacks.first = self
userCallbacks.last = self
else
local node = userCallbacks.last
local callCounter = self.callCounter
while node and node.callCounter > callCounter do
node = node.previous
end
if node == nil then
--Insert at the beginning
userCallbacks.first.previous = self
self.next = userCallbacks.first
userCallbacks.first = self
else
if node == userCallbacks.last then
--Insert at the end
userCallbacks.last = self
else
--Insert in the middle
self.next = node.next
self.next.previous = self
end
self.previous = node
node.next = self
end
end
end
local function PeriodicWrapper(caller)
if caller.excess > 0 then
local returnValue = caller.excess
caller.excess = caller.excess - config.MAX_INTERVAL
return returnValue
end
local returnValue = caller.callback(unpack(caller))
if returnValue and returnValue > config.MAX_INTERVAL then
caller.excess = returnValue - config.MAX_INTERVAL
end
return returnValue
end
local function RepeatedWrapper(caller)
if caller.excess > 0 then
local returnValue = caller.excess
caller.excess = caller.excess - config.MAX_INTERVAL
return returnValue
end
caller.currentExecution = caller.currentExecution + 1
if caller.currentExecution == caller.howOften then
ALICE_DisablePeriodic()
end
local returnValue = caller.callback(caller.currentExecution, unpack(caller))
if returnValue and returnValue > config.MAX_INTERVAL then
caller.excess = returnValue - config.MAX_INTERVAL
end
return returnValue
end
local function ToUpperCase(__, letter)
return letter:upper()
end
local toCamelCase = setmetatable({}, {
__index = function(self, whichString)
whichString = whichString:gsub("|[cC]\x25x\x25x\x25x\x25x\x25x\x25x\x25x\x25x", "") --remove color codes
whichString = whichString:gsub("|[rR]", "") --remove closing color codes
whichString = whichString:gsub("(\x25s)(\x25a)", ToUpperCase) --remove spaces and convert to upper case after space
whichString = whichString:gsub("[^\x25w]", "") --remove special characters
self[whichString] = string.lower(whichString:sub(1,1)) .. string.sub(whichString,2) --converts first character to lower case
return self[whichString]
end
})
--For debug mode
local function Function2String(func)
if functionName[func] then
return functionName[func]
end
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
--For debug mode
local function Object2String(object)
if IsHandle[object] then
if IsWidget[object] then
if HandleType[object] == "unit" then
local str = string.gsub(tostring(object), "unit: ", "")
if str:sub(1,1) == "0" then
return GetUnitName(object) .. ": " .. str:sub(str:len() - 3, str:len())
else
return str
end
elseif HandleType[object] == "destructable" then
local str = string.gsub(tostring(object), "destructable: ", "")
if str:sub(1,1) == "0" then
return GetDestructableName(object) .. ": " .. str:sub(str:len() - 3, str:len())
else
return str
end
else
local str = string.gsub(tostring(object), "item: ", "")
if str:sub(1,1) == "0" then
return GetItemName(object) .. ": " .. str:sub(str:len() - 3, str:len())
else
return str
end
end
else
local str = tostring(object)
local address = str:sub((str:find(":", nil, true) or 0) + 2, str:len())
return HandleType[object] .. " " .. (address:sub(1,1) == "0" and address:sub(address:len() - 3, address:len()))
end
elseif object.__name then
local str = string.gsub(tostring(object), object.__name .. ": ", "")
str = string.sub(str, string.len(str) - 3, string.len(str))
return object.__name .. " " .. str
else
local str = tostring(object)
if string.sub(str,8,8) == "0" then
return "table: " .. string.sub(str, string.len(str) - 3, string.len(str))
else
return str
end
end
end
local function OnUnitChangeOwner()
local u = GetTriggerUnit()
local newOwner = GetOwningPlayer(u)
unitOwnerFunc[newOwner] = unitOwnerFunc[newOwner] or function() return newOwner end
if actorOf[u] then
if actorOf[u].isActor then
actorOf[u].getOwner = unitOwnerFunc[newOwner]
else
for __, actor in ipairs(actorOf[u]) do
actor.getOwner = unitOwnerFunc[newOwner]
end
end
end
for __, func in ipairs(eventHooks.onUnitChangeOwner) do
func(u)
end
end
--#endregion
--===========================================================================================================================================================
--Getter functions
--===========================================================================================================================================================
--#region Getter Functions
--x and y are stored with an anchor key because GetUnitX etc. cannot take an actor as an argument and they are identical for all actors anchored to the same
--object. z is stored with an actor key because it requires zOffset, which is stored on the actor, and the z-values are not guaranteed to be identical for all
--actors anchored to the same object.
local coord = {
classX = setmetatable({}, {__index = function(self, key) self[key] = key.x return self[key] end}),
classY = setmetatable({}, {__index = function(self, key) self[key] = key.y return self[key] end}),
classZ = setmetatable({}, {__index = function(self, key) self[key] = key.anchor.z + key.zOffset return self[key] end}),
unitX = setmetatable({}, {__index = function(self, key) self[key] = GetUnitX(key) return self[key] end}),
unitY = setmetatable({}, {__index = function(self, key) self[key] = GetUnitY(key) return self[key] end}),
unitZ = setmetatable({}, {__index = function(self, key) self[key] = GetTerrainZ(key.x[key.anchor], key.y[key.anchor]) + GetUnitFlyHeight(key.anchor) + key.zOffset return self[key] end}),
destructableX = setmetatable({}, {__index = function(self, key) self[key] = GetDestructableX(key) return self[key] end}),
destructableY = setmetatable({}, {__index = function(self, key) self[key] = GetDestructableY(key) return self[key] end}),
destructableZ = setmetatable({}, {__index = function(self, key) self[key] = GetTerrainZ(key.x[key.anchor], key.y[key.anchor]) + key.zOffset return self[key] end}),
itemX = setmetatable({}, {__index = function(self, key) self[key] = GetItemX(key) return self[key] end}),
itemY = setmetatable({}, {__index = function(self, key) self[key] = GetItemY(key) return self[key] end}),
itemZ = setmetatable({}, {__index = function(self, key) self[key] = GetTerrainZ(key.x[key.anchor], key.y[key.anchor]) + key.zOffset return self[key] end}),
terrainZ = setmetatable({}, {__index = function(self, key) self[key] = GetTerrainZ(key.x[key.anchor], key.y[key.anchor]) return self[key] end}),
globalXYZ = setmetatable({}, {__index = function(self, key) self[key] = 0 return 0 end})
}
local function GetClassOwner(source)
return source.owner
end
local function GetClassOwnerById(source)
return Player(source.owner - 1)
end
--#endregion
--===========================================================================================================================================================
--Pair Class
--===========================================================================================================================================================
--#region Pair
---@class Pair
local Pair = {
[ACTOR_A] = nil, ---@type Actor
[ACTOR_B] = nil, ---@type Actor
[HOST_A] = nil, ---@type any
[HOST_B] = nil, ---@type any
[CURRENT_POSITION] = nil, ---@type integer
[POSITION_IN_STEP] = nil, ---@type integer
[NEXT] = nil, ---@type Pair
[PREVIOUS] = nil, ---@type Pair
[INTERACTION_FUNC] = nil, ---@type function
[EVERY_STEP] = nil, ---@type boolean
[DESTRUCTION_QUEUED] = nil, ---@type boolean
[USER_DATA] = nil, ---@type table
[HAD_CONTACT] = nil, ---@type boolean
[COOLDOWN] = nil, ---@type number
[PAUSED] = nil, ---@type boolean
}
local function GetInteractionFunc(male, female)
local func = pairingFunctions[female.identifierClass][male.interactionsClass]
if func ~= nil then
return func
end
local identifier = female.identifier
local level = 0
local conflict = false
for key, value in pairs(male.interactions) do
if type(key) == "string" then
if identifier[key] then
if level < 1 then
func = value
level = 1
elseif level == 1 then
conflict = true
end
end
else
local match = true
for __, tableKey in ipairs(key) do
if not identifier[tableKey] then
match = false
break
end
end
if match then
if #key > level then
func = value
level = #key
conflict = false
elseif #key == level then
conflict = true
end
end
end
end
if conflict then
error("InteractionFunc ambiguous for actors with identifiers " .. Identifier2String(male.identifier) .. " and " .. Identifier2String(female.identifier) .. ".")
end
if func then
pairingFunctions[female.identifierClass][male.interactionsClass] = func
return func
else
pairingFunctions[female.identifierClass][male.interactionsClass] = false
return false
end
end
---@param whichPair Pair
local function AddPairToEveryStepList(whichPair)
whichPair[PREVIOUS] = lastEveryStepPair
whichPair[NEXT] = nil
lastEveryStepPair[NEXT] = whichPair
lastEveryStepPair = whichPair
numEveryStepPairs = numEveryStepPairs + 1
end
---@param whichPair Pair
local function RemovePairFromEveryStepList(whichPair)
if whichPair[PREVIOUS] == nil then
return
end
if whichPair[NEXT] then
whichPair[NEXT][PREVIOUS] = whichPair[PREVIOUS]
else
lastEveryStepPair = whichPair[PREVIOUS]
end
whichPair[PREVIOUS][NEXT] = whichPair[NEXT]
whichPair[PREVIOUS] = nil
numEveryStepPairs = numEveryStepPairs - 1
end
local function CheckRequiredFields(host, actor, fieldType, interactionFunc)
local missingFields
for key, __ in pairs(functionRequiredFields[interactionFunc][fieldType]) do
if not host[key] then
missingFields = missingFields or {}
insert(missingFields, key)
end
end
if missingFields then
local str = "|cffffcc00"
local first = true
for __, value in ipairs(missingFields) do
if not first then
str = str .. ", "
end
str = str .. value
first = false
end
if fieldType == "male" then
str = "|cffff0000Warning:|r Required field(s) " .. str .. "|r for function " .. Function2String(interactionFunc) .. " not present in host table of male actor |cffaaaaff" .. Identifier2String(actor.identifier) .. "|r."
else
str = "|cffff0000Warning:|r Required field(s) " .. str .. "|r for function " .. Function2String(interactionFunc) .. " not present in host table of female actor |cffaaaaff" .. Identifier2String(actor.identifier) .. "|r."
end
if not requiredFieldWarningGiven[str] then
Warning(str)
requiredFieldWarningGiven[str] = true
end
end
end
---@param actorA Actor
---@param actorB Actor
---@param interactionFunc function
---@return Pair | nil
local function CreatePair(actorA, actorB, interactionFunc)
if pairingExcluded[actorA][actorB] or interactionFunc == nil or actorA.host == actorB.host or actorA.originalAnchor == actorB.originalAnchor then
pairingExcluded[actorA][actorB] = true
pairingExcluded[actorB][actorA] = true
return nil
end
if (actorA.isSuspended or actorB.isSuspended) and not functionIsUnsuspendable[interactionFunc] then
return nil
end
local self ---@type Pair
if #unusedPairs == 0 then
self = {}
else
self = unusedPairs[#unusedPairs]
unusedPairs[#unusedPairs] = nil
end
self[ACTOR_A] = actorA
self[ACTOR_B] = actorB
self[HOST_A] = actorA.host
if actorB == SELF_INTERACTION_ACTOR then
self[HOST_B] = actorA.host
else
self[HOST_B] = actorB.host
end
if config.REQUIRED_FIELD_WARNINGS then
local requiredFields = functionRequiredFields[interactionFunc]
if requiredFields then
if requiredFields.male then
CheckRequiredFields(self[HOST_A], self[ACTOR_A], "male", interactionFunc)
end
if requiredFields.female then
CheckRequiredFields(self[HOST_B], self[ACTOR_B], "female", interactionFunc)
end
end
end
self[INTERACTION_FUNC] = interactionFunc
local lastPair = actorA.lastPair
actorA.previousPair[self] = lastPair
actorA.nextPair[lastPair] = self
actorA.lastPair = self
lastPair = actorB.lastPair
actorB.previousPair[self] = lastPair
actorB.nextPair[lastPair] = self
actorB.lastPair = self
self[DESTRUCTION_QUEUED] = nil
pairList[actorA][actorB] = self
if functionInitializer[interactionFunc] then
local tempPair = currentPair
currentPair = self
functionInitializer[interactionFunc](self[HOST_A], self[HOST_B])
currentPair = tempPair
end
if (functionPauseOnStationary[interactionFunc] and actorA.isStationary) then
if functionIsEveryStep[interactionFunc] then
self[EVERY_STEP] = true
else
self[CURRENT_POSITION] = DO_NOT_EVALUATE
end
self[PAUSED] = true
elseif functionIsEveryStep[interactionFunc] then
AddPairToEveryStepList(self)
self[EVERY_STEP] = true
else
local firstStep
if functionDelay[interactionFunc] then
if functionDelayIsDistributed[interactionFunc] then
functionDelayCurrent[interactionFunc] = functionDelayCurrent[interactionFunc] + config.MIN_INTERVAL
if functionDelayCurrent[interactionFunc] > functionDelay[interactionFunc] then
functionDelayCurrent[interactionFunc] = functionDelayCurrent[interactionFunc] - functionDelay[interactionFunc]
end
firstStep = cycle.counter + (functionDelayCurrent[interactionFunc]*INV_MIN_INTERVAL + 1) // 1
else
firstStep = cycle.counter + (functionDelay[interactionFunc]*INV_MIN_INTERVAL + 1) // 1
end
else
firstStep = cycle.counter + 1
end
if firstStep > CYCLE_LENGTH then
firstStep = firstStep - CYCLE_LENGTH
end
numPairs[firstStep] = numPairs[firstStep] + 1
whichPairs[firstStep][numPairs[firstStep]] = self
self[CURRENT_POSITION] = firstStep
self[POSITION_IN_STEP] = numPairs[firstStep]
end
return self
end
local function DestroyPair(self)
if self[EVERY_STEP] then
RemovePairFromEveryStepList(self)
else
whichPairs[self[CURRENT_POSITION]][self[POSITION_IN_STEP]] = DUMMY_PAIR
end
self[CURRENT_POSITION] = nil
self[POSITION_IN_STEP] = nil
self[DESTRUCTION_QUEUED] = true
local tempPair = currentPair
currentPair = self
if self[HAD_CONTACT] then
if functionOnReset[self[INTERACTION_FUNC]] and not cycle.isCrash then
functionOnReset[self[INTERACTION_FUNC]](self[HOST_A], self[HOST_B], self[USER_DATA], true)
end
self[HAD_CONTACT] = nil
end
if functionOnBreak[self[INTERACTION_FUNC]] and not cycle.isCrash then
functionOnBreak[self[INTERACTION_FUNC]](self[HOST_A], self[HOST_B], self[USER_DATA], true)
end
if functionOnDestroy[self[INTERACTION_FUNC]] and not cycle.isCrash then
functionOnDestroy[self[INTERACTION_FUNC]](self[HOST_A], self[HOST_B], self[USER_DATA])
end
if self[USER_DATA] then
ReturnTable(self[USER_DATA])
end
currentPair = tempPair
--Reset ALICE_PairIsUnoccupied()
if self[ACTOR_B][self[INTERACTION_FUNC]] == self then
self[ACTOR_B][self[INTERACTION_FUNC]] = nil
end
if self[ACTOR_B] == SELF_INTERACTION_ACTOR then
self[ACTOR_A].selfInteractions[self[INTERACTION_FUNC]] = nil
end
local actorA = self[ACTOR_A]
local previous = actorA.previousPair
local next = actorA.nextPair
if next[self] then
previous[next[self]] = previous[self]
else
actorA.lastPair = previous[self]
end
next[previous[self]] = next[self]
previous[self] = nil
next[self] = nil
local actorB = self[ACTOR_B]
previous = actorB.previousPair
next = actorB.nextPair
if next[self] then
previous[next[self]] = previous[self]
else
actorB.lastPair = previous[self]
end
next[previous[self]] = next[self]
previous[self] = nil
next[self] = nil
unusedPairs[#unusedPairs + 1] = self
pairList[actorA][actorB] = nil
pairList[actorB][actorA] = nil
self[USER_DATA] = nil
self[HAD_CONTACT] = nil
self[EVERY_STEP] = nil
self[PAUSED] = nil
if self[COOLDOWN] then
ReturnTable(self[COOLDOWN])
self[COOLDOWN] = nil
end
end
local function PausePair(self)
if self[DESTRUCTION_QUEUED] then
return
end
if self[EVERY_STEP] then
RemovePairFromEveryStepList(self)
else
if self[CURRENT_POSITION] ~= DO_NOT_EVALUATE then
whichPairs[self[CURRENT_POSITION]][self[POSITION_IN_STEP]] = DUMMY_PAIR
local nextStep = DO_NOT_EVALUATE
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = self
self[CURRENT_POSITION] = nextStep
self[POSITION_IN_STEP] = numPairs[nextStep]
end
end
self[PAUSED] = true
end
local function UnpausePair(self)
if self[DESTRUCTION_QUEUED] then
return
end
local actorA = self[ACTOR_A]
local actorB = self[ACTOR_B]
if self[EVERY_STEP] then
if self[PREVIOUS] == nil and (not actorA.usesCells or not actorB.usesCells or SharesCellWith(actorA, actorB)) then
AddPairToEveryStepList(self)
end
else
if self[CURRENT_POSITION] == DO_NOT_EVALUATE and (not actorA.usesCells or not actorB.usesCells or SharesCellWith(actorA, actorB)) then
local nextStep = cycle.counter + 1
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = self
self[CURRENT_POSITION] = nextStep
self[POSITION_IN_STEP] = numPairs[nextStep]
end
end
self[PAUSED] = nil
end
--#endregion
--===========================================================================================================================================================
--Actor Class
--===========================================================================================================================================================
local function GetUnusedActor()
local self
if #unusedActors == 0 then
--Actors have their own table recycling system. These fields do not get nilled on destroy.
self = {} ---@type Actor
self.isActor = true
self.identifier = {}
self.firstPair = {}
self.lastPair = self.firstPair
self.nextPair = {}
self.previousPair = {}
self.isInCell = {}
self.nextInCell = {}
self.previousInCell = {}
self.interactions = {}
self.selfInteractions = {}
self.references = {}
pairList[self] = {}
pairingExcluded[self] = {}
else
self = unusedActors[#unusedActors]
unusedActors[#unusedActors] = nil
end
return self
end
GetActor = function(object, keyword)
if object == nil then
if debug.selectedActor then
return debug.selectedActor
end
return nil
end
if actorOf[object] then
if actorOf[object].isActor then
if keyword == nil or actorOf[object].identifier[keyword] then
return actorOf[object]
else
return nil
end
elseif keyword == nil then
--If called within interactionFunc and keyword is not specified, prioritize returning actor that's in the current pair, then an actor for which the object is the
--host, not the anchor.
if currentPair ~= OUTSIDE_OF_CYCLE then
if object == currentPair[HOST_A] then
return currentPair[ACTOR_A]
elseif object == currentPair[HOST_B] then
return currentPair[ACTOR_B]
end
end
for __, actor in ipairs(actorOf[object]) do
if actor.host == object then
return actor
end
end
return actorOf[object][1]
else
for __, actor in ipairs(actorOf[object]) do
if actor.identifier[keyword] then
return actor
end
end
return nil
end
elseif type(object) == "table" and object.isActor then
return object
end
return nil
end
--#region Actor
---@class Actor
local Actor = {
--Main:
isActor = nil, ---@type boolean
host = nil, ---@type any
anchor = nil, ---@type any
originalAnchor = nil, ---@type any
getOwner = nil, ---@type function
interactions = nil, ---@type function | table | nil
selfInteractions = nil, ---@type table
identifier = nil, ---@type table
visualizer = nil, ---@type effect
alreadyDestroyed = nil, ---@type boolean
causedCrash = nil, ---@type boolean
isSuspended = nil, ---@type boolean
identifierClass = nil, ---@type string
interactionsClass = nil, ---@type string
references = nil, ---@type table
periodicPair = nil, ---@type Pair
--Pairs:
firstPair = nil, ---@type table
lastPair = nil, ---@type table
nextPair = nil, ---@type table
previousPair = nil, ---@type table
--Coordinates:
x = nil, ---@type table
y = nil, ---@type table
z = nil, ---@type table
lastX = nil, ---@type number
lastY = nil, ---@type number
zOffset = nil, ---@type number
--Flags:
priority = nil, ---@type integer
index = nil, ---@type integer
isStationary = nil, ---@type boolean
unique = nil, ---@type integer
bindToBuff = nil, ---@type string | nil
persistOnDeath = nil, ---@type boolean
unit = nil, ---@type unit | nil
waitingForBuff = nil, ---@type boolean
bindToOrder = nil, ---@type integer | nil
onDestroy = nil, ---@type function | nil
isUnselectable = nil, ---@type boolean
--Cell interaction:
isGlobal = nil, ---@type boolean
usesCells = nil, ---@type boolean
halfWidth = nil, ---@type number
halfHeight = 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
isInCell = nil, ---@type boolean[]
nextInCell = nil, ---@type Actor[]
previousInCell = nil, ---@type Actor[]
cellsVisualized = nil, ---@type boolean
cellVisualizers = nil, ---@type lightning[]
}
---@param host any
---@param identifier string | string[]
---@param interactions table | nil
---@param flags table
---@return Actor | nil
Create = function(host, identifier, interactions, flags)
local identifierType = type(identifier)
local tempIdentifier = GetTable()
if identifierType == "string" then
tempIdentifier[1] = identifier
elseif identifierType == "table" then
for i = 1, #identifier do
tempIdentifier[i] = identifier[i]
end
else
if identifier == nil then
error("Object identifier is nil.")
else
error("Object identifier must be string or table, but was " .. identifierType)
end
end
local self = GetUnusedActor()
totalActors = totalActors + 1
self.unique = totalActors
self.causedCrash = nil
self.host = host or EMPTY_TABLE
if flags.anchor then
local anchor = flags.anchor
while type(anchor) == "table" and anchor.anchor do
CreateReference(self, anchor)
anchor = anchor.anchor --Sup dawg, I heard you like anchors.
end
self.anchor = anchor
CreateReference(self, anchor)
if host then
CreateReference(self, host)
end
elseif host then
self.anchor = host
CreateReference(self, host)
end
self.originalAnchor = self.anchor
--Execute onCreation functions before flags are initialized.
for __, keyword in ipairs(tempIdentifier) do
if onCreation.funcs[keyword] then
for __, func in ipairs(onCreation.funcs[keyword]) do
func(self.host)
end
end
end
--Add additional flags from onCreation hooks.
for __, keyword in ipairs(tempIdentifier) do
if onCreation.flags[keyword] then
local onCreationFlags = onCreation.flags[keyword]
for key, __ in pairs(OVERWRITEABLE_FLAGS) do
if onCreationFlags[key] then
if type(onCreationFlags[key]) == "function" then
additionalFlags[key] = onCreationFlags[key](host)
else
additionalFlags[key] = onCreationFlags[key]
end
end
end
end
end
--Transform identifier sequence into hashmap.
local onCreationIdentifiers
for __, keyword in ipairs(tempIdentifier) do
self.identifier[keyword] = true
if onCreation.identifiers[keyword] then
onCreationIdentifiers = GetTable()
for __, newIdentifier in ipairs(onCreation.identifiers[keyword]) do
if type(newIdentifier) == "function" then
onCreationIdentifiers[#onCreationIdentifiers + 1] = newIdentifier(self.host)
else
onCreationIdentifiers[#onCreationIdentifiers + 1] = newIdentifier
end
end
end
end
if onCreationIdentifiers then
for __, keyword in ipairs(onCreationIdentifiers) do
self.identifier[keyword] = true
end
end
--Copy interactions.
if interactions then
for keyword, func in pairs(interactions) do
if keyword ~= "self" then
self.interactions[keyword] = func
end
end
end
--Add additional interactions from onCreation hooks.
for keyword, __ in pairs(self.identifier) do
if onCreation.interactions[keyword] then
for target, func in pairs(onCreation.interactions[keyword]) do
self.interactions[target] = func
end
end
end
AssignActorClass(self, true, true)
self.zOffset = additionalFlags.zOffset or flags.zOffset or 0
SetOwnerFunc(self, host)
--Set or inherit stationary.
if objectIsStationary[self.anchor] then
self.isStationary = true
elseif additionalFlags.isStationary or flags.isStationary then
if not objectIsStationary[self.anchor] then
objectIsStationary[self.anchor] = true
if not actorOf[self.anchor].isActor then
for __, actor in ipairs(actorOf[self.anchor]) do
if actor ~= self then
SetStationary(actor, true)
end
end
end
end
self.isStationary = true
else
self.isStationary = nil
end
--Set coordinate getter functions.
SetCoordinateFuncs(self)
self.isGlobal = flags.isGlobal or (self.x == coord.globalXYZ or self.x == nil) or nil
self.usesCells = not self.isGlobal and not additionalFlags.hasInfiniteRange and not flags.hasInfiniteRange
if not self.isGlobal then
self.lastX = self.x[self.anchor]
self.lastY = self.y[self.anchor]
end
self.priority = additionalFlags.priority or flags.priority or 0
--Pair with global actors or all actors if self is global.
local selfFunc, actorFunc
for __, actor in ipairs(self.usesCells and celllessActorList or actorList) do
selfFunc = GetInteractionFunc(self, actor)
actorFunc = GetInteractionFunc(actor, self)
if selfFunc and actorFunc then
if self.priority < actor.priority then
CreatePair(actor, self, actorFunc)
else
CreatePair(self, actor, selfFunc)
end
elseif selfFunc then
CreatePair(self, actor, selfFunc)
elseif actorFunc then
CreatePair(actor, self, actorFunc)
end
end
--Create self-interactions.
local selfInteractions = interactions and interactions.self or flags.selfInteractions
if selfInteractions then
if type(selfInteractions) == "table" then
for __, func in ipairs(selfInteractions) do
self.selfInteractions[func] = CreatePair(self, SELF_INTERACTION_ACTOR, func)
end
else
self.selfInteractions[selfInteractions] = CreatePair(self, SELF_INTERACTION_ACTOR, selfInteractions)
end
self.interactions.self = nil
end
--Add additional self-interactions from onCreation hooks.
for __, keyword in ipairs(tempIdentifier) do
if onCreation.selfInteractions[keyword] then
for __, func in ipairs(onCreation.selfInteractions[keyword]) do
self.selfInteractions[func] = CreatePair(self, SELF_INTERACTION_ACTOR, func)
end
end
end
--Add additional self-interactions from onCreation hooks to onCreation identifiers.
if onCreationIdentifiers then
for __, keyword in ipairs(onCreationIdentifiers) do
if onCreation.selfInteractions[keyword] then
for __, func in ipairs(onCreation.selfInteractions[keyword]) do
self.selfInteractions[func] = CreatePair(self, SELF_INTERACTION_ACTOR, func)
end
end
end
ReturnTable(onCreationIdentifiers)
end
--Set actor size and initialize cells and cell checks.
if not self.isGlobal then
if flags.width then
self.halfWidth = flags.width/2
if flags.height then
self.halfHeight = flags.height/2
else
Warning("|cffff0000Warning:|r width flag set for actor, but not height flag.")
self.halfHeight = flags.width/2
end
else
local radius = additionalFlags.radius or flags.radius
if radius then
self.halfWidth = radius
self.halfHeight = radius
else
self.halfWidth = config.DEFAULT_OBJECT_RADIUS
self.halfHeight = config.DEFAULT_OBJECT_RADIUS
end
end
InitCells(self)
if self.isStationary then
self.nextCellCheck = DO_NOT_EVALUATE
local interval = additionalFlags.cellCheckInterval or flags.cellCheckInterval or config.DEFAULT_CELL_CHECK_INTERVAL
self.cellCheckInterval = min(MAX_STEPS, max(1, (interval*INV_MIN_INTERVAL) // 1 + 1))
else
InitCellChecks(self, additionalFlags.cellCheckInterval or flags.cellCheckInterval or config.DEFAULT_CELL_CHECK_INTERVAL)
end
end
--Create onDeath trigger.
self.persistOnDeath = flags.persistOnDeath
if (HandleType[self.anchor] == "destructable" or HandleType[self.anchor] == "item") and widgets.deathTriggers[self.anchor] == nil then
widgets.deathTriggers[self.anchor] = CreateTrigger()
TriggerRegisterDeathEvent(widgets.deathTriggers[self.anchor], self.anchor)
if HandleType[self.anchor] == "destructable" then
TriggerAddAction(widgets.deathTriggers[self.anchor], OnDestructableDeath)
else
TriggerAddAction(widgets.deathTriggers[self.anchor], OnItemDeath)
end
end
--Create binds.
if flags.bindToBuff then
CreateBinds(self, flags.bindToBuff, nil)
elseif flags.bindToOrder then
CreateBinds(self, nil, flags.bindToOrder)
end
--Misc.
self.onDestroy = additionalFlags.onActorDestroy or flags.onActorDestroy
if debug.visualizeAllActors and not self.isGlobal then
CreateVisualizer(self)
end
self.alreadyDestroyed = nil
actorList[#actorList + 1] = self
if not self.usesCells then
celllessActorList[#celllessActorList + 1] = self
end
self.index = #actorList
self.isUnselectable = additionalFlags.isUnselectable or flags.isUnselectable
for key, __ in pairs(additionalFlags) do
additionalFlags[key] = nil
end
ReturnTable(tempIdentifier)
return self
end
Destroy = function(self)
if self == nil or self.alreadyDestroyed then
return
end
self.alreadyDestroyed = true
destroyedActors[#destroyedActors + 1] = self
if self.onDestroy then
self.onDestroy(self.host)
self.onDestroy = nil
end
if self.index then
actorList[#actorList].index = self.index
actorList[self.index] = actorList[#actorList]
actorList[#actorList] = nil
end
if not self.usesCells then
for i, actor in ipairs(celllessActorList) do
if self == actor then
celllessActorList[i] = celllessActorList[#celllessActorList]
celllessActorList[#celllessActorList] = nil
break
end
end
end
for key, __ in pairs(self.interactions) do
self.interactions[key] = nil
end
for key, __ in pairs(self.identifier) do
self.identifier[key] = nil
end
for key, __ in pairs(self.selfInteractions) do
self.selfInteractions[key] = nil
end
local next = self.nextPair
local pair = next[self.firstPair]
while pair do
pair[DESTRUCTION_QUEUED] = true
pair = next[pair]
end
for key, __ in pairs(pairingExcluded[self]) do
pairingExcluded[self][key] = nil
pairingExcluded[key][self] = nil
end
if not self.isGlobal then
local nextCheck = self.nextCellCheck
if nextCheck ~= DO_NOT_EVALUATE then
local actorAtHighestPosition = cellCheckedActors[nextCheck][numCellChecks[nextCheck]]
actorAtHighestPosition.positionInCellCheck = self.positionInCellCheck
cellCheckedActors[nextCheck][self.positionInCellCheck] = actorAtHighestPosition
numCellChecks[nextCheck] = numCellChecks[nextCheck] - 1
end
for X = self.minX, self.maxX do
for Y = self.minY, self.maxY do
RemoveCell(CELL_LIST[X][Y], self)
end
end
end
for object, __ in pairs(self.references) do
RemoveReference(self, object)
end
if self.host ~= EMPTY_TABLE then
self.host = nil
self.x[self.anchor] = nil
self.y[self.anchor] = nil
self.z[self] = nil
self.anchor = nil
end
if self.cellsVisualized then
for __, bolt in ipairs(self.cellVisualizers) do
DestroyLightning(bolt)
end
self.cellsVisualized = nil
end
if debug.visualizeAllActors and not self.isGlobal then
DestroyEffect(self.visualizer)
end
if self == debug.selectedActor then
DestroyEffect(self.visualizer)
debug.selectedActor = nil
end
self.x = nil
self.y = nil
self.z = nil
self.lastX = nil
self.lastY = nil
self.bindToBuff = nil
self.bindToOrder = nil
self.isSuspended = nil
end
---Create a reference to the actor. If more than one actor, transform into a table and store actors in a sequence.
CreateReference = function(self, object)
if actorOf[object] == nil then
actorOf[object] = self
elseif actorOf[object].isActor then
actorOf[object] = {actorOf[object], self}
else
actorOf[object][#actorOf[object] + 1] = self
end
self.references[object] = true
end
RemoveReference = function(self, object)
if actorOf[object].isActor 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
self.references[object] = nil
end
SetCoordinateFuncs = function(self)
if self.anchor ~= nil then
if IsHandle[self.anchor] then
local type = HandleType[self.anchor]
if type == "unit" then
self.x = coord.unitX
self.y = coord.unitY
self.z = coord.unitZ
elseif type == "destructable" then
self.x = coord.destructableX
self.y = coord.destructableY
self.z = coord.destructableZ
elseif type == "item" then
self.x = coord.itemX
self.y = coord.itemY
self.z = coord.itemZ
else
self.x = coord.globalXYZ
self.y = coord.globalXYZ
self.z = coord.globalXYZ
end
elseif self.anchor.x then
self.x = coord.classX
self.y = coord.classY
if self.anchor.z then
self.z = coord.classZ
else
self.z = coord.terrainZ
end
else
self.x = coord.globalXYZ
self.y = coord.globalXYZ
self.z = coord.globalXYZ
end
self.x[self.anchor] = nil
self.y[self.anchor] = nil
self.z[self] = nil
end
end
SetOwnerFunc = function(self, source)
if source then
if IsHandle[source] then
if HandleType[source] == "unit" then
local owner = GetOwningPlayer(source)
unitOwnerFunc[owner] = unitOwnerFunc[owner] or function() return owner end
self.getOwner = unitOwnerFunc[owner]
else
self.getOwner = DoNothing
end
elseif type(source) == "table" then
if type(source.owner) == "number" then
self.getOwner = GetClassOwnerById
elseif source.owner then
self.getOwner = GetClassOwner
else
self.getOwner = DoNothing
end
end
end
end
InitCells = function(self)
local x = self.x[self.anchor]
local y = self.y[self.anchor]
self.minX = min(NUM_CELLS_X, max(1, (NUM_CELLS_X*(x - self.halfWidth - MAP_MIN_X)/MAP_SIZE_X) // 1 + 1))
self.minY = min(NUM_CELLS_Y, max(1, (NUM_CELLS_Y*(y - self.halfHeight - MAP_MIN_Y)/MAP_SIZE_Y) // 1 + 1))
self.maxX = min(NUM_CELLS_X, max(1, (NUM_CELLS_X*(x + self.halfWidth - MAP_MIN_X)/MAP_SIZE_X) // 1 + 1))
self.maxY = min(NUM_CELLS_Y, max(1, (NUM_CELLS_Y*(y + self.halfHeight - MAP_MIN_Y)/MAP_SIZE_Y) // 1 + 1))
for key, __ in pairs(actorAlreadyChecked) do
actorAlreadyChecked[key] = nil
end
actorAlreadyChecked[self] = true
for X = self.minX, self.maxX do
for Y = self.minY, self.maxY do
EnterCell(CELL_LIST[X][Y], self)
end
end
end
InitCellChecks = function(self, interval)
self.cellCheckInterval = min(MAX_STEPS, max(1, (interval*INV_MIN_INTERVAL) // 1 + 1))
local nextStep = cycle.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
AssignActorClass = function(self, doIdentifier, doInteractions)
--Concatenates all identifiers and interaction table keys to generate a unique string for an interactionFunc lookup table.
if doIdentifier then
local i = 1
local identifierClass = GetTable()
for id, __ in pairs(self.identifier) do
identifierClass[i] = id
i = i + 1
end
sort(identifierClass)
self.identifierClass = concat(identifierClass)
pairingFunctions[self.identifierClass] = pairingFunctions[self.identifierClass] or {}
ReturnTable(identifierClass)
end
if doInteractions then
local j = 1
local first, entry
local interactionsClass = GetTable()
for target, func in pairs(self.interactions) do
if type(target) == "string" then
if not functionKey[func] then
highestFunctionKey = highestFunctionKey + 1
functionKey[func] = highestFunctionKey
end
interactionsClass[j] = target .. functionKey[func]
else
first = true
entry = ""
for __, subtarget in ipairs(target) do
if not first then
entry = entry .. "+"
else
first = false
end
if not functionKey[func] then
highestFunctionKey = highestFunctionKey + 1
functionKey[func] = highestFunctionKey
end
entry = entry .. subtarget
end
interactionsClass[j] = entry .. functionKey[func]
end
j = j + 1
end
sort(interactionsClass)
self.interactionsClass = concat(interactionsClass)
ReturnTable(interactionsClass)
end
end
--Repair with all actors currently in interaction range.
Flicker = function(self)
if self.alreadyDestroyed then
return
end
if not self.isGlobal then
for key, __ in pairs(actorAlreadyChecked) do
actorAlreadyChecked[key] = nil
end
actorAlreadyChecked[self] = true
for cell, __ in pairs(self.isInCell) do
LeaveCell(cell, self)
end
InitCells(self)
if self.cellsVisualized then
RedrawCellVisualizers(self)
end
end
local selfFunc, actorFunc
for __, actor in ipairs(self.usesCells and celllessActorList or actorList) do
if not pairList[actor][self] and not pairList[self][actor] then
selfFunc = GetInteractionFunc(self, actor)
actorFunc = GetInteractionFunc(actor, self)
if selfFunc and actorFunc then
if self.priority < actor.priority then
CreatePair(actor, self, actorFunc)
else
CreatePair(self, actor, selfFunc)
end
elseif selfFunc then
CreatePair(self, actor, selfFunc)
elseif actorFunc then
CreatePair(actor, self, actorFunc)
end
end
end
end
SharesCellWith = function(self, actor)
if self.halfWidth < actor.halfWidth then
for cellA in pairs(self.isInCell) do
if actor.isInCell[cellA] then
return true
end
end
return false
else
for cellB in pairs(actor.isInCell) do
if self.isInCell[cellB] then
return true
end
end
return false
end
end
CreateBinds = function(self, bindToBuff, bindToOrder)
if bindToBuff then
self.bindToBuff = type(bindToBuff) == "number" and bindToBuff or FourCC(bindToBuff)
self.waitingForBuff = true
insert(widgets.bindChecks, self)
elseif bindToOrder then
self.bindToOrder = type(bindToOrder) == "number" and bindToOrder or OrderId(bindToOrder)
insert(widgets.bindChecks, self)
end
if HandleType[self.host] == "unit" then
self.unit = self.host
elseif HandleType[self.anchor] == "unit" 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 or anchor.")
end
end
DestroyObsoletePairs = function(self)
local ACTOR_A = ACTOR_A
local ACTOR_B = ACTOR_B
if self.alreadyDestroyed then
return
end
local actor
local next = self.nextPair
local pair = next[self.firstPair]
local thisPair
while pair do
if pair[ACTOR_B] ~= SELF_INTERACTION_ACTOR then
if self == pair[ACTOR_A] then
actor = pair[ACTOR_B]
else
actor = pair[ACTOR_A]
end
if not actor.alreadyDestroyed and not GetInteractionFunc(self, actor) and not GetInteractionFunc(actor, self) then
thisPair = pair
pair = next[pair]
DestroyPair(thisPair)
else
pair = next[pair]
end
else
pair = next[pair]
end
end
end
Unpause = function(self, whichFunctions)
local actorA, actorB, nextStep
local INTERACTION_FUNC = INTERACTION_FUNC
local POSITION_IN_STEP = POSITION_IN_STEP
local CURRENT_POSITION = CURRENT_POSITION
local ACTOR_A = ACTOR_A
local ACTOR_B = ACTOR_B
local EVERY_STEP = EVERY_STEP
local DO_NOT_EVALUATE = DO_NOT_EVALUATE
local CYCLE_LENGTH = CYCLE_LENGTH
local next = self.nextPair
local pair = next[self.firstPair]
while pair do
if whichFunctions == nil or whichFunctions[pair[INTERACTION_FUNC]] then
actorA = pair[ACTOR_A]
actorB = pair[ACTOR_B]
if pair[EVERY_STEP] then
if pair[PREVIOUS] == nil and (not actorA.usesCells or not actorB.usesCells or SharesCellWith(actorA, actorB)) then
AddPairToEveryStepList(pair)
end
else
if pair[CURRENT_POSITION] == DO_NOT_EVALUATE and (not actorA.usesCells or not actorB.usesCells or SharesCellWith(actorA, actorB)) then
nextStep = cycle.counter + 1
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = pair
pair[CURRENT_POSITION] = nextStep
pair[POSITION_IN_STEP] = numPairs[nextStep]
end
end
pair[PAUSED] = nil
end
pair = next[pair]
end
end
SetStationary = function(self, enable)
local INTERACTION_FUNC = INTERACTION_FUNC
local ACTOR_A = ACTOR_A
if (self.isStationary == true) == enable then
return
end
self.isStationary = enable
if enable 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
self.nextCellCheck = DO_NOT_EVALUATE
local next = self.nextPair
local thisPair = next[self.firstPair]
while thisPair do
if functionPauseOnStationary[thisPair[INTERACTION_FUNC]] and self == thisPair[ACTOR_A] then
AddDelayedCallback(PausePair, thisPair)
end
thisPair = next[thisPair]
end
else
local nextStep = cycle.counter + 1
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]
AddDelayedCallback(Unpause, self, functionPauseOnStationary)
end
SetCoordinateFuncs(self)
end
---For debug mode.
VisualizeCells = function(self, 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])
elseif not self.isGlobal then
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
---For debug mode.
RedrawCellVisualizers = function(self)
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
---Called when an object is loaded into a transport actor crashes a thread.
Suspend = function(self, enable)
if enable then
local pair
for __, actor in ipairs(actorList) do
pair = pairList[actor][self] or pairList[self][actor]
if pair and not functionIsUnsuspendable[pair[INTERACTION_FUNC]] then
DestroyPair(pair)
end
end
self.isSuspended = true
else
self.isSuspended = false
AddDelayedCallback(Flicker, self)
end
end
---For debug mode.
Deselect = function(self)
debug.selectedActor = nil
if not debug.visualizeAllActors then
DestroyEffect(self.visualizer)
end
VisualizeCells(self, false)
BlzFrameSetVisible(debug.tooltip, false)
end
---For debug mode.
GetDescription = function(self)
local description = setmetatable({}, {__add = function(old, new) old[#old + 1] = new return old end})
description = description + "|cffffcc00Identifiers:|r "
local first = true
for key, __ in pairs(self.identifier) do
if not first then
description = description + ", "
else
first = false
end
description = description + key
end
if self.host ~= EMPTY_TABLE then
description = description + "\n\n|cffffcc00Host:|r " + Object2String(self.host)
end
if self.originalAnchor ~= self.host then
description = description + "\n|cffffcc00Anchor:|r " + Object2String(self.originalAnchor)
end
description = description + "\n|cffffcc00Interactions:|r "
first = true
for key, func in pairs(self.interactions) do
if not first then
description = description + ", "
end
if type(key) == "string" then
description = description + key + " - " + Function2String(func)
else
local subFirst = true
for __, word in ipairs(key) do
if not subFirst then
description = description + " + "
end
description = description + word
subFirst = false
end
description = description + " - " + Function2String(func)
end
first = false
end
if next(self.selfInteractions) then
description = description + "\n|cffffcc00Self-Interactions:|r "
first = true
for key, __ in pairs(self.selfInteractions) do
if not first then
description = description + ", "
end
first = false
description = description + Function2String(key)
end
end
if self.priority ~= 0 then
description = description + "\n|cffffcc00Priority:|r " + self.priority
end
if self.cellCheckInterval and math.abs(self.cellCheckInterval*config.MIN_INTERVAL - config.DEFAULT_CELL_CHECK_INTERVAL) > 0.001 then
description = description + "\n|cffffcc00Cell Check Interval:|r " + self.cellCheckInterval*config.MIN_INTERVAL
end
if self.isStationary then
description = description + "\n|cffffcc00Stationary:|r true"
end
if not self.isGlobal and not self.usesCells then
description = description + "\n|cffffcc00Has infinite range:|r true"
end
if self.halfWidth and self.halfWidth ~= config.DEFAULT_OBJECT_RADIUS then
if self.halfWidth ~= self.halfHeight then
description = description + "\n|cffffcc00Width:|r " + 2*self.halfWidth
description = description + "\n|cffffcc00Height:|r " + 2*self.halfHeight
else
description = description + "\n|cffffcc00Radius:|r " + self.halfWidth
end
end
if self.getOwner(self.host) then
description = description + "\n|cffffcc00Owner:|r Player " + (GetPlayerId(self.getOwner(self.host)) + 1)
end
if self.bindToBuff then
description = description + "\n|cffffcc00Bound to buff:|r " + string.pack(">I4", self.bindToBuff)
if self.waitingForBuff then
description = description + " |cffaaaaaa(waiting for buff to be applied)|r"
end
end
if self.bindToOrder then
description = description + "\n|cffffcc00Bound to order:|r " + OrderId2String(self.bindToOrder) + " |cffaaaaaa(current order = " + OrderId2String(GetUnitCurrentOrder(self.anchor)) + ")|r"
end
if self.onDestroy then
description = description + "\n|cffffcc00On Destroy:|r " + Function2String(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 = {}
local nextPair = self.nextPair
local pair = nextPair[self.firstPair]
while pair do
if pair[ACTOR_B] ~= SELF_INTERACTION_ACTOR then
if pair[ACTOR_A] == self then
numOutgoing = numOutgoing + 1
outgoingFuncs[pair[INTERACTION_FUNC]] = (outgoingFuncs[pair[INTERACTION_FUNC]] or 0) + 1
elseif pair[ACTOR_B] == self then
numIncoming = numIncoming + 1
incomingFuncs[pair[INTERACTION_FUNC]] = (incomingFuncs[pair[INTERACTION_FUNC]] or 0) + 1
else
hasError = true
end
end
pair = nextPair[pair]
end
description = description + "\n|cffffcc00Outgoing pairs:|r " + numOutgoing
if numOutgoing > 0 then
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" + Function2String(key)
first = false
end
description = description + ")|r"
end
description = description + "\n|cffffcc00Incoming pairs:|r " + numIncoming
if numIncoming > 0 then
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" + Function2String(key)
first = false
end
description = description + ")|r"
end
if not self.isGlobal then
local x, y = self.x[self.anchor], self.y[self.anchor]
description = description + "\n\n|cffffcc00x:|r " + x
description = description + "\n|cffffcc00y:|r " + y
description = description + "\n|cffffcc00z:|r " + self.z[self]
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 next(debug.trackedVariables) then
description = description + "\n\n|cffff0000Tracked variables:|r"
for key, __ in pairs(debug.trackedVariables) do
if type(self.host) == "table" and self.host[key] then
description = description + "\n|cffffcc00" + key + "|r: " + tostring(self.host[key])
end
if self.host ~= self.anchor and type(self.anchor) == "table" and self.anchor[key] then
description = description + "\n|cffffcc00" + key + "|r: " + tostring(self.host[key])
end
if _G[key] then
if _G[key][self.host] then
description = description + "\n|cffffcc00" + key + "|r: " + tostring(_G[key][self.host])
end
if self.host ~= self.anchor and _G[key][self.anchor] then
description = description + "\n|cffffcc00" + key + "|r: " + tostring(_G[key][self.anchor])
end
end
end
end
local str = concat(description)
if self.isGlobal then
return str, "|cff00bb00Global Actor|r"
else
if numOutgoing == 0 and numIncoming == 0 then
return str, "|cffaaaaaaUnpaired Actor|r"
elseif numOutgoing == 0 then
return str, "|cffffc0cbFemale Actor|r"
elseif numIncoming == 0 then
return str, "|cff90b5ffMale Actor|r"
else
return str, "|cffffff00Hybrid Actor|r"
end
end
end
---For debug mode.
Select = function(self)
debug.selectedActor = self
local description, title = GetDescription(self)
BlzFrameSetText(debug.tooltipText, description)
BlzFrameSetText(debug.tooltipTitle, title )
BlzFrameSetSize(debug.tooltipText, 0.28, 0.0)
BlzFrameSetSize(debug.tooltip, 0.29, BlzFrameGetHeight(debug.tooltipText) + 0.0315)
BlzFrameSetVisible(debug.tooltip, true)
if not self.isGlobal then
VisualizeCells(self, true)
if not self.isGlobal and not debug.visualizeAllActors then
CreateVisualizer(self)
end
end
end
---For debug mode.
CreateVisualizer = function(self)
local x, y = self.x[self.anchor], self.y[self.anchor]
self.visualizer = AddSpecialEffect("Abilities\\Spells\\Other\\Aneu\\AneuTarget.mdl", x, y)
BlzSetSpecialEffectColorByPlayer(self.visualizer, self.getOwner(self.host) or Player(21))
BlzSetSpecialEffectZ(self.visualizer, self.z[self] + 75)
end
--#endregion
--Stub actors are used by periodic callers.
CreateStub = function(host)
local actor = GetUnusedActor()
actor.host = host
actor.anchor = host
actor.isGlobal = true
actor.x = coord.globalXYZ
actor.y = coord.globalXYZ
actor.z = coord.globalXYZ
actor.unique = 0
actorOf[host] = actor
return actor
end
DestroyStub = function(self)
if self == nil or self.alreadyDestroyed then
return
end
self.periodicPair = nil
actorOf[self.host] = nil
self.host = nil
self.anchor = nil
self.isGlobal = nil
self.x = nil
self.y = nil
self.z = nil
self.alreadyDestroyed = true
unusedActors[#unusedActors + 1] = self
end
local SetFlag = {
radius = function(self, radius)
self.halfWidth = radius
self.halfHeight = radius
AddDelayedCallback(Flicker, self)
end,
anchor = function(self, anchor)
if anchor == self.originalAnchor then
return
end
for object, __ in pairs(self.references) do
if object ~= self.host then
RemoveReference(self, object)
end
end
if anchor then
while type(anchor) == "table" and anchor.anchor do
CreateReference(self, anchor)
anchor = anchor.anchor
end
self.anchor = anchor
self.originalAnchor = self.anchor
CreateReference(self, anchor)
SetCoordinateFuncs(self)
else
local oldAnchor = self.anchor
self.anchor = self.host
self.originalAnchor = self.anchor
if type(self.host) == "table" then
self.host.x, self.host.y, self.host.z = ALICE_GetCoordinates3D(oldAnchor)
end
SetCoordinateFuncs(self)
end
AddDelayedCallback(Flicker, self)
end,
width = function(self, width)
self.halfWidth = width/2
AddDelayedCallback(Flicker, self)
end,
height = function(self, height)
self.halfHeight = height/2
AddDelayedCallback(Flicker, self)
end,
cellCheckInterval = function(self, cellCheckInterval)
self.cellCheckInterval = min(MAX_STEPS, max(1, (cellCheckInterval*INV_MIN_INTERVAL) // 1 + 1))
end,
onActorDestroy = function(self, onActorDestroy)
self.onActorDestroy = onActorDestroy
end,
isUnselectable = function(self, isUnselectable)
self.isUnselectable = isUnselectable
end,
persistOnDeath = function(self, persistOnDeath)
self.persistOnDeath = persistOnDeath
end,
priority = function(self, priority)
self.priority = priority
end,
zOffset = function(self, zOffset)
self.zOffset = zOffset
self.z[self] = nil
end,
bindToBuff = function(self, buff)
if self.bindToBuff then
self.bindToBuff = type(buff) == "number" and buff or FourCC(buff)
else
CreateBinds(self, buff, nil)
end
end,
bindToOrder = function(self, order)
if self.bindToOrder then
self.bindToorder = type(order) == "number" and order or OrderId(order)
else
CreateBinds(self, nil, order)
end
end
}
--===========================================================================================================================================================
--Cell Class
--===========================================================================================================================================================
--#region Cell
---@class Cell
local Cell = {
horizontalLightning = nil, ---@type lightning
verticalLightning = nil, ---@type lightning
first = nil, ---@type Actor
last = nil, ---@type Actor
numActors = nil ---@type integer
}
EnterCell = function(self, actorA)
local aFunc, bFunc
actorA.isInCell[self] = true
actorA.nextInCell[self] = nil
actorA.previousInCell[self] = self.last
if self.first == nil then
self.first = actorA
else
self.last.nextInCell[self] = actorA
end
self.last = actorA
if actorA.hasInfiniteRange then
return
end
local POSITION_IN_STEP = POSITION_IN_STEP
local CURRENT_POSITION = CURRENT_POSITION
local EVERY_STEP = EVERY_STEP
local INTERACTION_FUNC = INTERACTION_FUNC
local DO_NOT_EVALUATE = DO_NOT_EVALUATE
local CYCLE_LENGTH = CYCLE_LENGTH
local PAUSED = PAUSED
local PREVIOUS = PREVIOUS
local actorB = self.first
for __ = 1, self.numActors do
if not actorAlreadyChecked[actorB] then
actorAlreadyChecked[actorB] = true
local thisPair = pairList[actorA][actorB] or pairList[actorB][actorA]
if thisPair then
if not thisPair[PAUSED] then
if thisPair[EVERY_STEP] then
if thisPair[PREVIOUS] == nil then
AddPairToEveryStepList(thisPair)
end
elseif thisPair[CURRENT_POSITION] == DO_NOT_EVALUATE then
local nextStep
if functionDelay[INTERACTION_FUNC] then
local interactionFunc = thisPair[INTERACTION_FUNC]
if functionDelayIsDistributed[interactionFunc] then
functionDelayCurrent[interactionFunc] = functionDelay[interactionFunc] + config.MIN_INTERVAL
if functionDelayCurrent[interactionFunc] > functionDelay[interactionFunc] then
functionDelayCurrent[interactionFunc] = functionDelayCurrent[interactionFunc] - functionDelay[interactionFunc]
end
nextStep = cycle.counter + (functionDelayCurrent[interactionFunc]*INV_MIN_INTERVAL + 1) // 1
else
nextStep = cycle.counter + (functionDelay[interactionFunc]*INV_MIN_INTERVAL + 1) // 1
end
else
nextStep = cycle.counter + 1
end
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = thisPair
thisPair[CURRENT_POSITION] = nextStep
thisPair[POSITION_IN_STEP] = numPairs[nextStep]
end
end
elseif not pairingExcluded[actorA][actorB] then
aFunc = GetInteractionFunc(actorA, actorB)
if aFunc then
if actorA.priority < actorB.priority then
bFunc = GetInteractionFunc(actorB, actorA)
if bFunc then
CreatePair(actorB, actorA, bFunc)
else
CreatePair(actorA, actorB, aFunc)
end
else
CreatePair(actorA, actorB, aFunc)
end
else
bFunc = GetInteractionFunc(actorB, actorA)
if bFunc then
CreatePair(actorB, actorA, bFunc)
end
end
end
end
actorB = actorB.nextInCell[self]
end
self.numActors = self.numActors + 1
end
RemoveCell = function(self, actorA)
if self.first == actorA then
self.first = actorA.nextInCell[self]
else
actorA.previousInCell[self].nextInCell[self] = actorA.nextInCell[self]
end
if self.last == actorA then
self.last = actorA.previousInCell[self]
else
actorA.nextInCell[self].previousInCell[self] = actorA.previousInCell[self]
end
actorA.isInCell[self] = nil
self.numActors = self.numActors - 1
end
LeaveCell = function(self, actorA, wasLoaded)
RemoveCell(self, actorA)
if actorA.hasInfiniteRange then
return
end
local POSITION_IN_STEP = POSITION_IN_STEP
local CURRENT_POSITION = CURRENT_POSITION
local EVERY_STEP = EVERY_STEP
local INTERACTION_FUNC = INTERACTION_FUNC
local DO_NOT_EVALUATE = DO_NOT_EVALUATE
local HAD_CONTACT = HAD_CONTACT
local PREVIOUS = PREVIOUS
local actorB = self.first
for __ = 1, self.numActors do
if not actorAlreadyChecked[actorB] then
actorAlreadyChecked[actorB] = true
local thisPair = pairList[actorA][actorB] or pairList[actorB][actorA]
if thisPair then
if thisPair[EVERY_STEP] then
if thisPair[PREVIOUS] and (((actorA.maxX < actorB.minX or actorA.minX > actorB.maxX or actorA.maxY < actorB.minY or actorA.minY > actorB.maxY) and not functionIsUnbreakable[thisPair[INTERACTION_FUNC]]) or wasLoaded) and actorB.usesCells then
RemovePairFromEveryStepList(thisPair)
if thisPair[HAD_CONTACT] then
if functionOnReset[thisPair[INTERACTION_FUNC]] and not cycle.isCrash then
local tempPair = currentPair
currentPair = thisPair
functionOnReset[thisPair[INTERACTION_FUNC]](thisPair[HOST_A], thisPair[HOST_B], thisPair[USER_DATA], false)
currentPair = tempPair
end
thisPair[HAD_CONTACT] = nil
end
if functionOnBreak[thisPair[INTERACTION_FUNC]] then
local tempPair = currentPair
currentPair = thisPair
functionOnBreak[thisPair[INTERACTION_FUNC]](thisPair[HOST_A], thisPair[HOST_B], thisPair[USER_DATA], false)
currentPair = tempPair
end
end
elseif thisPair[CURRENT_POSITION] ~= 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 functionIsUnbreakable[thisPair[INTERACTION_FUNC]] and actorB.usesCells then
whichPairs[thisPair[CURRENT_POSITION]][thisPair[POSITION_IN_STEP]] = DUMMY_PAIR
local nextStep = DO_NOT_EVALUATE
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = thisPair
thisPair[CURRENT_POSITION] = nextStep
thisPair[POSITION_IN_STEP] = numPairs[nextStep]
if thisPair[HAD_CONTACT] then
if functionOnReset[thisPair[INTERACTION_FUNC]] and not cycle.isCrash then
local tempPair = currentPair
currentPair = thisPair
functionOnReset[thisPair[INTERACTION_FUNC]](thisPair[HOST_A], thisPair[HOST_B], thisPair[USER_DATA], false)
currentPair = tempPair
end
thisPair[HAD_CONTACT] = nil
end
if functionOnBreak[thisPair[INTERACTION_FUNC]] then
local tempPair = currentPair
currentPair = thisPair
functionOnBreak[thisPair[INTERACTION_FUNC]](thisPair[HOST_A], thisPair[HOST_B], thisPair[USER_DATA], false)
currentPair = tempPair
end
end
end
end
actorB = actorB.nextInCell[self]
end
end
--#endregion
--===========================================================================================================================================================
--Repair
--===========================================================================================================================================================
--#region Repair
local function RepairCycle(firstPosition)
local numSteps
local nextStep
--Variable Step Cycle
local returnValue
local pairsThisStep = whichPairs[cycle.counter]
for i = firstPosition, numPairs[cycle.counter] do
currentPair = pairsThisStep[i]
if currentPair[DESTRUCTION_QUEUED] then
if currentPair ~= DUMMY_PAIR then
nextStep = cycle.counter + MAX_STEPS
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = currentPair
currentPair[CURRENT_POSITION] = nextStep
currentPair[POSITION_IN_STEP] = numPairs[nextStep]
end
else
returnValue = currentPair[INTERACTION_FUNC](currentPair[HOST_A], currentPair[HOST_B])
if returnValue then
numSteps = (returnValue*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
nextStep = cycle.counter + numSteps
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = currentPair
currentPair[CURRENT_POSITION] = nextStep
currentPair[POSITION_IN_STEP] = numPairs[nextStep]
else
AddPairToEveryStepList(currentPair)
functionIsEveryStep[currentPair[INTERACTION_FUNC]] = true
currentPair[EVERY_STEP] = true
end
end
end
numPairs[cycle.counter] = 0
currentPair = OUTSIDE_OF_CYCLE
end
local function OnCrash()
local crashingPair = currentPair
--Remove pair and continue with cycle after the crashing pair.
local A = crashingPair[ACTOR_A]
local B = crashingPair[ACTOR_B]
pairingExcluded[A][B] = true
pairingExcluded[B][A] = true
if B == SELF_INTERACTION_ACTOR then
Warning("\n|cffff0000Error:|r ALICE Cycle crashed during last execution. The identifier of the actor responsible is "
.. "|cffffcc00" .. Identifier2String(A.identifier) .. "|r. Unique number: " .. A.unique .. ". The crash occured during self-interaction with function |cffaaaaff" .. Function2String(crashingPair[INTERACTION_FUNC]) .. "|r. The interaction has been disabled.")
else
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.")
end
if not crashingPair[EVERY_STEP] then
local nextPosition = crashingPair[POSITION_IN_STEP] + 1
numPairs[DO_NOT_EVALUATE] = numPairs[DO_NOT_EVALUATE] + 1
whichPairs[DO_NOT_EVALUATE][numPairs[DO_NOT_EVALUATE]] = crashingPair
crashingPair[CURRENT_POSITION] = DO_NOT_EVALUATE
crashingPair[POSITION_IN_STEP] = numPairs[DO_NOT_EVALUATE]
cycle.isCrash = true
DestroyPair(crashingPair)
RepairCycle(nextPosition)
else
cycle.isCrash = true
DestroyPair(crashingPair)
end
--If this is the second time the same actor caused a crash, isolate it to prevent it from causing further crashes.
if A.causedCrash then
Warning("\nActor with identifier " .. Identifier2String(A.identifier) .. ", unique number: " .. A.unique .. " is repeatedly causing crashes. Isolating...")
Suspend(A)
elseif B.causedCrash and B ~= SELF_INTERACTION_ACTOR then
Warning("\nActor with identifier " .. Identifier2String(B.identifier) .. ", unique number: " .. B.unique .. " is repeatedly causing crashes. Isolating...")
Suspend(B)
end
A.causedCrash = true
B.causedCrash = true
cycle.isCrash = false
end
--#endregion
--===========================================================================================================================================================
--Main Functions
--===========================================================================================================================================================
--#region Main Functions
local function ResetCoordinateLookupTables()
local classX, classY = coord.classX, coord.classY
for key, __ in pairs(classX) do
classX[key], classY[key] = nil, nil
end
local classZ = coord.classZ
for key, __ in pairs(classZ) do
classZ[key] = nil
end
local unitX, unitY = coord.unitX, coord.unitY
for key, __ in pairs(unitX) do
unitX[key], unitY[key] = nil, nil
end
local unitZ = coord.unitZ
for key, __ in pairs(unitZ) do
unitZ[key] = nil
end
if not config.ITEMS_ARE_STATIONARY then
local itemX, itemY = coord.itemX, coord.itemY
for key, __ in pairs(itemX) do
itemX[key], itemY[key] = nil, nil
end
local itemZ = coord.itemZ
for key, __ in pairs(itemZ) do
itemZ[key] = nil
end
end
local terrainZ = coord.terrainZ
for key, __ in pairs(terrainZ) do
terrainZ[key] = nil
end
end
local function BindChecks()
for i = #widgets.bindChecks, 1, -1 do
local actor = widgets.bindChecks[i]
if actor.bindToBuff 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
Destroy(actor)
widgets.bindChecks[i] = widgets.bindChecks[#widgets.bindChecks]
widgets.bindChecks[#widgets.bindChecks] = nil
end
elseif actor.bindToOrder then
if GetUnitCurrentOrder(actor.unit) ~= actor.bindToOrder then
Destroy(actor)
widgets.bindChecks[i] = widgets.bindChecks[#widgets.bindChecks]
widgets.bindChecks[#widgets.bindChecks] = nil
end
end
end
end
---All destroyed pairs are only flagged and not destroyed until main cycle completes. This function destroys all pairs in one go.
local function RemovePairsFromCycle()
for i = #destroyedActors, 1, -1 do
local actor = destroyedActors[i]
if actor then
local firstPair = actor.firstPair
local thisPair = actor.lastPair
while thisPair ~= firstPair do
DestroyPair(thisPair)
thisPair = actor.lastPair
end
unusedActors[#unusedActors + 1] = actor
end
destroyedActors[i] = nil
end
end
local function CellCheck()
local x, y
local minx, miny, maxx, maxy
local changedCells
local newMinX, newMinY, newMaxX, newMaxY
local oldMinX, oldMinY, oldMaxX, oldMaxY
local halfWidth, halfHeight
local actor
local currentCounter = cycle.counter
local actorsThisStep = cellCheckedActors[currentCounter]
local nextStep
local CYCLE_LENGTH = CYCLE_LENGTH
for i = 1, numCellChecks[currentCounter] do
actor = actorsThisStep[i]
x = actor.x[actor.anchor]
y = actor.y[actor.anchor]
halfWidth = actor.halfWidth
halfHeight = actor.halfHeight
minx = x - halfWidth
miny = y - halfHeight
maxx = x + halfWidth
maxy = y + halfHeight
newMinX = actor.minX
newMinY = actor.minY
newMaxX = actor.maxX
newMaxY = actor.maxY
if x > actor.lastX then
while minx > CELL_MAX_X[newMinX] and newMinX < NUM_CELLS_X do
changedCells = true
newMinX = newMinX + 1
end
while maxx > CELL_MAX_X[newMaxX] and newMaxX < NUM_CELLS_X do
changedCells = true
newMaxX = newMaxX + 1
end
else
while minx < CELL_MIN_X[newMinX] and newMinX > 1 do
changedCells = true
newMinX = newMinX - 1
end
while maxx < CELL_MIN_X[newMaxX] and newMaxX > 1 do
changedCells = true
newMaxX = newMaxX - 1
end
end
if y > actor.lastY then
while miny > CELL_MAX_Y[newMinY] and newMinY < NUM_CELLS_Y do
changedCells = true
newMinY = newMinY + 1
end
while maxy > CELL_MAX_Y[newMaxY] and newMaxY < NUM_CELLS_Y do
changedCells = true
newMaxY = newMaxY + 1
end
else
while miny < CELL_MIN_Y[newMinY] and newMinY > 1 do
changedCells = true
newMinY = newMinY - 1
end
while maxy < CELL_MIN_Y[newMaxY] and newMaxY > 1 do
changedCells = true
newMaxY = newMaxY - 1
end
end
if changedCells then
oldMinX = actor.minX
oldMinY = actor.minY
oldMaxX = actor.maxX
oldMaxY = actor.maxY
actor.minY = newMinY
actor.maxX = newMaxX
actor.maxY = newMaxY
for key, __ in pairs(actorAlreadyChecked) do
actorAlreadyChecked[key] = nil
end
actorAlreadyChecked[actor] = true
if newMinX > oldMinX then
actor.minX = newMinX
for X = oldMinX, newMinX - 1 < oldMaxX and newMinX - 1 or oldMaxX do
for Y = oldMinY, oldMaxY do
LeaveCell(CELL_LIST[X][Y], actor)
end
end
elseif newMinX < oldMinX then
actor.minX = newMinX
for X = newMinX, newMaxX < oldMinX - 1 and newMaxX or oldMinX - 1 do
for Y = newMinY, newMaxY do
EnterCell(CELL_LIST[X][Y], actor)
end
end
end
if newMaxX > oldMaxX then
for X = oldMaxX + 1 > newMinX and oldMaxX + 1 or newMinX, newMaxX do
for Y = newMinY, newMaxY do
EnterCell(CELL_LIST[X][Y], actor)
end
end
elseif newMaxX < oldMaxX then
for X = newMaxX + 1 > oldMinX and newMaxX + 1 or oldMinX , oldMaxX do
for Y = oldMinY, oldMaxY do
LeaveCell(CELL_LIST[X][Y], actor)
end
end
end
if newMinY > oldMinY then
for Y = oldMinY, newMinY - 1 < oldMaxY and newMinY - 1 or oldMaxY do
for X = oldMinX > newMinX and oldMinX or newMinX, oldMaxX < newMaxX and oldMaxX or newMaxX do
LeaveCell(CELL_LIST[X][Y], actor)
end
end
elseif newMinY < oldMinY then
for Y = newMinY, newMaxY < oldMinY - 1 and newMaxY or oldMinY - 1 do
for X = oldMinX > newMinX and oldMinX or newMinX, oldMaxX < newMaxX and oldMaxX or newMaxX do
EnterCell(CELL_LIST[X][Y], actor)
end
end
end
if newMaxY > oldMaxY then
for Y = oldMaxY + 1 > newMinY and oldMaxY + 1 or newMinY, newMaxY do
for X = oldMinX > newMinX and oldMinX or newMinX, oldMaxX < newMaxX and oldMaxX or newMaxX do
EnterCell(CELL_LIST[X][Y], actor)
end
end
elseif newMaxY < oldMaxY then
for Y = newMaxY + 1 > oldMinY and newMaxY + 1 or oldMinY , oldMaxY do
for X = oldMinX > newMinX and oldMinX or newMinX, oldMaxX < newMaxX and oldMaxX or newMaxX do
LeaveCell(CELL_LIST[X][Y], actor)
end
end
end
if actor.cellsVisualized then
RedrawCellVisualizers(actor)
end
changedCells = false
end
actor.lastX, actor.lastY = x, y
nextStep = currentCounter + 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]
end
if debug.visualizeAllActors then
for i = 1, numCellChecks[currentCounter] do
actor = actorsThisStep[i]
BlzSetSpecialEffectPosition(actor.visualizer, actor.x[actor.anchor], actor.y[actor.anchor], actor.z[actor] + 75)
end
end
numCellChecks[currentCounter] = 0
end
--#endregion
--===========================================================================================================================================================
--Main
--===========================================================================================================================================================
--#region Main
local function Main()
local DESTRUCTION_QUEUED = DESTRUCTION_QUEUED
local INTERACTION_FUNC = INTERACTION_FUNC
local HOST_A, HOST_B = HOST_A, HOST_B
local CURRENT_POSITION = CURRENT_POSITION
local POSITION_IN_STEP = POSITION_IN_STEP
local INV_MIN_INTERVAL = INV_MIN_INTERVAL
local CYCLE_LENGTH = CYCLE_LENGTH
local MAX_STEPS = MAX_STEPS
local NEXT = NEXT
local evalCounter = cycle.unboundCounter - (cycle.unboundCounter // 10)*10 + 1
local startTime = os.clock()
if currentPair ~= OUTSIDE_OF_CYCLE then
if config.HALT_ON_FIRST_CRASH then
local A = currentPair[ACTOR_A]
local B = currentPair[ACTOR_B]
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 .. ". ALICE Cycle aborted due to HALT_ON_FIRST_CRASH being enabled. To resume, do ALICE_Resume().")
ALICE_Halt()
if not debug.enabled then
EnableDebugMode()
end
return
else
OnCrash()
end
end
--First-in first-out.
local k = 1
while delayedCallbackFunctions[k] do
delayedCallbackFunctions[k](unpack(delayedCallbackArgs[k]))
k = k + 1
end
for i = 1, #delayedCallbackFunctions do
delayedCallbackFunctions[i] = nil
end
BindChecks()
RemovePairsFromCycle()
cycle.counter = cycle.counter + 1
if cycle.counter > CYCLE_LENGTH then
cycle.counter = 1
end
local currentCounter = cycle.counter
cycle.unboundCounter = cycle.unboundCounter + 1
ALICE_TimeElapsed = cycle.unboundCounter*config.MIN_INTERVAL
while userCallbacks.first and userCallbacks.first.callCounter == cycle.unboundCounter do
ExecuteUserCallback(userCallbacks.first)
end
for i = 1, #debug.visualizationLightnings do
local lightning = debug.visualizationLightnings[i]
TimerStart(CreateTimer(), 0.02, false, function()
DestroyTimer(GetExpiredTimer())
DestroyLightning(lightning)
end)
debug.visualizationLightnings[i] = nil
end
if debug.benchmark then
local averageEvalTime = 0
for i = 1, 10 do
averageEvalTime = averageEvalTime + (debug.evaluationTime[i] or 0)/10
end
Warning("eval time: |cffffcc00" .. string.format("\x25.2f", 1000*averageEvalTime) .. "ms|r, actors: " .. #actorList .. ", pairs: " .. numPairs[currentCounter] + numEveryStepPairs .. ", cell checks: " .. numCellChecks[currentCounter])
end
if debug.enabled then
UpdateSelectedActor()
end
local numSteps, nextStep
--Every Step Cycle
currentPair = firstEveryStepPair
for __ = 1, numEveryStepPairs do
currentPair = currentPair[NEXT]
if not currentPair[DESTRUCTION_QUEUED] then
currentPair[INTERACTION_FUNC](currentPair[HOST_A], currentPair[HOST_B])
end
end
ResetCoordinateLookupTables()
CellCheck()
--Variable Step Cycle
local returnValue
local pairsThisStep = whichPairs[currentCounter]
for i = 1, numPairs[currentCounter] do
currentPair = pairsThisStep[i]
if currentPair[DESTRUCTION_QUEUED] then
if currentPair ~= DUMMY_PAIR then
nextStep = currentCounter + MAX_STEPS
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = currentPair
currentPair[CURRENT_POSITION] = nextStep
currentPair[POSITION_IN_STEP] = numPairs[nextStep]
end
else
returnValue = currentPair[INTERACTION_FUNC](currentPair[HOST_A], currentPair[HOST_B])
if returnValue then
numSteps = (returnValue*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
nextStep = currentCounter + numSteps
if nextStep > CYCLE_LENGTH then
nextStep = nextStep - CYCLE_LENGTH
end
numPairs[nextStep] = numPairs[nextStep] + 1
whichPairs[nextStep][numPairs[nextStep]] = currentPair
currentPair[CURRENT_POSITION] = nextStep
currentPair[POSITION_IN_STEP] = numPairs[nextStep]
else
AddPairToEveryStepList(currentPair)
if currentPair[INTERACTION_FUNC] ~= PeriodicWrapper and currentPair[INTERACTION_FUNC] ~= RepeatedWrapper then
functionIsEveryStep[currentPair[INTERACTION_FUNC]] = true
end
currentPair[EVERY_STEP] = true
end
end
end
numPairs[currentCounter] = 0
currentPair = OUTSIDE_OF_CYCLE
k = 1
while delayedCallbackFunctions[k] do
delayedCallbackFunctions[k](unpack(delayedCallbackArgs[k]))
k = k + 1
end
for i = 1, #delayedCallbackFunctions do
delayedCallbackFunctions[i] = nil
end
local endTime = os.clock()
debug.evaluationTime[evalCounter] = endTime - startTime
ALICE_CPULoad = (endTime - startTime)/config.MIN_INTERVAL
end
--#endregion
--===========================================================================================================================================================
--Debug Mode
--===========================================================================================================================================================
---@param whichPair Pair
---@param lightningType string
VisualizationLightning = function(whichPair, lightningType)
local A = whichPair[ACTOR_A]
local B = whichPair[ACTOR_B]
if A.alreadyDestroyed or B.alreadyDestroyed or A.isGlobal or B.isGlobal then
return
end
local xa = A.x[A.anchor]
local ya = A.y[A.anchor]
local za = A.z[A]
local xb = B.x[B.anchor]
local yb = B.y[B.anchor]
local zb = B.z[B]
if za and zb then
insert(debug.visualizationLightnings, AddLightningEx(lightningType, true, xa, ya, za, xb, yb, zb))
else
insert(debug.visualizationLightnings, AddLightning(lightningType, true, xa, ya, xb, yb))
end
end
UpdateSelectedActor = function()
if debug.selectedActor then
if not debug.selectedActor.isGlobal then
local x = debug.selectedActor.x[debug.selectedActor.anchor]
local y = debug.selectedActor.y[debug.selectedActor.anchor]
BlzSetSpecialEffectPosition(debug.selectedActor.visualizer, x, y, debug.selectedActor.z[debug.selectedActor] + 75)
SetCameraQuickPosition(x, y)
end
local description, title = GetDescription(debug.selectedActor)
BlzFrameSetText(debug.tooltipText, description)
BlzFrameSetText(debug.tooltipTitle, title )
BlzFrameSetSize(debug.tooltipText, 0.28, 0.0)
BlzFrameSetSize(debug.tooltip, 0.29, BlzFrameGetHeight(debug.tooltipText) + 0.0315)
local funcs = {}
local next = debug.selectedActor.nextPair
local pair = next[debug.selectedActor.firstPair]
while pair do
if (pair[EVERY_STEP] and pair[PREVIOUS] ~= nil) or (not pair[EVERY_STEP] and pair[CURRENT_POSITION] == cycle.counter) then
VisualizationLightning(pair, "DRAL")
if debug.printFunctionNames then
funcs[pair[INTERACTION_FUNC]] = (funcs[pair[INTERACTION_FUNC]] or 0) + 1
end
end
pair = next[pair]
end
if debug.printFunctionNames then
local first = true
local message
for func, amount in pairs(funcs) do
if first then
message = "\n|cffffcc00Step " .. cycle.unboundCounter .. ":|r"
first = false
end
if amount > 1 then
message = message .. "\n" .. Function2String(func) .. " |cffaaaaffx" .. amount .. "|r"
else
message = message .. "\n" .. Function2String(func)
end
end
if message then
Warning(message)
end
end
end
end
---@param x number
---@param y number
---@param z number
---@return number, number
local function World2Screen(eyeX, eyeY, eyeZ, angleOfAttack, x, y, z)
local cosAngle = math.cos(angleOfAttack)
local sinAngle = math.sin(angleOfAttack)
local dx = x - eyeX
local dy = y - eyeY
local dz = (z or 0) - eyeZ
local yPrime = cosAngle*dy - sinAngle*dz
local zPrime = sinAngle*dy + cosAngle*dz
return 0.4 + 0.7425*dx/yPrime, 0.355 + 0.7425*zPrime/yPrime
end
--#region Debug Mode
local function OnMouseClick()
if debug.selectionLocked or BlzGetTriggerPlayerMouseButton() ~= MOUSE_BUTTON_TYPE_LEFT then
return
end
local previousSelectedActor = debug.selectedActor
if debug.selectedActor then
Deselect(debug.selectedActor)
end
local mouseX = BlzGetTriggerPlayerMouseX()
local mouseY = BlzGetTriggerPlayerMouseY()
local objects = ALICE_EnumObjectsInRange(mouseX, mouseY, 500, {MATCHING_TYPE_ALL}, nil)
local closestDist = 0.04
local closestObject = nil
local eyeX = GetCameraEyePositionX()
local eyeY = GetCameraEyePositionY()
local eyeZ = GetCameraEyePositionZ()
local angleOfAttack = -GetCameraField(CAMERA_FIELD_ANGLE_OF_ATTACK)
local mouseScreenX, mouseScreenY = World2Screen(eyeX, eyeY, eyeZ, angleOfAttack, mouseX, mouseY, GetTerrainZ(mouseX, mouseY))
local x, y, dx, dy
for __, object in ipairs(objects) do
local actor = GetActor(object)
--Find the actor that is closest to the mouse-cursor.
if not actor.isUnselectable and (previousSelectedActor == nil or ALICE_GetAnchor(object) ~= previousSelectedActor.anchor) then
x, y = World2Screen(eyeX, eyeY, eyeZ, angleOfAttack, ALICE_GetCoordinates3D(actor))
dx, dy = x - mouseScreenX, y - mouseScreenY
local dist = sqrt(dx*dx + dy*dy)
if dist < closestDist then
closestDist = dist
closestObject = actor.anchor
end
end
end
if closestObject then
if actorOf[closestObject].isActor then
Select(actorOf[closestObject])
else
Warning("Multiple actors are anchored to this object. Press |cffffcc00Ctrl + Q|r to cycle through.")
Select(actorOf[closestObject][1])
end
end
end
local function OnCtrlR()
Warning("Going to step " .. cycle.unboundCounter + 1 .. " |cffaaaaaa(" .. string.format("\x25.2f", config.MIN_INTERVAL*(cycle.unboundCounter + 1)) .. "s)|r.")
Main()
if debug.gameIsPaused then
ALICE_ForAllObjectsDo(function(unit) PauseUnit(unit, true) end, "unit")
end
end
local function OnCtrlG()
if debug.printFunctionNames then
Warning("\nPrinting function names disabled.")
else
Warning("\nPrinting function names enabled.")
end
debug.printFunctionNames = not debug.printFunctionNames
end
local function OnCtrlW()
if debug.selectionLocked then
Warning("\nSelection unlocked.")
else
Warning("\nSelection locked. To unlock, press |cffffcc00Ctrl + W|r.")
end
debug.selectionLocked = not debug.selectionLocked
end
---Cycle through actors anchored to the same object.
local function OnCtrlQ()
if debug.selectedActor == nil then
return
end
local selectedObject = debug.selectedActor.anchor
if actorOf[selectedObject].isActor then
return
end
for index, actor in ipairs(actorOf[selectedObject]) do
if debug.selectedActor == actor then
Deselect(debug.selectedActor)
if actorOf[selectedObject][index + 1] then
Select(actorOf[selectedObject][index + 1])
return
else
Select(actorOf[selectedObject][1])
return
end
end
end
end
local function OnCtrlT()
if cycle.isHalted then
ALICE_Resume()
Warning("\nALICE Cycle resumed.")
else
ALICE_Halt(BlzGetTriggerPlayerMetaKey() == 3)
Warning("\nALICE Cycle halted. To go to the next step, press |cffffcc00Ctrl + R|r. To resume, press |cffffcc00Ctrl + T|r.")
end
end
local function DownTheRabbitHole()
EnableDebugMode()
if debug.enabled then
Warning("\nDebug mode enabled. Left-click near an actor to display attributes and enable visualization.")
else
Warning("\nDebug mode has been disabled.")
end
end
EnableDebugMode = function()
if not debug.enabled then
debug.enabled = true
BlzLoadTOCFile("CustomTooltip.toc")
debug.tooltip = BlzCreateFrame("CustomTooltip", BlzGetOriginFrame(ORIGIN_FRAME_WORLD_FRAME, 0), 0, 0)
BlzFrameSetAbsPoint(debug.tooltip, FRAMEPOINT_BOTTOMRIGHT, 0.8, 0.165)
BlzFrameSetSize(debug.tooltip, 0.32, 0.0)
debug.tooltipTitle = BlzGetFrameByName("CustomTooltipTitle", 0)
debug.tooltipText = BlzGetFrameByName("CustomTooltipValue", 0)
debug.nextStepTrigger = CreateTrigger()
BlzTriggerRegisterPlayerKeyEvent(debug.nextStepTrigger, GetTriggerPlayer() or Player(0), OSKEY_R, 2, true)
TriggerAddAction(debug.nextStepTrigger, OnCtrlR)
debug.mouseClickTrigger = CreateTrigger()
TriggerRegisterPlayerEvent(debug.mouseClickTrigger, GetTriggerPlayer() or Player(0), EVENT_PLAYER_MOUSE_DOWN)
TriggerAddAction(debug.mouseClickTrigger, OnMouseClick)
debug.lockSelectionTrigger = CreateTrigger()
BlzTriggerRegisterPlayerKeyEvent(debug.lockSelectionTrigger, GetTriggerPlayer() or Player(0), OSKEY_W, 2, true)
TriggerAddAction(debug.lockSelectionTrigger, OnCtrlW)
debug.cycleSelectTrigger = CreateTrigger()
BlzTriggerRegisterPlayerKeyEvent(debug.cycleSelectTrigger, GetTriggerPlayer() or Player(0), OSKEY_Q, 2, true)
TriggerAddAction(debug.cycleSelectTrigger, OnCtrlQ)
debug.haltTrigger = CreateTrigger()
BlzTriggerRegisterPlayerKeyEvent(debug.haltTrigger, GetTriggerPlayer() or Player(0), OSKEY_T, 2, true)
BlzTriggerRegisterPlayerKeyEvent(debug.haltTrigger, GetTriggerPlayer() or Player(0), OSKEY_T, 3, true)
TriggerAddAction(debug.haltTrigger, OnCtrlT)
debug.printFunctionsTrigger = CreateTrigger()
BlzTriggerRegisterPlayerKeyEvent(debug.printFunctionsTrigger, GetTriggerPlayer() or Player(0), OSKEY_G, 2, true)
TriggerAddAction(debug.printFunctionsTrigger, OnCtrlG)
else
if debug.selectedActor then
Deselect(debug.selectedActor)
end
debug.enabled = false
DestroyTrigger(debug.nextStepTrigger)
DestroyTrigger(debug.lockSelectionTrigger)
DestroyTrigger(debug.mouseClickTrigger)
DestroyTrigger(debug.cycleSelectTrigger)
DestroyTrigger(debug.haltTrigger)
DestroyTrigger(debug.printFunctionsTrigger)
BlzDestroyFrame(debug.tooltip)
end
end
--#endregion
--===========================================================================================================================================================
--Widget Actors
--===========================================================================================================================================================
--#region WidgetActors
local actorFlags = {}
local identifiers = {}
local function Kill(object)
if type(object) == "table" then
if type(object.destroy) == "function" then
object:destroy()
elseif object.visual then
if HandleType[object.visual] == "effect" then
DestroyEffect(object.visual)
elseif HandleType[object.visual] == "unit" then
KillUnit(object.visual)
elseif HandleType[object.visual] == "image" then
DestroyImage(object.visual)
end
end
elseif IsHandle[object] then
if HandleType[object] == "unit" then
KillUnit(object)
elseif HandleType[object] == "destructable" then
KillDestructable(object)
elseif HandleType[object] == "item" then
RemoveItem(object)
end
end
end
local function Clear(object, wasUnitDeath)
local actor = actorOf[object]
if actor then
if not actor.isActor then
for i = #actor, 1, -1 do
if not wasUnitDeath or not actor[i].persistOnDeath then
if actor[i].host ~= object then
Kill(actor[i].host)
end
Destroy(actor[i])
end
end
elseif not wasUnitDeath or not actor.persistOnDeath then
Destroy(actor)
end
end
end
local function OnLoad(widget, transport)
if actorOf[widget] == nil then
return
end
if actorOf[widget].isActor then
actorOf[widget].anchor = transport
SetCoordinateFuncs(actorOf[widget])
Suspend(actorOf[widget], true)
else
for __, actor in ipairs(actorOf[widget]) do
actor.anchor = transport
SetCoordinateFuncs(actor)
Suspend(actor, true)
end
end
end
local function OnUnload(widget)
if actorOf[widget].isActor then
local actor = actorOf[widget]
actor.anchor = actor.originalAnchor
actor.x[actor.anchor] = nil
actor.y[actor.anchor] = nil
actor.z[actor] = nil
SetCoordinateFuncs(actor)
Suspend(actorOf[widget], false)
else
for __, actor in ipairs(actorOf[widget]) do
actor.anchor = actor.originalAnchor
actor.x[actor.anchor] = nil
actor.y[actor.anchor] = nil
actor.z[actor] = nil
SetCoordinateFuncs(actor)
Suspend(actor, false)
end
end
end
--===========================================================================================================================================================
--Unit Actors
--===========================================================================================================================================================
local function CorpseCleanUp(u)
if GetUnitTypeId(u) == 0 then
DestroyTrigger(widgets.reviveTriggers[u])
widgets.reviveTriggers[u] = nil
for __, func in ipairs(eventHooks.onUnitRemove) do
func(u)
end
Clear(u)
end
return 1.0
end
---@param u unit
local function CreateUnitActor(u)
local id = GetUnitTypeId(u)
if GetUnitAbilityLevel(u, 1097625443) > 0 then --FourCC "Aloc" (Locust)
return
end
if not widgets.idInclusions[id] and (config.NO_UNIT_ACTOR or widgets.idExclusions[id]) then
return
end
if id == 0 then
return
end
for key, __ in pairs(identifiers) do
identifiers[key] = nil
end
local interactions
if GetUnitState(u, UNIT_STATE_LIFE) > 0.405 then
identifiers[#identifiers + 1] = "unit"
actorFlags.isStationary = IsUnitType(u, UNIT_TYPE_STRUCTURE)
elseif config.UNITS_LEAVE_BEHIND_CORPSES then
identifiers[#identifiers + 1] = "corpse"
interactions = {self = CorpseCleanUp}
actorFlags.isStationary = config.UNIT_CORPSES_ARE_STATIONARY
else
return
end
identifiers[#identifiers + 1] = toCamelCase[GetUnitName(u)]
for __, unittype in ipairs(config.UNIT_ADDED_CLASSIFICATIONS) do
if IsUnitType(u, unittype) then
identifiers[#identifiers + 1] = UNIT_CLASSIFICATION_NAMES[unittype]
else
identifiers[#identifiers + 1] = "non" .. UNIT_CLASSIFICATION_NAMES[unittype]
end
end
if IsUnitType(u, UNIT_TYPE_HERO) then
identifiers[#identifiers + 1] = toCamelCase[GetHeroProperName(u)]
end
identifiers[#identifiers + 1] = string.pack(">I4", id)
actorFlags.radius = config.DEFAULT_UNIT_RADIUS
actorFlags.persistOnDeath = config.UNITS_LEAVE_BEHIND_CORPSES
Create(u, identifiers, interactions, actorFlags)
end
local function OnRevive()
local u = GetTriggerUnit()
ALICE_RemoveSelfInteraction(u, CorpseCleanUp, "corpse")
ALICE_SwapIdentifier(u, "corpse", "unit", "corpse")
if config.UNIT_CORPSES_ARE_STATIONARY and not IsUnitType(u, UNIT_TYPE_STRUCTURE) then
ALICE_SetStationary(u, false)
end
DestroyTrigger(widgets.reviveTriggers[u])
widgets.reviveTriggers[u] = nil
for __, func in ipairs(eventHooks.onUnitRevive) do
func(u)
end
end
local function OnUnitDeath()
local u = GetTriggerUnit()
local actor = actorOf[u]
if actor == nil then
return
end
if config.UNITS_LEAVE_BEHIND_CORPSES then
ALICE_AddSelfInteraction(u, CorpseCleanUp, "unit")
ALICE_SwapIdentifier(u, "unit", "corpse", "unit")
if config.UNIT_CORPSES_ARE_STATIONARY then
ALICE_SetStationary(u, true)
end
widgets.reviveTriggers[u] = CreateTrigger()
TriggerAddAction(widgets.reviveTriggers[u], OnRevive)
TriggerRegisterUnitStateEvent(widgets.reviveTriggers[u], u, UNIT_STATE_LIFE, GREATER_THAN_OR_EQUAL, 0.405)
for __, func in ipairs(eventHooks.onUnitDeath) do
func(u)
end
Clear(u, true)
else
for __, func in ipairs(eventHooks.onUnitRemove) do
func(u)
end
Clear(u)
end
end
local function OnUnitEnter()
local u = GetTrainedUnit() or GetTriggerUnit()
if GetActor(u, "unit") then
return
end
CreateUnitActor(u)
for __, func in ipairs(eventHooks.onUnitEnter) do
func(u)
end
end
local function OnUnitLoaded()
local u = GetLoadedUnit()
OnLoad(u, GetTransportUnit())
ALICE_CallPeriodic(function(unit)
if not IsUnitLoaded(unit) then
ALICE_DisablePeriodic()
if actorOf[unit] then
OnUnload(unit)
end
end
end, 0, u)
end
--===========================================================================================================================================================
--Destructable Actors
--===========================================================================================================================================================
---@param d destructable
local function CreateDestructableActor(d)
local id = GetDestructableTypeId(d)
if not widgets.idInclusions[id] and (config.NO_DESTRUCTABLE_ACTOR or widgets.idExclusions[id]) then
return
end
if id == 0 then
return
end
for key, __ in pairs(identifiers) do
identifiers[key] = nil
end
identifiers[#identifiers + 1] = "destructable"
local name = GetDestructableName(d)
identifiers[#identifiers + 1] = toCamelCase[name]
for __, keyword in ipairs(config.DESTRUCTABLE_KEYWORDS) do
if string.find(name, keyword) then
identifiers[#identifiers + 1] = toCamelCase[keyword]
end
end
identifiers[#identifiers + 1] = string.pack(">I4", id)
actorFlags.radius = config.DEFAULT_DESTRUCTABLE_RADIUS
actorFlags.isStationary = true
actorFlags.persistOnDeath = nil
Create(d, identifiers, nil, actorFlags)
end
OnDestructableDeath = function()
local whichObject = GetTriggerDestructable()
DestroyTrigger(widgets.deathTriggers[whichObject])
widgets.deathTriggers[whichObject] = nil
for __, func in ipairs(eventHooks.onDestructableDestroy) do
func(whichObject)
end
Clear(whichObject)
end
--===========================================================================================================================================================
--Item Actors
--===========================================================================================================================================================
---@param i item
local function CreateItemActor(i)
local id = GetItemTypeId(i)
if not widgets.idInclusions[id] and (config.NO_ITEM_ACTOR or widgets.idExclusions[id]) then
return
end
if id == 0 then
return
end
for key, __ in pairs(identifiers) do
identifiers[key] = nil
end
identifiers[#identifiers + 1] = "item"
identifiers[#identifiers + 1] = toCamelCase[GetItemName(i)]
identifiers[#identifiers + 1] = string.pack(">I4", id)
actorFlags.radius = config.DEFAULT_ITEM_RADIUS
actorFlags.isStationary = config.ITEMS_ARE_STATIONARY
actorFlags.persistOnDeath = nil
Create(i, identifiers, nil, actorFlags)
end
local function OnItemPickup()
local item = GetManipulatedItem()
OnLoad(item, GetTriggerUnit())
if config.ITEMS_ARE_STATIONARY then
ALICE_SetStationary(item, false)
end
end
local function OnItemDrop()
local item = GetManipulatedItem()
if actorOf[item] then
OnUnload(item)
if config.ITEMS_ARE_STATIONARY then
ALICE_SetStationary(item, true)
end
else
AddDelayedCallback(function(whichItem)
if GetItemTypeId(whichItem) == 0 then
return
end
CreateItemActor(whichItem)
for __, func in ipairs(eventHooks.onItemEnter) do
func(whichItem)
end
end, item)
end
end
local function OnItemSold()
Clear(GetManipulatedItem())
end
OnItemDeath = function()
SaveWidgetHandle(widgets.hash, 0, 0, GetTriggerWidget())
local whichObject = LoadItemHandle(widgets.hash, 0, 0)
DestroyTrigger(widgets.deathTriggers[whichObject])
widgets.deathTriggers[whichObject] = nil
for __, func in ipairs(eventHooks.onItemDestroy) do
func(whichObject)
end
Clear(whichObject)
end
--#endregion
--===========================================================================================================================================================
--Init
--===========================================================================================================================================================
--#region Init
local function Init()
Require "HandleType"
Require "Hook"
MASTER_TIMER = CreateTimer()
MAX_STEPS = (config.MAX_INTERVAL/config.MIN_INTERVAL) // 1
CYCLE_LENGTH = MAX_STEPS + 1
DO_NOT_EVALUATE = CYCLE_LENGTH + 1
for i = 1, DO_NOT_EVALUATE do
numPairs[i] = 0
whichPairs[i] = {}
end
for i = 1, CYCLE_LENGTH do
numCellChecks[i] = 0
cellCheckedActors[i] = {}
end
local worldBounds = GetWorldBounds()
MAP_MIN_X = GetRectMinX(worldBounds)
MAP_MAX_X = GetRectMaxX(worldBounds)
MAP_MIN_Y = GetRectMinY(worldBounds)
MAP_MAX_Y = GetRectMaxY(worldBounds)
MAP_SIZE_X = MAP_MAX_X - MAP_MIN_X
MAP_SIZE_Y = MAP_MAX_Y - MAP_MIN_Y
NUM_CELLS_X = MAP_SIZE_X // config.CELL_SIZE
NUM_CELLS_Y = MAP_SIZE_Y // config.CELL_SIZE
for X = 1, NUM_CELLS_X do
CELL_LIST[X] = {}
for Y = 1, NUM_CELLS_Y do
CELL_LIST[X][Y] = {numActors = 0}
end
end
for x = 1, NUM_CELLS_X do
CELL_MIN_X[x] = MAP_MIN_X + (x-1)/NUM_CELLS_X*MAP_SIZE_X
CELL_MAX_X[x] = MAP_MIN_X + x/NUM_CELLS_X*MAP_SIZE_X
end
for y = 1, NUM_CELLS_Y do
CELL_MIN_Y[y] = MAP_MIN_Y + (y-1)/NUM_CELLS_Y*MAP_SIZE_Y
CELL_MAX_Y[y] = MAP_MIN_Y + y/NUM_CELLS_Y*MAP_SIZE_Y
end
GetTable = config.TABLE_RECYCLER_GET or function()
local numUnusedTables = #unusedTables
if numUnusedTables == 0 then
return {}
else
local returnTable = unusedTables[numUnusedTables]
unusedTables[numUnusedTables] = nil
return returnTable
end
end
ReturnTable = config.TABLE_RECYCLER_RETURN or function(whichTable)
for key, __ in pairs(whichTable) do
whichTable[key] = nil
end
unusedTables[#unusedTables + 1] = whichTable
setmetatable(whichTable, nil)
end
local trig = CreateTrigger()
for i = 0, 23 do
for __, name in ipairs(config.MAP_CREATORS) do
if string.find(GetPlayerName(Player(i)), name) then
TriggerRegisterPlayerChatEvent(trig, Player(i), "downtherabbithole", true)
TriggerRegisterPlayerChatEvent(trig, Player(i), "-downtherabbithole", true)
break
end
end
end
TriggerAddAction(trig, DownTheRabbitHole)
SELF_INTERACTION_ACTOR = Create({}, "selfInteraction", nil, EMPTY_TABLE)
actorList[#actorList] = nil
celllessActorList[#celllessActorList] = nil
totalActors = totalActors - 1
SELF_INTERACTION_ACTOR.unique = 0
functionName[CorpseCleanUp] = "CorpseCleanUp"
TimerStart(MASTER_TIMER, config.MIN_INTERVAL, true, Main)
local precomputedHeightMap = Require.optionally "PrecomputedHeightMap"
if precomputedHeightMap then
GetTerrainZ = _G.GetTerrainZ
else
moveableLoc = Location(0, 0)
GetTerrainZ = function(x, y)
MoveLocation(moveableLoc, x, y)
return GetLocationZ(moveableLoc)
end
end
widgets.hash = InitHashtable()
trig = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_HERO_REVIVE_FINISH)
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_SUMMON)
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_TRAIN_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()
local u = GetEnumUnit()
CreateUnitActor(u)
for __, func in ipairs(eventHooks.onUnitEnter) do
func(u)
end
end)
DestroyGroup(G)
EnumDestructablesInRect(worldBounds, nil, function() CreateDestructableActor(GetEnumDestructable()) end)
EnumItemsInRect(worldBounds, nil, function() CreateItemActor(GetEnumItem()) end)
trig = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_DROP_ITEM)
TriggerAddAction(trig, OnItemDrop)
trig = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_PICKUP_ITEM)
TriggerAddAction(trig, OnItemPickup)
trig = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_PAWN_ITEM)
TriggerAddAction(trig, OnItemSold)
trig = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_CHANGE_OWNER)
TriggerAddAction(trig, OnUnitChangeOwner)
trig = CreateTrigger()
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_LOADED)
TriggerAddAction(trig, OnUnitLoaded)
local function CreateUnitHookFunc(self, ...)
local newUnit = self.old(...)
CreateUnitActor(newUnit)
for __, func in ipairs(eventHooks.onUnitEnter) do
func(newUnit)
end
return newUnit
end
---@diagnostic disable-next-line: duplicate-set-field
Hook.CreateUnit = CreateUnitHookFunc
---@diagnostic disable-next-line: duplicate-set-field
Hook.CreateUnitByName = CreateUnitHookFunc
---@diagnostic disable-next-line: duplicate-set-field
Hook.CreateUnitAtLoc = CreateUnitHookFunc
---@diagnostic disable-next-line: duplicate-set-field
Hook.CreateUnitAtLocByName = CreateUnitHookFunc
if config.UNITS_LEAVE_BEHIND_CORPSES then
---@diagnostic disable-next-line: duplicate-set-field
Hook.CreateCorpse = CreateUnitHookFunc
end
---@diagnostic disable-next-line: duplicate-set-field
function Hook:RemoveUnit(whichUnit)
local item
for i = 0, UnitInventorySize(whichUnit) - 1 do
item = UnitItemInSlot(whichUnit, i)
for __, func in ipairs(eventHooks.onItemDestroy) do
func(item)
end
Clear(item)
end
for __, func in ipairs(eventHooks.onUnitRemove) do
func(whichUnit)
end
Clear(whichUnit)
self.old(whichUnit)
end
---@diagnostic disable-next-line: duplicate-set-field
function Hook:ShowUnit(whichUnit, enable)
self.old(whichUnit, enable)
if actorOf[whichUnit] == nil then
return
end
if actorOf[whichUnit].isActor then
Suspend(actorOf[whichUnit], not enable)
else
for __, actor in ipairs(actorOf[whichUnit]) do
Suspend(actor, not enable)
end
end
end
local function CreateDestructableHookFunc(self, ...)
local newDestructable = self.old(...)
CreateDestructableActor(newDestructable)
for __, func in ipairs(eventHooks.onDestructableEnter) do
func(newDestructable)
end
return newDestructable
end
---@diagnostic disable-next-line: duplicate-set-field
Hook.CreateDestructable = CreateDestructableHookFunc
---@diagnostic disable-next-line: duplicate-set-field
Hook.CreateDestructableZ = CreateDestructableHookFunc
---@diagnostic disable-next-line: duplicate-set-field
Hook.BlzCreateDestructableWithSkin = CreateDestructableHookFunc
---@diagnostic disable-next-line: duplicate-set-field
Hook.BlzCreateDestructableZWithSkin = CreateDestructableHookFunc
---@diagnostic disable-next-line: duplicate-set-field
function Hook:RemoveDestructable(whichDestructable)
for __, func in ipairs(eventHooks.onDestructableDestroy) do
func(whichDestructable)
end
Clear(whichDestructable)
if widgets.deathTriggers[whichDestructable] then
DestroyTrigger(widgets.deathTriggers[whichDestructable])
widgets.deathTriggers[whichDestructable] = nil
end
self.old(whichDestructable)
end
---@diagnostic disable-next-line: duplicate-set-field
function Hook:DestructableRestoreLife(whichDestructable, life, birth)
self.old(whichDestructable, life, birth)
if GetDestructableLife(whichDestructable) > 0 and GetActor(whichDestructable, "destructable") == nil then
CreateDestructableActor(whichDestructable)
for __, func in ipairs(eventHooks.onDestructableEnter) do
func(whichDestructable)
end
end
end
---@diagnostic disable-next-line: duplicate-set-field
function Hook:CreateItem(...)
local newItem
newItem = self.old(...)
CreateItemActor(newItem)
for __, func in ipairs(eventHooks.onItemEnter) do
func(newItem)
end
return newItem
end
---@diagnostic disable-next-line: duplicate-set-field
function Hook:RemoveItem(whichItem)
for __, func in ipairs(eventHooks.onItemDestroy) do
func(whichItem)
end
Clear(whichItem)
if widgets.deathTriggers[whichItem] then
DestroyTrigger(widgets.deathTriggers[whichItem])
widgets.deathTriggers[whichItem] = nil
end
self.old(whichItem)
end
---@diagnostic disable-next-line: duplicate-set-field
function Hook:SetItemVisible(whichItem, enable)
self.old(whichItem, enable)
if actorOf[whichItem] == nil then
return
end
if actorOf[whichItem].isActor then
Suspend(actorOf[whichItem], not enable)
else
for __, actor in ipairs(actorOf[whichItem]) do
Suspend(actor, not enable)
end
end
end
end
OnInit.final("ALICE", Init)
--#endregion
--===========================================================================================================================================================
--API
--===========================================================================================================================================================
--#region API
--Core API
--===========================================================================================================================================================
---Create an actor for the object host and add it to the cycle. If the host is a table and is provided as the only input argument, all other arguments will be retrieved directly from that table.
---@param host any
---@param identifier? string | string[]
---@param interactions? table
---@param flags? table
function ALICE_Create(host, identifier, interactions, flags)
if host == nil then
error("Host is nil.")
end
if identifier then
if flags and config.UNRECOGNIZED_FIELD_WARNINGS then
for key, __ in pairs(flags) do
if not recognizedFields[key] then
Warning("|cffff0000Warning:|r Unrecognized flag |cffffcc00" .. key .. "|r in flags passed to function ALICE_Create.")
recognizedFields[key] = true
end
end
end
Create(host, identifier, interactions, flags or EMPTY_TABLE)
else
if config.UNRECOGNIZED_FIELD_WARNINGS then
for key, __ in pairs(host) do
if not recognizedFields[key] then
Warning("|cffff0000Warning:|r Unrecognized field |cffffcc00" .. key .. "|r in host table passed to function ALICE_Create. To add fields, use ALICE_RecognizeFields.")
recognizedFields[key] = true
end
end
local mt = getmetatable(host)
if mt and mt.__index then
for key, __ in pairs(mt) do
if not recognizedFields[key] then
Warning("|cffff0000Warning:|r Unrecognized field |cffffcc00" .. key .. "|r in host table passed to function ALICE_Create. To add fields, use ALICE_RecognizeFields.")
recognizedFields[key] = true
end
end
end
end
Create(host, host.identifier, host.interactions, host)
end
end
---Destroy the actor of the specified object. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param keyword? string
function ALICE_Destroy(object, keyword)
local actor = GetActor(object, keyword)
if actor then
Destroy(actor)
end
end
---Calls the appropriate function to destroy the object, then destroys all actors attached to it. If the object is a table, the object:destroy() method will be called. If no destroy function exists, it will try to destroy the table's visual, which can be an effect, a unit, or an image.
---@param object Object
function ALICE_Kill(object)
if object == nil then
return
end
Kill(object)
Clear(object)
end
--Math API
--===========================================================================================================================================================
---Returns the distance between the objects of the pair currently being evaluated in two dimensions. This function uses cached values and may not be accurate if immediately called after changing an object's location.
---@return number
function ALICE_PairGetDistance2D()
local actorA = currentPair[ACTOR_A]
local actorB = currentPair[ACTOR_B]
if actorA and actorB == SELF_INTERACTION_ACTOR then
return 0
end
local anchorA = actorA.anchor
local anchorB = actorB.anchor
local dx = actorA.x[anchorA] - actorB.x[anchorB]
local dy = actorA.y[anchorA] - actorB.y[anchorB]
return sqrt(dx*dx + dy*dy)
end
---Returns the distance between the objects of the pair currently being evaluated in three dimensions. This function uses cached values and may not be accurate if immediately called after changing an object's location.
---@return number
function ALICE_PairGetDistance3D()
local actorA = currentPair[ACTOR_A]
local actorB = currentPair[ACTOR_B]
if actorA and actorB == SELF_INTERACTION_ACTOR then
return 0
end
local anchorA = actorA.anchor
local anchorB = actorB.anchor
local dx = actorA.x[anchorA] - actorB.x[anchorB]
local dy = actorA.y[anchorA] - actorB.y[anchorB]
local dz = actorA.z[actorA] - actorB.z[actorB]
return sqrt(dx*dx + dy*dy + dz*dz)
end
---Returns the angle from object A to object B of the pair currently being evaluated. This function uses cached values and may not be accurate if immediately called after changing an object's location.
---@return number
function ALICE_PairGetAngle2D()
local actorA = currentPair[ACTOR_A]
local actorB = currentPair[ACTOR_B]
if actorA and actorB == SELF_INTERACTION_ACTOR then
return 0
end
local anchorA = actorA.anchor
local anchorB = actorB.anchor
local dx = actorB.x[anchorB] - actorA.x[anchorA]
local dy = actorB.y[anchorB] - actorA.y[anchorA]
return atan(dy, dx)
end
---Returns the horizontal and vertical angles from object A to object B of the pair currently being evaluated. This function uses cached values and may not be accurate if immediately called after changing an object's location.
---@return number, number
function ALICE_PairGetAngle3D()
local actorA = currentPair[ACTOR_A]
local actorB = currentPair[ACTOR_B]
if actorA and actorB == SELF_INTERACTION_ACTOR then
return 0, 0
end
local anchorA = actorA.anchor
local anchorB = actorB.anchor
local dx = actorB.x[anchorB] - actorA.x[anchorA]
local dy = actorB.y[anchorB] - actorA.y[anchorA]
local dz = actorB.z[actorB] - actorA.z[actorA]
return atan(dy, dx), atan(dz, sqrt(dx*dx + dy*dy))
end
---Returns the coordinates of the objects in the pair currently being evaluated in the order x1, y1, x2, y2. This function uses cached values and may not be accurate if immediately called after changing an object's location.
---@return number, number, number, number
function ALICE_PairGetCoordinates2D()
local actorA = currentPair[ACTOR_A]
local actorB = currentPair[ACTOR_B]
local anchorA = actorA.anchor
local anchorB = actorB.anchor
return actorA.x[anchorA], actorA.y[anchorA], actorB.x[anchorB], actorB.y[anchorB]
end
---Returns the coordinates of the objects in the pair currently being evaluated in the order x1, y1, z1, x2, y2, z2. This function uses cached values and may not be accurate if immediately called after changing an object's location.
---@return number, number, number, number, number, number
function ALICE_PairGetCoordinates3D()
local actorA = currentPair[ACTOR_A]
local actorB = currentPair[ACTOR_B]
local anchorA = actorA.anchor
local anchorB = actorB.anchor
return actorA.x[anchorA], actorA.y[anchorA], actorA.z[actorA], actorB.x[anchorB], actorB.y[anchorB], actorB.z[actorB]
end
---Returns the coordinates x, y of an object. This function uses cached values and may not be accurate if immediately called after changing an object's location.
---@param object Object
---@param keyword? string
---@return number, number
function ALICE_GetCoordinates2D(object, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return 0, 0
end
local anchor = actor.anchor
return actor.x[anchor], actor.y[anchor]
end
---Returns the coordinates x, y, z of an object. This function uses cached values and may not be accurate if immediately called after changing an object's location.
---@param object Object
---@param keyword? string
---@return number, number, number
function ALICE_GetCoordinates3D(object, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return 0, 0, 0
end
local anchor = actor.anchor
return actor.x[anchor], actor.y[anchor], actor.z[actor]
end
--Callback API
--===========================================================================================================================================================
---Invokes the callback function after the specified delay, passing additional arguments into the callback function.
---@param callback function
---@param delay? number
---@vararg any
function ALICE_CallDelayed(callback, delay, ...)
local new = GetTable()
new.callCounter = cycle.unboundCounter + ((delay or 0)*INV_MIN_INTERVAL + 1) // 1
new.callback = callback
local numArgs = select("#", ...)
if numArgs == 1 then
new.args = select(1, ...)
elseif numArgs > 1 then
new.args = pack(...)
new.args.unpack = true
end
AddUserCallback(new)
end
---Invokes the callback function after the specified delay, passing the hosts of the current pair as arguments. A third parameter is passed into the callback, specifying whether you have access to the ALICE_Pair functions. You will not if the current pair has been destroyed after the callback was queued up.
---@param callback function
---@param delay? number
function ALICE_PairCallDelayed(callback, delay)
local new = GetTable()
new.callCounter = cycle.unboundCounter + ((delay or 0)*INV_MIN_INTERVAL + 1) // 1
new.callback = callback
new.hostA = currentPair[HOST_A]
new.hostB = currentPair[HOST_B]
new.pair = currentPair
AddUserCallback(new)
end
---Periodically invokes the callback function. Optional delay parameter to delay the first execution. Additional arguments are passed into the callback function. The return value of the callback function specifies the interval until next execution.
---@param callback function
---@param delay? number
---@vararg any
---@return table
function ALICE_CallPeriodic(callback, delay, ...)
local host = pack(...)
host.callback = callback
host.excess = delay or 0
local actor = CreateStub(host)
actor.periodicPair = CreatePair(actor, SELF_INTERACTION_ACTOR, PeriodicWrapper)
return host
end
---Periodically invokes the callback function up to howOften times. Optional delay parameter to delay the first execution. The arguments passed into the callback function are the current iteration, followed by any additional arguments. The return value of the callback function specifies the interval until next execution.
---@param callback function
---@param howOften integer
---@param delay? number
---@vararg any
---@return table
function ALICE_CallRepeated(callback, howOften, delay, ...)
local host = pack(...)
host.callback = callback
host.howOften = howOften
host.currentExecution = 0
host.excess = delay or 0
local actor = CreateStub(host)
actor.periodicPair = CreatePair(actor, SELF_INTERACTION_ACTOR, RepeatedWrapper)
return host
end
---Disables a periodic callback returned by ALICE_CallPeriodic or ALICE_CallRepeated. If called from within the callback function itself, the parameter can be omitted.
---@param callback? table
function ALICE_DisablePeriodic(callback)
local actor
if currentPair ~= OUTSIDE_OF_CYCLE then
actor = currentPair[ACTOR_A]
elseif callback then
actor = GetActor(callback)
else
Warning("|cffff0000Warning:|r Attempted to call ALICE_DisablePeriodic outside of callback function without specifying it.")
return
end
if actor.periodicPair == nil then
return
end
AddDelayedCallback(DestroyPair, actor.periodicPair)
DestroyStub(actor)
end
--Enum API
--===========================================================================================================================================================
---Enum functions return a table with all objects that have the specified identifier. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional condition to specify an additional filter function, which takes the enumerated objects as an argument and returns a boolean. Additional arguments are passed into the filter function.
---@param identifier string | table
---@param condition? function
---@vararg any
---@return table
function ALICE_EnumObjects(identifier, condition, ...)
local returnTable = GetTable()
if type(identifier) == "string" then
for __, actor in ipairs(actorList) do
if actor.identifier[identifier] and (condition == nil or condition(actor.host, ...)) and not enumExceptions[actor.host] then
if not actor.isSuspended then
returnTable[#returnTable + 1] = actor.host
end
enumExceptions[actor.host] = true
end
end
else
for __, actor in ipairs(actorList) do
if HasIdentifierFromTable(actor, identifier) and (condition == nil or condition(actor.host, ...)) and not enumExceptions[actor.host] then
if not actor.isSuspended then
returnTable[#returnTable + 1] = actor.host
end
enumExceptions[actor.host] = true
end
end
end
for key, __ in pairs(enumExceptions) do
enumExceptions[key] = nil
end
return returnTable
end
---Performs the action on all objects that have the specified identifier. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional condition to specify an additional filter function, which takes the enumerated objects as an argument and returns a boolean. Additional arguments are passed into both the filter and the action function.
---@param action function
---@param identifier string | table
---@param condition function | nil
---@vararg any
function ALICE_ForAllObjectsDo(action, identifier, condition, ...)
local list = ALICE_EnumObjects(identifier, condition, ...)
for __, object in ipairs(list) do
action(object, ...)
end
ReturnTable(list)
end
---Enum functions return a table with all objects that have the specified identifier. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional condition to specify an additional filter function, which takes the enumerated objects as an argument and returns a boolean. Additional arguments are passed into the filter function.
---@param x number
---@param y number
---@param range number
---@param identifier string | table
---@param condition? function
---@vararg any
---@return table
function ALICE_EnumObjectsInRange(x, y, range, identifier, condition, ...)
local returnTable = GetTable()
ResetCoordinateLookupTables()
local minX = min(NUM_CELLS_X, max(1, (NUM_CELLS_X*(x - range - MAP_MIN_X)/MAP_SIZE_X) // 1 + 1))
local minY = min(NUM_CELLS_Y, max(1, (NUM_CELLS_Y*(y - range - MAP_MIN_Y)/MAP_SIZE_Y) // 1 + 1))
local maxX = min(NUM_CELLS_X, max(1, (NUM_CELLS_X*(x + range - MAP_MIN_X)/MAP_SIZE_X) // 1 + 1))
local maxY = min(NUM_CELLS_Y, max(1, (NUM_CELLS_Y*(y + range - MAP_MIN_Y)/MAP_SIZE_Y) // 1 + 1))
local dx
local dy
local rangeSquared = range*range
local identifierIsString = type(identifier) == "string"
local actor, cell
for X = minX, maxX do
for Y = minY, maxY do
cell = CELL_LIST[X][Y]
actor = cell.first
if actor then
if identifierIsString then
for __ = 1, cell.numActors do
if actor.identifier[identifier] and (condition == nil or condition(actor.host, ...)) and not enumExceptions[actor.host] then
enumExceptions[actor.host] = true
dx = actor.x[actor.anchor] - x
dy = actor.y[actor.anchor] - y
if dx*dx + dy*dy < rangeSquared and not actor.isSuspended then
returnTable[#returnTable + 1] = actor.host
end
end
actor = actor.nextInCell[cell]
end
else
for __ = 1, cell.numActors do
if HasIdentifierFromTable(actor, identifier) and (condition == nil or condition(actor.host, ...)) and not enumExceptions[actor.host] then
enumExceptions[actor.host] = true
dx = actor.x[actor.anchor] - x
dy = actor.y[actor.anchor] - y
if dx*dx + dy*dy < rangeSquared and not actor.isSuspended then
returnTable[#returnTable + 1] = actor.host
end
end
actor = actor.nextInCell[cell]
end
end
end
end
end
for key, __ in pairs(enumExceptions) do
enumExceptions[key] = nil
end
return returnTable
end
---Performs the action on all objects that have the specified identifier. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional condition to specify an additional filter function, which takes the enumerated objects as an argument and returns a boolean. Additional arguments are passed into both the filter and the action function.
---@param action function
---@param x number
---@param y number
---@param range number
---@param identifier string | table
---@param condition? function
---@vararg any
function ALICE_ForAllObjectsInRangeDo(action, x, y, range, identifier, condition, ...)
local list = ALICE_EnumObjectsInRange(x, y, range, identifier, condition, ...)
for __, object in ipairs(list) do
action(object, ...)
end
ReturnTable(list)
end
---Enum functions return a table with all objects that have the specified identifier. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional condition to specify an additional filter function, which takes the enumerated objects as an argument and returns a boolean. Additional arguments are passed into the filter function.
---@param minx number
---@param miny number
---@param maxx number
---@param maxy number
---@param identifier string | table
---@param condition? function
---@vararg any
---@return table
function ALICE_EnumObjectsInRect(minx, miny, maxx, maxy, identifier, condition, ...)
local returnTable = GetTable()
ResetCoordinateLookupTables()
local minX = min(NUM_CELLS_X, max(1, (NUM_CELLS_X*(minx - MAP_MIN_X)/MAP_SIZE_X) // 1 + 1))
local minY = min(NUM_CELLS_Y, max(1, (NUM_CELLS_Y*(miny - MAP_MIN_Y)/MAP_SIZE_Y) // 1 + 1))
local maxX = min(NUM_CELLS_X, max(1, (NUM_CELLS_X*(maxx - MAP_MIN_X)/MAP_SIZE_X) // 1 + 1))
local maxY = min(NUM_CELLS_Y, max(1, (NUM_CELLS_Y*(maxy - MAP_MIN_Y)/MAP_SIZE_Y) // 1 + 1))
local identifierIsString = type(identifier) == "string"
local x
local y
local actor, cell
for X = minX, maxX do
for Y = minY, maxY do
cell = CELL_LIST[X][Y]
actor = cell.first
if actor then
if identifierIsString then
for __ = 1, cell.numActors do
if actor.identifier[identifier] and (condition == nil or condition(actor.host, ...)) and not enumExceptions[actor.host] then
enumExceptions[actor.host] = true
x = actor.x[actor.anchor]
y = actor.y[actor.anchor]
if x > minx and x < maxx and y > miny and y < maxy and not actor.isSuspended then
returnTable[#returnTable + 1] = actor.host
end
end
actor = actor.nextInCell[cell]
end
else
for __ = 1, cell.numActors do
if HasIdentifierFromTable(actor, identifier) and (condition == nil or condition(actor.host, ...)) and not enumExceptions[actor.host] then
enumExceptions[actor.host] = true
x = actor.x[actor.anchor]
y = actor.y[actor.anchor]
if x > minx and x < maxx and y > miny and y < maxy and not actor.isSuspended then
returnTable[#returnTable + 1] = actor.host
end
end
actor = actor.nextInCell[cell]
end
end
end
end
end
for key, __ in pairs(enumExceptions) do
enumExceptions[key] = nil
end
return returnTable
end
---Performs the action on all objects that have the specified identifier. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional condition to specify an additional filter function, which takes the enumerated objects as an argument and returns a boolean. Additional arguments are passed into both the filter and the action function.
---@param action function
---@param minx number
---@param miny number
---@param maxx number
---@param maxy number
---@param identifier string | table
---@param condition? function
---@vararg any
function ALICE_ForAllObjectsInRectDo(action, minx, miny, maxx, maxy, identifier, condition, ...)
local list = ALICE_EnumObjectsInRect(minx, miny, maxx, maxy, identifier, condition, ...)
for __, object in ipairs(list) do
action(object, ...)
end
ReturnTable(list)
end
---Enum functions return a table with all objects that have the specified identifier. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional condition to specify an additional filter function, which takes the enumerated objects as an argument and returns a boolean. Additional arguments are passed into the filter function.
---@param x1 number
---@param y1 number
---@param x2 number
---@param y2 number
---@param halfWidth number
---@param identifier string | table
---@param condition? function
---@vararg any
---@return table
function ALICE_EnumObjectsInLineSegment(x1, y1, x2, y2, halfWidth, identifier, condition, ...)
if x2 == x1 then
return ALICE_EnumObjectsInRect(x1 - halfWidth, min(y1, y2), x1 + halfWidth, max(y1, y2), identifier, condition, ...)
end
ResetCoordinateLookupTables()
local returnTable = GetTable()
local cells = GetTable()
local angle = atan(y2 - y1, x2 - x1)
local cosAngle = math.cos(angle)
local sinAngle = math.sin(angle)
local Xmin, Xmax, Ymin, Ymax, cRight, cLeft, slope
local XminRight = (NUM_CELLS_X*(x1 + halfWidth*sinAngle - MAP_MIN_X)/MAP_SIZE_X)
local XmaxRight = (NUM_CELLS_X*(x2 + halfWidth*sinAngle - MAP_MIN_X)/MAP_SIZE_X)
local YminRight = (NUM_CELLS_Y*(y1 - halfWidth*cosAngle - MAP_MIN_Y)/MAP_SIZE_Y)
local YmaxRight = (NUM_CELLS_Y*(y2 - halfWidth*cosAngle - MAP_MIN_Y)/MAP_SIZE_Y)
local XminLeft = (NUM_CELLS_X*(x1 - halfWidth*sinAngle - MAP_MIN_X)/MAP_SIZE_X)
local XmaxLeft = (NUM_CELLS_X*(x2 - halfWidth*sinAngle - MAP_MIN_X)/MAP_SIZE_X)
local YminLeft = (NUM_CELLS_Y*(y1 + halfWidth*cosAngle - MAP_MIN_Y)/MAP_SIZE_Y)
local YmaxLeft = (NUM_CELLS_Y*(y2 + halfWidth*cosAngle - MAP_MIN_Y)/MAP_SIZE_Y)
local identifierIsString = type(identifier) == "string"
slope = (y2 - y1)/(x2 - x1)
cRight = YminRight - XminRight*slope
cLeft = YminLeft - XminLeft*slope
if x2 > x1 then
if y2 > y1 then
Ymin = min(NUM_CELLS_Y, max(1, YminRight // 1)) + 1
Ymax = min(NUM_CELLS_Y, max(1, YmaxLeft // 1)) + 1
for j = Ymin, Ymax do
Xmin = min(NUM_CELLS_X, max(1, max((j - 1 - cLeft)/slope, XminLeft) // 1 + 1))
Xmax = min(NUM_CELLS_X, max(1, min((j - cRight)/slope, XmaxRight) // 1 + 1))
for i = Xmin, Xmax do
cells[#cells + 1] = CELL_LIST[i][j]
end
end
else
Ymin = min(NUM_CELLS_Y, max(1, YmaxRight // 1)) + 1
Ymax = min(NUM_CELLS_Y, max(1, YminLeft // 1)) + 1
for j = Ymin, Ymax do
Xmin = min(NUM_CELLS_X, max(1, max((j - cRight)/slope, XminRight) // 1 + 1))
Xmax = min(NUM_CELLS_X, max(1, min((j - 1 - cLeft)/slope, XmaxLeft) // 1 + 1))
for i = Xmin, Xmax do
cells[#cells + 1] = CELL_LIST[i][j]
end
end
end
else
if y2 > y1 then
Ymin = min(NUM_CELLS_Y, max(1, YminLeft // 1)) + 1
Ymax = min(NUM_CELLS_Y, max(1, YmaxRight // 1)) + 1
for j = Ymin, Ymax do
Xmin = min(NUM_CELLS_X, max(1, max((j - cLeft)/slope, XmaxLeft) // 1 + 1))
Xmax = min(NUM_CELLS_X, max(1, min((j - 1 - cRight)/slope, XminRight) // 1 + 1))
for i = Xmin, Xmax do
cells[#cells + 1] = CELL_LIST[i][j]
end
end
else
Ymin = min(NUM_CELLS_Y, max(1, YmaxLeft // 1)) + 1
Ymax = min(NUM_CELLS_Y, max(1, YminRight // 1)) + 1
for j = Ymin, Ymax do
Xmin = min(NUM_CELLS_X, max(1, max((j - 1 - cRight)/slope, XmaxRight) // 1 + 1))
Xmax = min(NUM_CELLS_X, max(1, min((j - cLeft)/slope, XminLeft) // 1 + 1))
for i = Xmin, Xmax do
cells[#cells + 1] = CELL_LIST[i][j]
end
end
end
end
local actor
local maxDist = sqrt((x2 - x1)^2 + (y2 - y1)^2)
local dx, dy, xPrime, yPrime
for __, cell in ipairs(cells) do
actor = cell.first
if actor then
if identifierIsString then
for __ = 1, cell.numActors do
if actor.identifier[identifier] and (condition == nil or condition(actor.host, ...)) and not enumExceptions[actor.host] then
enumExceptions[actor.host] = true
dx = actor.x[actor.anchor] - x1
dy = actor.y[actor.anchor] - y1
xPrime = cosAngle*dx + sinAngle*dy
yPrime = -sinAngle*dx + cosAngle*dy
if yPrime < halfWidth and yPrime > -halfWidth and xPrime > 0 and xPrime < maxDist and not actor.isSuspended then
returnTable[#returnTable + 1] = actor.host
end
end
actor = actor.nextInCell[cell]
end
else
for __ = 1, cell.numActors do
if HasIdentifierFromTable(actor, identifier) and (condition == nil or condition(actor.host, ...)) and not enumExceptions[actor.host] then
enumExceptions[actor.host] = true
dx = actor.x[actor.anchor] - x1
dy = actor.y[actor.anchor] - y1
xPrime = cosAngle*dx + sinAngle*dy
yPrime = -sinAngle*dx + cosAngle*dy
if yPrime < halfWidth and yPrime > -halfWidth and xPrime > 0 and xPrime < maxDist and not actor.isSuspended then
returnTable[#returnTable + 1] = actor.host
end
end
actor = actor.nextInCell[cell]
end
end
end
end
ReturnTable(cells)
for key, __ in pairs(enumExceptions) do
enumExceptions[key] = nil
end
return returnTable
end
---Performs the action on all objects that have the specified identifier. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional condition to specify an additional filter function, which takes the enumerated objects as an argument and returns a boolean. Additional arguments are passed into both the filter and the action function.
---@param action function
---@param x1 number
---@param y1 number
---@param x2 number
---@param y2 number
---@param halfWidth number
---@param identifier string | table
---@param condition? function
---@vararg any
function ALICE_ForAllObjectsInLineSegmentDo(action, x1, y1, x2, y2, halfWidth, identifier, condition, ...)
local list = ALICE_EnumObjectsInLineSegment(x1, y1, x2, y2, halfWidth, identifier, condition, ...)
for __, object in ipairs(list) do
action(object, ...)
end
ReturnTable(list)
end
---Returns the closest object to a point from among objects with the specified identifier. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional condition to specify an additional filter function, which takes the enumerated objects as an argument and returns a boolean. Additional arguments are passed into the filter function.
---@param x number
---@param y number
---@param identifier string | table
---@param cutOffDistance? number
---@param condition? function
---@vararg any
---@return Object | nil
function ALICE_GetClosestObject(x, y, identifier, cutOffDistance, condition, ...)
ResetCoordinateLookupTables()
cutOffDistance = cutOffDistance or 99999
local minX = min(NUM_CELLS_X, max(1, (NUM_CELLS_X*(x - cutOffDistance - MAP_MIN_X)/MAP_SIZE_X) // 1 + 1))
local minY = min(NUM_CELLS_Y, max(1, (NUM_CELLS_Y*(y - cutOffDistance - MAP_MIN_Y)/MAP_SIZE_Y) // 1 + 1))
local maxX = min(NUM_CELLS_X, max(1, (NUM_CELLS_X*(x + cutOffDistance - MAP_MIN_X)/MAP_SIZE_X) // 1 + 1))
local maxY = min(NUM_CELLS_Y, max(1, (NUM_CELLS_Y*(y + cutOffDistance - MAP_MIN_Y)/MAP_SIZE_Y) // 1 + 1))
local dx, dy
local closestDistSquared = cutOffDistance*cutOffDistance
local closestObject, thisDistSquared
local identifierIsString = type(identifier) == "string"
local actor, cell
for X = minX, maxX do
for Y = minY, maxY do
cell = CELL_LIST[X][Y]
actor = cell.first
if actor then
if identifierIsString then
for __ = 1, cell.numActors do
dx = actor.x[actor.anchor] - x
dy = actor.y[actor.anchor] - y
thisDistSquared = dx*dx + dy*dy
if thisDistSquared < closestDistSquared and actor.identifier[identifier] and (condition == nil or condition(actor.host, ...)) and not actor.isSuspended then
closestDistSquared = thisDistSquared
closestObject = actor.host
end
actor = actor.nextInCell[cell]
end
else
for __ = 1, cell.numActors do
dx = actor.x[actor.anchor] - x
dy = actor.y[actor.anchor] - y
thisDistSquared = dx*dx + dy*dy
if thisDistSquared < closestDistSquared and HasIdentifierFromTable(actor, identifier) and (condition == nil or condition(actor.host, ...)) and not actor.isSuspended then
closestDistSquared = thisDistSquared
closestObject = actor.host
end
actor = actor.nextInCell[cell]
end
end
end
end
end
return closestObject
end
--Debug API
--===========================================================================================================================================================
---Add fields that ALICE recognizes on actor creation for ALICE_UNRECOGNIZED_FIELD_WARNINGS.
---@vararg string | string[]
function ALICE_RecognizeFields(...)
local entry
for i = 1, select("#", ...) do
entry = select(i, ...)
if type(entry) == "table" then
for j = 1, #entry do
recognizedFields[select(j, ...)] = true
end
else
recognizedFields[select(i, ...)] = true
end
end
end
---Throws an error when a pair is initialized with the specified function and the listed fields are not present in the host table of the initiating (male) actor and/or the receiving (female) actor. For ALICE_REQUIRED_FIELD_WARNINGS.
---@param whichFunc function
---@param requireMale boolean
---@param requireFemale boolean
---@vararg string
function ALICE_FuncRequireFields(whichFunc, requireMale, requireFemale, ...)
functionRequiredFields[whichFunc] = functionRequiredFields[whichFunc] or {}
if requireMale then
functionRequiredFields[whichFunc].male = functionRequiredFields[whichFunc].male or {}
for i = 1, select("#", ...) do
functionRequiredFields[whichFunc].male[select(i, ...)] = true
end
end
if requireFemale then
functionRequiredFields[whichFunc].female = functionRequiredFields[whichFunc].female or {}
for i = 1, select("#", ...) do
functionRequiredFields[whichFunc].female[select(i, ...)] = true
end
end
ALICE_RecognizeFields(...)
end
---Sets the name of a function when displayed in debug mode.
---@param whichFunc function
---@param name string
function ALICE_FuncSetName(whichFunc, name)
functionName[whichFunc] = name
end
---Enable or disable debug mode.
---@param enable? boolean
function ALICE_Debug(enable)
if enable == nil or (not debug.enabled and enable == true) or (debug.enabled and enable == false) then
EnableDebugMode()
end
end
---List all global actors.
function ALICE_ListGlobals()
local message = "List of all global actors:"
for __, actor in ipairs(celllessActorList) do
if actor.isGlobal then
message = message .. "\n" .. Identifier2String(actor.identifier) .. ", Unique: " .. actor.unique
end
end
Warning(message)
end
---Select the specified object. Pass integer to select by unique number. Requires debug mode.
---@param object Object | integer
function ALICE_Select(object)
if not debug.enabled then
Warning("|cffff0000Error:|r ALICE_Select only available in debug mode.")
return
end
if type(object) == "number" then
for __, actor in ipairs(actorList) do
if actor.unique == object then
Select(actor)
SetCameraPosition(ALICE_GetCoordinates2D(actor))
return
end
end
Warning("\nNo actor exists with the specified unique number.")
else
local actor = GetActor(object)
if actor then
Select(object)
SetCameraPosition(ALICE_GetCoordinates2D(actor))
else
Warning("\nNo actor exists for the specified object.")
end
end
end
---Returns true if one of the actors in the current pair is selected.
---@return boolean
function ALICE_PairIsSelected()
return debug.selectedActor == currentPair[ACTOR_A] or debug.selectedActor == currentPair[ACTOR_B]
end
---Create a lightning effect between the objects of the current pair. Optional lightning type argument.
---@param lightningType? string
function ALICE_PairVisualize(lightningType)
VisualizationLightning(currentPair, lightningType or "DRAL")
end
---Pause the entire cycle. Optional pauseGame parameter to pause all units on the map.
---@param pauseGame? boolean
function ALICE_Halt(pauseGame)
cycle.isHalted = true
PauseTimer(MASTER_TIMER)
if pauseGame then
ALICE_ForAllObjectsDo(PauseUnit, "unit", nil, true)
end
debug.gameIsPaused = pauseGame
end
---Resume the entire cycle.
function ALICE_Resume()
cycle.isHalted = false
TimerStart(MASTER_TIMER, config.MIN_INTERVAL, true, Main)
if debug.gameIsPaused then
ALICE_ForAllObjectsDo(PauseUnit, "unit", nil, false)
debug.gameIsPaused = false
end
end
---Prints out statistics showing which functions are occupying which percentage of the calculations.
function ALICE_Statistics()
local countActivePairs = 0
local functionCount = {}
--Every Step Cycle
local thisPair = firstEveryStepPair
for __ = 1, numEveryStepPairs do
thisPair = thisPair[NEXT]
if not thisPair[DESTRUCTION_QUEUED] then
functionCount[thisPair[INTERACTION_FUNC]] = (functionCount[thisPair[INTERACTION_FUNC]] or 0) + 1
countActivePairs = countActivePairs + 1
end
end
local currentCounter = cycle.counter + 1
--Variable Step Cycle
local pairsThisStep = whichPairs[currentCounter]
for i = 1, numPairs[currentCounter] do
thisPair = pairsThisStep[i]
if not thisPair[DESTRUCTION_QUEUED] then
functionCount[thisPair[INTERACTION_FUNC]] = (functionCount[thisPair[INTERACTION_FUNC]] or 0) + 1
countActivePairs = countActivePairs + 1
end
end
if countActivePairs == 0 then
return "\nThere are no functions currently being evaluated."
end
local statistic = "Here is a breakdown of the functions currently being evaluated:"
local sortedKeys = {}
local count = 0
for key, __ in pairs(functionCount) do
count = count + 1
sortedKeys[count] = key
end
sort(sortedKeys, function(a, b) return functionCount[a] > functionCount[b] end)
for __, functionType in ipairs(sortedKeys) do
if (100*functionCount[functionType]/countActivePairs) > 0.1 then
statistic = statistic .. "\n" .. string.format("\x25.2f", 100*functionCount[functionType]/countActivePairs) .. "\x25 |cffffcc00" .. Function2String(functionType) .. "|r |cffaaaaaa(" .. functionCount[functionType] .. ")|r"
end
end
print(statistic)
end
---Continuously prints the cycle evaluation time and the number of actors, pair interactions, and cell checks until disabled.
function ALICE_Benchmark()
debug.benchmark = not debug.benchmark
end
---Prints the values of _G.whichVar[host], if _G.whichVar exists, as well as host.whichVar, if the host is a table, in the actor tooltips in debug mode. You can list multiple variables.
---@vararg ... string
function ALICE_TrackVariables(...)
for i = 1, select("#", ...) do
debug.trackedVariables[select(i, ...)] = true
end
end
---Attempts to find the pair of the specified objects and prints the state of that pair. Pass integers to select by unique numbers. Possible return values are "active", "outofrange", "paused", "disabled", and "uninitialized". Optional keyword parameters to specify actor with the keyword in its identifier for objects with multiple actors.
---@param objectA Object | integer
---@param objectB Object | integer
---@param keywordA? string
---@param keywordB? string
---@return string
function ALICE_GetPairState(objectA, objectB, keywordA, keywordB)
local actorA, actorB
if type(objectA) == "number" then
for __, actor in ipairs(actorList) do
if actor.unique == objectA then
actorA = actor
break
end
end
if actorA == nil then
Warning("\nNo actor exists with unique number " .. objectA .. ".")
end
else
actorA = GetActor(objectA, keywordA)
if actorA == nil then
Warning("\nNo actor exists for the specified object.")
end
end
if type(objectB) == "number" then
for __, actor in ipairs(actorList) do
if actor.unique == objectB then
actorB = actor
break
end
end
if actorB == nil then
Warning("\nNo actor exists with unique number " .. objectB .. ".")
end
else
actorB = GetActor(objectB, keywordB)
if actorB == nil then
Warning("\nNo actor exists for the specified object.")
end
end
local thisPair = pairList[actorA][actorB] or pairList[actorB][actorA]
if thisPair then
if thisPair[PAUSED] then
return "paused"
elseif (thisPair[EVERY_STEP] and thisPair[PREVIOUS]) or (not thisPair[EVERY_STEP] and thisPair[CURRENT_POSITION] ~= DO_NOT_EVALUATE) then
return "active"
else
return "outofrange"
end
elseif pairingExcluded[actorA][actorB] then
return "disabled"
else
return "uninitialized"
end
end
---Create lightning effects around all cells.
function ALICE_VisualizeAllCells()
debug.visualizeAllCells = not debug.visualizeAllCells
if debug.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_SIZE_X
local miny = MAP_MIN_Y + (Y-1)/NUM_CELLS_Y*MAP_SIZE_Y
local maxx = MAP_MIN_X + X/NUM_CELLS_X*MAP_SIZE_X
local maxy = MAP_MIN_Y + Y/NUM_CELLS_Y*MAP_SIZE_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
---Creates arrows above all non-global actors.
function ALICE_VisualizeAllActors()
debug.visualizeAllActors = not debug.visualizeAllActors
if debug.visualizeAllActors then
for __, actor in ipairs(actorList) do
if not actor.isGlobal and actor ~= debug.selectedActor then
CreateVisualizer(actor)
end
end
else
for __, actor in ipairs(actorList) do
if not actor.isGlobal and actor ~= debug.selectedActor then
DestroyEffect(actor.visualizer)
end
end
end
end
--Pair Utility API
--===========================================================================================================================================================
---Returns true if the owners of the objects in the current pair are allies.
---@return boolean
function ALICE_PairIsFriend()
local actorA = currentPair[ACTOR_A]
local actorB = currentPair[ACTOR_B]
local ownerA = actorA.getOwner(actorA.host)
local ownerB = actorB.getOwner(actorB.host)
return IsPlayerAlly(ownerA, ownerB)
end
---Returns true if the owners of the objects in the current pair are enemies.
---@return boolean
function ALICE_PairIsEnemy()
local actorA = currentPair[ACTOR_A]
local actorB = currentPair[ACTOR_B]
local ownerA = actorA.getOwner(actorA.host)
local ownerB = actorB.getOwner(actorB.host)
return IsPlayerEnemy(ownerA, ownerB)
end
---Changes the interactionFunc of the pair currently being evaluated. You cannot replace a function without a return value with one that has a return value.
---@param whichFunc function
function ALICE_PairSetInteractionFunc(whichFunc)
if currentPair[ACTOR_B] == SELF_INTERACTION_ACTOR then
currentPair[ACTOR_A].selfInteractions[currentPair[INTERACTION_FUNC]] = nil
currentPair[ACTOR_A].selfInteractions[whichFunc] = currentPair
end
currentPair[INTERACTION_FUNC] = whichFunc
end
---Disables interactions between the actors of the current pair after this one.
function ALICE_PairDisable()
if not functionIsUnbreakable[currentPair[INTERACTION_FUNC]] and currentPair[ACTOR_B] ~= SELF_INTERACTION_ACTOR then
pairingExcluded[currentPair[ACTOR_A]][currentPair[ACTOR_B]] = true
pairingExcluded[currentPair[ACTOR_B]][currentPair[ACTOR_A]] = true
end
if currentPair[DESTRUCTION_QUEUED] then
return
end
if currentPair[ACTOR_B] == SELF_INTERACTION_ACTOR then
currentPair[ACTOR_A].selfInteractions[currentPair[INTERACTION_FUNC]] = nil
end
currentPair[DESTRUCTION_QUEUED] = true
AddDelayedCallback(DestroyPair, currentPair)
end
---Modifies the return value of an interactionFunc so that, on average, the interval is the specified value, even if it isn't an integer multiple of the minimum interval.
---@param value number
---@return number
function ALICE_PairPreciseInterval(value)
local ALICE_MIN_INTERVAL = config.MIN_INTERVAL
local data = ALICE_PairLoadData()
local numSteps = (value*INV_MIN_INTERVAL + 1) // 1
local newDelta = (data.returnDelta or 0) + value - ALICE_MIN_INTERVAL*numSteps
if newDelta > 0.5*ALICE_MIN_INTERVAL then
newDelta = newDelta - ALICE_MIN_INTERVAL
numSteps = numSteps + 1
data.returnDelta = newDelta
elseif newDelta < -0.5*ALICE_MIN_INTERVAL then
newDelta = newDelta + ALICE_MIN_INTERVAL
numSteps = numSteps - 1
data.returnDelta = newDelta
if numSteps == 0 and not currentPair[DESTRUCTION_QUEUED] then
currentPair[INTERACTION_FUNC](currentPair[HOST_A], currentPair[HOST_B])
end
else
data.returnDelta = newDelta
end
return ALICE_MIN_INTERVAL*numSteps
end
---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.
function ALICE_PairIsUnoccupied()
if currentPair[ACTOR_B][currentPair[INTERACTION_FUNC]] and currentPair[ACTOR_B][currentPair[INTERACTION_FUNC]] ~= currentPair then
return false
else
--Store for the female actor at the key of the interaction func the current pair as occupying that slot, blocking other pairs.
currentPair[ACTOR_B][currentPair[INTERACTION_FUNC]] = currentPair
return true
end
end
---Returns the remaining cooldown for this pair, then invokes a cooldown of the specified duration. Optional cooldownType parameter to create and differentiate between multiple separate cooldowns.
---@param duration number
---@param cooldownType? string
---@return number
function ALICE_PairCooldown(duration, cooldownType)
currentPair[COOLDOWN] = currentPair[COOLDOWN] or GetTable()
local key = cooldownType or "default"
local cooldownExpiresStep = currentPair[COOLDOWN][key]
if cooldownExpiresStep == nil or cooldownExpiresStep <= cycle.unboundCounter then
currentPair[COOLDOWN][key] = cycle.unboundCounter + (duration*INV_MIN_INTERVAL + 1) // 1
return 0
else
return (cooldownExpiresStep - cycle.unboundCounter)*config.MIN_INTERVAL
end
end
---Returns a table unique to the pair currently being evaluated, which can be used to read and write data. Optional argument to set a metatable for the data table.
---@param whichMetatable? table
---@return table
function ALICE_PairLoadData(whichMetatable)
if currentPair[USER_DATA] == nil then
currentPair[USER_DATA] = GetTable()
setmetatable(currentPair[USER_DATA], whichMetatable)
end
return currentPair[USER_DATA]
end
---Returns true if this is the first time this function was invoked for the current pair, otherwise false. Resets when the objects in the pair leave the interaction range.
---@return boolean
function ALICE_PairIsFirstContact()
if currentPair[HAD_CONTACT] == nil then
currentPair[HAD_CONTACT] = true
return true
else
return false
end
end
---Calls the initFunc with the hosts as arguments whenever a pair is created with the specified interactions.
---@param whichFunc function
---@param initFunc function
function ALICE_FuncSetInit(whichFunc, initFunc)
functionInitializer[whichFunc] = initFunc
end
---Executes the function onDestroyFunc(objectA, objectB, pairData) when a pair using the specified function is destroyed. Only one callback per function.
---@param whichFunc function
---@param onDestroyFunc function
function ALICE_FuncSetOnDestroy(whichFunc, onDestroyFunc)
functionOnDestroy[whichFunc] = onDestroyFunc
end
---Executes the function onBreakFunc(objectA, objectB, pairData, wasDestroyed) when a pair using the specified function is destroyed or the actors leave interaction range. Only one callback per function.
---@param whichFunc function
---@param onBreakFunc function
function ALICE_FuncSetOnBreak(whichFunc, onBreakFunc)
functionOnBreak[whichFunc] = onBreakFunc
end
---Executes the function onResetFunc(objectA, objectB, pairData, wasDestroyed) when a pair using the specified function is destroyed, the actors leave interaction range, or the ALICE_PairReset function is called, but only if ALICE_PairIsFirstContact has been called previously. Only one callback per function.
---@param whichFunc function
---@param onResetFunc function
function ALICE_FuncSetOnReset(whichFunc, onResetFunc)
functionOnReset[whichFunc] = onResetFunc
end
---Purge pair data, call onDestroy method and reset ALICE_PairIsFirstContact and ALICE_PairIsUnoccupied functions.
function ALICE_PairReset()
if currentPair[HAD_CONTACT] then
if functionOnReset[currentPair[INTERACTION_FUNC]] and not cycle.isCrash then
functionOnReset[currentPair[INTERACTION_FUNC]](currentPair[HOST_A], currentPair[HOST_B], currentPair[USER_DATA], false)
end
currentPair[HAD_CONTACT] = nil
end
if currentPair[ACTOR_B][currentPair[INTERACTION_FUNC]] == currentPair then
currentPair[ACTOR_B][currentPair[INTERACTION_FUNC]] = nil
end
currentPair[ACTOR_B][currentPair[INTERACTION_FUNC]] = nil
end
--Widget API
--===========================================================================================================================================================
---Widgets with the specified fourCC codes will always receive actors, indepedent of the config.
---@vararg string | integer
function ALICE_IncludeTypes(...)
for i = 1, select("#", ...) do
local whichType = select(i, ...)
if type(whichType) == "string" then
widgets.idInclusions[FourCC(whichType)] = true
else
widgets.idInclusions[whichType] = true
end
end
end
---Widgets with the specified fourCC codes will not receive actors, indepedent of the config.
---@vararg string | integer
function ALICE_ExcludeTypes(...)
for i = 1, select("#", ...) do
local whichType = select(i, ...)
if type(whichType) == "string" then
widgets.idExclusions[FourCC(whichType)] = true
else
widgets.idExclusions[whichType] = true
end
end
end
---Injects the functions listed in the hookTable into the hooks created by ALICE. The hookTable can have the keys: onUnitEnter - The listed function is called for all preplaced units and whenever a unit enters the map or a hero is revived. onUnitDeath - The listed function is called when a unit dies. onUnitRevive - The listed function is called when a nonhero unit is revived. onUnitRemove - The listed function is called when a unit is removed from the game or its corpse decays fully. onDestructableEnter - The listed function is called for all preplaced destructables and whenever a destructable is created. onDestructableDestroy - The listed function is called when a destructable dies or is removed. onItemEnter - The listed function is called for all preplaced items and whenever an item is dropped or created. onItemDestroy - The listed function is called when an item is destroyed, removed, or picked up.
---@param hookTable table
function ALICE_OnWidgetEvent(hookTable)
insert(eventHooks.onUnitEnter, hookTable.onUnitEnter)
insert(eventHooks.onUnitDeath, hookTable.onUnitDeath)
insert(eventHooks.onUnitRevive, hookTable.onUnitRevive)
insert(eventHooks.onUnitRemove, hookTable.onUnitRemove)
insert(eventHooks.onUnitChangeOwner, hookTable.onUnitChangeOwner)
insert(eventHooks.onDestructableEnter, hookTable.onDestructableEnter)
insert(eventHooks.onDestructableDestroy, hookTable.onDestructableDestroy)
insert(eventHooks.onItemEnter, hookTable.onItemEnter)
insert(eventHooks.onItemDestroy, hookTable.onItemDestroy)
for key, __ in pairs(hookTable) do
if not eventHooks[key] then
Warning("|cffff0000Warning:|r Unrecognized key " .. key .. " in hookTable passed to ALICE_OnWidgetEvent.")
end
end
if hookTable.onDeath and not config.UNITS_LEAVE_BEHIND_CORPSES then
Warning("|cffff0000Warning:|r Attempted to create onDeath unit event hook, but ALICE_UNITS_LEAVE_BEHIND_CORPSES is not enabled. Use onRemove instead.")
end
end
--Identifier API
--===========================================================================================================================================================
---Add identifier(s) to an object and pair it with all other objects it is now eligible to be paired with. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param newIdentifier string | string[]
---@param keyword? string
function ALICE_AddIdentifier(object, newIdentifier, keyword)
local actor = GetActor(object, keyword)
if actor == nil or newIdentifier == nil then
return
end
if type(newIdentifier) == "string" then
actor.identifier[newIdentifier] = true
else
for __, word in ipairs(newIdentifier) do
actor.identifier[word] = true
end
end
AssignActorClass(actor, true, false)
AddDelayedCallback(DestroyObsoletePairs, actor)
AddDelayedCallback(Flicker, actor)
end
---Remove identifier(s) from an object and remove all pairings with objects it is no longer eligible to be paired with. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param toRemove string | string[]
---@param keyword? string
function ALICE_RemoveIdentifier(object, toRemove, keyword)
local actor = GetActor(object, keyword)
if actor == nil or toRemove == nil then
return
end
if type(toRemove) == "string" then
if actor.identifier[toRemove] == nil then
return
end
actor.identifier[toRemove] = nil
else
local removedSomething = false
for __, word in ipairs(toRemove) do
if actor.identifier[word] then
removedSomething = true
actor.identifier[word] = nil
end
end
if not removedSomething then
return
end
end
AssignActorClass(actor, true, false)
AddDelayedCallback(DestroyObsoletePairs, actor)
AddDelayedCallback(Flicker, actor)
end
---Exchanges one of the object's identifier with another. If the old identifier is not found, the new one won't be added. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param oldIdentifier string
---@param newIdentifier string
---@param keyword? string
function ALICE_SwapIdentifier(object, oldIdentifier, newIdentifier, keyword)
local actor = GetActor(object, keyword)
if actor == nil or oldIdentifier == nil or newIdentifier == nil then
return
end
if actor.identifier[oldIdentifier] == nil then
return
end
actor.identifier[oldIdentifier] = nil
actor.identifier[newIdentifier] = true
AssignActorClass(actor, true, false)
AddDelayedCallback(DestroyObsoletePairs, actor)
AddDelayedCallback(Flicker, actor)
end
---Sets the object's identifier to a string or string sequence.
---@param object Object
---@param newIdentifier string | string[]
---@param keyword? string
function ALICE_SetIdentifier(object, newIdentifier, keyword)
local actor = GetActor(object, keyword)
if actor == nil or newIdentifier == nil then
return
end
for word, __ in pairs(actor.identifier) do
actor.identifier[word] = nil
end
if type(newIdentifier) == "string" then
actor.identifier[newIdentifier] = true
else
for __, word in ipairs(newIdentifier) do
actor.identifier[word] = true
end
end
AssignActorClass(actor, true, false)
AddDelayedCallback(DestroyObsoletePairs, actor)
AddDelayedCallback(Flicker, actor)
end
---Checks if the object has the specified identifiers. Identifier can be a string or a table. If it is a table, the last entry must be MATCHING_TYPE_ANY or MATCHING_TYPE_ALL. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param identifier string | table
---@param keyword? string
---@return boolean
function ALICE_HasIdentifier(object, identifier, keyword)
local actor = GetActor(object, keyword)
if actor == nil or identifier == nil then
return false
end
if type(identifier) == "string" then
return actor.identifier[identifier] == true
else
return HasIdentifierFromTable(actor, identifier)
end
end
---Compiles the identifiers of an object into the provided table or a new table. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param keyword? string
---@param table? table
function ALICE_GetIdentifier(object, keyword, table)
local actor = GetActor(object, keyword)
if actor == nil then
return
end
local returnTable = table or {}
for key, __ in pairs(actor.identifier) do
insert(returnTable, key)
end
sort(returnTable)
return returnTable
end
---Returns the first entry in the given list of identifiers for which an actor exists for the specified object.
---@param object Object
---@vararg ... string
---@return string | nil
function ALICE_FindIdentifier(object, ...)
local identifier
for i = 1, select("#", ...) do
identifier = select(i, ...)
if GetActor(object, identifier) then
return identifier
end
end
return nil
end
---If table is a table with identifier keys, returns the field that matches with the specified object's identifier. If no match is found, returns table.other. If table is not a table, returns the variable itself. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param table any
---@param object Object
---@param keyword? string
---@return any
function ALICE_FindField(table, object, keyword)
if type(table) ~= "table" then
return table
end
local actor = GetActor(object, keyword)
if actor == nil then
return nil
end
local identifier = actor.identifier
local entry
local level = 0
local conflict = false
for key, value in pairs(table) do
if type(key) == "string" then
if identifier[key] then
if level < 1 then
entry = value
level = 1
elseif level == 1 then
conflict = true
end
end
else
local match = true
for __, tableKey in ipairs(key) do
if not identifier[tableKey] then
match = false
break
end
end
if match then
if #key > level then
entry = value
level = #key
conflict = false
elseif #key == level then
conflict = true
end
end
end
end
if entry == nil and table.other then
return table.other
end
if conflict then
Warning("Return value ambiguous in ALICE_FindField for " .. Identifier2String(object.identifier) .. ".")
return nil
end
return entry
end
--Interaction API
--===========================================================================================================================================================
---Changes the interaction function of the specified object towards the target identifier to the specified function or removes it. Pairs already established will not be affected. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param target string | string[]
---@param interactionFunc function | nil
---@param keyword? string
function ALICE_SetInteractionFunc(object, target, interactionFunc, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return
end
if actor.interactions[target] ~= interactionFunc then
actor.interactions[target] = interactionFunc
AssignActorClass(actor, false, true)
Flicker(actor)
end
end
---Adds a self-interaction with the specified function to the object. If a self-interaction with that function already exists, nothing happens. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param whichFunc function
---@param keyword? string
function ALICE_AddSelfInteraction(object, whichFunc, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return
end
if actor.selfInteractions[whichFunc] then
return
end
actor.selfInteractions[whichFunc] = CreatePair(actor, SELF_INTERACTION_ACTOR, whichFunc)
end
---Removes the self-interaction with the specified function from the object. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param whichFunc function
---@param keyword? string
function ALICE_RemoveSelfInteraction(object, whichFunc, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return
end
if actor.selfInteractions[whichFunc] == nil then
return
end
local pair = actor.selfInteractions[whichFunc]
actor.selfInteractions[whichFunc] = nil
AddDelayedCallback(DestroyPair, pair)
end
---Checks if the object has a self-interaction with the specified function. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param whichFunc function
---@param keyword? string
---@return boolean
function ALICE_HasSelfInteraction(object, whichFunc, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return false
end
return actor.selfInteractions[whichFunc] ~= nil
end
--Misc API
--===========================================================================================================================================================
---The first interaction of all pairs using this function will be delayed by the specified number.
---@param whichFunc function
---@param delay number
function ALICE_FuncSetDelay(whichFunc, delay)
if delay > config.MAX_INTERVAL then
Warning("|cffff0000Warning:|r Delay specified in ALICE_FuncSetDelay is greater than ALICE_MAX_INTERVAL.")
end
functionDelay[whichFunc] = min(config.MAX_INTERVAL, delay)
end
---Changes the behavior of pairs using the specified function so that the interactions continue to be evaluated when the two objects leave their interaction range. Also changes the behavior of ALICE_PairDisable to not prevent the two object from pairing again.
---@param whichFunc function
function ALICE_FuncSetUnbreakable(whichFunc)
functionIsUnbreakable[whichFunc] = true
end
---Changes the behavior of the specified function such that pairs using this function will persist if a unit is loaded into a transport or an item is picked up by a unit.
---@param whichFunc function
function ALICE_FuncSetUnsuspendable(whichFunc)
functionIsUnsuspendable[whichFunc] = true
end
---Automatically pauses and unpauses all pairs using the specified function whenever the initiating (male) actor is set to stationary/not stationary.
---@param whichFunc function
function ALICE_FuncPauseOnStationary(whichFunc)
functionPauseOnStationary[whichFunc] = true
end
---Checks if an actor exists with the specified identifier for the specified object. Optional strict flag to exclude actors that are anchored to that object.
---@param object Object
---@param identifier string
---@param strict? boolean
---@return boolean
function ALICE_HasActor(object, identifier, strict)
local actor = GetActor(object, identifier)
if actor == nil then
return false
end
return not strict or actor.host == object
end
---Returns the object the specified object is anchored to or itself if there is no anchor.
---@param object Object
---@return Object | nil
function ALICE_GetAnchor(object)
local actor = GetActor(object)
if actor == nil then
return object
end
return actor.originalAnchor
end
---Accesses all objects anchored to the specified object and returns the one with the specified identifier.
---@param object Object
---@param identifier string
---@return Object | nil
function ALICE_GetAnchoredObject(object, identifier)
local actor = GetActor(object, identifier)
if actor == nil then
return nil
end
return actor.host
end
---Sets the value of a flag for the actor of an object to the specified value. To change the isStationary flag, use ALICE_SetStationary instead. Cannot change hasInfiniteRange flag. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param whichFlag string
---@param value any
---@param keyword? string
function ALICE_SetFlag(object, whichFlag, value, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return
end
assert(recognizedFields[whichFlag], "Flag " .. whichFlag .. " is not recognized.")
assert(SetFlag[whichFlag], "Flag " .. whichFlag .. " cannot be changed with ALICE_SetFlag.")
SetFlag[whichFlag](actor, value)
end
---Returns the value stored for the specified flag of the specified actor. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param whichFlag string
---@param keyword? string
---@return any
function ALICE_GetFlag(object, whichFlag, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return
end
assert(recognizedFields[whichFlag], "Flag " .. whichFlag .. " is not recognized.")
if whichFlag == "radius" then
return actor.halfWidth
elseif whichFlag == "width" then
return 2*actor.halfWidth
elseif whichFlag == "height" then
return 2*actor.halfHeight
elseif whichFlag == "cellCheckInterval" then
return actor.cellCheckInterval*config.MIN_INTERVAL
elseif whichFlag == "anchor" then
return actor.originalAnchor
else
return actor[whichFlag]
end
end
---Returns the owner of the specified object. Faster than GetOwningPlayer. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param keyword? string
---@return player | nil
function ALICE_GetOwner(object, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return object
end
return actor.getOwner(actor.host)
end
--Pair Access API
--===========================================================================================================================================================
---Restore a pair that has been previously destroyed with ALICE_PairDisable. Returns two booleans. The first denotes whether a pair now exists and the second if it was just created.
---@param objectA Object
---@param objectB Object
---@param keywordA? string
---@param keywordB? string
---@return boolean, boolean
function ALICE_Enable(objectA, objectB, keywordA, keywordB)
local actorA = GetActor(objectA, keywordA)
local actorB = GetActor(objectB, keywordB)
if actorA == nil or actorB == nil then
return false, false
end
if pairingExcluded[actorA][actorB] == nil then
if pairList[actorA][actorB] or pairList[actorB][actorA] then
return true, false
else
return false, false
end
end
pairingExcluded[actorA][actorB] = nil
pairingExcluded[actorB][actorA] = nil
if (not actorA.usesCells or not actorB.usesCells or SharesCellWith(actorA, actorB)) then
local actorAFunc = GetInteractionFunc(actorA, actorB)
local actorBFunc = GetInteractionFunc(actorB, actorA)
if actorAFunc and actorBFunc then
if actorA.priority < actorB.priority then
CreatePair(actorB, actorA, actorBFunc)
return true, true
else
CreatePair(actorA, actorB, actorAFunc)
return true, true
end
elseif actorAFunc then
CreatePair(actorA, actorB, actorAFunc)
return true, true
elseif actorBFunc then
CreatePair(actorB, actorA, actorBFunc)
return true, true
end
end
return false, false
end
---Access the pair for objects A and B and, if it exists, return the data table stored for that pair. If objectB is a function, returns the data of the self-interaction of objectA using the specified function.
---@param objectA Object
---@param objectB Object | function
---@param keywordA? string
---@param keywordB? string
---@return table | nil
function ALICE_AccessData(objectA, objectB, keywordA, keywordB)
local actorA = GetActor(objectA, keywordA)
local actorB
local whichPair
if type(objectB) == "function" then
whichPair = actorA.selfInteractions[objectB]
else
actorB = GetActor(objectB, keywordB)
if actorA == nil or actorB == nil then
return nil
end
whichPair = pairList[actorA][actorB] or pairList[actorB][actorA]
end
if whichPair then
if whichPair[USER_DATA] then
return whichPair[USER_DATA]
else
whichPair[USER_DATA] = GetTable()
return whichPair[USER_DATA]
end
end
return nil
end
---Access the pair for objects A and B and, if it is paused, unpause it. If objectB is a function, unpauses the self-interaction of objectA using the specified function.
---@param objectA Object
---@param objectB Object | function
---@param keywordA? string
---@param keywordB? string
function ALICE_UnpausePair(objectA, objectB, keywordA, keywordB)
local actorA = GetActor(objectA, keywordA)
local actorB
local whichPair
if type(objectB) == "function" then
whichPair = actorA.selfInteractions[objectB]
else
actorB = GetActor(objectB, keywordB)
if actorA == nil or actorB == nil then
return nil
end
whichPair = pairList[actorA][actorB] or pairList[actorB][actorA]
end
if whichPair then
AddDelayedCallback(UnpausePair, whichPair)
end
end
---Access the pair for objects A and B and, if it exists, perform the specified action. Returns the return value of the action function. The hosts of the pair as well as any additional parameters are passed into the action function. If objectB is a function, access the pair of the self-inteaction of objectA using the specified function.
---@param action function
---@param objectA Object
---@param objectB Object | function
---@param keywordA? string
---@param keywordB? string
---@vararg any
---@return any
function ALICE_GetPairAndDo(action, objectA, objectB, keywordA, keywordB, ...)
local actorA = GetActor(objectA, keywordA)
local actorB
local whichPair
if type(objectB) == "function" then
whichPair = actorA.selfInteractions[objectB]
else
actorB = GetActor(objectB, keywordB)
if actorA == nil or actorB == nil then
return nil
end
whichPair = pairList[actorA][actorB] or pairList[actorB][actorA]
end
if whichPair then
local tempPair = currentPair
currentPair = whichPair
local returnValue = action(whichPair[HOST_A], whichPair[HOST_B], ...)
currentPair = tempPair
return returnValue
end
end
---Access all pairs for the object using the specified interactionFunc and perform the specified action. The hosts of the pairs as well as any additional parameters are passed into the action function. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param action function
---@param object Object
---@param whichFunc function
---@param includeInactive? boolean
---@param keyword? string
---@vararg any
function ALICE_ForAllPairsDo(action, object, whichFunc, includeInactive, keyword, ...)
local actor = GetActor(object, keyword)
if actor == nil then
return
end
local INTERACTION_FUNC = INTERACTION_FUNC
local EVERY_STEP = EVERY_STEP
local PREVIOUS = PREVIOUS
local CURRENT_POSITION = CURRENT_POSITION
local DO_NOT_EVALUATE = DO_NOT_EVALUATE
local next = actor.nextPair
local thisPair = next[actor.firstPair]
local tempPair = currentPair
while thisPair do
if thisPair[INTERACTION_FUNC] == whichFunc and (includeInactive or (thisPair[EVERY_STEP] and thisPair[PREVIOUS] ~= nil) or (not thisPair[EVERY_STEP] and thisPair[CURRENT_POSITION] ~= DO_NOT_EVALUATE)) then
currentPair = thisPair
action(thisPair[HOST_A], thisPair[HOST_B], ...)
end
thisPair = next[thisPair]
end
currentPair = tempPair
end
--Optimization API
--===========================================================================================================================================================
---Pauses interactions of the current pair after this one. Resume with an unpause function.
function ALICE_PairPause()
AddDelayedCallback(PausePair, currentPair)
end
---Unpauses all paused interactions of the object. Optional whichFunctions argument, which can be a function or a function sequence, to limit unpausing to pairs using those functions. Optional keyword parameter to specify actor with the keyword in its identifier for an object with multiple actors.
---@param object Object
---@param whichFunctions? function | table
---@param keyword? string
function ALICE_Unpause(object, whichFunctions, keyword)
local actor = GetActor(object, keyword)
if actor == nil then
return
end
if type(whichFunctions) == "table" then
for key, value in ipairs(whichFunctions) do
whichFunctions[value] = true
whichFunctions[key] = nil
end
elseif whichFunctions then
local functionsTable = GetTable()
functionsTable[whichFunctions] = true
whichFunctions = functionsTable
end
AddDelayedCallback(Unpause, actor, whichFunctions)
end
---Sets an object to stationary/not stationary. Will affect all actors attached to the object.
---@param object Object
---@param enable? boolean
function ALICE_SetStationary(object, enable)
objectIsStationary[object] = enable ~= false
if actorOf[object] == nil then
return
end
if actorOf[object].isActor then
SetStationary(actorOf[object], enable ~= false)
else
for __, actor in ipairs(actorOf[object]) do
SetStationary(actor, enable ~= false)
end
end
end
---Returns whether the specified object is set to stationary.
---@param object Object
function ALICE_IsStationary(object)
return objectIsStationary[object]
end
---The first interaction of all pairs using this function will be delayed by up to the specified number, distributing individual calls over the interval to prevent computation spikes.
---@param whichFunc function
---@param interval number
function ALICE_FuncDistribute(whichFunc, interval)
if interval > config.MAX_INTERVAL then
Warning("|cffff0000Warning:|r Delay specified in ALICE_FuncDistribute is greater than ALICE_MAX_INTERVAL.")
end
functionDelay[whichFunc] = interval
functionDelayIsDistributed[whichFunc] = true
functionDelayCurrent[whichFunc] = 0
end
--Modular API
--===========================================================================================================================================================
---Executes the specified function before an object with the specified identifier is created. The function is called with the host as the parameter.
---@param matchingIdentifier string
---@param whichFunc function
function ALICE_OnCreation(matchingIdentifier, whichFunc)
onCreation.funcs[matchingIdentifier] = onCreation.funcs[matchingIdentifier] or {}
insert(onCreation.funcs[matchingIdentifier], whichFunc)
end
---Add a flag with the specified value to objects with matchingIdentifier when they are created. If a function is provided for value, the returned value of the function will be added.
---@param matchingIdentifier string
---@param flag string
---@param value any
function ALICE_OnCreationAddFlag(matchingIdentifier, flag, value)
if not OVERWRITEABLE_FLAGS[flag] then
error("Flag " .. flag .. " cannot be overwritten with ALICE_OnCreationAddFlag.")
end
onCreation.flags[matchingIdentifier] = onCreation.flags[matchingIdentifier] or {}
onCreation.flags[matchingIdentifier][flag] = value
end
---Adds an additional identifier to objects with matchingIdentifier when they are created. If a function is provided for value, the returned string of the function will be added.
---@param matchingIdentifier string
---@param value string | function
function ALICE_OnCreationAddIdentifier(matchingIdentifier, value)
onCreation.identifiers[matchingIdentifier] = onCreation.identifiers[matchingIdentifier] or {}
insert(onCreation.identifiers[matchingIdentifier], value)
end
---Adds an interaction to all objects with matchingIdentifier when they are created towards objects with the specified keyword in their identifier. To add a self-interaction, use ALICE_OnCreationAddSelfInteraction instead.
---@param matchingIdentifier string
---@param keyword string | string[]
---@param interactionFunc function
function ALICE_OnCreationAddInteraction(matchingIdentifier, keyword, interactionFunc)
onCreation.interactions[matchingIdentifier] = onCreation.interactions[matchingIdentifier] or {}
if onCreation.interactions[matchingIdentifier][keyword] then
error("Multiple interactionsFuncs added on creation to " .. matchingIdentifier .. " and " .. keyword .. ".")
end
onCreation.interactions[matchingIdentifier][keyword] = interactionFunc
end
---Adds a self-interaction to all objects with matchingIdentifier when they are created.
---@param matchingIdentifier string
---@param selfinteractions function
function ALICE_OnCreationAddSelfInteraction(matchingIdentifier, selfinteractions)
onCreation.selfInteractions[matchingIdentifier] = onCreation.selfInteractions[matchingIdentifier] or {}
insert(onCreation.selfInteractions[matchingIdentifier], selfinteractions)
end
--#endregion
end
if Debug then Debug.beginFile "CAT Rects" end
do
--[[
=============================================================================================================================================================
Complementary ALICE Template
by Antares
Requires:
ALICE https://www.hiveworkshop.com/threads/a-l-i-c-e-interaction-engine.353126/
=============================================================================================================================================================
R E C T S
=============================================================================================================================================================
This template contains function to help with the creation of actors representing rects, which can be built from the native rect type or from tables with the
minX, minY, maxX, and maxY fields.
=============================================================================================================================================================
L I S T O F F U N C T I O N S
=============================================================================================================================================================
CAT_CreateFromRect(rect, flags) Creates a stationary actor with the extents of the specified rect. Rect can be a native rect type or a table with the minX,
minY, maxX, and maxY fields. All fields added with the fields parameter are passed into ALICE, including identifier and
interactions. This parameter can be omitted and all fields directly put into the rect if a table is used to represent it. This
function returns the table that it created for the host.
CAT_RectCheck An interaction function. Checks if the object is inside the rect, invokes the .onEnter(object, rect) function when it enters,
the .onPeriodic(object, rect) function while it is inside the rect, and the .onLeave(object, rect) function when it leaves the
rect. The .interval field determines the interaction interval. The rect must be the female actor for this interaction function.
CAT_IsPointInRect(x, y, rect)
CAT_DoRectsIntersect(rect1, rect2)
CAT_IsRectInRect(smallerRect, largerRect)
=============================================================================================================================================================
]]
---Creates a stationary actor with the extents of the specified rect. All fields added with the fields parameter are passed into ALICE, including identifier and interactions. This parameter can be omitted and all fields directly put into the rect if a table is used to represent it. This function returns the table that it created for the host.
---@param rect rect | table
---@param fields? table
---@return table
function CAT_CreateFromRect(rect, fields)
local self
if IsHandle[rect] then
self = {
x = GetRectCenterX(rect),
y = GetRectCenterY(rect),
minX = GetRectMinX(rect),
minY = GetRectMinY(rect),
maxX = GetRectMaxX(rect),
maxY = GetRectMaxY(rect),
}
self.width = self.maxX - self.minX
self.height = self.maxY - self.minY
for key, value in pairs(fields) do
self[key] = value
end
else
self = rect
self.x = (rect.maxX + rect.minX)/2
self.y = (rect.maxY + rect.minY)/2
self.width = rect.maxX - rect.minX
self.height = rect.maxY - rect.minY
for key, value in pairs(fields) do
self[key] = value
end
end
self.isStationary = true
ALICE_Create(self)
return self
end
local function RectOnLeave(object, rect)
if rect.onLeave then
rect.onLeave(object, rect)
end
end
function CAT_RectCheck(object, rect)
local x, y = ALICE_GetCoordinates2D(object)
if CAT_IsPointInRect(x, y, rect) then
if ALICE_PairIsFirstContact() then
if rect.onEnter then
rect.onEnter(object, rect)
end
end
if rect.onPeriodic then
rect.onPeriodic(object, rect)
end
else
ALICE_PairReset()
end
return rect.interval or 0
end
---@param x number
---@param y number
---@param rect table
function CAT_IsPointInRect(x, y, rect)
return x > rect.minX and x < rect.maxX and y > rect.minY and y < rect.maxY
end
---@param rect1 table
---@param rect2 table
function CAT_DoRectsIntersect(rect1, rect2)
return rect1.maxX > rect2.minX and rect1.minX < rect2.maxX and rect1.maxY > rect2.minY and rect1.minY < rect2.maxY
end
---@param smallerRect table
---@param largerRect table
function CAT_IsRectInRect(smallerRect, largerRect)
return smallerRect.minX >= largerRect.minX and smallerRect.maxX <= largerRect.maxX and smallerRect.minY >= largerRect.minY and smallerRect.maxY <= largerRect.maxY
end
local function InitRectsCAT()
ALICE_RecognizeFields("minX", "maxX", "minY", "maxY", "onEnter", "onLeave", "onPeriodic", "interval")
ALICE_FuncRequireFields(CAT_RectCheck, false, true, "minX", "maxX", "minY", "maxY")
ALICE_FuncSetOnReset(CAT_RectCheck, RectOnLeave)
end
OnInit.global("CAT_Rects", InitRectsCAT)
end
if Debug then Debug.beginFile "CAT Mice" end
do
--[[
=============================================================================================================================================================
Complementary ALICE Template
by Antares
Requires:
ALICE https://www.hiveworkshop.com/threads/a-l-i-c-e-interaction-engine.353126/
PrecomputedHeightMap (optional) https://www.hiveworkshop.com/threads/precomputed-synchronized-terrain-height-map.353477/
=============================================================================================================================================================
M I C E
=============================================================================================================================================================
This template creates an actor for each player's mouse. The mouse gets the identifier "mouse".
=============================================================================================================================================================
]]
CAT_PlayerMouse = {} ---@type Mouse[]
local moveableLoc = nil ---@type location
local GetTerrainZ = nil ---@type function
local function OnMoveMouse()
local whichMouse = CAT_PlayerMouse[GetTriggerPlayer()]
local x, y = BlzGetTriggerPlayerMouseX(), BlzGetTriggerPlayerMouseY()
if x ~= 0 or y ~= 0 then
whichMouse.x = x
whichMouse.y = y
whichMouse.z = GetTerrainZ(x, y)
end
end
local function OnLeave()
local P = GetTriggerPlayer()
ALICE_Kill(CAT_PlayerMouse[P])
CAT_PlayerMouse[P] = nil
end
local function InitMiceCAT()
Require "ALICE"
---@class Mouse
local Mouse = {
x = nil,
y = nil,
z = nil,
owner = nil,
identifier = "mouse",
interactions = nil,
cellCheckInterval = ALICE_Config.MIN_INTERVAL,
isUnselectable = true
}
Mouse.__index = Mouse
local moveTrig = CreateTrigger()
local leaveTrig = CreateTrigger()
local newMouse
for i = 0, 23 do
local P = Player(i)
if GetPlayerSlotState(P) == PLAYER_SLOT_STATE_PLAYING and GetPlayerController(P) == MAP_CONTROL_USER then
TriggerRegisterPlayerEvent(moveTrig, P, EVENT_PLAYER_MOUSE_MOVE)
newMouse = {}
setmetatable(newMouse, Mouse)
newMouse.x, newMouse.y, newMouse.z = 0, 0, 0
newMouse.owner = P
ALICE_Create(newMouse)
CAT_PlayerMouse[P] = newMouse
TriggerRegisterPlayerEvent(leaveTrig, P, EVENT_PLAYER_LEAVE)
end
end
TriggerAddAction(moveTrig, OnMoveMouse)
TriggerAddAction(leaveTrig, OnLeave)
local precomputedHeightMap = Require.optionally "PrecomputedHeightMap"
if precomputedHeightMap then
GetTerrainZ = _G.GetTerrainZ
else
moveableLoc = Location(0, 0)
GetTerrainZ = function(x, y)
MoveLocation(moveableLoc, x, y)
return GetLocationZ(moveableLoc)
end
end
end
OnInit.final("CAT_Mice", InitMiceCAT)
end
if Debug then Debug.beginFile "CAT Camera" end
do
--[[
=============================================================================================================================================================
Complementary ALICE Template
by Antares
Requires:
ALICE https://www.hiveworkshop.com/threads/a-l-i-c-e-interaction-engine.353126/
PrecomputedHeightMap (optional) https://www.hiveworkshop.com/threads/precomputed-synchronized-terrain-height-map.353477/
=============================================================================================================================================================
C A M E R A S
=============================================================================================================================================================
This template creates an actor for each player's camera, which can be used for visibility detection. The camera gets the identifier "camera".
The camera actor is fully asynchronous and must not engage in any interactions that require synchronicity (see under Tutorial & Documentation -> Advanced ->
Asynchronous Code).
The following fields can be read:
CAT_Camera.x The camera's target position.
CAT_Camera.y
CAT_Camera.z
CAT_Camera.eyeX The camera's eye position.
CAT_Camera.eyeY
CAT_Camera.eyeZ
CAT_Camera.angleOfAttack The camera's angle of attack.
CAT_Camera.rotation The camera's rotation.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
local MAX_CAMERA_RADIUS = 3000 ---@type number
--Caps the maximum radius of the camera field when the camera is at a low angle.
--===========================================================================================================================================================
CAT_Camera = nil ---@type Camera
--InteractionFunc
function UpdateCameraParameters(camera)
camera.angleOfAttack = GetCameraField(CAMERA_FIELD_ANGLE_OF_ATTACK)
camera.rotation = GetCameraField(CAMERA_FIELD_ROTATION)
camera.eyeX = GetCameraEyePositionX()
camera.eyeY = GetCameraEyePositionY()
camera.eyeZ = GetCameraEyePositionZ()
camera.x = GetCameraTargetPositionX()
camera.y = GetCameraTargetPositionY()
camera.z = GetCameraTargetPositionZ()
--Approximation of camera viewing distance.
local newCameraRadius = math.min(MAX_CAMERA_RADIUS, 0.5*GetCameraField(CAMERA_FIELD_TARGET_DISTANCE)/(5.88 - camera.angleOfAttack))
if math.abs(ALICE_GetFlag(camera, "radius") - newCameraRadius) > 100 then
ALICE_SetFlag(camera, "radius", newCameraRadius)
end
end
---@class Camera
local Camera = {
eyeX = nil,
eyeY = nil,
eyeZ = nil,
angleOfAttack = nil,
rotation = nil,
--ALICE
x = nil,
y = nil,
z = nil,
identifier = nil,
interactions = nil,
cellCheckInterval = nil,
}
Camera.__index = Camera
OnInit.final("CAT_Camera", function()
Require "ALICE"
ALICE_RecognizeFields("eyeX", "eyeY", "eyeZ", "angleOfAttack", "rotation")
CAT_Camera = {
eyeX = GetCameraEyePositionX(),
eyeY = GetCameraEyePositionY(),
eyeZ = GetCameraEyePositionZ(),
angleOfAttack = 0,
rotation = 0,
--ALICE
x = GetCameraTargetPositionX(),
y = GetCameraTargetPositionY(),
z = GetCameraTargetPositionZ(),
identifier = "camera",
interactions = {
self = UpdateCameraParameters,
},
cellCheckInterval = ALICE_Config.MIN_INTERVAL,
}
ALICE_Create(CAT_Camera)
end)
end
if Debug then Debug.beginFile "CAT Objects" end
do
--[[
=============================================================================================================================================================
Complementary ALICE Template
ALICE https://www.hiveworkshop.com/threads/a-l-i-c-e-interaction-engine.353126/
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
Knockback Item ('Ikno') Required for unit knockback (optional).
=============================================================================================================================================================
O B J E C T S
=============================================================================================================================================================
This template contains functions and config variables required for other CATs. For many config parameters, CATs other than the one they primarily affect need
access to them, so they are put here as globals.
=============================================================================================================================================================
L I S T O F F U N C T I O N S
=============================================================================================================================================================
CAT_Knockback(whichUnit, vx, vy, vz) Applies a knockback to the specified unit. NOTE: 3D knockbacks are not yet implemented!
CAT_GetObjectVelocity3D(whichObject) Returns the x, y, and z-velocity of the specified object. Accepts widgets and gizmos.
CAT_GetObjectMass(whichObject) Returns the mass of the specified object. Accepts widgets and gizmos.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--ALICE default widget actor properties
--Shifts the coordinates returned by ALICE up by half a widget's height so that it represents the center, not the origin. The Collisions CAT is expecting
--center-point coordinates.
local CENTER_POINT_COORDINATES = true ---@type boolean
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--For Collisions
--Periodically check each unit's position so that the unit's velocity can be retrieved for collisions.
local MONITOR_UNIT_VELOCITY = true ---@type boolean
--By default, a unit's height is this factor times its collision size.
DEFAULT_UNIT_HEIGHT_FACTOR = 4.0 ---@type number
DEFAULT_UNIT_ELASTICITY = 0.5 ---@type number
DEFAULT_UNIT_MASS = 5 ---@type number
DEFAULT_UNIT_FRICTION = 350 ---@type number
DEFAULT_DESTRUCTABLE_COLLISION_RADIUS = 64 ---@type number
DEFAULT_DESTRUCTABLE_HEIGHT = 250 ---@type number
DEFAULT_DESTRUCTABLE_ELASTICITY = 0.2 ---@type number
DEFAULT_ITEM_COLLISION_RADIUS = 40 ---@type number
DEFAULT_ITEM_HEIGHT = 40 ---@type number
DEFAULT_ITEM_ELASTICITY = 0.2 ---@type number
--These tables allow you to overwrite the default values for specific widget types. Keys of these tables are fourCC codes.
UNIT_TYPE_MASS = {} ---@type table<string,number>
UNIT_TYPE_FRICTION = {} ---@type table<string,number>
WIDGET_TYPE_COLLISION_RADIUS = {} ---@type table<string,number>
WIDGET_TYPE_HEIGHT = {} ---@type table<string,number>
WIDGET_TYPE_ELASTICITY = {} ---@type table<string,number>
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--For Gizmos
--The maximum speed that a gizmo can reasonably achieve to determine the frequency with which collision checks must be performed. Can be overwritten with the
--.maxSpeed field in a gizmo's class table.
DEFAULT_GIZMO_MAX_SPEED = 2000 ---@type number
--Sets the vertical bounds for the kill trigger in CAT_OutOfBoundsCheck.
GIZMO_MAXIMUM_Z = 3000 ---@type number
GIZMO_MINIMUM_Z = -2000 ---@type number
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--For Ballistics
--The friction increase for a sliding object when it comes to rest. High value can prevent jittering in tightly packed collisions.
STATIC_FRICTION_FACTOR = 5 ---@type number
--If an airborne object would bounce off the surface with this much or less speed, it will become ground-bound instead.
MINIMUM_BOUNCE_VELOCITY = 5 ---@type number
--Strength of gravitational acceleration.
GRAVITY = 800 ---@type number
--Determines how curved a surface must be before an object can no longer slide across it but is instead reflected as though it hit a wall. Higher value is
--less forgiving.
MAX_SLIDING_CURVATURE_RADIUS = 80 ---@type number
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--Terrain Properties
--You can adjust the friction of different terrain types by editing the TERRAIN_TYPE_FRICTION table. Disable if not needed to improve performance.
DIFFERENT_SURFACE_FRICTIONS = false ---@type boolean
TERRAIN_TYPE_FRICTION = {} ---@type table<string,number>
TERRAIN_TYPE_ELASTICITY = {} ---@type table<string,number>
--===========================================================================================================================================================
--Overwrite the default values for different widget types and terrain types like this:
--TERRAIN_TYPE_FRICTION["Ydtr"] = 1.5
--UNIT_TYPE_MASS["hfoo"] = 3
--WIDGET_TYPE_HEIGHT["Etyr"] = 75
--===========================================================================================================================================================
local INF = math.huge
local sqrt = math.sqrt
local max = math.max
local cos = math.cos
local sin = math.sin
local atan2 = math.atan
local mt = {__mode = "k"}
local knockbackItem = nil ---@type item
local knockbackSpeed = setmetatable({}, mt) ---@type table[]
local monitorUnitX = setmetatable({}, mt)
local monitorUnitY = setmetatable({}, mt)
local monitorUnitZ = setmetatable({}, mt)
local unitVelocityX = setmetatable({}, mt)
local unitVelocityY = setmetatable({}, mt)
local unitVelocityZ = setmetatable({}, mt)
local UNIT_MAX_SPEED = 522
local UNIT_MAX_SPEED_SQUARED = UNIT_MAX_SPEED^2
local WORLD_MIN_X = nil ---@type number
local WORLD_MIN_Y = nil ---@type number
local MONITOR_INTERVAL = (0.1 // ALICE_Config.MIN_INTERVAL)*ALICE_Config.MIN_INTERVAL
local function InitApplyKnockback(u)
local data = ALICE_PairLoadData()
data.friction = (UNIT_TYPE_FRICTION[GetUnitTypeId(u)] or DEFAULT_UNIT_FRICTION)
end
local function InitMonitorUnitVelocity(unit)
monitorUnitX[unit], monitorUnitY[unit], monitorUnitZ[unit] = ALICE_GetCoordinates3D(unit)
unitVelocityX[unit], unitVelocityY[unit], unitVelocityZ[unit] = 0, 0, 0
end
function CAT_MonitorUnitVelocity(unit)
local x, y, z = ALICE_GetCoordinates3D(unit)
unitVelocityX[unit], unitVelocityY[unit], unitVelocityZ[unit] = (x - monitorUnitX[unit])/MONITOR_INTERVAL, (y - monitorUnitY[unit])/MONITOR_INTERVAL, (z - monitorUnitZ[unit])/MONITOR_INTERVAL
monitorUnitX[unit], monitorUnitY[unit], monitorUnitZ[unit] = x, y, z
return MONITOR_INTERVAL
end
local function CAT_ApplyKnockback(u)
local data = ALICE_PairLoadData()
local xi
local yi
local phi = atan2(knockbackSpeed[u].y, knockbackSpeed[u].x)
local x = GetUnitX(u) + knockbackSpeed[u].x*ALICE_Config.MIN_INTERVAL
local y = GetUnitY(u) + knockbackSpeed[u].y*ALICE_Config.MIN_INTERVAL
if knockbackItem then
SetItemPosition(knockbackItem, x, y)
xi = GetItemX(knockbackItem)
yi = GetItemY(knockbackItem)
if not IsTerrainPathable(x , y , PATHING_TYPE_WALKABILITY) and x - xi < 1 and x - xi > -1 and y - yi < 1 and y - yi > -1 then
SetUnitX(u, x)
SetUnitY(u, y)
SetItemPosition(knockbackItem, WORLD_MIN_X, WORLD_MIN_Y)
else
knockbackSpeed[u].x = 0
knockbackSpeed[u].y = 0
ALICE_PairPause()
SetItemPosition(knockbackItem, WORLD_MIN_X, WORLD_MIN_Y)
return
end
else
SetUnitX(u, x)
SetUnitY(u, y)
end
local velocity = sqrt(knockbackSpeed[u].x^2 + knockbackSpeed[u].y^2)
velocity = max(0, velocity - data.friction*(TERRAIN_TYPE_FRICTION[GetTerrainType(x, y)] or 1)*ALICE_Config.MIN_INTERVAL)
knockbackSpeed[u].x = velocity*cos(phi)
knockbackSpeed[u].y = velocity*sin(phi)
if velocity == 0 then
ALICE_PairPause()
end
end
---Applies a knockback to the specified unit. NOTE: 3D knockbacks are not yet implemented!
---@param u unit
---@param vx number
---@param vy number
---@param vz number
function CAT_Knockback(u, vx, vy, vz)
local identifier = ALICE_HasActor(u, "unit") and "unit" or "corpse"
if ALICE_HasSelfInteraction(u, CAT_ApplyKnockback, identifier) then
ALICE_Unpause(u, CAT_ApplyKnockback, identifier)
else
knockbackSpeed[u] = {}
ALICE_AddSelfInteraction(u, CAT_ApplyKnockback, identifier)
knockbackSpeed[u].x = 0
knockbackSpeed[u].y = 0
knockbackSpeed[u].z = 0
end
knockbackSpeed[u].x = (knockbackSpeed[u].x) + vx
knockbackSpeed[u].y = (knockbackSpeed[u].y) + vy
end
---Returns the mass of the specified object.
---@param object unit | destructable | item | table
---@return number
function CAT_GetObjectMass(object)
if type(object) == "table" then
if object.mass then
return object.mass
elseif object.anchor then
if type(object.anchor) == "table" then
return object.anchor.mass
elseif HandleType[object.anchor] == "unit" then
return UNIT_TYPE_MASS[GetUnitTypeId(object.anchor)] or DEFAULT_UNIT_MASS
else
return INF
end
else
return 0
end
elseif HandleType[object] == "unit" then
return UNIT_TYPE_MASS[GetUnitTypeId(object)] or DEFAULT_UNIT_MASS
else
return INF
end
end
---@param unit unit
---@return number, number, number
local function GetUnitVelocity3D(unit)
if unitVelocityX[unit] then
local totalSpeedSquared = unitVelocityX[unit]^2 + unitVelocityY[unit]^2 + unitVelocityZ[unit]^2
--If unit could not have traveled that fast naturally, it was most likely a teleport. Then, do not use velocity.
if totalSpeedSquared > UNIT_MAX_SPEED_SQUARED then
local totalSpeed = sqrt(totalSpeedSquared)
if knockbackSpeed[unit] then --Collisions CAT
local kbSpeed = knockbackSpeed[unit].x^2 + knockbackSpeed[unit].y^2 + knockbackSpeed[unit].z^2
if totalSpeed > kbSpeed + UNIT_MAX_SPEED then
return knockbackSpeed[unit].x, knockbackSpeed[unit].y, knockbackSpeed[unit].z
else
return unitVelocityX[unit], unitVelocityY[unit], unitVelocityZ[unit]
end
else
return 0, 0, 0
end
else
return unitVelocityX[unit], unitVelocityY[unit], unitVelocityZ[unit]
end
elseif knockbackSpeed[unit] then
return knockbackSpeed[unit].x, knockbackSpeed[unit].y, knockbackSpeed[unit].z
else
return 0, 0, 0
end
end
---Returns the x, y, and z-velocity of the specified object.
---@param object unit | destructable | item | table
---@return number, number, number
function CAT_GetObjectVelocity3D(object)
if type(object) == "table" then
if object.vx then
return object.vx, object.vy, object.vz
elseif object.anchor then
if type(object.anchor) == "table" then
return object.anchor.vx, object.anchor.vy, object.anchor.vz
elseif HandleType[object.anchor] == "unit" then
return GetUnitVelocity3D(object.anchor)
else
return 0, 0, 0
end
else
return 0, 0, 0
end
else
if HandleType[object] == "unit" then
return GetUnitVelocity3D(object)
else
return 0, 0, 0
end
end
end
---@param unit unit
---@return number, number
local function GetUnitVelocity2D(unit)
if unitVelocityX[unit] then --Units CAT
local totalSpeedSquared = unitVelocityX[unit]^2 + unitVelocityY[unit]^2
--If unit could not have traveled that fast naturally, it was most likely a teleport. Then, do not use velocity.
if totalSpeedSquared > UNIT_MAX_SPEED_SQUARED then
local totalSpeed = sqrt(totalSpeedSquared)
if knockbackSpeed[unit] then --Collisions CAT
local kbSpeed = knockbackSpeed[unit].x^2 + knockbackSpeed[unit].y^2
if totalSpeed > kbSpeed + UNIT_MAX_SPEED then
return knockbackSpeed[unit].x, knockbackSpeed[unit].y
else
return unitVelocityX[unit], unitVelocityY[unit]
end
else
return 0, 0
end
else
return unitVelocityX[unit], unitVelocityY[unit]
end
elseif knockbackSpeed[unit] then
return knockbackSpeed[unit].x, knockbackSpeed[unit].y
else
return 0, 0
end
end
---Returns the x- and y-velocity of the specified object.
---@param object unit | destructable | item | table
---@return number, number
function CAT_GetObjectVelocity2D(object)
if type(object) == "table" then
if object.vx then
return object.vx, object.vy
elseif object.anchor then
if type(object.anchor) == "table" then
return object.anchor.vx, object.anchor.vy
elseif HandleType[object.anchor] == "unit" then
return GetUnitVelocity2D(object.anchor)
else
return 0, 0
end
else
return 0, 0
end
else
if HandleType[object] == "unit" then
return GetUnitVelocity2D(object)
else
return 0, 0
end
end
end
---Shifts the position of the gizmo by its launchOffset field in the direction of its velocity.
---@param gizmo table
function CAT_LaunchOffset(gizmo)
if gizmo.vz then
local vTotal = sqrt(gizmo.vx^2 + gizmo.vy^2 + gizmo.vz^2)
gizmo.x = gizmo.x + gizmo.launchOffset*gizmo.vx/vTotal
gizmo.y = gizmo.y + gizmo.launchOffset*gizmo.vy/vTotal
gizmo.z = gizmo.z + gizmo.launchOffset*gizmo.vz/vTotal
if gizmo.visual then
BlzSetSpecialEffectPosition(gizmo.visual, gizmo.x, gizmo.y, gizmo.z)
end
else
local vTotal = sqrt(gizmo.vx^2 + gizmo.vy^2)
gizmo.x = gizmo.x + gizmo.launchOffset*gizmo.vx/vTotal
gizmo.y = gizmo.y + gizmo.launchOffset*gizmo.vy/vTotal
if gizmo.visual then
BlzSetSpecialEffectX(gizmo.visual, gizmo.x)
BlzSetSpecialEffectY(gizmo.visual, gizmo.y)
end
end
end
OnInit.global("CAT_Objects", function()
for key, value in pairs(UNIT_TYPE_MASS) do
if type(key) == "string" then
UNIT_TYPE_MASS[FourCC(key)] = value
end
end
for key, value in pairs(UNIT_TYPE_FRICTION) do
if type(key) == "string" then
UNIT_TYPE_FRICTION[FourCC(key)] = value
end
end
for key, value in pairs(WIDGET_TYPE_COLLISION_RADIUS) do
if type(key) == "string" then
WIDGET_TYPE_COLLISION_RADIUS[FourCC(key)] = value
end
end
for key, value in pairs(WIDGET_TYPE_HEIGHT) do
if type(key) == "string" then
WIDGET_TYPE_HEIGHT[FourCC(key)] = value
end
end
for key, value in pairs(WIDGET_TYPE_ELASTICITY) do
if type(key) == "string" then
WIDGET_TYPE_ELASTICITY[FourCC(key)] = value
end
end
if CENTER_POINT_COORDINATES then
ALICE_OnCreationAddFlag("unit", "zOffset", function(host)
return (WIDGET_TYPE_HEIGHT[GetUnitTypeId(host)] or DEFAULT_UNIT_HEIGHT_FACTOR*BlzGetUnitCollisionSize(host))/2
end)
ALICE_OnCreationAddFlag("destructable", "zOffset", function(host)
return (WIDGET_TYPE_HEIGHT[GetDestructableTypeId(host)] or DEFAULT_DESTRUCTABLE_HEIGHT)/2
end)
ALICE_OnCreationAddFlag("item", "zOffset", function(host)
return (WIDGET_TYPE_HEIGHT[GetItemTypeId(host)] or DEFAULT_DESTRUCTABLE_HEIGHT)/2
end)
end
if MONITOR_UNIT_VELOCITY then
ALICE_OnCreationAddSelfInteraction("unit", CAT_MonitorUnitVelocity)
end
ALICE_FuncSetInit(CAT_MonitorUnitVelocity, InitMonitorUnitVelocity)
ALICE_FuncDistribute(CAT_MonitorUnitVelocity, 0.1)
ALICE_FuncSetName(CAT_ApplyKnockback, "CAT_ApplyKnockback")
local worldBounds = GetWorldBounds()
WORLD_MIN_X = GetRectMinX(worldBounds)
WORLD_MIN_Y = GetRectMinY(worldBounds)
ALICE_ExcludeTypes("Ikno")
knockbackItem = CreateItem(FourCC("Ikno"), WORLD_MIN_X, WORLD_MIN_Y)
SetItemInvulnerable(knockbackItem, true)
ALICE_FuncSetInit(CAT_ApplyKnockback, InitApplyKnockback)
end)
end
if Debug then Debug.beginFile "CAT Gizmos" end
do
--[[
===============================================================================================================================================================================
Complementary ALICE Template
by Antares
Requires:
ALICE https://www.hiveworkshop.com/threads/a-l-i-c-e-interaction-engine.353126/
PrecomputedHeightMap (optional) https://www.hiveworkshop.com/threads/precomputed-synchronized-terrain-height-map.353477/
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
===============================================================================================================================================================================
G I Z M O S
===============================================================================================================================================================================
This template contains several functions that help with creating and managing gizmos*. It also includes the terrain collision check function.
*Objects represented by a table with coordinate fields .x, .y, .z, velocity fields .vx, .vy, .vz, and a special effect .visual.
How to create a gizmo:
Create a table that contains coordinate and velocity fields. If you want 3D movement, you need to include z-coordinates and z-velocity, otherwise x and y suffice. Also create
the .visual field in your gizmo for the special effect.
To interface the gizmos with the functions in this template, add self-interactions to your gizmos. Function parameters are customized by editing table fields of your gizmo.
Some parameters cannot be changed after creation, others can. In many cases, you can easily alter the implementation of a function to make a parameter changeable.
Example:
Football = {
x = nil,
y = nil,
z = nil,
vx = nil,
vy = nil,
vz = nil,
visual = nil,
--ALICE
identifier = "football",
interactions = {
football = CAT_CollisionCheck3D,
self = {
CAT_MoveBallistic,
CAT_CheckTerrainCollision
}
},
--CAT
onTerrainCollision = CAT_OnTerrainCollisionBounce,
onTerrainCallback = BounceFootball,
onGizmoCollision = CAT_GizmoBounce3D,
friction = 100,
elasticity = 0.7,
collisionRadius = 35
}
Football.__index = Football
function Football.create(x, y, z, vx, vy, vz)
local new = {}
setmetatable(new, Football)
new.x, new.y, new.z = x, y, z
new.vx, new.vy, new.vz = vx, vy, vz
new.visual = AddSpecialEffect(effectPath, x, y)
BlzSetSpecialEffectZ(effectPath, z)
ALICE_Create(new)
end
===============================================================================================================================================================================
L I S T O F F U N C T I O N S
===============================================================================================================================================================================
CAT_Decay Makes your gizmo get destroyed after X seconds, where X is set through the .lifetime field of your gizmo table.
With the optional .onExpire field, you can set a callback function that is invoked when the gizmo decays.
CAT_CheckTerrainCollision When enabled, checks for terrain collision and invokes a callback function upon collision. The callback function is
retrieved from the .onTerrainCollision field. It is called with the parameters
(gizmo, normalSpeed, tangentialSpeed, totalSpeed). If the onTerrainCollision field is empty, ALICE_Kill will be
invoked instead. Requires the .collisionRadius field of your table to be set.
CAT_TerrainBounce A function for onTerrainCollision. Uses the .elasticity field to determine the elasticity of the collision. This
value is multiplied by the TERRAIN_TYPE_ELASTICITY, which can be set in the Objects CAT.
CAT_OutOfBoundsCheck Checks if the gizmo has left the playable map area and destroys it if it does. You can set the .reflectsOnBounds
field of your gizmo table to true to make it reflect on the bounds instead of being destroyed. Uses the .maxSpeed
field to determine how often the out-of-bounds check is performed, or DEFAULT_GIZMO_MAX_SPEED if not set.
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CAT_AutoZ(gizmo) Initializes the gizmo's z-coordinate to GetTerrainZ(x, y) + gizmo.collisionRadius.
CAT_SetGizmoBounds(xMin, yMin, xMax, yMax) Change the gizmo bounds for CAT_OutOfBoundsCheck. The default bounds are the world bounds. z-bounds are set in the
config.
CAT_GlobalReplace(widgetId, widgetType, constructorFunc) A function that allows you to place widgets using the World Editor and replace them on map initialization with
gizmos. The constructorFunc is the function creating your gizmo. It will be called with the parameters
(x, y, z, life, mana, owner, facing, unit) if the replaced widget is a unit, (x, y, z, life, widget) if the widget is
a destructable, and (x, y, z, widget) if it is an item.
===============================================================================================================================================================================
]]
local sqrt = math.sqrt
local min = math.min
local atan2 = math.atan
local INTERVAL = nil ---@type number
local gizmoBoundMinX = nil ---@type number
local gizmoBoundMinY = nil ---@type number
local gizmoBoundMaxX = nil ---@type number
local gizmoBoundMaxY = nil ---@type number
local GetTerrainZ = nil ---@type function
local moveableLoc = nil ---@type location
--=============================================================================================================================================================================
function CAT_Decay(gizmo)
gizmo.lifetime = gizmo.lifetime - INTERVAL
if gizmo.lifetime <= 0 then
if gizmo.onExpire then
gizmo:onExpire()
end
ALICE_Kill(gizmo)
end
end
---@param gizmo table
---@param x number
---@param y number
function CAT_TerrainBounce(gizmo, x, y, z)
--Get normal vector of surface.
local z_x1 = GetTerrainZ(x - 4, y)
local z_x2 = GetTerrainZ(x + 4, y)
local z_y1 = GetTerrainZ(x, y - 4)
local z_y2 = GetTerrainZ(x, y + 4)
local dz_x = (z_x2 - z_x1)/8
local dz_y = (z_y2 - z_y1)/8
local vec1_z = dz_x
local vec2_z = dz_y
local vecN_x = -vec1_z
local vecN_y = -vec2_z
local vecN_z = 1
local norm = sqrt(vecN_x^2 + vecN_y^2 + vecN_z^2)
vecN_x = vecN_x/norm
vecN_y = vecN_y/norm
vecN_z = vecN_z/norm
--object is coming from below the ground.
local normalSpeed = -(vecN_x*gizmo.vx + vecN_y*gizmo.vy + vecN_z*gizmo.vz)
if normalSpeed < 0 then
return
end
local e = (1 + gizmo.elasticity*(TERRAIN_TYPE_ELASTICITY[GetTerrainType(x, y)] or 1))
--Householder transformation.
local H11 = 1 - e*vecN_x^2
local H12 = -e*vecN_x*vecN_y
local H13 = -e*vecN_x*vecN_z
local H21 = H12
local H22 = 1 - e*vecN_y^2
local H23 = -e*vecN_y*vecN_z
local H31 = H13
local H32 = H23
local H33 = 1 - e*vecN_z^2
if gizmo.onTerrainCallback ~= nil then
local totalSpeed = sqrt(gizmo.vx^2 + gizmo.vy^2 + gizmo.vz^2)
local tangentialSpeed = sqrt(totalSpeed^2 - normalSpeed^2)
gizmo:onTerrainCallback(normalSpeed, tangentialSpeed, totalSpeed)
end
local newvx = H11*gizmo.vx + H12*gizmo.vy + H13*gizmo.vz
local newvy = H21*gizmo.vx + H22*gizmo.vy + H23*gizmo.vz
local newvz = H31*gizmo.vx + H32*gizmo.vy + H33*gizmo.vz
gizmo.vx, gizmo.vy, gizmo.vz = newvx, newvy, newvz
gizmo.vzOld = gizmo.vz
gizmo.hasCollided = true
local vHorizontal = sqrt(newvx^2 + newvy^2)
local vTotal = sqrt(vHorizontal^2 + newvz^2)
local overShoot = sqrt((x - gizmo.x)^2 + (y - gizmo.y)^2)*vTotal/(vHorizontal + 0.01)
gizmo.x, gizmo.y, gizmo.z = x + gizmo.vx/vTotal*overShoot, y + gizmo.vy/vTotal*overShoot, gizmo.z + gizmo.vz/vTotal*overShoot
if vecN_x*gizmo.vx + vecN_y*gizmo.vy + vecN_z*gizmo.vz < MINIMUM_BOUNCE_VELOCITY then
gizmo.theta = atan2(gizmo.vz, sqrt(gizmo.vx^2 + gizmo.vy^2))
gizmo.isAirborne = false
end
end
local function GetTerrainCollisionPoint(gizmo)
local x, y, z = gizmo.x, gizmo.y, gizmo.z
local interval = ALICE_TimeElapsed - (gizmo.lastTerrainCollisionCheck or ALICE_TimeElapsed)
local dx, dy, dz = gizmo.vx*interval, gizmo.vy*interval, gizmo.vz*interval
local dist = sqrt(dx^2 + dy^2 + dz^2)
local iterations = math.log(dist/4, 2) // 1
local p = 0.5
local shift = 0.5
for __ = 1, iterations do
shift = 0.5*shift
if z - p*dz > GetTerrainZ(x - p*dx, y - p*dy) then
p = p - shift
else
p = p + shift
end
end
return x - p*dx, y - p*dy
end
function CAT_CheckTerrainCollision(gizmo)
if gizmo.isAirborne == false then
ALICE_PairPause()
end
local height = GetTerrainZ(gizmo.x, gizmo.y)
local dist = gizmo.z - height - gizmo.collisionRadius
local vHorizontal = sqrt(gizmo.vx^2 + gizmo.vy^2)
if dist < 0 then
if gizmo.onTerrainCollision then
gizmo:onTerrainCollision(GetTerrainCollisionPoint(gizmo))
else
ALICE_Kill(gizmo)
end
gizmo.lastTerrainCollisionCheck = ALICE_TimeElapsed
return INTERVAL
elseif vHorizontal - gizmo.vz < 200 then
gizmo.lastTerrainCollisionCheck = ALICE_TimeElapsed
return dist/600
else
gizmo.lastTerrainCollisionCheck = ALICE_TimeElapsed
return dist/(3*(vHorizontal - gizmo.vz))
end
end
---@param gizmo table
---@param isVertical boolean
---@param coord number
local function ReflectOnBounds(gizmo, isVertical, coord)
if isVertical then
gizmo.vy = -gizmo.vy
gizmo.y = 2*coord - gizmo.y
else
gizmo.vx = -gizmo.vx
gizmo.x = 2*coord - gizmo.x
end
end
function CAT_OutOfBoundsCheck(gizmo)
local nearestDist
if gizmo.x < gizmoBoundMinX then
if gizmo.reflectOnBounds then
ReflectOnBounds(gizmo, false, gizmoBoundMinX)
else
ALICE_Kill(gizmo)
end
return 0
else
nearestDist = gizmo.x - gizmoBoundMinX
end
if gizmo.y < gizmoBoundMinY then
if gizmo.reflectOnBounds then
ReflectOnBounds(gizmo, true, gizmoBoundMinY)
else
ALICE_Kill(gizmo)
end
return 0
else
nearestDist = min(nearestDist, gizmo.y - gizmoBoundMinY)
end
if gizmo.x > gizmoBoundMaxX then
if gizmo.reflectOnBounds then
ReflectOnBounds(gizmo, false, gizmoBoundMaxX)
else
ALICE_Kill(gizmo)
end
return 0
else
nearestDist = min(nearestDist, gizmoBoundMaxX - gizmo.x)
end
if gizmo.y > gizmoBoundMaxY then
if gizmo.reflectOnBounds then
ReflectOnBounds(gizmo, true, gizmoBoundMaxY)
else
ALICE_Kill(gizmo)
end
return 0
else
nearestDist = min(nearestDist, gizmoBoundMaxY - gizmo.y)
end
if gizmo.z then
if gizmo.z > GIZMO_MAXIMUM_Z then
ALICE_Kill(gizmo)
return 0
end
if gizmo.z < GIZMO_MINIMUM_Z then
ALICE_Kill(gizmo)
return 0
end
end
if gizmo.isResting then
ALICE_PairPause()
end
return nearestDist/(gizmo.maxSpeed or DEFAULT_GIZMO_MAX_SPEED)
end
---Initializes the gizmo's z-coordinate to GetTerrainZ(x, y) + gizmo.collisionRadius.
---@param gizmo table
function CAT_AutoZ(gizmo)
gizmo.z = GetTerrainZ(gizmo.x, gizmo.y) + (gizmo.collisionRadius or 0)
end
---Removes all widgets with the specified widgetId and calls the constructorFunc with the parameters func(x, y, z, life, mana, owner, facing). The last three parameters are nil if the widget is not a unit.
---@param widgetId integer
---@param widgetType string
---@param constructorFunc function
function CAT_GlobalReplace(widgetId, widgetType, constructorFunc)
if widgetType == "unit" then
local G = CreateGroup()
GroupEnumUnitsInRect(G, bj_mapInitialPlayableArea, nil)
local i = 0
local u = BlzGroupUnitAt(G, i)
while u do
if GetUnitTypeId(u) == widgetId then
local x, y = GetUnitX(u), GetUnitY(u)
local z = GetTerrainZ(x, y) + GetUnitFlyHeight(u)
local life, mana = GetUnitState(u, UNIT_STATE_LIFE), GetUnitState(u, UNIT_STATE_MANA)
local owner = GetOwningPlayer(u)
local facing = GetUnitFacing(u)
constructorFunc(x, y, z, life, mana, owner, facing, u)
RemoveUnit(u)
end
i = i + 1
u = BlzGroupUnitAt(G, i)
end
DestroyGroup(G)
elseif widgetType == "destructable" then
EnumDestructablesInRect(bj_mapInitialPlayableArea, nil, function()
local d = GetEnumDestructable()
if GetDestructableTypeId(d) == widgetId then
local x = GetDestructableX(d)
local y = GetDestructableY(d)
local z = GetTerrainZ(x, y)
local life = GetDestructableLife(d)
constructorFunc(x, y, z, life, d)
RemoveDestructable(d)
end
end)
elseif widgetType == "item" then
EnumItemsInRect(bj_mapInitialPlayableArea, nil, function()
local i = GetEnumItem()
if GetItemTypeId(i) == widgetId then
local x = GetItemX(i)
local y = GetItemY(i)
local z = GetTerrainZ(x, y)
constructorFunc(x, y, z, i)
RemoveItem(i)
end
end)
end
end
---Change the gizmo bounds for CAT_OutOfBoundsCheck. The default bounds are the world bounds. z-bounds are set in the config.
---@param minX number
---@param minY number
---@param maxX number
---@param maxY number
function CAT_SetGizmoBounds(minX, minY, maxX, maxY)
gizmoBoundMinX = minX
gizmoBoundMinY = minY
gizmoBoundMaxX = maxX
gizmoBoundMaxY = maxY
end
local function InitGizmosCAT()
Require "ALICE"
local worldBounds = GetWorldBounds()
CAT_SetGizmoBounds(GetRectMinX(worldBounds), GetRectMinY(worldBounds), GetRectMaxX(worldBounds), GetRectMaxY(worldBounds))
RemoveRect(worldBounds)
INTERVAL = ALICE_Config.MIN_INTERVAL
local precomputedHeightMap = Require.optionally "PrecomputedHeightMap"
if precomputedHeightMap then
GetTerrainZ = _G.GetTerrainZ
else
moveableLoc = Location(0,0)
GetTerrainZ = function(x, y)
MoveLocation(moveableLoc, x, y)
return GetLocationZ(moveableLoc)
end
end
ALICE_RecognizeFields(
"vx",
"vy",
"vz",
"onTerrainCollision",
"onTerrainCallback",
"elasticity",
"collisionRadius",
"onExpire",
"lifetime",
"reflectsOnBounds"
)
ALICE_FuncRequireFields(CAT_CheckTerrainCollision, true, false, "collisionRadius")
ALICE_FuncRequireFields(CAT_Decay, true, false, "lifetime")
end
OnInit.final("CAT_Gizmos", InitGizmosCAT)
--===========================================================================================================================================================
end
if Debug then Debug.beginFile "CAT Missiles" end
do
--[[
===============================================================================================================================================================================
Complementary ALICE Template
by Antares
Requires:
ALICE https://www.hiveworkshop.com/threads/a-l-i-c-e-interaction-engine.353126/
Objects CAT
PrecomputedHeightMap https://www.hiveworkshop.com/threads/precomputed-synchronized-terrain-height-map.353477/
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
===============================================================================================================================================================================
M I S S I L E S
===============================================================================================================================================================================
This template includes a several functions that move or accelerate gizmos*, allowing for the creation of missiles or projectiles. Only the ballistic move function is found in
the Ballistics CAT. For an example of how to use a movement functions, see Gizmos CAT.
*Objects represented by a table with coordinate fields .x, .y, .z, velocity fields .vx, .vy, .vz, and a special effect .visual.
===============================================================================================================================================================================
L I S T O F F U N C T I O N S
===============================================================================================================================================================================
• All movement functions use the optional .visualZ field. You can use this field to shift the position of the
special effect in z-direction.
• All movement functions use the optional .launchOffset field. This shifts the position of the gizmo by that
much in the direction of the movement.
CAT_MoveAutoHeight Linear movement along the terrain surface.
CAT_Move2D Simplest movement function. Linear movement in the x-y plane.
CAT_Move3D Linear movement in any direction.
CAT_MoveArced The missile moves towards the target location specified by the fields .targetX and .targetY with the velocity .speed.
The .arc field determines how curved the missile's path is. The optional .arcAngle field shifts the direction of the
missile's arc. With an arcAngle of 0, the missile arcs vertically, with 90 or -90, it arcs horizontally. A missile
using this movement function will move towards the location until it collides with something, ignoring all external
effects.
CAT_MoveHoming2D The missile follows an object specified by the .target field with a velocity .speed. You can limit the turn rate with
the optional .turnRate field. The value is expected to be in degrees per second. The optional .disconnectionDistance
field controls the maximum distance the unit can travel between two updates before the homing breaks. Gizmos using
homing movement will always move with the same speed, ignoring external effects.
CAT_MoveArcedHoming The same as MoveHoming2D, but movement in three dimensions. The additional .arc field determines how high the
missile flies as it travels towards the unit. The optional .arcAngle field shifts the direction of the missile's arc.
With an arcAngle of 0, the missile arcs vertically, with 90 or -90, it arcs horizontally.Attempts to turn towards the
unit will still be only in the x-y-plane.
CAT_MoveHoming3D The same as MoveHoming2D, but movement in three dimensions. The missile will use all three dimensions to find the
lowest turn angle towards the unit.
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CAT_AccelerateHoming2D Accelerates the gizmo towards the target unit set with the .target field. The acceleration is set with the
.acceleration field. The optional .deceleration field determines the acceleration the gizmo experiences when it is
currently not moving towards the gizmo. Will use acceleration if not set. The optional .maxSpeed field limits the
maximum velocity of the gizmo in direction of the target. This is not a movement function and must be paired with a
compatible movement function; one that reacts to external effects. Can be combined with CAT_OrientPropelled2D function
(Effects CAT).
CAT_AccelerateHoming3D The same as CAT_AccelerateHoming2D, but in three dimensions.
===============================================================================================================================================================================
]]
local sqrt = math.sqrt
local atan2 = math.atan
local cos = math.cos
local sin = math.sin
local acos = math.acos
local exp = math.exp
local PI = bj_PI
local TAU = 2*PI
local INTERVAL = nil ---@type number
local moveableLoc = nil ---@type location
local GetTerrainZ = nil ---@type function
local function Cosh(x)
return (exp(x) + exp(-x))/2
end
local function Sinh(x)
return (exp(x) - exp(-x))/2
end
local function InitMoveGeneric(missile)
missile.visualZ = missile.visualZ or 0
if missile.launchOffset then
CAT_LaunchOffset(missile)
end
end
function CAT_MoveAutoHeight(missile)
missile.x = missile.x + missile.vx*INTERVAL
missile.y = missile.y + missile.vy*INTERVAL
missile.z = GetTerrainZ(missile.x, missile.y)
BlzSetSpecialEffectPosition(missile.visual, missile.x, missile.y, missile.z + missile.visualZ)
end
local function InitMove2D(missile)
missile.visualZ = (missile.visualZ or 0) + GetTerrainZ(missile.x, missile.y)
if missile.launchOffset then
CAT_LaunchOffset(missile)
end
end
function CAT_Move2D(missile)
missile.x = missile.x + missile.vx*INTERVAL
missile.y = missile.y + missile.vy*INTERVAL
BlzSetSpecialEffectPosition(missile.visual, missile.x, missile.y, missile.visualZ)
end
function CAT_Move3D(missile)
missile.x = missile.x + missile.vx*INTERVAL
missile.y = missile.y + missile.vy*INTERVAL
missile.z = missile.z + missile.vz*INTERVAL
BlzSetSpecialEffectPosition(missile.visual, missile.x, missile.y, missile.z + missile.visualZ)
end
local function InitMoveArced(missile)
missile.launchX = missile.x
missile.launchY = missile.y
missile.launchZ = missile.z or GetTerrainZ(missile.x, missile.y)
missile.targetZ = missile.targetZ or GetTerrainZ(missile.targetX, missile.targetY)
local dx, dy, dz = missile.targetX - missile.launchX, missile.targetY - missile.launchY, missile.targetZ - missile.launchZ
local dist = sqrt(dx*dx + dy*dy + dz*dz)
local angle = acos(dx/dist)
local nx = 0
local ny = -dz
local nz = dy
local norm = sqrt(nx^2 + ny^2 + nz^2)
nx, ny, nz = nx/norm, ny/norm, nz/norm
local cosAngle = cos(angle)
local sinAngle = sin(angle)
local oneMinCos = 1 - cosAngle
missile.R11 = nx*nx*oneMinCos + cosAngle
missile.R12 = nx*ny*oneMinCos - nz*sinAngle
missile.R13 = nx*nz*oneMinCos + ny*sinAngle
missile.R21 = ny*nx*oneMinCos + nz*sinAngle
missile.R22 = ny*ny*oneMinCos + cosAngle
missile.R23 = ny*nz*oneMinCos - nx*sinAngle
missile.R31 = nz*nx*oneMinCos - ny*sinAngle
missile.R32 = nz*ny*oneMinCos + nx*sinAngle
missile.R33 = nz*nz*oneMinCos + cosAngle
missile.cosArcAngle = cos((missile.arcAngle or 0)*bj_DEGTORAD)
missile.sinArcAngle = sin((missile.arcAngle or 0)*bj_DEGTORAD)
missile.coshArc = Cosh(missile.arc)
missile.travelDist = dist
missile.dparam = missile.speed*INTERVAL/dist
local timeDilation = sqrt(1 + (2*missile.arc*Sinh(-1))^2) --param goes from -1 to 1.
local param
if missile.launchOffset then --If no launch offset is set, we need to fake a displacement to calculate velocity direction.
param = -1 + missile.launchOffset/(missile.travelDist*timeDilation)
else
param = -1 + missile.dparam
end
local xPrime = missile.travelDist*(param + 1)/2
local y = missile.travelDist*(Cosh(missile.arc*param) - missile.coshArc)
local yPrime = y*missile.sinArcAngle
local zPrime = y*missile.cosArcAngle
local xNew = missile.launchX + missile.R11*xPrime + missile.R12*yPrime + missile.R13*zPrime
local yNew = missile.launchY + missile.R21*xPrime + missile.R22*yPrime + missile.R23*zPrime
local zNew = missile.launchZ + missile.R31*xPrime + missile.R32*yPrime + missile.R33*zPrime
dist = sqrt((xNew - missile.launchX)^2 + (yNew - missile.launchY) + (zNew - missile.launchZ))
missile.vx = missile.speed*(xNew - missile.launchX)/dist
missile.vy = missile.speed*(yNew - missile.launchY)/dist
missile.vz = missile.speed*(zNew - missile.launchZ)/dist
if missile.launchOffset then
missile.x = xNew
missile.y = yNew
missile.z = zNew
missile.param = param
if missile.visual then
BlzSetSpecialEffectPosition(missile.visual, missile.x, missile.y, missile.z)
end
else
missile.param = -1
end
end
function CAT_MoveArced(missile)
missile.param = missile.param + missile.dparam/sqrt(1 + (2*missile.arc*Sinh(missile.param))^2)
local xLast, yLast, zLast = missile.x, missile.y, missile.z
local xPrime = missile.travelDist*(missile.param + 1)/2
local y = missile.travelDist*(Cosh(missile.arc*missile.param) - missile.coshArc)
local yPrime = y*missile.sinArcAngle
local zPrime = y*missile.cosArcAngle
missile.x = missile.launchX + missile.R11*xPrime + missile.R12*yPrime + missile.R13*zPrime
missile.y = missile.launchY + missile.R21*xPrime + missile.R22*yPrime + missile.R23*zPrime
missile.z = missile.launchZ + missile.R31*xPrime + missile.R32*yPrime + missile.R33*zPrime
missile.vx = (missile.x - xLast)/INTERVAL
missile.vy = (missile.y - yLast)/INTERVAL
missile.vz = (missile.z - zLast)/INTERVAL
BlzSetSpecialEffectPosition(missile.visual, missile.x, missile.y, missile.z)
end
local function InitMoveHoming2D(missile)
missile.visualZ = missile.visualZ or 0
missile.turnRate = missile.turnRate or math.huge
missile.turnRateNormalized = bj_DEGTORAD*missile.turnRate*0.1
missile.turnRadius = missile.speed/(bj_DEGTORAD*missile.turnRate)
local x, y = ALICE_GetCoordinates2D(missile.target)
missile.lastKnownTargetX, missile.lastKnownTargetY = x, y
if missile.vx and missile.vy then
missile.currentAngle = atan2(missile.vy, missile.vx)
else
missile.currentAngle = atan2(y - missile.y, x - missile.x)
end
if missile.launchOffset then
CAT_LaunchOffset(missile)
end
end
function CAT_MoveHoming2D(missile)
if ALICE_PairCooldown(0.1) == 0 then
local x, y = ALICE_GetCoordinates2D(missile.target)
if x ~= 0 or y ~= 0 then
if missile.disconnectionDistance then
local distSquared = (x - missile.lastKnownTargetX)^2 + (y - missile.lastKnownTargetY)^2
if distSquared < missile.disconnectionDistance^2 then
missile.lastKnownTargetX, missile.lastKnownTargetY = x, y
else
missile.target = nil
end
else
missile.lastKnownTargetX, missile.lastKnownTargetY = x, y
end
end
local angle = atan2(missile.lastKnownTargetY - missile.y, missile.lastKnownTargetX - missile.x)
local currentAngle = missile.currentAngle
local diff = angle - currentAngle
local absDiff
if diff < 0 then
diff = diff + TAU
elseif diff > TAU then
diff = diff - TAU
end
if diff > PI then
diff = diff - TAU
absDiff = -diff
else
absDiff = diff
end
if absDiff < missile.turnRateNormalized then
currentAngle = angle
elseif diff < 0 then
--Check if target is inside the circle that the missile cannot currently reach. If so, stop turning to gain distance.
local turnLocAngle = currentAngle - PI/2
local turnLocX = missile.x + missile.turnRadius*cos(turnLocAngle)
local turnLocY = missile.y + missile.turnRadius*sin(turnLocAngle)
local targetTurnLocDist = sqrt((turnLocX - missile.lastKnownTargetX)^2 + (turnLocY - missile.lastKnownTargetY)^2)
if targetTurnLocDist > missile.turnRadius or (targetTurnLocDist > 0.9*missile.turnRadius and missile.isTurning) then
missile.isTurning = true
currentAngle = currentAngle - missile.turnRateNormalized
if currentAngle < 0 then
currentAngle = currentAngle + TAU
end
else
missile.isTurning = false
end
else
local turnLocAngle = currentAngle + PI/2
local turnLocX = missile.x + missile.turnRadius*cos(turnLocAngle)
local turnLocY = missile.y + missile.turnRadius*sin(turnLocAngle)
local targetTurnLocDist = sqrt((turnLocX - missile.lastKnownTargetX)^2 + (turnLocY - missile.lastKnownTargetY)^2)
if targetTurnLocDist > missile.turnRadius or (targetTurnLocDist > 0.9*missile.turnRadius and missile.isTurning) then
missile.isTurning = true
currentAngle = currentAngle + missile.turnRateNormalized
if currentAngle > TAU then
currentAngle = currentAngle - TAU
end
else
missile.isTurning = false
end
end
missile.vx = missile.speed*cos(currentAngle)
missile.vy = missile.speed*sin(currentAngle)
missile.currentAngle = currentAngle
end
missile.x = missile.x + missile.vx
missile.y = missile.y + missile.vy
BlzSetSpecialEffectPosition(missile.visual, missile.x, missile.y, GetTerrainZ(missile.x, missile.y) + missile.visualZ)
end
local function InitMoveArcedHoming(missile)
missile.visualZ = missile.visualZ or 0
missile.turnRate = missile.turnRate or math.huge
missile.turnRateNormalized = bj_DEGTORAD*missile.turnRate*0.1
missile.turnRadius = missile.speed/(bj_DEGTORAD*missile.turnRate)
missile.lastKnownTargetX, missile.lastKnownTargetY, missile.lastKnownTargetZ = ALICE_GetCoordinates3D(missile.target)
missile.verticalArc = missile.arc*cos((missile.arcAngle or 0)*bj_DEGTORAD)
missile.horizontalArc = missile.arc*sin((missile.arcAngle or 0)*bj_DEGTORAD)
if missile.disconnectionDistance then
missile.discDistSquared = missile.disconnectionDistance^2
end
if not missile.vx then
local xu, yu, zu = ALICE_GetCoordinates3D(missile.target)
local dx, dy = xu - missile.x, yu - missile.y
local horizontalDist = sqrt(dx*dx + dy*dy)
local dz = zu - missile.z + missile.arc*horizontalDist
local dist = sqrt(horizontalDist^2 + dz*dz)
missile.vx = dx/dist*missile.speed
missile.vy = dy/dist*missile.speed
missile.vz = dz/dist*missile.speed
else
local norm = missile.speed/sqrt(missile.vx^2 + missile.vy^2 + missile.vz^2)
missile.vx, missile.vy, missile.vz = missile.vx*norm, missile.vy*norm, missile.vz*norm
end
if missile.launchOffset then
CAT_LaunchOffset(missile)
end
end
function CAT_MoveArcedHoming(missile)
if ALICE_PairCooldown(0.1) == 0 then
local x, y, z = ALICE_GetCoordinates3D(missile.target)
if x ~= 0 or y ~= 0 or z ~= 0 then
if missile.disconnectionDistance then
local dx, dy, dz = x - missile.lastKnownTargetX, y - missile.lastKnownTargetY, z - missile.lastKnownTargetZ
local distSquared = dx*dx + dy*dy + dz*dz
if distSquared < missile.discDistSquared then
missile.lastKnownTargetX, missile.lastKnownTargetY, missile.lastKnownTargetZ = x, y, z
else
missile.target = nil
end
else
missile.lastKnownTargetX, missile.lastKnownTargetY, missile.lastKnownTargetZ = ALICE_GetCoordinates3D(missile.target)
end
end
local vx, vy, vz = missile.vx, missile.vy, missile.vz
local dx, dy = missile.lastKnownTargetX - missile.x, missile.lastKnownTargetY - missile.y
local horizontalDist = sqrt(dx*dx + dy*dy)
local phi = atan2(dy, dx) + missile.horizontalArc
local currentPhi = atan2(vy, vx)
local diff = phi - currentPhi
local absDiff
if diff < 0 then
diff = diff + TAU
elseif diff > TAU then
diff = diff - TAU
end
if diff > PI then
diff = diff - TAU
absDiff = -diff
else
absDiff = diff
end
if absDiff < missile.turnRateNormalized then
currentPhi = phi
elseif diff < 0 then
--Check if target is inside the circle that the missile cannot currently reach. If so, stop turning to gain distance.
local turnLocPhi = currentPhi - PI/2
local turnLocX = missile.x + missile.turnRadius*cos(turnLocPhi)
local turnLocY = missile.y + missile.turnRadius*sin(turnLocPhi)
dx, dy = turnLocX - missile.lastKnownTargetX, turnLocY - missile.lastKnownTargetY
local targetTurnLocHoriDist = sqrt(dx*dx + dy*dy)
if targetTurnLocHoriDist > missile.turnRadius or (targetTurnLocHoriDist > 0.9*missile.turnRadius and missile.isTurning) then
missile.isTurning = true
currentPhi = currentPhi - missile.turnRateNormalized
if currentPhi < 0 then
currentPhi = currentPhi + TAU
end
else
missile.isTurning = false
end
else
local turnLocPhi = currentPhi + PI/2
local turnLocX = missile.x + missile.turnRadius*cos(turnLocPhi)
local turnLocY = missile.y + missile.turnRadius*sin(turnLocPhi)
dx, dy = turnLocX - missile.lastKnownTargetX, turnLocY - missile.lastKnownTargetY
local targetTurnLocHoriDist = sqrt(dx*dx + dy*dy)
missile.isTurning = true
if targetTurnLocHoriDist > missile.turnRadius or (targetTurnLocHoriDist > 0.9*missile.turnRadius and missile.isTurning) then
currentPhi = currentPhi + missile.turnRateNormalized
if currentPhi > TAU then
currentPhi = currentPhi - TAU
end
else
missile.isTurning = false
end
end
local dz = missile.lastKnownTargetZ - missile.z + missile.verticalArc*(horizontalDist + absDiff*missile.turnRadius)
local theta = atan2(dz, horizontalDist)
local currentTheta = atan2(vz, sqrt(vx*vx + vy*vy))
diff = theta - currentTheta
if diff < 0 then
diff = diff + TAU
elseif diff > TAU then
diff = diff - TAU
end
if diff > PI then
diff = diff - TAU
absDiff = -diff
else
absDiff = diff
end
if absDiff < missile.turnRateNormalized then
currentTheta = theta
elseif diff < 0 then
currentTheta = currentTheta - missile.turnRateNormalized
if currentTheta < 0 then
currentTheta = currentTheta + TAU
end
else
currentTheta = currentTheta + missile.turnRateNormalized
if currentTheta > TAU then
currentTheta = currentTheta - TAU
end
end
local cosCurrentTheta = cos(currentTheta)
missile.vx = missile.speed*cos(currentPhi)*cosCurrentTheta
missile.vy = missile.speed*sin(currentPhi)*cosCurrentTheta
missile.vz = missile.speed*sin(currentTheta)
end
missile.x = missile.x + missile.vx*INTERVAL
missile.y = missile.y + missile.vy*INTERVAL
missile.z = missile.z + missile.vz*INTERVAL
BlzSetSpecialEffectPosition(missile.visual, missile.x, missile.y, missile.z + missile.visualZ)
end
local function InitMoveHoming3D(missile)
missile.visualZ = missile.visualZ or 0
missile.turnRate = missile.turnRate or math.huge
missile.turnRateNormalized = bj_DEGTORAD*missile.turnRate*0.1
missile.turnRadius = missile.speed/(bj_DEGTORAD*missile.turnRate)
missile.lastKnownTargetX, missile.lastKnownTargetY, missile.lastKnownTargetZ = ALICE_GetCoordinates3D(missile.target)
if not missile.vx then
local xu, yu, zu = ALICE_GetCoordinates3D(missile.target)
local dx, dy = xu - missile.x, yu - missile.y
local horizontalDist = sqrt(dx*dx + dy*dy)
local dz = zu - missile.z
local dist = sqrt(horizontalDist^2 + dz*dz)
missile.vx = dx/dist*missile.speed
missile.vy = dy/dist*missile.speed
missile.vz = dz/dist*missile.speed
else
local norm = missile.speed/sqrt(missile.vx^2 + missile.vy^2 + missile.vz^2)
missile.vx, missile.vy, missile.vz = missile.vx*norm, missile.vy*norm, missile.vz*norm
end
if missile.launchOffset then
CAT_LaunchOffset(missile)
end
end
function CAT_MoveHoming3D(missile)
if ALICE_PairCooldown(0.1) == 0 then
local x, y, z = ALICE_GetCoordinates3D(missile.target)
if x ~= 0 or y ~= 0 or z ~= 0 then
if missile.disconnectionDistance then
local distSquared = (x - missile.lastKnownTargetX)^2 + (y - missile.lastKnownTargetY)^2 + (z - missile.lastKnownTargetZ)^2
if distSquared < missile.disconnectionDistance^2 then
missile.lastKnownTargetX, missile.lastKnownTargetY, missile.lastKnownTargetZ = x, y, z
else
missile.target = nil
end
else
missile.lastKnownTargetX, missile.lastKnownTargetY, missile.lastKnownTargetZ = ALICE_GetCoordinates3D(missile.target)
end
end
local vx, vy, vz = missile.vx, missile.vy, missile.vz
local dx, dy, dz = missile.lastKnownTargetX - missile.x, missile.lastKnownTargetY - missile.y, missile.lastKnownTargetZ - missile.z
local dist = sqrt(dx*dx + dy*dy + dz*dz)
local angleDiff = acos((dx*vx + dy*vy + dz*vz)/(missile.speed*dist))
local turnAngle
if angleDiff >= missile.turnRateNormalized then
turnAngle = -angleDiff
else
turnAngle = -missile.turnRateNormalized
end
local nx = vy*dz - vz*dy
local ny = vz*dx - vx*dz
local nz = vx*dy - vy*dx
local invNorm = 1/sqrt(nx^2 + ny^2 + nz^2)
if invNorm ~= math.huge then
nx, ny, nz = nx*invNorm, ny*invNorm, nz*invNorm
if dist < 2*missile.turnRadius then
--Check if target is inside the circle that the missile cannot currently reach. If so, stop turning to gain distance.
local ntpx = vz*ny - vy*nz
local ntpy = vx*nz - vz*nx
local ntpz = vy*nx - vx*ny
invNorm = missile.turnRadius/sqrt(ntpx^2 + ntpy^2 + ntpz^2)
ntpx, ntpy, ntpz = ntpx*invNorm + missile.x, ntpy*invNorm + missile.y, ntpz*invNorm + missile.z
local targetTurnLocDist = sqrt((missile.lastKnownTargetX - ntpx)^2 + (missile.lastKnownTargetY - ntpy)^2 + (missile.lastKnownTargetZ - ntpz)^2)
if targetTurnLocDist > missile.turnRadius or (targetTurnLocDist > 0.9*missile.turnRadius and missile.isTurning) then
missile.isTurning = true
missile.x = missile.x + missile.vx*INTERVAL
missile.y = missile.y + missile.vy*INTERVAL
missile.z = missile.z + missile.vz*INTERVAL
BlzSetSpecialEffectPosition(missile.visual, missile.x, missile.y, missile.z + missile.visualZ)
return
else
missile.isTurning = false
end
end
local cosAngle = cos(turnAngle)
local sinAngle = sin(turnAngle)
local oneMinCos = 1 - cosAngle
M11 = nx*nx*oneMinCos + cosAngle
M12 = nx*ny*oneMinCos - nz*sinAngle
M13 = nx*nz*oneMinCos + ny*sinAngle
M21 = ny*nx*oneMinCos + nz*sinAngle
M22 = ny*ny*oneMinCos + cosAngle
M23 = ny*nz*oneMinCos - nx*sinAngle
M31 = nz*nx*oneMinCos - ny*sinAngle
M32 = nz*ny*oneMinCos + nx*sinAngle
M33 = nz*nz*oneMinCos + cosAngle
local newvx = vx*M11 + vy*M21 + vz*M31
local newvy = vx*M12 + vy*M22 + vz*M32
local newvz = vx*M13 + vy*M23 + vz*M33
invNorm = missile.speed/sqrt(newvx*newvx + newvy*newvy + newvz*newvz)
missile.vx, missile.vy, missile.vz = newvx*invNorm, newvy*invNorm, newvz*invNorm
end
end
missile.x = missile.x + missile.vx*INTERVAL
missile.y = missile.y + missile.vy*INTERVAL
missile.z = missile.z + missile.vz*INTERVAL
BlzSetSpecialEffectPosition(missile.visual, missile.x, missile.y, missile.z + missile.visualZ)
end
local function InitAccelerateHoming(missile)
missile.deceleration = missile.deceleration or missile.acceleration
missile.maxSpeed = missile.maxSpeed or math.huge
end
function CAT_AccelerateHoming2D(missile)
if ALICE_PairCooldown(0.1) == 0 then
local decelerationNormed = missile.deceleration*INTERVAL
local x, y = ALICE_GetCoordinates2D(missile.target)
if x ~= 0 or y ~= 0 then
local dx = x - missile.x
local dy = y - missile.y
local dist = sqrt(dx*dx + dy*dy)
local cosAngle = dx/dist
local sinAngle = dy/dist
local vxPrime = cosAngle * missile.vx + sinAngle * missile.vy
local vyPrime = -sinAngle * missile.vx + cosAngle * missile.vy
local axPrime
local ayPrime
if vxPrime > missile.maxSpeed then
axPrime = -missile.deceleration
elseif vxPrime < 0 then
axPrime = missile.deceleration
else
axPrime = missile.acceleration
end
if vyPrime > decelerationNormed then
ayPrime = -missile.deceleration
elseif vyPrime > 0 then
ayPrime = -vyPrime/INTERVAL
elseif vyPrime < -decelerationNormed then
ayPrime = missile.deceleration
else
ayPrime = -vyPrime/INTERVAL
end
missile.ax = cosAngle * axPrime - sinAngle * ayPrime
missile.ay = sinAngle * axPrime + cosAngle * ayPrime
end
end
missile.vx = missile.vx + missile.ax*INTERVAL
missile.vy = missile.vy + missile.ay*INTERVAL
end
local function InitMissilesCAT()
Require "ALICE"
Require "CAT_Objects"
INTERVAL = ALICE_Config.MIN_INTERVAL
ALICE_FuncSetInit(CAT_MoveAutoHeight, InitMoveGeneric)
ALICE_FuncSetInit(CAT_Move2D, InitMove2D)
ALICE_FuncSetInit(CAT_Move3D, InitMoveGeneric)
ALICE_FuncSetInit(CAT_MoveHoming2D, InitMoveHoming2D)
ALICE_FuncSetInit(CAT_MoveHoming3D, InitMoveHoming3D)
ALICE_FuncSetInit(CAT_MoveArcedHoming, InitMoveArcedHoming)
ALICE_FuncSetInit(CAT_AccelerateHoming2D, InitAccelerateHoming)
ALICE_FuncSetInit(CAT_MoveArced, InitMoveArced)
ALICE_RecognizeFields(
"visualZ",
"launchOffset",
"targetX",
"targetY",
"arc",
"arcAngle",
"target",
"speed",
"turnRate",
"disconnectionDistance",
"acceleration",
"maxSpeed"
)
ALICE_FuncRequireFields(CAT_MoveAutoHeight, true, false, "x", "y", "vx", "vy")
ALICE_FuncRequireFields(CAT_Move2D, true, false, "x", "y", "vx", "vy")
ALICE_FuncRequireFields(CAT_Move3D, true, false, "x", "y", "z", "vx", "vy", "vz")
ALICE_FuncRequireFields(CAT_MoveArced, true, false, "x", "y", "z", "targetX", "targetY", "speed", "arc")
ALICE_FuncRequireFields(CAT_MoveHoming2D, true, false, "x", "y", "z", "target", "speed")
ALICE_FuncRequireFields(CAT_MoveArcedHoming, true, false, "x", "y", "z", "target", "speed", "arc")
ALICE_FuncRequireFields(CAT_MoveHoming3D, true, false, "x", "y", "z", "target", "speed")
local precomputedHeightMap = Require.optionally "PrecomputedHeightMap"
if precomputedHeightMap then
GetTerrainZ = _G.GetTerrainZ
else
moveableLoc = Location(0, 0)
GetTerrainZ = function(x, y)
MoveLocation(moveableLoc, x, y)
return GetLocationZ(moveableLoc)
end
end
end
OnInit.final("CAT_Missiles", InitMissilesCAT)
end
if Debug then Debug.beginFile "CAT Effects" end
do
--[[
============================================================================================================================================================================
Complementary ALICE Template
by Antares
Requires:
ALICE https://www.hiveworkshop.com/threads/a-l-i-c-e-interaction-engine.353126/
PrecomuptedHeightMap https://www.hiveworkshop.com/threads/precomputed-synchronized-terrain-height-map.353477/
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
============================================================================================================================================================================
E F F E C T S
============================================================================================================================================================================
This template contains various auxiliary functions to make your gizmos* look nice. Functions are added to a gizmo by adding it to the self-interaction table. Function
parameters are customized by editing table fields of your gizmo. Some parameters are mutable, others are not. In many cases, you can easily alter the implementation of a
function to make a parameter mutable.
*Objects represented by a table with coordinate fields .x, .y, .z, velocity fields .vx, .vy, .vz, and a special effect .visual.
============================================================================================================================================================================
L I S T O F F U N C T I O N S
============================================================================================================================================================================
CAT_MoveEffect A simple function that moves the gizmo's visual to its current location. Useful for gizmos anchored to a unit.
CAT_AnimateShadow Adds a shadow to your gizmo. Your gizmo table requires multiple fields to be set: shadowPath controls the path of the
shadow image. You can use the preset paths UNIT_SHADOW_PATH and FLYER_SHADOW_PATH. shadowWidth and shadowHeight control
the size of the shadow. shadowX and shadowY are optional parameters that control the offset of the shadow center.
shadowAlpha is an optional parameter that controls the maximum alpha of the shadow. Default 255.
CAT_Orient2D Orients the special effect to always be aligned with its movement direction in 2 dimensions.
CAT_Orient3D Orients the special effect to always be aligned with its movement direction in 3 dimensions.
CAT_OrientPropelled2D Orients the special effect to always be aligned with its acceleration direction in 2 dimensions. Can be combined with
CAT_AccelerateHoming functions. If you use your own acceleration function, use .ax and .ay for the fields determining
the acceleration.
CAT_OrientPropelled3D The same as CAT_OrientPropelled2D, but takes z-acceleration into account.
CAT_OrientRoll Orients the special effect of your gizmo to look like it is rolling across the ground. Your gizmo table requires
the .collisionRadius field to be set. Optional field .rollSpeed. Default value 1.
CAT_OrientProjectile Orients the special effect with OrientEffect3D until it collides with something, after which OrientRoll will be used.
CAT_InitRandomOrientation(gizmo) Initializes the gizmo's special effect to a random orientation. Not a self-interaction function! Call this function
on your gizmo during creation after creating the special effect.
CAT_InitDirectedOrientation(gizmo) Initializes the gizmo's special effect to an orientation pointing towards its movement direction. Not a
self-interaction function! Call this function on your gizmo during creation after creating the special effect.
CAT_AttachEffect(whichGizmo, whichEffect, zOffset) Attaches an additional effect to the gizmo. Not a self-interaction function! Call this function at any time, but only
after registering your gizmo with ALICE.
--==========================================================================================================================================================================
]]
local sqrt = math.sqrt
local atan2 = math.atan
local cos = math.cos
local sin = math.sin
local min = math.min
UNIT_SHADOW_PATH = "ReplaceableTextures\\Shadows\\Shadow.blp"
FLYER_SHADOW_PATH = "ReplaceableTextures\\Shadows\\ShadowFlyer.blp"
local function ClearShadow(gizmo, __, __)
DestroyImage(gizmo.shadow)
end
---@param gizmo table
local function InitAnimateShadow(gizmo)
gizmo.shadowX = gizmo.shadowX or 0
gizmo.shadowY = gizmo.shadowY or 0
gizmo.shadow = CreateImage(gizmo.shadowPath, gizmo.shadowWidth, gizmo.shadowHeight, 0, gizmo.x + (gizmo.shadowX) - 0.5*gizmo.shadowWidth, gizmo.y + (gizmo.shadowY) - 0.5*gizmo.shadowHeight, 0, 0, 0, 0, 1)
SetImageRenderAlways(gizmo.shadow, true)
gizmo.shadowAlpha = gizmo.shadowAlpha or 255
SetImageColor(gizmo.shadow, 255, 255, 255, gizmo.shadowAlpha)
SetImageAboveWater(gizmo.shadow, false, true)
gizmo.shadowAttenuation = 0.047*gizmo.shadowAlpha/min(gizmo.shadowHeight, gizmo.shadowWidth)
end
---@param gizmo table
function CAT_AnimateShadow(gizmo)
local terrainZ = GetTerrainZ(gizmo.x, gizmo.y)
if gizmo.z then
local alpha = gizmo.shadowAlpha - (gizmo.shadowAttenuation*(gizmo.z - terrainZ)) // 1
if alpha < 0 then
alpha = 0
end
SetImageColor(gizmo.shadow, 255, 255, 255, alpha)
end
SetImagePosition(gizmo.shadow, gizmo.x + gizmo.shadowX - 0.5*gizmo.shadowWidth, gizmo.y + gizmo.shadowY - 0.5*gizmo.shadowHeight, 0)
if gizmo.isResting then
ALICE_PairPause()
end
end
local function ClearAttachedEffect(gizmo)
if IsHandle[gizmo.attachedEffect] then
DestroyEffect(gizmo.attachedEffect)
else
for __, effect in ipairs(gizmo.attachedEffect) do
DestroyEffect(effect)
end
end
end
function CAT_MoveAttachedEffect(gizmo)
if IsHandle[gizmo.attachedEffect] then
BlzSetSpecialEffectPosition(gizmo.attachedEffect, gizmo.x, gizmo.y, (gizmo.z or GetTerrainZ(gizmo.x, gizmo.y)) + gizmo.attachedEffectZ)
else
for index, effect in ipairs(gizmo.attachedEffect) do
BlzSetSpecialEffectPosition(effect, gizmo.x, gizmo.y, (gizmo.z or GetTerrainZ(gizmo.x, gizmo.y)) + gizmo.attachedEffectZ[index])
end
end
if gizmo.isResting then
ALICE_PairPause()
end
end
---Attaches an additional effect to the gizmo. Not a self-interaction function! Call this function at any time, but only after registering your gizmo with ALICE.
---@param whichGizmo table
---@param whichEffect effect
---@param zOffset? number
function CAT_AttachEffect(whichGizmo, whichEffect, zOffset)
if whichGizmo.attachedEffect == nil then
whichGizmo.attachedEffect = whichEffect
whichGizmo.attachedEffectZ = zOffset or 0
ALICE_AddSelfInteraction(whichGizmo, CAT_MoveAttachedEffect)
elseif IsHandle[whichGizmo.attachedEffect] then
whichGizmo.attachedEffect = {whichGizmo.attachedEffect, whichEffect}
whichGizmo.attachedEffectZ = {whichGizmo.attachedEffectZ, zOffset or 0}
else
table.insert(whichGizmo.attachedEffect, whichEffect)
table.insert(whichGizmo.attachedEffectZ, zOffset or 0)
end
end
local function InitMoveEffect(gizmo)
gizmo.visualZ = gizmo.visualZ or 0
end
function CAT_MoveEffect(gizmo)
local x, y, z = ALICE_GetCoordinates3D(gizmo)
BlzSetSpecialEffectPosition(gizmo.visual, x, y, z + gizmo.visualZ)
end
local function InitOrient2D(gizmo)
if gizmo.vx and gizmo.vy then
CAT_Orient2D(gizmo)
end
end
local function InitOrient3D(gizmo)
if gizmo.vx and gizmo.vy and gizmo.vz then
CAT_Orient3D(gizmo)
end
end
local function InitOrientPropelled2D(gizmo)
if gizmo.ax and gizmo.ay then
CAT_OrientPropelled2D(gizmo)
end
end
local function InitOrientPropelled3D(gizmo)
if gizmo.ax and gizmo.ay and gizmo.az then
CAT_OrientPropelled3D(gizmo)
end
end
function CAT_Orient2D(gizmo)
if gizmo.vx ~= 0 or gizmo.vy ~= 0 then
BlzSetSpecialEffectYaw(gizmo.visual, atan2(gizmo.vy, gizmo.vx))
end
if gizmo.isResting then
ALICE_PairPause()
end
return 0.1
end
function CAT_Orient3D(gizmo)
if gizmo.vx ~= 0 or gizmo.vy ~= 0 or gizmo.vz ~= 0 then
BlzSetSpecialEffectOrientation(gizmo.visual, atan2(gizmo.vy, gizmo.vx), atan2(-gizmo.vz, sqrt(gizmo.vx^2 + gizmo.vy^2)), 0)
end
if gizmo.isResting then
ALICE_PairPause()
end
return 0.1
end
function CAT_OrientPropelled2D(gizmo)
if gizmo.ax ~= 0 or gizmo.ay ~= 0 then
BlzSetSpecialEffectYaw(gizmo.visual, atan2(gizmo.ay, gizmo.ax))
end
return 0.1
end
function CAT_OrientPropelled3D(gizmo)
if gizmo.ax ~= 0 or gizmo.ay ~= 0 or gizmo.az ~= 0 then
BlzSetSpecialEffectOrientation(gizmo.visual, atan2(gizmo.ay, gizmo.ax), atan2(-gizmo.az, sqrt(gizmo.ax^2 + gizmo.ay^2)), 0)
end
return 0.1
end
local function InitOrientation(gizmo)
if gizmo.O11 then
return
end
gizmo.O11 = 1
gizmo.O12 = 0
gizmo.O13 = 0
gizmo.O21 = 0
gizmo.O22 = 1
gizmo.O23 = 0
gizmo.O31 = 0
gizmo.O32 = 0
gizmo.O33 = 1
BlzSetSpecialEffectOrientation(gizmo.visual, atan2(-gizmo.O12, gizmo.O11), atan2(gizmo.O13, sqrt(gizmo.O12^2 + gizmo.O11^2)), atan2(gizmo.O23, gizmo.O33))
end
function CAT_OrientRoll(gizmo)
local norm = sqrt(gizmo.vy^2 + gizmo.vx^2)
if norm == 0 then
if gizmo.isResting then
ALICE_PairPause()
end
return
end
local nx, ny = gizmo.vy/norm, gizmo.vx/norm
local alpha = INTERVAL*norm/gizmo.collisionRadius*(gizmo.rollSpeed or 1)
local cosAngle = cos(alpha)
local sinAngle = sin(alpha)
local oneMinCos = 1 - cosAngle
local M11 = nx*nx*oneMinCos + cosAngle
local M12 = nx*ny*oneMinCos
local M13 = ny*sinAngle
local M21 = ny*nx*oneMinCos
local M22 = ny*ny*oneMinCos + cosAngle
local M23 = -nx*sinAngle
local M31 = -ny*sinAngle
local M32 = nx*sinAngle
local M33 = cosAngle
local O11 = gizmo.O11*M11 + gizmo.O12*M21 + gizmo.O13*M31
local O12 = gizmo.O11*M12 + gizmo.O12*M22 + gizmo.O13*M32
local O13 = gizmo.O11*M13 + gizmo.O12*M23 + gizmo.O13*M33
local O21 = gizmo.O21*M11 + gizmo.O22*M21 + gizmo.O23*M31
local O22 = gizmo.O21*M12 + gizmo.O22*M22 + gizmo.O23*M32
local O23 = gizmo.O21*M13 + gizmo.O22*M23 + gizmo.O23*M33
local O31 = gizmo.O31*M11 + gizmo.O32*M21 + gizmo.O33*M31
local O32 = gizmo.O31*M12 + gizmo.O32*M22 + gizmo.O33*M32
local O33 = gizmo.O31*M13 + gizmo.O32*M23 + gizmo.O33*M33
gizmo.O11, gizmo.O12, gizmo.O13, gizmo.O21, gizmo.O22, gizmo.O23, gizmo.O31, gizmo.O32, gizmo.O33 = O11, O12, O13, O21, O22, O23, O31, O32, O33
BlzSetSpecialEffectOrientation(gizmo.visual, atan2(-gizmo.O12, gizmo.O11), atan2(gizmo.O13, sqrt(gizmo.O12^2 + gizmo.O11^2)), atan2(gizmo.O23, gizmo.O33))
end
function CAT_OrientProjectile(gizmo)
if not gizmo.hasCollided then
CAT_Orient3D(gizmo)
else
CAT_InitRandomOrientation(gizmo)
ALICE_PairSetInteractionFunc(CAT_OrientRoll)
CAT_OrientRoll(gizmo)
end
end
---Initializes the gizmo's special effect to a random orientation. Not a self-interaction function! Call this function on your gizmo during creation after creating the special effect.
---@param gizmo table
function CAT_InitRandomOrientation(gizmo)
local nx = 1- GetRandomReal(0, 2)
local ny = 1- GetRandomReal(0, 2)
local nz = 1- GetRandomReal(0, 2)
local norm = sqrt(nx^2 + ny^2 + nz^2)
if norm == 0 then
return
end
nx, ny, nz = nx/norm, ny/norm, nz/norm
local alpha = GetRandomReal(0, 2*bj_PI)
local cosAngle = cos(alpha)
local sinAngle = sin(alpha)
local oneMinCos = 1 - cosAngle
gizmo.O11 = nx*nx*oneMinCos + cosAngle
gizmo.O12 = nx*ny*oneMinCos - nz*sinAngle
gizmo.O13 = nx*nz*oneMinCos + ny*sinAngle
gizmo.O21 = ny*nx*oneMinCos + nz*sinAngle
gizmo.O22 = ny*ny*oneMinCos + cosAngle
gizmo.O23 = ny*nz*oneMinCos - nx*sinAngle
gizmo.O31 = nz*nx*oneMinCos - ny*sinAngle
gizmo.O32 = nz*ny*oneMinCos + nx*sinAngle
gizmo.O33 = nz*nz*oneMinCos + cosAngle
BlzSetSpecialEffectOrientation(gizmo.visual, atan2(-gizmo.O12, gizmo.O11), atan2(gizmo.O13, sqrt(gizmo.O12^2 + gizmo.O11^2)), atan2(gizmo.O23, gizmo.O33))
end
---Initializes the gizmo's special effect to an orientation pointing towards its movement direction. Not a self-interaction function! Call this function on your gizmo during creation after creating the special effect.
---@param gizmo table
function CAT_InitDirectedOrientation(gizmo)
local alpha = atan2(gizmo.vy, gizmo.vx)
local cosAngle = cos(alpha)
local sinAngle = sin(alpha)
gizmo.O11 = cosAngle
gizmo.O12 = -sinAngle
gizmo.O13 = 0
gizmo.O21 = sinAngle
gizmo.O22 = cosAngle
gizmo.O23 = 0
gizmo.O31 = 0
gizmo.O32 = 0
gizmo.O33 = 1
BlzSetSpecialEffectOrientation(gizmo.visual, atan2(-gizmo.O12, gizmo.O11), atan2(gizmo.O13, sqrt(gizmo.O12^2 + gizmo.O11^2)), atan2(gizmo.O23, gizmo.O33))
end
function InitEffectsCAT()
Require "ALICE"
Require "PrecomputedHeightMap"
INTERVAL = ALICE_Config.MIN_INTERVAL
ALICE_FuncSetInit(CAT_AnimateShadow, InitAnimateShadow)
ALICE_FuncSetInit(CAT_MoveEffect, InitMoveEffect)
ALICE_FuncSetInit(CAT_OrientRoll, InitOrientation)
ALICE_FuncSetInit(CAT_Orient2D, InitOrient2D)
ALICE_FuncSetInit(CAT_Orient3D, InitOrient3D)
ALICE_FuncSetInit(CAT_OrientPropelled2D, InitOrientPropelled2D)
ALICE_FuncSetInit(CAT_OrientPropelled3D, InitOrientPropelled3D)
ALICE_FuncSetInit(CAT_OrientProjectile, InitOrient3D)
ALICE_FuncSetOnDestroy(CAT_MoveAttachedEffect, ClearAttachedEffect)
ALICE_FuncSetOnDestroy(CAT_AnimateShadow, ClearShadow)
ALICE_RecognizeFields(
"shadowX", "shadowY", "shadowAlpha",
"ax", "ay",
"collisionRadius",
"rollSpeed",
"O11", "O12", "O13", "O21", "O22", "O23", "O31", "O32", "O33"
)
ALICE_FuncRequireFields(CAT_AnimateShadow, true, false, "shadowPath", "shadowWidth", "shadowHeight")
ALICE_FuncRequireFields(CAT_OrientRoll, true, false, "collisionRadius")
ALICE_FuncRequireFields(CAT_OrientProjectile, true, false, "collisionRadius")
end
OnInit.final("CAT_Effects", InitEffectsCAT)
end
if Debug then Debug.beginFile "CAT Collisions2D" end
do
--[[
=============================================================================================================================================================
Complementary ALICE Template
by Antares
Requires:
ALICE https://www.hiveworkshop.com/threads/a-l-i-c-e-interaction-engine.353126/
Objects CAT
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
PrecomuptedHeightMap (optional) https://www.hiveworkshop.com/threads/precomputed-synchronized-terrain-height-map.353477/
Knockback Item ('Ikno') (optional)
=============================================================================================================================================================
C O L L I S I O N S 2 D
=============================================================================================================================================================
This template contains various functions to detect and execute collisions between gizmos* and any type of object. Terrain collision is not part of this
template. The functions are accessed by adding them to your gizmo class tables (for an example, see gizmos CAT).
*Objects represented by a table with coordinate fields .x, .y, .z, velocity fields .vx, .vy, .vz, and a special effect .visual.
To add collisions, add a collision check function to the ALICE interactions table of your gizmos. Each object type has its own collision check function.
They are:
CAT_GizmoCollisionCheck2D
CAT_UnitCollisionCheck2D
CAT_DestructableCollisionCheck2D
CAT_ItemCollisionCheck2D
Example:
interactions = {
unit = CAT_UnitCollisionCheck2D,
destructable = CAT_DestructableCollisionCheck2D
}
By default, collision checks will not discriminate between friend or foe. To disable friendly-fire, set the .friendlyFire field in your gizmo table to false
and the .owner field to the owner of the gizmo. This works for unit and gizmo collision checks.
You can also set the .onlyTarget field. This will disable collision checks with any unit that isn't set as the .target of the gizmo.
-------------------------------------------------------------------------------------------------------------------------------------------------------------
To execute code on collision, you need to define an onCollision function, where there are, again, different ones for each object type. The table fields you
need to set for onCollision functions are:
onGizmoCollision
onUnitCollision
onDestructableCollision
onItemCollision
You can use an onCollision function provided in this CAT or your own function. The preset functions are listed further down below.
The value for any table field you set for this CAT can be either a function or a table. A table is set up similarly to how an ALICE interactions table is set
up, where the keys denote the identifiers of the objects for which that function is used. You can use tables as keys, listing multiple identifiers, and you
can also use the "other" keyword. If no onCollision function is provided, the gizmo will simply be destroyed on collision.
Example:
onGizmoCollision = {
[{"ball", "soft"}] = CAT_GizmoBounce2D,
spike = CAT_GizmoImpact2D,
other = CAT_GizmoPassThrough2D
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------
For a simple projectile or missile dealing damage, you can use the onDamage feature without defining an onCollision function. The possible table fields are:
onUnitDamage
onDestructableDamage
onItemDamage
Each value can be a function or a number. A function is called with the arguments (gizmo, object) and the return value is used as the damage amount.
Example:
onUnitDamage = {
"hero" = GetRandomDamageAmount,
"nonhero" = 5,
}
You can customize the damage and attack types of the damage. The .onUnitAttackType field determines the attack type used. The default type is ATTACK_TYPE_NORMAL.
The same for .onUnitDamageType. The default type is DAMAGE_TYPE_MAGIC.
onDamage can be combined with onCollision functions. If you do, additional parameters are passed into a damage function related to the impact velocity of the
collision:
onDamageFunction(gizmo, object, perpendicularSpeed, parallelSpeed, totalSpeed)
-------------------------------------------------------------------------------------------------------------------------------------------------------------
The onCollision functions also allow you to define an additional callback function. There are no preset functions. The table fields for these callback functions
are:
onGizmoCallback
onUnitCallback
onDestructableCallback
onItemCallback
These table fields have no effect unless an onCollision function has been set. The callback function will be called with these input arguments:
callback(
gizmo, object,
collisionPointX, collisionPointY, collisionPointZ,
perpendicularSpeed, parallelSpeed, totalSpeed,
centerOfMassVelocityX, centerOfMassVelocityY, centerOfMassVelocityZ
)
The main advantage of definining your custom callback function as an onCallback instead of an onCollision function is that the onCollision functions calculate
additional parameters of the collision, such as impact velocity and exact impact point, before invoking the callback function.
-------------------------------------------------------------------------------------------------------------------------------------------------------------
!!!IMPORTANT!!! There are additional table fields that need to be set for collision checks to work correctly.
• .collisionRadius must be set to define the radius of your gizmo. Their collision box is a sphere. The collision boxes of widgets are customized in the
Objects CAT.
• .mass is necessary for knockbacks. The masses of units are customized in the Objects CAT.
• .maxSpeed controls how often a collision check is performed. It represents the maximum speed that the gizmo can reasonably reach. If not set, the
default value, set in the Objects CAT, will be used.
• .elasticity is used by bounce functions. The default value is 1. The elasticity of widgets can be customized in the Objects CAT. The elasticity of a
collision is sqrt(elasticity 1 * elasticity 2).
-------------------------------------------------------------------------------------------------------------------------------------------------------------
Anchors:
You can anchor a table to a widget. This will reroute the collision recoil to the anchor if it is a unit. You can also enable unit-widget collisions this way,
although there may be some bugs and issues with this. If the table has a mass field, that value will be used to calculate the recoil. Otherwise, the unit's mass
will be used. Other fields cannot be overwritten and must be provided.
=============================================================================================================================================================
L I S T O F F U N C T I O N S
=============================================================================================================================================================
Gizmo-Gizmo Collisions:
CAT_GizmoCollisionCheck2D
Callbacks:
CAT_GizmoBounce2D Reflect the two gizmos.
CAT_GizmoImpact2D Destroy the initiating gizmo and recoil the other.
CAT_GizmoDevour2D Destroy the receiving gizmo and recoil the other.
CAT_GizmoAnnihilate2D Destroy both gizmos.
CAT_GizmoPassThrough2D Execute the callback function once, but do not destroy or recoil either.
Gizmo-Unit Collisions:
CAT_UnitCollisionCheck2D
Callbacks:
CAT_UnitBounce2D Reflect the gizmo on the unit and recoil the unit.
CAT_UnitImpact2D Destroy the gizmo and recoil the unit.
CAT_UnitDevour2D Kill the unit and recoil the gizmo.
CAT_UnitAnnihilate2D Destroy both the unit and the gizmo.
CAT_UnitPassThrough2D Execute the callback function once, but do not destroy or recoil either.
Gizmo-Destructable Collisions:
CAT_DestructableCollisionCheck2D
Callbacks:
CAT_DestructableBounce2D Reflect the gizmo on the destructable.
CAT_DestructableImpact2D Destroy the gizmo.
CAT_DestructableDevour2D Destroy the destructable and recoil the gizmo.
CAT_DestructableAnnihilate2D Destroy both the destructable and the gizmo.
CAT_DestructablePassThrough2D Execute the callback function once, but do not destroy or recoil either.
Gizmo-Item Collisions:
CAT_ItemCollisionCheck2D
Callbacks:
CAT_ItemBounce2D Reflect the gizmo on the item.
CAT_ItemImpact2D Destroy the gizmo.
CAT_ItemDevour2D Destroy the item and recoil the gizmo.
CAT_ItemAnnihilate2D Destroy the item and the gizmo.
CAT_ItemPassThrough2D Execute the callback function once, but do not destroy or recoil either.
--===========================================================================================================================================================
]]
local INTERVAL = nil
local UNIT_MAX_SPEED = 522
local INF = math.huge
local sqrt = math.sqrt
local GetTerrainZ = nil ---@type function
local moveableLoc = nil ---@type location
local function DamageWidget(gizmo, widget, perpendicularSpeed, parallelSpeed, totalSpeed)
if HandleType[widget] == "unit" then
local damage = ALICE_FindField(gizmo.onUnitDamage, widget)
if type(damage) == "function" then
UnitDamageTarget(gizmo.source, widget, damage(gizmo, widget, perpendicularSpeed, parallelSpeed, totalSpeed), false, false, gizmo.onUnitAttackType or ATTACK_TYPE_NORMAL, gizmo.onUnitDamageType or DAMAGE_TYPE_MAGIC, WEAPON_TYPE_WHOKNOWS)
else
UnitDamageTarget(gizmo.source, widget, damage, false, false, gizmo.onUnitAttackType or ATTACK_TYPE_NORMAL, gizmo.onUnitDamageType or DAMAGE_TYPE_MAGIC, WEAPON_TYPE_WHOKNOWS)
end
elseif HandleType[widget] == "destructable" then
local damage = ALICE_FindField(gizmo.onDestructableDamage, widget)
if type(damage) == "function" then
SetDestructableLife(widget, GetDestructableLife(widget) - damage(gizmo, widget, perpendicularSpeed, parallelSpeed, totalSpeed))
else
SetDestructableLife(widget, GetDestructableLife(widget) - damage)
end
else
local damage = ALICE_FindField(gizmo.onItemDamage, widget)
if type(damage) == "function" then
SetWidgetLife(widget, GetWidgetLife(widget) - damage(gizmo, widget, perpendicularSpeed, parallelSpeed, totalSpeed))
else
SetWidgetLife(widget, GetWidgetLife(widget) - damage)
end
end
end
local function Backtrack(gizmo, vx, vy, collisionX, collisionY)
if vx == nil or (vx == 0 and vy == 0) then
return
end
local factor = gizmo.collisionRadius/sqrt(vx*vx + vy*vy)
gizmo.x = collisionX - vx*factor
gizmo.y = collisionY - vy*factor
BlzSetSpecialEffectPosition(gizmo.visual, gizmo.x, gizmo.y, gizmo.z or GetTerrainZ(gizmo.x, gizmo.y))
end
--===========================================================================================================================================================
--Gizmo-Gizmo Collisions
--==========================================================================================================================================================
---@param A table
---@param B table
local function GetGizmoCollisionPoint2D(A, B, ax, ay, bx, by)
local collisionDist = A.collisionRadius + B.collisionRadius
local collisionX = (ax*B.collisionRadius + bx*A.collisionRadius)/collisionDist
local collisionY = (ay*B.collisionRadius + by*A.collisionRadius)/collisionDist
return collisionX, collisionY, collisionDist
end
local function GizmoCollisionMath2D(A, B)
local xa, ya, xb, yb = ALICE_PairGetCoordinates2D()
local dx, dy = xa - xb, ya - yb
local vxa, vya = CAT_GetObjectVelocity2D(A)
local vxb, vyb = CAT_GetObjectVelocity2D(B)
local dvx, dvy = vxa - vxb, vya - vyb
local dist = sqrt(dx*dx + dy*dy)
local perpendicularSpeed = -(dx*dvx + dy*dvy)/dist
if perpendicularSpeed < 0 then
return false
end
local totalSpeed = sqrt(dvx*dvx + dvy*dvy)
local parallelSpeed = sqrt(totalSpeed^2 - perpendicularSpeed^2)
local massA = CAT_GetObjectMass(A)
local massB = CAT_GetObjectMass(B)
local invMassSum = 1/(massA + massB)
local centerOfMassVx, centerOfMassVy
if massA == INF then
if massB == INF then
centerOfMassVx = (vxa*massA + vxb*massB)*invMassSum
centerOfMassVy = (vya*massA + vyb*massB)*invMassSum
else
centerOfMassVx = vxa
centerOfMassVy = vya
end
elseif massB == INF then
centerOfMassVx = vxb
centerOfMassVy = vyb
elseif massA == 0 and massB == 0 then
centerOfMassVx = (vxa + vxb)/2
centerOfMassVy = (vya + vyb)/2
else
centerOfMassVx = (vxa*massA + vxb*massB)*invMassSum
centerOfMassVy = (vya*massA + vyb*massB)*invMassSum
end
return true, xa, ya, xb, yb, dist,
vxa, vya, vxb, vyb,
dx, dy, dvx, dvy,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy
end
local function GizmoRecoilAndDisplace2D(object, x, y, recoilX, recoilY)
if object.anchor then
if type(object.anchor) == "table" then
object.anchor.x,object.anchor.y = x, y
object.anchor.vx, object.anchor.vy = object.anchor.vx + recoilX, object.anchor.vy + recoilY
else
SetUnitX(object.anchor, x)
SetUnitY(object.anchor, y)
CAT_Knockback(object.anchor, recoilX, recoilY, 0)
end
else
object.x,object.y = x, y
object.vx, object.vy = object.vx + recoilX, object.vy + recoilY
end
end
local function GizmoRecoil2D(object, recoilX, recoilY)
if object.anchor then
if type(object.anchor) == "table" then
object.anchor.vx, object.anchor.vy = object.anchor.vx + recoilX, object.anchor.vy + recoilY
else
CAT_Knockback(object.anchor, recoilX, recoilY, 0)
end
else
object.vx, object.vy = object.vx + recoilX, object.vy + recoilY
end
end
local function GetMassRatio(massA, massB)
--massA >>> massB -> 1
--massB >>> massA -> 0
if massA == 0 and massB == 0 then
return 0.5
elseif massA == INF then
if massB == INF then
return 0.5
else
return 1
end
else
return massA/(massA + massB)
end
end
-------------
--Callbacks
-------------
function CAT_GizmoBounce2D(A, B)
local validCollision, xa, ya, xb, yb, dist,
vxa, vya, vxb, vyb,
dx, dy, dvx, dvy,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy = GizmoCollisionMath2D(A, B)
if not validCollision then
return
end
local elasticity = sqrt((A.elasticity or 1)*(B.elasticity or 1))
local e = (1 + elasticity)
local nx, ny = dx/dist, dy/dist
local Advx = vxa - centerOfMassVx
local Advy = vya - centerOfMassVy
local Bdvx = vxb - centerOfMassVx
local Bdvy = vyb - centerOfMassVy
--Householder transformation.
local H11 = 1 - e*nx^2
local H12 = -e*nx*ny
local H21 = H12
local H22 = 1 - e*ny^2
local collisionX, collisionY, collisionDist = GetGizmoCollisionPoint2D(A, B, xa, ya, xb, yb)
local massRatio = GetMassRatio(massA, massB)
local xNew, yNew, recoilX, recoilY
local displacement = collisionDist - dist
if massRatio < 1 then
xNew = xa + 1.001*dx/dist*displacement*(1 - massRatio)
yNew = ya + 1.001*dy/dist*displacement*(1 - massRatio)
recoilX = H11*Advx + H12*Advy + centerOfMassVx - vxa
recoilY = H21*Advx + H22*Advy + centerOfMassVy - vya
GizmoRecoilAndDisplace2D(A, xNew, yNew, recoilX, recoilY)
else
A.vx, A.vy = 0, 0
end
if massRatio > 0 then
xNew = xb - 1.001*dx/dist*displacement*massRatio
yNew = yb - 1.001*dy/dist*displacement*massRatio
recoilX = H11*Bdvx + H12*Bdvy + centerOfMassVx - vxb
recoilY = H21*Bdvx + H22*Bdvy + centerOfMassVy - vyb
GizmoRecoilAndDisplace2D(B, xNew, yNew, recoilX, recoilY)
else
B.vx, B.vy = 0, 0
end
local callback = ALICE_FindField(A.onGizmoCallback, B)
if callback then
callback(A, B, collisionX, collisionY, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy)
end
end
function CAT_GizmoImpact2D(A, B)
local validCollision, xa, ya, xb, yb, dist,
vxa, vya, vxb, vyb,
dx, dy, dvx, dvy,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy = GizmoCollisionMath2D(A, B)
local collisionX, collisionY, collisionDist = GetGizmoCollisionPoint2D(A, B, xa, ya, xb, yb)
if massA > 0 then
local unmoved
--Avoid unpausing resting gizmo with only minor bounce.
if B.isResting and perpendicularSpeed/2*A.mass/B.mass < B.friction*STATIC_FRICTION_FACTOR*INTERVAL or (massB == INF and massA == INF) then
unmoved = true
end
if not unmoved then
local recoilX, recoilY, recoilZ
local massRatio = GetMassRatio(massA, massB)
if massRatio > 0 then
recoilX = dvx*massRatio
recoilY = dvy*massRatio
GizmoRecoil2D(B, recoilX, recoilY)
end
end
end
local callback = ALICE_FindField(A.onGizmoCallback, B)
if callback then
callback(A, B, collisionX, collisionY, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy)
end
Backtrack(A, vxa, vya, collisionX, collisionY)
ALICE_Kill(A)
end
function CAT_GizmoDevour2D(A, B)
local validCollision, xa, ya, xb, yb, dist,
vxa, vya, vxb, vyb,
dx, dy, dvx, dvy,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy = GizmoCollisionMath2D(A, B)
local collisionX, collisionY, collisionDist = GetGizmoCollisionPoint2D(A, B, xa, ya, xb, yb)
if massA > 0 then
local unmoved
--Avoid unpausing resting gizmo with only minor bounce.
if A.isResting and perpendicularSpeed/2*B.mass/A.mass < A.friction*STATIC_FRICTION_FACTOR*INTERVAL or (massA == INF and massB == INF) then
unmoved = true
end
if not unmoved then
local recoilX, recoilY
local massRatio = GetMassRatio(massA, massB)
if massRatio > 0 then
recoilX = -dvx*(1 - massRatio)
recoilY = -dvy*(1 - massRatio)
GizmoRecoil2D(A, recoilX, recoilY)
end
end
end
local callback = ALICE_FindField(A.onGizmoCallback, B)
if callback then
callback(A, B, collisionX, collisionY, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy)
end
Backtrack(B, vxb, vyb, collisionX, collisionY)
ALICE_Kill(B)
end
function CAT_GizmoAnnihilate2D(A, B)
local validCollision, xa, ya, xb, yb, dist,
vxa, vya, vxb, vyb,
dx, dy, dvx, dvy,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy = GizmoCollisionMath2D(A, B)
local collisionX, collisionY, collisionDist = GetGizmoCollisionPoint2D(A, B, xa, ya, xb, yb)
local callback = ALICE_FindField(A.onGizmoCallback, B)
if callback then
callback(A, B, collisionX, collisionY, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy)
end
Backtrack(A, vxa, vya, collisionX, collisionY)
ALICE_Kill(A)
Backtrack(B, vxb, vyb, collisionX, collisionY)
ALICE_Kill(B)
end
function CAT_GizmoPassThrough2D(A, B)
local callback = ALICE_FindField(A.onGizmoCallback, B)
if callback then
local validCollision, xa, ya, xb, yb, dist,
vxa, vya, vxb, vyb,
dx, dy, dvx, dvy,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy = GizmoCollisionMath2D(A, B)
local collisionX, collisionY, collisionDist = GetGizmoCollisionPoint2D(A, B, xa, ya, xb, yb)
callback(A, B, collisionX, collisionY, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy)
end
ALICE_PairDisable()
end
--------------------
--Collision Checks
--------------------
function CAT_GizmoCollisionCheck2D(A, B)
local dx, dy, dist
if A.anchor or B.anchor then
dist = ALICE_PairGetDistance2D()
else
dx = A.x - B.x
dy = A.y - B.y
dist = sqrt(dx*dx + dy*dy)
end
local collisionRange = A.collisionRadius + B.collisionRadius
if dist < collisionRange and not (A.friendlyFire == false and ALICE_PairIsFriend()) then
local callback = ALICE_FindField(A.onGizmoCollision, B)
if callback then
callback(A, B)
end
A.hasCollided = true
B.hasCollided = true
end
if A.isResting and B.isResting then
ALICE_PairPause()
end
return (dist - collisionRange)/((A.maxSpeed or DEFAULT_GIZMO_MAX_SPEED) + (B.maxSpeed or DEFAULT_GIZMO_MAX_SPEED))
end
--===========================================================================================================================================================
--Gizmo-Widget Collisions
--==========================================================================================================================================================
local function WidgetCollisionMath2D(gizmo, widget)
local data = ALICE_PairLoadData()
local xa, ya, xb, yb = ALICE_PairGetCoordinates2D()
local dx, dy = xa - xb, ya - yb
local vxa, vya = CAT_GetObjectVelocity2D(gizmo)
local vxb, vyb = CAT_GetObjectVelocity2D(widget)
local dvx, dvy = vxa - vxb, vya - vyb
local dist = sqrt(dx*dx + dy*dy)
local nx, ny = dx/dist, dy/dist
local collisionX, collisionY
local overlap = data.radius + gizmo.collisionRadius - dist
local perpendicularSpeed = -(nx*dvx + ny*dvy)
collisionX = xb + nx*data.radius
collisionY = yb + ny*data.radius
local totalSpeed = sqrt(dvx*dvx + dvy*dvy)
local parallelSpeed = sqrt(totalSpeed^2 - perpendicularSpeed^2)
local massA = CAT_GetObjectMass(gizmo)
local massB = CAT_GetObjectMass(widget)
local massSum = massA + massB
local centerOfMassVx, centerOfMassVy
if massA == INF then
if massB == INF then
centerOfMassVx = (vxa*massA + vxb*massB)/massSum
centerOfMassVy = (vya*massA + vyb*massB)/massSum
else
centerOfMassVx = vxa
centerOfMassVy = vya
end
elseif massB == INF then
centerOfMassVx = vxb
centerOfMassVy = vyb
else
centerOfMassVx = (vxa*massA + vxb*massB)/massSum
centerOfMassVy = (vya*massA + vyb*massB)/massSum
end
return perpendicularSpeed >= 0, xa, ya, xb, yb, dist,
vxa, vya, vxb, vyb,
dx, dy, dvx, dvy,
nx, ny,
collisionX, collisionY, overlap,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy
end
-------------
--Callbacks
-------------
local function WidgetBounce2D(gizmo, widget)
local isValidCollision, xa, ya, xb, yb, dist,
vxa, vya, vxb, vyb,
dx, dy, dvx, dvy,
nx, ny,
collisionX, collisionY, overlap,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy = WidgetCollisionMath2D(gizmo, widget)
if not isValidCollision then
return
end
local elasticity
local callbackName
local damageName
local isUnit = false
if HandleType[widget] == "unit" then
isUnit = true
elasticity = sqrt((gizmo.elasticity or 1)*(WIDGET_TYPE_ELASTICITY[GetUnitTypeId(widget)] or DEFAULT_UNIT_ELASTICITY))
callbackName = "onUnitCallback"
damageName = "onUnitDamage"
elseif HandleType[widget] == "destructable" then
elasticity = sqrt((gizmo.elasticity or 1)*(WIDGET_TYPE_ELASTICITY[GetDestructableTypeId(widget)] or DEFAULT_DESTRUCTABLE_ELASTICITY))
callbackName = "onDestructableCallback"
damageName = "onDestructableDamage"
else
elasticity = sqrt((gizmo.elasticity or 1)*(WIDGET_TYPE_ELASTICITY[GetItemTypeId(widget)] or DEFAULT_ITEM_ELASTICITY))
callbackName = "onItemCallback"
damageName = "onItemDamage"
end
local e = (1 + elasticity)
local Advx = vxa - centerOfMassVx
local Advy = vya - centerOfMassVy
local Bdvx = vxb - centerOfMassVx
local Bdvy = vyb - centerOfMassVy
--Householder transformation.
local H11 = 1 - e*nx^2
local H12 = -e*nx*ny
local H21 = H12
local H22 = 1 - e*ny^2
local massRatio = GetMassRatio(massA, massB)
local xNew, yNew, recoilX, recoilY
if massRatio < 1 then
xNew = xa + 1.001*nx*overlap*(1 - massRatio)
yNew = ya + 1.001*ny*overlap*(1 - massRatio)
recoilX = H11*Advx + H12*Advy + centerOfMassVx - vxa
recoilY = H21*Advx + H22*Advy + centerOfMassVy - vya
GizmoRecoilAndDisplace2D(gizmo, xNew, yNew, recoilX, recoilY)
end
if massRatio > 0 then
xNew = xb - 1.001*nx*overlap*massRatio
yNew = yb - 1.001*ny*overlap*massRatio
recoilX = H11*Bdvx + H12*Bdvy + centerOfMassVx - vxb
recoilY = H21*Bdvx + H22*Bdvy + centerOfMassVy - vyb
if isUnit then
SetUnitX(widget, xNew)
SetUnitY(widget, yNew)
CAT_Knockback(widget, recoilX, recoilY, 0)
end
end
if gizmo[damageName] then
DamageWidget(gizmo, widget)
end
local callback = ALICE_FindField(gizmo[callbackName], widget)
if callback then
callback(gizmo, widget, collisionX, collisionY, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy)
end
end
local function WidgetImpact2D(gizmo, widget)
local isValidCollision, xa, ya, xb, yb, dist,
vxa, vya, vxb, vyb,
dx, dy, dvx, dvy,
nx, ny,
collisionX, collisionY, overlap,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy = WidgetCollisionMath2D(gizmo, widget)
if massA > 0 then
local recoilX, recoilY
local massRatio = GetMassRatio(massA, massB)
if massRatio > 0 then
recoilX = dvx*massRatio
recoilY = dvy*massRatio
if HandleType[widget] == "unit" then
CAT_Knockback(widget, recoilX, recoilY, 0)
end
end
end
local callbackName
local damageName
if HandleType[widget] == "unit" then
callbackName = "onUnitCallback"
damageName = "onUnitDamage"
elseif HandleType[widget] == "destructable" then
callbackName = "onDestructableCallback"
damageName = "onDestructableDamage"
else
callbackName = "onItemCallback"
damageName = "onItemDamage"
end
if gizmo[damageName] then
DamageWidget(gizmo, widget)
end
local callback = ALICE_FindField(gizmo[callbackName], widget)
if callback then
callback(gizmo, widget, collisionX, collisionY, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy)
end
Backtrack(gizmo, vxa, vya, collisionX, collisionY)
ALICE_Kill(gizmo)
end
local function WidgetDevour2D(gizmo, widget)
local isValidCollision, xa, ya, xb, yb, dist,
vxa, vya, vxb, vyb,
dx, dy, dvx, dvy,
nx, ny,
collisionX, collisionY, overlap,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy = WidgetCollisionMath2D(gizmo, widget)
if massA > 0 then
local recoilX, recoilY, recoilZ
local massRatio = GetMassRatio(massA, massB)
if massRatio > 0 then
recoilX = -dvx*(1 - massRatio)
recoilY = -dvy*(1 - massRatio)
GizmoRecoil2D(gizmo, recoilX, recoilY)
end
end
local callbackName
local damageName
if HandleType[widget] == "unit" then
callbackName = "onUnitCallback"
damageName = "onUnitDamage"
elseif HandleType[widget] == "destructable" then
callbackName = "onDestructableCallback"
damageName = "onDestructableDamage"
else
callbackName = "onItemCallback"
damageName = "onItemDamage"
end
if gizmo[damageName] then
DamageWidget(gizmo, widget)
end
local callback = ALICE_FindField(gizmo[callbackName], widget)
if callback then
callback(gizmo, widget, collisionX, collisionY, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy)
end
ALICE_Kill(widget)
end
local function WidgetAnnihilate2D(gizmo, widget)
local isValidCollision, xa, ya, xb, yb, dist,
vxa, vya, vxb, vyb,
dx, dy, dvx, dvy,
nx, ny,
collisionX, collisionY, overlap,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy = WidgetCollisionMath2D(gizmo, widget)
local callbackName
if HandleType[widget] == "unit" then
callbackName = "onUnitCallback"
elseif HandleType[widget] == "destructable" then
callbackName = "onDestructableCallback"
else
callbackName = "onItemCallback"
end
local callback = ALICE_FindField(gizmo[callbackName], widget)
if callback then
callback(gizmo, widget, collisionX, collisionY, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy)
end
Backtrack(gizmo, vxa, vya, collisionX, collisionY)
ALICE_Kill(gizmo)
ALICE_Kill(widget)
end
local function WidgetPassThrough2D(gizmo, widget)
local callbackName
local damageName
if HandleType[widget] == "unit" then
callbackName = "onUnitCallback"
damageName = "onUnitDamage"
elseif HandleType[widget] == "destructable" then
callbackName = "onDestructableCallback"
damageName = "onDestructableDamage"
else
callbackName = "onItemCallback"
damageName = "onItemDamage"
end
if gizmo[damageName] then
DamageWidget(gizmo, widget)
end
local callback = ALICE_FindField(gizmo[callbackName], widget)
if callback then
local isValidCollision, xa, ya, xb, yb, dist,
vxa, vya, vxb, vyb,
dx, dy, dvx, dvy,
nx, ny,
collisionX, collisionY, overlap,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy = WidgetCollisionMath2D(gizmo, widget)
callback(gizmo, widget, collisionX, collisionY, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy)
end
ALICE_PairDisable()
end
CAT_UnitBounce2D = WidgetBounce2D
CAT_UnitImpact2D = WidgetImpact2D
CAT_UnitDevour2D = WidgetDevour2D
CAT_UnitAnnihilate2D = WidgetAnnihilate2D
CAT_UnitPassThrough2D = WidgetPassThrough2D
CAT_DestructableBounce2D = WidgetBounce2D
CAT_DestructableImpact2D = WidgetImpact2D
CAT_DestructableDevour2D = WidgetDevour2D
CAT_DestructableAnnihilate2D = WidgetAnnihilate2D
CAT_DestructablePassThrough2D = WidgetPassThrough2D
CAT_ItemBounce2D = WidgetBounce2D
CAT_ItemImpact2D = WidgetImpact2D
CAT_ItemDevour2D = WidgetDevour2D
CAT_ItemAnnihilate2D = WidgetAnnihilate2D
CAT_ItemPassThrough2D = WidgetPassThrough2D
--===========================================================================================================================================================
--Gizmo-Unit Collisions
--==========================================================================================================================================================
--------------------
--Collision Checks
--------------------
local function InitUnitCollisionCheck2D(gizmo, unit)
local data = ALICE_PairLoadData()
local id = GetUnitTypeId(unit)
local collisionSize = BlzGetUnitCollisionSize(unit)
data.radius = WIDGET_TYPE_COLLISION_RADIUS[id] or collisionSize
data.collisionRange = data.radius + gizmo.collisionRadius
gizmo.maxSpeed = gizmo.maxSpeed or DEFAULT_GIZMO_MAX_SPEED
end
function CAT_UnitCollisionCheck2D(gizmo, unit)
local data = ALICE_PairLoadData()
local dist = ALICE_PairGetDistance2D()
if dist < data.collisionRange and not (gizmo.friendlyFire == false and ALICE_PairIsFriend()) and (gizmo.onlyTarget == nil or unit == gizmo.target) then
local callback = ALICE_FindField(gizmo.onUnitCollision, unit)
if callback then
callback(gizmo, unit)
else
ALICE_Kill(gizmo)
end
end
return (dist - data.collisionRange)/(gizmo.maxSpeed + UNIT_MAX_SPEED)
end
--===========================================================================================================================================================
--Gizmo-Destructable Collisions
--==========================================================================================================================================================
--------------------
--Collision Checks
--------------------
local function InitDestructableCollisionCheck2D(gizmo, destructable)
local data = ALICE_PairLoadData()
local id = GetDestructableTypeId(destructable)
data.radius = WIDGET_TYPE_COLLISION_RADIUS[id] or DEFAULT_DESTRUCTABLE_COLLISION_RADIUS
data.collisionRange = data.radius + gizmo.collisionRadius
gizmo.maxSpeed = gizmo.maxSpeed or DEFAULT_GIZMO_MAX_SPEED
end
function CAT_DestructableCollisionCheck2D(gizmo, destructable)
local data = ALICE_PairLoadData()
local dist = ALICE_PairGetDistance2D()
if dist < data.collisionRange then
local callback = ALICE_FindField(gizmo.onDestructableCollision, destructable)
if callback then
callback(gizmo, destructable)
else
ALICE_Kill(gizmo)
end
end
if gizmo.isResting then
ALICE_PairPause()
end
return (dist - data.collisionRange)/gizmo.maxSpeed
end
--===========================================================================================================================================================
--Gizmo-Item Collisions
--==========================================================================================================================================================
--------------------
--Collision Checks
--------------------
local function InitItemCollisionCheck2D(gizmo, item)
local data = ALICE_PairLoadData()
local id = GetItemTypeId(item)
data.collisionRange = (WIDGET_TYPE_COLLISION_RADIUS[id] or DEFAULT_ITEM_COLLISION_RADIUS) + gizmo.collisionRadius
gizmo.maxSpeed = gizmo.maxSpeed or DEFAULT_GIZMO_MAX_SPEED
end
function CAT_ItemCollisionCheck2D(gizmo, item)
local data = ALICE_PairLoadData()
local dist = ALICE_PairGetDistance2D()
if dist < data.collisionRange then
local callback = ALICE_FindField(gizmo.onItemCollision, item)
if callback then
callback(gizmo, item)
else
ALICE_Kill(gizmo)
end
end
if gizmo.isResting then
ALICE_PairPause()
end
return (dist - data.collisionRange)/gizmo.maxSpeed
end
--===========================================================================================================================================================
--Init
--==========================================================================================================================================================
local function InitCollisionsCAT()
Require "ALICE"
Require "CAT_Objects"
INTERVAL = ALICE_Config.MIN_INTERVAL
ALICE_FuncSetInit(CAT_UnitCollisionCheck2D, InitUnitCollisionCheck2D)
ALICE_FuncSetInit(CAT_DestructableCollisionCheck2D, InitDestructableCollisionCheck2D)
ALICE_FuncSetInit(CAT_ItemCollisionCheck2D, InitItemCollisionCheck2D)
ALICE_RecognizeFields(
"vx",
"vy",
"vz",
"friction",
"isResting",
"collisionRadius",
"onGizmoCollision",
"onUnitCollision",
"onDestructableCollision",
"onItemCollision",
"onGizmoCallback",
"onUnitCallback",
"onDestructableCallback",
"onItemCallback",
"onUnitDamage",
"onDestructableDamage",
"onItemDamage",
"collisionRadius",
"mass",
"elasticity",
"maxSpeed",
"target",
"onlyTarget"
)
ALICE_FuncRequireFields(CAT_GizmoCollisionCheck2D, true, true, "collisionRadius")
ALICE_FuncRequireFields(CAT_UnitCollisionCheck2D, true, false, "collisionRadius")
ALICE_FuncRequireFields(CAT_DestructableCollisionCheck2D, true, false, "collisionRadius")
ALICE_FuncRequireFields(CAT_ItemCollisionCheck2D, true, false, "collisionRadius")
local precomputedHeightMap = Require.optionally "PrecomputedHeightMap"
if precomputedHeightMap then
GetTerrainZ = _G.GetTerrainZ
else
moveableLoc = Location(0, 0)
GetTerrainZ = function(x, y)
MoveLocation(moveableLoc, x, y)
return GetLocationZ(moveableLoc)
end
end
end
OnInit.final("CAT_Collisions", InitCollisionsCAT)
end
if Debug then Debug.beginFile "CAT Collisions3D" end
do
--[[
=============================================================================================================================================================
Complementary ALICE Template
by Antares
Requires:
ALICE https://www.hiveworkshop.com/threads/a-l-i-c-e-interaction-engine.353126/
Objects CAT
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
PrecomuptedHeightMap (optional) https://www.hiveworkshop.com/threads/precomputed-synchronized-terrain-height-map.353477/
Knockback Item ('Ikno') (optional)
=============================================================================================================================================================
C O L L I S I O N S 3 D
=============================================================================================================================================================
This template contains various functions to detect and execute collisions between gizmos* and any type of object. Terrain collision is not part of this
template. The functions are accessed by adding them to your gizmo class tables (for an example, see Gizmos CAT).
*Objects represented by a table with coordinate fields .x, .y, .z, velocity fields .vx, .vy, .vz, and a special effect .visual.
To add collisions, add a collision check function to the ALICE interactions table of your gizmos. Each object type has its own collision check function.
They are:
CAT_GizmoCollisionCheck3D
CAT_UnitCollisionCheck3D
CAT_DestructableCollisionCheck3D
CAT_ItemCollisionCheck3D
Example:
interactions = {
unit = CAT_UnitCollisionCheck3D,
destructable = CAT_DestructableCollisionCheck3D
}
By default, collision checks will not discriminate between friend or foe. To disable friendly-fire, set the .friendlyFire field in your gizmo table to false
and the .owner field to the owner of the gizmo. This works for unit and gizmo collision checks.
You can also set the .onlyTarget field. This will disable collision checks with any unit that isn't set as the .target of the gizmo.
-------------------------------------------------------------------------------------------------------------------------------------------------------------
To execute code on collision, you need to define an onCollision function, where there are, again, different ones for each object type. The table fields you
need to set for onCollision functions are:
onGizmoCollision
onUnitCollision
onDestructableCollision
onItemCollision
You can use an onCollision function provided in this CAT or your own function. The preset functions are listed further down below.
The value for any table field you set for this CAT can be either a function or a table. A table is set up similarly to how an ALICE interactions table is set
up, where the keys denote the identifiers of the objects for which that function is used. You can use tables as keys, listing multiple identifiers, and you
can also use the "other" keyword. If no onCollision function is provided, the gizmo will simply be destroyed on collision.
Example:
onGizmoCollision = {
[{"ball", "soft"}] = CAT_GizmoBounce3D,
spike = CAT_GizmoImpact3D,
other = CAT_GizmoPassThrough3D
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------
For a simple projectile or missile dealing damage, you can use the onDamage feature without defining an onCollision function. The possible table fields are:
onUnitDamage
onDestructableDamage
onItemDamage
Each value can be a function or a number. A function is called with the arguments (gizmo, object) and the return value is used as the damage amount.
Example:
onUnitDamage = {
"hero" = GetRandomDamageAmount,
"nonhero" = 5,
}
You can customize the damage and attack types of the damage. The .onUnitAttackType field determines the attack type used. The default type is ATTACK_TYPE_NORMAL.
The same for .onUnitDamageType. The default type is DAMAGE_TYPE_MAGIC.
onDamage can be combined with onCollision functions. If you do, additional parameters are passed into a damage function related to the impact velocity of the
collision:
onDamageFunction(gizmo, object, perpendicularSpeed, parallelSpeed, totalSpeed)
For onUnitDamage, the .source field must be set to specify the source of the damage.
-------------------------------------------------------------------------------------------------------------------------------------------------------------
The onCollision functions also allow you to define an additional callback function. There are no preset functions. The table fields for these callback functions
are:
onGizmoCallback
onUnitCallback
onDestructableCallback
onItemCallback
These table fields have no effect unless an onCollision function has been set. The callback function will be called with these input arguments:
callback(
gizmo, object,
collisionPointX, collisionPointY, collisionPointZ,
perpendicularSpeed, parallelSpeed, totalSpeed,
centerOfMassVelocityX, centerOfMassVelocityY, centerOfMassVelocityZ
)
The main advantage of definining your custom callback function as an onCallback instead of an onCollision function is that the onCollision functions calculate
additional parameters of the collision, such as impact velocity and exact impact point, before invoking the callback function.
-------------------------------------------------------------------------------------------------------------------------------------------------------------
!!!IMPORTANT!!! There are additional table fields that need to be set for collision checks to work correctly.
• .collisionRadius must be set to define the radius of your gizmo. Their collision box is a sphere. The collision boxes of widgets are customized in the
Objects CAT.
• .mass is necessary for knockbacks. The masses of units are customized in the Objects CAT.
• .maxSpeed controls how often a collision check is performed. It represents the maximum speed that the gizmo can reasonably reach. If not set, the
default value, set in the Objects CAT, will be used.
• .elasticity is used by bounce functions. The default value is 1. The elasticity of widgets can be customized in the Objects CAT. The elasticity of a
collision is sqrt(elasticity 1 * elasticity 2).
-------------------------------------------------------------------------------------------------------------------------------------------------------------
Anchors:
You can anchor a table to a widget. This will reroute the collision recoil to the anchor if it is a unit. You can also enable unit-widget collisions this way,
although there may be some bugs and issues with this. If the table has a mass field, that value will be used to calculate the recoil. Otherwise, the unit's mass
will be used. Other fields cannot be overwritten and must be provided.
=============================================================================================================================================================
L I S T O F F U N C T I O N S
=============================================================================================================================================================
Gizmo-Gizmo Collisions:
CAT_GizmoCollisionCheck3D
CAT_GizmoCylindricalCollisionCheck3D Models the receiving gizmo as a cylinder with a rounded top instead of a sphere. The receiving gizmo needs to have
the collisionHeight field in its table.
Callbacks:
CAT_GizmoBounce3D Reflect the two gizmos.
CAT_GizmoImpact3D Destroy the initiating gizmo and recoil the other.
CAT_GizmoDevour3D Destroy the receiving gizmo and recoil the other.
CAT_GizmoAnnihilate3D Destroy both gizmos.
CAT_GizmoPassThrough3D Execute the callback function once, but do not destroy or recoil either.
Gizmo-Unit Collisions:
CAT_UnitCollisionCheck3D
Callbacks:
CAT_UnitBounce3D Reflect the gizmo on the unit and recoil the unit.
CAT_UnitImpact3D Destroy the gizmo and recoil the unit.
CAT_UnitDevour3D Kill the unit and recoil the gizmo.
CAT_UnitAnnihilate3D Destroy both the unit and the gizmo.
CAT_UnitPassThrough3D Execute the callback function once, but do not destroy or recoil either.
Gizmo-Destructable Collisions:
CAT_DestructableCollisionCheck3D
Callbacks:
CAT_DestructableBounce3D Reflect the gizmo on the destructable.
CAT_DestructableImpact3D Destroy the gizmo.
CAT_DestructableDevour3D Destroy the destructable and recoil the gizmo.
CAT_DestructableAnnihilate3D Destroy both the destructable and the gizmo.
CAT_DestructablePassThrough3D Execute the callback function once, but do not destroy or recoil either.
Gizmo-Item Collisions:
CAT_ItemCollisionCheck3D
Callbacks:
CAT_ItemBounce3D Reflect the gizmo on the item.
CAT_ItemImpact3D Destroy the gizmo.
CAT_ItemDevour3D Destroy the item and recoil the gizmo.
CAT_ItemAnnihilate3D Destroy the item and the gizmo.
CAT_ItemPassThrough3D Execute the callback function once, but do not destroy or recoil either.
--===========================================================================================================================================================
]]
local INTERVAL = nil
local UNIT_MAX_SPEED = 522
local INF = math.huge
local sqrt = math.sqrt
local cos = math.cos
local sin = math.sin
local atan2 = math.atan
local GetTerrainZ = nil ---@type function
local moveableLoc = nil ---@type location
local function DamageWidget(gizmo, widget, perpendicularSpeed, parallelSpeed, totalSpeed)
if HandleType[widget] == "unit" then
local damage = ALICE_FindField(gizmo.onUnitDamage, widget)
if type(damage) == "function" then
UnitDamageTarget(gizmo.source, widget, damage(gizmo, widget, perpendicularSpeed, parallelSpeed, totalSpeed), false, false, gizmo.onUnitAttackType or ATTACK_TYPE_NORMAL, gizmo.onUnitDamageType or DAMAGE_TYPE_MAGIC, WEAPON_TYPE_WHOKNOWS)
else
UnitDamageTarget(gizmo.source, widget, damage, false, false, gizmo.onUnitAttackType or ATTACK_TYPE_NORMAL, gizmo.onUnitDamageType or DAMAGE_TYPE_MAGIC, WEAPON_TYPE_WHOKNOWS)
end
elseif HandleType[widget] == "destructable" then
local damage = ALICE_FindField(gizmo.onDestructableDamage, widget)
if type(damage) == "function" then
SetDestructableLife(widget, GetDestructableLife(widget) - damage(gizmo, widget, perpendicularSpeed, parallelSpeed, totalSpeed))
else
SetDestructableLife(widget, GetDestructableLife(widget) - damage)
end
else
local damage = ALICE_FindField(gizmo.onItemDamage, widget)
if type(damage) == "function" then
SetWidgetLife(widget, GetWidgetLife(widget) - damage(gizmo, widget, perpendicularSpeed, parallelSpeed, totalSpeed))
else
SetWidgetLife(widget, GetWidgetLife(widget) - damage)
end
end
end
local function Backtrack(gizmo, vx, vy, vz, collisionX, collisionY, collisionZ)
vz = vz or 0
if vx == nil or (vx == 0 and vy == 0 and vz == 0) then
return
end
local factor = gizmo.collisionRadius/sqrt(vx*vx + vy*vy + vz*vz)
gizmo.x = collisionX - vx*factor
gizmo.y = collisionY - vy*factor
gizmo.z = collisionZ - vz*factor
BlzSetSpecialEffectPosition(gizmo.visual, gizmo.x, gizmo.y, gizmo.z)
end
--===========================================================================================================================================================
--Gizmo-Gizmo Collisions
--==========================================================================================================================================================
---@param A table
---@param B table
local function GetGizmoCollisionPoint3D(A, B, ax, ay, az, bx, by, bz)
local collisionDist = A.collisionRadius + B.collisionRadius
local collisionX = (ax*B.collisionRadius + bx*A.collisionRadius)/collisionDist
local collisionY = (ay*B.collisionRadius + by*A.collisionRadius)/collisionDist
local collisionZ = (az*B.collisionRadius + bz*A.collisionRadius)/collisionDist
return collisionX, collisionY, collisionZ, collisionDist
end
local function GizmoCollisionMath3D(A, B)
local xa, ya, za, xb, yb, zb = ALICE_PairGetCoordinates3D()
local dx, dy, dz = xa - xb, ya - yb, za - zb
local vxa, vya, vza = CAT_GetObjectVelocity3D(A)
local vxb, vyb, vzb = CAT_GetObjectVelocity3D(B)
local dvx, dvy, dvz = vxa - vxb, vya - vyb, vza - vzb
local dist = sqrt(dx*dx + dy*dy + dz*dz)
local perpendicularSpeed = -(dx*dvx + dy*dvy + dz*dvz)/dist
local totalSpeed = sqrt(dvx*dvx + dvy*dvy + dvz*dvz)
local parallelSpeed = sqrt(totalSpeed^2 - perpendicularSpeed^2)
local massA = CAT_GetObjectMass(A)
local massB = CAT_GetObjectMass(B)
local invMassSum = 1/(massA + massB)
local centerOfMassVx, centerOfMassVy, centerOfMassVz
if massA == INF then
if massB == INF then
centerOfMassVx = (vxa*massA + vxb*massB)*invMassSum
centerOfMassVy = (vya*massA + vyb*massB)*invMassSum
centerOfMassVz = (vza*massA + vzb*massB)*invMassSum
else
centerOfMassVx = vxa
centerOfMassVy = vya
centerOfMassVz = vza
end
elseif massB == INF then
centerOfMassVx = vxb
centerOfMassVy = vyb
centerOfMassVz = vzb
elseif massA == 0 and massB == 0 then
centerOfMassVx = (vxa + vxb)/2
centerOfMassVy = (vya + vyb)/2
centerOfMassVz = (vza + vzb)/2
else
centerOfMassVx = (vxa*massA + vxb*massB)*invMassSum
centerOfMassVy = (vya*massA + vyb*massB)*invMassSum
centerOfMassVz = (vza*massA + vzb*massB)*invMassSum
end
return perpendicularSpeed >= 0, xa, ya, za, xb, yb, zb, dist,
vxa, vya, vza, vxb, vyb, vzb,
dx, dy, dz, dvx, dvy, dvz,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy, centerOfMassVz
end
local function GizmoRecoilAndDisplace3D(object, x, y, z, recoilX, recoilY, recoilZ)
if object.anchor then
if type(object.anchor) == "table" then
object.anchor.x,object.anchor.y, object.anchor.z = x, y, z
object.anchor.vx, object.anchor.vy, object.anchor.vz = object.anchor.vx + recoilX, object.anchor.vy + recoilY, object.anchor.vz + recoilZ
else
SetUnitX(object.anchor, x)
SetUnitY(object.anchor, y)
CAT_Knockback(object.anchor, recoilX, recoilY, recoilZ)
end
else
object.x,object.y, object.z = x, y, z
object.vx, object.vy, object.vz = object.vx + recoilX, object.vy + recoilY, object.vz + recoilZ
end
end
local function GizmoRecoil3D(object, recoilX, recoilY, recoilZ)
if object.anchor then
if type(object.anchor) == "table" then
object.anchor.vx, object.anchor.vy, object.anchor.vz = object.anchor.vx + recoilX, object.anchor.vy + recoilY, object.anchor.vz + recoilZ
else
CAT_Knockback(object.anchor, recoilX, recoilY, recoilZ)
end
else
object.vx, object.vy, object.vz = object.vx + recoilX, object.vy + recoilY, object.vz + recoilZ
end
end
local function GetMassRatio(massA, massB)
--massA >>> massB -> 1
--massB >>> massA -> 0
if massA == 0 and massB == 0 then
return 0.5
elseif massA == INF then
if massB == INF then
return 0.5
else
return 1
end
else
return massA/(massA + massB)
end
end
-------------
--Callbacks
-------------
function CAT_GizmoBounce3D(A, B)
local validCollision, xa, ya, za, xb, yb, zb, dist,
vxa, vya, vza, vxb, vyb, vzb,
dx, dy, dz, dvx, dvy, dvz,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy, centerOfMassVz = GizmoCollisionMath3D(A, B)
if not validCollision then
return
end
local elasticity = sqrt((A.elasticity or 1)*(B.elasticity or 1))
local e = (1 + elasticity)
local Aunmoved
local Bunmoved
--Avoid unpausing resting gizmo with only minor bounce.
if A.isResting and perpendicularSpeed*e/2*B.mass/A.mass < A.friction*STATIC_FRICTION_FACTOR*INTERVAL then
Aunmoved = true
end
if B.isResting and perpendicularSpeed*e/2*A.mass/B.mass < B.friction*STATIC_FRICTION_FACTOR*INTERVAL then
Bunmoved = true
end
local nx, ny, nz = dx/dist, dy/dist, dz/dist
local Advx = vxa - centerOfMassVx
local Advy = vya - centerOfMassVy
local Advz = vza - centerOfMassVz
local Bdvx = vxb - centerOfMassVx
local Bdvy = vyb - centerOfMassVy
local Bdvz = vzb - centerOfMassVz
--Householder transformation.
local H11 = 1 - e*nx^2
local H12 = -e*nx*ny
local H13 = -e*nx*nz
local H21 = H12
local H22 = 1 - e*ny^2
local H23 = -e*ny*nz
local H31 = H13
local H32 = H23
local H33 = 1 - e*nz^2
local collisionX, collisionY, collisionZ, collisionDist = GetGizmoCollisionPoint3D(A, B, xa, ya, za, xb, yb, zb)
local massRatio
if Aunmoved then
massRatio = 1
elseif Bunmoved then
massRatio = 0
else
massRatio = GetMassRatio(massA, massB)
end
local xNew, yNew, zNew, recoilX, recoilY, recoilZ
local displacement = collisionDist - dist
if massRatio < 1 then
xNew = xa + 1.001*dx/dist*displacement*(1 - massRatio)
yNew = ya + 1.001*dy/dist*displacement*(1 - massRatio)
zNew = za + 1.001*dz/dist*displacement*(1 - massRatio)
if A.isAirborne == false and GetTerrainZ(xNew,yNew) - zNew > 64 then --Object is against a cliff and can't be displaced.
massRatio = 1
else
recoilX = H11*Advx + H12*Advy + H13*Advz + centerOfMassVx - vxa
recoilY = H21*Advx + H22*Advy + H23*Advz + centerOfMassVy - vya
recoilZ = H31*Advx + H32*Advy + H33*Advz + centerOfMassVz - vza
GizmoRecoilAndDisplace3D(A, xNew, yNew, zNew, recoilX, recoilY, recoilZ)
end
else
A.vx, A.vy, A.vz = 0, 0, 0
end
if massRatio > 0 then
xNew = xb - 1.001*dx/dist*displacement*massRatio
yNew = yb - 1.001*dy/dist*displacement*massRatio
zNew = zb - 1.001*dz/dist*displacement*massRatio
if B.isAirborne ~= false or GetTerrainZ(xNew,yNew) - zNew < 64 then --Object is against a cliff and can't be displaced.
recoilX = H11*Bdvx + H12*Bdvy + H13*Bdvz + centerOfMassVx - vxb
recoilY = H21*Bdvx + H22*Bdvy + H23*Bdvz + centerOfMassVy - vyb
recoilZ = H31*Bdvx + H32*Bdvy + H33*Bdvz + centerOfMassVz - vzb
GizmoRecoilAndDisplace3D(B, xNew, yNew, zNew, recoilX, recoilY, recoilZ)
end
else
B.vx, B.vy, B.vz = 0, 0, 0
end
local callback = ALICE_FindField(A.onGizmoCallback, B)
if callback then
callback(A, B, collisionX, collisionY, collisionZ, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy, centerOfMassVz)
end
end
function CAT_GizmoImpact3D(A, B)
local validCollision, xa, ya, za, xb, yb, zb, dist,
vxa, vya, vza, vxb, vyb, vzb,
dx, dy, dz, dvx, dvy, dvz,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy, centerOfMassVz = GizmoCollisionMath3D(A, B)
local collisionX, collisionY, collisionZ, collisionDist = GetGizmoCollisionPoint3D(A, B, xa, ya, za, xb, yb, zb)
if massA > 0 then
local unmoved
--Avoid unpausing resting gizmo with only minor bounce.
if B.isResting and perpendicularSpeed/2*A.mass/B.mass < B.friction*STATIC_FRICTION_FACTOR*INTERVAL or (massB == INF and massA == INF) then
unmoved = true
end
if not unmoved then
local recoilX, recoilY, recoilZ
local massRatio = GetMassRatio(massA, massB)
if massRatio > 0 then
recoilX = dvx*massRatio
recoilY = dvy*massRatio
recoilZ = dvz*massRatio
GizmoRecoil3D(B, recoilX, recoilY, recoilZ)
end
end
end
local callback = ALICE_FindField(A.onGizmoCallback, B)
if callback then
callback(A, B, collisionX, collisionY, collisionZ, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy, centerOfMassVz)
end
Backtrack(A, vxa, vya, vza, collisionX, collisionY, collisionZ)
ALICE_Kill(A)
end
function CAT_GizmoDevour3D(A, B)
local validCollision, xa, ya, za, xb, yb, zb, dist,
vxa, vya, vza, vxb, vyb, vzb,
dx, dy, dz, dvx, dvy, dvz,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy, centerOfMassVz = GizmoCollisionMath3D(A, B)
local collisionX, collisionY, collisionZ, collisionDist = GetGizmoCollisionPoint3D(A, B, xa, ya, za, xb, yb, zb)
if massA > 0 then
local unmoved
--Avoid unpausing resting gizmo with only minor bounce.
if A.isResting and perpendicularSpeed/2*B.mass/A.mass < A.friction*STATIC_FRICTION_FACTOR*INTERVAL or (massA == INF and massB == INF) then
unmoved = true
end
if not unmoved then
local recoilX, recoilY, recoilZ
local massRatio = GetMassRatio(massA, massB)
if massRatio > 0 then
recoilX = -dvx*(1 - massRatio)
recoilY = -dvy*(1 - massRatio)
recoilZ = -dvz*(1 - massRatio)
GizmoRecoil3D(A, recoilX, recoilY, recoilZ)
end
end
end
local callback = ALICE_FindField(A.onGizmoCallback, B)
if callback then
callback(A, B, collisionX, collisionY, collisionZ, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy, centerOfMassVz)
end
Backtrack(B, vxb, vyb, vzb, collisionX, collisionY, collisionZ)
ALICE_Kill(B)
end
function CAT_GizmoAnnihilate3D(A, B)
local validCollision, xa, ya, za, xb, yb, zb, dist,
vxa, vya, vza, vxb, vyb, vzb,
dx, dy, dz, dvx, dvy, dvz,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy, centerOfMassVz = GizmoCollisionMath3D(A, B)
local collisionX, collisionY, collisionZ, collisionDist = GetGizmoCollisionPoint3D(A, B, xa, ya, za, xb, yb, zb)
local callback = ALICE_FindField(A.onGizmoCallback, B)
if callback then
callback(A, B, collisionX, collisionY, collisionZ, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy, centerOfMassVz)
end
Backtrack(A, vxa, vya, vza, collisionX, collisionY, collisionZ)
ALICE_Kill(A)
Backtrack(B, vxb, vyb, vzb, collisionX, collisionY, collisionZ)
ALICE_Kill(B)
end
function CAT_GizmoPassThrough3D(A, B)
local callback = ALICE_FindField(A.onGizmoCallback, B)
if callback then
local validCollision, xa, ya, za, xb, yb, zb, dist,
vxa, vya, vza, vxb, vyb, vzb,
dx, dy, dz, dvx, dvy, dvz,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy, centerOfMassVz = GizmoCollisionMath3D(A, B)
local collisionX, collisionY, collisionZ, collisionDist = GetGizmoCollisionPoint3D(A, B, xa, ya, za, xb, yb, zb)
callback(A, B, collisionX, collisionY, collisionZ, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy, centerOfMassVz)
end
ALICE_PairDisable()
end
--------------------
--Collision Checks
--------------------
function CAT_GizmoCylindricalCollisionCheck3D(gizmo, cylinder)
local dx, dy, dz, dist
if gizmo.anchor or cylinder.anchor then
local xa, ya, za, xb, yb, zb = ALICE_PairGetCoordinates3D()
dx, dy, dz = xb - xa, yb - ya, zb - za
else
dx, dy, dz = cylinder.x - gizmo.x, cylinder.y - gizmo.y, cylinder.z - gizmo.z
end
local horiDist = sqrt(dx*dx + dy*dy)
local collisionRange = gizmo.collisionRadius + cylinder.collisionRadius
local maxdz = cylinder.collisionHeight/2 + gizmo.collisionRadius
if horiDist < collisionRange and dz < maxdz and dz > -maxdz and not (gizmo.friendlyFire == false and ALICE_PairIsFriend()) then
local dtop = cylinder.collisionHeight/2 - dz
if dtop < cylinder.collisionRadius then
dist = sqrt(horiDist*horiDist + (dtop - cylinder.collisionRadius)^2)
else
dist = horiDist
end
if dist < collisionRange then
local callback = ALICE_FindField(gizmo.onGizmoCollision, cylinder)
if callback then
callback(gizmo, cylinder)
else
if gizmo.onUnitDamage then
DamageWidget(gizmo, cylinder)
end
ALICE_Kill(gizmo)
end
end
else
dist = sqrt(horiDist*horiDist + dz*dz)
end
return (horiDist - collisionRange)/((gizmo.maxSpeed or DEFAULT_GIZMO_MAX_SPEED) + (cylinder.maxSpeed or DEFAULT_GIZMO_MAX_SPEED))
end
function CAT_GizmoCollisionCheck3D(A, B)
local dx, dy, dz, dist
if A.anchor or B.anchor then
dist = ALICE_PairGetDistance3D()
else
dx = A.x - B.x
dy = A.y - B.y
dz = A.z - B.z
dist = sqrt(dx*dx + dy*dy + dz*dz)
end
local collisionRange = A.collisionRadius + B.collisionRadius
if dist < collisionRange and not (A.friendlyFire == false and ALICE_PairIsFriend()) then
local callback = ALICE_FindField(A.onGizmoCollision, B)
if callback then
callback(A, B)
end
A.hasCollided = true
B.hasCollided = true
end
if A.isResting and B.isResting then
ALICE_PairPause()
end
return (dist - collisionRange)/((A.maxSpeed or DEFAULT_GIZMO_MAX_SPEED) + (B.maxSpeed or DEFAULT_GIZMO_MAX_SPEED))
end
--===========================================================================================================================================================
--Gizmo-Widget Collisions
--==========================================================================================================================================================
local function WidgetCollisionMath3D(gizmo, widget)
local data = ALICE_PairLoadData()
local xa, ya, za, xb, yb, zb = ALICE_PairGetCoordinates3D()
local dx, dy, dz = xa - xb, ya - yb, za - zb
local vxa, vya, vza = CAT_GetObjectVelocity3D(gizmo)
local vxb, vyb, vzb = CAT_GetObjectVelocity3D(widget)
local dvx, dvy, dvz = vxa - vxb, vya - vyb, vza - vzb
local dist = sqrt(dx*dx + dy*dy + dz*dz)
local nx, ny, nz
local collisionX, collisionY, collisionZ
local overlap
local phi = atan2(dy, dx)
local theta
local dtop = data.height/2 - dz
local dbottom = -dz - data.height/2
if dtop < data.radius then
theta = atan2(data.radius - dtop, sqrt(dx*dx + dy*dy))
local cosTheta = cos(theta)
nx = cos(phi)*cosTheta
ny = sin(phi)*cosTheta
nz = sin(theta)
collisionZ = zb + data.height/2 - (1 - nz)*data.radius
overlap = (data.radius + gizmo.collisionRadius) - sqrt(dx*dx + dy*dy + (data.radius - dtop)^2)
elseif HandleType[widget] == "unit" and GetUnitFlyHeight(widget) > 0 and dbottom < data.radius then
theta = atan2(dbottom - data.radius, sqrt(dx*dx + dy*dy))
local cosTheta = cos(theta)
nx = cos(phi)*cosTheta
ny = sin(phi)*cosTheta
nz = sin(theta)
collisionZ = zb - data.height/2 + (1 + nz)*data.radius
overlap = (data.radius + gizmo.collisionRadius) - sqrt(dx*dx + dy*dy + (dbottom - data.radius)^2)
else
local horiDist = sqrt(dx*dx + dy*dy)
nx = dx/horiDist
ny = dy/horiDist
nz = 0
collisionZ = za
overlap = data.radius + gizmo.collisionRadius - horiDist
end
local perpendicularSpeed = -(nx*dvx + ny*dvy + nz*dvz)
collisionX = xb + nx*data.radius
collisionY = yb + ny*data.radius
local totalSpeed = sqrt(dvx*dvx + dvy*dvy + dvz*dvz)
local parallelSpeed = sqrt(totalSpeed^2 - perpendicularSpeed^2)
local massA = CAT_GetObjectMass(gizmo)
local massB = CAT_GetObjectMass(widget)
local massSum = massA + massB
local centerOfMassVx, centerOfMassVy, centerOfMassVz
if massA == INF then
if massB == INF then
centerOfMassVx = (vxa*massA + vxb*massB)/massSum
centerOfMassVy = (vya*massA + vyb*massB)/massSum
centerOfMassVz = (vza*massA + vzb*massB)/massSum
else
centerOfMassVx = vxa
centerOfMassVy = vya
centerOfMassVz = vza
end
elseif massB == INF then
centerOfMassVx = vxb
centerOfMassVy = vyb
centerOfMassVz = vzb
else
centerOfMassVx = (vxa*massA + vxb*massB)/massSum
centerOfMassVy = (vya*massA + vyb*massB)/massSum
centerOfMassVz = (vza*massA + vzb*massB)/massSum
end
return perpendicularSpeed >= 0, xa, ya, za, xb, yb, zb, dist,
vxa, vya, vza, vxb, vyb, vzb,
dx, dy, dz, dvx, dvy, dvz,
nx, ny, nz,
collisionX, collisionY, collisionZ, overlap,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy, centerOfMassVz
end
-------------
--Callbacks
-------------
local function WidgetBounce3D(gizmo, widget)
local isValidCollision, xa, ya, za, xb, yb, zb, dist,
vxa, vya, vza, vxb, vyb, vzb,
dx, dy, dz, dvx, dvy, dvz,
nx, ny, nz,
collisionX, collisionY, collisionZ, overlap,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy, centerOfMassVz = WidgetCollisionMath3D(gizmo, widget)
if not isValidCollision then
return
end
local elasticity
local callbackName
local damageName
local isUnit = false
if HandleType[widget] == "unit" then
isUnit = true
elasticity = sqrt((gizmo.elasticity or 1)*(WIDGET_TYPE_ELASTICITY[GetUnitTypeId(widget)] or DEFAULT_UNIT_ELASTICITY))
callbackName = "onUnitCallback"
damageName = "onUnitDamage"
elseif HandleType[widget] == "destructable" then
elasticity = sqrt((gizmo.elasticity or 1)*(WIDGET_TYPE_ELASTICITY[GetDestructableTypeId(widget)] or DEFAULT_DESTRUCTABLE_ELASTICITY))
callbackName = "onDestructableCallback"
damageName = "onDestructableDamage"
else
elasticity = sqrt((gizmo.elasticity or 1)*(WIDGET_TYPE_ELASTICITY[GetItemTypeId(widget)] or DEFAULT_ITEM_ELASTICITY))
callbackName = "onItemCallback"
damageName = "onItemDamage"
end
local e = (1 + elasticity)
local Advx = vxa - centerOfMassVx
local Advy = vya - centerOfMassVy
local Advz = vza - centerOfMassVz
local Bdvx = vxb - centerOfMassVx
local Bdvy = vyb - centerOfMassVy
local Bdvz = vzb - centerOfMassVz
--Householder transformation.
local H11 = 1 - e*nx^2
local H12 = -e*nx*ny
local H13 = -e*nx*nz
local H21 = H12
local H22 = 1 - e*ny^2
local H23 = -e*ny*nz
local H31 = H13
local H32 = H23
local H33 = 1 - e*nz^2
local massRatio = GetMassRatio(massA, massB)
local xNew, yNew, zNew, recoilX, recoilY, recoilZ
if massRatio < 1 then
xNew = xa + 1.001*nx*overlap*(1 - massRatio)
yNew = ya + 1.001*ny*overlap*(1 - massRatio)
zNew = za + 1.001*nz*overlap*(1 - massRatio)
recoilX = H11*Advx + H12*Advy + H13*Advz + centerOfMassVx - vxa
recoilY = H21*Advx + H22*Advy + H23*Advz + centerOfMassVy - vya
recoilZ = H31*Advx + H32*Advy + H33*Advz + centerOfMassVz - vza
GizmoRecoilAndDisplace3D(gizmo, xNew, yNew, zNew, recoilX, recoilY, recoilZ)
end
if massRatio > 0 then
xNew = xb - 1.001*nx*overlap*massRatio
yNew = yb - 1.001*ny*overlap*massRatio
zNew = zb - 1.001*nz*overlap*massRatio
recoilX = H11*Bdvx + H12*Bdvy + H13*Bdvz + centerOfMassVx - vxb
recoilY = H21*Bdvx + H22*Bdvy + H23*Bdvz + centerOfMassVy - vyb
recoilZ = H31*Bdvx + H32*Bdvy + H33*Bdvz + centerOfMassVz - vzb
if isUnit then
SetUnitX(widget, xNew)
SetUnitY(widget, yNew)
CAT_Knockback(widget, recoilX, recoilY, recoilZ)
end
end
if gizmo[damageName] then
DamageWidget(gizmo, widget, perpendicularSpeed, parallelSpeed, totalSpeed)
end
local callback = ALICE_FindField(gizmo[callbackName], widget)
if callback then
callback(gizmo, widget, collisionX, collisionY, collisionZ, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy, centerOfMassVz)
end
end
local function WidgetImpact3D(gizmo, widget)
local isValidCollision, xa, ya, za, xb, yb, zb, dist,
vxa, vya, vza, vxb, vyb, vzb,
dx, dy, dz, dvx, dvy, dvz,
nx, ny, nz,
collisionX, collisionY, collisionZ, overlap,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy, centerOfMassVz = WidgetCollisionMath3D(gizmo, widget)
if massA > 0 then
local recoilX, recoilY, recoilZ
local massRatio = GetMassRatio(massA, massB)
if massRatio > 0 then
recoilX = dvx*massRatio
recoilY = dvy*massRatio
recoilZ = dvz*massRatio
if HandleType[widget] == "unit" then
CAT_Knockback(widget, recoilX, recoilY, recoilZ)
end
end
end
local callbackName
local damageName
if HandleType[widget] == "unit" then
callbackName = "onUnitCallback"
damageName = "onUnitDamage"
elseif HandleType[widget] == "destructable" then
callbackName = "onDestructableCallback"
damageName = "onDestructableDamage"
else
callbackName = "onItemCallback"
damageName = "onItemDamage"
end
if gizmo[damageName] then
DamageWidget(gizmo, widget, perpendicularSpeed, parallelSpeed, totalSpeed)
end
local callback = ALICE_FindField(gizmo[callbackName], widget)
if callback then
callback(gizmo, widget, collisionX, collisionY, collisionZ, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy, centerOfMassVz)
end
Backtrack(gizmo, vxa, vya, vza, collisionX, collisionY, collisionZ)
ALICE_Kill(gizmo)
end
local function WidgetDevour3D(gizmo, widget)
local isValidCollision, xa, ya, za, xb, yb, zb, dist,
vxa, vya, vza, vxb, vyb, vzb,
dx, dy, dz, dvx, dvy, dvz,
nx, ny, nz,
collisionX, collisionY, collisionZ, overlap,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy, centerOfMassVz = WidgetCollisionMath3D(gizmo, widget)
if massA > 0 then
local recoilX, recoilY, recoilZ
local massRatio = GetMassRatio(massA, massB)
if massRatio > 0 then
recoilX = -dvx*(1 - massRatio)
recoilY = -dvy*(1 - massRatio)
recoilZ = -dvz*(1 - massRatio)
GizmoRecoil3D(gizmo, recoilX, recoilY, recoilZ)
end
end
local callbackName
local damageName
if HandleType[widget] == "unit" then
callbackName = "onUnitCallback"
damageName = "onUnitDamage"
elseif HandleType[widget] == "destructable" then
callbackName = "onDestructableCallback"
damageName = "onDestructableDamage"
else
callbackName = "onItemCallback"
damageName = "onItemDamage"
end
if gizmo[damageName] then
DamageWidget(gizmo, widget, perpendicularSpeed, parallelSpeed, totalSpeed)
end
local callback = ALICE_FindField(gizmo[callbackName], widget)
if callback then
callback(gizmo, widget, collisionX, collisionY, collisionZ, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy, centerOfMassVz)
end
ALICE_Kill(widget)
end
local function WidgetAnnihilate3D(gizmo, widget)
local isValidCollision, xa, ya, za, xb, yb, zb, dist,
vxa, vya, vza, vxb, vyb, vzb,
dx, dy, dz, dvx, dvy, dvz,
nx, ny, nz,
collisionX, collisionY, collisionZ, overlap,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy, centerOfMassVz = WidgetCollisionMath3D(gizmo, widget)
local callbackName
if HandleType[widget] == "unit" then
callbackName = "onUnitCallback"
elseif HandleType[widget] == "destructable" then
callbackName = "onDestructableCallback"
else
callbackName = "onItemCallback"
end
local callback = ALICE_FindField(gizmo[callbackName], widget)
if callback then
callback(gizmo, widget, collisionX, collisionY, collisionZ, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy, centerOfMassVz)
end
Backtrack(gizmo, vxa, vya, vza, collisionX, collisionY, collisionZ)
ALICE_Kill(gizmo)
ALICE_Kill(widget)
end
local function WidgetPassThrough3D(gizmo, widget)
local isValidCollision, xa, ya, za, xb, yb, zb, dist,
vxa, vya, vza, vxb, vyb, vzb,
dx, dy, dz, dvx, dvy, dvz,
nx, ny, nz,
collisionX, collisionY, collisionZ, overlap,
massA, massB,
perpendicularSpeed, totalSpeed, parallelSpeed,
centerOfMassVx, centerOfMassVy, centerOfMassVz = WidgetCollisionMath3D(gizmo, widget)
local callbackName
local damageName
if HandleType[widget] == "unit" then
callbackName = "onUnitCallback"
damageName = "onUnitDamage"
elseif HandleType[widget] == "destructable" then
callbackName = "onDestructableCallback"
damageName = "onDestructableDamage"
else
callbackName = "onItemCallback"
damageName = "onItemDamage"
end
if gizmo[damageName] then
DamageWidget(gizmo, widget, perpendicularSpeed, parallelSpeed, totalSpeed)
end
local callback = ALICE_FindField(gizmo[callbackName], widget)
if callback then
callback(gizmo, widget, collisionX, collisionY, collisionZ, perpendicularSpeed, parallelSpeed, totalSpeed, centerOfMassVx, centerOfMassVy, centerOfMassVz)
end
ALICE_PairDisable()
end
CAT_UnitBounce3D = WidgetBounce3D
CAT_UnitImpact3D = WidgetImpact3D
CAT_UnitDevour3D = WidgetDevour3D
CAT_UnitAnnihilate3D = WidgetAnnihilate3D
CAT_UnitPassThrough3D = WidgetPassThrough3D
CAT_DestructableBounce3D = WidgetBounce3D
CAT_DestructableImpact3D = WidgetImpact3D
CAT_DestructableDevour3D = WidgetDevour3D
CAT_DestructableAnnihilate3D = WidgetAnnihilate3D
CAT_DestructablePassThrough3D = WidgetPassThrough3D
CAT_ItemBounce3D = WidgetBounce3D
CAT_ItemImpact3D = WidgetImpact3D
CAT_ItemDevour3D = WidgetDevour3D
CAT_ItemAnnihilate3D = WidgetAnnihilate3D
CAT_ItemPassThrough3D = WidgetPassThrough3D
--===========================================================================================================================================================
--Gizmo-Unit Collisions
--==========================================================================================================================================================
--------------------
--Collision Checks
--------------------
local function InitUnitCollisionCheck3D(gizmo, unit)
local data = ALICE_PairLoadData()
local id = GetUnitTypeId(unit)
local collisionSize = BlzGetUnitCollisionSize(unit)
data.radius = WIDGET_TYPE_COLLISION_RADIUS[id] or collisionSize
data.height = WIDGET_TYPE_HEIGHT[id] or DEFAULT_UNIT_HEIGHT_FACTOR*collisionSize
data.collisionRange = data.radius + gizmo.collisionRadius
data.maxdz = data.height/2 + gizmo.collisionRadius
gizmo.maxSpeed = gizmo.maxSpeed or DEFAULT_GIZMO_MAX_SPEED
end
function CAT_UnitCollisionCheck3D(gizmo, unit)
local data = ALICE_PairLoadData()
local dx, dy, dz
if gizmo.x then
local x, y, z = ALICE_GetCoordinates3D(unit)
dx, dy, dz = x - gizmo.x, y - gizmo.y, z - gizmo.z
else
local xa, ya, za, xb, yb, zb = ALICE_PairGetCoordinates3D()
dx, dy, dz = xb - xa, yb - ya, zb - za
end
local horiDist = sqrt(dx*dx + dy*dy)
local dist
if horiDist < data.collisionRange and dz < data.maxdz and dz > -data.maxdz and not (gizmo.friendlyFire == false and ALICE_PairIsFriend()) and (gizmo.onlyTarget == nil or unit == gizmo.target) then
local dtop = data.height/2 - dz
local dbottom = data.height/2 + dz
if dtop < data.radius then
dist = sqrt(horiDist*horiDist + (dtop - data.radius)^2)
elseif dbottom < data.radius then
if GetUnitFlyHeight(unit) > 0 then
dist = sqrt(horiDist*horiDist + (dbottom - data.radius)^2)
else
dist = horiDist
end
else
dist = horiDist
end
if dist < data.collisionRange then
local callback = ALICE_FindField(gizmo.onUnitCollision, unit)
if callback then
callback(gizmo, unit)
else
if gizmo.onUnitDamage then
DamageWidget(gizmo, unit)
end
ALICE_Kill(gizmo)
end
end
else
dist = sqrt(horiDist*horiDist + dz*dz)
end
return (horiDist - data.collisionRange)/(gizmo.maxSpeed + UNIT_MAX_SPEED)
end
--===========================================================================================================================================================
--Gizmo-Destructable Collisions
--==========================================================================================================================================================
--------------------
--Collision Checks
--------------------
local function InitDestructableCollisionCheck3D(gizmo, destructable)
local data = ALICE_PairLoadData()
local id = GetDestructableTypeId(destructable)
data.radius = WIDGET_TYPE_COLLISION_RADIUS[id] or DEFAULT_DESTRUCTABLE_COLLISION_RADIUS
data.height = WIDGET_TYPE_HEIGHT[id] or DEFAULT_DESTRUCTABLE_HEIGHT
data.collisionRange = data.radius + gizmo.collisionRadius
data.maxdz = data.height/2 + gizmo.collisionRadius
gizmo.maxSpeed = gizmo.maxSpeed or DEFAULT_GIZMO_MAX_SPEED
data.xDest, data.yDest, data.zDest = ALICE_GetCoordinates3D(destructable)
end
function CAT_DestructableCollisionCheck3D(gizmo, destructable)
local data = ALICE_PairLoadData()
local dx, dy, dz
if gizmo.x then
dx, dy, dz = data.xDest - gizmo.x, data.yDest - gizmo.y, data.zDest - gizmo.z
else
local x, y, z = ALICE_GetCoordinates3D(gizmo)
dx, dy, dz = data.xDest - x, data.yDest - y, data.zDest - z
end
local horiDist = sqrt(dx*dx + dy*dy)
local dist
if horiDist < data.collisionRange and dz < data.maxdz and dz > -data.maxdz then
local dtop = data.height/2 - dz
if dtop < data.radius then
dist = sqrt(horiDist*horiDist + (dtop - data.radius)^2)
else
dist = horiDist
end
if dist < data.collisionRange then
local callback = ALICE_FindField(gizmo.onDestructableCollision, destructable)
if callback then
callback(gizmo, destructable)
else
if gizmo.onDestructableDamage then
DamageWidget(gizmo, destructable)
end
ALICE_Kill(gizmo)
end
end
else
dist = sqrt(horiDist*horiDist + dz*dz)
end
if gizmo.isResting then
ALICE_PairPause()
end
return (horiDist - data.collisionRange)/gizmo.maxSpeed
end
--===========================================================================================================================================================
--Gizmo-Item Collisions
--==========================================================================================================================================================
--------------------
--Collision Checks
--------------------
local function InitItemCollisionCheck3D(gizmo, item)
local data = ALICE_PairLoadData()
local id = GetItemTypeId(item)
data.radius = WIDGET_TYPE_COLLISION_RADIUS[id] or DEFAULT_ITEM_COLLISION_RADIUS
data.height = WIDGET_TYPE_HEIGHT[id] or DEFAULT_ITEM_HEIGHT
data.collisionRange = data.radius + gizmo.collisionRadius
data.maxdz = data.height/2 + gizmo.collisionRadius
gizmo.maxSpeed = gizmo.maxSpeed or DEFAULT_GIZMO_MAX_SPEED
end
function CAT_ItemCollisionCheck3D(gizmo, item)
local data = ALICE_PairLoadData()
local xa, ya, za, xb, yb, zb = ALICE_PairGetCoordinates3D()
local dx, dy, dz = xb - xa, yb - ya, zb - za
local horiDist = sqrt(dx*dx + dy*dy)
local dist
if horiDist < data.collisionRange and dz < data.maxdz and dz > -data.maxdz then
local dtop = data.height/2 - dz
if dtop < data.radius then
dist = sqrt(horiDist*horiDist + (dtop - data.radius)^2)
else
dist = horiDist
end
if dist < data.collisionRange then
local callback = ALICE_FindField(gizmo.onItemCollision, item)
if callback then
callback(gizmo, item)
else
if gizmo.onItemDamage then
DamageWidget(gizmo, item)
end
ALICE_Kill(gizmo)
end
end
else
dist = sqrt(horiDist*horiDist + dz*dz)
end
if gizmo.isResting then
ALICE_PairPause()
end
return (horiDist - data.collisionRange)/gizmo.maxSpeed
end
--===========================================================================================================================================================
--Init
--==========================================================================================================================================================
local function InitCollisionsCAT()
Require "ALICE"
Require "CAT_Objects"
INTERVAL = ALICE_Config.MIN_INTERVAL
ALICE_FuncSetInit(CAT_UnitCollisionCheck3D, InitUnitCollisionCheck3D)
ALICE_FuncSetInit(CAT_DestructableCollisionCheck3D, InitDestructableCollisionCheck3D)
ALICE_FuncSetInit(CAT_ItemCollisionCheck3D, InitItemCollisionCheck3D)
ALICE_RecognizeFields(
"vx",
"vy",
"vz",
"friction",
"isResting",
"collisionRadius",
"onGizmoCollision",
"onUnitCollision",
"onDestructableCollision",
"onItemCollision",
"onGizmoCallback",
"onUnitCallback",
"onDestructableCallback",
"onItemCallback",
"onUnitDamage",
"onDestructableDamage",
"onItemDamage",
"source",
"onUnitAttackType",
"onUnitDamageType",
"collisionRadius",
"mass",
"elasticity",
"maxSpeed",
"friendlyFire",
"collisionHeight",
"target",
"onlyTarget"
)
ALICE_FuncRequireFields(CAT_GizmoCollisionCheck3D, true, true, "collisionRadius")
ALICE_FuncRequireFields(CAT_GizmoCylindricalCollisionCheck3D, true, true, "collisionRadius")
ALICE_FuncRequireFields(CAT_GizmoCylindricalCollisionCheck3D, false, true, "collisionHeight")
ALICE_FuncRequireFields(CAT_UnitCollisionCheck3D, true, false, "collisionRadius")
ALICE_FuncRequireFields(CAT_DestructableCollisionCheck3D, true, false, "collisionRadius")
ALICE_FuncRequireFields(CAT_ItemCollisionCheck3D, true, false, "collisionRadius")
local precomputedHeightMap = Require.optionally "PrecomputedHeightMap"
if precomputedHeightMap then
GetTerrainZ = _G.GetTerrainZ
else
moveableLoc = Location(0, 0)
GetTerrainZ = function(x, y)
MoveLocation(moveableLoc, x, y)
return GetLocationZ(moveableLoc)
end
end
end
OnInit.final("CAT_Collisions3D", InitCollisionsCAT)
end
if Debug then Debug.beginFile "CAT Ballistics" end
do
--[[
=============================================================================================================================================================
Complementary ALICE Template
by Antares
Requires:
ALICE https://www.hiveworkshop.com/threads/a-l-i-c-e-interaction-engine.353126/
Objects CAT
PrecomuptedHeightMap https://www.hiveworkshop.com/threads/precomputed-synchronized-terrain-height-map.353477/
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
=============================================================================================================================================================
B A L L I S T I C S
=============================================================================================================================================================
This template includes a function for realistic, ballistic and sliding movement for gizmos* as well as some helper functions for ballistic movement. To add
ballistic movement to a gizmo, add the CAT_MoveBallistic function to their self-interaction table (for an example, see gizmos CAT).
*Objects represented by a table with coordinate fields .x, .y, .z, velocity fields .vx, .vy, .vz, and a special effect .visual.
CAT_MoveBallistic requires the .collisionRadius field for ground-bound sliding movement. To become ground-bound, a gizmo requires CAT_TerrainCollisionCheck
to be added to its self-iteraction table, and CAT_TerrainBounce set for its .onTerrainCollision field (gizmos CAT).
A gizmo becomes ground-bound when it bounces off the surface with less than the MINIMUM_BOUNCE_VELOCITY (Objects CAT). While ground-bound, an object will slide
realistically across the surface with a friction determined by the .friction field. The value is interpreted as the deceleration experienced per second. It is
multiplied with TERRAIN_TYPE_FRICTION, which can also be set in the Objects CAT.
Once a ground-bound gizmo has come to rest, its friction increases by the STATIC_FRICTION_FACTOR (Objects CAT) and a greater force is required to displace it
again. The ballistic movement function writes values into the gizmo table to determine its current state. These values are used by other functions. The
.isResting field is used to detect if certain interactions can be paused to save computation resources. This means, that, even large numbers of resting gizmos
do not affect performance in a significant way.
This library, combined with the collisions library, is optimized towards allowing a large number of objects to sit idly on the map and not affect performance,
while waiting for another object to collide with them.
Sliding movement is currently bugged around cliffs.
-------------------------------------------------------------------------------------------------------------------------------------------------------------
Two helper functions for ballistic projectiles are included in this template.
CAT_GetBallisticLaunchSpeedFromVelocity takes a velocity and returns the x, y, and z-velocities that would cause a ballistic projectile launched with the
specified velocity from the launch coordinates to impact at the specified target coordinates. There are usually two solutions. The highArc flag specifies if
the function should search for the solution with the higher angle first. It is possible that there is no solution for a given velocity. In that case, the
function will return nil.
CAT_GetBallisticLaunchSpeedFromAngle takes an angle and returns the x, y, and z-velocities that would cause the proctile launched at that angle from the launch
coordinates to impact at the specified target coordinates. Unlike the from-velocity version, this function always has a solution as long as the vertical angle
between the launch and target coordinates is not greater than the specified launch angle. In that case, the function will return nil.
=============================================================================================================================================================
L I S T O F F U N C T I O N S
=============================================================================================================================================================
CAT_MoveBallistic
CAT_GetBallisticLaunchSpeedFromVelocity(xLaunch, yLaunch, zLaunch, xTarget, yTarget, zTarget, velocity, highArc) -> vx, vy, vz
CAT_GetBallisticLaunchSpeedFromAngle(xLaunch, yLaunch, zLaunch, xTarget, yTarget, zTarget, angle) -> vx, vy, vz
=============================================================================================================================================================
]]
local sqrt = math.sqrt
local atan2 = math.atan
local cos = math.cos
local sin = math.sin
local tan = math.tan
local abs = math.abs
local PI = bj_PI
local INTERVAL
local PAUSEABLE_FUNCTIONS = {
CAT_GizmoCollisionCheck3D,
CAT_UnitCollisionCheck3D,
CAT_DestructableCollisionCheck3D,
CAT_ItemCollisionCheck3D,
CAT_GizmoCollisionCheck2D,
CAT_UnitCollisionCheck2D,
CAT_DestructableCollisionCheck2D,
CAT_ItemCollisionCheck2D,
CAT_OrientRoll,
CAT_Orient3D,
CAT_Orient2D,
CAT_AnimateShadow,
CAT_MoveAttachedEffect,
CAT_OutOfBoundsCheck,
}
local function InitMoveBallistic(gizmo)
gizmo.visualZ = gizmo.visualZ or 0
gizmo.isAirborne = gizmo.z ~= nil
gizmo.vz = gizmo.vz or 0
gizmo.vzOld = gizmo.vz
gizmo.friction = gizmo.friction or 0
gizmo.theta = atan2(gizmo.vz, sqrt(gizmo.vx^2 + gizmo.vy^2))
if gizmo.launchOffset then
CAT_LaunchOffset(gizmo)
end
end
---@param gizmo table
function CAT_MoveBallistic(gizmo)
if gizmo.isResting and gizmo.vx == 0 and gizmo.vy == 0 and gizmo.vz == 0 then
return
elseif gizmo.isAirborne then
--Ballistic movement
gizmo.x = gizmo.x + gizmo.vx*INTERVAL
gizmo.y = gizmo.y + gizmo.vy*INTERVAL
gizmo.z = gizmo.z + gizmo.vz*INTERVAL - 0.5*GRAVITY*INTERVAL^2
gizmo.vz = gizmo.vz - GRAVITY*INTERVAL
gizmo.vzOld = gizmo.vz
BlzSetSpecialEffectPosition(gizmo.visual, gizmo.x, gizmo.y, gizmo.z + gizmo.visualZ)
if gizmo.isResting then
ALICE_Unpause(gizmo, PAUSEABLE_FUNCTIONS)
gizmo.isResting = false
end
else
--Check if object has received external force that could catapult it off the ground.
if gizmo.vz > gizmo.vzOld + MINIMUM_BOUNCE_VELOCITY or gizmo.vz < gizmo.vzOld - MINIMUM_BOUNCE_VELOCITY/gizmo.elasticity then
if gizmo.isResting then
ALICE_Unpause(gizmo, PAUSEABLE_FUNCTIONS)
gizmo.isResting = false
end
gizmo.isAirborne = true
gizmo.lastTerrainCollisionCheck = ALICE_TimeElapsed
ALICE_Unpause(gizmo, CAT_CheckTerrainCollision)
ALICE_SetStationary(gizmo, false)
gizmo.vzOld = gizmo.vz
CAT_MoveBallistic(gizmo)
return
end
--Ground movement
local vHorizontal = sqrt(gizmo.vx^2 + gizmo.vy^2)
if vHorizontal > 0 then
--Determine if object is too fast to remain in contact with downwards curved surface.
local freeFallCurvature = -GRAVITY/(vHorizontal*vHorizontal)
local deltaScanX = 2*gizmo.vx*INTERVAL
local deltaScanY = 2*gizmo.vy*INTERVAL
local deltaScanDist = sqrt(deltaScanX*deltaScanX + deltaScanY*deltaScanY)
local z1 = GetTerrainZ(gizmo.x - deltaScanX, gizmo.y - deltaScanY)
local z2 = GetTerrainZ(gizmo.x + deltaScanX, gizmo.y + deltaScanY)
local z = GetTerrainZ(gizmo.x, gizmo.y)
local curvature = (z2 + z1 - 2*z)*1/(128*deltaScanDist)
if freeFallCurvature > curvature then
gizmo.isAirborne = true
gizmo.lastTerrainCollisionCheck = ALICE_TimeElapsed
ALICE_Unpause(gizmo, CAT_CheckTerrainCollision)
gizmo.x = gizmo.x + gizmo.vx*INTERVAL
gizmo.y = gizmo.y + gizmo.vy*INTERVAL
gizmo.z = gizmo.z + gizmo.vz*INTERVAL
BlzSetSpecialEffectPosition(gizmo.visual, gizmo.x, gizmo.y, gizmo.z + gizmo.visualZ)
else
local frictionMultiplier = (freeFallCurvature - curvature)/freeFallCurvature --If the object is pressed against the surface due to its curvature, the friction increases.
local curvatureAngle
--Check if the curvature of the surface is so high that an object of its size would get reflected like it hit a wall.
if curvature > 0.0015 then --Don't run this calculation unless curvature is high enough (dz > ~50)
curvatureAngle = atan2(z2 - z, 32) - atan2(z - z1, 32) --Gradient angle difference between two neighboring tiles.
if MAX_SLIDING_CURVATURE_RADIUS*(PI/2 - curvatureAngle)/curvatureAngle < gizmo.collisionRadius then
local xCollision, yCollision, zCollision = gizmo.x, gizmo.y, gizmo.z
local invVTotal = 1/sqrt(gizmo.vx^2 + gizmo.vy^2 + gizmo.vz^2)
local i = 1
repeat
xCollision = xCollision + 10*gizmo.vx*invVTotal
yCollision = yCollision + 10*gizmo.vy*invVTotal
zCollision = zCollision + 10*gizmo.vz*invVTotal
i = i + 1
until zCollision < GetTerrainZ(xCollision, yCollision) or i > 50
if i <= 50 then
CAT_TerrainBounce(gizmo, xCollision, yCollision, zCollision)
ALICE_Unpause(gizmo, CAT_CheckTerrainCollision)
gizmo.isAirborne = true
gizmo.lastTerrainCollisionCheck = ALICE_TimeElapsed
return
end
end
end
local x, y = gizmo.x, gizmo.y
local xGrad, yGrad = x - gizmo.vx*INTERVAL, y - gizmo.vy*INTERVAL
--Get surface orientation. Must be one movement step behind actual position so that vz does not go crazy on cliffs.
local gradientX = (GetTerrainZ(xGrad + 1, yGrad) - GetTerrainZ(xGrad - 1, yGrad))*0.5
local gradientY = (GetTerrainZ(xGrad, yGrad + 1) - GetTerrainZ(xGrad, yGrad - 1))*0.5
local gradientSquared = gradientX*gradientX + gradientY*gradientY
local oldvx = gizmo.vx
local oldvy = gizmo.vy
local oldTheta = gizmo.theta
--Gravitational force
local factor = sqrt(gradientSquared + 1)/GRAVITY
local gx = gradientX/factor
local gy = gradientY/factor
local newvx = oldvx - gx*INTERVAL
local newvy = oldvy - gy*INTERVAL
local phi = atan2(newvy, newvx)
vHorizontal = sqrt(newvx*newvx + newvy*newvy)
--Surface friction
local textureFactor
if DIFFERENT_SURFACE_FRICTIONS then
textureFactor = TERRAIN_TYPE_FRICTION[GetTerrainType(x, y)] or 1
else
textureFactor = 1
end
local totalFriction = (gizmo.friction*textureFactor*frictionMultiplier)*INTERVAL
if vHorizontal < STATIC_FRICTION_FACTOR*totalFriction then
vHorizontal = 0
else
vHorizontal = vHorizontal - totalFriction
end
gizmo.x = x + (oldvx + newvx)/2*INTERVAL
gizmo.y = y + (oldvy + newvy)/2*INTERVAL
gizmo.z = GetTerrainZ(gizmo.x, gizmo.y) + gizmo.collisionRadius
gizmo.vx = vHorizontal*cos(phi)
gizmo.vy = vHorizontal*sin(phi)
gizmo.vz = gradientX*gizmo.vx + gradientY*gizmo.vy
gizmo.theta = atan2(gizmo.vz, vHorizontal)
--Conversion of momentum on upward-curved surface.
if oldTheta < gizmo.theta - 0.001 then
local conversion = cos(gizmo.theta)/cos(oldTheta)
gizmo.vx = gizmo.vx*conversion
gizmo.vy = gizmo.vy*conversion
end
gizmo.vzOld = gizmo.vz
BlzSetSpecialEffectPosition(gizmo.visual, gizmo.x, gizmo.y, gizmo.z + gizmo.visualZ)
end
if gizmo.isResting then
ALICE_Unpause(gizmo, PAUSEABLE_FUNCTIONS)
ALICE_SetStationary(gizmo, false)
gizmo.isResting = false
end
elseif not gizmo.isResting then
--If object has come to a full stop, check if it is stable, and if so, set it to resting.
local x, y = gizmo.x, gizmo.y
local gradientX = (GetTerrainZ(x + 16, y) - GetTerrainZ(x - 16, y))/32
local gradientY = (GetTerrainZ(x, y + 16) - GetTerrainZ(x, y - 16))/32
local gradientSquared = gradientX*gradientX + gradientY*gradientY
local gx = gradientX/sqrt(gradientSquared + 1)*GRAVITY
local gy = gradientY/sqrt(gradientSquared + 1)*GRAVITY
local g = sqrt(gx*gx + gy*gy)
local textureFactor = 1
if DIFFERENT_SURFACE_FRICTIONS then
textureFactor = TERRAIN_TYPE_FRICTION[GetTerrainType(x, y)] or 1
end
if g > STATIC_FRICTION_FACTOR*gizmo.friction*textureFactor then
local phi = atan2(gy, gx)
gizmo.vx = (g - gizmo.friction)*cos(phi)*INTERVAL
gizmo.vy = (g - gizmo.friction)*sin(phi)*INTERVAL
gizmo.vz = gradientX*gizmo.vx + gradientY*gizmo.vy
gizmo.vzOld = gizmo.vz
gizmo.x = x + gizmo.vx*INTERVAL/2
gizmo.y = y + gizmo.vy*INTERVAL/2
gizmo.z = GetTerrainZ(gizmo.x, gizmo.y) + gizmo.collisionRadius
else
ALICE_SetStationary(gizmo, true)
gizmo.isResting = true
gizmo.vz = 0
end
BlzSetSpecialEffectPosition(gizmo.visual, gizmo.x, gizmo.y, gizmo.z + gizmo.visualZ)
end
end
end
---Takes a velocity and returns the x, y, and z-velocities that would cause a ballistic projectile launched with the specified velocity from the launch coordinates to impact at the specified target coordinates. There are usually two solutions. The highArc flag specifies if the function should search for the solution with the higher angle first. It is possible that there is no solution for a given velocity. In that case, the function will return nil.
---@param xLaunch number
---@param yLaunch number
---@param zLaunch number
---@param xTarget number
---@param yTarget number
---@param zTarget number
---@param velocity number
---@param highArc? boolean
---@return number | nil, number | nil, number | nil
function CAT_GetBallisticLaunchSpeedFromVelocity(xLaunch, yLaunch, zLaunch, xTarget, yTarget, zTarget, velocity, highArc)
local dx = xTarget - xLaunch
local dy = yTarget - yLaunch
local dist = sqrt(dx^2 + dy^2)
local stepSize = PI/8
local epsilon = 0.01
local goUp = not highArc
local guess
if highArc then
guess = PI/2.001
else
guess = -PI/2.001
end
local zGuess = zLaunch + dist*tan(guess) - 0.5*GRAVITY*(dist/(cos(guess)*velocity))^2
local delta
local deltaPrevious
for __ = 1, 100 do
if goUp then
guess = guess + stepSize
else
guess = guess - stepSize
end
zGuess = zLaunch + dist*tan(guess) - 0.5*GRAVITY*(dist/(cos(guess)*velocity))^2
deltaPrevious = delta
delta = zGuess - zTarget
if abs(delta) < epsilon then
break
end
if deltaPrevious and (delta > 0) ~= (deltaPrevious > 0) then
goUp = not goUp
stepSize = stepSize*(1 - abs(deltaPrevious)/(abs(deltaPrevious) + abs(delta)))
end
end
if delta > epsilon or delta < -epsilon then
return nil, nil, nil
end
return velocity*cos(guess)*dx/dist, velocity*cos(guess)*dy/dist, velocity*sin(guess)
end
---Takes an angle and returns the x, y, and z-velocities that would cause the proctile launched at that angle from the launch coordinates to impact at the specified target coordinates. Unlike the from-velocity version, this function always has a solution as long as the vertical angle between the launch and target coordinates is not greater than the specified launch angle. In that case, the function will return nil.
---@param xLaunch number
---@param yLaunch number
---@param zLaunch number
---@param xTarget number
---@param yTarget number
---@param zTarget number
---@param angle number
---@return number | nil, number | nil, number | nil
function CAT_GetBallisticLaunchSpeedFromAngle(xLaunch, yLaunch, zLaunch, xTarget, yTarget, zTarget, angle)
local dx = xTarget - xLaunch
local dy = yTarget - yLaunch
local dz = zTarget - zLaunch
local dist = sqrt(dx*dx + dy*dy)
local cosAngle, sinAngle = cos(angle), sin(angle)
local vSquared = (GRAVITY*dist*dist/(2*cosAngle*cosAngle))/(dist*tan(angle) - dz)
if vSquared < 0 then
return nil, nil, nil
end
local velocity = sqrt(vSquared)
return velocity*cosAngle*dx/dist, velocity*sinAngle*dy/dist, velocity*sinAngle
end
local function InitBallisticsCAT()
Require "ALICE"
Require "CAT_Objects"
Require "PrecomputedHeightMap"
INTERVAL = ALICE_Config.MIN_INTERVAL
ALICE_FuncSetInit(CAT_MoveBallistic, InitMoveBallistic)
ALICE_RecognizeFields(
"vx",
"vy",
"vz",
"friction",
"isResting",
"collisionRadius"
)
ALICE_FuncRequireFields(CAT_MoveBallistic, true, false, "x", "y", "z", "vx", "vy", "collisionRadius")
end
OnInit.final("CAT_Ballistics", InitBallisticsCAT)
end
if Debug then Debug.beginFile "CAT Forces2D" end ---@diagnostic disable: need-check-nil
do
--[[
=============================================================================================================================================================
Complementary ALICE Template
by Antares
Requires:
ALICE https://www.hiveworkshop.com/threads/a-l-i-c-e-interaction-engine.353126/
Objects CAT
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
=============================================================================================================================================================
F O R C E S 2 D
=============================================================================================================================================================
This is the simplified 2D version of the Forces CAT. It is recommended to only use either this or the 3D version.
The forces library allows you to create interactions where objects are pushing or pulling other objects in the vicinity. A force can affect units and gizmos,
but the source cannot be a unit. To enable a unit as the source of a force, create a class as the source of the force and anchor it to that unit. There are
preset force functions packaged with this CAT that you can use, but you can also create your own force functions.
To add a force to a class, use the corresponding AddForce function on your class on map initialization. The function will add the necessary entries to your
class table to make the class instances a source of the force field. The AddForce functions modify the class's interaction tables. Make sure these changes
are preserved!
To define your own force, you need to define three functions:
InitFunc This function is called when a pair is created for this force interaction. It can be used to precompute data and write it into the pair matrix.
ForceFunc This function determines the strength and direction of the force. It receives 8 input arguments:
(source, target, matrixData, distance, deltaX, deltaY, deltaVelocityX, deltaVelocityY). It returns two numbers: (forceX, forceY).
IntervalFunc This function determines the interaction interval of your force (the same as the ALICE interactionFunc interval). A lower interval makes the
force more accurate. It receives the same 8 input arguments and returns a number.
The preset force functions can serve as a blueprint for your custom functions.
=============================================================================================================================================================
L I S T O F F U N C T I O N S
=============================================================================================================================================================
The pairsWith parameter is a string or a string sequence listing identifiers of objects that the force should affect.
CAT_AddGravity2D(gizmo, pairsWith) A long-range attraction that gets stronger as objects move closer together. Uses the
mass field to determine the force strength.
CAT_AddPressure2D(gizmo, pairsWith) Pushes nearby objects away. The strength is determined by the .pressureStrength field.
The coupling strength with objects is based on the .collisionRadius in the case of
gizmos, and the collision radius and height in the case of units. The field
.pressureMaxRange determines the maximum range of the force. The force will drop
gradually until it hits zero at that range.
CAT_AddWindField2D(gizmo, pairsWith) A force that pushes objects into a certain direction. The .windFieldDensity field
determines the strength of the wind field. The .windFieldSpeed field determines the
speed of the wind, the field .windFieldAngle the direction of the wind. The
.windFieldMaxRange field determines the radius of the field. The wind density will
drop gradually until it hits zero at that range.
CAT_AddForce2D(gizmo, pairsWith, initFunc, forceFunc, intervalFunc) Add a custom force to the gizmo.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
--Multiplies the forces on a unit (compared to a gizmo) by this factor.
local FORCE_UNIT_MULTIPLIER = 0.3 ---@type number
--Determines the strength of gravity.
local GRAVITY_STRENGTH = 50000 ---@type number
--Determines how often the force fields are updated for gravity. A greater accuracy requires more calculations. Use debug mode to gauge the appropriate accuracy.
local GRAVITY_ACCURACY = 10 ---@type number
--Avoids infinities by making the gravity strength not increase further when objects move closer to each other than this value. Can be overwritten with the
--.minDistance field.
local DEFAULT_GRAVITY_MIN_DISTANCE = 128 ---@type number
--Determines how often the force fields are updated for the pressure force. A greater accuracy requires more calculations. Use debug mode to gauge the
--appropriate accuracy.
local PRESSURE_ACCURACY = 0.05 ---@type number
--Determines how often the force fields are updated for the wind force. A greater accuracy requires more calculations. Use debug mode to gauge the appropriate
--accuracy.
local WIND_FIELD_ACCURACY = 2.0 ---@type number
--===========================================================================================================================================================
local sqrt = math.sqrt
local cos = math.cos
local sin = math.sin
local INTERVAL = nil
local unitForce = {}
local Force2D = nil ---@type function
local SPHERE_CROSS_SECTION = 4 - 8/bj_PI
local CYLINDER_CROSS_SECTION = 2/bj_PI
---@class forceMatrix
local forceMatrix = {
Fx = 0,
Fy = 0,
Fxdt = 0,
Fydt = 0,
lastUpdate = nil,
doUserInit = true
}
forceMatrix.__index = forceMatrix
local function GetObjectCrossSection(object)
if type(object) == "table" then
if object.collisionRadius then
return SPHERE_CROSS_SECTION*object.collisionRadius
elseif object.anchor then
if type(object.anchor) == "table" then
return SPHERE_CROSS_SECTION*object.anchor.collisionRadius
elseif HandleType[object.anchor] == "unit" then
local collisionSize = BlzGetUnitCollisionSize(object.anchor)
return CYLINDER_CROSS_SECTION*collisionSize*(WIDGET_TYPE_HEIGHT[GetUnitTypeId(object.anchor)] or DEFAULT_UNIT_HEIGHT_FACTOR*collisionSize)
else
return 0
end
else
return 0
end
elseif HandleType[object] == "unit" then
local collisionSize = BlzGetUnitCollisionSize(object)
return CYLINDER_CROSS_SECTION*collisionSize*(WIDGET_TYPE_HEIGHT[GetUnitTypeId(object)] or DEFAULT_UNIT_HEIGHT_FACTOR*collisionSize)
else
return 0
end
end
--===========================================================================================================================================================
--2D Force Functions
--===========================================================================================================================================================
local function InitAccelerateGizmo2D(gizmo)
gizmo.multiplier = INTERVAL/CAT_GetObjectMass(gizmo)
if gizmo.multiplier == math.huge then
error("Attempting to apply force to object for which no mass was assigned.")
end
end
local function AccelerateGizmo2D(gizmo)
if gizmo.Fx == 0 and gizmo.Fy == 0 then
ALICE_PairPause()
return
end
if gizmo.anchor then
if type(gizmo.anchor) == "table" then
gizmo.anchor.vx = gizmo.anchor.vx + gizmo.Fx*gizmo.multiplier
gizmo.anchor.vy = gizmo.anchor.vy + gizmo.Fy*gizmo.multiplier
else
CAT_Knockback(gizmo.anchor, gizmo.Fx*gizmo.multiplier, gizmo.Fy*gizmo.multiplier, 0)
end
else
gizmo.vx = gizmo.vx + gizmo.Fx*gizmo.multiplier
gizmo.vy = gizmo.vy + gizmo.Fy*gizmo.multiplier
end
gizmo.Fx = gizmo.Fx + gizmo.Fxdt*INTERVAL
gizmo.Fy = gizmo.Fy + gizmo.Fydt*INTERVAL
end
local function ResumForceCallback2D(source, target, forceTable)
local data = ALICE_PairLoadData(forceMatrix)
forceTable.Fx = forceTable.Fx + data.Fx
forceTable.Fy = forceTable.Fy + data.Fy
forceTable.Fxdt = forceTable.Fxdt + data.Fxdt
forceTable.Fydt = forceTable.Fydt + data.Fydt
end
local function ResumForceGizmo2D(gizmo)
gizmo.Fx, gizmo.Fy = 0, 0
gizmo.Fxdt, gizmo.Fydt = 0, 0
ALICE_ForAllPairsDo(ResumForceCallback2D, gizmo, Force2D, false, nil, gizmo)
if gizmo.Fx == 0 and gizmo.Fy == 0 then
ALICE_PairPause()
end
return 5.0
end
local function ClearUnitForce(unit, __, __)
unitForce[unit] = nil
end
local function InitAccelerateUnit2D(unit)
local data = ALICE_PairLoadData(forceMatrix)
data.multiplier = INTERVAL/CAT_GetObjectMass(unit)
if data.multiplier == math.huge then
error("Attempting to apply force to unit with no mass.")
end
end
local function AccelerateUnit2D(unit)
local data = ALICE_PairLoadData(forceMatrix)
local forceTable = unitForce[unit]
if not forceTable or (forceTable.Fx == 0 and forceTable.Fy == 0) then
ALICE_PairPause()
return
end
CAT_Knockback(unit, forceTable.Fx*data.multiplier, forceTable.Fy*data.multiplier, 0)
forceTable.Fx = forceTable.Fx + forceTable.Fxdt*INTERVAL
forceTable.Fy = forceTable.Fy + forceTable.Fydt*INTERVAL
end
local function ResumForceUnit2D(unit)
local forceTable = unitForce[unit]
if forceTable == nil then
ALICE_PairPause()
return 5.0
end
forceTable.Fx, forceTable.Fy = 0, 0
forceTable.Fxdt, forceTable.Fydt = 0, 0
ALICE_ForAllPairsDo(ResumForceCallback2D, unit, Force2D, false, nil, forceTable)
if forceTable.Fx == 0 and forceTable.Fy == 0 then
ALICE_PairPause()
end
return 5.0
end
--===========================================================================================================================================================
local function ClearForce2D(source, target)
local data = ALICE_PairLoadData(forceMatrix)
local FxOld = data.Fx + data.Fxdt*(ALICE_TimeElapsed - data.lastUpdate)
local FyOld = data.Fy + data.Fydt*(ALICE_TimeElapsed - data.lastUpdate)
local FxdtOld = data.Fxdt
local FydtOld = data.Fydt
local forceTable
if data.targetIsGizmo then
forceTable = target
else
forceTable = unitForce[target]
end
if forceTable then
forceTable.Fx = forceTable.Fx - FxOld
forceTable.Fy = forceTable.Fy - FyOld
forceTable.Fxdt = forceTable.Fxdt - FxdtOld
forceTable.Fydt = forceTable.Fydt - FydtOld
end
end
local function InitForce2D(source, target)
local data = ALICE_PairLoadData(forceMatrix)
data.lastUpdate = ALICE_TimeElapsed
data.targetIsGizmo = type(target) == "table"
if data.targetIsGizmo then
data.typeMultiplier = 1
if target.Fx == nil then
ALICE_AddSelfInteraction(target, AccelerateGizmo2D)
ALICE_AddSelfInteraction(target, ResumForceGizmo2D)
target.Fx, target.Fy = 0, 0
target.Fxdt, target.Fydt = 0, 0
end
elseif HandleType[target] == "unit" then
data.typeMultiplier = FORCE_UNIT_MULTIPLIER
if unitForce[target] == nil then
unitForce[target] = {}
local forceTable = unitForce[target]
ALICE_AddSelfInteraction(target, AccelerateUnit2D)
ALICE_AddSelfInteraction(target, ResumForceUnit2D)
forceTable.Fx, forceTable.Fy = 0, 0
forceTable.Fxdt, forceTable.Fydt = 0, 0
end
end
end
Force2D = function(source, target)
local data = ALICE_PairLoadData(forceMatrix)
if data.doUserInit then
if source.initForceFunc then
source.initForceFunc(source, target)
end
data.doUserInit = false
end
local xf, yf, xo, yo = ALICE_PairGetCoordinates2D()
local vxf, vyf = CAT_GetObjectVelocity2D(source)
local vxo, vyo = CAT_GetObjectVelocity2D(target)
local dx, dy = xf - xo, yf - yo
local dvx, dvy = vxf - vxo, vyf - vyo
local dist = sqrt(dx*dx + dy*dy)
local forceX, forceY = source.forceFunc(source, target, data, dist, dx, dy, dvx, dvy)
local interval = (source.intervalFunc(source, target, data, dist, dx, dy, dvx, dvy) / INTERVAL + 1)*INTERVAL
if interval > ALICE_Config.MAX_INTERVAL then
interval = ALICE_Config.MAX_INTERVAL
end
--Force at next step.
local dxNS = dx + 0.5*dvx*interval
local dyNS = dy + 0.5*dvy*interval
local distNS = sqrt(dxNS*dxNS + dyNS*dyNS)
local forceXNS, forceYNS = source.forceFunc(source, target, data, distNS, dxNS, dyNS, dvx, dvy)
local forceXdt = 2*(forceXNS - forceX)/interval
local forceYdt = 2*(forceYNS - forceY)/interval
local lastInterval = (ALICE_TimeElapsed - data.lastUpdate)
local forceTable
if data.targetIsGizmo then
forceTable = target
else
forceTable = unitForce[target]
end
local FxOld = data.Fx + data.Fxdt*lastInterval
local FyOld = data.Fy + data.Fydt*lastInterval
if forceTable.Fx == 0 and forceTable.Fy == 0 and (forceX ~= 0 or forceY ~= 0) then
ALICE_Unpause(target)
end
forceTable.Fxdt = forceTable.Fxdt + forceXdt - data.Fxdt
forceTable.Fydt = forceTable.Fydt + forceYdt - data.Fydt
forceTable.Fx = forceTable.Fx + forceX - FxOld
forceTable.Fy = forceTable.Fy + forceY - FyOld
data.Fx, data.Fy = forceX, forceY
data.Fxdt, data.Fydt = forceXdt, forceYdt
data.lastUpdate = ALICE_TimeElapsed
return interval
end
--===========================================================================================================================================================
--Gravity
--===========================================================================================================================================================
local function InitGravity(source, target)
local data = ALICE_PairLoadData(forceMatrix)
local massSource = CAT_GetObjectMass(source)
local massTarget = CAT_GetObjectMass(target)
data.strength = massSource*massTarget*(GRAVITY_STRENGTH*1.0001)*data.typeMultiplier --1.0001 to convert to float to avoid integer overflow
data.minDistance = source.minDistance or DEFAULT_GRAVITY_MIN_DISTANCE
data.intervalFactor = 1/(GRAVITY_ACCURACY*data.strength/massTarget)
if data.strength == 0 then
ALICE_PairDisable()
end
end
local function GravityForce2D(source, target, data, dist, dx, dy, dvx, dvy)
if data.minDistance > dist then
dist = data.minDistance
end
local factor = data.strength/dist^3
return dx*factor, dy*factor
end
local function GravityInterval2D(source, target, data, dist, dx, dy, dvx, dvy)
--Increased update frequency when objects are moving towards each other.
local vdotd = -(dvx*dx + dvy*dy)
if vdotd < 0 then
vdotd = 0
end
return dist*dist*data.intervalFactor/(1 + vdotd*data.intervalFactor)
end
--===========================================================================================================================================================
--Pressure Force
--===========================================================================================================================================================
local function InitPressureForce(source, target)
local data = ALICE_PairLoadData(forceMatrix)
data.strengthFactor = GetObjectCrossSection(target)*data.typeMultiplier
data.intervalFactor = CAT_GetObjectMass(target)/(PRESSURE_ACCURACY*data.strengthFactor)
if data.strengthFactor*source.pressureStrength == 0 then
ALICE_PairDisable()
end
end
local function PressureForce2D(source, target, data, dist, dx, dy, dvx, dvy)
if dist > source.pressureMaxRange then
return 0, 0
end
local factor = -source.pressureStrength*data.strengthFactor*(source.pressureMaxRange - dist)/(source.pressureMaxRange*dist)
return dx*factor, dy*factor
end
local function PressureInterval2D(source, target, data, dist, dx, dy, dvx, dvy)
--Increased update frequency when objects are moving towards each other.
local vdivd = -(dvx*dx + dvy*dy)/dist^2
if vdivd < 0 then
vdivd = 0
end
local interval = (0.15 + 0.85*(dist/source.pressureMaxRange))*data.intervalFactor/source.pressureStrength
return interval/(1 + vdivd*interval)
end
--===========================================================================================================================================================
--Windfield Force
--===========================================================================================================================================================
local function InitWindField(source, target)
local data = ALICE_PairLoadData(forceMatrix)
data.strengthFactor = GetObjectCrossSection(target)*data.typeMultiplier/1000
data.intervalFactor = CAT_GetObjectMass(target)/(WIND_FIELD_ACCURACY*data.strengthFactor)
data.vx = source.windFieldSpeed*cos(source.windFieldAngle)
data.vy = source.windFieldSpeed*sin(source.windFieldAngle)
if data.strengthFactor*source.windFieldDensity == 0 then
ALICE_PairDisable()
end
end
local function WindForce2D(source, target, data, dist, dx, dy, dvx, dvy)
if dist > source.windFieldMaxRange then
return 0, 0
end
local dvxWind = dvx + data.vx
local dvyWind = dvy + data.vy
local dvWindTotal = sqrt(dvxWind*dvxWind + dvyWind*dvyWind)
local factor = dvWindTotal*source.windFieldDensity*data.strengthFactor*(source.windFieldMaxRange - dist)/(source.windFieldMaxRange*dist)
return dvxWind*factor, dvyWind*factor
end
local function WindFieldInterval2D(source, target, data, dist, dx, dy, dvx, dvy)
--Increased update frequency when objects are moving towards each other.
local vdivd = -(dvx*dx + dvy*dy)/dist^2
if vdivd < 0 then
vdivd = 0
end
--Arbitrary numbers
local interval = (0.15 + 0.85*(dist/source.windFieldMaxRange))*data.intervalFactor/source.windFieldDensity
return interval/(1 + vdivd*interval)
end
--===========================================================================================================================================================
--API
--===========================================================================================================================================================
---Add a custom force to the gizmo.
---@param class table
---@param interactsWith table | string
---@param initFunc function
---@param forceFunc function
---@param intervalFunc function
function CAT_AddForce2D(class, interactsWith, initFunc, forceFunc, intervalFunc)
class.initForceFunc = initFunc
class.forceFunc = forceFunc
class.intervalFunc = intervalFunc
if class.interactions == nil then
class.interactions = {}
end
if type(interactsWith) == "table" then
for __, id in pairs(interactsWith) do
class.interactions[id] = Force2D
end
else
class.interactions[interactsWith] = Force2D
end
end
---A long-range attraction that gets stronger as objects move closer together. Uses the mass field to determine the force strength.
---@param class table
---@param interactsWith table | string
function CAT_AddGravity2D(class, interactsWith)
CAT_AddForce2D(class, interactsWith, InitGravity, GravityForce2D, GravityInterval2D)
class.hasInfiniteRange = true
end
---Pushes nearby objects away. The strength is determined by the .pressureStrength field. The coupling strength with objects is based on the .collisionRadius in the case of gizmos, and the collision radius and height in the case of units. The field .pressureMaxRange determines the maximum range of the force. The force will drop gradually until it hits zero at that range.
---@param class table
---@param interactsWith table | string
function CAT_AddPressure2D(class, interactsWith)
CAT_AddForce2D(class, interactsWith, InitPressureForce, PressureForce2D, PressureInterval2D)
class.radius = math.max(class.radius or ALICE_Config.DEFAULT_OBJECT_RADIUS, class.pressureMaxRange)
end
---A force that pushes objects into a certain direction. The .windFieldDensity field determines the strength of the wind field. The .windFieldSpeed field determines the speed of the wind, the field .windFieldAngle the direction of the wind. The .windFieldMaxRange field determines the radius of the field. The wind density will drop gradually until it hits zero at that range.
---@param class table
---@param interactsWith table | string
function CAT_AddWindField2D(class, interactsWith)
CAT_AddForce2D(class, interactsWith, InitWindField, WindForce2D, WindFieldInterval2D)
class.radius = math.max(class.radius or ALICE_Config.DEFAULT_OBJECT_RADIUS, class.windFieldMaxRange)
end
--===========================================================================================================================================================
local function InitForcesCAT()
Require "ALICE"
Require "CAT_Objects"
INTERVAL = ALICE_Config.MIN_INTERVAL
ALICE_FuncSetInit(AccelerateGizmo2D, InitAccelerateGizmo2D)
ALICE_FuncSetInit(AccelerateUnit2D, InitAccelerateUnit2D)
ALICE_FuncSetInit(Force2D, InitForce2D)
ALICE_FuncDistribute(ResumForceGizmo2D, 5.0)
ALICE_FuncDistribute(ResumForceUnit2D, 5.0)
ALICE_FuncSetOnBreak(Force2D, ClearForce2D)
ALICE_FuncSetOnDestroy(AccelerateUnit2D, ClearUnitForce)
ALICE_FuncSetName(AccelerateGizmo2D, "AccelerateGizmo2D")
ALICE_FuncSetName(ResumForceGizmo2D, "ResumForceGizmo2D")
ALICE_FuncSetName(AccelerateUnit2D, "AccelerateUnit2D")
ALICE_FuncSetName(ResumForceUnit2D, "ResumForceUnit2D")
ALICE_FuncSetName(Force2D, "Force2D")
ALICE_RecognizeFields(
"initForceFunc",
"forceFunc",
"intervalFunc",
"collisionRadius",
"pressureStrength",
"pressureMaxRange",
"mass",
"windFieldAngle",
"windFieldSpeed",
"windFieldDensity",
"windFieldMaxRange"
)
end
OnInit.final("CAT_Forces2D", InitForcesCAT)
end
if Debug then Debug.beginFile "CAT Forces3D" end ---@diagnostic disable: need-check-nil
do
--[[
=============================================================================================================================================================
Complementary ALICE Template
by Antares
Requires:
ALICE https://www.hiveworkshop.com/threads/a-l-i-c-e-interaction-engine.353126/
Objects CAT
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
=============================================================================================================================================================
F O R C E S 3 D
=============================================================================================================================================================
The forces library allows you to create interactions where objects are pushing or pulling other objects in the vicinity. A force can affect units and gizmos,
but the source cannot be a unit. To enable a unit as the source of a force, create a class as the source of the force and anchor it to that unit. There are
preset force functions packaged with this CAT that you can use, but you can also create your own force functions.
To add a force to a class, use the corresponding AddForce function on your class on map initialization. The function will add the necessary entries to your
class table to make the class instances a source of the force field. The AddForce functions modify the class's interaction tables. Make sure these changes
are preserved!
To define your own force, you need to define three functions:
InitFunc This function is called when a pair is created for this force interaction. It can be used to precompute data and write it into the pair matrix.
ForceFunc This function determines the strength and direction of the force. It receives 10 input arguments:
(source, target, matrixData, distance, deltaX, deltaY, deltaZ, deltaVelocityX, deltaVelocityY, deltaVelocityZ). It returns three numbers:
(forceX, forceY, forceZ).
IntervalFunc This function determines the interaction interval of your force (the same as the ALICE interactionFunc interval). A lower interval makes the
force more accurate. It receives the same 10 input arguments and returns a number.
The preset force functions can serve as a blueprint for your custom functions.
=============================================================================================================================================================
L I S T O F F U N C T I O N S
=============================================================================================================================================================
The pairsWith parameter is a string or a string sequence listing identifiers of objects that the force should affect.
CAT_AddGravity3D(gizmo, pairsWith) A long-range attraction that gets stronger as objects move closer together. Uses the
mass field to determine the force strength.
CAT_AddPressure3D(gizmo, pairsWith) Pushes nearby objects away. The strength is determined by the .pressureStrength field.
The coupling strength with objects is based on the .collisionRadius in the case of
gizmos, and the collision radius and height in the case of units. The field
.pressureMaxRange determines the maximum range of the force. The force will drop
gradually until it hits zero at that range.
CAT_AddWindField3D(gizmo, pairsWith) A force that pushes objects into a certain direction. The .windFieldDensity field
determines the strength of the wind field. The .windFieldSpeed field determines the
speed of the wind, the field .windFieldAnglePhi the horizontal direction of the wind,
and the field .windFieldAngleTheta the vertical direction. The .windFieldMaxRange
field determines the radius of the field. The wind density will drop gradually until
it hits zero at that range.
CAT_AddForce3D(gizmo, pairsWith, initFunc, forceFunc, intervalFunc) Add a custom force to the gizmo.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
--Multiplies the forces on a unit (compared to a gizmo) by this factor.
local FORCE_UNIT_MULTIPLIER = 0.3 ---@type number
--Determines the strength of gravity.
local GRAVITY_STRENGTH = 50000 ---@type number
--Determines how often the force fields are updated for gravity. A greater accuracy requires more calculations. Use debug mode to gauge the appropriate accuracy.
local GRAVITY_ACCURACY = 10 ---@type number
--Avoids infinities by making the gravity strength not increase further when objects move closer to each other than this value. Can be overwritten with the
--.minDistance field.
local DEFAULT_GRAVITY_MIN_DISTANCE = 128 ---@type number
--Determines how often the force fields are updated for the pressure force. A greater accuracy requires more calculations. Use debug mode to gauge the
--appropriate accuracy.
local PRESSURE_ACCURACY = 0.05 ---@type number
--Determines how often the force fields are updated for the wind force. A greater accuracy requires more calculations. Use debug mode to gauge the appropriate
--accuracy.
local WIND_FIELD_ACCURACY = 2.0 ---@type number
--===========================================================================================================================================================
local sqrt = math.sqrt
local cos = math.cos
local sin = math.sin
local INTERVAL = nil
local unitForce = {}
local Force3D = nil ---@type function
local SPHERE_CROSS_SECTION = 4 - 8/bj_PI
local CYLINDER_CROSS_SECTION = 2/bj_PI
---@gizmo forceMatrix
local forceMatrix = {
Fx = 0,
Fy = 0,
Fz = 0,
Fxdt = 0,
Fydt = 0,
Fzdt = 0,
lastUpdate = nil,
doUserInit = true
}
forceMatrix.__index = forceMatrix
local function GetObjectCrossSection(object)
if type(object) == "table" then
if object.collisionRadius then
return SPHERE_CROSS_SECTION*object.collisionRadius
elseif object.anchor then
if type(object.anchor) == "table" then
return SPHERE_CROSS_SECTION*object.anchor.collisionRadius
elseif HandleType[object.anchor] == "unit" then
local collisionSize = BlzGetUnitCollisionSize(object.anchor)
return CYLINDER_CROSS_SECTION*collisionSize*(WIDGET_TYPE_HEIGHT[GetUnitTypeId(object.anchor)] or DEFAULT_UNIT_HEIGHT_FACTOR*collisionSize)
else
return 0
end
else
return 0
end
elseif HandleType[object] == "unit" then
local collisionSize = BlzGetUnitCollisionSize(object)
return CYLINDER_CROSS_SECTION*collisionSize*(WIDGET_TYPE_HEIGHT[GetUnitTypeId(object)] or DEFAULT_UNIT_HEIGHT_FACTOR*collisionSize)
else
return 0
end
end
--===========================================================================================================================================================
--3D Force Functions
--===========================================================================================================================================================
local function InitAccelerateGizmo3D(gizmo)
gizmo.multiplier = INTERVAL/CAT_GetObjectMass(gizmo)
if gizmo.multiplier == math.huge then
error("Attempting to apply force to object for which no mass was assigned.")
end
end
local function AccelerateGizmo3D(gizmo)
if gizmo.Fx == 0 and gizmo.Fy == 0 and gizmo.Fz == 0 then
ALICE_PairPause()
return
end
if gizmo.anchor then
if type(gizmo.anchor) == "table" then
gizmo.anchor.vx = gizmo.anchor.vx + gizmo.Fx*gizmo.multiplier
gizmo.anchor.vy = gizmo.anchor.vy + gizmo.Fy*gizmo.multiplier
gizmo.anchor.vz = gizmo.anchor.vz + gizmo.Fz*gizmo.multiplier
else
CAT_Knockback(gizmo.anchor, gizmo.Fx*gizmo.multiplier, gizmo.Fy*gizmo.multiplier, gizmo.Fz*gizmo.multiplier)
end
else
gizmo.vx = gizmo.vx + gizmo.Fx*gizmo.multiplier
gizmo.vy = gizmo.vy + gizmo.Fy*gizmo.multiplier
gizmo.vz = gizmo.vz + gizmo.Fz*gizmo.multiplier
end
gizmo.Fx = gizmo.Fx + gizmo.Fxdt*INTERVAL
gizmo.Fy = gizmo.Fy + gizmo.Fydt*INTERVAL
gizmo.Fz = gizmo.Fz + gizmo.Fzdt*INTERVAL
end
local function ResumForceCallback3D(source, target, forceTable)
local data = ALICE_PairLoadData(forceMatrix)
forceTable.Fx = forceTable.Fx + data.Fx
forceTable.Fy = forceTable.Fy + data.Fy
forceTable.Fz = forceTable.Fz + data.Fz
forceTable.Fxdt = forceTable.Fxdt + data.Fxdt
forceTable.Fydt = forceTable.Fydt + data.Fydt
forceTable.Fzdt = forceTable.Fzdt + data.Fzdt
end
local function ResumForceGizmo3D(gizmo)
gizmo.Fx, gizmo.Fy, gizmo.Fz = 0, 0, 0
gizmo.Fxdt, gizmo.Fydt, gizmo.Fzdt = 0, 0, 0
ALICE_ForAllPairsDo(ResumForceCallback3D, gizmo, Force3D, false, nil, gizmo)
if gizmo.Fx == 0 and gizmo.Fy == 0 and gizmo.Fz == 0 then
ALICE_PairPause()
end
return 5.0
end
local function ClearUnitForce(unit, __, __)
unitForce[unit] = nil
end
local function InitAccelerateUnit3D(unit)
local data = ALICE_PairLoadData(forceMatrix)
data.multiplier = INTERVAL/CAT_GetObjectMass(unit)
if data.multiplier == math.huge then
error("Attempting to apply force to unit with no mass.")
end
end
local function AccelerateUnit3D(unit)
local data = ALICE_PairLoadData(forceMatrix)
local forceTable = unitForce[unit]
if not forceTable or (forceTable.Fx == 0 and forceTable.Fy == 0 and forceTable.Fz == 0) then
ALICE_PairPause()
return
end
CAT_Knockback(unit, forceTable.Fx*data.multiplier, forceTable.Fy*data.multiplier, forceTable.Fz*data.multiplier)
forceTable.Fx = forceTable.Fx + forceTable.Fxdt*INTERVAL
forceTable.Fy = forceTable.Fy + forceTable.Fydt*INTERVAL
forceTable.Fz = forceTable.Fz + forceTable.Fzdt*INTERVAL
end
local function ResumForceUnit3D(unit)
local forceTable = unitForce[unit]
if forceTable == nil then
ALICE_PairPause()
return 5.0
end
forceTable.Fx, forceTable.Fy, forceTable.Fz = 0, 0, 0
forceTable.Fxdt, forceTable.Fydt, forceTable.Fzdt = 0, 0, 0
ALICE_ForAllPairsDo(ResumForceCallback3D, unit, Force3D, false, nil, forceTable)
if forceTable.Fx == 0 and forceTable.Fy == 0 then
ALICE_PairPause()
end
return 5.0
end
--===========================================================================================================================================================
local function ClearForce3D(source, target)
local data = ALICE_PairLoadData(forceMatrix)
local FxOld = data.Fx + data.Fxdt*(ALICE_TimeElapsed - data.lastUpdate)
local FyOld = data.Fy + data.Fydt*(ALICE_TimeElapsed - data.lastUpdate)
local FzOld = data.Fz + data.Fzdt*(ALICE_TimeElapsed - data.lastUpdate)
local FxdtOld = data.Fxdt
local FydtOld = data.Fydt
local FzdtOld = data.Fzdt
local forceTable
if data.targetIsGizmo then
forceTable = target
else
forceTable = unitForce[target]
end
if forceTable then
forceTable.Fx = forceTable.Fx - FxOld
forceTable.Fy = forceTable.Fy - FyOld
forceTable.Fz = forceTable.Fz - FzOld
forceTable.Fxdt = forceTable.Fxdt - FxdtOld
forceTable.Fydt = forceTable.Fydt - FydtOld
forceTable.Fzdt = forceTable.Fzdt - FzdtOld
end
end
local function InitForce3D(source, target)
local data = ALICE_PairLoadData(forceMatrix)
data.lastUpdate = ALICE_TimeElapsed
data.targetIsGizmo = type(target) == "table"
if data.targetIsGizmo then
data.typeMultiplier = 1
if target.Fx == nil then
ALICE_AddSelfInteraction(target, AccelerateGizmo3D)
ALICE_AddSelfInteraction(target, ResumForceGizmo3D)
target.Fx, target.Fy, target.Fz = 0, 0, 0
target.Fxdt, target.Fydt, target.Fzdt = 0, 0, 0
end
elseif HandleType[target] == "unit" then
data.typeMultiplier = FORCE_UNIT_MULTIPLIER
if unitForce[target] == nil then
unitForce[target] = {}
local forceTable = unitForce[target]
ALICE_AddSelfInteraction(target, AccelerateUnit3D)
ALICE_AddSelfInteraction(target, ResumForceUnit3D)
forceTable.Fx, forceTable.Fy, forceTable.Fz = 0, 0, 0
forceTable.Fxdt, forceTable.Fydt, forceTable.Fzdt = 0, 0, 0
end
end
end
Force3D = function(source, target)
local data = ALICE_PairLoadData(forceMatrix)
if data.doUserInit then
if source.initForceFunc then
source.initForceFunc(source, target)
end
data.doUserInit = false
end
local xf, yf, zf, xo, yo, zo = ALICE_PairGetCoordinates3D()
local vxf, vyf, vzf = CAT_GetObjectVelocity3D(source)
local vxo, vyo, vzo = CAT_GetObjectVelocity3D(target)
local dx, dy, dz = xf - xo, yf - yo, zf - zo
local dvx, dvy, dvz = vxf - vxo, vyf - vyo, vzf - vzo
local dist = sqrt(dx*dx + dy*dy + dz*dz)
local forceX, forceY, forceZ = source.forceFunc(source, target, data, dist, dx, dy, dz, dvx, dvy, dvz)
local interval = (source.intervalFunc(source, target, data, dist, dx, dy, dz, dvx, dvy, dvz) / INTERVAL + 1)*INTERVAL
if interval > ALICE_Config.MAX_INTERVAL then
interval = ALICE_Config.MAX_INTERVAL
end
--Force at next step.
local dxNS = dx + 0.5*dvx*interval
local dyNS = dy + 0.5*dvy*interval
local dzNS = dz + 0.5*dvz*interval
local distNS = sqrt(dxNS*dxNS + dyNS*dyNS + dzNS*dzNS)
local forceXNS, forceYNS, forceZNS = source.forceFunc(source, target, data, distNS, dxNS, dyNS, dzNS, dvx, dvy, dvz)
local forceXdt = 2*(forceXNS - forceX)/interval
local forceYdt = 2*(forceYNS - forceY)/interval
local forceZdt = 2*(forceZNS - forceZ)/interval
local lastInterval = (ALICE_TimeElapsed - data.lastUpdate)
local forceTable
if data.targetIsGizmo then
forceTable = target
else
forceTable = unitForce[target]
end
local FxOld = data.Fx + data.Fxdt*lastInterval
local FyOld = data.Fy + data.Fydt*lastInterval
local FzOld = data.Fz + data.Fzdt*lastInterval
if forceTable.Fx == 0 and forceTable.Fy == 0 and forceTable.Fz == 0 and (forceX ~= 0 or forceY ~= 0 or forceZ ~= 0) then
ALICE_Unpause(target)
end
forceTable.Fxdt = forceTable.Fxdt + forceXdt - data.Fxdt
forceTable.Fydt = forceTable.Fydt + forceYdt - data.Fydt
forceTable.Fzdt = forceTable.Fzdt + forceZdt - data.Fzdt
forceTable.Fx = forceTable.Fx + forceX - FxOld
forceTable.Fy = forceTable.Fy + forceY - FyOld
forceTable.Fz = forceTable.Fz + forceZ - FzOld
data.Fx, data.Fy, data.Fz = forceX, forceY, forceZ
data.Fxdt, data.Fydt, data.Fzdt = forceXdt, forceYdt, forceZdt
data.lastUpdate = ALICE_TimeElapsed
return interval
end
--===========================================================================================================================================================
--Gravity
--===========================================================================================================================================================
local function InitGravity(source, target)
local data, __ = ALICE_PairLoadData(forceMatrix)
local massSource = CAT_GetObjectMass(source)
local massTarget = CAT_GetObjectMass(target)
data.strength = massSource*massTarget*(GRAVITY_STRENGTH*1.0001)*data.typeMultiplier --1.0001 to convert to float to avoid integer overflow
data.minDistance = source.minDistance or DEFAULT_GRAVITY_MIN_DISTANCE
data.intervalFactor = 1/(GRAVITY_ACCURACY*data.strength/massTarget)
if data.strength == 0 then
ALICE_PairDisable()
end
end
local function GravityForce3D(source, target, data, dist, dx, dy, dz, dvx, dvy, dvz)
if data.minDistance > dist then
dist = data.minDistance
end
local factor = data.strength/dist^3
return dx*factor, dy*factor, dz*factor
end
local function GravityInterval3D(source, target, data, dist, dx, dy, dz, dvx, dvy, dvz)
--Increased update frequency when objects are moving towards each other.
local vdotd = -(dvx*dx + dvy*dy + dvz*dz)
if vdotd < 0 then
vdotd = 0
end
return dist*dist*data.intervalFactor/(1 + vdotd*data.intervalFactor)
end
--===========================================================================================================================================================
--Pressure Force
--===========================================================================================================================================================
local function InitPressureForce(source, target)
local data, __ = ALICE_PairLoadData(forceMatrix)
data.strengthFactor = GetObjectCrossSection(target)*data.typeMultiplier
data.intervalFactor = CAT_GetObjectMass(target)/(PRESSURE_ACCURACY*data.strengthFactor)
if data.strengthFactor*source.pressureStrength == 0 then
ALICE_PairDisable()
end
end
local function PressureForce3D(source, target, data, dist, dx, dy, dz, dvx, dvy, dvz)
if dist > source.pressureMaxRange then
return 0, 0, 0
end
local factor = -source.pressureStrength*data.strengthFactor*(source.pressureMaxRange - dist)/(source.pressureMaxRange*dist)
return dx*factor, dy*factor, dz*factor
end
local function PressureInterval3D(source, target, data, dist, dx, dy, dz, dvx, dvy, dvz)
--Increased update frequency when objects are moving towards each other.
local vdivd = -(dvx*dx + dvy*dy + dvz*dz)/dist^2
if vdivd < 0 then
vdivd = 0
end
--Arbitrary numbers
local interval = (0.15 + 0.85*(dist/source.pressureMaxRange))*data.intervalFactor/source.pressureStrength
return interval/(1 + vdivd*interval)
end
--===========================================================================================================================================================
--Windfield Force
--===========================================================================================================================================================
local function InitWindField(source, target)
local data, __ = ALICE_PairLoadData(forceMatrix)
data.strengthFactor = GetObjectCrossSection(target)*data.typeMultiplier/1000
data.intervalFactor = CAT_GetObjectMass(target)/(WIND_FIELD_ACCURACY*data.strengthFactor)
data.vx = source.windFieldSpeed*cos(source.windFieldAnglePhi)*cos(source.windFieldAngleTheta or 0)
data.vy = source.windFieldSpeed*sin(source.windFieldAnglePhi)*cos(source.windFieldAngleTheta or 0)
data.vz = source.windFieldSpeed*sin(source.windFieldAngleTheta or 0)
if data.strengthFactor*source.windFieldDensity == 0 then
ALICE_PairDisable()
end
end
local function WindForce3D(source, target, data, dist, dx, dy, dz, dvx, dvy, dvz)
if dist > source.windFieldMaxRange then
return 0, 0, 0
end
local dvxWind = dvx + data.vx
local dvyWind = dvy + data.vy
local dvzWind = dvz + data.vz
local dvWindTotal = sqrt(dvxWind*dvxWind + dvyWind*dvyWind + dvzWind*dvzWind)
local factor = dvWindTotal*source.windFieldDensity*data.strengthFactor*(source.windFieldMaxRange - dist)/(source.windFieldMaxRange*dist)
return dvxWind*factor, dvyWind*factor, dvzWind*factor
end
local function WindFieldInterval3D(source, target, data, dist, dx, dy, dz, dvx, dvy, dvz)
--Increased update frequency when objects are moving towards each other.
local vdivd = -(dvx*dx + dvy*dy + dvz*dz)/dist^2
if vdivd < 0 then
vdivd = 0
end
local interval = (0.15 + 0.85*(dist/source.windFieldMaxRange))*data.intervalFactor/source.windFieldDensity
return interval/(1 + vdivd*interval)
end
--===========================================================================================================================================================
--API
--===========================================================================================================================================================
---Add a custom force to the gizmo.
---@param class table
---@param interactsWith table | string
---@param initFunc function
---@param forceFunc function
---@param intervalFunc function
function CAT_AddForce3D(class, interactsWith, initFunc, forceFunc, intervalFunc)
class.initForceFunc = initFunc
class.forceFunc = forceFunc
class.intervalFunc = intervalFunc
if class.interactions == nil then
class.interactions = {}
end
if type(interactsWith) == "table" then
for __, id in pairs(interactsWith) do
class.interactions[id] = Force3D
end
else
class.interactions[interactsWith] = Force3D
end
end
---A long-range attraction that gets stronger as objects move closer together. Uses the mass field to determine the force strength.
---@param class table
---@param interactsWith table | string
function CAT_AddGravity3D(class, interactsWith)
CAT_AddForce3D(class, interactsWith, InitGravity, GravityForce3D, GravityInterval3D)
class.hasInfiniteRange = true
end
---Pushes nearby objects away. The strength is determined by the .pressureStrength field. The coupling strength with objects is based on the .collisionRadius in the case of gizmos, and the collision radius and height in the case of units. The field .pressureMaxRange determines the maximum range of the data. The force will drop gradually until it hits zero at that range.
---@param class table
---@param interactsWith table | string
function CAT_AddPressure3D(class, interactsWith)
CAT_AddForce3D(class, interactsWith, InitPressureForce, PressureForce3D, PressureInterval3D)
class.radius = math.max(class.radius or ALICE_Config.DEFAULT_OBJECT_RADIUS, class.pressureMaxRange)
end
---A force that pushes objects into a certain direction. The .windFieldDensity field determines the strength of the wind field. The .windFieldSpeed field determines the speed of the wind, the field .windFieldAnglePhi the horizontal direction of the wind, and the field .windFieldAngleTheta the vertical direction. The .windFieldMaxRange field determines the radius of the field. The wind density will drop gradually until it hits zero at that range.
---@param class table
---@param interactsWith table | string
function CAT_AddWindField3D(class, interactsWith)
CAT_AddForce3D(class, interactsWith, InitWindField, WindForce3D, WindFieldInterval3D)
class.radius = math.max(class.radius or ALICE_Config.DEFAULT_OBJECT_RADIUS, class.windFieldMaxRange)
end
--===========================================================================================================================================================
local function InitForcesCAT()
Require "ALICE"
Require "CAT_Objects"
INTERVAL = ALICE_Config.MIN_INTERVAL
ALICE_FuncSetInit(AccelerateGizmo3D, InitAccelerateGizmo3D)
ALICE_FuncSetInit(AccelerateUnit3D, InitAccelerateUnit3D)
ALICE_FuncSetInit(Force3D, InitForce3D)
ALICE_FuncDistribute(ResumForceGizmo3D, 5.0)
ALICE_FuncDistribute(ResumForceUnit3D, 5.0)
ALICE_FuncSetOnBreak(Force3D, ClearForce3D)
ALICE_FuncSetOnDestroy(AccelerateUnit3D, ClearUnitForce)
ALICE_FuncSetName(AccelerateGizmo3D, "AccelerateGizmo3D")
ALICE_FuncSetName(ResumForceGizmo3D, "ResumForceGizmo3D")
ALICE_FuncSetName(AccelerateUnit3D, "AccelerateUnit3D")
ALICE_FuncSetName(ResumForceUnit3D, "ResumForceUnit3D")
ALICE_FuncSetName(Force3D, "Force3D")
ALICE_RecognizeFields(
"initForceFunc",
"forceFunc",
"intervalFunc",
"collisionRadius",
"pressureStrength",
"pressureMaxRange",
"mass",
"windFieldSpeed",
"windFieldDensity",
"windFieldMaxRange",
"windFieldAnglePhi",
"windFieldAngleTheta"
)
end
OnInit.final("CAT_Forces3D", InitForcesCAT)
end
function Play3DSound(soundPath, x, y)
local s = CreateSound(soundPath , false, true, true, 10, 10, "DefaultEAXON")
SetSoundDistances( s , 600 , 4000 )
SetSoundPosition( s, x, y, 50)
StartSound(s)
KillSoundWhenDone(s)
end
---@param soundPath string
---@param localPlayerCanHearSound boolean
function PlaySoundLocal(soundPath, localPlayerCanHearSound)
local volume
local s = CreateSound( soundPath , false, false, false, 10, 10, "DefaultEAXON")
if localPlayerCanHearSound then
volume = 100
else
volume = 0
end
SetSoundVolumeBJ( s , volume )
StartSound(s)
KillSoundWhenDone(s)
end
do
local function ExplodeDynamite(dynamite)
local x, y, z = dynamite.x, dynamite.y, dynamite.z
local explosion = AddSpecialEffect("Objects\\Spawnmodels\\Other\\NeutralBuildingExplosion\\NeutralBuildingExplosion.mdl", x, y)
BlzSetSpecialEffectZ(explosion, dynamite.z)
DestroyEffect(explosion)
BlzSetSpecialEffectZ(dynamite.visual, -2000)
ALICE_ForAllObjectsInRangeDo(function(unit)
local xu, yu = ALICE_GetCoordinates2D(unit)
local dist = math.sqrt((xu - x)^2 + (yu - y)^2)
local strength = 1 - dist/475
local angle = math.atan(yu - y, xu - x)
UnitDamageTarget(dynamite.thrower, unit, 1500*strength, false, false, ATTACK_TYPE_HERO, DAMAGE_TYPE_MAGIC, WEAPON_TYPE_WHOKNOWS)
CAT_Knockback(unit, 1200*strength*math.cos(angle), 1200*strength*math.sin(angle), 0)
end, dynamite.x, dynamite.y, 475, "unit")
end
---@class Dynamite
local Dynamite = {
x = nil,
y = nil,
z = nil,
vx = nil,
vy = nil,
vz = nil,
visual = nil,
thrower = nil,
--ALICE
identifier = {"projectile", "dynamite"},
interactions = {
destructable = CAT_DestructableCollisionCheck3D,
self = {
CAT_MoveBallistic,
CAT_CheckTerrainCollision,
CAT_OrientRoll,
CAT_AnimateShadow,
CAT_Decay
}
},
--CAT
onEntityCollision = CAT_EntityBounce3D,
onDestructableCollision = CAT_DestructableBounce3D,
onTerrainCollision = CAT_TerrainBounce,
onExpire = ExplodeDynamite,
collisionRadius = 20,
visualZ = -20,
rollSpeed = 0.89,
lifetime = 8,
friction = 600,
mass = 1,
shadowPath = UNIT_SHADOW_PATH,
shadowWidth = 30,
shadowHeight = 30,
shadowAlpha = 150,
elasticity = 0.35,
}
Dynamite.__index = Dynamite
function Dynamite.create(x, y, z, vx, vy, vz, thrower)
local new = {}
setmetatable(new, Dynamite)
new.x, new.y, new.z = x, y, z
new.vx, new.vy, new.vz = vx, vy, vz
new.visual = AddSpecialEffect("Missile_Dynamite.mdx", x, y)
new.thrower = thrower
BlzSetSpecialEffectZ(new.visual, z)
BlzSetSpecialEffectScale(new.visual, 0.6)
CAT_InitDirectedOrientation(new)
ALICE_Create(new)
end
local function ThrowDynamite()
if GetSpellAbilityId() ~= FourCC("Adyn") then
return
end
local u = GetSpellAbilityUnit()
DestroyEffect(Dynamites[u])
local xo, yo = GetUnitX(u), GetUnitY(u)
local xt, yt = GetSpellTargetX(), GetSpellTargetY()
local angle = math.atan(yt - yo, xt - xo)
xo = xo + 50*math.cos(angle)
yo = yo + 50*math.sin(angle)
local zo = GetTerrainZ(xo, yo) + 50
local zt = GetTerrainZ(xt, yt)
local vx, vy, vz = CAT_GetBallisticLaunchSpeedFromVelocity(xo, yo, zo, xt, yt, zt, 700, true)
Dynamite.create(xo, yo, zo, vx, vy, vz, u)
end
OnInit.global(function()
local trig = CreateTrigger()
TriggerAddAction(trig, ThrowDynamite)
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_SPELL_EFFECT)
end)
end
do
---@class ExplosionForce
local ExplosionForce = {
visual = nil,
--ALICE
identifier = "explosionForce",
interactions = {
self = {
CAT_MoveEffect,
CAT_Decay
}
},
lifetime = 3,
zOffset = -75,
anchor = nil,
--CAT
visualZ = 115,
pressureStrength = 50,
pressureMaxRange = 650
}
ExplosionForce.__index = ExplosionForce
local function ArcaneExplosion()
if GetSpellAbilityId() ~= FourCC("Aaex") then
return
end
local u = GetSpellAbilityUnit()
PlaySoundLocal( "Abilities\\Spells\\Orc\\Voodoo\\BigBadVoodooSpellBirth1.wav", true)
local explosion = {}
explosion.visual = AddSpecialEffect( "CyclonExplosion.mdx" , GetUnitX(u), GetUnitY(u) )
BlzSetSpecialEffectScale(explosion.visual, 1.5)
setmetatable(explosion, ExplosionForce)
explosion.anchor = u
ALICE_Create(explosion)
end
OnInit.global(function()
local trig = CreateTrigger()
TriggerAddAction(trig, ArcaneExplosion)
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_SPELL_EFFECT)
CAT_AddPressure3D(ExplosionForce, {"projectile", "unit"})
end)
end
do
---@class Shell
local Shell = {
x = nil,
y = nil,
z = nil,
vx = nil,
vy = nil,
vz = nil,
visual = nil,
--ALICE
identifier = {"projectile", "shell"},
interactions = {
destructable = CAT_DestructableCollisionCheck3D,
},
selfInteractions = {
CAT_MoveBallistic,
CAT_CheckTerrainCollision,
CAT_OrientProjectile,
CAT_AnimateShadow,
},
--CAT
onDestructableCollision = CAT_DestructableImpact3D,
collisionRadius = 15,
rollSpeed = 3,
mass = 1,
shadowPath = UNIT_SHADOW_PATH,
shadowWidth = 25,
shadowHeight = 25,
shadowAlpha = 150,
elasticity = 0.2,
}
Shell.__index = Shell
function Shell.create(x, y, z, vx, vy, vz)
local new = {}
setmetatable(new, Shell)
new.x, new.y, new.z = x, y, z
new.vx, new.vy, new.vz = vx, vy, vz
new.visual = AddSpecialEffect("Abilities\\Weapons\\CannonTowerMissile\\CannonTowerMissile.mdl", x, y)
BlzSetSpecialEffectZ(new.visual, z)
BlzSetSpecialEffectScale(new.visual, 0.7)
ALICE_Create(new)
end
local function OnAttack()
if not BlzGetEventIsAttack() then
return
end
local source = GetEventDamageSource()
if GetUnitTypeId(source) ~= FourCC("hrif") then
return
end
BlzSetEventDamage(0)
local target = BlzGetEventDamageTarget()
local xo, yo = GetUnitX(source), GetUnitY(source)
local zo = GetTerrainZ(xo, yo) + 50
local xt, yt = GetUnitX(target), GetUnitY(target)
local zt = GetTerrainZ(xt, yt) + 75
xo = xo + 40*math.cos(math.atan(yt - yo, xt - xo))
yo = yo + 40*math.sin(math.atan(yt - yo, xt - xo))
local vx, vy, vz = CAT_GetBallisticLaunchSpeedFromVelocity(xo, yo, zo, xt, yt, zt, 900, false)
if vx then
vx = vx * (1 + 0.05*(1 - 2*math.random()))
vy = vy * (1 + 0.05*(1 - 2*math.random()))
vz = vz * (1 + 0.05*(1 - 2*math.random()))
Shell.create(xo, yo, zo, vx, vy, vz)
end
end
OnInit.global(function()
local trig = CreateTrigger()
TriggerAddAction(trig, OnAttack)
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_DAMAGED)
end)
end
do
local function ReflectProjectile(barrier, shell, x, y, z, normalSpeed, __, __)
local phi, theta = ALICE_PairGetAngle3D()
local shieldEffect = AddSpecialEffect("Abilities\\Spells\\Undead\\ReplenishMana\\ReplenishManaCasterOverhead.mdl", x, y)
BlzSetSpecialEffectZ(shieldEffect, z)
BlzSetSpecialEffectYaw(shieldEffect, phi)
BlzSetSpecialEffectPitch(shieldEffect, -theta + bj_PI/2)
BlzSetSpecialEffectAlpha(shieldEffect, math.min(128, normalSpeed // 2))
BlzSetSpecialEffectScale(shieldEffect, 1.2)
DestroyEffect(shieldEffect)
end
---@class ReflectiveBarrier
ReflectiveBarrier = {
--ALICE
radius = 200,
identifier = "reflectiveBarrier",
interactions = {
projectile = CAT_GizmoCollisionCheck3D
},
bindToOrder = "starfall",
anchor = nil,
--CAT
onGizmoCollision = {
shell = CAT_GizmoBounce3D,
other = CAT_GizmoDevour3D
},
onGizmoCallback = ReflectProjectile,
collisionRadius = 160,
elasticity = 0.2,
mass = 1100,
zOffset = 50
}
ReflectiveBarrier.__index = ReflectiveBarrier
local function CreateReflectiveBarrier()
if GetSpellAbilityId() ~= FourCC("Ashi") then
return
end
local barrier = {}
setmetatable(barrier, ReflectiveBarrier)
local u = GetSpellAbilityUnit()
barrier.anchor = u
PlaySoundLocal("Abilities\\Spells\\Human\\ManaShield\\ManaShieldCaster1.flac", true)
ALICE_Create(barrier)
end
OnInit.global(function()
local trig = CreateTrigger()
TriggerAddAction(trig, CreateReflectiveBarrier)
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_SPELL_EFFECT)
end)
end
do
---@class Missile
local Missile = {
x = nil,
y = nil,
z = nil,
vx = nil,
vy = nil,
vz = nil,
visual = nil,
target = nil,
source = nil,
--ALICE
identifier = {"projectile", "missile"},
interactions = {
destructable = CAT_DestructableCollisionCheck3D,
unit = CAT_UnitCollisionCheck3D,
self = {
CAT_MoveArcedHoming,
CAT_CheckTerrainCollision,
CAT_OrientProjectile,
CAT_AnimateShadow,
}
},
--CAT
collisionRadius = 25,
arc = 0.23,
turnRate = 58,
speed = 440,
mass = 1,
shadowPath = UNIT_SHADOW_PATH,
shadowWidth = 25,
shadowHeight = 25,
shadowAlpha = 150
}
Missile.__index = Missile
function Missile.create(x, y, z, vx, vy, vz, source, target)
local new = {}
setmetatable(new, Missile)
new.x, new.y, new.z = x, y, z
new.vx, new.vy, new.vz = vx, vy, vz
new.visual = AddSpecialEffect("DO_RocketMissile.mdx", x, y)
new.target = target
new.source = source
BlzSetSpecialEffectZ(new.visual, z)
ALICE_Create(new)
end
function Missile:destroy()
BlzSetSpecialEffectZ(self.visual, -2000)
DestroyEffect(self.visual)
local explosion = AddSpecialEffect("Objects\\Spawnmodels\\Other\\NeutralBuildingExplosion\\NeutralBuildingExplosion.mdl", self.x, self.y)
BlzSetSpecialEffectZ(explosion, self.z)
DestroyEffect(explosion)
ALICE_ForAllObjectsInRangeDo(function(object)
local x, y, z = ALICE_GetCoordinates3D(object, ALICE_FindIdentifier("unit", "destructable"))
local dist = math.sqrt((x - self.x)^2 + (y - self.y)^2 + (z - self.z)^2)
if dist < 350 then
if HandleType[object] == "unit" then
UnitDamageTarget(self.source, object, 100*(350 - dist)/350, false, false, ATTACK_TYPE_HERO, DAMAGE_TYPE_MAGIC, WEAPON_TYPE_WHOKNOWS)
else
SetDestructableLife(object, GetDestructableLife(object) - 35*(350 - dist)/350)
end
end
end, self.x, self.y, 350, {"unit", "destructable", MATCHING_TYPE_ANY})
end
local function OnAttack()
if not BlzGetEventIsAttack() then
return
end
local source = GetEventDamageSource()
if GetUnitTypeId(source) ~= FourCC("hfly") then
return
end
BlzSetEventDamage(0)
local target = BlzGetEventDamageTarget()
local xo, yo, zo = GetUnitCoordinates(source)
local xt, yt, zt = GetUnitCoordinates(target)
local dx, dy, dz = xt - xo, yt - yo, zt - zo
local phi = math.atan(dy, dx) + 0.98*(1 - 2*math.random())
local theta = math.atan(dz, math.sqrt(dx^2 + dy^2)) + 0.9*(1 - 2*math.random())
xo = xo + 75*math.cos(phi)*math.cos(theta)
yo = yo + 75*math.sin(phi)*math.cos(theta)
zo = zo + 75*math.sin(theta)
local vx = math.cos(phi)*math.cos(theta)
local vy = math.sin(phi)*math.cos(theta)
local vz = math.sin(theta)
Missile.create(xo, yo, zo, vx, vy, vz, source, target)
end
OnInit.main(function()
local trig = CreateTrigger()
TriggerAddAction(trig, OnAttack)
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_DAMAGED)
end)
end
do
---@class Fireball
local Fireball = {
visual = nil,
--ALICE
identifier = "fireball",
interactions = {
projectile = CAT_GizmoCollisionCheck3D,
self = {
CAT_Move3D,
CAT_Decay,
CAT_OutOfBoundsCheck,
CAT_Orient3D,
CAT_CheckTerrainCollision
}
},
lifetime = 4,
--CAT
collisionRadius = 35,
onGizmoCollision = CAT_GizmoAnnihilate3D,
}
Fireball.__index = Fireball
function Fireball.create(x, y, z, vx, vy, vz)
local new = {}
setmetatable(new, Fireball)
new.x, new.y, new.z = x, y, z
new.vx, new.vy, new.vz = vx, vy, vz
new.visual = AddSpecialEffect("Abilities\\Weapons\\FireBallMissile\\FireBallMissile.mdl", x, y)
BlzSetSpecialEffectZ(new.visual, z)
ALICE_Create(new)
end
local function FireballVolley()
if GetSpellAbilityId() == FourCC("Ahot") then
local u = GetSpellAbilityUnit()
local burn = AddSpecialEffectTarget("Abilities\\Spells\\Other\\ImmolationRed\\ImmolationRedTarget.mdl", u, "chest")
TimerStart(CreateTimer(), 0.1, true, function()
if GetUnitCurrentOrder(u) ~= OrderId("tranquility") then
DestroyEffect(burn)
DestroyTimer(GetExpiredTimer())
end
end)
end
if GetSpellAbilityId() ~= FourCC("Afvl") then
return
end
local u = GetSpellAbilityUnit()
local xu, yu, zu = GetUnitCoordinates(u)
ALICE_ForAllObjectsInRangeDo(function(object)
local x, y, z = ALICE_GetCoordinates3D(object)
local dx, dy, dz = x - xu, y - yu, z - zu
local phi, theta = math.atan(dy, dx), math.atan(dz, math.sqrt(dx*dx + dy*dy))
local xf = xu + 75*math.cos(phi)*math.cos(theta)
local yf = yu + 75*math.sin(phi)*math.cos(theta)
local zf = zu + 75*math.sin(theta)
local vx = 600*math.cos(phi)*math.cos(theta)
local vy = 600*math.sin(phi)*math.cos(theta)
local vz = 600*math.sin(theta)
Fireball.create(xf, yf, zf, vx, vy, vz)
end, xu, yu, 750, "projectile")
end
OnInit.global(function()
local trig = CreateTrigger()
TriggerAddAction(trig, FireballVolley)
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_SPELL_EFFECT)
end)
end
do
local function CreateDust(rock, normalSpeed, __, __)
if normalSpeed > 300/rock.size then
DestroyEffect(AddSpecialEffect("Objects\\Spawnmodels\\Undead\\ImpaleTargetDust\\ImpaleTargetDust.mdl", rock.x, rock.y))
Play3DSound("Abilities\\Weapons\\AncientProtectorMissile\\AncientProtectorMissileHit" .. math.random(1,3) .. ".flac", rock.x, rock.y)
end
end
local function CreateSparksRock(rockA, rockB, x, y, z, normalSpeed, __, __)
if normalSpeed > 500/(math.sqrt(rockA.size*rockB.size)) then
local sparks = AddSpecialEffect("Abilities\\Weapons\\FlyingMachine\\FlyingMachineImpact.mdl", x, y)
BlzSetSpecialEffectZ(sparks, z)
DestroyEffect(sparks)
Play3DSound("Abilities\\Weapons\\AncientProtectorMissile\\AncientProtectorMissileHit" .. math.random(1,3) .. ".flac", x, y)
end
end
local function CreateSparksUnit(rock, unit, x, y, z, normalSpeed, __, __)
if normalSpeed > 600 then
local sparks = DestroyEffect(AddSpecialEffect("Abilities\\Spells\\Orc\\WarStomp\\WarStompCaster.mdl", x, y))
elseif normalSpeed > 200 then
local sparks = AddSpecialEffect("Abilities\\Weapons\\FlyingMachine\\FlyingMachineImpact.mdl", x, y)
BlzSetSpecialEffectZ(sparks, z)
DestroyEffect(sparks)
Play3DSound("Abilities\\Weapons\\AncientProtectorMissile\\AncientProtectorMissileHit" .. math.random(1,3) .. ".flac", x, y)
end
end
---@class Rock
Rock ={
x = nil,
y = nil,
vx = nil,
vy = nil,
vz = nil,
visual = nil,
size = nil,
--ALICE
identifier = "rock",
interactions = {
rock = CAT_GizmoCollisionCheck3D,
unit = CAT_UnitCollisionCheck3D,
tree = CAT_DestructableCollisionCheck3D,
self = {
CAT_MoveBallistic,
CAT_CheckTerrainCollision,
CAT_OutOfBoundsCheck,
CAT_OrientRoll,
CAT_AnimateShadow
}
},
cellCheckInterval = 0.06,
--CAT
onTerrainCollision = CAT_TerrainBounce,
onTerrainCallback = CreateDust,
onGizmoCollision = CAT_GizmoBounce3D,
onGizmoCallback = CreateSparksRock,
onDestructableCollision = CAT_DestructableBounce3D,
onUnitCollision = CAT_UnitBounce3D,
onUnitCallback = CreateSparksUnit,
collisionRadius = nil,
visualZ = 0,
friction = 150,
maxSpeed = 1000,
mass = nil,
shadowWidth = nil,
shadowHeight = nil,
shadowPath = UNIT_SHADOW_PATH,
shadowAlpha = 150,
elasticity = 0.3,
}
local rockMt = {__index = Rock}
---@return Rock
function Rock.create(x, y, vx, vy)
local new = {}
setmetatable(new, rockMt)
new.x = x
new.y = y
new.vx = vx
new.vy = vy
new.size = 0.5 + 2*math.random()
new.visual = AddSpecialEffect("Rock.mdx", new.x, new.y)
BlzSetSpecialEffectScale(new.visual, new.size)
BlzSetSpecialEffectTimeScale(new.visual, 0)
CAT_InitRandomOrientation(new)
new.collisionRadius = 25*new.size
CAT_AutoZ(new)
new.radius = new.collisionRadius + 50
new.mass = 0.5*new.size^3
new.shadowWidth = 60*new.size
new.shadowHeight = 80*new.size
ALICE_Create(new)
return new
end
function ReplaceRock(x, y, __, __)
Rock.create(x, y, 0, 0)
end
end
do
local function JainaCrit(__, jaina)
Play3DSound("Jaina_Crit.mp3", GetUnitX(jaina), GetUnitY(jaina))
end
---@class Hammer
local Hammer = {
x = nil,
y = nil,
z = nil,
vx = nil,
vy = nil,
vz = nil,
visual = nil,
--ALICE
identifier = {"projectile", "hammer"},
interactions = {
destructable = CAT_DestructableCollisionCheck3D,
unit = CAT_UnitCollisionCheck3D,
self = {
CAT_Move3D,
CAT_CheckTerrainCollision,
CAT_Orient3D,
CAT_AnimateShadow,
}
},
cellCheckInterval = 0.02,
--CAT
onUnitCollision = CAT_UnitImpact3D,
onUnitCallback = JainaCrit,
collisionRadius = 40,
mass = 100,
maxSpeed = 2000, --This is used in the collision check functions to determine intervals betwen checks. Does not affect missile velocity.
shadowPath = UNIT_SHADOW_PATH,
shadowWidth = 40,
shadowHeight = 40,
launchOffset = 75
}
Hammer.__index = Hammer
function Hammer.create(x, y, z, vx, vy, vz)
local new = {}
setmetatable(new, Hammer)
new.x, new.y, new.z = x, y, z
new.vx, new.vy, new.vz = vx, vy, vz
new.visual = AddSpecialEffect("Abilities\\Spells\\Human\\StormBolt\\StormBoltMissile.mdl", x, y)
BlzSetSpecialEffectZ(new.visual, z)
BlzSetSpecialEffectColorByPlayer(new.visual, Player(PLAYER_NEUTRAL_PASSIVE))
ALICE_Create(new)
end
local function ThrowHammer()
if GetSpellAbilityId() ~= FourCC("Aham") then
return
end
local caster = GetSpellAbilityUnit()
local target = GetSpellTargetUnit()
local xo, yo, zo = ALICE_GetCoordinates3D(caster)
local xt, yt, zt = ALICE_GetCoordinates3D(target)
local dx, dy, dz = xt - xo, yt - yo, zt - zo + Hammer.collisionRadius
local phi = math.atan(dy, dx)
local theta = math.atan(dz, math.sqrt(dx^2 + dy^2))
--This sets the velocity of the missile.
local vx = 2000*math.cos(phi)*math.cos(theta)
local vy = 2000*math.sin(phi)*math.cos(theta)
local vz = 2000*math.sin(theta)
Hammer.create(xo, yo, zo, vx, vy, vz)
end
OnInit.global(function()
local trig = CreateTrigger()
TriggerAddAction(trig, ThrowHammer)
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_SPELL_EFFECT)
end)
end
if Debug then Debug.beginFile "Machine Gun" end
do
---@class Bullet
local Bullet = {
x = nil,
y = nil,
z = nil,
vx = nil,
vy = nil,
vz = nil,
visual = nil,
source = nil,
--ALICE
identifier = {"projectile", "shell"},
interactions = {
unit = CAT_UnitCollisionCheck3D,
destructable = CAT_DestructableCollisionCheck3D,
self = {
CAT_Move3D,
CAT_CheckTerrainCollision,
CAT_Orient3D,
CAT_OutOfBoundsCheck,
}
},
--CAT
onUnitCollision = CAT_UnitImpact3D,
onUnitDamage = 1000,
onDestructableCollision = CAT_DestructableImpact3D,
onDestructableDamage = 25,
maxSpeed = 2500, --This is used in the collision check functions to determine intervals betwen checks. Does not affect missile velocity.
cellCheckInterval = 0.02,
collisionRadius = 15,
}
Bullet.__index = Bullet
function Bullet.create(x, y, z, phi, source)
local new = {}
setmetatable(new, Bullet)
new.x, new.y, new.z = x, y, z
phi = phi + 0.05*(1 - 2*math.random())
local theta = 0.05*(1 - 2*math.random())
--This sets the velocity of the missile.
new.vx, new.vy, new.vz = 2500*math.cos(phi + 0.17)*math.cos(theta), 2500*math.sin(phi + 0.17)*math.cos(theta), 2500*math.sin(theta)
new.visual = AddSpecialEffect("SMGPellet.mdl", x, y)
new.source = source
local muzzleFlash = AddSpecialEffect("MuzzleFlash.mdl", x, y)
BlzSetSpecialEffectYaw(muzzleFlash, phi)
BlzSetSpecialEffectZ(muzzleFlash, z)
BlzSetSpecialEffectTimeScale(muzzleFlash, 4.0)
DestroyEffect(muzzleFlash)
BlzSetSpecialEffectZ(new.visual, z)
Play3DSound("Units\\Human\\Rifleman\\RiflemanAttack1.flac", x, y)
ALICE_Create(new)
end
local function Shoot(u)
if GetUnitTypeId(u) ~= FourCC("Hakj") then
DestroyTimer(GetExpiredTimer())
return
end
local angle = GetUnitFacing(u)*bj_DEGTORAD
local x, y = GetUnitX(u) + 75*math.cos(angle), GetUnitY(u) + 75*math.sin(angle)
Bullet.create(x, y, GetUnitZ(u) + 70, angle, u)
return 0.1
end
local function InitShoot()
if GetSpellAbilityId() ~= FourCC("Amag") then
return
end
local u = GetSpellAbilityUnit()
TimerStart(CreateTimer(), 1.334, false, function()
local t = ALICE_CallPeriodic(Shoot, 0.1, u)
end)
end
OnInit.global(function()
local trig = CreateTrigger()
TriggerAddAction(trig, InitShoot)
TriggerRegisterAnyUnitEventBJ(trig, EVENT_PLAYER_UNIT_SPELL_EFFECT)
end)
end
---@diagnostic disable: undefined-global
do
function CameraStuff()
local t = CreateTimer()
CinematicFadeBJ( bj_CINEFADETYPE_FADEIN, 2.00, "ReplaceableTextures\\CameraMasks\\Black_mask.blp", 0, 0, 0, 0 )
SetUserControlForceOff( GetPlayersAll() )
CameraSetupApplyForPlayer( true, gg_cam_Camera_1, Player(0), 0 )
CameraSetupApplyForPlayer( true, gg_cam_Camera_2, Player(0), 5.50 )
TimerStart(t, 4.70, false, function()
CinematicFadeBJ( bj_CINEFADETYPE_FADEOUT, 0.50, "ReplaceableTextures\\CameraMasks\\Black_mask.blp", 0, 0, 0, 0 )
TimerStart(t, 0.50, false, function()
CameraSetupApplyForPlayer( true, gg_cam_Camera_3, Player(0), 0 )
CinematicFadeBJ( bj_CINEFADETYPE_FADEIN, 1.00, "ReplaceableTextures\\CameraMasks\\Black_mask.blp", 0, 0, 0, 0 )
TimerStart(t, 3.70, false, function()
CinematicFadeBJ( bj_CINEFADETYPE_FADEOUT, 0.50, "ReplaceableTextures\\CameraMasks\\Black_mask.blp", 0, 0, 0, 0 )
TimerStart(t, 0.50, false, function()
CameraSetupApplyForPlayer( true, gg_cam_Camera_4, Player(0), 0 )
CinematicFadeBJ( bj_CINEFADETYPE_FADEIN, 1.00, "ReplaceableTextures\\CameraMasks\\Black_mask.blp", 0, 0, 0, 0 )
TimerStart(t, 3.20, false, function()
RotateCameraAroundLocBJ( 330.00, GetRectCenter(GetPlayableMapRect()), Player(0), 13.00 )
TimerStart(t, 17.10, false, function()
CinematicFadeBJ( bj_CINEFADETYPE_FADEOUT, 0.50, "ReplaceableTextures\\CameraMasks\\Black_mask.blp", 0, 0, 0, 0 )
TimerStart(t, 0.50, false, function()
CameraSetupApplyForPlayer( true, gg_cam_Camera_5, Player(0), 0 )
CameraSetupApplyForPlayer( true, gg_cam_Camera_6, Player(0), 6.00 )
CinematicFadeBJ( bj_CINEFADETYPE_FADEIN, 0.50, "ReplaceableTextures\\CameraMasks\\Black_mask.blp", 0, 0, 0, 0 )
TimerStart(t, 7.20, false, function()
CameraSetupApplyForPlayer( true, gg_cam_Camera_7, Player(0), 2.50 )
TimerStart(t, 6.70, false, function()
CinematicFadeBJ( bj_CINEFADETYPE_FADEOUT, 0.50, "ReplaceableTextures\\CameraMasks\\Black_mask.blp", 0, 0, 0, 0 )
TimerStart(t, 0.50, false, function()
CameraSetupApplyForPlayer( true, gg_cam_Camera_4, Player(0), 0 )
CinematicFadeBJ( bj_CINEFADETYPE_FADEIN, 0.50, "ReplaceableTextures\\CameraMasks\\Black_mask.blp", 0, 0, 0, 0 )
CameraSetupApplyForPlayer( true, gg_cam_Camera_8, Player(0), 3.5 )
TimerStart(t, 6.95, false, function()
CinematicFadeBJ( bj_CINEFADETYPE_FADEOUT, 0.50, "ReplaceableTextures\\CameraMasks\\Black_mask.blp", 0, 0, 0, 0 )
TimerStart(t, 0.50, false, function()
CameraSetupApplyForPlayer( true, gg_cam_Camera_9, Player(0), 0 )
CinematicFadeBJ( bj_CINEFADETYPE_FADEIN, 1.00, "ReplaceableTextures\\CameraMasks\\Black_mask.blp", 0, 0, 0, 0 )
CameraSetupApplyForPlayer( true, gg_cam_Camera_10, Player(0), 5.0 )
TimerStart(t, 7.4, false, function()
CinematicFadeBJ( bj_CINEFADETYPE_FADEOUT, 0.50, "ReplaceableTextures\\CameraMasks\\Black_mask.blp", 0, 0, 0, 0 )
TimerStart(t, 0.50, false, function()
CameraSetupApplyForPlayer( true, gg_cam_Camera_11, Player(0), 0 )
CinematicFadeBJ( bj_CINEFADETYPE_FADEIN, 0.50, "ReplaceableTextures\\CameraMasks\\Black_mask.blp", 0, 0, 0, 0 )
TimerStart(t, 14.75, false, function()
CinematicFadeBJ( bj_CINEFADETYPE_FADEOUT, 0.50, "ReplaceableTextures\\CameraMasks\\Black_mask.blp", 0, 0, 0, 0 )
TimerStart(t, 0.50, false, function()
CameraSetupApplyForPlayer( true, gg_cam_Camera_12, Player(0), 0 )
CinematicFadeBJ( bj_CINEFADETYPE_FADEIN, 0.50, "ReplaceableTextures\\CameraMasks\\Black_mask.blp", 0, 0, 0, 0 )
TimerStart(t, 5.0, false, function()
CameraSetupApplyForPlayer( true, gg_cam_Camera_13, Player(0), 1.15 )
TimerStart(t, 2.20, false, function()
CameraSetupApplyForPlayer( true, gg_cam_Camera_14, Player(0), 0 )
CinematicFadeBJ( bj_CINEFADETYPE_FADEIN, 0.50, "ReplaceableTextures\\CameraMasks\\Black_mask.blp", 0, 0, 0, 0 )
TimerStart(t, 4.20, false, function()
CameraSetupApplyForPlayer( true, gg_cam_Camera_15, Player(0), 3.0 )
TimerStart(t, 7.0, false, function()
CameraSetupApplyForPlayer( true, gg_cam_Camera_16, Player(0), 4.0 )
end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end)
end
OnInit.final(CameraStuff)
end
if Debug then Debug.beginFile("Video") end
do
local dwarves = nil
local jaina = nil
Dynamites = {}
local function Init()
ALICE_RecognizeFields("size", "thrower")
BlzFrameSetVisible(BlzGetFrameByName("ConsoleUIBackdrop",0), false)
BlzHideOriginFrames(true)
CreateFogModifierRectBJ( true, Player(0), FOG_OF_WAR_VISIBLE, GetPlayableMapRect() )
SetTimeOfDayScale(0)
CAT_GlobalReplace(FourCC("Droc"), "destructable", ReplaceRock)
jaina = CreateUnit(Player(21), FourCC("Hjai"), 0, 0, 90)
dwarves = {}
local posX = {}
local posY = {}
posX[1] = -420
posX[2] = -230
posX[3] = 230
posX[4] = 420
posX[5] = -420
posX[6] = -230
posX[7] = 230
posX[8] = 420
posY[1] = -1150 - 1024
posY[2] = -1340 - 1024
posY[3] = -1340 - 1024
posY[4] = -1150 - 1024
posY[5] = 1150 + 1024
posY[6] = 1340 + 1024
posY[7] = 1340 + 1024
posY[8] = 1150 + 1024
for i = 1, 8 do
dwarves[i] = CreateUnit(Player(PLAYER_NEUTRAL_PASSIVE), FourCC("hrif"), posX[i], posY[i], 0)
end
local t = CreateTimer()
TimerStart(t, 2.0, false, function()
for i = 1, 4 do
IssuePointOrder(dwarves[i], "smart", GetUnitX(dwarves[i]), GetUnitY(dwarves[i]) + 1536)
end
for i = 5, 8 do
IssuePointOrder(dwarves[i], "smart", GetUnitX(dwarves[i]), GetUnitY(dwarves[i]) - 1536)
end
TimerStart(t, 8.0, false, function()
IssueImmediateOrder(jaina, "starfall")
TimerStart(t, 1.5, false, function()
PlaySoundLocal("Units\\Human\\Rifleman\\RiflemanYesAttack1.flac", true)
TimerStart(t, 0.5, false, function()
for i = 1, 8 do
TimerStart(CreateTimer(), math.random(), false, function()
IssueTargetOrder(dwarves[i], "attack", jaina)
end)
end
TimerStart(t, 10, false, function()
CreateFogModifierRectBJ( true, Player(0), FOG_OF_WAR_VISIBLE, GetPlayableMapRect() )
posX[1] = -325
posX[2] = 0
posX[3] = 325
posX[4] = -325
posX[5] = 0
posX[6] = 325
posY[1] = -1245 - 1024
posY[2] = -1340 - 1024
posY[3] = -1245 - 1024
posY[4] = 1245 + 1024
posY[5] = 1340 + 1024
posY[6] = 1245 + 1024
local grenadiers = {}
for i = 1, 6 do
grenadiers[i] = CreateUnit(Player(PLAYER_NEUTRAL_PASSIVE), FourCC("hgre"), posX[i], posY[i], 0)
Dynamites[grenadiers[i]] = AddSpecialEffectTarget("Attachment_Dynamite.mdx", grenadiers[i], "hand")
end
TimerStart(t, 2, false, function()
for i = 1, 8 do
IssueImmediateOrder(dwarves[i], "stop")
end
for i = 1, 3 do
IssuePointOrder(grenadiers[i], "smart", GetUnitX(grenadiers[i]), GetUnitY(grenadiers[i]) + 1280)
end
for i = 4, 6 do
IssuePointOrder(grenadiers[i], "smart", GetUnitX(grenadiers[i]), GetUnitY(grenadiers[i]) - 1280)
end
TimerStart(t, 7.5, false ,function()
PlaySoundLocal("Units\\Human\\Rifleman\\RiflemanYesAttack4.flac", true)
TimerStart(t, 0.5, false ,function()
for i = 1, 6 do
TimerStart(CreateTimer(), math.random(), false, function()
local angle = math.atan(GetUnitY(jaina) - GetUnitY(grenadiers[i]), GetUnitX(jaina) - GetUnitX(grenadiers[i]))
local x = GetUnitX(grenadiers[i]) + 625*math.cos(angle)
local y = GetUnitY(grenadiers[i]) + 625*math.sin(angle)
IssuePointOrder(grenadiers[i], "stampede", x, y)
end)
end
SetUnitFacingTimed(jaina, 270, 0.5)
TimerStart(t, 3.5, false ,function()
SetUnitFacingTimed(jaina, 90, 0.5)
TimerStart(t, 1.5, false ,function()
IssueImmediateOrder(jaina, "roar")
TimerStart(t, 1.6, false, function()
for i = 1,8 do
local angle = math.atan(GetUnitY(dwarves[i]), GetUnitX(dwarves[i]))
local x, y = GetUnitX(dwarves[i]) + 3000*math.cos(angle), GetUnitY(dwarves[i]) + 3000*math.sin(angle)
IssuePointOrder(dwarves[i], "smart", x, y)
end
for i = 1,6 do
local angle = math.atan(GetUnitY(grenadiers[i]), GetUnitX(grenadiers[i]))
local x, y = GetUnitX(grenadiers[i]) + 3000*math.cos(angle), GetUnitY(grenadiers[i]) + 3000*math.sin(angle)
IssuePointOrder(grenadiers[i], "smart", x, y)
end
TimerStart(t, 5.0, false , function()
local gyros = {}
gyros[1] = CreateUnit(Player(PLAYER_NEUTRAL_PASSIVE), FourCC("hfly"), -800, -3000, 0)
gyros[2] = CreateUnit(Player(PLAYER_NEUTRAL_PASSIVE), FourCC("hfly"), 800, -3000, 0)
IssuePointOrder(gyros[1], "smart", -384, -1860)
IssuePointOrder(gyros[2], "smart", 384, -1860)
TimerStart(t, 2.0, false, function()
SetUnitFacingTimed(jaina, 270, 0.5)
for i = 1,4 do
if UnitAlive(dwarves[i]) then
IssueImmediateOrder(dwarves[i], "stop")
SetUnitFacingToFaceUnitTimed(dwarves[i], jaina, 0.5)
end
end
for i = 1,3 do
if UnitAlive(grenadiers[i]) then
IssueImmediateOrder(dwarves[i], "stop")
SetUnitFacingToFaceUnitTimed(grenadiers[i], jaina, 0.5)
end
end
TimerStart(t, 3.0, false, function()
PlaySoundLocal("Units\\Human\\Gyrocopter\\GyrocopterYesAttack1.flac", true)
TimerStart(t, 1.0, false, function()
for i = 1,8 do
if UnitAlive(dwarves[i]) then
local angle = math.atan(GetUnitY(dwarves[i]), GetUnitX(dwarves[i]))
local x, y = GetUnitX(dwarves[i]) - 500*math.cos(angle), GetUnitY(dwarves[i]) - 500*math.sin(angle)
IssuePointOrder(dwarves[i], "smart", x, y)
end
end
for i = 1,6 do
if UnitAlive(grenadiers[i]) then
local angle = math.atan(GetUnitY(grenadiers[i]), GetUnitX(grenadiers[i]))
local x, y = GetUnitX(grenadiers[i]) - 500*math.cos(angle), GetUnitY(grenadiers[i]) - 500*math.sin(angle)
IssuePointOrder(grenadiers[i], "smart", x, y)
end
end
IssueTargetOrder(gyros[1], "attack", jaina)
IssueTargetOrder(gyros[2], "attack", jaina)
TimerStart(t, 1.25, false, function()
IssuePointOrder(jaina, "smart", 0, 1550)
TimerStart(t, 0.55, false, function()
IssueImmediateOrder(gyros[1], "stop")
IssueImmediateOrder(gyros[2], "stop")
TimerStart(t, 4.6, false, function()
SetUnitFacingTimed(jaina, 270, 0.5)
TimerStart(t, 1.0, false, function()
IssuePointOrder(jaina, "blink", 0, 0)
TimerStart(t, 0.5, false, function()
SetUnitFacingTimed(jaina, 90, 0.5)
TimerStart(t, 0.6, false, function()
IssuePointOrder(jaina, "smart", -750, -225)
TimerStart(t, 2.5, false, function()
SetUnitFacingTimed(jaina, 90, 0.5)
TimerStart(t, 1.1, false, function()
IssuePointOrder(jaina, "blink", 250, -450)
TimerStart(t, 0.5, false, function()
IssuePointOrder(jaina, "smart", 600, -380)
TimerStart(t, 1.3, false, function()
SetUnitFacingTimed(jaina, 160, 0.5)
TimerStart(t, 0.7, false, function()
IssuePointOrder(jaina, "blink", 0, 0)
TimerStart(t, 0.5, false, function()
IssuePointOrder(jaina, "smart", -800, 0)
TimerStart(t, 2.5, false, function()
SetUnitFacingTimed(jaina, 330, 0.5)
TimerStart(t , 0.8, false, function()
IssueImmediateOrder(jaina, "tranquility")
TimerStart(t, 1.75, false, function()
IssueImmediateOrder(jaina, "stomp")
TimerStart(t, 4.05, false, function()
IssuePointOrder(jaina, "smart", 0, 0)
TimerStart(t, 0.5, false, function()
local mountainKing = CreateUnit(Player(PLAYER_NEUTRAL_PASSIVE), FourCC("Hmkg"), 0, 2300, 270)
RemoveUnit(gyros[1])
RemoveUnit(gyros[2])
for i = 1,8 do
if UnitAlive(dwarves[i]) then
RemoveUnit(dwarves[i])
end
end
for i = 1,6 do
if UnitAlive(grenadiers[i]) then
RemoveUnit(grenadiers[i])
end
end
TimerStart(t, 2.25, false, function()
SetUnitFacingTimed(jaina, 270, 0.5)
TimerStart(t, 1.85, false, function()
PlaySoundLocal("Units\\Human\\Muradin\\MuradinYesAttack3.flac", true)
TimerStart(t, 1.5, false, function()
IssueTargetOrder(mountainKing, "deathcoil", jaina)
TimerStart(t, 1.0, false, function()
SetUnitFacingTimed(jaina, 90, 0.5)
TimerStart(t, 1.5, false, function()
SetUnitY(mountainKing, 0)
IssuePointOrder(mountainKing, "smart", 0, -1450)
posX[1] = -1850
posX[2] = -2100
posX[3] = -2350
posX[4] = -2600
posX[5] = 1850
posX[6] = 2100
posX[7] = 2350
posX[8] = 2600
posY[1] = -1900
posY[2] = -2000
posY[3] = -2100
posY[4] = -2200
posY[5] = -1900
posY[6] = -2000
posY[7] = -2100
posY[8] = -2200
for i = 1, 8 do
dwarves[i] = CreateUnit(Player(PLAYER_NEUTRAL_PASSIVE), FourCC("hrif"), posX[i], posY[i], 0)
end
for i = 1, 4 do
IssuePointOrder(dwarves[i], "smart", GetUnitX(dwarves[i]) + 1600, GetUnitY(dwarves[i]) + 350)
end
for i = 5, 8 do
IssuePointOrder(dwarves[i], "smart", GetUnitX(dwarves[i]) - 1600, GetUnitY(dwarves[i]) + 350)
end
TimerStart(CreateTimer(), 6.5, false, function()
for i = 1, 8 do
SetUnitFacingToFaceUnitTimed(dwarves[i], jaina, 0.5)
end
end)
TimerStart(t, 0.1, false ,function()
UnitRemoveAbility(jaina, FourCC("Aaex"))
UnitAddAbility(jaina, FourCC("Adiv"))
IssueImmediateOrder(jaina, "roar")
TimerStart(t, 4.4, false, function()
IssuePointOrder(jaina, "smart", 0, -2625)
TimerStart(t, 2.4, false, function()
SetUnitFacingTimed(jaina, 90, 0.5)
TimerStart(t, 0.5, false, function()
IssueTargetOrder(mountainKing, "deathcoil", jaina)
IssueImmediateOrder(jaina, "starfall")
TimerStart(t, 1.25, false, function()
IssueTargetOrder(mountainKing, "deathcoil", jaina)
TimerStart(t, 1.25, false, function()
IssueTargetOrder(mountainKing, "deathcoil", jaina)
TimerStart(t, 1.0, false, function()
IssueImmediateOrder(jaina, "stop")
TimerStart(t, 1.0, false, function()
SetUnitMoveSpeed(jaina, 150)
IssuePointOrder(jaina, "smart", -10, -2425)
TimerStart(t, 2.9, false, function()
SetUnitFacingTimed(jaina, 20, 0.5)
TimerStart(t, 1.25, false, function()
IssueImmediateOrder(jaina, "robogoblin")
PlaySoundLocal("JainaYesAttack2.mp3", true)
TimerStart(t, 1.5, false, function()
SetUnitFacingTimed(jaina, 100, 6.0)
for i = 1, 8 do
IssuePointOrder(dwarves[i], "smart", 0, 2000)
end
IssuePointOrder(mountainKing, "smart", 0, 2000)
TimerStart(t, 6.0, false, function()
SetUnitFacingTimed(jaina, 55, 5.0)
TimerStart(t, 5.0, false, function()
SetUnitFacingTimed(jaina, 100, 5.0)
end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end) end)
end
OnInit.final(Init)
end