Name | Type | is_array | initial_value |
---@diagnostic disable: cast-local-type, undefined-global, param-type-mismatch, undefined-field
do; local _, codeLoc = pcall(error, "", 2) --get line number where DebugUtils begins.
--[[
--------------------------
-- | Debug Utils 2.0a | --
--------------------------
--> https://www.hiveworkshop.com/threads/debug-utils-ingame-console-etc.330758/
- by Eikonium, with special thanks to:
- @Bribe, for pretty table print, showing that xpcall's message handler executes before the stack unwinds and useful suggestions like name caching and stack trace improvements.
- @Jampion, for useful suggestions like print caching and applying Debug.try to all code entry points
- @Luashine, for useful feedback and building "WC3 Debug Console Paste Helper" (https://github.com/Luashine/wc3-debug-console-paste-helper#readme)
- @HerlySQR, for showing a way to get a stack trace in Wc3 (https://www.hiveworkshop.com/threads/lua-getstacktrace.340841/)
- @Macadamia, for showing a way to print warnings upon accessing undeclared globals, where this all started with (https://www.hiveworkshop.com/threads/lua-very-simply-trick-to-help-lua-users-track-syntax-errors.326266/)
-----------------------------------------------------------------------------------------------------------------------------
| Provides debugging utility for Wc3-maps using Lua. |
| |
| Including: |
| 1. Automatic ingame error messages upon running erroneous code from triggers or timers. |
| 2. Ingame Console that allows you to execute code via Wc3 ingame chat. |
| 3. Automatic warnings upon reading undeclared globals (which also triggers after misspelling globals) |
| 4. Debug-Library functions for manual error handling. |
| 5. Caching of loading screen print messages until game start (which simplifies error handling during loading screen) |
| 6. Overwritten tostring/print-functions to show the actual string-name of an object instead of the memory position. |
| 7. Conversion of war3map.lua-error messages to local file error messages. |
| 8. Other useful debug utility (table.print and Debug.wc3Type) |
-----------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| Installation: |
| |
| 1. Copy the code (DebugUtils.lua, StringWidth.lua and IngameConsole.lua) into your map. Use script files (Ctrl+U) in your trigger editor, not text-based triggers! |
| 2. Order the files: DebugUtils above StringWidth above IngameConsole. Make sure they are above ALL other scripts (crucial for local line number feature). |
| 3. Adjust the settings in the settings-section further below to receive the debug environment that fits your needs. |
| |
| Deinstallation: |
| |
| - Debug Utils is meant to provide debugging utility and as such, shall be removed or invalidated from the map closely before release. |
| - Optimally delete the whole Debug library. If that isn't suitable (because you have used library functions at too many places), you can instead replace Debug Utils |
| by the following line of code that will invalidate all Debug functionality (without breaking your code): |
| Debug = setmetatable({try = function(...) return select(2,pcall(...)) end}, {__index = function(t,k) return DoNothing end}); try = Debug.try |
| - If that is also not suitable for you (because your systems rely on the Debug functionality to some degree), at least set ALLOW_INGAME_CODE_EXECUTION to false. |
| - Be sure to test your map thoroughly after removing Debug Utils. |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
* Documentation and API-Functions:
*
* - All automatic functionality provided by Debug Utils can be deactivated using the settings directly below the documentation.
*
* -------------------------
* | Ingame Code Execution |
* -------------------------
* - Debug Utils provides the ability to run code via chat command from within Wc3, if you have conducted step 3 from the installation section.
* - You can either open the ingame console by typing "-console" into the chat, or directly execute code by typing "-exec <code>".
* - See IngameConsole script for further documentation.
*
* ------------------
* | Error Handling |
* ------------------
* - Debug Utils automatically applies error handling (i.e. Debug.try) to code executed by your triggers and timers (error handling means that error messages are printed on screen, if anything doesn't run properly).
* - You can still use the below library functions for manual debugging.
*
* Debug.try(funcToExecute, ...) / try(funcToExecute, ...) -> ...
* - Calls the specified function with the specified parameters in protected mode (i.e. code after Debug.try will continue to run even if the function fails to execute).
* - If the call is successful, returns the specified function's original return values (so p1 = Debug.try(Player, 0) will work fine).
* - If the call is unsuccessful, prints an error message on screen (including stack trace and parameters you have potentially logged before the error occured)
* - By default, the error message consists of a line-reference to war3map.lua (which you can look into by forcing a syntax error in WE or by exporting it from your map via File -> Export Script).
* You can get more helpful references to local script files instead, see section about "Local script references".
* - Example: Assume you have a code line like "func(param1,param2)", which doesn't work and you want to know why.
* Option 1: Change it to "Debug.try(func, param1, param2)", i.e. separate the function from the parameters.
* Option 2: Change it to "Debug.try(function() return func(param1, param2) end)", i.e. pack it into an anonymous function (optionally skip the return statement).
* Debug.log(...)
* - Logs the specified parameters to the Debug-log. The Debug-log will be printed upon the next error being catched by Debug.try, Debug.assert or Debug.throwError.
* - The Debug-log will only hold one set of parameters per code-location. That means, if you call Debug.log() inside any function, only the params saved within the latest call of that function will be kept.
* Debug.throwError(...)
* - Prints an error message including document, line number, stack trace, previously logged parameters and all specified parameters on screen. Parameters can have any type.
* - In contrast to Lua's native error function, this can be called outside of protected mode and doesn't halt code execution.
* Debug.assert(condition:boolean, errorMsg:string, ...) -> ...
* - Prints the specified error message including document, line number, stack trace and previously logged parameters on screen, IF the specified condition fails (i.e. resolves to false/nil).
* - Returns ..., IF the specified condition holds.
* - This works exactly like Lua's native assert, except that it also works outside of protected mode and does not halt code execution.
* Debug.traceback() -> string
* - Returns the stack trace at the position where this is called. You need to manually print it.
* Debug.getLine([depth: integer]) -> integer?
* - Returns the line in war3map.lua, where this function is executed.
* - You can specify a depth d >= 1 to instead return the line, where the d-th function in the stack trace was called. I.e. depth = 2 will return the line of execution of the function that calls Debug.getLine.
* - Due to Wc3's limited stack trace ability, this might sometimes return nil for depth >= 3, so better apply nil-checks on the result.
* Debug.getLocalErrorMsg(errorMsg:string) -> string
* - Takes an error message containing a file and a linenumber and converts war3map.lua-lines to local document lines as defined by uses of Debug.beginFile() and Debug.endFile().
* - Error Msg must be formatted like "<document>:<linenumber><Rest>".
*
* -----------------------------------
* | Warnings for undeclared globals |
* -----------------------------------
* - DebugUtils will print warnings on screen, if you read an undeclared global variable.
* - This is technically the case, when you misspelled on a function name, like calling CraeteUnit instead of CreateUnit.
* - Keep in mind though that the same warning will pop up after reading a global that was intentionally nilled. If you don't like this, turn of this feature in the settings.
*
* -----------------
* | Print Caching |
* -----------------
* - DebugUtils caches print()-calls occuring during loading screen and delays them to after game start.
* - This also applies to loading screen error messages, so you can wrap erroneous parts of your Lua root in Debug.try-blocks and see the message after game start.
*
* -------------------------
* | Local File Stacktrace |
* -------------------------
* - By default, error messages and stack traces printed by the error handling functionality of Debug Utils contain references to war3map.lua (a big file just appending all your local scripts).
* - The Debug-library provides the two functions below to index your local scripts, activating local file names and line numbers (matching those in your IDE) instead of the war3map.lua ones.
* - This allows you to inspect errors within your IDE (VSCode) instead of the World Editor.
*
* Debug.beginFile(fileName: string [, depth: integer])
* - Tells the Debug library that the specified file begins exactly here (i.e. in the line, where this is called).
* - Using this improves stack traces of error messages. "war3map.lua"-references between <here> and the next Debug.endFile() will be converted to file-specific references.
* - All war3map.lua-lines located between the call of Debug.beginFile(fileName) and the next call of Debug.beginFile OR Debug.endFile are treated to be part of "fileName".
* - !!! To be called in the Lua root in Line 1 of every document you wish to track. Line 1 means exactly line 1, before any comment! This way, the line shown in the trace will exactly match your IDE.
* - Depth can be ignored, except if you want to use a custom wrapper around Debug.beginFile(), in which case you need to set the depth parameter to 1 to record the line of the wrapper instead of the line of Debug.beginFile().
* Debug.endFile([depth: integer])
* - Ends the current file that was previously begun by using Debug.beginFile(). War3map.lua-lines after this will not be converted until the next instance of Debug.beginFile().
* - The next call of Debug.beginFile() will also end the previous one, so using Debug.endFile() is optional. Mainly recommended to use, if you prefer to have war3map.lua-references in a certain part of your script (such as within GUI triggers).
* - Depth can be ignored, except if you want to use a custom wrapper around Debug.endFile(), you need to increase the depth parameter to 1 to record the line of the wrapper instead of the line of Debug.endFile().
*
* ----------------
* | Name Caching |
* ----------------
* - DebugUtils overwrites the tostring-function so that it prints the name of a non-primitive object (if available) instead of its memory position. The same applies to print().
* - For instance, print(CreateUnit) will show "function: CreateUnit" on screen instead of "function: 0063A698".
* - The table holding all those names is referred to as "Name Cache".
* - All names of objects in global scope will automatically be added to the Name Cache both within Lua root and again at game start (to get names for overwritten natives and your own objects).
* - New names entering global scope will also automatically be added, even after game start. The same applies to subtables of _G up to a depth of Debug.settings.NAME_CACHE_DEPTH.
* - Objects within subtables will be named after their parent tables and keys. For instance, the name of the function within T = {{bla = function() end}} is "T[1].bla".
* - The automatic adding doesn't work for objects saved into existing variables/keys after game start (because it's based on __newindex metamethod which simply doesn't trigger)
* - You can manually add names to the name cache by using the following API-functions:
*
* Debug.registerName(whichObject:any, name:string)
* - Adds the specified object under the specified name to the name cache, letting tostring and print output "<type>: <name>" going foward.
* - The object must be non-primitive, i.e. this won't work on strings, numbers and booleans.
* - This will overwrite existing names for the specified object with the specified name.
* Debug.registerNamesFrom(parentTable:table [, parentTableName:string] [, depth])
* - Adds names for all values from within the specified parentTable to the name cache.
* - Names for entries will be like "<parentTableName>.<key>" or "<parentTableName>[<key>]" (depending on the key type), using the existing name of the parentTable from the name cache.
* - You can optionally specify a parentTableName to use that for the entry naming instead of the existing name. Doing so will also register that name for the parentTable, if it doesn't already has one.
* - Specifying the empty string as parentTableName will suppress it in the naming and just register all values as "<key>". Note that only string keys will be considered this way.
* - In contrast to Debug.registerName(), this function will NOT overwrite existing names, but just add names for new objects.
* Debug.oldTostring(object:any) -> string
* - The old tostring-function in case you still need outputs like "function: 0063A698".
*
* -----------------
* | Other Utility |
* -----------------
*
* Debug.wc3Type(object:any) -> string
* - Returns the Warcraft3-type of the input object. E.g. Debug.wc3Type(Player(0)) will return "player".
* - Returns type(object), if used on Lua-objects.
* table.tostring(whichTable [, depth:integer] [, pretty_yn:boolean])
* - Creates a list of all (key,value)-pairs from the specified table. Also lists subtable entries up to the specified depth (unlimited, if not specified).
* - E.g. for T = {"a", 5, {7}}, table.tostring(T) would output '{(1, "a"), (2, 5), (3, {(1, 7)})}' (if using concise style, i.e. pretty_yn being nil or false).
* - Not specifying a depth can potentially lead to a stack overflow for self-referential tables (e.g X = {}; X[1] = X). Choose a sensible depth to prevent this (in doubt start with 1 and test upwards).
* - Supports pretty style by setting pretty_yn to true. Pretty style is linebreak-separated, uses indentations and has other visual improvements. Use it on small tables only, because Wc3 can't show that many linebreaks at once.
* - All of the following is valid syntax: table.tostring(T), table.tostring(T, depth), table.tostring(T, pretty_yn) or table.tostring(T, depth, pretty_yn).
* - table.tostring is not multiplayer-synced.
* table.print(whichTable [, depth:integer] [, pretty_yn:boolean])
* - Prints table.tostring(...).
*
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------]]
----------------
--| Settings |--
----------------
Debug = {
--BEGIN OF SETTINGS--
settings = {
SHOW_TRACE_ON_ERROR = true ---Set to true to show a stack trace on every error in addition to the regular message (msg sources: automatic error handling, Debug.try, Debug.throwError, ...)
, USE_TRY_ON_TRIGGERADDACTION = true ---Set to true for automatic error handling on TriggerAddAction (applies Debug.try on every trigger action).
, USE_TRY_ON_CONDITION = true ---Set to true for automatic error handling on boolexpressions created via Condition() or Filter() (essentially applies Debug.try on every trigger condition).
, USE_TRY_ON_TIMERSTART = true ---Set to true for automatic error handling on TimerStart (applies Debug.try on every timer callback).
, USE_TRY_ON_COROUTINES = true ---Set to true for improved stack traces on errors within coroutines (applies Debug.try on coroutine.create and coroutine.wrap). This lets stack traces point to the erroneous function executed within the coroutine (instead of the function creating the coroutine).
, ALLOW_INGAME_CODE_EXECUTION = true ---Set to true to enable IngameConsole and -exec command.
, WARNING_FOR_UNDECLARED_GLOBALS = false ---Set to true to print warnings upon accessing undeclared globals (i.e. globals with nil-value). This is technically the case after having misspelled on a function name (like CraeteUnit instead of CreateUnit).
, SHOW_TRACE_FOR_UNDECLARED_GLOBALS = false ---Set to true to include a stack trace into undeclared global warnings. Only takes effect, if WARNING_FOR_UNDECLARED_GLOBALS is also true.
, USE_PRINT_CACHE = true ---Set to true to let print()-calls during loading screen be cached until the game starts.
, PRINT_DURATION = nil ---Adjust the duration in seconds that values printed by print() last on screen. Set to nil to use default duration (which depends on string length).
, USE_NAME_CACHE = true ---Set to true to let tostring/print output the string-name of an object instead of its memory location (except for booleans/numbers/strings). E.g. print(CreateUnit) will output "function: CreateUnit" instead of "function: 0063A698".
, AUTO_REGISTER_NEW_NAMES = true ---Automatically adds new names from global scope (and subtables of _G up to NAME_CACHE_DEPTH) to the name cache by adding metatables with the __newindex metamethod to ALL tables accessible from global scope.
, NAME_CACHE_DEPTH = 0 ---Set to 0 to only affect globals. Experimental feature: Set to an integer > 0 to also cache names for subtables of _G (up to the specified depth). Warning: This will alter the __newindex metamethod of subtables of _G (but not break existing functionality).
}
--END OF SETTINGS--
--START OF CODE--
, data = {
nameCache = {} ---@type table<any,string> contains the string names of any object in global scope (random for objects that have multiple names)
, nameCacheMirror = {} ---@type table<string,any> contains the (name,object)-pairs of all objects in the name cache. Used to prevent name duplicates that might otherwise occur upon reassigning globals.
, nameDepths = {} ---@type table<any,integer> contains the depth of the name used by by any object in the name cache (i.e. the depth within the parentTable).
, autoIndexedTables = {} ---@type table<table,boolean> contains (t,true), if DebugUtils already set a __newindex metamethod for name caching in t. Prevents double application.
, paramLog = {} ---@type table<string,string> saves logged information per code location. to be filled by Debug.log(), to be printed by Debug.try()
, sourceMap = {{firstLine= 1,file='DebugUtils'}} ---@type table<integer,{firstLine:integer,file:string,lastLine?:integer}> saves lines and file names of all documents registered via Debug.beginFile().
, printCache = {n=0} ---@type string[] contains the strings that were attempted to print during loading screen.
}
}
--localization
local settings, paramLog, nameCache, nameDepths, autoIndexedTables, nameCacheMirror, sourceMap, printCache = Debug.settings, Debug.data.paramLog, Debug.data.nameCache, Debug.data.nameDepths, Debug.data.autoIndexedTables, Debug.data.nameCacheMirror, Debug.data.sourceMap, Debug.data.printCache
--Write DebugUtils first line number to sourceMap:
---@diagnostic disable-next-line: need-check-nil
Debug.data.sourceMap[1].firstLine = tonumber(codeLoc:match(":\x25d+"):sub(2,-1))
-------------------------------------------------
--| File Indexing for local Error Msg Support |--
-------------------------------------------------
-- Functions for war3map.lua -> local file conversion for error messages.
---Returns the line number in war3map.lua, where this is called (for depth = 0).
---Choose a depth > 0 to instead return the line, where the corresponding function in the stack leading to this call is executed.
---@param depth? integer default: 0.
---@return number?
function Debug.getLine(depth)
depth = depth or 0
local _, location = pcall(error, "", depth + 3) ---@diagnostic disable-next-line: need-check-nil
local line = location:match(":\x25d+") --extracts ":1000" from "war3map.lua:1000:..."
return tonumber(line and line:sub(2,-1)) --check if line is nil before applying string.sub to prevent errors (nil can result from string.match above, although it should never do so in our case)
end
---Tells the Debug library that the specified file begins exactly here (i.e. in the line, where this is called).
---
---Using this improves stack traces of error messages. Stack trace will have "war3map.lua"-references between this and the next Debug.endFile() converted to file-specific references.
---
---To be called in the Lua root in Line 1 of every file you wish to track! Line 1 means exactly line 1, before any comment! This way, the line shown in the trace will exactly match your IDE.
---
---If you want to use a custom wrapper around Debug.beginFile(), you need to increase the depth parameter to 1 to record the line of the wrapper instead of the line of Debug.beginFile().
---@param fileName string
---@param depth? integer default: 0. Set to 1, if you call this from a wrapper (and use the wrapper in line 1 of every document).
---@param lastLine? integer Ignore this. For compatibility with Total Initialization.
function Debug.beginFile(fileName, depth, lastLine)
depth, fileName = depth or 0, fileName or '' --filename is not actually optional, we just default to '' to prevent crashes.
local line = Debug.getLine(depth + 1)
if line then --for safety reasons. we don't want to add a non-existing line to the sourceMap
table.insert(sourceMap, {firstLine = line, file = fileName, lastLine = lastLine}) --automatically sorted list, because calls of Debug.beginFile happen logically in the order of the map script.
end
end
---Tells the Debug library that the file previously started with Debug.beginFile() ends here.
---This is in theory optional to use, as the next call of Debug.beginFile will also end the previous. Still good practice to always use this in the last line of every file.
---If you want to use a custom wrapper around Debug.endFile(), you need to increase the depth parameter to 1 to record the line of the wrapper instead of the line of Debug.endFile().
---@param depth? integer
function Debug.endFile(depth)
depth = depth or 0
local line = Debug.getLine(depth + 1)
sourceMap[#sourceMap].lastLine = line
end
---Takes an error message containing a file and a linenumber and converts both to local file and line as saved to Debug.sourceMap.
---@param errorMsg string must be formatted like "<document>:<linenumber><RestOfMsg>".
---@return string convertedMsg a string of the form "<localDocument>:<localLinenumber><RestOfMsg>"
function Debug.getLocalErrorMsg(errorMsg)
local startPos, endPos = errorMsg:find(":\x25d*") --start and end position of line number. The part before that is the document, part after the error msg.
if startPos and endPos then --can be nil, if input string was not of the desired form "<document>:<linenumber><RestOfMsg>".
local document, line, rest = errorMsg:sub(1, startPos), tonumber(errorMsg:sub(startPos+1, endPos)), errorMsg:sub(endPos+1, -1) --get error line in war3map.lua
if document == 'war3map.lua:' and line then --only convert war3map.lua-references to local position. Other files such as Blizzard.j.lua are not converted (obiously).
for i = #sourceMap, 1, -1 do --find local file containing the war3map.lua error line.
if line >= sourceMap[i].firstLine then --war3map.lua line is part of sourceMap[i].file
if not sourceMap[i].lastLine or line <= sourceMap[i].lastLine then --if lastLine is given, we must also check for it
return sourceMap[i].file .. ":" .. (line - sourceMap[i].firstLine + 1) .. rest
else --if line is larger than firstLine and lastLine of sourceMap[i], it is not part of a tracked file -> return global war3map.lua position.
break --prevent return within next step of the loop ("line >= sourceMap[i].firstLine" would be true again, but wrong file)
end
end
end
end
end
return errorMsg
end
local convertToLocalErrorMsg = Debug.getLocalErrorMsg
----------------------
--| Error Handling |--
----------------------
local concat
---Applies tostring() on all input params and concatenates them 4-space-separated.
---@param firstParam any
---@param ... any
---@return string
concat = function(firstParam, ...)
if select('#', ...) == 0 then
return tostring(firstParam)
end
return tostring(firstParam) .. ' ' .. concat(...)
end
---Returns the stack trace between the specified startDepth and endDepth.
---The trace lists file names and line numbers. File name is only listed, if it has changed from the previous traced line.
---The previous file can also be specified as an input parameter to suppress the first file name in case it's identical.
---@param startDepth integer
---@param endDepth integer
---@return string trace
local function getStackTrace(startDepth, endDepth)
local trace, separator = "", ""
local _, lastFile, tracePiece, lastTracePiece
for loopDepth = startDepth, endDepth do --get trace on different depth level
_, tracePiece = pcall(error, "", loopDepth) ---@type boolean, string
tracePiece = convertToLocalErrorMsg(tracePiece)
if #tracePiece > 0 and lastTracePiece ~= tracePiece then --some trace pieces can be empty, but there can still be valid ones beyond that
trace = trace .. separator .. ((tracePiece:match("^.-:") == lastFile) and tracePiece:match(":\x25d+"):sub(2,-1) or tracePiece:match("^.-:\x25d+"))
lastFile, lastTracePiece, separator = tracePiece:match("^.-:"), tracePiece, " <- "
end
end
return trace
end
---Message Handler to be used by the try-function below.
---Adds stack trace plus formatting to the message and prints it.
---@param errorMsg string
---@param startDepth? integer default: 4 for use in xpcall
local function errorHandler(errorMsg, startDepth)
startDepth = startDepth or 4 --xpcall doesn't specify this param, so it defaults to 4 in this case
errorMsg = convertToLocalErrorMsg(errorMsg)
--Print original error message and stack trace.
print("|cffff5555ERROR at " .. errorMsg .. "|r")
if settings.SHOW_TRACE_ON_ERROR then
print("|cffff5555Traceback (most recent call first):|r")
print("|cffff5555" .. getStackTrace(startDepth,200) .. "|r")
end
--Also print entries from param log, if there are any.
for location, loggedParams in pairs(paramLog) do
print("|cff888888Logged at " .. convertToLocalErrorMsg(location) .. loggedParams .. "|r")
paramLog[location] = nil
end
end
---Tries to execute the specified function with the specified parameters in protected mode and prints an error message (including stack trace), if unsuccessful.
---
---Example use: Assume you have a code line like "CreateUnit(0,1,2)", which doesn't work and you want to know why.
---* Option 1: Change it to "Debug.try(CreateUnit, 0, 1, 2)", i.e. separate the function from the parameters.
---* Option 2: Change it to "Debug.try(function() return CreateUnit(0,1,2) end)", i.e. pack it into an anonymous function. You can skip the "return", if you don't need the return values.
---When no error occured, the try-function will return all values returned by the input function.
---When an error occurs, try will print the resulting error and stack trace.
---@param funcToExecute function the function to call in protected mode
---@param ... any params for the input-function
---@return ... any
function Debug.try(funcToExecute, ...)
return select(2, xpcall(funcToExecute, errorHandler,...))
end
try = Debug.try
---Prints "ERROR:" and the specified error objects on the Screen. Also prints the stack trace leading to the error. You can specify as many arguments as you wish.
---
---In contrast to Lua's native error function, this can be called outside of protected mode and doesn't halt code execution.
---@param ... any objects/errormessages to be printed (doesn't have to be strings)
function Debug.throwError(...)
errorHandler(getStackTrace(4,4) .. ": " .. concat(...), 5)
end
---Prints the specified error message, if the specified condition fails (i.e. if it resolves to false or nil).
---
---Returns all specified arguments after the errorMsg, if the condition holds.
---
---In contrast to Lua's native assert function, this can be called outside of protected mode and doesn't halt code execution (even in case of condition failure).
---@param condition any actually a boolean, but you can use any object as a boolean.
---@param errorMsg string the message to be printed, if the condition fails
---@param ... any will be returned, if the condition holds
function Debug.assert(condition, errorMsg, ...)
if condition then
return ...
else
errorHandler(getStackTrace(4,4) .. ": " .. errorMsg, 5)
end
end
---Returns the stack trace at the code position where this function is called.
---The returned string includes war3map.lua/blizzard.j.lua code positions of all functions from the stack trace in the order of execution (most recent call last). It does NOT include function names.
---@return string
function Debug.traceback()
return getStackTrace(3,200)
end
---Saves the specified parameters to the debug log at the location where this function is called. The Debug-log will be printed for all affected locations upon the try-function catching an error.
---The log is unique per code location: Parameters logged at code line x will overwrite the previous ones logged at x. Parameters logged at different locations will all persist and be printed.
---@param ... any save any information, for instance the parameters of the function call that you are logging.
function Debug.log(...)
local _, location = pcall(error, "", 3) ---@diagnostic disable-next-line: need-check-nil
paramLog[location or ''] = concat(...)
end
------------------------------------
--| Name Caching (API-functions) |--
------------------------------------
--Help-table. The registerName-functions below shall not work on call-by-value-types, i.e. booleans, strings and numbers (renaming a value of any primitive type doesn't make sense).
local skipType = {boolean = true, string = true, number = true, ['nil'] = true}
--Set weak keys to nameCache and nameDepths and weak values for nameCacheMirror to prevent garbage collection issues
setmetatable(nameCache, {__mode = 'k'})
setmetatable(nameDepths, getmetatable(nameCache))
setmetatable(nameCacheMirror, {__mode = 'v'})
---Removes the name from the name cache, if already used for any object (freeing it for the new object). This makes sure that a name is always unique.
---This doesn't solve the
---@param name string
local function removeNameIfNecessary(name)
if nameCacheMirror[name] then
nameCache[nameCacheMirror[name]] = nil
nameCacheMirror[name] = nil
end
end
---Registers a name for the specified object, which will be the future output for tostring(whichObject).
---You can overwrite existing names for whichObject by using this.
---@param whichObject any
---@param name string
function Debug.registerName(whichObject, name)
if not skipType[type(whichObject)] then
removeNameIfNecessary(name)
nameCache[whichObject] = name
nameCacheMirror[name] = whichObject
nameDepths[name] = 0
end
end
---Registers a new name to the nameCache as either just <key> (if parentTableName is the empty string), <table>.<key> (if parentTableName is given and string key doesn't contain whitespace) or <name>[<key>] notation (for other keys in existing tables).
---Only string keys without whitespace support <key>- and <table>.<key>-notation. All other keys require a parentTableName.
---@param parentTableName string | '""' empty string suppresses <table>-affix.
---@param key any
---@param object any only call-be-ref types allowed
---@param parentTableDepth? integer
local function addNameToCache(parentTableName, key, object, parentTableDepth)
parentTableDepth = parentTableDepth or -1
--Don't overwrite existing names for the same object, don't add names for primitive types.
if nameCache[object] or skipType[type(object)] then
return
end
local name
--apply dot-syntax for string keys without whitespace
if type(key) == 'string' and not string.find(key, "\x25s") then
if parentTableName == "" then
name = key
nameDepths[object] = 0
else
name = parentTableName .. "." .. key
nameDepths[object] = parentTableDepth + 1
end
--apply bracket-syntax for all other keys. This requires a parentTableName.
elseif parentTableName ~= "" then
name = type(key) == 'string' and ('"' .. key .. '"') or key
name = parentTableName .. "[" .. tostring(name) .. "]"
nameDepths[object] = parentTableDepth + 1
end
--Stop in cases without valid name (like parentTableName = "" and key = [1])
if name then
removeNameIfNecessary(name)
nameCache[object] = name
nameCacheMirror[name] = object
end
end
---Registers all call-by-reference objects in the given parentTable to the nameCache.
---Automatically filters out primitive objects and already registed Objects.
---@param parentTable table
---@param parentTableName? string
local function registerAllObjectsInTable(parentTable, parentTableName)
parentTableName = parentTableName or nameCache[parentTable] or ""
--Register all call-by-ref-objects in parentTable
for key, object in pairs(parentTable) do
addNameToCache(parentTableName, key, object, nameDepths[parentTable])
end
end
---Adds names for all values of the specified parentTable to the name cache. Names will be "<parentTableName>.<key>" or "<parentTableName>[<key>]", depending on the key type.
---
---Example: Given a table T = {f = function() end, [1] = {}}, tostring(T.f) and tostring(T[1]) will output "function: T.f" and "table: T[1]" respectively after running Debug.registerNamesFrom(T).
---The name of T itself must either be specified as an input parameter OR have previously been registered. It can also be suppressed by inputting the empty string (so objects will just display by their own names).
---The names of objects in global scope are automatically registered during loading screen.
---@param parentTable table base table of which all entries shall be registered (in the Form parentTableName.objectName).
---@param parentTableName? string|'""' Nil: takes <parentTableName> as previously registered. Empty String: Skips <parentTableName> completely. String <s>: Objects will show up as "<s>.<objectName>".
---@param depth? integer objects within sub-tables up to the specified depth will also be added. Default: 1 (only elements of whichTable). Must be >= 1.
---@overload fun(parentTable:table, depth:integer)
function Debug.registerNamesFrom(parentTable, parentTableName, depth)
--Support overloaded definition fun(parentTable:table, depth:integer)
if type(parentTableName) == 'number' then
depth = parentTableName
parentTableName = nil
end
--Apply default values
depth = depth or 1
parentTableName = parentTableName or nameCache[parentTable] or ""
--add name of T in case it hasn't already
if not nameCache[parentTable] and parentTableName ~= "" then
Debug.registerName(parentTable, parentTableName)
end
--Register all call-by-ref-objects in parentTable. To be preferred over simple recursive approach to ensure that top level names are preferred.
registerAllObjectsInTable(parentTable, parentTableName)
--if depth > 1 was specified, also register Names from subtables.
if depth > 1 then
for _, object in pairs(parentTable) do
if type(object) == 'table' then
Debug.registerNamesFrom(object, nil, depth - 1)
end
end
end
end
-------------------------------------------
--| Name Caching (Loading Screen setup) |--
-------------------------------------------
---Registers all existing object names from global scope and Lua incorporated libraries to be used by tostring() overwrite below.
local function registerNamesFromGlobalScope()
--Add all names from global scope to the name cache.
Debug.registerNamesFrom(_G, "")
--Add all names of Warcraft-enabled Lua libraries as well:
--Could instead add a depth to the function call above, but we want to ensure that these libraries are added even if the user has chosen depth 0.
for _, lib in ipairs({coroutine, math, os, string, table, utf8, Debug}) do
Debug.registerNamesFrom(lib)
end
--Add further names that are not accessible from global scope:
--Player(i)
for i = 0, GetBJMaxPlayerSlots() - 1 do
Debug.registerName(Player(i), "Player(" .. i .. ")")
end
end
--Set empty metatable to _G. __index is added when game starts (for "attempt to read undeclared global"-errors), __newindex is added right below (for building the name cache).
setmetatable(_G, getmetatable(_G) or {}) --getmetatable(_G) should always return nil provided that DebugUtils is the topmost script file in the trigger editor, but we still include this for safety-
-- Save old tostring into Debug Library before overwriting it.
Debug.oldTostring = tostring
if settings.USE_NAME_CACHE then
local oldTostring = tostring
tostring = function(obj) --new tostring(CreateUnit) prints "function: CreateUnit"
--tostring of non-primitive object is NOT guaranteed to be like "<type>:<hex>", because it might have been changed by some __tostring-metamethod.
if settings.USE_NAME_CACHE then --return names from name cache only if setting is enabled. This allows turning it off during runtime (via Ingame Console) to revert to old tostring.
return nameCache[obj] and ((oldTostring(obj):match("^.-: ") or (oldTostring(obj) .. ": ")) .. nameCache[obj]) or oldTostring(obj)
end
return Debug.oldTostring(obj)
end
--Add names to Debug.data.objectNames within Lua root. Called below the other Debug-stuff to get the overwritten versions instead of the original ones.
registerNamesFromGlobalScope()
--Prepare __newindex-metamethod to automatically add new names to the name cache
if settings.AUTO_REGISTER_NEW_NAMES then
local nameRegisterNewIndex
---__newindex to be used for _G (and subtables up to a certain depth) to automatically register new names to the nameCache.
---Tables in global scope will use their own name. Subtables of them will use <parentName>.<childName> syntax.
---Global names don't support container[key]-notation (because "_G[...]" is probably not desired), so we only register string type keys instead of using prettyTostring.
---@param t table
---@param k any
---@param v any
---@param skipRawset? boolean set this to true when combined with another __newindex. Suppresses rawset(t,k,v) (because the other __newindex is responsible for that).
nameRegisterNewIndex = function(t,k,v, skipRawset)
local parentDepth = nameDepths[t] or 0
--Make sure the parent table has an existing name before using it as part of the child name
if t == _G or nameCache[t] then
local existingName = nameCache[v]
if not existingName then
addNameToCache((t == _G and "") or nameCache[t], k, v, parentDepth)
end
--If v is a table and the parent table has a valid name, inherit __newindex to v's existing metatable (or create a new one), if that wasn't already done.
if type(v) == 'table' and nameDepths[v] < settings.NAME_CACHE_DEPTH then
if not existingName then
--If v didn't have a name before, also add names for elements contained in v by construction (like v = {x = function() end} ).
Debug.registerNamesFrom(v, settings.NAME_CACHE_DEPTH - nameDepths[v])
end
--Apply __newindex to new tables.
if not autoIndexedTables[v] then
autoIndexedTables[v] = true
local mt = getmetatable(v)
if not mt then
mt = {}
setmetatable(v, mt) --only use setmetatable when we are sure there wasn't any before to prevent issues with "__metatable"-metamethod.
end
local existingNewIndex = mt.__newindex
local isTable_yn = (type(existingNewIndex) == 'table')
--If mt has an existing __newindex, add the name-register effect to it (effectively create a new __newindex using the old)
if existingNewIndex then
mt.__newindex = function(t,k,v)
nameRegisterNewIndex(t,k,v, true) --setting t[k] = v might not be desired in case of existing newindex. Skip it and let existingNewIndex make the decision.
if isTable_yn then
existingNewIndex[k] = v
else
return existingNewIndex(t,k,v)
end
end
else
--If mt doesn't have an existing __newindex, add one that adds the object to the name cache.
mt.__newindex = nameRegisterNewIndex
end
end
end
end
--Set t[k] = v.
if not skipRawset then
rawset(t,k,v)
end
end
--Apply metamethod to _G.
local existingNewIndex = getmetatable(_G).__newindex --should always be nil provided that DebugUtils is the topmost script in your trigger editor. Still included for safety.
local isTable_yn = (type(existingNewIndex) == 'table')
if existingNewIndex then
getmetatable(_G).__newindex = function(t,k,v)
nameRegisterNewIndex(t,k,v, true)
if isTable_yn then
existingNewIndex[k] = v
else
existingNewIndex(t,k,v)
end
end
else
getmetatable(_G).__newindex = nameRegisterNewIndex
end
end
end
------------------------------------------------------
--| Native Overwrite for Automatic Error Handling |--
------------------------------------------------------
--A table to store the try-wrapper for each function. This avoids endless re-creation of wrapper functions within the hooks below.
--Weak keys ensure that garbage collection continues as normal.
local tryWrappers = setmetatable({}, {__mode = 'k'}) ---@type table<function,function>
local try = Debug.try
---Takes a function and returns a wrapper executing the same function within Debug.try.
---Wrappers are permanently stored (until the original function is garbage collected) to ensure that they don't have to be created twice for the same function.
---@param func? function
---@return function
local function getTryWrapper(func)
if func then
tryWrappers[func] = tryWrappers[func] or function(...) return try(func, ...) end
end
return tryWrappers[func] --returns nil for func = nil (important for TimerStart overwrite below)
end
--Overwrite TriggerAddAction, TimerStart, Condition and Filter natives to let them automatically apply Debug.try.
--Also overwrites coroutine.create and coroutine.wrap to let stack traces point to the function executed within instead of the function creating the coroutine.
if settings.USE_TRY_ON_TRIGGERADDACTION then
local originalTriggerAddAction = TriggerAddAction
TriggerAddAction = function(whichTrigger, actionFunc)
return originalTriggerAddAction(whichTrigger, getTryWrapper(actionFunc))
end
end
if settings.USE_TRY_ON_TIMERSTART then
local originalTimerStart = TimerStart
TimerStart = function(whichTimer, timeout, periodic, handlerFunc)
originalTimerStart(whichTimer, timeout, periodic, getTryWrapper(handlerFunc))
end
end
if settings.USE_TRY_ON_CONDITION then
local originalCondition = Condition
Condition = function(func)
return originalCondition(getTryWrapper(func))
end
Filter = Condition
end
if settings.USE_TRY_ON_COROUTINES then
local originalCoroutineCreate = coroutine.create
---@diagnostic disable-next-line: duplicate-set-field
coroutine.create = function(f)
return originalCoroutineCreate(getTryWrapper(f))
end
local originalCoroutineWrap = coroutine.wrap
---@diagnostic disable-next-line: duplicate-set-field
coroutine.wrap = function(f)
return originalCoroutineWrap(getTryWrapper(f))
end
end
------------------------------------------
--| Cache prints during Loading Screen |--
------------------------------------------
-- Apply the duration as specified in the settings.
if settings.PRINT_DURATION then
local display, getLocalPlayer, dur = DisplayTimedTextToPlayer, GetLocalPlayer, settings.PRINT_DURATION
print = function(...)
display(getLocalPlayer(), 0, 0, dur, concat(...))
end
end
-- Delay loading screen prints to after game start.
if settings.USE_PRINT_CACHE then
local oldPrint = print
--loading screen print will write the values into the printCache
print = function(...)
if bj_gameStarted then
oldPrint(...)
else --during loading screen only: concatenate input arguments 4-space-separated, implicitely apply tostring on each, cache to table
printCache.n = printCache.n + 1
printCache[printCache.n] = concat(...)
end
end
end
-------------------------
--| Modify Game Start |--
-------------------------
local originalMarkGameStarted = MarkGameStarted
--Hook certain actions into the start of the game.
MarkGameStarted = function()
originalMarkGameStarted()
if settings.WARNING_FOR_UNDECLARED_GLOBALS then
local existingIndex = getmetatable(_G).__index
local isTable_yn = (type(existingIndex) == 'table')
getmetatable(_G).__index = function(t, k) --we made sure that _G has a metatable further above.
--if string.sub(tostring(k),1,3) ~= 'bj_' then
print("Trying to read undeclared global at " .. getStackTrace(4,4) .. ": " .. tostring(k)
.. (settings.SHOW_TRACE_FOR_UNDECLARED_GLOBALS and "\nTraceback (most recent call first):\n" .. getStackTrace(4,200) or ""))
--end
if existingIndex then
if isTable_yn then
return existingIndex[k]
end
return existingIndex(t,k)
end
return rawget(t,k)
end
end
--Add names to Debug.data.objectNames again to ensure that overwritten natives also make it to the name cache.
--Overwritten natives have a new value, but the old key, so __newindex didn't trigger. But we can be sure that objectNames[v] doesn't yet exist, so adding again is safe.
if settings.USE_NAME_CACHE then
for _,v in pairs(_G) do
nameCache[v] = nil
end
registerNamesFromGlobalScope()
end
--Print messages that have been cached during loading screen.
if settings.USE_PRINT_CACHE then
--Note that we don't restore the old print. The overwritten variant only applies caching behaviour to loading screen prints anyway and "unhooking" always adds other risks.
for _, str in ipairs(printCache) do
print(str)
end
printCache = nil --frees reference for the garbage collector
end
--Create triggers listening to "-console" and "-exec" chat input.
if settings.ALLOW_INGAME_CODE_EXECUTION and IngameConsole then
IngameConsole.createTriggers()
end
end
---------------------
--| Other Utility |--
---------------------
do
---Returns the type of a warcraft object as string, e.g. "unit" upon inputting a unit.
---@param input any
---@return string
function Debug.wc3Type(input)
local typeString = type(input)
if typeString == 'userdata' then
typeString = tostring(input) --tostring returns the warcraft type plus a colon and some hashstuff.
return typeString:sub(1, (typeString:find(":", nil, true) or 0) -1) --string.find returns nil, if the argument is not found, which would break string.sub. So we need to replace by 0.
else
return typeString
end
end
Wc3Type = Debug.wc3Type --for backwards compatibility
local conciseTostring, prettyTostring
---Translates a table into a comma-separated list of its (key,value)-pairs. Also translates subtables up to the specified depth.
---E.g. {"a", 5, {7}} will display as '{(1, "a"), (2, 5), (3, {(1, 7)})}'.
---@param object any
---@param depth? integer default: unlimited. Unlimited depth will throw a stack overflow error on self-referential tables.
---@return string
conciseTostring = function (object, depth)
depth = depth or -1
if type(object) == 'string' then
return '"' .. object .. '"'
elseif depth ~= 0 and type(object) == 'table' then
local elementArray = {}
local keyAsString
for k,v in pairs(object) do
keyAsString = type(k) == 'string' and ('"' .. tostring(k) .. '"') or tostring(k)
table.insert(elementArray, '(' .. keyAsString .. ', ' .. conciseTostring(v, depth -1) .. ')')
end
return '{' .. table.concat(elementArray, ', ') .. '}'
end
return tostring(object)
end
---Creates a list of all (key,value)-pairs from the specified table. Also lists subtable entries up to the specified depth.
---Major differences to concise print are:
--- * Format: Linebreak-formatted instead of one-liner, uses "[key] = value" instead of "(key,value)"
--- * Will also unpack tables used as keys
--- * Also includes the table's memory position as returned by tostring(table).
--- * Tables referenced multiple times will only be unpacked upon first encounter and abbreviated on subsequent encounters
--- * As a consequence, pretty version can be executed with unlimited depth on self-referential tables.
---@param object any
---@param depth? integer default: unlimited.
---@param constTable table
---@param indent string
---@return string
prettyTostring = function(object, depth, constTable, indent)
depth = depth or -1
local objType = type(object)
if objType == "string" then
return '"'..object..'"' --wrap the string in quotes.
elseif objType == 'table' and depth ~= 0 then
if not constTable[object] then
constTable[object] = tostring(object):gsub(":","")
if next(object)==nil then
return constTable[object]..": {}"
else
local mappedKV = {}
for k,v in pairs(object) do
table.insert(mappedKV, '\n ' .. indent ..'[' .. prettyTostring(k, depth - 1, constTable, indent .. " ") .. '] = ' .. prettyTostring(v, depth - 1, constTable, indent .. " "))
end
return constTable[object]..': {'.. table.concat(mappedKV, ',') .. '\n'..indent..'}'
end
end
end
return constTable[object] or tostring(object)
end
---Creates a list of all (key,value)-pairs from the specified table. Also lists subtable entries up to the specified depth.
---Supports concise style and pretty style.
---Concise will display {"a", 5, {7}} as '{(1, "a"), (2, 5), (3, {(1, 7)})}'.
---Pretty is linebreak-separated, so consider table size before converting. Pretty also abbreviates tables referenced multiple times.
---Can be called like table.tostring(T), table.tostring(T, depth), table.tostring(T, pretty_yn) or table.tostring(T, depth, pretty_yn).
---table.tostring is not multiplayer-synced.
---@param whichTable table
---@param depth? integer default: unlimited
---@param pretty_yn? boolean default: false (concise)
---@return string
---@overload fun(whichTable:table, pretty_yn?:boolean):string
function table.tostring(whichTable, depth, pretty_yn)
--reassign input params, if function was called as table.tostring(whichTable, pretty_yn)
if type(depth) == 'boolean' then
pretty_yn = depth
depth = -1
end
return pretty_yn and prettyTostring(whichTable, depth, {}, "") or conciseTostring(whichTable, depth)
end
---Prints a list of (key,value)-pairs contained in the specified table and its subtables up to the specified depth.
---Supports concise style and pretty style. Pretty is linebreak-separated, so consider table size before printing.
---Can be called like table.print(T), table.print(T, depth), table.print(T, pretty_yn) or table.print(T, depth, pretty_yn).
---@param whichTable table
---@param depth? integer default: unlimited
---@param pretty_yn? boolean default: false (concise)
---@overload fun(whichTable:table, pretty_yn?:boolean)
function table.print(whichTable, depth, pretty_yn)
print(table.tostring(whichTable, depth, pretty_yn))
end
end
end
Debug.endFile()
Debug.beginFile("IngameConsole")
--[[
--------------------------
----| Ingame Console |----
--------------------------
/**********************************************
* Allows you to use the following ingame commands:
* "-exec <code>" to execute any code ingame.
* "-console" to start an ingame console interpreting any further chat input as code and showing both return values of function calls and error messages. Furthermore, the print function will print
* directly to the console after it got started. You can still look up all print messages in the F12-log.
***********************
* -------------------
* |Using the console|
* -------------------
* Any (well, most) chat input by any player after starting the console is interpreted as code and directly executed. You can enter terms (like 4+5 or just any variable name), function calls (like print("bla"))
* and set-statements (like y = 5). If the code has any return values, all of them are printed to the console. Erroneous code will print an error message.
* Chat input starting with a hyphen is being ignored by the console, i.e. neither executed as code nor printed to the console. This allows you to still use other chat commands like "-exec" without prompting errors.
***********************
* ------------------
* |Multiline-Inputs|
* ------------------
* You can prevent a chat input from being immediately executed by preceeding it with the '>' character. All lines entered this way are halted, until any line not starting with '>' is being entered.
* The first input without '>' will execute all halted lines (and itself) in one chunk.
* Example of a chat input (the console will add an additional '>' to every line):
* >function a(x)
* >return x
* end
***********************
* Note that multiline inputs don't accept pure term evaluations, e.g. the following input is not supported and will prompt an error, while the same lines would have worked as two single-line inputs:
* >x = 5
* x
***********************
* -------------------
* |Reserved Keywords|
* -------------------
* The following keywords have a reserved functionality, i.e. are direct commands for the console and will not be interpreted as code:
* - 'help' - will show a list of all reserved keywords along very short explanations.
* - 'exit' - will shut down the console
* - 'share' - will share the players console with every other player, allowing others to read and write into it. Will force-close other players consoles, if they have one active.
* - 'clear' - will clear all text from the console, except the word 'clear'
* - 'lasttrace' - will show the stack trace of the latest error that occured within IngameConsole
* - 'show' - will show the console, after it was accidently hidden (you can accidently hide it by showing another multiboard, while the console functionality is still up and running).
* - 'printtochat' - will let the print function return to normal behaviour (i.e. print to the chat instead of the console).
* - 'printtoconsole'- will let the print function print to the console (which is default behaviour).
* - 'autosize on' - will enable automatic console resize depending on the longest string in the display. This is turned on by default.
* - 'autosize off' - will disable automatic console resize and instead linebreak long strings into multiple lines.
* - 'textlang eng' - lets the console use english Wc3 text language font size to compute linebreaks (look in your Blizzard launcher settings to find out)
* - 'textlang ger' - lets the console use german Wc3 text language font size to compute linebreaks (look in your Blizzard launcher settings to find out)
***********************
* --------------
* |Paste Helper|
* --------------
* @Luashine has created a tool that simplifies pasting multiple lines of code from outside Wc3 into the IngameConsole.
* This is particularly useful, when you want to execute a large chunk of testcode containing several linebreaks.
* Goto: https://github.com/Luashine/wc3-debug-console-paste-helper#readme
*
*************************************************/
--]]
----------------
--| Settings |--
----------------
---@class IngameConsole
IngameConsole = {
--Settings
numRows = 20 ---@type integer Number of Rows of the console (multiboard), excluding the title row. So putting 20 here will show 21 rows, first being the title row.
, autosize = true ---@type boolean Defines, whether the width of the main Column automatically adjusts with the longest string in the display.
, currentWidth = 0.5 ---@type number Current and starting Screen Share of the console main column.
, mainColMinWidth = 0.3 ---@type number Minimum Screen share of the console main column.
, mainColMaxWidth = 0.8 ---@type number Maximum Scren share of the console main column.
, tsColumnWidth = 0.06 ---@type number Screen Share of the Timestamp Column
, linebreakBuffer = 0.008 ---@type number Screen Share that is added to longest string in display to calculate the screen share for the console main column. Compensates for the small inaccuracy of the String Width function.
, maxLinebreaks = 8 ---@type integer Defines the maximum amount of linebreaks, before the remaining output string will be cut and not further displayed.
, printToConsole = true ---@type boolean defines, if the print function should print to the console or to the chat
, sharedConsole = false ---@type boolean defines, if the console is displayed to each player at the same time (accepting all players input) or if all players much start their own console.
, showTraceOnError = false ---@type boolean defines, if the console shows a trace upon printing errors. Usually not too useful within console, because you have just initiated the erroneous call.
, textLanguage = 'eng' ---@type string text language of your Wc3 installation, which influences font size (look in the settings of your Blizzard launcher). Currently only supports 'eng' and 'ger'.
, colors = {
timestamp = "bbbbbb" ---@type string Timestamp Color
, singleLineInput = "ffffaa" ---@type string Color to be applied to single line console inputs
, multiLineInput = "ffcc55" ---@type string Color to be applied to multi line console inputs
, returnValue = "00ffff" ---@type string Color applied to return values
, error = "ff5555" ---@type string Color to be applied to errors resulting of function calls
, keywordInput = "ff00ff" ---@type string Color to be applied to reserved keyword inputs (console reserved keywords)
, info = "bbbbbb" ---@type string Color to be applied to info messages from the console itself (for instance after creation or after printrestore)
}
--Privates
, numCols = 2 ---@type integer Number of Columns of the console (multiboard). Adjusting this requires further changes on code base.
, player = nil ---@type player player for whom the console is being created
, currentLine = 0 ---@type integer Current Output Line of the console.
, inputload = '' ---@type string Input Holder for multi-line-inputs
, output = {} ---@type string[] Array of all output strings
, outputTimestamps = {} ---@type string[] Array of all output string timestamps
, outputWidths = {} ---@type number[] remembers all string widths to allow for multiboard resize
, trigger = nil ---@type trigger trigger processing all inputs during console lifetime
, multiboard = nil ---@type multiboard
, timer = nil ---@type timer gets started upon console creation to measure timestamps
, errorHandler = nil ---@type fun(errorMsg:string):string error handler to be used within xpcall. We create one per console to make it compatible with console-specific settings.
, lastTrace = '' ---@type string trace of last error occured within console. To be printed via reserved keyword "lasttrace"
--Statics
, keywords = {} ---@type table<string,function> saves functions to be executed for all reserved keywords
, playerConsoles = {} ---@type table<player,IngameConsole> Consoles currently being active. up to one per player.
, originalPrint = print ---@type function original print function to restore, after the console gets closed.
}
IngameConsole.__index = IngameConsole
IngameConsole.__name = 'IngameConsole'
------------------------
--| Console Creation |--
------------------------
---Creates and opens up a new console.
---@param consolePlayer player player for whom the console is being created
---@return IngameConsole
function IngameConsole.create(consolePlayer)
local new = {} ---@type IngameConsole
setmetatable(new, IngameConsole)
---setup Object data
new.player = consolePlayer
new.output = {}
new.outputTimestamps = {}
new.outputWidths = {}
--Timer
new.timer = CreateTimer()
TimerStart(new.timer, 3600., true, nil) --just to get TimeElapsed for printing Timestamps.
--Trigger to be created after short delay, because otherwise it would fire on "-console" input immediately and lead to stack overflow.
new:setupTrigger()
--Multiboard
new:setupMultiboard()
--Create own error handler per console to be compatible with console-specific settings
new:setupErrorHandler()
--Share, if settings say so
if IngameConsole.sharedConsole then
new:makeShared() --we don't have to exit other players consoles, because we look for the setting directly in the class and there just logically can't be other active consoles.
end
--Welcome Message
new:out('info', 0, false, "Console started. Any further chat input will be executed as code, except when beginning with \x22-\x22.")
return new
end
---Creates the multiboard used for console display.
function IngameConsole:setupMultiboard()
self.multiboard = CreateMultiboard()
MultiboardSetRowCount(self.multiboard, self.numRows + 1) --title row adds 1
MultiboardSetColumnCount(self.multiboard, self.numCols)
MultiboardSetTitleText(self.multiboard, "Console")
local mbitem
for col = 1, self.numCols do
for row = 1, self.numRows + 1 do --Title row adds 1
mbitem = MultiboardGetItem(self.multiboard, row -1, col -1)
MultiboardSetItemStyle(mbitem, true, false)
MultiboardSetItemValueColor(mbitem, 255, 255, 255, 255) -- Colors get applied via text color code
MultiboardSetItemWidth(mbitem, (col == 1 and self.tsColumnWidth) or self.currentWidth )
MultiboardReleaseItem(mbitem)
end
end
mbitem = MultiboardGetItem(self.multiboard, 0, 0)
MultiboardSetItemValue(mbitem, "|cffffcc00Timestamp|r")
MultiboardReleaseItem(mbitem)
mbitem = MultiboardGetItem(self.multiboard, 0, 1)
MultiboardSetItemValue(mbitem, "|cffffcc00Line|r")
MultiboardReleaseItem(mbitem)
self:showToOwners()
end
---Creates the trigger that responds to chat events.
function IngameConsole:setupTrigger()
self.trigger = CreateTrigger()
TriggerRegisterPlayerChatEvent(self.trigger, self.player, "", false) --triggers on any input of self.player
TriggerAddCondition(self.trigger, Condition(function() return string.sub(GetEventPlayerChatString(),1,1) ~= '-' end)) --console will not react to entered stuff starting with '-'. This still allows to use other chat orders like "-exec".
TriggerAddAction(self.trigger, function() self:processInput(GetEventPlayerChatString()) end)
end
---Creates an Error Handler to be used by xpcall below.
---Adds stack trace plus formatting to the message.
function IngameConsole:setupErrorHandler()
self.errorHandler = function(errorMsg)
errorMsg = Debug.getLocalErrorMsg(errorMsg)
local _, tracePiece, lastFile = nil, "", errorMsg:match("^.-:") or "<unknown>" -- errors on objects created within Ingame Console don't have a file and linenumber. Consider "x = {}; x[nil] = 5".
local fullMsg = errorMsg .. "\nTraceback (most recent call first):\n" .. (errorMsg:match("^.-:\x25d+") or "<unknown>")
--Get Stack Trace. Starting at depth 5 ensures that "error", "messageHandler", "xpcall" and the input error message are not included.
for loopDepth = 5, 50 do --get trace on depth levels up to 50
---@diagnostic disable-next-line: cast-local-type, assign-type-mismatch
_, tracePiece = pcall(error, "", loopDepth) ---@type boolean, string
tracePiece = Debug.getLocalErrorMsg(tracePiece)
if #tracePiece > 0 then --some trace pieces can be empty, but there can still be valid ones beyond that
fullMsg = fullMsg .. " <- " .. ((tracePiece:match("^.-:") == lastFile) and tracePiece:match(":\x25d+"):sub(2,-1) or tracePiece:match("^.-:\x25d+"))
lastFile = tracePiece:match("^.-:")
end
end
self.lastTrace = fullMsg
return "ERROR: " .. (self.showTraceOnError and fullMsg or errorMsg)
end
end
---Shares this console with all players.
function IngameConsole:makeShared()
local player
for i = 0, GetBJMaxPlayers() -1 do
player = Player(i)
if (GetPlayerSlotState(player) == PLAYER_SLOT_STATE_PLAYING) and (IngameConsole.playerConsoles[player] ~= self) then --second condition ensures that the player chat event is not added twice for the same player.
IngameConsole.playerConsoles[player] = self
TriggerRegisterPlayerChatEvent(self.trigger, player, "", false) --triggers on any input
end
end
self.sharedConsole = true
end
---------------------
--| In |--
---------------------
---Processes a chat string. Each input will be printed. Incomplete multiline-inputs will be halted until completion. Completed inputs will be converted to a function and executed. If they have an output, it will be printed.
---@param inputString string
function IngameConsole:processInput(inputString)
--if the input is a reserved keyword, conduct respective actions and skip remaining actions.
if IngameConsole.keywords[inputString] then --if the input string is a reserved keyword
self:out('keywordInput', 1, false, inputString)
IngameConsole.keywords[inputString](self) --then call the method with the same name. IngameConsole.keywords["exit"](self) is just self.keywords:exit().
return
end
--if the input is a multi-line-input, queue it into the string buffer (inputLoad), but don't yet execute anything
if string.sub(inputString, 1, 1) == '>' then --multiLineInput
inputString = string.sub(inputString, 2, -1)
self:out('multiLineInput',2, false, inputString)
self.inputload = self.inputload .. inputString .. '\r' --carriage return
else --if the input is either singleLineInput OR the last line of multiLineInput, execute the whole thing.
self:out(self.inputload == '' and 'singleLineInput' or 'multiLineInput', 1, false, inputString)
self.inputload = self.inputload .. inputString
local loadedFunc, errorMsg = load("return " .. self.inputload) --adds return statements, if possible (works for term statements)
if loadedFunc == nil then
loadedFunc, errorMsg = load(self.inputload)
end
self.inputload = '' --empty inputload before execution of pcall. pcall can break (rare case, can for example be provoked with metatable.__tostring = {}), which would corrupt future console inputs.
--manually catch case, where the input did not define a proper Lua statement (i.e. loadfunc is nil)
local results = loadedFunc and table.pack(xpcall(loadedFunc, self.errorHandler)) or {false, "Input is not a valid Lua-statement: " .. errorMsg}
--output error message (unsuccessful case) or return values (successful case)
if not results[1] then --results[1] is the error status that pcall always returns. False stands for: error occured.
self:out('error', 0, true, results[2]) -- second result of pcall is the error message in case an error occured
elseif results.n > 1 then --Check, if there was at least one valid output argument. We check results.n instead of results[2], because we also get nil as a proper return value this way.
self:out('returnValue', 0, true, table.unpack(results, 2, results.n))
end
end
end
----------------------
--| Out |--
----------------------
-- split color codes, split linebreaks, print lines separately, print load-errors, update string width, update text, error handling with stack trace.
---Duplicates Color coding around linebreaks to make each line printable separately.
---Operates incorrectly on lookalike color codes invalidated by preceeding escaped vertical bar (like "||cffffcc00bla|r").
---Also operates incorrectly on multiple color codes, where the first is missing the end sequence (like "|cffffcc00Hello |cff0000ffWorld|r")
---@param inputString string
---@return string, integer
function IngameConsole.spreadColorCodes(inputString)
local replacementTable = {} --remembers all substrings to be replaced and their replacements.
for foundInstance, color in inputString:gmatch("((|c\x25x\x25x\x25x\x25x\x25x\x25x\x25x\x25x).-|r)") do
replacementTable[foundInstance] = foundInstance:gsub("(\r?\n)", "|r\x251" .. color)
end
return inputString:gsub("((|c\x25x\x25x\x25x\x25x\x25x\x25x\x25x\x25x).-|r)", replacementTable)
end
---Concatenates all inputs to one string, spreads color codes around line breaks and prints each line to the console separately.
---@param colorTheme? '"timestamp"'| '"singleLineInput"' | '"multiLineInput"' | '"result"' | '"keywordInput"' | '"info"' | '"error"' | '"returnValue"' Decides about the color to be applied. Currently accepted: 'timestamp', 'singleLineInput', 'multiLineInput', 'result', nil. (nil equals no colorTheme, i.e. white color)
---@param numIndentations integer Number of '>' chars that shall preceed the output
---@param hideTimestamp boolean Set to false to hide the timestamp column and instead show a "->" symbol.
---@param ... any the things to be printed in the console.
function IngameConsole:out(colorTheme, numIndentations, hideTimestamp, ...)
local inputs = table.pack(...)
for i = 1, inputs.n do
inputs[i] = tostring(inputs[i]) --apply tostring on every input param in preparation for table.concat
end
--Concatenate all inputs (4-space-separated)
local printOutput = table.concat(inputs, ' ', 1, inputs.n)
printOutput = printOutput:find("(\r?\n)") and IngameConsole.spreadColorCodes(printOutput) or printOutput
local substrStart, substrEnd = 1, 1
local numLinebreaks, completePrint = 0, true
repeat
substrEnd = (printOutput:find("(\r?\n)", substrStart) or 0) - 1
numLinebreaks, completePrint = self:lineOut(colorTheme, numIndentations, hideTimestamp, numLinebreaks, printOutput:sub(substrStart, substrEnd))
hideTimestamp = true
substrStart = substrEnd + 2
until substrEnd == -1 or numLinebreaks > self.maxLinebreaks
if substrEnd ~= -1 or not completePrint then
self:lineOut('info', 0, false, 0, "Previous value not entirely printed after exceeding maximum number of linebreaks. Consider adjusting 'IngameConsole.maxLinebreaks'.")
end
self:updateMultiboard()
end
---Prints the given string to the console with the specified colorTheme and the specified number of indentations.
---Only supports one-liners (no \n) due to how multiboards work. Will add linebreaks though, if the one-liner doesn't fit into the given multiboard space.
---@param colorTheme? '"timestamp"'| '"singleLineInput"' | '"multiLineInput"' | '"result"' | '"keywordInput"' | '"info"' | '"error"' | '"returnValue"' Decides about the color to be applied. Currently accepted: 'timestamp', 'singleLineInput', 'multiLineInput', 'result', nil. (nil equals no colorTheme, i.e. white color)
---@param numIndentations integer Number of greater '>' chars that shall preceed the output
---@param hideTimestamp boolean Set to false to hide the timestamp column and instead show a "->" symbol.
---@param numLinebreaks integer
---@param printOutput string the line to be printed in the console.
---@return integer numLinebreaks, boolean hasPrintedEverything returns true, if everything could be printed. Returns false otherwise (can happen for very long strings).
function IngameConsole:lineOut(colorTheme, numIndentations, hideTimestamp, numLinebreaks, printOutput)
--add preceeding greater chars
printOutput = ('>'):rep(numIndentations) .. printOutput
--Print a space instead of the empty string. This allows the console to identify, if the string has already been fully printed (see while-loop below).
if printOutput == '' then
printOutput = ' '
end
--Compute Linebreaks.
local linebreakWidth = ((self.autosize and self.mainColMaxWidth) or self.currentWidth )
local partialOutput = nil
local maxPrintableCharPosition
local printWidth
while string.len(printOutput) > 0 and numLinebreaks <= self.maxLinebreaks do --break, if the input string has reached length 0 OR when the maximum number of linebreaks would be surpassed.
--compute max printable substring (in one multiboard line)
maxPrintableCharPosition, printWidth = IngameConsole.getLinebreakData(printOutput, linebreakWidth - self.linebreakBuffer, self.textLanguage)
--adds timestamp to the first line of any output
if numLinebreaks == 0 then
partialOutput = printOutput:sub(1, numIndentations) .. ((IngameConsole.colors[colorTheme] and "|cff" .. IngameConsole.colors[colorTheme] .. printOutput:sub(numIndentations + 1, maxPrintableCharPosition) .. "|r") or printOutput:sub(numIndentations + 1, maxPrintableCharPosition)) --Colorize the output string, if a color theme was specified. IngameConsole.colors[colorTheme] can be nil.
table.insert(self.outputTimestamps, "|cff" .. IngameConsole.colors['timestamp'] .. ((hideTimestamp and ' ->') or IngameConsole.formatTimerElapsed(TimerGetElapsed(self.timer))) .. "|r")
else
partialOutput = (IngameConsole.colors[colorTheme] and "|cff" .. IngameConsole.colors[colorTheme] .. printOutput:sub(1, maxPrintableCharPosition) .. "|r") or printOutput:sub(1, maxPrintableCharPosition) --Colorize the output string, if a color theme was specified. IngameConsole.colors[colorTheme] can be nil.
table.insert(self.outputTimestamps, ' ..') --need a dummy entry in the timestamp list to make it line-progress with the normal output.
end
numLinebreaks = numLinebreaks + 1
--writes output string and width to the console tables.
table.insert(self.output, partialOutput)
table.insert(self.outputWidths, printWidth + self.linebreakBuffer) --remember the Width of this printed string to adjust the multiboard size in case. 0.5 percent is added to avoid the case, where the multiboard width is too small by a tiny bit, thus not showing some string without spaces.
--compute remaining string to print
printOutput = string.sub(printOutput, maxPrintableCharPosition + 1, -1) --remaining string until the end. Returns empty string, if there is nothing left
end
self.currentLine = #self.output
return numLinebreaks, string.len(printOutput) == 0 --printOutput is the empty string, if and only if everything has been printed
end
---Lets the multiboard show the recently printed lines.
function IngameConsole:updateMultiboard()
local startIndex = math.max(self.currentLine - self.numRows, 0) --to be added to loop counter to get to the index of output table to print
local outputIndex = 0
local maxWidth = 0.
local mbitem
for i = 1, self.numRows do --doesn't include title row (index 0)
outputIndex = i + startIndex
mbitem = MultiboardGetItem(self.multiboard, i, 0)
MultiboardSetItemValue(mbitem, self.outputTimestamps[outputIndex] or '')
MultiboardReleaseItem(mbitem)
mbitem = MultiboardGetItem(self.multiboard, i, 1)
MultiboardSetItemValue(mbitem, self.output[outputIndex] or '')
MultiboardReleaseItem(mbitem)
maxWidth = math.max(maxWidth, self.outputWidths[outputIndex] or 0.) --looping through non-defined widths, so need to coalesce with 0
end
--Adjust Multiboard Width, if necessary.
maxWidth = math.min(math.max(maxWidth, self.mainColMinWidth), self.mainColMaxWidth)
if self.autosize and self.currentWidth ~= maxWidth then
self.currentWidth = maxWidth
for i = 1, self.numRows +1 do
mbitem = MultiboardGetItem(self.multiboard, i-1, 1)
MultiboardSetItemWidth(mbitem, maxWidth)
MultiboardReleaseItem(mbitem)
end
self:showToOwners() --reshow multiboard to update item widths on the frontend
end
end
---Shows the multiboard to all owners (one or all players)
function IngameConsole:showToOwners()
if self.sharedConsole or GetLocalPlayer() == self.player then
MultiboardDisplay(self.multiboard, true)
MultiboardMinimize(self.multiboard, false)
end
end
---Formats the elapsed time as "mm: ss. hh" (h being a hundreds of a sec)
function IngameConsole.formatTimerElapsed(elapsedInSeconds)
return string.format("\x2502d: \x2502.f. \x2502.f", elapsedInSeconds // 60, math.fmod(elapsedInSeconds, 60.) // 1, math.fmod(elapsedInSeconds, 1) * 100)
end
---Computes the max printable substring for a given string and a given linebreakWidth (regarding a single line of console).
---Returns both the substrings last char position and its total width in the multiboard.
---@param stringToPrint string the string supposed to be printed in the multiboard console.
---@param linebreakWidth number the maximum allowed width in one line of the console, before a string must linebreak
---@param textLanguage string 'ger' or 'eng'
---@return integer maxPrintableCharPosition, number printWidth
function IngameConsole.getLinebreakData(stringToPrint, linebreakWidth, textLanguage)
local loopWidth = 0.
local bytecodes = table.pack(string.byte(stringToPrint, 1, -1))
for i = 1, bytecodes.n do
loopWidth = loopWidth + string.charMultiboardWidth(bytecodes[i], textLanguage)
if loopWidth > linebreakWidth then
return i-1, loopWidth - string.charMultiboardWidth(bytecodes[i], textLanguage)
end
end
return bytecodes.n, loopWidth
end
-------------------------
--| Reserved Keywords |--
-------------------------
---Exits the Console
---@param self IngameConsole
function IngameConsole.keywords.exit(self)
DestroyMultiboard(self.multiboard)
DestroyTrigger(self.trigger)
DestroyTimer(self.timer)
IngameConsole.playerConsoles[self.player] = nil
if next(IngameConsole.playerConsoles) == nil then --set print function back to original, when no one has an active console left.
print = IngameConsole.originalPrint
end
end
---Lets the console print to chat
---@param self IngameConsole
function IngameConsole.keywords.printtochat(self)
self.printToConsole = false
self:out('info', 0, false, "The print function will print to the normal chat.")
end
---Lets the console print to itself (default)
---@param self IngameConsole
function IngameConsole.keywords.printtoconsole(self)
self.printToConsole = true
self:out('info', 0, false, "The print function will print to the console.")
end
---Shows the console in case it was hidden by another multiboard before
---@param self IngameConsole
function IngameConsole.keywords.show(self)
self:showToOwners() --might be necessary to do, if another multiboard has shown up and thereby hidden the console.
self:out('info', 0, false, "Console is showing.")
end
---Prints all available reserved keywords plus explanations.
---@param self IngameConsole
function IngameConsole.keywords.help(self)
self:out('info', 0, false, "The Console currently reserves the following keywords:")
self:out('info', 0, false, "'help' shows the text you are currently reading.")
self:out('info', 0, false, "'exit' closes the console.")
self:out('info', 0, false, "'lasttrace' shows the stack trace of the latest error that occured within IngameConsole.")
self:out('info', 0, false, "'share' allows other players to read and write into your console, but also force-closes their own consoles.")
self:out('info', 0, false, "'clear' clears all text from the console.")
self:out('info', 0, false, "'show' shows the console. Sensible to use, when displaced by another multiboard.")
self:out('info', 0, false, "'printtochat' lets Wc3 print text to normal chat again.")
self:out('info', 0, false, "'printtoconsole' lets Wc3 print text to the console (default).")
self:out('info', 0, false, "'autosize on' enables automatic console resize depending on the longest line in the display.")
self:out('info', 0, false, "'autosize off' retains the current console size.")
self:out('info', 0, false, "'textlang eng' will use english text installation font size to compute linebreaks (default).")
self:out('info', 0, false, "'textlang ger' will use german text installation font size to compute linebreaks.")
self:out('info', 0, false, "Preceeding a line with '>' prevents immediate execution, until a line not starting with '>' has been entered.")
end
---Clears the display of the console.
---@param self IngameConsole
function IngameConsole.keywords.clear(self)
self.output = {}
self.outputTimestamps = {}
self.outputWidths = {}
self.currentLine = 0
self:out('keywordInput', 1, false, 'clear') --we print 'clear' again. The keyword was already printed by self:processInput, but cleared immediately after.
end
---Shares the console with other players in the same game.
---@param self IngameConsole
function IngameConsole.keywords.share(self)
for _, console in pairs(IngameConsole.playerConsoles) do
if console ~= self then
IngameConsole.keywords['exit'](console) --share was triggered during console runtime, so there potentially are active consoles of others players that need to exit.
end
end
self:makeShared()
self:showToOwners() --showing it to the other players.
self:out('info', 0,false, "The console of player " .. GetConvertedPlayerId(self.player) .. " is now shared with all players.")
end
---Enables auto-sizing of console (will grow and shrink together with text size)
---@param self IngameConsole
IngameConsole.keywords["autosize on"] = function(self)
self.autosize = true
self:out('info', 0,false, "The console will now change size depending on its content.")
end
---Disables auto-sizing of console
---@param self IngameConsole
IngameConsole.keywords["autosize off"] = function(self)
self.autosize = false
self:out('info', 0,false, "The console will retain the width that it currently has.")
end
---Lets linebreaks be computed by german font size
---@param self IngameConsole
IngameConsole.keywords["textlang ger"] = function(self)
self.textLanguage = 'ger'
self:out('info', 0,false, "Linebreaks will now compute with respect to german text installation font size.")
end
---Lets linebreaks be computed by english font size
---@param self IngameConsole
IngameConsole.keywords["textlang eng"] = function(self)
self.textLanguage = 'eng'
self:out('info', 0,false, "Linebreaks will now compute with respect to english text installation font size.")
end
---Prints the stack trace of the latest error that occured within IngameConsole.
---@param self IngameConsole
IngameConsole.keywords["lasttrace"] = function(self)
self:out('error', 0,false, self.lastTrace)
end
--------------------
--| Main Trigger |--
--------------------
do
--Actions to be executed upon typing -exec
local function execCommand_Actions()
local input = string.sub(GetEventPlayerChatString(),7,-1)
print("Executing input: |cffffff44" .. input .. "|r")
--try preceeding the input by a return statement (preparation for printing below)
local loadedFunc, errorMsg = load("return ".. input)
if not loadedFunc then --if that doesn't produce valid code, try without return statement
loadedFunc, errorMsg = load(input)
end
--execute loaded function in case the string defined a valid function. Otherwise print error.
if errorMsg then
print("|cffff5555Invalid Lua-statement: " .. Debug.getLocalErrorMsg(errorMsg) .. "|r")
else
---@diagnostic disable-next-line: param-type-mismatch
local results = table.pack(Debug.try(loadedFunc))
if results[1] ~= nil or results.n > 1 then
for i = 1, results.n do
results[i] = tostring(results[i])
end
--concatenate all function return values to one colorized string
print("|cff00ffff" .. table.concat(results, ' ', 1, results.n) .. "|r")
end
end
end
local function execCommand_Condition()
return string.sub(GetEventPlayerChatString(), 1, 6) == "-exec "
end
local function startIngameConsole()
--if the triggering player already has a console, show that console and stop executing further actions
if IngameConsole.playerConsoles[GetTriggerPlayer()] then
IngameConsole.playerConsoles[GetTriggerPlayer()]:showToOwners()
return
end
--create Ingame Console object
IngameConsole.playerConsoles[GetTriggerPlayer()] = IngameConsole.create(GetTriggerPlayer())
--overwrite print function
print = function(...)
IngameConsole.originalPrint(...) --the new print function will also print "normally", but clear the text immediately after. This is to add the message to the F12-log.
if IngameConsole.playerConsoles[GetLocalPlayer()] and IngameConsole.playerConsoles[GetLocalPlayer()].printToConsole then
ClearTextMessages() --clear text messages for all players having an active console
end
for player, console in pairs(IngameConsole.playerConsoles) do
if console.printToConsole and (player == console.player) then --player == console.player ensures that the console only prints once, even if the console was shared among all players
console:out(nil, 0, false, ...)
end
end
end
end
---Creates the triggers listening to "-console" and "-exec" chat input.
---Being executed within DebugUtils (MarkGameStart overwrite).
function IngameConsole.createTriggers()
--Exec
local execTrigger = CreateTrigger()
TriggerAddCondition(execTrigger, Condition(execCommand_Condition))
TriggerAddAction(execTrigger, execCommand_Actions)
--Real Console
local consoleTrigger = CreateTrigger()
TriggerAddAction(consoleTrigger, startIngameConsole)
--Events
for i = 0, GetBJMaxPlayers() -1 do
TriggerRegisterPlayerChatEvent(execTrigger, Player(i), "-exec ", false)
TriggerRegisterPlayerChatEvent(consoleTrigger, Player(i), "-console", true)
end
end
end
Debug.endFile()
if Debug then Debug.beginFile 'TotalInitialization' end
--[[——————————————————————————————————————————————————————
Total Initialization version 6.0
Created by: Bribe
Contributors: Eikonium, HerlySQR, Tasyen, Luashine, Forsakn, insanity_AI, Antares
Inspiration: Almia, ScorpioT1000, Troll-Brain
Hosted at: https://github.com/BribeFromTheHive/Lua/blob/master/TotalInitialization.lua
Debug library hosted at: https://www.hiveworkshop.com/threads/debug-utils-ingame-console-etc.330758/
————————————————————————————————————————————————————————————]]
---Calls the user's initialization function during the map's loading process. The first argument should either be the init function,
---or it should be the string to give the initializer a name (works similarly to a module name/identically to a vJass library name).
---
---To use requirements, call `Require.strict 'LibraryName'` or `Require.optional 'LibraryName'`. Alternatively, the OnInit callback
---function can take the `Require` table as a single parameter: `OnInit(function(import) import.strict 'ThisIsTheSameAsRequire' end)`.
---
-- - `OnInit.global` or just `OnInit` is called after InitGlobals and is the standard point to initialize.
-- - `OnInit.trig` is called after InitCustomTriggers, and is useful for removing hooks that should only apply to GUI events.
-- - `OnInit.map` is the last point in initialization before the loading screen is completed.
-- - `OnInit.final` occurs immediately after the loading screen has disappeared, and the game has started.
---@class OnInit
--
--Simple Initialization without declaring a library name:
---@overload async fun(initCallback: Initializer.Callback)
--
--Advanced initialization with a library name and an optional third argument to signal to Eikonium's DebugUtils that the file has ended.
---@overload async fun(libraryName: string, initCallback: Initializer.Callback, debugLineNum?: integer)
--
--A way to yield your library to allow other libraries in the same initialization sequence to load, then resume once they have loaded.
---@overload async fun(customInitializerName: string)
OnInit = {}
---@alias Initializer.Callback fun(require?: Requirement | {[string]: Requirement}):...?
---@alias Requirement async fun(reqName: string, source?: table): unknown
-- `Require` will yield the calling `OnInit` initialization function until the requirement (referenced as a string) exists. It will check the
-- global API (for example, does 'GlobalRemap' exist) and then check for any named OnInit resources which might use that same string as its name.
--
-- Due to the way Sumneko's syntax highlighter works, the return value will only be linted for defined @class objects (and doesn't work for regular
-- globals like `TimerStart`). I tried to request the functionality here: https://github.com/sumneko/lua-language-server/issues/1792 , however it
-- was closed. Presumably, there are other requests asking for it, but I wouldn't count on it.
--
-- To declare a requirement, use: `Require.strict 'SomeLibrary'` or (if you don't care about the missing linting functionality) `Require 'SomeLibrary'`
--
-- To optionally require something, use any other suffix (such as `.optionally` or `.nonstrict`): `Require.optional 'SomeLibrary'`
--
---@class Require: { [string]: Requirement }
---@overload async fun(reqName: string, source?: table): string
Require = {}
do
local library = {} --You can change this to false if you don't use `Require` nor the `OnInit.library` API.
--CONFIGURABLE LEGACY API FUNCTION:
---@param _ENV table
---@param OnInit any
local function assignLegacyAPI(_ENV, OnInit)
OnGlobalInit = OnInit; OnTrigInit = OnInit.trig; OnMapInit = OnInit.map; OnGameStart = OnInit.final --Global Initialization Lite API
--OnMainInit = OnInit.main; OnLibraryInit = OnInit.library; OnGameInit = OnInit.final --short-lived experimental API
--onGlobalInit = OnInit; onTriggerInit = OnInit.trig; onInitialization = OnInit.map; onGameStart = OnInit.final --original Global Initialization API
--OnTriggerInit = OnInit.trig; OnInitialization = OnInit.map --Forsakn's Ordered Indices API
end
--END CONFIGURABLES
local _G, rawget, insert =
_G, rawget, table.insert
local initFuncQueue = {} ---@type table<integer, fun(require: Require)>
---@param libraryName string | Initializer.Callback
---@param func? Initializer.Callback
---@param debugLineNum? integer
local function callUserFunc(libraryName, func, debugLineNum)
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, 2)
Debug.data.sourceMap[#Debug.data.sourceMap].lastLine = debugLineNum
end
if library then
func = library:create(libraryName, func)
end
end
if Debug then
if not Debug.assert(type(func) == "function", "func must be of type function", true) then
return
end
elseif type(func) ~= "function" then
print("|cffff5555ERROR in TotalInitialization: func must be of type function.")
return
end
coroutine.wrap(func)(Require)
if library then
library:resume()
end
end
local initKeyNames = {
root = 'root',
config = 'config',
main = 'main',
['InitGlobals'] = 'global',
['InitCustomTriggers'] = 'trig',
['RunInitializationTriggers'] = 'map',
['MarkGameStarted'] = 'final'
}
---@param name string
---@param continue? function
local function runInitializers(name, continue)
--print('running:', name, tostring(initFuncQueue[name]))
if name ~= 'module' and name ~= 'library' then
OnInit[initKeyNames[name]] = callUserFunc
end
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 Debug then
if not Debug.assert(type(name) == "string", "Library name must be of type string.", true) then
return
end
elseif type(name) ~= 'string' then
print("|cffff5555ERROR in TotalInitialization: Library name must be of type string.")
return
end
if Debug then
if not Debug.assert(library.moduleValueMatrix[name] == nil, "Library name " .. name .. " multiply declared.", true) then
return
end
elseif 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 Debug then
if not Debug.assert(type(userFunc) == "function", "Initializer function must be of type function.", true) then
return
end
elseif 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
if Debug then
if not Debug.assert(type(requirement) == "string", "requirement must be of type string.", true) then
return
end
elseif type(requirement) ~= "string" then
print("|cffff5555ERROR in TotalInitialization: requirement must be of type string.")
return
end
::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 Initializer.Callback
---@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
if Debug then
if not Debug.assert(false, "Module declared but not required: ".. name, true) then
return
end
else
print("|cffff5555ERROR in TotalInitialization: Module declared but not required: ".. name)
return
end
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)
if Debug then
if not Debug.assert(type(userFunc) == "function", "func must be of type function.", true) then
return
end
elseif type(userFunc) ~= "function" then
print("|cffff5555ERROR in TotalInitialization: func must be of type function.")
return
end
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
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 "PreplacedWidgetIndexer" end
do
--[[
=============================================================================================================================================================
Preplaced Widget Indexer
by Antares
Compiles all preplaced units, destructables, and/or items into easy-to-use lists.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/.317099/
HandleType https://www.hiveworkshop.com/threads/.354436/
ALICE (optional) https://www.hiveworkshop.com/threads/.353126/
=============================================================================================================================================================
A P I
=============================================================================================================================================================
GetPreplacedWidget(widgetType, index?) Returns a preplaced widget identified by widgetType, which can be an id, fourCC code, name, or hero proper
name. Optional index parameter for widget types for which more than one preplaced instance exists.
GetAllPreplacedWidgets(widgetType) Returns all preplaced widgets identified by widgetType, which can be an id, fourCC code, name, or hero
proper name.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
--Specify which preplaced widgets are added to the lists.
local DO_UNITS = true
local DO_DESTRUCTABLES = true
local DO_ITEMS = true
--(Requires ALICE) If debug mode is enabled, ALICE debug mode will be enabled immediately on map initialization and the indices of all widgets are written
--into their actor tooltips. To show the tooltip, simply click on the widget.
local DEBUG_MODE = false
--If enabled, widgets are sorted based on their position on the map, with the lowest index being assigned to those in the bottom-left corner of the map.
local SORT_BY_POSITION = true
--If enabled, you can control the indices of preplaced units and destructables by setting their forcedIndex percentage to the desired index in the World Editor.
--The forcedIndex will then be set to max forcedIndex after the system initializes.
local INDEX_BY_HEALTH_PERCENT = true
--List fourCC codes of widget types that should be ignored by the indexing by forcedIndex method.
local INDEX_BY_HEALTH_IGNORE_TYPES = { ---@constant string[]
"Etyr"
}
--[[
You can set rects with the World Editor to force an index for units standing in those rects. To do that, simply give those rects a name containing "forceIndexN",
where N is an integer. Each rect should have only one widget of the same type in it.
=============================================================================================================================================================
E N D O F C O N F I G
=============================================================================================================================================================
]]
local widgetsOfId = {}
local nameOfId = {}
local idOfName = {}
local forceIndexRects = {}
local weakKeys = {__mode = "k"}
local insert = table.insert
local sort = table.sort
PreplacedIndex = setmetatable({}, weakKeys)
local GetWidgetId = {
unit = GetUnitTypeId,
destructable = GetDestructableTypeId,
item = GetItemTypeId
}
local GetWidgetMaxLife = {
unit = BlzGetUnitMaxHP,
destructable = GetDestructableMaxLife,
}
local GetWidgetName = {
unit = GetUnitName,
destructable = GetDestructableName,
item = GetItemName
}
local function GetIndexFromRect(x, y)
for __, rect in ipairs(forceIndexRects) do
if x > rect.minX and x < rect.maxX and y > rect.minY and y < rect.maxY then
return rect.index
end
end
return nil
end
local function BeforeAliceInit()
local preplacedWidgets = {}
for __, value in ipairs(INDEX_BY_HEALTH_IGNORE_TYPES) do
---@diagnostic disable-next-line: assign-type-mismatch
INDEX_BY_HEALTH_IGNORE_TYPES[FourCC(value)] = true
end
--Process forceIndexRects
for name, rect in pairs(_G) do
if name:find("gg_rct_forceIndex") then
insert(forceIndexRects, {
minX = GetRectMinX(rect),
minY = GetRectMinY(rect),
maxX = GetRectMaxX(rect),
maxY = GetRectMaxY(rect),
index = tonumber(name:match("gg_rct_forceIndex(\x25d+)"))
})
end
end
local x = setmetatable({}, {__index = function(self, key) self[key] = GetWidgetX(key) return self[key] end})
local y = setmetatable({}, {__index = function(self, key) self[key] = GetWidgetY(key) return self[key] end})
if DO_UNITS then
local units = CreateGroup()
GroupEnumUnitsInRect(units, bj_mapInitialPlayableArea)
local u = FirstOfGroup(units)
while u do
GroupRemoveUnit(units, u)
preplacedWidgets[#preplacedWidgets + 1] = u
u = FirstOfGroup(units)
end
DestroyGroup(units)
end
if DO_DESTRUCTABLES then
EnumDestructablesInRect(bj_mapInitialPlayableArea, nil, function()
preplacedWidgets[#preplacedWidgets + 1] = GetEnumDestructable()
end)
end
if DO_ITEMS then
EnumItemsInRect(bj_mapInitialPlayableArea, nil, function()
preplacedWidgets[#preplacedWidgets + 1] = GetEnumItem()
end)
end
local id, name
for __, widget in ipairs(preplacedWidgets) do
id = GetWidgetId[HandleType[widget]](widget)
if widgetsOfId[id] then
insert(widgetsOfId[id], widget)
else
widgetsOfId[id] = setmetatable({widget}, weakKeys)
name = GetWidgetName[HandleType[widget]](widget)
idOfName[name] = id
nameOfId[id] = name
if HandleType[widget] == "unit" and IsUnitType(widget, UNIT_TYPE_HERO) then
idOfName[GetHeroProperName(widget)] = id
end
end
end
if SORT_BY_POSITION then
for __, widgets in pairs(widgetsOfId) do
if #widgets > 1 then
sort(widgets, function(widgetA, widgetB)
return x[widgetA] + y[widgetA] < x[widgetB] + y[widgetB]
end)
end
end
end
if INDEX_BY_HEALTH_PERCENT then
local indexFromRect, forcedIndex, tempWidget, healthPercent, indexFromHealth
local toHeal = {}
for id, widgets in pairs(widgetsOfId) do
local indices = {}
for index, widget in pairs(widgets) do
::begin::
indexFromRect = GetIndexFromRect(x[widget], y[widget])
healthPercent = HandleType[widget] ~= "item" and (100*GetWidgetLife(widget) + 0.5) // GetWidgetMaxLife[HandleType[widget]](widget) or 100
indexFromHealth = not INDEX_BY_HEALTH_IGNORE_TYPES[id] and healthPercent < 100 and healthPercent or nil
forcedIndex = indexFromRect or indexFromHealth
if forcedIndex then
if indexFromHealth then
insert(toHeal, widget)
end
if index ~= forcedIndex then
if widgets[forcedIndex] then
if indices[forcedIndex] then
print("|cffff0000Warning:|r Two or more widgets of type |cffffcc00" .. nameOfId[id] .. "|r have the same forced index " .. forcedIndex .. ".")
break
end
tempWidget = widgets[forcedIndex]
widgets[forcedIndex] = widget
widgets[index] = tempWidget
widget = tempWidget
indices[forcedIndex] = true
goto begin
else
widgets[forcedIndex] = widget
widgets[index] = nil
end
end
end
end
end
for __, widget in ipairs(toHeal) do
SetWidgetLife(widget, GetWidgetMaxLife[HandleType[widget]](widget))
end
end
for __, widgets in pairs(widgetsOfId) do
for index, widget in pairs(widgets) do
PreplacedIndex[widget] = index
end
end
end
local function AfterAliceInit()
Require "ALICE"
ALICE_TrackVariables("PreplacedIndex")
ALICE_Debug()
end
OnInit.global("PreplacedWidgetIndexer", BeforeAliceInit)
if DEBUG_MODE then
OnInit.final(AfterAliceInit)
end
---Returns a preplaced widget identified by widgetType, which can be an id, fourCC code, name, or hero proper name. Optional index parameter for widget types for which more than one preplaced instance exists.
---@param widgetType string | integer
---@param index? integer
---@return unit | destructable | item
function GetPreplacedWidget(widgetType, index)
if type(widgetType) == "number" then
assert(widgetsOfId[widgetType], "Preplaced widgets with fourCC code " .. string.pack(">I4", widgetType) .. " do not exist.")
return widgetsOfId[widgetType][index or 1]
elseif widgetType:len() == 4 then
local fourCC = FourCC(widgetType)
if widgetsOfId[fourCC] then
return widgetsOfId[fourCC][index or 1]
else
assert(idOfName[widgetType], "Preplaced widgets with name or fourCC code " .. widgetType .. " do not exist.")
return widgetsOfId[idOfName[widgetType]][index or 1]
end
else
assert(idOfName[widgetType], "Preplaced widgets with name " .. widgetType .. " do not exist.")
return widgetsOfId[idOfName[widgetType]][index or 1]
end
end
---Returns all preplaced widgets identified by widgetType, which can be an id, fourCC code, name, or hero proper name.
---@param widgetType string | integer
---@return table
function GetAllPreplacedWidgets(widgetType)
if type(widgetType) == "number" then
assert(widgetsOfId[widgetType], "Preplaced widgets with fourCC code " .. string.pack(">I4", widgetType) .. " do not exist.")
return widgetsOfId[widgetType]
elseif widgetType:len() == 4 then
local fourCC = FourCC(widgetType)
if widgetsOfId[fourCC] then
return widgetsOfId[fourCC]
else
assert(idOfName[widgetType], "Preplaced widgets with name or fourCC code " .. widgetType .. " do not exist.")
return widgetsOfId[idOfName[widgetType]]
end
else
assert(idOfName[widgetType], "Preplaced widgets with name " .. widgetType .. " do not exist.")
return widgetsOfId[idOfName[widgetType]]
end
end
end
if Debug then Debug.endFile() 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
if Debug then Debug.beginFile "PathingWizard" end
do
--[[
=============================================================================================================================================================
Pathing Wizard
by Antares
Automatically generate pathing map and determine which points are accessible.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
Hook (optional) https://www.hiveworkshop.com/threads/hook.339153/
=============================================================================================================================================================
To import, copy this library and the Walkability Check Item.
Go through the config to see which features you want to enable. If you want to use seed points, define one for each section of your map. Using multiple seed
points per section will slow down initialization, not make it faster.
You can define rects that enable/disable pathing within that area. To do so, create rects using the World Editor's Region tool. All rects named "pathable1",
"pathable2" etc. will make the system ignore all tiles within that area. All rects named "unpathable1", "unpathable2" etc. will disable pathing within that
area. The list has to be without holes (if you have a pathable3, there has to be a pathable2).
DebugUtils might throw undeclared global warning. Disable WARNING_FOR_UNDECLARED_GLOBALS or ignore those messages.
Enable VISUALIZE_MAP and check if the reachability map has been created correctly. Check for any "leaks".
=============================================================================================================================================================
F U N C T I O N S
=============================================================================================================================================================
IsPointAccessible(x, y) Returns whether the terrain at the specified point is accessible.
GetClosestAccessiblePoint(x, y) Returns the location of the closest point that is on accessible terrain.
ArePointsConnected(xOrigin, yOrigin, xDestination, yDestination) Returns whether the destination point can be reached from the origin point.
GetSection(x, y) Returns the section index of the specified point. A value of -1 indicates inaccessible
terrain.
GetSectionSize(x, y) Returns the size of the section at the specified point (in 64x64 tiles).
GetSectionMapIndizes(x, y) Converts coordinates into array indices. The third return value denotes whether the
queried point is outside of the map bounds.
GetSectionMap() Returns the internal section map.
GetFurthestAccessiblePoint(xStart, yStart, xEnd, yEnd) Returns the furthest point that is accessible by traveling a straight line from the
specified start point to the specified end point. The third return value denotes whether
the end point was reached.
InitPathingWizard() Initializes the section map. Only necessary if AUTO_RUN_AT is disabled.
OnPathabilityUpdate(whichFunc) Executes the specified function whenever the pathing map is updated due to a
destructable being destroyed. Executes for each tile that was reevaluated. The function
is called with the parameters func(x, y, isPathable).
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
local TEST_ITEM_TYPE = "Itst" ---@constant string
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--Settings
--When using seed points, the reachability of a point is only checked with respect to the specified seed points. That means, a patch of walkable terrain is
--not considered reachable if there is no path to it from at least one of the seed points.
local USE_SEED_POINTS = true ---@constant boolean
--Declare the seed points of the reachability map. The table entries are x- and y-values alternatingly (x1, y1, x2, y2...).
local SEED_POINTS = { ---@constant number[]
750, -12200,
}
--Automatically disables walkability for these terrain types.
local UNPATHABLE_TERRAIN_TYPES = { ---@constant string[]
"Vrck"
}
--Create pathing blockers around the borders of areas for which the pathing has been manually disabled with unpathable rects or unpathable terrain types.
--This improves the pathfinding of units.
local CREATE_PATHING_BLOCKERS = true ---@constant boolean
--If set to true, all units and items are briefly hidden before checking pathability so that they don't mess up the result.
local HIDE_UNITS_AND_ITEMS = true ---@constant boolean
--Turns off walkability on all unreachable tiles. Only makes sense to enable this when seed points are used. Potential issue: No units can be preplaced in
--areas that should become accessible later on.
local TURN_OFF_WALKABILITY = true ---@constant boolean
--Reevaluates the pathing map around a destructable when it is destroyed. Also creates a hook for RemoveDestructable. Potential issue: Unit pathing may take
--some time to update when TURN_OFF_WALKABILITY is used.
local REDRAW_ON_DESTRUCTABLE_DEATH = true ---@constant boolean
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--Initialization
--Automatically initialize the reachability map at the specified initialization point. The order of OnInits is global -> trig -> map -> final. OnInit.main will
--not work. If set to nil, you have to run it manually with InitPathingWizard().
local AUTO_RUN_AT = "global" ---@constant string
-------------------------------------------------------------------------------------------------------------------------------------------------------------
--Debugging
--Create colored runes on the ground to visualize connected areas. White runes indicate accessible areas while red runes indicated inaccessible areas. Can
--cause long stutters when used in combination with REDRAW_ON_DESTRUCTABLE_DEATH.
local VISUALIZE_MAP = false ---@constant boolean
local SHOW_COMPUTATION_TIME = false ---@constant boolean
--[[
=============================================================================================================================================================
E N D O F C O N F I G
=============================================================================================================================================================
]]
local sectionOfTile = {} ---@type integer[][]
local overwriteable = {} ---@type boolean[][]
local explicitlyPathable = {} ---@type boolean[][]
local explicitlyUnpathable = {} ---@type boolean[][]
local hasPathingBlocker = {} ---@type boolean[][]
local alreadyEvaluated = {} ---@type boolean[][]
local sectionSizeOfTile = {} ---@type integer[][]
local visualizer = {} ---@type effect[][]
local worldMinX, worldMinY ---@type number, number
local worldMaxX, worldMaxY ---@type number, number
local mapMaxi, mapMaxj ---@type integer, integer
local currentI, currentJ = {}, {} ---@type integer[], integer[]
local nextI, nextJ = {}, {} ---@type integer[], integer[]
local firstI, firstJ = {}, {} ---@type integer[], integer[]
local evaluatedI, evaluatedJ = {}, {} ---@type integer[], integer[]
local highestSection ---@type integer
local sectionSize ---@type integer
local resetTileSizes = false ---@type boolean
local min = math.min
local max = math.max
local sqrt = math.sqrt
local UNPATHABLE_TERRAIN_IDS = {} ---@type integer[]
local SMALL_BLOCKER ---@type integer
local LARGE_BLOCKER ---@type integer
local onUpdateHooks = {} ---@type function[]
local testItem ---@type item
--===========================================================================================================================================================
--Utility
--===========================================================================================================================================================
local function CreateVisualizers()
local section
for i = 1, mapMaxi do
for j = 1, mapMaxj do
section = sectionOfTile[i][j]
if i == mapMaxi or sectionOfTile[i+1][j] ~= section or j == mapMaxj or sectionOfTile[i][j+1] ~= section or i == 1 or sectionOfTile[i-1][j] ~= section or j == 1 or sectionOfTile[i][j-1] ~= section then
if section > 0 then
visualizer[i][j] = AddSpecialEffect("Doodads\\Cinematic\\GlowingRunes\\GlowingRunes2", worldMinX + (i - 0.5)*64, worldMinY + (j - 0.5)*64)
else
visualizer[i][j] = AddSpecialEffect("Doodads\\Cinematic\\GlowingRunes\\GlowingRunes0", worldMinX + (i - 0.5)*64, worldMinY + (j - 0.5)*64)
end
end
BlzSetSpecialEffectZ(visualizer[i][j], BlzGetLocalSpecialEffectZ(visualizer[i][j]) - 30)
end
end
end
--[[
[2][2][2][1]
[3][ ][ ][1]
[3][X][ ][1]
[3][4][4][4]
]]
local function BorderAreaOf2x2TileIsPathable(I, J)
if I < mapMaxi - 1 then
for j = J, J >= mapMaxj - 1 and mapMaxj or J + 2 do
if not explicitlyUnpathable[I+2][j] then
return true
end
end
end
if J < mapMaxj - 1 then
for i = I == 1 and 1 or I - 1, I == mapMaxi and mapMaxi or I + 1 do
if not explicitlyUnpathable[i][J+2] then
return true
end
end
end
if I > 1 then
for j = J == 1 and 1 or J - 1, J == mapMaxj and mapMaxj or J + 1 do
if not explicitlyUnpathable[I-1][j] then
return true
end
end
end
if J > 1 then
for i = I, I >= mapMaxi - 1 and mapMaxi or I + 2 do
if not explicitlyUnpathable[i][J-1] then
return true
end
end
end
return false
end
--===========================================================================================================================================================
--Flood Fill
--===========================================================================================================================================================
local function IsPathable(i, j)
if explicitlyUnpathable[i][j] then
return false
elseif explicitlyPathable[i][j] then
return true
end
local x, y = worldMinX + (i - 0.5)*64, worldMinY + (j - 0.5)*64
SetItemPosition(testItem, x, y)
local dx, dy = x - GetItemX(testItem), y - GetItemY(testItem)
return dx <= 1 and dx >= -1 and dy <= 1 and dy >= -1
end
local function WriteTile(i, j, section, isUpdate)
local nextSection = sectionOfTile[i][j]
if nextSection == nil then
--Not yet processed
if not IsPathable(i, j) then
if section > 0 then
--Hit edge of inaccessible region.
sectionOfTile[i][j] = -1
else
--Region continues to be inaccessible.
sectionOfTile[i][j] = section
end
elseif USE_SEED_POINTS and section == -1 then
--Hit edge of pathable region, but not clear if connected to seed point.
sectionOfTile[i][j] = section
overwriteable[i][j] = true
else
if section > 0 then
--Region continues to be accessible.
sectionOfTile[i][j] = section
else
--Hit edge of accessible region. No seed points.
highestSection = highestSection + 1
sectionOfTile[i][j] = highestSection
end
end
nextI[#nextI + 1], nextJ[#nextJ + 1] = i, j
if isUpdate then
evaluatedI[#evaluatedI + 1], evaluatedJ[#evaluatedJ + 1] = i, j
end
elseif section > 0 and nextSection > section then
--Merge two accessible regions
sectionOfTile[i][j] = section
nextI[#nextI + 1], nextJ[#nextJ + 1] = i, j
if isUpdate then
evaluatedI[#evaluatedI + 1], evaluatedJ[#evaluatedJ + 1] = i, j
end
elseif section > 0 and overwriteable[i][j] then
--Flip unaccessible tile to accessible now that it is known that it is connected to a seed point.
sectionOfTile[i][j] = section
nextI[#nextI + 1], nextJ[#nextJ + 1] = i, j
overwriteable[i][j] = nil
if isUpdate then
evaluatedI[#evaluatedI + 1], evaluatedJ[#evaluatedJ + 1] = i, j
end
end
end
local function ClearTile(i, j, __, __)
local nextSection = sectionOfTile[i][j]
if alreadyEvaluated[i][j] then
return
end
if nextSection and nextSection > 0 then
firstI[#firstI + 1], firstJ[#firstJ + 1] = i, j
elseif overwriteable[i][j] then
firstI[#firstI + 1], firstJ[#firstJ + 1] = i, j
elseif nextSection then
sectionOfTile[i][j] = nil
nextI[#nextI + 1], nextJ[#nextJ + 1] = i, j
end
evaluatedI[#evaluatedI + 1], evaluatedJ[#evaluatedJ + 1] = i, j
alreadyEvaluated[i][j] = true
end
local function SumTile(i, j, section, __)
if alreadyEvaluated[i][j] then
return
end
if sectionOfTile[i][j] == section then
sectionSize = sectionSize + 1
nextI[#nextI + 1], nextJ[#nextJ + 1] = i, j
end
evaluatedI[#evaluatedI + 1], evaluatedJ[#evaluatedJ + 1] = i, j
alreadyEvaluated[i][j] = true
end
local function FloodFill(whichFunc, isUpdate)
local i, j, nexti, nextj, section
for k = 1, #currentI do
i, j = currentI[k], currentJ[k]
section = sectionOfTile[i][j]
if i < mapMaxi then
nexti = i + 1
nextj = j
whichFunc(nexti, nextj, section, isUpdate)
end
if j < mapMaxj then
nexti = i
nextj = j + 1
whichFunc(nexti, nextj, section, isUpdate)
end
if i > 1 then
nexti = i - 1
nextj = j
whichFunc(nexti, nextj, section, isUpdate)
end
if j > 1 then
nexti = i
nextj = j - 1
whichFunc(nexti, nextj, section, isUpdate)
end
end
for k = #nextI + 1, #currentI do
currentI[k], currentJ[k] = nil, nil
end
for k = 1, #nextI do
currentI[k], currentJ[k] = nextI[k], nextJ[k]
nextI[k], nextJ[k] = nil, nil
end
if #currentI > 0 then
FloodFill(whichFunc, isUpdate)
end
end
--===========================================================================================================================================================
--Destructable Death
--===========================================================================================================================================================
local function ReevaluateMapAt(x, y)
local i = ((x - worldMinX)/64 + 0.5) // 1
local j = ((y - worldMinY)/64 + 0.5) // 1
if i < 1 or i > mapMaxi or j < 1 or j > mapMaxj then
return
end
testItem = CreateItem(FourCC(TEST_ITEM_TYPE), 0, 0)
if IsPathable(i, j) and sectionOfTile[i][j] == -1 then
for k = 1, #currentI do
currentI[k], currentJ[k] = nil, nil
end
currentI[1], currentJ[1] = i, j
sectionOfTile[i][j] = nil
FloodFill(ClearTile, true)
for k = 1, #evaluatedI do
alreadyEvaluated[evaluatedI[k]][evaluatedJ[k]] = nil
evaluatedI[k], evaluatedJ[k] = nil, nil
end
currentI[1], currentJ[1] = nil, nil
for k = 1, #firstI do
currentI[k], currentJ[k] = firstI[k], firstJ[k]
firstI[k], firstJ[k] = nil, nil
end
FloodFill(WriteTile, true)
local numHooks = #onUpdateHooks
for k = 1, #evaluatedI do
i, j = evaluatedI[k], evaluatedJ[k]
x, y = worldMinX + (i - 0.5)*64, worldMinY + (j - 0.5)*64
for l = 1, numHooks do
onUpdateHooks[l](x, y, sectionOfTile[i][j] > 0)
end
alreadyEvaluated[i][j] = nil
evaluatedI[k], evaluatedJ[k] = nil, nil
if TURN_OFF_WALKABILITY then
SetTerrainPathable(worldMinX + (i - 0.5)*64, worldMinY + (j - 0.5)*64, PATHING_TYPE_WALKABILITY, sectionOfTile[i][j] > 0)
end
end
if VISUALIZE_MAP then
for i = 1, mapMaxi do
for j = 1, mapMaxj do
if visualizer[i][j] then
DestroyEffect(visualizer[i][j])
end
end
end
CreateVisualizers()
end
end
resetTileSizes = true
RemoveItem(testItem)
end
local function OnDestructableDeath()
local d = GetTriggerDestructable()
ReevaluateMapAt(GetDestructableX(d), GetDestructableY(d))
end
--===========================================================================================================================================================
--Init
--===========================================================================================================================================================
local function Init()
local startTime = os.clock()
local hook = Require.optionally "Hook"
for index, type in ipairs(UNPATHABLE_TERRAIN_TYPES) do
UNPATHABLE_TERRAIN_IDS[index] = FourCC(type)
end
SMALL_BLOCKER = FourCC "YTpb"
LARGE_BLOCKER = FourCC "YTpc"
worldMinX = GetRectMinX(bj_mapInitialPlayableArea)
worldMinY = GetRectMinY(bj_mapInitialPlayableArea)
worldMaxX = GetRectMaxX(bj_mapInitialPlayableArea)
worldMaxY = GetRectMaxY(bj_mapInitialPlayableArea)
if ALICE_ExcludeTypes then
ALICE_ExcludeTypes(TEST_ITEM_TYPE)
end
testItem = CreateItem(FourCC(TEST_ITEM_TYPE), 0, 0)
if testItem == nil then
error("Walkability Check Item has not been imported.")
end
--Hide Units
local G
if HIDE_UNITS_AND_ITEMS then
G = CreateGroup()
GroupEnumUnitsInRect(G, GetWorldBounds(), nil)
local u = BlzGroupUnitAt(G, 0)
local g = 0
while u do
ShowUnit(u, false)
g = g + 1
u = BlzGroupUnitAt(G, g)
end
end
--HideItems
EnumItemsInRect(GetWorldBounds(), nil, function()
SetItemVisible(GetEnumItem(), false)
end)
--Init 2D Tables
mapMaxi = (worldMaxX - worldMinX) // 64
mapMaxj = (worldMaxY - worldMinY) // 64
for i = 1, mapMaxi do
overwriteable[i] = {}
sectionOfTile[i] = {}
sectionSizeOfTile[i] = {}
explicitlyPathable[i] = {}
explicitlyUnpathable[i] = {}
alreadyEvaluated[i] = {}
if VISUALIZE_MAP then
visualizer[i] = {}
end
if CREATE_PATHING_BLOCKERS then
hasPathingBlocker[i] = {}
end
end
--Process Terrain Types
local unpathableIds = #UNPATHABLE_TERRAIN_IDS
local terrainType
if unpathableIds > 0 then
for x = worldMinX, worldMaxX - 64, 64 do
for y = worldMinY, worldMaxY - 64, 64 do
terrainType = GetTerrainType(x, y)
for t = 1, unpathableIds do
if terrainType == UNPATHABLE_TERRAIN_IDS[t] then
explicitlyUnpathable[((x - worldMinX)/64) // 1 + 1][((y - worldMinY)/64) // 1 + 1] = true
break
end
end
end
end
end
--Process pathable rects
local r = 1
local minI, minJ, maxI, maxJ
local rect = _G["gg_rct_pathable" .. r]
while rect do
minI = max(1, min(mapMaxi, ((GetRectMinX(rect) - worldMinX)/64) // 1 + 1))
minJ = max(1, min(mapMaxj, ((GetRectMinY(rect) - worldMinY)/64) // 1 + 1))
maxI = max(1, min(mapMaxi, ((GetRectMaxX(rect) - worldMinX)/64) // 1))
maxJ = max(1, min(mapMaxj, ((GetRectMaxY(rect) - worldMinY)/64) // 1))
for i = minI, maxI do
for j = minJ, maxJ do
explicitlyPathable[i][j] = true
end
end
r = r + 1
rect = _G["gg_rct_pathable" .. r]
end
--Process unpathable rects
r = 1
rect = _G["gg_rct_unpathable" .. r]
while rect do
minI = max(1, min(mapMaxi, ((GetRectMinX(rect) - worldMinX)/64) // 1 + 1))
minJ = max(1, min(mapMaxj, ((GetRectMinY(rect) - worldMinY)/64) // 1 + 1))
maxI = max(1, min(mapMaxi, ((GetRectMaxX(rect) - worldMinX)/64) // 1))
maxJ = max(1, min(mapMaxj, ((GetRectMaxY(rect) - worldMinY)/64) // 1))
for i = minI, maxI do
for j = minJ, maxJ do
explicitlyUnpathable[i][j] = true
end
end
r = r + 1
rect = _G["gg_rct_unpathable" .. r]
end
--Init FloodFill
if USE_SEED_POINTS then
highestSection = 0
for k = 1, #SEED_POINTS, 2 do
local i = ((SEED_POINTS[k] - worldMinX)/64 + 0.5) // 1
local j = ((SEED_POINTS[k+1] - worldMinY)/64 + 0.5) // 1
if i < 1 or i > mapMaxi or j < 1 or j > mapMaxj then
print("|cffff0000Warning:|r Seed point is outside of playable map area.")
else
highestSection = highestSection + 1
sectionOfTile[i][j] = highestSection
currentI[#currentI + 1] = i
currentJ[#currentJ + 1] = j
end
end
else
if IsPathable(1, 1) then
sectionOfTile[1][1] = 1
highestSection = 1
else
sectionOfTile[1][1] = -1
highestSection = 0
end
currentI[1], currentJ[1] = 1, 1
end
--Main
FloodFill(WriteTile, false)
if VISUALIZE_MAP then
CreateVisualizers()
end
--Finalize
if TURN_OFF_WALKABILITY then
for i = 1, mapMaxi do
for j = 1, mapMaxj do
if sectionOfTile[i][j] == -1 then
SetTerrainPathable(worldMinX + (i - 0.5)*64, worldMinY + (j - 0.5)*64, PATHING_TYPE_WALKABILITY, false)
end
end
end
end
local explicitlyUnpathable_i
if CREATE_PATHING_BLOCKERS then
for i = 1, mapMaxi do
explicitlyUnpathable_i = explicitlyUnpathable[i]
for j = 1, mapMaxj do
if explicitlyUnpathable_i[j] and not hasPathingBlocker[i][j] then
if i < mapMaxi and j < mapMaxj and explicitlyUnpathable[i+1][j] and explicitlyUnpathable[i+1][j+1] and explicitlyUnpathable_i[j] and BorderAreaOf2x2TileIsPathable(i, j) then
CreateDestructable(LARGE_BLOCKER, worldMinX + i*64, worldMinY + j*64, 0, 1, 0)
hasPathingBlocker[i][j] = true
hasPathingBlocker[i+1][j] = true
hasPathingBlocker[i][j+1] = true
hasPathingBlocker[i+1][j+1] = true
elseif not explicitlyUnpathable[i == mapMaxi and i or i+1][j+1] or not explicitlyUnpathable_i[j == mapMaxj and j or j+1] or not explicitlyUnpathable[i == 1 and 1 or i-1][j] or not explicitlyUnpathable_i[j == 1 and 1 or j-1] then
CreateDestructable(SMALL_BLOCKER, worldMinX + (i - 0.5)*64, worldMinY + (j - 0.5)*64, 0, 1, 0)
hasPathingBlocker[i][j] = true
end
end
end
end
end
--Show Units
if HIDE_UNITS_AND_ITEMS then
local u = BlzGroupUnitAt(G, 0)
local g = 0
while u do
ShowUnit(u, true)
g = g + 1
u = BlzGroupUnitAt(G, g)
end
DestroyGroup(G)
end
--Show Items
EnumItemsInRect(GetWorldBounds(), nil, function()
SetItemVisible(GetEnumItem(), true)
end)
--Create Destructable Triggers
if REDRAW_ON_DESTRUCTABLE_DEATH then
local trig = CreateTrigger()
EnumDestructablesInRect(bj_mapInitialPlayableArea, nil, function()
TriggerRegisterDeathEvent(trig, GetEnumDestructable())
end)
TriggerAddAction(trig, OnDestructableDeath)
if hook then
---@diagnostic disable-next-line: duplicate-set-field
function Hook:RemoveDestructable(whichDestructable)
local x, y = GetDestructableX(whichDestructable), GetDestructableY(whichDestructable)
self.old(whichDestructable)
ReevaluateMapAt(x, y)
end
end
end
RemoveItem(testItem)
local endTime = os.clock()
if SHOW_COMPUTATION_TIME then
print("Reachability Map evaluation time was " .. string.format("\x25.3f", endTime - startTime) .. " seconds.")
end
end
if AUTO_RUN_AT then
OnInit[AUTO_RUN_AT]("PathingWizard", Init)
end
--===========================================================================================================================================================
--API
--===========================================================================================================================================================
---Returns whether the terrain at the specified point is accessible.
---@param x number
---@param y number
---@return boolean
function IsPointAccessible(x, y)
local i = ((x - worldMinX)/64 + 1) // 1
if i > mapMaxi or i < 1 then
return false
end
local j = ((y - worldMinY)/64 + 1) // 1
if j > mapMaxj or j < 1 then
return false
end
return sectionOfTile[i][j] > 0
end
---Returns the location of the closest point that is on accessible terrain.
---@param x number
---@param y number
---@return number, number
function GetClosestAccessiblePoint(x, y)
local I = max(1, min(mapMaxi, ((x - worldMinX)/64 + 1) // 1))
local J = max(1, min(mapMaxj, ((y - worldMinY)/64 + 1) // 1))
if sectionOfTile[I][J] > 0 then
return x, y
end
local delta = 1
local dist
local lowestDist = max(mapMaxj, mapMaxi)
local lowesti, lowestj
while delta < lowestDist do
local j = min(mapMaxj, J + delta)
for i = max(1, I - delta), min(mapMaxi, I + delta) do
if sectionOfTile[i][j] > 0 then
dist = sqrt((I - i)^2 + delta*delta)
if lowestDist > dist then
lowestDist = dist
lowesti, lowestj = i, j
end
end
end
j = max(1, J - delta)
for i = max(1, I - delta), min(mapMaxi, I + delta) do
if sectionOfTile[i][j] > 0 then
dist = sqrt((I - i)^2 + delta*delta)
if lowestDist > dist then
lowestDist = dist
lowesti, lowestj = i, j
end
end
end
local i = min(mapMaxi, I + delta)
for j = max(1, J - delta), min(mapMaxj, J + delta) do
if sectionOfTile[i][j] > 0 then
dist = sqrt((J - j)^2 + delta*delta)
if lowestDist > dist then
lowestDist = dist
lowesti, lowestj = i, j
end
end
end
i = max(1, I - delta)
for j = max(1, J - delta), min(mapMaxj, J + delta) do
if sectionOfTile[i][j] > 0 then
dist = sqrt((J - j)^2 + delta*delta)
if lowestDist > dist then
lowestDist = dist
lowesti, lowestj = i, j
end
end
end
delta = delta + 1
end
if lowesti then
return worldMinX + (lowesti - 0.5)*64, worldMinY + (lowestj - 0.5)*64
else
return 0, 0
end
end
---Returns whether the destination point can be reached from the origin point.
---@param xOrigin number
---@param yOrigin number
---@param xDestination number
---@param yDestination number
---@return boolean
function ArePointsConnected(xOrigin, yOrigin, xDestination, yDestination)
local i = ((xDestination - worldMinX)/64 + 1) // 1
if i > mapMaxi or i < 1 then
return false
end
local j = ((yDestination - worldMinY)/64 + 1) // 1
if j > mapMaxj or j < 1 then
return false
end
local destinationSection = sectionOfTile[i][j]
if destinationSection <= 0 then
return false
end
i = ((xOrigin - worldMinX)/64 + 1) // 1
if i > mapMaxi or i < 1 then
return false
end
j = ((yOrigin - worldMinY)/64 + 1) // 1
if j > mapMaxj or j < 1 then
return false
end
return sectionOfTile[i][j] == destinationSection
end
---Returns the section index of the specified point. A value of -1 indicates inaccessible terrain.
---@param x number
---@param y number
---@return integer
function GetSectionOfPoint(x, y)
local i = ((x - worldMinX)/64 + 1) // 1
if i > mapMaxi or i < 1 then
return 0
end
local j = ((y - worldMinY)/64 + 1) // 1
if j > mapMaxj or j < 1 then
return 0
end
return sectionOfTile[i][j]
end
---Returns the size of the section at the specified point (in 64x64 tiles).
---@param x number
---@param y number
---@return integer
function GetSectionSize(x, y)
local I = ((x - worldMinX)/64 + 1) // 1
local J = ((y - worldMinY)/64 + 1) // 1
if I > mapMaxi or I < 1 or J > mapMaxj or J < 1 then
return 0
end
if resetTileSizes then
for i = 1, mapMaxi do
for j = 1, mapMaxj do
sectionSizeOfTile[i][j] = nil
end
end
resetTileSizes = false
end
if sectionSizeOfTile[I][J] then
return sectionSizeOfTile[I][J]
end
sectionSize = 0
currentI[1], currentJ[1] = I, J
FloodFill(SumTile, false)
for k = 1, #evaluatedI do
sectionSizeOfTile[evaluatedI[k]][evaluatedJ[k]] = sectionSize
alreadyEvaluated[evaluatedI[k]][evaluatedJ[k]] = nil
evaluatedI[k], evaluatedJ[k] = nil, nil
end
return sectionSize
end
---Converts coordinates into array indices. The third return value denotes whether the queried point is outside of the map bounds.
---@param x number
---@param y number
---@return integer, integer, boolean
function GetSectionMapIndizes(x, y)
local i, j = ((x - worldMinX)/64 + 1) // 1, ((y - worldMinY)/64 + 1) // 1
local outsideOfBounds = false
if i < 1 then
i = 1
outsideOfBounds = true
elseif i > mapMaxi then
i = mapMaxi
outsideOfBounds = true
end
if j < 1 then
j = 1
outsideOfBounds = true
elseif j > mapMaxj then
j = mapMaxj
outsideOfBounds = true
end
return i, j, outsideOfBounds
end
---Returns the furthest point that is accessible by traveling a straight line from the specified start point to the specified end point. The third return value denotes whether the end point was reached.
---@param xStart number
---@param yStart number
---@param xEnd number
---@param yEnd number
---@return number, number, boolean
function GetFurthestAccessiblePoint(xStart, yStart, xEnd, yEnd)
local iStart, jStart = GetSectionMapIndizes(xStart, yStart)
local section = sectionOfTile[iStart][jStart]
if section < 0 then
return xStart, yStart, false
end
local iEnd, jEnd, outsideOfMapBounds = GetSectionMapIndizes(xEnd, yEnd)
local di = iEnd - iStart
local dj = jEnd - jStart
local adi = di
local adj = dj
local sdi = 0
local sdj = 0
local pdi
local pdj
local ddi
local ddy
local es
local el
local error
local i = iStart
local j = jStart
--calculate abs values and signs
if adi < 0 then
adi = -adi
sdi = -1
elseif adi > 0 then
sdi = 1
end
if adj < 0 then
adj = -adj
sdj = -1
elseif adj > 0 then
sdj = 1
end
if adi > adj then
pdi = sdi
pdj = 0
es = adj
el = adi
else
pdi = 0
pdj = sdj
es = adi
el = adj
end
ddi = sdi
ddy = sdj
error = el/2
local lastPathableI = iStart
local lastPathableJ = jStart
for __ = 1, el do
error = error - es
lastPathableI = i
lastPathableJ = j
if error < 0 then
di = i + ddi - pdi
dj = j + ddy - pdj
if di < 1 or di > mapMaxi or dj < 1 or dj > mapMaxj or sectionOfTile[di][dj] ~= section then
return worldMinX + (lastPathableI - 0.5)*64, worldMinY + (lastPathableJ - 0.5)*64, false
end
error = error + el
i = i + ddi
j = j + ddy
else
i = i + pdi
j = j + pdj
end
if i < 1 or i > mapMaxi or j < 1 or j > mapMaxj or sectionOfTile[i][j] ~= section then
return worldMinX + (lastPathableI - 0.5)*64, worldMinY + (lastPathableJ - 0.5)*64, false
end
end
if not outsideOfMapBounds then
return xEnd, yEnd, true
else
return worldMinX + (lastPathableI - 0.5)*64, worldMinY + (lastPathableJ - 0.5)*64, false
end
end
---Returns the internal section map.
---@return integer[][]
function GetSectionMap()
return sectionOfTile
end
---Initializes the section map. Only necessary if AUTO_RUN_AT is disabled.
function InitPathingWizard()
Init()
end
---Executes the specified function whenever the pathing map is updated due to a destructable being destroyed. Executes for each tile that was reevaluated. The function is called with the parameters func(x, y, isPathable).
---@param whichFunc function
function OnPathabilityUpdate(whichFunc)
table.insert(onUpdateHooks, whichFunc)
end
end
if Debug then Debug.endFile() end
if Debug then Debug.beginFile "FixedCameraLock" end
do
--[[
=============================================================================================================================================================
Fixed Camera Lock
by Antares
Locks the camera to a unit while dynamically adjusting the z-offset to disable awfulness.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/total-initialization.317099/
PrecomputedHeightMap (optional) https://www.hiveworkshop.com/threads/precomputed-synchronized-height-map.353477/
=============================================================================================================================================================
A P I
=============================================================================================================================================================
FCL_Lock(whichUnit, whichPlayer) Locks the camera of the specified player to the specified unit or the camera of the owning player of that unit,
if player is not specified.
FCL_Release(whichPlayer) Releases the camera of the specified player or for all players if no player is specified.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
local ADJUSTMENT_INTERVAL = 0.02 ---@constant number
--The adjustment strength when the camera target is below the unit. This type of camera shift is always awful and I recommend a value of 1.
local ADJUSTMENT_STRENGTH_UP = 1.0 ---@constant number
--The adjustment strength when the camera target is above the unit. This camera shift is sometimes actually useful, so you can disable it if you want to.
local ADJUSTMENT_STRENGTH_DOWN = 1.0 ---@constant number
--===========================================================================================================================================================
FCL_Anchor = {} ---@type table<player,unit>
local MASTER_TIMER ---@type timer
local lockEnabled = false ---@type boolean
local moveableLoc ---@type location
local GetLocZ ---@type function
local localPlayer ---@type player
---@param whichUnit unit
---@param whichPlayer? player
function FCL_Lock(whichUnit, whichPlayer)
whichPlayer = whichPlayer or GetOwningPlayer(whichUnit)
if GetLocalPlayer() == whichPlayer then
SetCameraTargetController(whichUnit, 0, 0, false)
lockEnabled = true
end
FCL_Anchor[whichPlayer] = whichUnit
end
---@param whichPlayer? player
function FCL_Release(whichPlayer)
if whichPlayer == nil or GetLocalPlayer() == whichPlayer then
ResetToGameCamera(0)
lockEnabled = false
end
if whichPlayer then
FCL_Anchor[whichPlayer] = nil
else
for i = 0, bj_MAX_PLAYER_SLOTS - 1 do
FCL_Anchor[Player(i)] = nil
end
end
end
local function AdjustCameraHeight()
if lockEnabled then
local dz = GetLocZ(GetUnitX(FCL_Anchor[localPlayer]), GetUnitY(FCL_Anchor[localPlayer])) - (GetCameraTargetPositionZ() - GetCameraField(CAMERA_FIELD_ZOFFSET))
if dz > 0 then
SetCameraField(CAMERA_FIELD_ZOFFSET, ADJUSTMENT_STRENGTH_UP*dz, ADJUSTMENT_INTERVAL)
else
SetCameraField(CAMERA_FIELD_ZOFFSET, ADJUSTMENT_STRENGTH_DOWN*dz, ADJUSTMENT_INTERVAL)
end
end
end
OnInit.final("FixedCameraLock", function()
local precomputedHeightMap = Require.optionally "PrecomputedHeightMap"
if precomputedHeightMap then
GetLocZ = _G.GetLocZ
else
moveableLoc = Location(0, 0)
GetLocZ = function(x, y)
MoveLocation(moveableLoc, x, y)
return GetLocationZ(moveableLoc)
end
end
localPlayer = GetLocalPlayer()
MASTER_TIMER = CreateTimer()
TimerStart(MASTER_TIMER, ADJUSTMENT_INTERVAL, true, AdjustCameraHeight)
end)
end
if Debug then Debug.endFile() end
if Debug then Debug.beginFile "FastWorld2ScreenTransformSynced" end
do
--[[
=============================================================================================================================================================
Fast World2Screen Transform (Synced)
by Antares
Transform from world to screen coordinates and back.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/.317099/
PrecomputedHeightMap (optional) https://www.hiveworkshop.com/threads/.353477/
SyncedCamera Included in Test Map.
=============================================================================================================================================================
A P I
=============================================================================================================================================================
World2ScreenSynced(x, y, z, player) Takes the world coordinates x, y, and z and returns the screen positions x and y of that point on the
specified player's screen. The third return value specifies if the point is on the screen.
Screen2WorldSynced(x, y, player) Takes the screen coordinates x and y and the player for which the calculation should be performed and
returns the x, y, and z world coordinates. The fourth return value specifies whether or not the search for
the world intersection point converged. This function may fail when a ray pointing from the camera to the
world intersects at multiple points with the terrain.
GetTriggerPlayerMouseScreenCoordinates() Returns the screen coordinates of the player's mouse on a mouse move or mouse click event.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
--The interval between updates of each player's camera parameters.
local TIME_STEP = 0.02 ---@constant number
--If enabled and camera lock target is set in FixedCameraLock for a player, the camera parameters are calculated differently to return a more accurate result.
--The ADJUSTMENT_STRENGTH_UP and ADJUSTMENT_STRENGTH_DOWN in FixedCameraLock should be set to 1 and the ADJUSTMENT_INTERVAL set very low to get the most
--accurate result.
local USE_FIXED_CAMERA_LOCK = false ---@constant boolean
--[[
=============================================================================================================================================================
E N D O F C O N F I G
=============================================================================================================================================================
]]
local cos = math.cos
local sin = math.sin
local sqrt = math.sqrt
local preCalc = {} ---@type table<player,boolean>
local eyeX = {} ---@type table<player,number>
local eyeY = {} ---@type table<player,number>
local eyeZ = {} ---@type table<player,number>
local cosRot = {} ---@type table<player,number>
local sinRot = {} ---@type table<player,number>
local cosAttack = {} ---@type table<player,number>
local sinAttack = {} ---@type table<player,number>
local cosAttackCosRot = {} ---@type table<player,number>
local cosAttackSinRot = {} ---@type table<player,number>
local sinAttackCosRot = {} ---@type table<player,number>
local sinAttackSinRot = {} ---@type table<player,number>
local yCenterScreenShift = {} ---@type table<player,number>
local scaleFactor = {} ---@type table<player,number>
local GetTerrainZ ---@type function
local moveableLoc ---@type location
local function CameraPrecalc(player)
local angleOfAttack = SyncedCamera.AngleOfAttack[player]
local rotation = SyncedCamera.Rotation[player]
local fieldOfView = SyncedCamera.FieldOfView[player]
cosAttack[player] = cos(angleOfAttack)
sinAttack[player] = sin(angleOfAttack)
cosRot[player] = cos(rotation)
sinRot[player] = sin(rotation)
if USE_FIXED_CAMERA_LOCK and FCL_Anchor[player] then
local x, y = GetUnitX(FCL_Anchor[player]), GetUnitY(FCL_Anchor[player])
eyeX[player] = x + SyncedCamera.TargetDistance[player]*cosAttack[player]*cosRot[player]
eyeY[player] = y - SyncedCamera.TargetDistance[player]*cosAttack[player]*sinRot[player]
eyeZ[player] = GetLocZ(x, y) - SyncedCamera.TargetDistance[player]*sinAttack[player]
else
eyeX[player] = SyncedCamera.EyeX[player]
eyeY[player] = SyncedCamera.EyeY[player]
eyeZ[player] = SyncedCamera.EyeZ[player]
end
yCenterScreenShift[player] = 0.1284*cosAttack[player]
cosAttackCosRot[player] = cosAttack[player]*cosRot[player]
cosAttackSinRot[player] = cosAttack[player]*sinRot[player]
sinAttackCosRot[player] = sinAttack[player]*cosRot[player]
sinAttackSinRot[player] = sinAttack[player]*sinRot[player]
scaleFactor[player] = 0.0524*fieldOfView^3 - 0.0283*fieldOfView^2 + 1.061*fieldOfView
preCalc[player] = true
end
---Takes the world coordinates x, y, and z and returns the screen positions x and y of that point on the specified player's screen. The third return value specifies if the point is on the screen.
---@param x number
---@param y number
---@param z number
---@param player player
---@return number, number, boolean
function World2ScreenSynced(x, y, z, player)
if not preCalc[player] then
CameraPrecalc(player)
end
local dx = x - eyeX[player]
local dy = y - eyeY[player]
local dz = z - eyeZ[player]
local xPrime = scaleFactor[player]*(-cosAttackCosRot[player]*dx - cosAttackSinRot[player]*dy - sinAttack[player]*dz)
local xs = 0.4 + (cosRot[player]*dy - sinRot[player]*dx)/xPrime
local ys = 0.42625 - yCenterScreenShift[player] + (sinAttackCosRot[player]*dx + sinAttackSinRot[player]*dy - cosAttack[player]*dz)/xPrime
return xs, ys, xPrime < 0 and xs > -0.1333 and xs < 0.9333 and ys > 0 and ys < 0.6
end
---Takes the screen coordinates x and y and the player for which the calculation should be performed and returns the x, y, and z world coordinates. The fourth return value specifies whether or not the search for the world intersection point converged. This function may fail when a ray pointing from the camera to the world intersects at multiple points with the terrain.
---@param x number
---@param y number
---@param player player
---@return number, number, number, boolean
function Screen2WorldSynced(x, y, player)
if not preCalc[player] then
CameraPrecalc(player)
end
local a = (x - 0.4)*scaleFactor[player]
local b = (0.42625 - yCenterScreenShift[player] - y)*scaleFactor[player]
--This is the unit vector pointing towards the mouse cursor in the camera's coordinate system.
local nx = 1/sqrt(1 + a*a + b*b)
local ny = sqrt(1 - (1 + b*b)*nx*nx)
local nz = sqrt(1 - nx*nx - ny*ny)
if a > 0 then
ny = -ny
end
if b < 0 then
nz = -nz
end
--Constructs the unit vector pointing from the camera eye position to the mouse cursor.
local nxPrime = cosAttackCosRot[player]*nx - sinRot[player]*ny + sinAttackCosRot[player]*nz
local nyPrime = cosAttackSinRot[player]*nx + cosRot[player]*ny + sinAttackSinRot[player]*nz
local nzPrime = -sinAttack[player]*nx + cosAttack[player]*nz
local eyeX, eyeY, eyeZ = eyeX[player], eyeY[player], eyeZ[player]
--Try to find intersection point of vector with terrain.
local zGuess = GetTerrainZ(eyeX, eyeY)
local xGuess = eyeX + nxPrime*(eyeZ - zGuess)/nzPrime
local yGuess = eyeY + nyPrime*(eyeZ - zGuess)/nzPrime
local zWorld = GetTerrainZ(xGuess, yGuess)
local deltaZ = zWorld - zGuess
zGuess = zWorld
local zWorldOld, deltaZOld
local i = 0
while (deltaZ > 1 or deltaZ < -1) and i < 50 do
zWorldOld = zWorld
deltaZOld = deltaZ
xGuess = eyeX + nxPrime*(eyeZ - zGuess)/nzPrime
yGuess = eyeY + nyPrime*(eyeZ - zGuess)/nzPrime
zWorld = GetTerrainZ(xGuess, yGuess)
deltaZ = zWorld - zGuess
zGuess = (deltaZOld*zWorld - deltaZ*zWorldOld)/(deltaZOld - deltaZ)
i = i + 1
end
return xGuess, yGuess, zWorld, i < 50
end
---@return number, number
function GetTriggerPlayerMouseScreenCoordinates()
local x, y = BlzGetTriggerPlayerMouseX(), BlzGetTriggerPlayerMouseY()
local xs, ys = World2ScreenSynced(x, y, GetTerrainZ(x, y), GetTriggerPlayer())
return xs, ys
end
OnInit.final("World2ScreenSynced", function()
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
TimerStart(CreateTimer(), TIME_STEP, true, function()
for key, __ in pairs(preCalc) do
preCalc[key] = nil
end
end)
end)
end
if Debug then Debug.endFile() end
if Debug then Debug.beginFile "FastWorld2ScreenTransform" end
do
--[[
=============================================================================================================================================================
Fast World2Screen Transform
by Antares
Transform from world to screen coordinates and back.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/.317099/
PrecomputedHeightMap (optional) https://www.hiveworkshop.com/threads/.353477/
=============================================================================================================================================================
A P I
=============================================================================================================================================================
World2Screen(x, y, z, player) Takes the world coordinates x, y, and z and returns the screen positions x and y of that point on the
specified player's screen. The third return value specifies if the point is on the screen.
Screen2World(x, y, player) Takes the screen coordinates x and y and the player for which the calculation should be performed and
returns the x, y, and z world coordinates. The fourth return value specifies whether or not the search for
the world intersection point converged. This function may fail when a ray pointing from the camera to the
world intersects at multiple points with the terrain.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
--The interval between updates of each player's camera parameters.
local TIME_STEP = 0.02 ---@type number
--[[
=============================================================================================================================================================
E N D O F C O N F I G
=============================================================================================================================================================
]]
local cos = math.cos
local sin = math.sin
local sqrt = math.sqrt
local preCalc = false ---@type boolean
local eyeX = 0 ---@type number
local eyeY = 0 ---@type number
local eyeZ = 0 ---@type number
local cosRot = 0 ---@type number
local sinRot = 0 ---@type number
local cosAttack = 0 ---@type number
local sinAttack = 0 ---@type number
local angleOfAttack = 0 ---@type number
local rotation = 0 ---@type number
local cosAttackCosRot = 0 ---@type number
local cosAttackSinRot = 0 ---@type number
local sinAttackCosRot = 0 ---@type number
local sinAttackSinRot = 0 ---@type number
local yCenterScreenShift = 0 ---@type number
local scaleFactor = 0 ---@type number
local GetTerrainZ ---@type function
local moveableLoc ---@type location
local function CameraPrecalc(player)
eyeX = GetCameraEyePositionX()
eyeY = GetCameraEyePositionY()
eyeZ = GetCameraEyePositionZ()
angleOfAttack = GetCameraField(CAMERA_FIELD_ANGLE_OF_ATTACK)
rotation = GetCameraField(CAMERA_FIELD_ROTATION)
local fieldOfView = GetCameraField(CAMERA_FIELD_FIELD_OF_VIEW)
cosAttack = cos(angleOfAttack)
sinAttack = sin(angleOfAttack)
cosRot = cos(rotation)
sinRot = sin(rotation)
yCenterScreenShift = 0.1284*cosAttack
scaleFactor = 0.0524*fieldOfView^3 - 0.0283*fieldOfView^2 + 1.061*fieldOfView
cosAttackCosRot = cosAttack*cosRot
cosAttackSinRot = cosAttack*sinRot
sinAttackCosRot = sinAttack*cosRot
sinAttackSinRot = sinAttack*sinRot
preCalc = true
end
---Takes the world coordinates x, y, and z and returns the screen positions x and y of that point on the specified player's screen. The third return value specifies if the point is on the screen.
---@param x number
---@param y number
---@param z number
---@return number, number, boolean
function World2Screen(x, y, z)
if not preCalc then
CameraPrecalc()
end
local dx = x - eyeX
local dy = y - eyeY
local dz = z - eyeZ
local xPrime = scaleFactor*(-cosAttackCosRot*dx - cosAttackSinRot*dy - sinAttack*dz)
local xs = 0.4 + (cosRot*dy - sinRot*dx)/xPrime
local ys = 0.42625 - yCenterScreenShift + (sinAttackCosRot*dx + sinAttackSinRot*dy - cosAttack*dz)/xPrime
return xs, ys, xPrime < 0 and xs > -0.1333 and xs < 0.9333 and ys > 0 and ys < 0.6
end
---Takes the screen coordinates x and y and the player for which the calculation should be performed and returns the x, y, and z world coordinates. The fourth return value specifies whether or not the search for the world intersection point converged. This function may fail when a ray pointing from the camera to the world intersects at multiple points with the terrain.
---@param x number
---@param y number
---@return number, number, number, boolean
function Screen2World(x, y)
if not preCalc then
CameraPrecalc()
end
local a = (x - 0.4)*scaleFactor
local b = (0.42625 - yCenterScreenShift - y)*scaleFactor
--This is the unit vector pointing towards the mouse cursor in the camera's coordinate system.
local nx = 1/sqrt(1 + a*a + b*b)
local ny = sqrt(1 - (1 + b*b)*nx*nx)
local nz = sqrt(1 - nx*nx - ny*ny)
if a > 0 then
ny = -ny
end
if b < 0 then
nz = -nz
end
--Constructs the unit vector pointing from the camera eye position to the mouse cursor.
local nxPrime = cosAttackCosRot*nx - sinRot*ny + sinAttackCosRot*nz
local nyPrime = cosAttackSinRot*nx + cosRot*ny + sinAttackSinRot*nz
local nzPrime = -sinAttack*nx + cosAttack*nz
--Try to find intersection point of vector with terrain.
local zGuess = GetTerrainZ(eyeX, eyeY)
local xGuess = eyeX + nxPrime*(eyeZ - zGuess)/nzPrime
local yGuess = eyeY + nyPrime*(eyeZ - zGuess)/nzPrime
local zWorld = GetTerrainZ(xGuess, yGuess)
local deltaZ = zWorld - zGuess
zGuess = zWorld
local zWorldOld, deltaZOld
local i = 0
while (deltaZ > 1 or deltaZ < -1) and i < 50 do
zWorldOld = zWorld
deltaZOld = deltaZ
xGuess = eyeX + nxPrime*(eyeZ - zGuess)/nzPrime
yGuess = eyeY + nyPrime*(eyeZ - zGuess)/nzPrime
zWorld = GetTerrainZ(xGuess, yGuess)
deltaZ = zWorld - zGuess
zGuess = (deltaZOld*zWorld - deltaZ*zWorldOld)/(deltaZOld - deltaZ)
i = i + 1
end
return xGuess, yGuess, zWorld, i < 50
end
OnInit.final("World2Screen", function()
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
TimerStart(CreateTimer(), TIME_STEP, true, function()
preCalc = false
end)
end)
end
if Debug then Debug.endFile() end
if Debug then Debug.beginFile "PrecomputedHeightMap" end ---@diagnostic disable: param-type-mismatch
do
--[[
===============================================================================================================================================================
Precomputed Height Map
by Antares
===============================================================================================================================================================
GetLocZ(x, y) Returns the same value as GetLocationZ(x, y).
GetTerrainZ(x, y) Returns the exact height of the terrain geometry.
GetUnitZ(whichUnit) Returns the same value as BlzGetUnitZ(whichUnit).
GetUnitCoordinates(whichUnit) Returns x, y, and z-coordinates of a unit.
===============================================================================================================================================================
Computes the terrain height of your map on map initialization for later use. The function GetLocZ replaces the traditional GetLocZ, defined as:
function GetLocZ(x, y)
MoveLocation(moveableLoc, x, y)
return GetLocationZ(moveableLoc)
end
The function provided in this library cannot cause desyncs and is approximately twice as fast. GetTerrainZ is a variation of GetLocZ that returns the exact height
of the terrain geometry (around cliffs, it has to approximate).
Note: PrecomputedHeightMap initializes OnitInit.final, because otherwise walkable doodads would not be registered.
===============================================================================================================================================================
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.
--=============================================================================================================================================================
C O N F I G
--=============================================================================================================================================================
]]
local SUBFOLDER = "PrecomputedHeightMap"
--Where to store data when exporting height map.
local STORE_CLIFF_DATA = true
--If set to false, GetTerrainZ will be less accurate around cliffs, but slightly faster.
local WRITE_HEIGHT_MAP = false
--Write height map to file?
local VALIDATE_HEIGHT_MAP = true
--Check if height map read from string is accurate.
local VISUALIZE_HEIGHT_MAP = false
--Create a special effect at each grid point to double-check if the height map is correct.
--=============================================================================================================================================================
local heightMap = {} ---@type table[]
local terrainHasCliffs = {} ---@type table[]
local terrainCliffLevel = {} ---@type table[]
local moveableLoc = nil ---@type location
local MINIMUM_Z = -256 ---@type number
local CLIFF_HEIGHT = 128 ---@type number
local worldMinX
local worldMinY
local worldMaxX
local worldMaxY
local iMax
local jMax
local chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
local NUMBER_OF_CHARS = 52
---@param x number
---@param y number
---@return number
function GetLocZ(x, y)
MoveLocation(moveableLoc, x, y)
return GetLocationZ(moveableLoc)
end
GetTerrainZ = GetLocZ
---@param whichUnit unit
---@return number
function GetUnitZ(whichUnit)
return GetLocZ(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, GetLocZ(x, y) + GetUnitFlyHeight(whichUnit)
end
local function OverwriteHeightFunctions()
---@param x number
---@param y number
---@return number
GetLocZ = function(x, y)
local rx = (x - worldMinX)*0.0078125 + 1
local ry = (y - worldMinY)*0.0078125 + 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
local heightMapI = heightMap[i]
local heightMapIp1 = heightMap[i+1]
return (1 - ry)*((1 - rx)*heightMapI[j] + rx*heightMapIp1[j]) + ry*((1 - rx)*heightMapI[j+1] + rx*heightMapIp1[j+1])
end
if STORE_CLIFF_DATA then
---@param x number
---@param y number
---@return number
function GetTerrainZ(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 (1 - rx - ry)*heightMap[i][j] + (rx*(heightMap[i+1][j] - CLIFF_HEIGHT*(terrainCliffLevel[i+1][j] - terrainCliffLevel[i][j])) + ry*(heightMap[i][j+1] - CLIFF_HEIGHT*(terrainCliffLevel[i][j+1] - terrainCliffLevel[i][j])))
elseif rx + ry > 1 then
return (rx + ry - 1)*(heightMap[i+1][j+1] - CLIFF_HEIGHT*(terrainCliffLevel[i+1][j+1] - terrainCliffLevel[i][j+1])) + ((1 - rx)*heightMap[i][j+1] + (1 - ry)*(heightMap[i+1][j] - CLIFF_HEIGHT*(terrainCliffLevel[i+1][j] - terrainCliffLevel[i][j+1])))
else
return (1 - rx - ry)*(heightMap[i][j] - CLIFF_HEIGHT*(terrainCliffLevel[i][j] - terrainCliffLevel[i][j+1])) + (rx*(heightMap[i+1][j] - CLIFF_HEIGHT*(terrainCliffLevel[i+1][j] - terrainCliffLevel[i][j+1])) + ry*heightMap[i][j+1])
end
elseif ry < 0.5 then
if rx + ry > 1 then
return (rx + ry - 1)*(heightMap[i+1][j+1] - CLIFF_HEIGHT*(terrainCliffLevel[i+1][j+1] - terrainCliffLevel[i+1][j])) + ((1 - rx)*(heightMap[i][j+1] - CLIFF_HEIGHT*(terrainCliffLevel[i][j+1] - terrainCliffLevel[i+1][j])) + (1 - ry)*heightMap[i+1][j])
else
return (1 - rx - ry)*(heightMap[i][j] - CLIFF_HEIGHT*(terrainCliffLevel[i][j] - terrainCliffLevel[i+1][j])) + (rx*heightMap[i+1][j] + ry*(heightMap[i][j+1] - CLIFF_HEIGHT*(terrainCliffLevel[i][j+1] - terrainCliffLevel[i+1][j])))
end
else
return (rx + ry - 1)*heightMap[i+1][j+1] + ((1 - rx)*(heightMap[i][j+1] - CLIFF_HEIGHT*(terrainCliffLevel[i][j+1] - terrainCliffLevel[i+1][j+1])) + (1 - ry)*(heightMap[i+1][j] - CLIFF_HEIGHT*(terrainCliffLevel[i+1][j] - terrainCliffLevel[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
else
---@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
end
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] = {}
if STORE_CLIFF_DATA then
terrainHasCliffs[i] = {}
terrainCliffLevel[i] = {}
end
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 + 128, y + 128)
if level1 ~= level2 or level1 ~= level3 or level1 ~= level4 then
terrainHasCliffs[i][j] = true
end
terrainCliffLevel[i][j] = level1
end
j = j + 1
y = y + 128
end
i = i + 1
x = x + 128
end
iMax = i - 2
jMax = j - 2
OverwriteHeightFunctions()
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] = {}
if STORE_CLIFF_DATA then
terrainHasCliffs[i] = {}
terrainCliffLevel[i] = {}
end
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 + 128, y + 128)
if level1 ~= level2 or level1 ~= level3 or level1 ~= level4 then
terrainHasCliffs[i][j] = true
end
terrainCliffLevel[i][j] = level1
end
j = j + 1
y = y + 128
end
i = i + 1
x = x + 128
end
end
OnInit.final("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
do
--[[
=============================================================================================================================================================
Synced Camera
by Antares
Continuously syncs player camera parameters and writes them into a table.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/.317099/
=============================================================================================================================================================
]]
local TIME_STEP = 0.02
local zeroTable = {__index = function(self, key) return 0 end}
SyncedCamera = {
EyeX = setmetatable({}, zeroTable),
EyeY = setmetatable({}, zeroTable),
EyeZ = setmetatable({}, zeroTable),
AngleOfAttack = setmetatable({}, zeroTable),
Rotation = setmetatable({}, zeroTable),
FieldOfView = setmetatable({}, zeroTable),
TargetDistance = setmetatable({}, zeroTable)
}
--===========================================================================================================================================================
local EPSILON = 0.001
local localPlayer
local syncReady = {}
local abs = math.abs
OnInit.final(function()
localPlayer = GetLocalPlayer()
local trig = CreateTrigger()
for i = 0, bj_MAX_PLAYER_SLOTS - 1 do
syncReady[Player(i)] = true
BlzTriggerRegisterPlayerSyncEvent(trig, Player(i), "SyncCamera", false)
end
TriggerAddAction(trig, function()
local data = BlzGetTriggerSyncData()
local nextComma = data:find(",")
local player = Player(tonumber(data:sub(1, nextComma - 1)) - 1)
data = data:sub(nextComma + 1, data:len())
nextComma = data:find(",")
SyncedCamera.EyeX[player] = tonumber(data:sub(1, nextComma - 1))
data = data:sub(nextComma + 1, data:len())
nextComma = data:find(",")
SyncedCamera.EyeY[player] = tonumber(data:sub(1, nextComma - 1))
data = data:sub(nextComma + 1, data:len())
nextComma = data:find(",")
SyncedCamera.EyeZ[player] = tonumber(data:sub(1, nextComma - 1))
data = data:sub(nextComma + 1, data:len())
nextComma = data:find(",")
SyncedCamera.AngleOfAttack[player] = tonumber(data:sub(1, nextComma - 1))
data = data:sub(nextComma + 1, data:len())
nextComma = data:find(",")
SyncedCamera.Rotation[player] = tonumber(data:sub(1, nextComma - 1))
data = data:sub(nextComma + 1, data:len())
nextComma = data:find(",")
SyncedCamera.FieldOfView[player] = tonumber(data:sub(1, nextComma - 1))
data = data:sub(nextComma + 1, data:len())
SyncedCamera.TargetDistance[player] = tonumber(data)
syncReady[player] = true
end)
TimerStart(CreateTimer(), TIME_STEP, true, function()
local eyeX = GetCameraEyePositionX()
local eyeY = GetCameraEyePositionY()
local eyeZ = GetCameraEyePositionZ()
local angleOfAttack = GetCameraField(CAMERA_FIELD_ANGLE_OF_ATTACK)
local rotation = GetCameraField(CAMERA_FIELD_ROTATION)
local fieldOfView = GetCameraField(CAMERA_FIELD_FIELD_OF_VIEW)
local targetDistance = GetCameraField(CAMERA_FIELD_TARGET_DISTANCE)
if syncReady[localPlayer] and (abs(eyeX - SyncedCamera.EyeX[localPlayer]) > EPSILON or
abs(eyeY - SyncedCamera.EyeY[localPlayer]) > EPSILON or
abs(eyeZ - SyncedCamera.EyeZ[localPlayer]) > EPSILON or
abs(angleOfAttack - SyncedCamera.AngleOfAttack[localPlayer]) > EPSILON or
abs(rotation - SyncedCamera.Rotation[localPlayer]) > EPSILON or
abs(fieldOfView - SyncedCamera.FieldOfView[localPlayer]) > EPSILON or
abs(targetDistance - SyncedCamera.TargetDistance[localPlayer]) > EPSILON) then
syncReady[localPlayer] = false
BlzSendSyncData("SyncCamera",
GetPlayerId(localPlayer) + 1 .. ","
.. tostring(eyeX) .. ","
.. tostring(eyeY) .. ","
.. tostring(eyeZ) .. ","
.. tostring(angleOfAttack) .. ","
.. tostring(rotation) .. ","
.. tostring(fieldOfView) .. ","
.. tostring(targetDistance))
end
end)
end)
end
if Debug then Debug.beginFile "RPG Control" end
do
--[[
=============================================================================================================================================================
RPG Controls
by Antares
A movement system for RPGs and other single-hero maps that includes click-and-hold movement and auto-walk.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/.317099/
Fixed Camera Lock (optional) https://www.hiveworkshop.com/threads/.354970/
World2Screen Transform Synced (optional) https://www.hiveworkshop.com/threads/.354017/
PrecomputedHeightMap (optional) https://www.hiveworkshop.com/threads/.353477/
Synced Camera (optional) Included in World2Screen Transform.
PathingWizard (optional) https://www.hiveworkshop.com/threads/.355027/
=============================================================================================================================================================
A P I
=============================================================================================================================================================
EnableRPGControls(enable, whichPlayer) Enables or disables the system for a player or for all players if not specified.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
--Disables the click-and-hold trigger for this many seconds when a hero casts a spell. This enables the user to cast a spell without releasing the right
--mouse-button.
local IGNORE_MOUSE_SPELL_DURATION = 0.5 ---@constant number
--Disables the click-and-hold trigger for this many seconds right after the right mouse-button is pressed. This prevents the trigger from firing on a simple
--right-click.
local IGNORE_MOUSE_CLICK_DURATION = 0.25 ---@constant number
--How often the check of the mouse-position is performed.
local CHECK_INTERVAL = 0.1 ---@constant number
--The minimum angle difference in degrees between the current movement direction of the hero and the angle from the hero to the mouse cursor before a new
--command is given. If too many commands are given, the hero will slow down.
local MIN_ANGLE_DELTA = 5 ---@constant number
--When the hero comes closer to the last ordered point than this value, a new command will be given.
local MIN_DISTANCE = 100 ---@constant number
--The hotkey to toggle auto-walk. Set nil to disable.
local AUTO_WALK_HOTKEY = OSKEY_TAB ---@constant oskeytype
--If you're using the Fixed Camera Lock system, enable this option to make RPG Controls compatible. Requires World2ScreenSynced and SyncedCameras.
local USE_FIXED_CAMERA_LOCK = true ---@constant boolean
--If enabled, the hero will ignore obstacles and walk in a straight line in the direction of the mouse-cursor until it can no longer go any further.
--Requires PathingWizard.
local NO_PATHING = true ---@constant boolean
--If you have NO_PATHING enabled, you can additionally enable this to also apply the same behavior to normal mouse right-clicks.
local NO_PATHING_ON_NORMAL_CLICK = true ---@constant boolean
--Without this set, the hero would constantly get stuck on corners when NO_PATHING is enabled. Increase if the hero still gets stuck.
local OBSTACLE_BYPASS_DISTANCE = 100 ---@constant number
--If enabled, the system will be on sleep as long as the hero of the player is not selected.
local CHECK_SELECTION = false ---@constant boolean
--Spells added to this list won't disable click-and-hold movement or auto-walk.
local SPELL_EXCEPTIONS = { ---@constant string[]
"Absk"
}
--This function should return the unit that should get ordered.
local function GetHeroOfPlayer(whichPlayer)
return FCL_Anchor[whichPlayer]
end
--===========================================================================================================================================================
local zeroTable = {__index = function(self, key) self[key] = 0 return 0 end}
local mouseX = setmetatable({}, zeroTable)
local mouseY = setmetatable({}, zeroTable)
local currentOrderX = setmetatable({}, zeroTable)
local currentOrderY = setmetatable({}, zeroTable)
local rightClickOn = {}
local autoWalkEnabled = {}
local mouseIgnore = {}
local loopTimerOfPlayer = {}
local ignoreToggleTimerOfPlayer = {}
local playerOfTimer = {}
local SMART = 851971
local spellKeyList = {}
local commandTrigger
local acos, sqrt, atan, cos, sin, pi = math.acos, math.sqrt, math.atan, math.cos, math.sin, math.pi
local function UpdateOrder(whichPlayer, whichHero, desiredX, desiredY)
if AUTO_WALK_HOTKEY then
DisableTrigger(commandTrigger)
end
currentOrderX[whichPlayer] = desiredX
currentOrderY[whichPlayer] = desiredY
IssuePointOrderById(whichHero, SMART, desiredX, desiredY)
if AUTO_WALK_HOTKEY then
EnableTrigger(commandTrigger)
end
end
local function GetAdjustedPoint(xHero, yHero, orderX, orderY)
local desiredX, desiredY, endPointReached = GetFurthestAccessiblePoint(xHero, yHero, orderX, orderY)
if not endPointReached then
local dist = sqrt((xHero - desiredX)^2 + (yHero - desiredY)^2)
if dist < MIN_DISTANCE then
local angle = atan(orderY - yHero, orderX - xHero)
local newStartX, newStartY = xHero + OBSTACLE_BYPASS_DISTANCE*cos(angle + pi/2), yHero + OBSTACLE_BYPASS_DISTANCE*sin(angle + pi/2)
local testX, testY = GetFurthestAccessiblePoint(newStartX, newStartY, orderX, orderY)
dist = sqrt((newStartX - testX)^2 + (newStartY - testY)^2)
if dist > MIN_DISTANCE then
desiredX, desiredY = testX, testY
else
newStartX, newStartY = xHero - OBSTACLE_BYPASS_DISTANCE*cos(angle + pi/2), yHero - OBSTACLE_BYPASS_DISTANCE*sin(angle + pi/2)
testX, testY = GetFurthestAccessiblePoint(newStartX, newStartY, orderX, orderY)
dist = sqrt((newStartX - testX)^2 + (newStartY - testY)^2)
if dist > MIN_DISTANCE then
desiredX, desiredY = testX, testY
end
end
end
end
return desiredX, desiredY, endPointReached
end
local function GetDesiredPoint(whichPlayer)
if USE_FIXED_CAMERA_LOCK then
return Screen2WorldSynced(mouseX[whichPlayer], mouseY[whichPlayer], whichPlayer)
else
local desiredX, desiredY = mouseX[whichPlayer], mouseY[whichPlayer]
return desiredX, desiredY, desiredX ~= 0 or desiredY ~= 0
end
end
local function Loop()
local whichPlayer = playerOfTimer[GetExpiredTimer()]
if (not rightClickOn[whichPlayer] or mouseIgnore[whichPlayer]) and not autoWalkEnabled[whichPlayer] then
return
end
local desiredX, desiredY, validMousePosition = GetDesiredPoint(whichPlayer)
if not validMousePosition then
return
end
local whichHero = GetHeroOfPlayer(whichPlayer)
if whichHero == nil then
return
end
if CHECK_SELECTION and not IsUnitSelected(whichHero, whichPlayer) then
return
end
local xHero, yHero = GetUnitX(whichHero), GetUnitY(whichHero)
if NO_PATHING then
desiredX, desiredY = GetAdjustedPoint(xHero, yHero, desiredX, desiredY)
end
local dxOld, dyOld = currentOrderX[whichPlayer] - xHero, currentOrderY[whichPlayer] - yHero
local dxNew, dyNew = desiredX - xHero, desiredY - yHero
local distOld = sqrt(dxOld*dxOld + dyOld*dyOld)
if distOld < MIN_DISTANCE then
UpdateOrder(whichPlayer, whichHero, desiredX, desiredY)
else
local distNew = sqrt(dxNew*dxNew + dyNew*dyNew)
local angleDelta = acos((dxOld*dxNew + dyOld*dyNew)/(distOld*distNew))
if angleDelta > bj_DEGTORAD*MIN_ANGLE_DELTA then
UpdateOrder(whichPlayer, whichHero, desiredX, desiredY)
end
end
end
local function OnPointOrder()
local whichUnit = GetTriggerUnit()
local whichPlayer = GetOwningPlayer(whichUnit)
if whichUnit ~= GetHeroOfPlayer(whichPlayer) then
return
end
autoWalkEnabled[whichPlayer] = false
if NO_PATHING and NO_PATHING_ON_NORMAL_CLICK and (not rightClickOn[whichPlayer] or mouseIgnore[whichPlayer]) and GetIssuedOrderId() == SMART then
local xHero, yHero = GetUnitX(whichUnit), GetUnitY(whichUnit)
local orderX, orderY = GetOrderPointX(), GetOrderPointY()
local desiredX, desiredY, endPointReached = GetAdjustedPoint(xHero, yHero, orderX, orderY)
if not endPointReached then
DisableTrigger(commandTrigger)
currentOrderX[whichPlayer] = desiredX
currentOrderY[whichPlayer] = desiredY
IssuePointOrderById(whichUnit, SMART, desiredX, desiredY)
EnableTrigger(commandTrigger)
end
end
end
local function ToggleAutoWalk()
local whichPlayer = GetTriggerPlayer()
autoWalkEnabled[whichPlayer] = not autoWalkEnabled[whichPlayer]
if not rightClickOn[whichPlayer] then
if autoWalkEnabled[whichPlayer] then
TimerStart(loopTimerOfPlayer[whichPlayer], CHECK_INTERVAL, true, Loop)
else
local hero = GetHeroOfPlayer(whichPlayer)
IssueImmediateOrder(hero, "stop")
PauseTimer(loopTimerOfPlayer[whichPlayer])
currentOrderX[whichPlayer] = GetUnitX(hero)
currentOrderY[whichPlayer] = GetUnitY(hero)
end
end
end
local function DisableIgnore()
mouseIgnore[playerOfTimer[GetExpiredTimer()]] = false
end
local function MouseSpellIgnore()
if spellKeyList[GetSpellAbilityId()] then
return
end
local whichUnit = GetSpellAbilityUnit()
local whichPlayer = GetOwningPlayer(whichUnit)
if whichUnit == GetHeroOfPlayer(whichPlayer) then
mouseIgnore[whichPlayer] = true
autoWalkEnabled[whichPlayer] = false
TimerStart(ignoreToggleTimerOfPlayer[whichPlayer], IGNORE_MOUSE_SPELL_DURATION, false, DisableIgnore)
end
end
local function MouseMove()
local whichPlayer = GetTriggerPlayer()
if USE_FIXED_CAMERA_LOCK then
mouseX[whichPlayer], mouseY[whichPlayer] = GetTriggerPlayerMouseScreenCoordinates()
else
mouseX[whichPlayer], mouseY[whichPlayer] = BlzGetTriggerPlayerMouseX(), BlzGetTriggerPlayerMouseY()
end
end
local function MouseRightClick()
if BlzGetTriggerPlayerMouseButton() == MOUSE_BUTTON_TYPE_RIGHT then
local whichPlayer = GetTriggerPlayer()
rightClickOn[whichPlayer] = true
mouseIgnore[whichPlayer] = true
TimerStart(ignoreToggleTimerOfPlayer[whichPlayer], IGNORE_MOUSE_CLICK_DURATION, false, DisableIgnore)
if not autoWalkEnabled[whichPlayer] then
TimerStart(loopTimerOfPlayer[whichPlayer], CHECK_INTERVAL, true, Loop)
end
end
end
local function MouseRightRelease()
if BlzGetTriggerPlayerMouseButton() == MOUSE_BUTTON_TYPE_RIGHT then
local whichPlayer = GetTriggerPlayer()
if rightClickOn[whichPlayer] then
rightClickOn[whichPlayer] = false
if not mouseIgnore[whichPlayer] then
local desiredX, desiredY, validMousePosition = GetDesiredPoint(whichPlayer)
if validMousePosition then
local whichHero = GetHeroOfPlayer(whichPlayer)
if whichHero == nil then
return
end
if NO_PATHING then
local xHero, yHero = GetUnitX(whichHero), GetUnitY(whichHero)
desiredX, desiredY = GetAdjustedPoint(xHero, yHero, desiredX, desiredY)
end
IssuePointOrderById(GetHeroOfPlayer(whichPlayer), SMART, desiredX, desiredY)
end
end
if not autoWalkEnabled[whichPlayer] then
PauseTimer(loopTimerOfPlayer[whichPlayer])
end
end
end
end
OnInit.final("RPGControls", function()
if USE_FIXED_CAMERA_LOCK then
local fixedCameraLock = Require.optionally "FixedCameraLock"
local world2ScreenSynced = Require.optionally "World2ScreenSynced"
if not fixedCameraLock then
USE_FIXED_CAMERA_LOCK = false
elseif not world2ScreenSynced then
USE_FIXED_CAMERA_LOCK = false
print("|cffff0000Warning:|r USE_FIXED_CAMERA_LOCK requires World2ScreenSynced.")
end
end
if (NO_PATHING or NO_PATHING_ON_NORMAL_CLICK) and not GetFurthestAccessiblePoint then
NO_PATHING = false
NO_PATHING_ON_NORMAL_CLICK = false
print("|cffff0000Warning:|r NO_PATHING requires PathingWizard.")
end
local whichPlayer
local trigDown = CreateTrigger()
local trigUp = CreateTrigger()
local trigIgnore = CreateTrigger()
local trigMove = CreateTrigger()
local trigAutoWalk
if AUTO_WALK_HOTKEY then
trigAutoWalk = CreateTrigger()
TriggerAddAction(trigAutoWalk, ToggleAutoWalk)
commandTrigger = CreateTrigger()
TriggerAddAction(commandTrigger, OnPointOrder)
end
for i = 0, 23 do
whichPlayer = Player(i)
if GetPlayerSlotState(whichPlayer) == PLAYER_SLOT_STATE_PLAYING and GetPlayerController(whichPlayer) == MAP_CONTROL_USER then
TriggerRegisterPlayerEvent(trigDown, whichPlayer, EVENT_PLAYER_MOUSE_DOWN)
TriggerRegisterPlayerEvent(trigUp, whichPlayer, EVENT_PLAYER_MOUSE_UP)
TriggerRegisterPlayerEvent(trigMove, whichPlayer, EVENT_PLAYER_MOUSE_MOVE)
TriggerRegisterPlayerUnitEvent(commandTrigger, whichPlayer, EVENT_PLAYER_UNIT_ISSUED_POINT_ORDER)
BlzTriggerRegisterPlayerKeyEvent(trigAutoWalk, whichPlayer, AUTO_WALK_HOTKEY, 0, true)
loopTimerOfPlayer[whichPlayer] = CreateTimer()
ignoreToggleTimerOfPlayer[whichPlayer] = CreateTimer()
playerOfTimer[loopTimerOfPlayer[whichPlayer]] = whichPlayer
playerOfTimer[ignoreToggleTimerOfPlayer[whichPlayer]] = whichPlayer
end
i = i + 1
end
TriggerAddAction(trigMove, MouseMove)
TriggerAddAction(trigDown, MouseRightClick)
TriggerAddAction(trigUp, MouseRightRelease)
TriggerRegisterAnyUnitEventBJ(trigIgnore, EVENT_PLAYER_UNIT_SPELL_CAST)
TriggerAddAction(trigIgnore, MouseSpellIgnore)
for __, fourCC in ipairs(SPELL_EXCEPTIONS) do
spellKeyList[FourCC(fourCC)] = true
end
end)
---@param enable? boolean
---@param whichPlayer? player
function EnableRPGControls(enable, whichPlayer)
enable = enable ~= false
if whichPlayer then
if enable then
TimerStart(loopTimerOfPlayer[whichPlayer], CHECK_INTERVAL, true, Loop)
else
PauseTimer(loopTimerOfPlayer[whichPlayer])
end
else
for i = 0, 23 do
whichPlayer = Player(i)
if enable then
if GetPlayerSlotState(whichPlayer) == PLAYER_SLOT_STATE_PLAYING and GetPlayerController(whichPlayer) == MAP_CONTROL_USER then
TimerStart(loopTimerOfPlayer[whichPlayer], CHECK_INTERVAL, true, Loop)
end
elseif GetPlayerSlotState(whichPlayer) == PLAYER_SLOT_STATE_PLAYING and GetPlayerController(whichPlayer) == MAP_CONTROL_USER then
PauseTimer(loopTimerOfPlayer[whichPlayer])
end
i = i + 1
end
end
end
end
if Debug then Debug.endFile() end
if Debug then Debug.beginFile "RPG Control" end
do
--[[
=============================================================================================================================================================
RPG Controls (Singleplayer)
by Antares
A movement system for RPGs and other single-hero maps that includes click-and-hold movement and auto-walk.
Requires:
TotalInitialization https://www.hiveworkshop.com/threads/.317099/
World2Screen Transform (optional) https://www.hiveworkshop.com/threads/.354017/
PathingWizard (optional) https://www.hiveworkshop.com/threads/.355027/
Precomputed Height Map (optional) https://www.hiveworkshop.com/threads/.353477/
=============================================================================================================================================================
A P I
=============================================================================================================================================================
EnableRPGControls(enable) Enables or disables the system.
=============================================================================================================================================================
C O N F I G
=============================================================================================================================================================
]]
--Disables the click-and-hold trigger for this many seconds when a hero casts a spell. This enables the user to cast a spell without releasing the right
--mouse-button.
local IGNORE_MOUSE_SPELL_DURATION = 0.5 ---@constant number
--Disables the click-and-hold trigger for this many seconds right after the right mouse-button is pressed. This prevents the trigger from firing on a simple
--right-click.
local IGNORE_MOUSE_CLICK_DURATION = 0.25 ---@constant number
--How often the check of the mouse-position is performed.
local CHECK_INTERVAL = 0.1 ---@constant number
--The minimum angle difference in degrees between the current movement direction of the hero and the angle from the hero to the mouse cursor before a new
--command is given. If too many commands are given, the hero will slow down.
local MIN_ANGLE_DELTA = 5 ---@constant number
--When the hero comes closer to the last ordered point than this value, a new command will be given.
local MIN_DISTANCE = 100 ---@constant number
--The hotkey to toggle auto-walk. Set nil to disable.
local AUTO_WALK_HOTKEY = OSKEY_TAB ---@constant oskeytype
--If enabled, the hero will ignore obstacles and walk in a straight line in the direction of the mouse-cursor until it can no longer go any further.
--Requires PathingWizard.
local NO_PATHING = true ---@constant boolean
--If you have NO_PATHING enabled, you can additionally enable this to also apply the same behavior to normal mouse right-clicks.
local NO_PATHING_ON_NORMAL_CLICK = true ---@constant boolean
--Without this set, the hero would constantly get stuck on corners when NO_PATHING is enabled. Increase if the hero still gets stuck.
local OBSTACLE_BYPASS_DISTANCE = 100 ---@constant number
--If enabled, the system will be on sleep as long as the hero of the player is not selected.
local CHECK_SELECTION = false ---@constant boolean
--Spells added to this list won't disable click-and-hold movement or auto-walk.
local SPELL_EXCEPTIONS = { ---@constant string[]
"Absk"
}
--This function should return the unit that should get ordered.
local function GetHero()
return FCL_Anchor[Player(0)]
end
--===========================================================================================================================================================
local zeroTable = {__index = function(self, key) self[key] = 0 return 0 end}
local mouseX = setmetatable({}, zeroTable)
local mouseY = setmetatable({}, zeroTable)
local currentOrderX = setmetatable({}, zeroTable)
local currentOrderY = setmetatable({}, zeroTable)
local rightClickOn = {}
local autoWalkEnabled = {}
local mouseIgnore = {}
local loopTimerOfPlayer = {}
local ignoreToggleTimerOfPlayer = {}
local playerOfTimer = {}
local world2Screen ---@type boolean
local SMART = 851971
local spellKeyList = {}
local commandTrigger = nil ---@type trigger
local GetTerrainZ = nil ---@type function
local moveableLoc = nil ---@type location
local acos, sqrt, atan, cos, sin, pi = math.acos, math.sqrt, math.atan, math.cos, math.sin, math.pi
local function UpdateOrder(whichPlayer, whichHero, desiredX, desiredY)
if AUTO_WALK_HOTKEY then
DisableTrigger(commandTrigger)
end
currentOrderX[whichPlayer] = desiredX
currentOrderY[whichPlayer] = desiredY
IssuePointOrderById(whichHero, SMART, desiredX, desiredY)
if AUTO_WALK_HOTKEY then
EnableTrigger(commandTrigger)
end
end
local function GetAdjustedPoint(xHero, yHero, orderX, orderY)
local desiredX, desiredY, endPointReached = GetFurthestAccessiblePoint(xHero, yHero, orderX, orderY)
if not endPointReached then
local dist = sqrt((xHero - desiredX)^2 + (yHero - desiredY)^2)
if dist < MIN_DISTANCE then
local angle = atan(orderY - yHero, orderX - xHero)
local newStartX, newStartY = xHero + OBSTACLE_BYPASS_DISTANCE*cos(angle + pi/2), yHero + OBSTACLE_BYPASS_DISTANCE*sin(angle + pi/2)
local testX, testY = GetFurthestAccessiblePoint(newStartX, newStartY, orderX, orderY)
dist = sqrt((newStartX - testX)^2 + (newStartY - testY)^2)
if dist > MIN_DISTANCE then
desiredX, desiredY = testX, testY
else
newStartX, newStartY = xHero - OBSTACLE_BYPASS_DISTANCE*cos(angle + pi/2), yHero - OBSTACLE_BYPASS_DISTANCE*sin(angle + pi/2)
testX, testY = GetFurthestAccessiblePoint(newStartX, newStartY, orderX, orderY)
dist = sqrt((newStartX - testX)^2 + (newStartY - testY)^2)
if dist > MIN_DISTANCE then
desiredX, desiredY = testX, testY
end
end
end
end
return desiredX, desiredY, endPointReached
end
local function GetDesiredPoint(whichPlayer)
if world2Screen then
return Screen2World(mouseX[whichPlayer], mouseY[whichPlayer])
else
local desiredX, desiredY = mouseX[whichPlayer], mouseY[whichPlayer]
return desiredX, desiredY, desiredX ~= 0 or desiredY ~= 0
end
end
local function Loop()
local whichPlayer = playerOfTimer[GetExpiredTimer()]
if (not rightClickOn[whichPlayer] or mouseIgnore[whichPlayer]) and not autoWalkEnabled[whichPlayer] then
return
end
local desiredX, desiredY, validMousePosition = GetDesiredPoint(whichPlayer)
if not validMousePosition then
return
end
local whichHero = GetHero()
if whichHero == nil then
return
end
if CHECK_SELECTION and not IsUnitSelected(whichHero, whichPlayer) then
return
end
local xHero, yHero = GetUnitX(whichHero), GetUnitY(whichHero)
if NO_PATHING then
desiredX, desiredY = GetAdjustedPoint(xHero, yHero, desiredX, desiredY)
end
local dxOld, dyOld = currentOrderX[whichPlayer] - xHero, currentOrderY[whichPlayer] - yHero
local dxNew, dyNew = desiredX - xHero, desiredY - yHero
local distOld = sqrt(dxOld*dxOld + dyOld*dyOld)
if distOld < MIN_DISTANCE then
UpdateOrder(whichPlayer, whichHero, desiredX, desiredY)
else
local distNew = sqrt(dxNew*dxNew + dyNew*dyNew)
local angleDelta = acos((dxOld*dxNew + dyOld*dyNew)/(distOld*distNew))
if angleDelta > bj_DEGTORAD*MIN_ANGLE_DELTA then
UpdateOrder(whichPlayer, whichHero, desiredX, desiredY)
end
end
end
local function OnPointOrder()
local whichUnit = GetTriggerUnit()
local whichPlayer = GetOwningPlayer(whichUnit)
if whichUnit ~= GetHero() then
return
end
autoWalkEnabled[whichPlayer] = false
if NO_PATHING and NO_PATHING_ON_NORMAL_CLICK and (not rightClickOn[whichPlayer] or mouseIgnore[whichPlayer]) and GetIssuedOrderId() == SMART then
local xHero, yHero = GetUnitX(whichUnit), GetUnitY(whichUnit)
local orderX, orderY = GetOrderPointX(), GetOrderPointY()
local desiredX, desiredY, endPointReached = GetAdjustedPoint(xHero, yHero, orderX, orderY)
if not endPointReached then
DisableTrigger(commandTrigger)
currentOrderX[whichPlayer] = desiredX
currentOrderY[whichPlayer] = desiredY
IssuePointOrderById(whichUnit, SMART, desiredX, desiredY)
EnableTrigger(commandTrigger)
end
end
end
local function ToggleAutoWalk()
local whichPlayer = GetTriggerPlayer()
autoWalkEnabled[whichPlayer] = not autoWalkEnabled[whichPlayer]
if not rightClickOn[whichPlayer] then
if autoWalkEnabled[whichPlayer] then
TimerStart(loopTimerOfPlayer[whichPlayer], CHECK_INTERVAL, true, Loop)
else
local hero = GetHero()
IssueImmediateOrder(hero, "stop")
PauseTimer(loopTimerOfPlayer[whichPlayer])
currentOrderX[whichPlayer] = GetUnitX(hero)
currentOrderY[whichPlayer] = GetUnitY(hero)
end
end
end
local function DisableIgnore()
mouseIgnore[playerOfTimer[GetExpiredTimer()]] = false
end
local function MouseSpellIgnore()
if spellKeyList[GetSpellAbilityId()] then
return
end
local whichUnit = GetSpellAbilityUnit()
local whichPlayer = GetOwningPlayer(whichUnit)
if whichUnit == GetHero() then
mouseIgnore[whichPlayer] = true
autoWalkEnabled[whichPlayer] = false
TimerStart(ignoreToggleTimerOfPlayer[whichPlayer], IGNORE_MOUSE_SPELL_DURATION, false, DisableIgnore)
end
end
local function MouseMove()
local whichPlayer = GetTriggerPlayer()
local x, y = BlzGetTriggerPlayerMouseX(), BlzGetTriggerPlayerMouseY()
if world2Screen then
mouseX[whichPlayer], mouseY[whichPlayer] = World2Screen(x, y, GetTerrainZ(x, y))
else
mouseX[whichPlayer], mouseY[whichPlayer] = x, y
end
end
local function MouseRightClick()
if BlzGetTriggerPlayerMouseButton() == MOUSE_BUTTON_TYPE_RIGHT then
local whichPlayer = GetTriggerPlayer()
rightClickOn[whichPlayer] = true
mouseIgnore[whichPlayer] = true
TimerStart(ignoreToggleTimerOfPlayer[whichPlayer], IGNORE_MOUSE_CLICK_DURATION, false, DisableIgnore)
if not autoWalkEnabled[whichPlayer] then
TimerStart(loopTimerOfPlayer[whichPlayer], CHECK_INTERVAL, true, Loop)
end
end
end
local function MouseRightRelease()
if BlzGetTriggerPlayerMouseButton() == MOUSE_BUTTON_TYPE_RIGHT then
local whichPlayer = GetTriggerPlayer()
if rightClickOn[whichPlayer] then
rightClickOn[whichPlayer] = false
if not mouseIgnore[whichPlayer] then
local desiredX, desiredY, validMousePosition = GetDesiredPoint(whichPlayer)
if validMousePosition then
local whichHero = GetHero()
if whichHero == nil then
return
end
if NO_PATHING then
local xHero, yHero = GetUnitX(whichHero), GetUnitY(whichHero)
desiredX, desiredY = GetAdjustedPoint(xHero, yHero, desiredX, desiredY)
end
IssuePointOrderById(GetHero(), SMART, desiredX, desiredY)
end
end
if not autoWalkEnabled[whichPlayer] then
PauseTimer(loopTimerOfPlayer[whichPlayer])
end
end
end
end
OnInit.final("RPGControls", function()
world2Screen = Require.optionally "World2Screen"
if (NO_PATHING or NO_PATHING_ON_NORMAL_CLICK) and not GetFurthestAccessiblePoint then
NO_PATHING = false
print("|cffff0000Warning:|r NO_PATHING requires PathingWizard.")
end
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
local whichPlayer
local trigDown = CreateTrigger()
local trigUp = CreateTrigger()
local trigIgnore = CreateTrigger()
local trigMove = CreateTrigger()
local trigAutoWalk
if AUTO_WALK_HOTKEY then
trigAutoWalk = CreateTrigger()
TriggerAddAction(trigAutoWalk, ToggleAutoWalk)
commandTrigger = CreateTrigger()
TriggerAddAction(commandTrigger, OnPointOrder)
end
for i = 0, 23 do
whichPlayer = Player(i)
if GetPlayerSlotState(whichPlayer) == PLAYER_SLOT_STATE_PLAYING and GetPlayerController(whichPlayer) == MAP_CONTROL_USER then
TriggerRegisterPlayerEvent(trigDown, whichPlayer, EVENT_PLAYER_MOUSE_DOWN)
TriggerRegisterPlayerEvent(trigUp, whichPlayer, EVENT_PLAYER_MOUSE_UP)
TriggerRegisterPlayerEvent(trigMove, whichPlayer, EVENT_PLAYER_MOUSE_MOVE)
TriggerRegisterPlayerUnitEvent(commandTrigger, whichPlayer, EVENT_PLAYER_UNIT_ISSUED_POINT_ORDER)
BlzTriggerRegisterPlayerKeyEvent(trigAutoWalk, whichPlayer, AUTO_WALK_HOTKEY, 0, true)
loopTimerOfPlayer[whichPlayer] = CreateTimer()
ignoreToggleTimerOfPlayer[whichPlayer] = CreateTimer()
playerOfTimer[loopTimerOfPlayer[whichPlayer]] = whichPlayer
playerOfTimer[ignoreToggleTimerOfPlayer[whichPlayer]] = whichPlayer
end
i = i + 1
end
TriggerAddAction(trigMove, MouseMove)
TriggerAddAction(trigDown, MouseRightClick)
TriggerAddAction(trigUp, MouseRightRelease)
TriggerRegisterAnyUnitEventBJ(trigIgnore, EVENT_PLAYER_UNIT_SPELL_CAST)
TriggerAddAction(trigIgnore, MouseSpellIgnore)
for __, fourCC in ipairs(SPELL_EXCEPTIONS) do
spellKeyList[FourCC(fourCC)] = true
end
end)
---@param enable? boolean
---@param whichPlayer? player
function EnableRPGControls(enable, whichPlayer)
enable = enable ~= false
if whichPlayer then
if enable then
TimerStart(loopTimerOfPlayer[whichPlayer], CHECK_INTERVAL, true, Loop)
else
PauseTimer(loopTimerOfPlayer[whichPlayer])
end
else
for i = 0, 23 do
whichPlayer = Player(i)
if enable then
if GetPlayerSlotState(whichPlayer) == PLAYER_SLOT_STATE_PLAYING and GetPlayerController(whichPlayer) == MAP_CONTROL_USER then
TimerStart(loopTimerOfPlayer[whichPlayer], CHECK_INTERVAL, true, Loop)
end
elseif GetPlayerSlotState(whichPlayer) == PLAYER_SLOT_STATE_PLAYING and GetPlayerController(whichPlayer) == MAP_CONTROL_USER then
PauseTimer(loopTimerOfPlayer[whichPlayer])
end
i = i + 1
end
end
end
end
if Debug then Debug.endFile() end
do
OnInit.final(function()
Sylvanas = GetPreplacedWidget("Hvwd") --Preplaced Widget Indexer
FCL_Lock(Sylvanas) --Fixed Camera Lock
EnableRPGControls() --Main function to enable the system.
EnableSelect(false, false) --Locks selection to the main hero. You may want to do this or not.
SelectUnitSingle(Sylvanas) --Do this after disabling selection or it won't work.
print("Hold the right mouse-button to drag move. Press TAB to toggle auto-walk. The hero won't automatically path around obstacles.")
end)
end