diff --git a/.gitignore b/.gitignore index e44edc3..2353505 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,7 @@ .vscode/ addons/sourcemod/scripting/surftimer-api.sp -addons/sourcemod/scripting/surftimer-api.smx \ No newline at end of file +addons/sourcemod/scripting/surftimer-api.smx +addons/sourcemod/scripting/compile.dat +addons/sourcemod/scripting/include/compile.dat +addons/sourcemod/scripting/compiled/* diff --git a/addons/sourcemod/extensions/SteamWorks.ext.so b/addons/sourcemod/extensions/SteamWorks.ext.so new file mode 100644 index 0000000..88c8e91 Binary files /dev/null and b/addons/sourcemod/extensions/SteamWorks.ext.so differ diff --git a/addons/sourcemod/extensions/dhooks.ext.dll b/addons/sourcemod/extensions/dhooks.ext.dll index 517adb4..93926b3 100644 Binary files a/addons/sourcemod/extensions/dhooks.ext.dll and b/addons/sourcemod/extensions/dhooks.ext.dll differ diff --git a/addons/sourcemod/extensions/socket.ext.dll b/addons/sourcemod/extensions/socket.ext.dll new file mode 100644 index 0000000..cbefa52 Binary files /dev/null and b/addons/sourcemod/extensions/socket.ext.dll differ diff --git a/addons/sourcemod/extensions/socket.ext.so b/addons/sourcemod/extensions/socket.ext.so new file mode 100644 index 0000000..25d8252 Binary files /dev/null and b/addons/sourcemod/extensions/socket.ext.so differ diff --git a/addons/sourcemod/gamedata/dhooks-test.games.txt b/addons/sourcemod/gamedata/dhooks-test.games.txt index 91c9a00..3bba654 100644 --- a/addons/sourcemod/gamedata/dhooks-test.games.txt +++ b/addons/sourcemod/gamedata/dhooks-test.games.txt @@ -29,18 +29,18 @@ } "GetMaxs" { - "windows" "338" - "linux" "339" + "windows" "339" + "linux" "340" } "CanUse" { - "windows" "259" - "linux" "260" + "windows" "260" + "linux" "261" } "CanHaveAmmo" { - "windows" "97" - "linux" "97" + "windows" "98" + "linux" "98" } "SetModel" { @@ -49,13 +49,13 @@ } "GetMaxPlayerSpeed" { - "windows" "437" - "linux" "438" + "windows" "438" + "linux" "439" } "GiveAmmo" { - "windows" "251" - "linux" "252" + "windows" "252" + "linux" "253" } "OnTakeDamage" { @@ -74,4 +74,4 @@ } } } -} +} \ No newline at end of file diff --git a/addons/sourcemod/plugins/ckSurf-telefinder.smx b/addons/sourcemod/plugins/ckSurf-telefinder.smx new file mode 100644 index 0000000..297bb84 Binary files /dev/null and b/addons/sourcemod/plugins/ckSurf-telefinder.smx differ diff --git a/addons/sourcemod/plugins/discord_api.smx b/addons/sourcemod/plugins/discord_api.smx index 81fc459..4b28e66 100644 Binary files a/addons/sourcemod/plugins/discord_api.smx and b/addons/sourcemod/plugins/discord_api.smx differ diff --git a/addons/sourcemod/plugins/nextmap.smx b/addons/sourcemod/plugins/nextmap.smx new file mode 100644 index 0000000..95d32fe Binary files /dev/null and b/addons/sourcemod/plugins/nextmap.smx differ diff --git a/addons/sourcemod/plugins/surftimer.smx b/addons/sourcemod/plugins/surftimer.smx index 4db6d18..de46dd7 100644 Binary files a/addons/sourcemod/plugins/surftimer.smx and b/addons/sourcemod/plugins/surftimer.smx differ diff --git a/addons/sourcemod/scripting/SurfTimer.sp b/addons/sourcemod/scripting/SurfTimer.sp index d4e6e51..3020bd8 100644 --- a/addons/sourcemod/scripting/SurfTimer.sp +++ b/addons/sourcemod/scripting/SurfTimer.sp @@ -1701,7 +1701,7 @@ public void OnMapStart() CreateTimer(1.0, CKTimer2, INVALID_HANDLE, TIMER_FLAG_NO_MAPCHANGE | TIMER_REPEAT); CreateTimer(60.0, AttackTimer, INVALID_HANDLE, TIMER_FLAG_NO_MAPCHANGE | TIMER_REPEAT); CreateTimer(600.0, PlayerRanksTimer, INVALID_HANDLE, TIMER_FLAG_NO_MAPCHANGE | TIMER_REPEAT); - g_hZoneTimer = CreateTimer(GetConVarFloat(g_hChecker), BeamBoxAll, _, TIMER_REPEAT); + g_hZoneTimer = CreateTimer(GetConVarFloat(g_hChecker), BeamBoxAll, _, TIMER_FLAG_NO_MAPCHANGE | TIMER_REPEAT); // AutoBhop if (GetConVarBool(g_hAutoBhopConVar)) @@ -2663,7 +2663,7 @@ public void OnSettingChanged(Handle convar, const char[] oldValue, const char[] g_hZoneTimer = INVALID_HANDLE; } - g_hZoneTimer = CreateTimer(GetConVarFloat(g_hChecker), BeamBoxAll, _, TIMER_REPEAT); + g_hZoneTimer = CreateTimer(GetConVarFloat(g_hChecker), BeamBoxAll, _, TIMER_FLAG_NO_MAPCHANGE | TIMER_REPEAT); } public void OnPluginStart() @@ -2938,8 +2938,8 @@ public int Native_GetMapStages(Handle plugin, int numParams) return stages; } -public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) -{ +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max){ + RegPluginLibrary("surftimer"); CreateNative("surftimer_GetTimerStatus", Native_GetTimerStatus); CreateNative("surftimer_StopTimer", Native_StopTimer); @@ -2958,7 +2958,7 @@ public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max CreateNative("surftimer_IsClientVip", Native_IsClientVip); MarkNativeAsOptional("Store_GetClientCredits"); MarkNativeAsOptional("Store_SetClientCredits"); - g_bLateLoaded = late; +/* g_bLateLoaded = late;*/ return APLRes_Success; } diff --git a/addons/sourcemod/scripting/ckSurf-telefinder.sp b/addons/sourcemod/scripting/ckSurf-telefinder.sp deleted file mode 100644 index fcf0271..0000000 --- a/addons/sourcemod/scripting/ckSurf-telefinder.sp +++ /dev/null @@ -1,99 +0,0 @@ -#pragma semicolon 1 - -#define DEBUG - -#define PLUGIN_AUTHOR "Elzi" -#define PLUGIN_VERSION "1.00" - -#include -#include -#include -#include - -EngineVersion g_Game; - -Handle g_hEntity; -int g_iEntIndex[MAXPLAYERS + 1]; - -public Plugin myinfo = -{ - name = "[surftimer] Teleport Destination Finder", - author = PLUGIN_AUTHOR, - description = "Teleports clients using !cktele to info_teleport_destinations", - version = PLUGIN_VERSION, - url = "" -}; - -public void OnPluginStart() -{ - g_Game = GetEngineVersion(); - if(g_Game != Engine_CSGO && g_Game != Engine_CSS) - { - SetFailState("This plugin is for CSGO/CSS only."); - } - - RegAdminCmd("sm_cktele", TeleToInfo, ADMFLAG_ROOT, "[surftimer] Teleport client to a teleport destination in the map"); - -} - -public void OnMapStart() -{ - for (int i = 0; i < MAXPLAYERS + 1; i++) - g_iEntIndex[i] = 0; - - int iEnt; - g_hEntity = CreateArray(12); - - while ((iEnt = FindEntityByClassname(iEnt, "info_teleport_destination")) != -1) - PushArrayCell(g_hEntity, iEnt); - -} - -public void OnMapEnd() -{ - if (g_hEntity != null) - g_hEntity.Close(); - - g_hEntity = null; -} - - -public Action TeleToInfo(int client, int args) -{ - if (g_hEntity == null) - { - ReplyToCommand(client, "[CK] g_hEntity was null!"); - return Plugin_Handled; - } - - if (GetArraySize(g_hEntity) < 1) - { - ReplyToCommand(client, "[CK] No info_teleport_destinations found in map!"); - return Plugin_Handled; - } - - if (g_iEntIndex[client] == GetArraySize(g_hEntity)) - { - ReplyToCommand(client, "[CK] All info_teleport_destinations were looped, back to index 0"); - g_iEntIndex[client] = 0; - } - - int iEnt = GetArrayCell(g_hEntity, g_iEntIndex[client]); - - if (IsValidEntity(iEnt)) - { - float position[3]; - GetEntPropVector(iEnt, Prop_Send, "m_vecOrigin", position); - - surftimer_SafeTeleport(client, position, NULL_VECTOR, NULL_VECTOR, true); - - ReplyToCommand(client, "[CK] Teleporting to entity at %f, %f, %f", position[0], position[1], position[2]); - } - else - - ReplyToCommand(client, "[CK] Entity was invalid!"); - - - g_iEntIndex[client]++; - return Plugin_Handled; -} diff --git a/addons/sourcemod/scripting/discord/DiscordRequest.sp b/addons/sourcemod/scripting/discord/DiscordRequest.sp new file mode 100644 index 0000000..11b93ed --- /dev/null +++ b/addons/sourcemod/scripting/discord/DiscordRequest.sp @@ -0,0 +1,94 @@ +/* +stock Handle PrepareRequest(DiscordBot bot, char[] url, EHTTPMethod method=k_EHTTPMethodGET, Handle hJson=null, SteamWorksHTTPDataReceived DataReceived = INVALID_FUNCTION, SteamWorksHTTPRequestCompleted RequestCompleted = INVALID_FUNCTION) { + static char stringJson[16384]; + stringJson[0] = '\0'; + if(hJson != null) { + json_dump(hJson, stringJson, sizeof(stringJson), 0, true); + } + + //Format url + static char turl[128]; + FormatEx(turl, sizeof(turl), "https://discordapp.com/api/%s", url); + + Handle request = SteamWorks_CreateHTTPRequest(method, turl); + if(request == null) { + return null; + } + + if(bot != null) { + BuildAuthHeader(request, bot); + } + + SteamWorks_SetHTTPRequestRawPostBody(request, "application/json; charset=UTF-8", stringJson, strlen(stringJson)); + + SteamWorks_SetHTTPRequestNetworkActivityTimeout(request, 30); + + if(RequestCompleted == INVALID_FUNCTION) { + //I had some bugs previously where it wouldn't send request and return code 0 if I didn't set request completed. + //This is just a safety then, my issue could have been something else and I will test more later on + RequestCompleted = HTTPCompleted; + } + + if(DataReceived == INVALID_FUNCTION) { + //Need to close the request handle + DataReceived = HTTPDataReceive; + } + + SteamWorks_SetHTTPCallbacks(request, RequestCompleted, HeadersReceived, DataReceived); + if(hJson != null) delete hJson; + + return request; +} + */ + +methodmap DiscordRequest < Handle { + public DiscordRequest(char[] url, EHTTPMethod method) { + Handle request = SteamWorks_CreateHTTPRequest(method, url); + return view_as(request); + } + + public void SetJsonBody(Handle hJson) { + static char stringJson[16384]; + stringJson[0] = '\0'; + if(hJson != null) { + json_dump(hJson, stringJson, sizeof(stringJson), 0, true); + } + SteamWorks_SetHTTPRequestRawPostBody(this, "application/json; charset=UTF-8", stringJson, strlen(stringJson)); + if(hJson != null) delete hJson; + } + + public void SetJsonBodyEx(Handle hJson) { + static char stringJson[16384]; + stringJson[0] = '\0'; + if(hJson != null) { + json_dump(hJson, stringJson, sizeof(stringJson), 0, true); + } + SteamWorks_SetHTTPRequestRawPostBody(this, "application/json; charset=UTF-8", stringJson, strlen(stringJson)); + } + + property int Timeout { + public set(int timeout) { + SteamWorks_SetHTTPRequestNetworkActivityTimeout(this, timeout); + } + } + + public void SetCallbacks(SteamWorksHTTPRequestCompleted OnComplete, SteamWorksHTTPDataReceived DataReceived) { + SteamWorks_SetHTTPCallbacks(this, OnComplete, HeadersReceived, DataReceived); + } + + public void SetContextValue(any data1, any data2) { + SteamWorks_SetHTTPRequestContextValue(this, data1, data2); + } + + public void SetData(any data1, char[] route) { + SteamWorks_SetHTTPRequestContextValue(this, data1, UrlToDP(route)); + } + + public void SetBot(DiscordBot bot) { + BuildAuthHeader(this, bot); + } + + public void Send(char[] route) { + DiscordSendRequest(this, route); + } +} \ No newline at end of file diff --git a/addons/sourcemod/scripting/discord/GetGuildChannels.sp b/addons/sourcemod/scripting/discord/GetGuildChannels.sp new file mode 100644 index 0000000..cdeea7a --- /dev/null +++ b/addons/sourcemod/scripting/discord/GetGuildChannels.sp @@ -0,0 +1,152 @@ +public int Native_DiscordBot_GetGuildChannels(Handle plugin, int numParams) { + DiscordBot bot = GetNativeCell(1); + + char guild[32]; + GetNativeString(2, guild, sizeof(guild)); + + Function fCallback = GetNativeCell(3); + Function fCallbackAll = GetNativeCell(4); + any data = GetNativeCell(5); + + DataPack dp = CreateDataPack(); + WritePackCell(dp, bot); + WritePackString(dp, guild); + WritePackCell(dp, plugin); + WritePackFunction(dp, fCallback); + WritePackFunction(dp, fCallbackAll); + WritePackCell(dp, data); + + ThisSendRequest(bot, guild, dp); +} + +static void ThisSendRequest(DiscordBot bot, char[] guild, DataPack dp) { + char url[64]; + FormatEx(url, sizeof(url), "guilds/%s/channels", guild); + + Handle request = PrepareRequest(bot, url, k_EHTTPMethodGET, null, GetGuildChannelsData); + if(request == null) { + CreateTimer(2.0, GetGuildChannelsDelayed, dp); + return; + } + + SteamWorks_SetHTTPRequestContextValue(request, dp, UrlToDP(url)); + + DiscordSendRequest(request, url); +} + +public Action GetGuildChannelsDelayed(Handle timer, any data) { + DataPack dp = view_as(data); + ResetPack(dp); + + DiscordBot bot = ReadPackCell(dp); + + char guild[32]; + ReadPackString(dp, guild, sizeof(guild)); + + ThisSendRequest(bot, guild, dp); +} + +public int GetGuildChannelsData(Handle request, bool failure, int offset, int statuscode, any dp) { + if(failure || statuscode != 200) { + if(statuscode == 429 || statuscode == 500) { + ResetPack(dp); + DiscordBot bot = ReadPackCell(dp); + + char guild[32]; + ReadPackString(dp, guild, sizeof(guild)); + + ThisSendRequest(bot, guild, view_as(dp)); + + delete request; + return; + } + LogError("[DISCORD] Couldn't Retrieve Guild Channels - Fail %i %i", failure, statuscode); + delete request; + delete view_as(dp); + return; + } + SteamWorks_GetHTTPResponseBodyCallback(request, GetGuildChannelsData_Data, dp); + delete request; +} + +public int GetGuildChannelsData_Data(const char[] data, any datapack) { + Handle hJson = json_load(data); + + //Read from datapack to get info + Handle dp = view_as(datapack); + ResetPack(dp); + int bot = ReadPackCell(dp); + + char guild[32]; + ReadPackString(dp, guild, sizeof(guild)); + + Handle plugin = view_as(ReadPackCell(dp)); + Function func = ReadPackFunction(dp); + Function funcAll = ReadPackFunction(dp); + any pluginData = ReadPackCell(dp); + delete dp; + + //Create forwards + Handle fForward = INVALID_HANDLE; + Handle fForwardAll = INVALID_HANDLE; + if(func != INVALID_FUNCTION) { + fForward = CreateForward(ET_Ignore, Param_Cell, Param_String, Param_Cell, Param_Cell); + AddToForward(fForward, plugin, func); + } + + if(funcAll != INVALID_FUNCTION) { + fForwardAll = CreateForward(ET_Ignore, Param_Cell, Param_String, Param_Cell, Param_Cell); + AddToForward(fForwardAll, plugin, funcAll); + } + + ArrayList alChannels = null; + + if(funcAll != INVALID_FUNCTION) { + alChannels = CreateArray(); + } + + //Loop through json + for(int i = 0; i < json_array_size(hJson); i++) { + Handle hObject = json_array_get(hJson, i); + + DiscordChannel Channel = view_as(hObject); + + if(fForward != INVALID_HANDLE) { + Call_StartForward(fForward); + Call_PushCell(bot); + Call_PushString(guild); + Call_PushCell(Channel); + Call_PushCell(pluginData); + Call_Finish(); + } + + if(fForwardAll != INVALID_HANDLE) { + alChannels.Push(Channel); + }else { + delete Channel; + } + } + + if(fForwardAll != INVALID_HANDLE) { + Call_StartForward(fForwardAll); + Call_PushCell(bot); + Call_PushString(guild); + Call_PushCell(alChannels); + Call_PushCell(pluginData); + Call_Finish(); + + for(int i = 0; i < alChannels.Length; i++) { + Handle hChannel = view_as(alChannels.Get(i)); + delete hChannel; + } + + delete alChannels; + delete fForwardAll; + } + + if(fForward != INVALID_HANDLE) { + delete fForward; + } + + delete hJson; +} \ No newline at end of file diff --git a/addons/sourcemod/scripting/discord/GetGuilds.sp b/addons/sourcemod/scripting/discord/GetGuilds.sp new file mode 100644 index 0000000..51d6e27 --- /dev/null +++ b/addons/sourcemod/scripting/discord/GetGuilds.sp @@ -0,0 +1,165 @@ +public int Native_DiscordBot_GetGuilds(Handle plugin, int numParams) { + DiscordBot bot = GetNativeCell(1); + Function fCallback = GetNativeCell(2); + Function fCallbackAll = GetNativeCell(3); + any data = GetNativeCell(4); + + DataPack dp = CreateDataPack(); + WritePackCell(dp, bot); + WritePackCell(dp, plugin); + WritePackFunction(dp, fCallback); + WritePackFunction(dp, fCallbackAll); + WritePackCell(dp, data); + + ThisSendRequest(bot, dp); +} + +static void ThisSendRequest(DiscordBot bot, DataPack dp) { + char url[64]; + FormatEx(url, sizeof(url), "users/@me/guilds"); + + Handle request = PrepareRequest(bot, url, k_EHTTPMethodGET, null, GetGuildsData); + if(request == null) { + CreateTimer(2.0, GetGuildsDelayed, dp); + return; + } + + SteamWorks_SetHTTPRequestContextValue(request, dp, UrlToDP(url)); + + DiscordSendRequest(request, url); +} + +public Action GetGuildsDelayed(Handle timer, any data) { + DataPack dp = view_as(data); + ResetPack(dp); + + DiscordBot bot = ReadPackCell(dp); + + ThisSendRequest(bot, dp); +} + +public int GetGuildsData(Handle request, bool failure, int offset, int statuscode, any dp) { + if(failure || statuscode != 200) { + if(statuscode == 429 || statuscode == 500) { + ResetPack(dp); + DiscordBot bot = ReadPackCell(dp); + ThisSendRequest(bot, dp); + + delete request; + return; + } + LogError("[DISCORD] Couldn't Retrieve Guilds - Fail %i %i", failure, statuscode); + delete request; + delete view_as(dp); + return; + } + SteamWorks_GetHTTPResponseBodyCallback(request, GetGuildsData_Data, dp); + delete request; +} + +public int GetGuildsData_Data(const char[] data, any datapack) { + Handle hJson = json_load(data); + + //Read from datapack to get info + Handle dp = view_as(datapack); + ResetPack(dp); + int bot = ReadPackCell(dp); + Handle plugin = view_as(ReadPackCell(dp)); + Function func = ReadPackFunction(dp); + Function funcAll = ReadPackFunction(dp); + any pluginData = ReadPackCell(dp); + delete dp; + + //Create forwards + Handle fForward = INVALID_HANDLE; + Handle fForwardAll = INVALID_HANDLE; + if(func != INVALID_FUNCTION) { + fForward = CreateForward(ET_Ignore, Param_Cell, Param_String, Param_String, Param_String, Param_Cell, Param_Cell, Param_Cell); + AddToForward(fForward, plugin, func); + } + + if(funcAll != INVALID_FUNCTION) { + fForwardAll = CreateForward(ET_Ignore, Param_Cell, Param_Cell, Param_Cell, Param_Cell, Param_Cell, Param_Cell, Param_Cell); + AddToForward(fForwardAll, plugin, funcAll); + } + + ArrayList alId = null; + ArrayList alName = null; + ArrayList alIcon = null; + ArrayList alOwner = null; + ArrayList alPermissions = null; + + if(funcAll != INVALID_FUNCTION) { + alId = CreateArray(32); + alName = CreateArray(64); + alIcon = CreateArray(128); + alOwner = CreateArray(); + alPermissions = CreateArray(); + } + + //Loop through json + for(int i = 0; i < json_array_size(hJson); i++) { + Handle hObject = json_array_get(hJson, i); + + static char id[32]; + static char name[64]; + static char icon[128]; + bool owner = false; + int permissions; + + JsonObjectGetString(hObject, "id", id, sizeof(id)); + JsonObjectGetString(hObject, "name", name, sizeof(name)); + JsonObjectGetString(hObject, "icon", icon, sizeof(icon)); + + owner = JsonObjectGetBool(hObject, "owner"); + permissions = JsonObjectGetBool(hObject, "permissions"); + + if(fForward != INVALID_HANDLE) { + Call_StartForward(fForward); + Call_PushCell(bot); + Call_PushString(id); + Call_PushString(name); + Call_PushString(icon); + Call_PushCell(owner); + Call_PushCell(permissions); + Call_PushCell(pluginData); + Call_Finish(); + } + + if(fForwardAll != INVALID_HANDLE) { + alId.PushString(id); + alName.PushString(name); + alIcon.PushString(icon); + alOwner.Push(owner); + alPermissions.Push(permissions); + } + + delete hObject; + } + + if(fForwardAll != INVALID_HANDLE) { + Call_StartForward(fForwardAll); + Call_PushCell(bot); + Call_PushCell(alId); + Call_PushCell(alName); + Call_PushCell(alIcon); + Call_PushCell(alOwner); + Call_PushCell(alPermissions); + Call_PushCell(pluginData); + Call_Finish(); + + delete alId; + delete alName; + delete alIcon; + delete alOwner; + delete alPermissions; + + delete fForwardAll; + } + + if(fForward != INVALID_HANDLE) { + delete fForward; + } + + delete hJson; +} \ No newline at end of file diff --git a/addons/sourcemod/scripting/discord/GuildMembers.sp b/addons/sourcemod/scripting/discord/GuildMembers.sp new file mode 100644 index 0000000..20ff7f6 --- /dev/null +++ b/addons/sourcemod/scripting/discord/GuildMembers.sp @@ -0,0 +1,156 @@ +/** + * public native void GetGuildMembers(char[] guild, OnGetMembers fCallback, char[] afterUserID="", int limit=250); + */ +public int Native_DiscordBot_GetGuildMembers(Handle plugin, int numParams) { + DiscordBot bot = view_as(CloneHandle(GetNativeCell(1))); + + char guild[32]; + GetNativeString(2, guild, sizeof(guild)); + + Function fCallback = GetNativeCell(3); + + int limit = GetNativeCell(4); + + char afterID[32]; + GetNativeString(5, afterID, sizeof(afterID)); + + Handle hData = json_object(); + json_object_set_new(hData, "bot", bot); + json_object_set_new(hData, "guild", json_string(guild)); + json_object_set_new(hData, "limit", json_integer(limit)); + json_object_set_new(hData, "afterID", json_string(afterID)); + + Handle fwd = CreateForward(ET_Ignore, Param_Cell, Param_String, Param_Cell); + AddToForward(fwd, plugin, fCallback); + json_object_set_new(hData, "callback", json_integer(view_as(fwd))); + + GetMembers(hData); +} + +public int Native_DiscordBot_GetGuildMembersAll(Handle plugin, int numParams) { + DiscordBot bot = view_as(CloneHandle(GetNativeCell(1))); + + char guild[32]; + GetNativeString(2, guild, sizeof(guild)); + + Function fCallback = GetNativeCell(3); + + int limit = GetNativeCell(4); + + char afterID[32]; + GetNativeString(5, afterID, sizeof(afterID)); + + Handle hData = json_object(); + json_object_set_new(hData, "bot", bot); + json_object_set_new(hData, "guild", json_string(guild)); + json_object_set_new(hData, "limit", json_integer(limit)); + json_object_set_new(hData, "afterID", json_string(afterID)); + + Handle fwd = CreateForward(ET_Ignore, Param_Cell, Param_String, Param_Cell); + AddToForward(fwd, plugin, fCallback); + json_object_set_new(hData, "callback", json_integer(view_as(fwd))); + + GetMembers(hData); +} + +static void GetMembers(Handle hData) { + DiscordBot bot = view_as(json_object_get(hData, "bot")); + + char guild[32]; + JsonObjectGetString(hData, "guild", guild, sizeof(guild)); + + int limit = JsonObjectGetInt(hData, "limit"); + + char afterID[32]; + JsonObjectGetString(hData, "afterID", afterID, sizeof(afterID)); + + char url[256]; + if(StrEqual(afterID, "")) { + FormatEx(url, sizeof(url), "https://discordapp.com/api/guilds/%s/members?limit=%i", guild, limit); + }else { + FormatEx(url, sizeof(url), "https://discordapp.com/api/guilds/%s/members?limit=%i&afterID=%s", guild, limit, afterID); + } + + char route[128]; + FormatEx(route, sizeof(route), "guild/%s/members", guild); + + DiscordRequest request = new DiscordRequest(url, k_EHTTPMethodGET); + if(request == null) { + delete bot; + CreateTimer(2.0, SendGetMembers, hData); + return; + } + request.SetCallbacks(HTTPCompleted, MembersDataReceive); + request.SetBot(bot); + request.SetData(hData, route); + + request.Send(route); + + delete bot; +} + +public Action SendGetMembers(Handle timer, any data) { + GetMembers(view_as(data)); +} + + +public MembersDataReceive(Handle request, bool failure, int offset, int statuscode, any dp) { + if(failure || (statuscode != 200)) { + if(statuscode == 400) { + PrintToServer("BAD REQUEST"); + } + + if(statuscode == 429 || statuscode == 500) { + GetMembers(dp); + + delete request; + return; + } + LogError("[DISCORD] Couldn't Send GetMembers - Fail %i %i", failure, statuscode); + delete request; + delete view_as(dp); + return; + } + SteamWorks_GetHTTPResponseBodyCallback(request, GetMembersData, dp); + delete request; +} + +public int GetMembersData(const char[] data, any dp) { + Handle hJson = json_load(data); + Handle hData = view_as(dp); + DiscordBot bot = view_as(json_object_get(hData, "bot")); + + Handle fwd = view_as(JsonObjectGetInt(hData, "callback")); + + char guild[32]; + JsonObjectGetString(hData, "guild", guild, sizeof(guild)); + + if(fwd != null) { + Call_StartForward(fwd); + Call_PushCell(bot); + Call_PushString(guild); + Call_PushCell(hJson); + Call_Finish(); + } + + delete bot; + if(JsonObjectGetBool(hData, "autoPaginate")) { + int size = json_array_size(hJson); + int limit = JsonObjectGetInt(hData, "limit"); + if(limit == size) { + Handle hLast = json_array_get(hJson, size - 1); + char lastID[32]; + json_string_value(hLast, lastID, sizeof(lastID)); + delete hJson; + delete hLast; + + json_object_set_new(hData, "afterID", json_string(lastID)); + GetMembers(hData); + return; + } + } + + delete hJson; + delete hData; + delete fwd; +} \ No newline at end of file diff --git a/addons/sourcemod/scripting/discord/GuildRole.sp b/addons/sourcemod/scripting/discord/GuildRole.sp new file mode 100644 index 0000000..77660ac --- /dev/null +++ b/addons/sourcemod/scripting/discord/GuildRole.sp @@ -0,0 +1,102 @@ +public int Native_DiscordBot_GetGuildRoles(Handle plugin, int numParams) { + DiscordBot bot = view_as(CloneHandle(GetNativeCell(1))); + + char guild[32]; + GetNativeString(2, guild, sizeof(guild)); + + Function fCallback = GetNativeCell(3); + + any data = GetNativeCell(4); + + Handle hData = json_object(); + json_object_set_new(hData, "bot", bot); + json_object_set_new(hData, "guild", json_string(guild)); + json_object_set_new(hData, "data1", json_integer(view_as(data))); + + Handle fwd = CreateForward(ET_Ignore, Param_Cell, Param_String, Param_Cell, Param_Cell); + AddToForward(fwd, plugin, fCallback); + json_object_set_new(hData, "callback", json_integer(view_as(fwd))); + + GetGuildRoles(hData); +} + +static void GetGuildRoles(Handle hData) { + DiscordBot bot = view_as(json_object_get(hData, "bot")); + + char guild[32]; + JsonObjectGetString(hData, "guild", guild, sizeof(guild)); + + + char url[256]; + FormatEx(url, sizeof(url), "https://discordapp.com/api/guilds/%s/roles", guild); + + char route[128]; + FormatEx(route, sizeof(route), "guild/%s/roles", guild); + + DiscordRequest request = new DiscordRequest(url, k_EHTTPMethodGET); + if(request == null) { + delete bot; + CreateTimer(2.0, SendGetGuildRoles, hData); + return; + } + request.SetCallbacks(HTTPCompleted, GetGuildRolesReceive); + request.SetBot(bot); + request.SetData(hData, route); + + request.Send(route); + + delete bot; +} + +public Action SendGetGuildRoles(Handle timer, any data) { + GetGuildRoles(view_as(data)); +} + + +public GetGuildRolesReceive(Handle request, bool failure, int offset, int statuscode, any dp) { + if(failure || (statuscode != 200)) { + if(statuscode == 400) { + PrintToServer("BAD REQUEST"); + } + + if(statuscode == 429 || statuscode == 500) { + GetGuildRoles(dp); + + delete request; + return; + } + LogError("[DISCORD] Couldn't Send GetGuildRoles - Fail %i %i", failure, statuscode); + delete request; + delete view_as(dp); + return; + } + SteamWorks_GetHTTPResponseBodyCallback(request, GetRolesData, dp); + delete request; +} + +public int GetRolesData(const char[] data, any dp) { + Handle hJson = json_load(data); + Handle hData = view_as(dp); + DiscordBot bot = view_as(json_object_get(hData, "bot")); + + Handle fwd = view_as(JsonObjectGetInt(hData, "callback")); + + char guild[32]; + JsonObjectGetString(hData, "guild", guild, sizeof(guild)); + + any data1 = JsonObjectGetInt(hData, "data1"); + + if(fwd != null) { + Call_StartForward(fwd); + Call_PushCell(bot); + Call_PushString(guild); + Call_PushCell(view_as(hJson)); + Call_PushCell(data1); + Call_Finish(); + } + + delete bot; + delete hJson; + delete hData; + delete fwd; +} \ No newline at end of file diff --git a/addons/sourcemod/scripting/discord/ListenToChannel.sp b/addons/sourcemod/scripting/discord/ListenToChannel.sp new file mode 100644 index 0000000..02574f8 --- /dev/null +++ b/addons/sourcemod/scripting/discord/ListenToChannel.sp @@ -0,0 +1,145 @@ +public int Native_DiscordBot_StartTimer(Handle plugin, int numParams) { + DiscordBot bot = GetNativeCell(1); + DiscordChannel channel = GetNativeCell(2); + Function func = GetNativeCell(3); + + Handle hObj = json_object(); + json_object_set(hObj, "bot", bot); + json_object_set(hObj, "channel", channel); + + Handle fwd = CreateForward(ET_Ignore, Param_Cell, Param_Cell, Param_Cell); + AddToForward(fwd, plugin, func); + + json_object_set_new(hObj, "callback", json_integer(view_as(fwd))); + + GetMessages(hObj); +} + +public void GetMessages(Handle hObject) { + DiscordBot bot = view_as(json_object_get(hObject, "bot")); + DiscordChannel channel = view_as(json_object_get(hObject, "channel")); + //Handle fwd = view_as(json_object_get(hObject, "callback")); + + char channelID[32]; + channel.GetID(channelID, sizeof(channelID)); + + char lastMessage[64]; + channel.GetLastMessageID(lastMessage, sizeof(lastMessage)); + + char url[256]; + FormatEx(url, sizeof(url), "channels/%s/messages?limit=%i&after=%s", channelID, 100, lastMessage); + + Handle request = PrepareRequest(bot, url, _, null, OnGetMessage); + if(request == null) { + delete bot; + delete channel; + CreateTimer(2.0, GetMessagesDelayed, hObject); + return; + } + + char route[128]; + FormatEx(route, sizeof(route), "channels/%s", channelID); + + SteamWorks_SetHTTPRequestContextValue(request, hObject, UrlToDP(route)); + + delete bot; + delete channel; + + DiscordSendRequest(request, route); +} + +public Action GetMessagesDelayed(Handle timer, any data) { + GetMessages(view_as(data)); +} + +public Action CheckMessageTimer(Handle timer, any dpt) { + GetMessages(view_as(dpt)); +} + +public int OnGetMessage(Handle request, bool failure, int offset, int statuscode, any dp) { + if(failure || statuscode != 200) { + if(statuscode == 429 || statuscode == 500) { + GetMessages(view_as(dp)); + delete request; + return; + } + LogError("[DISCORD] Couldn't Retrieve Messages - Fail %i %i", failure, statuscode); + delete request; + Handle fwd = view_as(JsonObjectGetInt(view_as(dp), "callback")); + if(fwd != null) delete fwd; + delete view_as(dp); + return; + } + + SteamWorks_GetHTTPResponseBodyCallback(request, OnGetMessage_Data, dp); + delete request; +} + +public int OnGetMessage_Data(const char[] data, any dpt) { + Handle hObj = view_as(dpt); + + DiscordBot Bot = view_as(json_object_get(hObj, "bot")); + DiscordChannel channel = view_as(json_object_get(hObj, "channel")); + Handle fwd = view_as(JsonObjectGetInt(hObj, "callback")); + + if(!Bot.IsListeningToChannel(channel) || GetForwardFunctionCount(fwd) == 0) { + delete Bot; + delete channel; + delete hObj; + delete fwd; + return; + } + + Handle hJson = json_load(data); + + if(json_is_array(hJson)) { + for(int i = json_array_size(hJson) - 1; i >= 0; i--) { + Handle hObject = json_array_get(hJson, i); + + //The reason we find Channel for each message instead of global incase + //Bot stops listening for the channel while we are still sending messages + char channelID[32]; + JsonObjectGetString(hObject, "channel_id", channelID, sizeof(channelID)); + + //Find Channel corresponding to Channel id + //DiscordChannel Channel = Bot.GetListeningChannelByID(channelID); + if(!Bot.IsListeningToChannelID(channelID)) { + //Channel is no longer listed to, remove any handles & stop + delete hObject; + delete hJson; + + delete fwd; + delete Bot; + delete channel; + delete hObj; + return; + } + + char id[32]; + JsonObjectGetString(hObject, "id", id, sizeof(id)); + + if(i == 0) { + channel.SetLastMessageID(id); + } + + //Get info and fire forward + if(fwd != null) { + Call_StartForward(fwd); + Call_PushCell(Bot); + Call_PushCell(channel); + Call_PushCell(view_as(hObject)); + Call_Finish(); + } + + delete hObject; + } + } + + CreateTimer(Bot.MessageCheckInterval, CheckMessageTimer, hObj); + + delete Bot; + delete channel; + + + delete hJson; +} \ No newline at end of file diff --git a/addons/sourcemod/scripting/discord/MessageObject.sp b/addons/sourcemod/scripting/discord/MessageObject.sp new file mode 100644 index 0000000..8d43a56 --- /dev/null +++ b/addons/sourcemod/scripting/discord/MessageObject.sp @@ -0,0 +1,36 @@ +public int Native_DiscordMessage_GetID(Handle plugin, int numParams) { + Handle hJson = GetNativeCell(1); + char buffer[64]; + JsonObjectGetString(hJson, "id", buffer, sizeof(buffer)); + SetNativeString(2, buffer, GetNativeCell(3)); +} + +public int Native_DiscordMessage_IsPinned(Handle plugin, int numParams) { + Handle hJson = GetNativeCell(1); + return JsonObjectGetBool(hJson, "pinned"); +} + +public int Native_DiscordMessage_GetAuthor(Handle plugin, int numParams) { + Handle hJson = GetNativeCell(1); + + Handle hAuthor = json_object_get(hJson, "author"); + + DiscordUser user = view_as(CloneHandle(hAuthor, plugin)); + delete hAuthor; + + return _:user; +} + +public int Native_DiscordMessage_GetContent(Handle plugin, int numParams) { + Handle hJson = GetNativeCell(1); + static char buffer[2000]; + JsonObjectGetString(hJson, "content", buffer, sizeof(buffer)); + SetNativeString(2, buffer, GetNativeCell(3)); +} + +public int Native_DiscordMessage_GetChannelID(Handle plugin, int numParams) { + Handle hJson = GetNativeCell(1); + char buffer[64]; + JsonObjectGetString(hJson, "channel_id", buffer, sizeof(buffer)); + SetNativeString(2, buffer, GetNativeCell(3)); +} \ No newline at end of file diff --git a/addons/sourcemod/scripting/discord/SendMessage.sp b/addons/sourcemod/scripting/discord/SendMessage.sp new file mode 100644 index 0000000..f5ce06c --- /dev/null +++ b/addons/sourcemod/scripting/discord/SendMessage.sp @@ -0,0 +1,138 @@ +public int Native_DiscordBot_SendMessageToChannel(Handle plugin, int numParams) { + DiscordBot bot = GetNativeCell(1); + char channel[32]; + static char message[2048]; + GetNativeString(2, channel, sizeof(channel)); + GetNativeString(3, message, sizeof(message)); + + Function fCallback = GetNativeCell(4); + any data = GetNativeCell(5); + Handle fForward = null; + if(fCallback != INVALID_FUNCTION) { + fForward = CreateForward(ET_Ignore, Param_Cell, Param_Cell, Param_Cell, Param_Cell); + AddToForward(fForward, plugin, fCallback); + } + + SendMessage(bot, channel, message, fForward, data); +} + +public int Native_DiscordBot_SendMessage(Handle plugin, int numParams) { + DiscordBot bot = GetNativeCell(1); + + DiscordChannel Channel = GetNativeCell(2); + char channelID[32]; + Channel.GetID(channelID, sizeof(channelID)); + + static char message[2048]; + GetNativeString(3, message, sizeof(message)); + + Function fCallback = GetNativeCell(4); + any data = GetNativeCell(5); + Handle fForward = null; + if(fCallback != INVALID_FUNCTION) { + fForward = CreateForward(ET_Ignore, Param_Cell, Param_Cell, Param_Cell, Param_Cell); + AddToForward(fForward, plugin, fCallback); + } + + SendMessage(bot, channelID, message, fForward, data); +} + +public int Native_DiscordChannel_SendMessage(Handle plugin, int numParams) { + DiscordChannel channel = view_as(GetNativeCell(1)); + + char channelID[32]; + channel.GetID(channelID, sizeof(channelID)); + + DiscordBot bot = GetNativeCell(2); + + static char message[2048]; + GetNativeString(3, message, sizeof(message)); + + Function fCallback = GetNativeCell(4); + any data = GetNativeCell(5); + Handle fForward = null; + if(fCallback != INVALID_FUNCTION) { + fForward = CreateForward(ET_Ignore, Param_Cell, Param_Cell, Param_Cell, Param_Cell); + AddToForward(fForward, plugin, fCallback); + } + + SendMessage(bot, channelID, message, fForward, data); +} + +static void SendMessage(DiscordBot bot, char[] channel, char[] message, Handle fForward, any data) { + Handle hJson = json_object(); + + json_object_set_new(hJson, "content", json_string(message)); + + char url[64]; + FormatEx(url, sizeof(url), "channels/%s/messages", channel); + + DataPack dpSafety = new DataPack(); + WritePackCell(dpSafety, bot); + WritePackString(dpSafety, channel); + WritePackString(dpSafety, message); + WritePackCell(dpSafety, fForward); + WritePackCell(dpSafety, data); + + Handle request = PrepareRequest(bot, url, k_EHTTPMethodPOST, hJson, GetSendMessageData); + if(request == null) { + delete hJson; + CreateTimer(2.0, SendMessageDelayed, dpSafety); + return; + } + + SteamWorks_SetHTTPRequestContextValue(request, dpSafety, UrlToDP(url)); + + DiscordSendRequest(request, url); +} + +public Action SendMessageDelayed(Handle timer, any data) { + DataPack dp = view_as(data); + ResetPack(dp); + + DiscordBot bot = ReadPackCell(dp); + + char channel[32]; + ReadPackString(dp, channel, sizeof(channel)); + + char message[2048]; + ReadPackString(dp, message, sizeof(message)); + + Handle fForward = ReadPackCell(dp); + any dataa = ReadPackCell(dp); + + delete dp; + + SendMessage(bot, channel, message, fForward, dataa); +} + +public int GetSendMessageData(Handle request, bool failure, int offset, int statuscode, any dp) { + if(failure || statuscode != 200) { + if(statuscode == 429 || statuscode == 500) { + ResetPack(dp); + DiscordBot bot = ReadPackCell(dp); + + char channel[32]; + ReadPackString(dp, channel, sizeof(channel)); + + char message[2048]; + ReadPackString(dp, message, sizeof(message)); + + Handle fForward = ReadPackCell(dp); + any data = ReadPackCell(dp); + + delete view_as(dp); + + SendMessage(bot, channel, message, fForward, data); + + delete request; + return; + } + LogError("[DISCORD] Couldn't Send Message - Fail %i %i", failure, statuscode); + delete request; + delete view_as(dp); + return; + } + delete request; + delete view_as(dp); +} \ No newline at end of file diff --git a/addons/sourcemod/scripting/discord/SendWebHook.sp b/addons/sourcemod/scripting/discord/SendWebHook.sp new file mode 100644 index 0000000..0efc560 --- /dev/null +++ b/addons/sourcemod/scripting/discord/SendWebHook.sp @@ -0,0 +1,104 @@ +public int Native_DiscordWebHook_Send(Handle plugin, int numParams) { + DiscordWebHook hook = GetNativeCell(1); + SendWebHook(view_as(hook)); +} + +public void SendWebHook(DiscordWebHook hook) { + if(!JsonObjectGetBool(hook, "__selfCopy", false)) { + hook = view_as(json_deep_copy(hook)); + json_object_set_new(hook, "__selfCopy", json_true()); + } + Handle hJson = hook.Data; + + char url[256]; + hook.GetUrl(url, sizeof(url)); + + if(hook.SlackMode) { + if(StrContains(url, "/slack") == -1) { + Format(url, sizeof(url), "%s/slack", url); + } + + RenameJsonObject(hJson, "content", "text"); + RenameJsonObject(hJson, "embeds", "attachments"); + + Handle hAttachments = json_object_get(hJson, "attachments"); + if(hAttachments != null) { + if(json_is_array(hAttachments)) { + for(int i = 0; i < json_array_size(hAttachments); i++) { + Handle hEmbed = json_array_get(hAttachments, i); + + Handle hFields = json_object_get(hEmbed, "fields"); + if(hFields) { + if(json_is_array(hFields)) { + for(int j = 0; j < json_array_size(hFields); j++) { + Handle hField = json_array_get(hFields, j); + RenameJsonObject(hField, "name", "title"); + RenameJsonObject(hField, "inline", "short"); + //json_array_set_new(hFields, j, hField); + delete hField; + } + } + + //json_object_set_new(hEmbed, "fields", hFields); + delete hFields; + } + + //json_array_set_new(hAttachments, i, hEmbed); + delete hEmbed; + } + } + + //json_object_set_new(hJson, "attachments", hAttachments); + delete hAttachments; + } + } + + //Send + DiscordRequest request = new DiscordRequest(url, k_EHTTPMethodPOST); + request.SetCallbacks(HTTPCompleted, SendWebHookReceiveData); + request.SetJsonBodyEx(hJson); + //Handle request = PrepareRequestRaw(null, url, k_EHTTPMethodPOST, hJson, SendWebHookReceiveData); + if(request == null) { + CreateTimer(2.0, SendWebHookDelayed, hJson); + return; + } + + request.SetContextValue(hJson, UrlToDP(url)); + + //DiscordSendRequest(request, url); + request.Send(url); +} + +public Action SendWebHookDelayed(Handle timer, any data) { + SendWebHook(view_as(data)); +} + +public SendWebHookReceiveData(Handle request, bool failure, int offset, int statuscode, any dp) { + if(failure || (statuscode != 200 && statuscode != 204)) { + if(statuscode == 400) { + PrintToServer("BAD REQUEST"); + SteamWorks_GetHTTPResponseBodyCallback(request, WebHookData, dp); + } + + if(statuscode == 429 || statuscode == 500) { + SendWebHook(view_as(dp)); + + delete request; + return; + } + LogError("[DISCORD] Couldn't Send Webhook - Fail %i %i", failure, statuscode); + delete request; + delete view_as(dp); + return; + } + delete request; + delete view_as(dp); +} + +public int WebHookData(const char[] data, any dp) { + PrintToServer("DATA RECE: %s", data); + static char stringJson[16384]; + stringJson[0] = '\0'; + json_dump(view_as(dp), stringJson, sizeof(stringJson), 0, true); + PrintToServer("DATA SENT: %s", stringJson); +} \ No newline at end of file diff --git a/addons/sourcemod/scripting/discord/UserObject.sp b/addons/sourcemod/scripting/discord/UserObject.sp new file mode 100644 index 0000000..bbe8ab2 --- /dev/null +++ b/addons/sourcemod/scripting/discord/UserObject.sp @@ -0,0 +1,44 @@ +public int Native_DiscordUser_GetID(Handle plugin, int numParams) { + Handle hJson = GetNativeCell(1); + char buffer[64]; + JsonObjectGetString(hJson, "id", buffer, sizeof(buffer)); + SetNativeString(2, buffer, GetNativeCell(3)); +} + +public int Native_DiscordUser_GetUsername(Handle plugin, int numParams) { + Handle hJson = GetNativeCell(1); + char buffer[64]; + JsonObjectGetString(hJson, "username", buffer, sizeof(buffer)); + SetNativeString(2, buffer, GetNativeCell(3)); +} + +public int Native_DiscordUser_GetDiscriminator(Handle plugin, int numParams) { + Handle hJson = GetNativeCell(1); + char buffer[16]; + JsonObjectGetString(hJson, "discriminator", buffer, sizeof(buffer)); + SetNativeString(2, buffer, GetNativeCell(3)); +} + +public int Native_DiscordUser_GetAvatar(Handle plugin, int numParams) { + Handle hJson = GetNativeCell(1); + char buffer[256]; + JsonObjectGetString(hJson, "avatar", buffer, sizeof(buffer)); + SetNativeString(2, buffer, GetNativeCell(3)); +} + +public int Native_DiscordUser_GetEmail(Handle plugin, int numParams) { + Handle hJson = GetNativeCell(1); + char buffer[64]; + JsonObjectGetString(hJson, "email", buffer, sizeof(buffer)); + SetNativeString(2, buffer, GetNativeCell(3)); +} + +public int Native_DiscordUser_IsVerified(Handle plugin, int numParams) { + Handle hJson = GetNativeCell(1); + return JsonObjectGetBool(hJson, "verified"); +} + +public int Native_DiscordUser_IsBot(Handle plugin, int numParams) { + Handle hJson = GetNativeCell(1); + return JsonObjectGetBool(hJson, "bot"); +} \ No newline at end of file diff --git a/addons/sourcemod/scripting/discord/deletemessage.sp b/addons/sourcemod/scripting/discord/deletemessage.sp new file mode 100644 index 0000000..fa2627d --- /dev/null +++ b/addons/sourcemod/scripting/discord/deletemessage.sp @@ -0,0 +1,129 @@ +public int Native_DiscordBot_DeleteMessageID(Handle plugin, int numParams) { + DiscordBot bot = GetNativeCell(1); + + char channelid[64]; + GetNativeString(2, channelid, sizeof(channelid)); + + char msgid[64]; + GetNativeString(3, msgid, sizeof(msgid)); + + Function fCallback = GetNativeCell(4); + any data = GetNativeCell(5); + + DataPack dp = CreateDataPack(); + WritePackCell(dp, bot); + WritePackString(dp, channelid); + WritePackString(dp, msgid); + WritePackCell(dp, plugin); + WritePackFunction(dp, fCallback); + WritePackCell(dp, data); + + ThisDeleteMessage(bot, channelid, msgid, dp); +} + +public int Native_DiscordBot_DeleteMessage(Handle plugin, int numParams) { + DiscordBot bot = GetNativeCell(1); + + char channelid[64]; + DiscordChannel channel = GetNativeCell(2); + channel.GetID(channelid, sizeof(channelid)); + + char msgid[64]; + DiscordMessage msg = GetNativeCell(3); + msg.GetID(msgid, sizeof(msgid)); + + Function fCallback = GetNativeCell(4); + any data = GetNativeCell(5); + + DataPack dp = CreateDataPack(); + WritePackCell(dp, bot); + WritePackString(dp, channelid); + WritePackString(dp, msgid); + WritePackCell(dp, plugin); + WritePackFunction(dp, fCallback); + WritePackCell(dp, data); + + ThisDeleteMessage(bot, channelid, msgid, dp); +} + +static void ThisDeleteMessage(DiscordBot bot, char[] channelid, char[] msgid, DataPack dp) { + char url[64]; + FormatEx(url, sizeof(url), "channels/%s/messages/%s", channelid, msgid); + + Handle request = PrepareRequest(bot, url, k_EHTTPMethodDELETE, null, MessageDeletedResp); + if(request == null) { + CreateTimer(2.0, ThisDeleteMessageDelayed, dp); + return; + } + + SteamWorks_SetHTTPRequestContextValue(request, dp, UrlToDP(url)); + + DiscordSendRequest(request, url); +} + +public Action ThisDeleteMessageDelayed(Handle timer, any data) { + DataPack dp = view_as(data); + ResetPack(dp); + + DiscordBot bot = ReadPackCell(dp); + + char channelid[32]; + ReadPackString(dp, channelid, sizeof(channelid)); + + char msgid[32]; + ReadPackString(dp, msgid, sizeof(msgid)); + + ThisDeleteMessage(bot, channelid, msgid, dp); +} + +public int MessageDeletedResp(Handle request, bool failure, int offset, int statuscode, any dp) { + if(failure || statuscode != 204) { + if(statuscode == 429 || statuscode == 500) { + ResetPack(dp); + DiscordBot bot = ReadPackCell(dp); + + char channelid[32]; + ReadPackString(dp, channelid, sizeof(channelid)); + + char msgid[32]; + ReadPackString(dp, msgid, sizeof(msgid)); + + ThisDeleteMessage(bot, channelid, msgid, view_as(dp)); + + delete request; + return; + } + LogError("[DISCORD] Couldn't delete message - Fail %i %i", failure, statuscode); + delete request; + delete view_as(dp); + return; + } + + ResetPack(dp); + DiscordBot bot = ReadPackCell(dp); + + char channelid[32]; + ReadPackString(dp, channelid, sizeof(channelid)); + + char msgid[32]; + ReadPackString(dp, msgid, sizeof(msgid)); + + Handle plugin = view_as(ReadPackCell(dp)); + Function func = ReadPackFunction(dp); + any pluginData = ReadPackCell(dp); + + Handle fForward = INVALID_HANDLE; + if(func != INVALID_FUNCTION) { + fForward = CreateForward(ET_Ignore, Param_Cell, Param_Cell); + AddToForward(fForward, plugin, func); + + Call_StartForward(fForward); + Call_PushCell(bot); + Call_PushCell(pluginData); + Call_Finish(); + delete fForward; + } + + delete view_as(dp); + delete request; +} \ No newline at end of file diff --git a/addons/sourcemod/scripting/discord/reactions.sp b/addons/sourcemod/scripting/discord/reactions.sp new file mode 100644 index 0000000..46a9e8c --- /dev/null +++ b/addons/sourcemod/scripting/discord/reactions.sp @@ -0,0 +1,328 @@ +public int Native_DiscordBot_AddReaction(Handle plugin, int numParams) { + DiscordBot bot = GetNativeCell(1); + + char channel[32]; + GetNativeString(2, channel, sizeof(channel)); + + char msgid[64]; + GetNativeString(3, msgid, sizeof(msgid)); + + char emoji[128]; + GetNativeString(4, emoji, sizeof(emoji)); + + AddReaction(bot, channel, msgid, emoji); +} + +public int Native_DiscordBot_DeleteReaction(Handle plugin, int numParams) { + DiscordBot bot = GetNativeCell(1); + + char channel[32]; + GetNativeString(2, channel, sizeof(channel)); + + char msgid[64]; + GetNativeString(3, msgid, sizeof(msgid)); + + char emoji[128]; + GetNativeString(4, emoji, sizeof(emoji)); + + char user[128]; + GetNativeString(5, user, sizeof(user)); + + DeleteReaction(bot, channel, msgid, emoji, user); +} + +public int Native_DiscordBot_GetReaction(Handle plugin, int numParams) { + DiscordBot bot = GetNativeCell(1); + + char channel[32]; + GetNativeString(2, channel, sizeof(channel)); + + char msgid[64]; + GetNativeString(3, msgid, sizeof(msgid)); + + char emoji[128]; + GetNativeString(4, emoji, sizeof(emoji)); + + OnGetReactions fCallback = GetNativeCell(5); + Handle fForward = null; + if(fCallback != INVALID_FUNCTION) { + fForward = CreateForward(ET_Ignore, Param_Cell, Param_Cell, Param_String, Param_String, Param_String, Param_String, Param_Cell); + AddToForward(fForward, plugin, fCallback); + } + + any data = GetNativeCell(6); + + GetReaction(bot, channel, msgid, emoji, fForward, data); +} + +///channels/{channel.id}/messages/{message.id}/reactions/{emoji}/@me +public void AddReaction(DiscordBot bot, char[] channel, char[] messageid, char[] emoji) { + char url[256]; + FormatEx(url, sizeof(url), "channels/%s/messages/%s/reactions/%s/@me", channel, messageid, emoji); + + Handle request = PrepareRequest(bot, url, k_EHTTPMethodPUT, null, AddReactionReceiveData); + + DataPack dp = new DataPack(); + WritePackCell(dp, bot); + WritePackString(dp, channel); + WritePackString(dp, messageid); + WritePackString(dp, emoji); + + if(request == dp) { + CreateTimer(2.0, AddReactionDelayed, dp); + return; + } + + char route[128]; + FormatEx(route, sizeof(route), "channels/%s/messages/msgid/reactions", channel); + + SteamWorks_SetHTTPRequestContextValue(request, dp, UrlToDP(route)); + + DiscordSendRequest(request, url); +} + +public Action AddReactionDelayed(Handle timer, any data) { + DataPack dp = view_as(data); + + DiscordBot bot = ReadPackCell(dp); + char channel[64]; + char messageid[64]; + char emoji[64]; + ReadPackString(dp, channel, sizeof(channel)); + ReadPackString(dp, messageid, sizeof(messageid)); + ReadPackString(dp, emoji, sizeof(emoji)); + delete dp; + + AddReaction(bot, channel, messageid, emoji); +} + +public AddReactionReceiveData(Handle request, bool failure, int offset, int statuscode, any data) { + if(failure || statuscode != 204) { + if(statuscode == 429 || statuscode == 500) { + + DataPack dp = view_as(data); + + DiscordBot bot = ReadPackCell(dp); + char channel[64]; + char messageid[64]; + char emoji[64]; + ReadPackString(dp, channel, sizeof(channel)); + ReadPackString(dp, messageid, sizeof(messageid)); + ReadPackString(dp, emoji, sizeof(emoji)); + delete dp; + + AddReaction(bot, channel, messageid, emoji); + + delete request; + return; + } + LogError("[DISCORD] Couldn't Add Reaction - Fail %i %i", failure, statuscode); + delete request; + delete view_as(data); + delete view_as(data); + return; + } + delete request; + delete view_as(data); +} + +///channels/{channel.id}/messages/{message.id}/reactions/{emoji}/{user.id} +public void DeleteReaction(DiscordBot bot, char[] channel, char[] messageid, char[] emoji, char[] userid) { + char url[256]; + + if(StrEqual(userid, "@all")) { + FormatEx(url, sizeof(url), "channels/%s/messages/%s/reactions/%s", channel, messageid, emoji); + }else { + FormatEx(url, sizeof(url), "channels/%s/messages/%s/reactions/%s/%s", channel, messageid, emoji, userid); + } + + Handle request = PrepareRequest(bot, url, k_EHTTPMethodDELETE, null, DeleteReactionReceiveData); + + DataPack dp = new DataPack(); + WritePackCell(dp, bot); + WritePackString(dp, channel); + WritePackString(dp, messageid); + WritePackString(dp, emoji); + WritePackString(dp, userid); + + if(request == dp) { + CreateTimer(2.0, DeleteReactionDelayed, dp); + return; + } + + char route[128]; + FormatEx(route, sizeof(route), "channels/%s/messages/msgid/reactions", channel); + + SteamWorks_SetHTTPRequestContextValue(request, dp, UrlToDP(route)); + + DiscordSendRequest(request, url); +} + +public Action DeleteReactionDelayed(Handle timer, any data) { + DataPack dp = view_as(data); + + DiscordBot bot = ReadPackCell(dp); + char channel[64]; + char messageid[64]; + char emoji[64]; + char userid[64]; + ReadPackString(dp, channel, sizeof(channel)); + ReadPackString(dp, messageid, sizeof(messageid)); + ReadPackString(dp, emoji, sizeof(emoji)); + ReadPackString(dp, userid, sizeof(userid)); + delete dp; + + DeleteReaction(bot, channel, messageid, emoji, userid); +} + +public DeleteReactionReceiveData(Handle request, bool failure, int offset, int statuscode, any data) { + if(failure || statuscode != 204) { + if(statuscode == 429 || statuscode == 500) { + + DataPack dp = view_as(data); + + DiscordBot bot = ReadPackCell(dp); + char channel[64]; + char messageid[64]; + char emoji[64]; + char userid[64]; + ReadPackString(dp, channel, sizeof(channel)); + ReadPackString(dp, messageid, sizeof(messageid)); + ReadPackString(dp, emoji, sizeof(emoji)); + ReadPackString(dp, userid, sizeof(userid)); + delete dp; + + DeleteReaction(bot, channel, messageid, emoji, userid); + + delete request; + return; + } + LogError("[DISCORD] Couldn't Delete Reaction - Fail %i %i", failure, statuscode); + delete request; + delete view_as(data); + return; + } + delete request; + delete view_as(data); +} + +public void GetReaction(DiscordBot bot, char[] channel, char[] messageid, char[] emoji, Handle fForward, any data) { + char url[256]; + FormatEx(url, sizeof(url), "channels/%s/messages/%s/reactions/%s", channel, messageid, emoji); + + Handle request = PrepareRequest(bot, url, k_EHTTPMethodGET, null, GetReactionReceiveData); + + DataPack dp = new DataPack(); + WritePackCell(dp, bot); + WritePackString(dp, channel); + WritePackString(dp, messageid); + WritePackString(dp, emoji); + WritePackCell(dp, fForward); + WritePackCell(dp, data); + + if(request == dp) { + CreateTimer(2.0, GetReactionDelayed, dp); + return; + } + + char route[128]; + FormatEx(route, sizeof(route), "channels/%s/messages/msgid/reactions", channel); + + SteamWorks_SetHTTPRequestContextValue(request, dp, UrlToDP(route)); + + DiscordSendRequest(request, url); +} + +public Action GetReactionDelayed(Handle timer, any data) { + DataPack dp = view_as(data); + + DiscordBot bot = ReadPackCell(dp); + char channel[64]; + char messageid[64]; + char emoji[64]; + ReadPackString(dp, channel, sizeof(channel)); + ReadPackString(dp, messageid, sizeof(messageid)); + ReadPackString(dp, emoji, sizeof(emoji)); + Handle fForward = ReadPackCell(dp); + any addData = ReadPackCell(dp); + delete dp; + + GetReaction(bot, channel, messageid, emoji, fForward, addData); +} + +public GetReactionReceiveData(Handle request, bool failure, int offset, int statuscode, any data) { + if(failure || statuscode != 204) { + if(statuscode == 429 || statuscode == 500) { + + DataPack dp = view_as(data); + + DiscordBot bot = ReadPackCell(dp); + char channel[64]; + char messageid[64]; + char emoji[64]; + ReadPackString(dp, channel, sizeof(channel)); + ReadPackString(dp, messageid, sizeof(messageid)); + ReadPackString(dp, emoji, sizeof(emoji)); + Handle fForward = ReadPackCell(dp); + any addData = ReadPackCell(dp); + delete dp; + + GetReaction(bot, channel, messageid, emoji, fForward, addData); + + delete request; + return; + } + LogError("[DISCORD] Couldn't Delete Reaction - Fail %i %i", failure, statuscode); + delete request; + delete view_as(data); + return; + } + + SteamWorks_GetHTTPResponseBodyCallback(request, GetReactionsData, data); + + delete request; +} + +public int GetReactionsData(const char[] data, any datapack) { + DataPack dp = view_as(datapack); + + DiscordBot bot = ReadPackCell(dp); + char channel[64]; + char messageid[64]; + char emoji[64]; + ReadPackString(dp, channel, sizeof(channel)); + ReadPackString(dp, messageid, sizeof(messageid)); + ReadPackString(dp, emoji, sizeof(emoji)); + Handle fForward = ReadPackCell(dp); + any addData = ReadPackCell(dp); + delete dp; + + Handle hJson = json_load(data); + + ArrayList alUsers = new ArrayList(); + + if(json_is_array(hJson)) { + for(int i = 0; i < json_array_size(hJson); i++) { + DiscordUser user = view_as(json_array_get(hJson, i)); + alUsers.Push(user); + } + } + delete hJson; + + if(fForward != null) { + Call_StartForward(fForward); + Call_PushCell(bot); + Call_PushCell(alUsers); + Call_PushString(channel); + Call_PushString(messageid); + Call_PushString(emoji); + Call_PushCell(addData); + Call_Finish(); + } + + for(int i = 0; i < alUsers.Length; i++) { + DiscordUser user = alUsers.Get(i); + delete user; + } + delete alUsers; +} \ No newline at end of file diff --git a/addons/sourcemod/scripting/discord_api.sp b/addons/sourcemod/scripting/discord_api.sp new file mode 100644 index 0000000..bec0309 --- /dev/null +++ b/addons/sourcemod/scripting/discord_api.sp @@ -0,0 +1,313 @@ +#pragma semicolon 1 + +#define PLUGIN_VERSION "0.1.103" + +#include +#include +#include +#include + +#include "discord/DiscordRequest.sp" +#include "discord/SendMessage.sp" +#include "discord/GetGuilds.sp" +#include "discord/GetGuildChannels.sp" +#include "discord/ListenToChannel.sp" +#include "discord/SendWebHook.sp" +#include "discord/reactions.sp" +#include "discord/UserObject.sp" +#include "discord/MessageObject.sp" +#include "discord/GuildMembers.sp" +#include "discord/GuildRole.sp" +#include "discord/deletemessage.sp" + +//For rate limitation +Handle hRateLimit = null; +Handle hRateReset = null; +Handle hRateLeft = null; + +public Plugin myinfo = { + name = "Discord API", + author = "Deathknife", + description = "", + version = PLUGIN_VERSION, + url = "" +}; + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) { + CreateNative("DiscordBot.GetToken", Native_DiscordBot_Token_Get); + + //SendMessage.sp + CreateNative("DiscordBot.SendMessage", Native_DiscordBot_SendMessage); + CreateNative("DiscordBot.SendMessageToChannelID", Native_DiscordBot_SendMessageToChannel); + CreateNative("DiscordChannel.SendMessage", Native_DiscordChannel_SendMessage); + + //deletemessage.sp + CreateNative("DiscordBot.DeleteMessageID", Native_DiscordBot_DeleteMessageID); + CreateNative("DiscordBot.DeleteMessage", Native_DiscordBot_DeleteMessage); + + //ListenToChannel.sp + CreateNative("DiscordBot.StartTimer", Native_DiscordBot_StartTimer); + + //GetGuilds.sp + CreateNative("DiscordBot.GetGuilds", Native_DiscordBot_GetGuilds); + //GetGuildChannels.sp + CreateNative("DiscordBot.GetGuildChannels", Native_DiscordBot_GetGuildChannels); + //GuildRole.sp + CreateNative("DiscordBot.GetGuildRoles", Native_DiscordBot_GetGuildRoles); + + //reactions.sp + CreateNative("DiscordBot.AddReactionID", Native_DiscordBot_AddReaction); + CreateNative("DiscordBot.DeleteReactionID", Native_DiscordBot_DeleteReaction); + CreateNative("DiscordBot.GetReactionID", Native_DiscordBot_GetReaction); + + //GuildMembers.sp + CreateNative("DiscordBot.GetGuildMembers", Native_DiscordBot_GetGuildMembers); + CreateNative("DiscordBot.GetGuildMembersAll", Native_DiscordBot_GetGuildMembersAll); + + //CreateNative("DiscordChannel.Destroy", Native_DiscordChannel_Destroy); + + //SendWebHook.sp + CreateNative("DiscordWebHook.Send", Native_DiscordWebHook_Send); + //CreateNative("DiscordWebHook.AddField", Native_DiscordWebHook_AddField); + //CreateNative("DiscordWebHook.DeleteFields", Native_DiscordWebHook_DeleteFields); + + //UserObject.sp + CreateNative("DiscordUser.GetID", Native_DiscordUser_GetID); + CreateNative("DiscordUser.GetUsername", Native_DiscordUser_GetUsername); + CreateNative("DiscordUser.GetDiscriminator", Native_DiscordUser_GetDiscriminator); + CreateNative("DiscordUser.GetAvatar", Native_DiscordUser_GetAvatar); + CreateNative("DiscordUser.IsVerified", Native_DiscordUser_IsVerified); + CreateNative("DiscordUser.GetEmail", Native_DiscordUser_GetEmail); + CreateNative("DiscordUser.IsBot", Native_DiscordUser_IsBot); + + //MessageObject.sp + CreateNative("DiscordMessage.GetID", Native_DiscordMessage_GetID); + CreateNative("DiscordMessage.IsPinned", Native_DiscordMessage_IsPinned); + CreateNative("DiscordMessage.GetAuthor", Native_DiscordMessage_GetAuthor); + CreateNative("DiscordMessage.GetContent", Native_DiscordMessage_GetContent); + CreateNative("DiscordMessage.GetChannelID", Native_DiscordMessage_GetChannelID); + + RegPluginLibrary("discord-api"); + + return APLRes_Success; +} + +public void OnPluginStart() { + hRateLeft = new StringMap(); + hRateReset = new StringMap(); + hRateLimit = new StringMap(); +} + +public int Native_DiscordBot_Token_Get(Handle plugin, int numParams) { + DiscordBot bot = GetNativeCell(1); + static char token[196]; + JsonObjectGetString(bot, "token", token, sizeof(token)); + SetNativeString(2, token, GetNativeCell(3)); +} + +stock void BuildAuthHeader(Handle request, DiscordBot Bot) { + static char buffer[256]; + static char token[196]; + JsonObjectGetString(Bot, "token", token, sizeof(token)); + FormatEx(buffer, sizeof(buffer), "Bot %s", token); + SteamWorks_SetHTTPRequestHeaderValue(request, "Authorization", buffer); +} + + +stock Handle PrepareRequest(DiscordBot bot, char[] url, EHTTPMethod method=k_EHTTPMethodGET, Handle hJson=null, SteamWorksHTTPDataReceived DataReceived = INVALID_FUNCTION, SteamWorksHTTPRequestCompleted RequestCompleted = INVALID_FUNCTION) { + static char stringJson[16384]; + stringJson[0] = '\0'; + if(hJson != null) { + json_dump(hJson, stringJson, sizeof(stringJson), 0, true); + } + + //Format url + static char turl[128]; + FormatEx(turl, sizeof(turl), "https://discordapp.com/api/%s", url); + + Handle request = SteamWorks_CreateHTTPRequest(method, turl); + if(request == null) { + return null; + } + + if(bot != null) { + BuildAuthHeader(request, bot); + } + + SteamWorks_SetHTTPRequestRawPostBody(request, "application/json; charset=UTF-8", stringJson, strlen(stringJson)); + + SteamWorks_SetHTTPRequestNetworkActivityTimeout(request, 30); + + if(RequestCompleted == INVALID_FUNCTION) { + //I had some bugs previously where it wouldn't send request and return code 0 if I didn't set request completed. + //This is just a safety then, my issue could have been something else and I will test more later on + RequestCompleted = HTTPCompleted; + } + + if(DataReceived == INVALID_FUNCTION) { + //Need to close the request handle + DataReceived = HTTPDataReceive; + } + + SteamWorks_SetHTTPCallbacks(request, RequestCompleted, HeadersReceived, DataReceived); + if(hJson != null) delete hJson; + + return request; +} + +stock Handle PrepareRequestRaw(DiscordBot bot, char[] url, EHTTPMethod method=k_EHTTPMethodGET, Handle hJson=null, SteamWorksHTTPDataReceived DataReceived = INVALID_FUNCTION, SteamWorksHTTPRequestCompleted RequestCompleted = INVALID_FUNCTION) { + static char stringJson[16384]; + stringJson[0] = '\0'; + if(hJson != null) { + json_dump(hJson, stringJson, sizeof(stringJson), 0, true); + } + + Handle request = SteamWorks_CreateHTTPRequest(method, url); + if(request == null) { + return null; + } + + if(bot != null) { + BuildAuthHeader(request, bot); + } + + SteamWorks_SetHTTPRequestRawPostBody(request, "application/json; charset=UTF-8", stringJson, strlen(stringJson)); + + SteamWorks_SetHTTPRequestNetworkActivityTimeout(request, 30); + + if(RequestCompleted == INVALID_FUNCTION) { + //I had some bugs previously where it wouldn't send request and return code 0 if I didn't set request completed. + //This is just a safety then, my issue could have been something else and I will test more later on + RequestCompleted = HTTPCompleted; + } + + if(DataReceived == INVALID_FUNCTION) { + //Need to close the request handle + DataReceived = HTTPDataReceive; + } + + SteamWorks_SetHTTPCallbacks(request, RequestCompleted, HeadersReceived, DataReceived); + if(hJson != null) delete hJson; + + return request; +} + +public int HTTPCompleted(Handle request, bool failure, bool requestSuccessful, EHTTPStatusCode statuscode, any data, any data2) { +} + +public int HTTPDataReceive(Handle request, bool failure, int offset, int statuscode, any dp) { + delete request; +} + +public int HeadersReceived(Handle request, bool failure, any data, any datapack) { + DataPack dp = view_as(datapack); + if(failure) { + delete dp; + return; + } + + char xRateLimit[16]; + char xRateLeft[16]; + char xRateReset[32]; + + bool exists = false; + + exists = SteamWorks_GetHTTPResponseHeaderValue(request, "X-RateLimit-Limit", xRateLimit, sizeof(xRateLimit)); + exists = SteamWorks_GetHTTPResponseHeaderValue(request, "X-RateLimit-Remaining", xRateLeft, sizeof(xRateLeft)); + exists = SteamWorks_GetHTTPResponseHeaderValue(request, "X-RateLimit-Reset", xRateReset, sizeof(xRateReset)); + + //Get url + char route[128]; + ResetPack(dp); + ReadPackString(dp, route, sizeof(route)); + delete dp; + + int reset = StringToInt(xRateReset); + if(reset > GetTime() + 3) { + reset = GetTime() + 3; + } + + if(exists) { + SetTrieValue(hRateReset, route, reset); + SetTrieValue(hRateLeft, route, StringToInt(xRateLeft)); + SetTrieValue(hRateLimit, route, StringToInt(xRateLimit)); + }else { + SetTrieValue(hRateReset, route, -1); + SetTrieValue(hRateLeft, route, -1); + SetTrieValue(hRateLimit, route, -1); + } +} + +/* +This is rate limit imposing for per-route basis. Doesn't support global limit yet. + */ +public void DiscordSendRequest(Handle request, const char[] route) { + //Check for reset + int time = GetTime(); + int resetTime; + + int defLimit = 0; + if(!GetTrieValue(hRateLimit, route, defLimit)) { + defLimit = 1; + } + + bool exists = GetTrieValue(hRateReset, route, resetTime); + + if(!exists) { + SetTrieValue(hRateReset, route, GetTime() + 5); + SetTrieValue(hRateLeft, route, defLimit - 1); + SteamWorks_SendHTTPRequest(request); + return; + } + + if(time == -1) { + //No x-rate-limit send + SteamWorks_SendHTTPRequest(request); + return; + } + + if(time > resetTime) { + SetTrieValue(hRateLeft, route, defLimit - 1); + SteamWorks_SendHTTPRequest(request); + return; + }else { + int left; + GetTrieValue(hRateLeft, route, left); + if(left == 0) { + float remaining = float(resetTime) - float(time) + 1.0; + Handle dp = new DataPack(); + WritePackCell(dp, request); + WritePackString(dp, route); + CreateTimer(remaining, SendRequestAgain, dp); + }else { + left--; + SetTrieValue(hRateLeft, route, left); + SteamWorks_SendHTTPRequest(request); + } + } +} + +public Handle UrlToDP(char[] url) { + DataPack dp = new DataPack(); + WritePackString(dp, url); + return dp; +} + +public Action SendRequestAgain(Handle timer, any dp) { + ResetPack(dp); + Handle request = ReadPackCell(dp); + char route[128]; + ReadPackString(dp, route, sizeof(route)); + delete view_as(dp); + DiscordSendRequest(request, route); +} + +stock bool RenameJsonObject(Handle hJson, char[] key, char[] toKey) { + Handle hObject = json_object_get(hJson, key); + if(hObject != null) { + json_object_set_new(hJson, toKey, hObject); + json_object_del(hJson, key); + return true; + } + return false; +} \ No newline at end of file diff --git a/addons/sourcemod/scripting/include/SteamWorks.inc b/addons/sourcemod/scripting/include/SteamWorks.inc new file mode 100644 index 0000000..565969f --- /dev/null +++ b/addons/sourcemod/scripting/include/SteamWorks.inc @@ -0,0 +1,413 @@ +#if defined _SteamWorks_Included + #endinput +#endif +#define _SteamWorks_Included + +/* results from UserHasLicenseForApp */ +enum EUserHasLicenseForAppResult +{ + k_EUserHasLicenseResultHasLicense = 0, // User has a license for specified app + k_EUserHasLicenseResultDoesNotHaveLicense = 1, // User does not have a license for the specified app + k_EUserHasLicenseResultNoAuth = 2, // User has not been authenticated +}; + +/* General result codes */ +enum EResult +{ + k_EResultOK = 1, // success + k_EResultFail = 2, // generic failure + k_EResultNoConnection = 3, // no/failed network connection +// k_EResultNoConnectionRetry = 4, // OBSOLETE - removed + k_EResultInvalidPassword = 5, // password/ticket is invalid + k_EResultLoggedInElsewhere = 6, // same user logged in elsewhere + k_EResultInvalidProtocolVer = 7, // protocol version is incorrect + k_EResultInvalidParam = 8, // a parameter is incorrect + k_EResultFileNotFound = 9, // file was not found + k_EResultBusy = 10, // called method busy - action not taken + k_EResultInvalidState = 11, // called object was in an invalid state + k_EResultInvalidName = 12, // name is invalid + k_EResultInvalidEmail = 13, // email is invalid + k_EResultDuplicateName = 14, // name is not unique + k_EResultAccessDenied = 15, // access is denied + k_EResultTimeout = 16, // operation timed out + k_EResultBanned = 17, // VAC2 banned + k_EResultAccountNotFound = 18, // account not found + k_EResultInvalidSteamID = 19, // steamID is invalid + k_EResultServiceUnavailable = 20, // The requested service is currently unavailable + k_EResultNotLoggedOn = 21, // The user is not logged on + k_EResultPending = 22, // Request is pending (may be in process, or waiting on third party) + k_EResultEncryptionFailure = 23, // Encryption or Decryption failed + k_EResultInsufficientPrivilege = 24, // Insufficient privilege + k_EResultLimitExceeded = 25, // Too much of a good thing + k_EResultRevoked = 26, // Access has been revoked (used for revoked guest passes) + k_EResultExpired = 27, // License/Guest pass the user is trying to access is expired + k_EResultAlreadyRedeemed = 28, // Guest pass has already been redeemed by account, cannot be acked again + k_EResultDuplicateRequest = 29, // The request is a duplicate and the action has already occurred in the past, ignored this time + k_EResultAlreadyOwned = 30, // All the games in this guest pass redemption request are already owned by the user + k_EResultIPNotFound = 31, // IP address not found + k_EResultPersistFailed = 32, // failed to write change to the data store + k_EResultLockingFailed = 33, // failed to acquire access lock for this operation + k_EResultLogonSessionReplaced = 34, + k_EResultConnectFailed = 35, + k_EResultHandshakeFailed = 36, + k_EResultIOFailure = 37, + k_EResultRemoteDisconnect = 38, + k_EResultShoppingCartNotFound = 39, // failed to find the shopping cart requested + k_EResultBlocked = 40, // a user didn't allow it + k_EResultIgnored = 41, // target is ignoring sender + k_EResultNoMatch = 42, // nothing matching the request found + k_EResultAccountDisabled = 43, + k_EResultServiceReadOnly = 44, // this service is not accepting content changes right now + k_EResultAccountNotFeatured = 45, // account doesn't have value, so this feature isn't available + k_EResultAdministratorOK = 46, // allowed to take this action, but only because requester is admin + k_EResultContentVersion = 47, // A Version mismatch in content transmitted within the Steam protocol. + k_EResultTryAnotherCM = 48, // The current CM can't service the user making a request, user should try another. + k_EResultPasswordRequiredToKickSession = 49,// You are already logged in elsewhere, this cached credential login has failed. + k_EResultAlreadyLoggedInElsewhere = 50, // You are already logged in elsewhere, you must wait + k_EResultSuspended = 51, // Long running operation (content download) suspended/paused + k_EResultCancelled = 52, // Operation canceled (typically by user: content download) + k_EResultDataCorruption = 53, // Operation canceled because data is ill formed or unrecoverable + k_EResultDiskFull = 54, // Operation canceled - not enough disk space. + k_EResultRemoteCallFailed = 55, // an remote call or IPC call failed + k_EResultPasswordUnset = 56, // Password could not be verified as it's unset server side + k_EResultExternalAccountUnlinked = 57, // External account (PSN, Facebook...) is not linked to a Steam account + k_EResultPSNTicketInvalid = 58, // PSN ticket was invalid + k_EResultExternalAccountAlreadyLinked = 59, // External account (PSN, Facebook...) is already linked to some other account, must explicitly request to replace/delete the link first + k_EResultRemoteFileConflict = 60, // The sync cannot resume due to a conflict between the local and remote files + k_EResultIllegalPassword = 61, // The requested new password is not legal + k_EResultSameAsPreviousValue = 62, // new value is the same as the old one ( secret question and answer ) + k_EResultAccountLogonDenied = 63, // account login denied due to 2nd factor authentication failure + k_EResultCannotUseOldPassword = 64, // The requested new password is not legal + k_EResultInvalidLoginAuthCode = 65, // account login denied due to auth code invalid + k_EResultAccountLogonDeniedNoMail = 66, // account login denied due to 2nd factor auth failure - and no mail has been sent + k_EResultHardwareNotCapableOfIPT = 67, // + k_EResultIPTInitError = 68, // + k_EResultParentalControlRestricted = 69, // operation failed due to parental control restrictions for current user + k_EResultFacebookQueryError = 70, // Facebook query returned an error + k_EResultExpiredLoginAuthCode = 71, // account login denied due to auth code expired + k_EResultIPLoginRestrictionFailed = 72, + k_EResultAccountLockedDown = 73, + k_EResultAccountLogonDeniedVerifiedEmailRequired = 74, + k_EResultNoMatchingURL = 75, + k_EResultBadResponse = 76, // parse failure, missing field, etc. + k_EResultRequirePasswordReEntry = 77, // The user cannot complete the action until they re-enter their password + k_EResultValueOutOfRange = 78, // the value entered is outside the acceptable range + k_EResultUnexpectedError = 79, // something happened that we didn't expect to ever happen + k_EResultDisabled = 80, // The requested service has been configured to be unavailable + k_EResultInvalidCEGSubmission = 81, // The set of files submitted to the CEG server are not valid ! + k_EResultRestrictedDevice = 82, // The device being used is not allowed to perform this action + k_EResultRegionLocked = 83, // The action could not be complete because it is region restricted + k_EResultRateLimitExceeded = 84, // Temporary rate limit exceeded, try again later, different from k_EResultLimitExceeded which may be permanent + k_EResultAccountLoginDeniedNeedTwoFactor = 85, // Need two-factor code to login + k_EResultItemDeleted = 86, // The thing we're trying to access has been deleted + k_EResultAccountLoginDeniedThrottle = 87, // login attempt failed, try to throttle response to possible attacker + k_EResultTwoFactorCodeMismatch = 88, // two factor code mismatch + k_EResultTwoFactorActivationCodeMismatch = 89, // activation code for two-factor didn't match + k_EResultAccountAssociatedToMultiplePartners = 90, // account has been associated with multiple partners + k_EResultNotModified = 91, // data not modified + k_EResultNoMobileDevice = 92, // the account does not have a mobile device associated with it + k_EResultTimeNotSynced = 93, // the time presented is out of range or tolerance + k_EResultSmsCodeFailed = 94, // SMS code failure (no match, none pending, etc.) + k_EResultAccountLimitExceeded = 95, // Too many accounts access this resource + k_EResultAccountActivityLimitExceeded = 96, // Too many changes to this account + k_EResultPhoneActivityLimitExceeded = 97, // Too many changes to this phone + k_EResultRefundToWallet = 98, // Cannot refund to payment method, must use wallet + k_EResultEmailSendFailure = 99, // Cannot send an email + k_EResultNotSettled = 100, // Can't perform operation till payment has settled + k_EResultNeedCaptcha = 101, // Needs to provide a valid captcha + k_EResultGSLTDenied = 102, // a game server login token owned by this token's owner has been banned + k_EResultGSOwnerDenied = 103, // game server owner is denied for other reason (account lock, community ban, vac ban, missing phone) + k_EResultInvalidItemType = 104 // the type of thing we were requested to act on is invalid +}; + +/* This enum is used in client API methods, do not re-number existing values. */ +enum EHTTPMethod +{ + k_EHTTPMethodInvalid = 0, + k_EHTTPMethodGET, + k_EHTTPMethodHEAD, + k_EHTTPMethodPOST, + k_EHTTPMethodPUT, + k_EHTTPMethodDELETE, + k_EHTTPMethodOPTIONS, + k_EHTTPMethodPATCH, + + // The remaining HTTP methods are not yet supported, per rfc2616 section 5.1.1 only GET and HEAD are required for + // a compliant general purpose server. We'll likely add more as we find uses for them. + + // k_EHTTPMethodTRACE, + // k_EHTTPMethodCONNECT +}; + + +/* HTTP Status codes that the server can send in response to a request, see rfc2616 section 10.3 for descriptions + of each of these. */ +enum EHTTPStatusCode +{ + // Invalid status code (this isn't defined in HTTP, used to indicate unset in our code) + k_EHTTPStatusCodeInvalid = 0, + + // Informational codes + k_EHTTPStatusCode100Continue = 100, + k_EHTTPStatusCode101SwitchingProtocols = 101, + + // Success codes + k_EHTTPStatusCode200OK = 200, + k_EHTTPStatusCode201Created = 201, + k_EHTTPStatusCode202Accepted = 202, + k_EHTTPStatusCode203NonAuthoritative = 203, + k_EHTTPStatusCode204NoContent = 204, + k_EHTTPStatusCode205ResetContent = 205, + k_EHTTPStatusCode206PartialContent = 206, + + // Redirection codes + k_EHTTPStatusCode300MultipleChoices = 300, + k_EHTTPStatusCode301MovedPermanently = 301, + k_EHTTPStatusCode302Found = 302, + k_EHTTPStatusCode303SeeOther = 303, + k_EHTTPStatusCode304NotModified = 304, + k_EHTTPStatusCode305UseProxy = 305, + //k_EHTTPStatusCode306Unused = 306, (used in old HTTP spec, now unused in 1.1) + k_EHTTPStatusCode307TemporaryRedirect = 307, + + // Error codes + k_EHTTPStatusCode400BadRequest = 400, + k_EHTTPStatusCode401Unauthorized = 401, // You probably want 403 or something else. 401 implies you're sending a WWW-Authenticate header and the client can sent an Authorization header in response. + k_EHTTPStatusCode402PaymentRequired = 402, // This is reserved for future HTTP specs, not really supported by clients + k_EHTTPStatusCode403Forbidden = 403, + k_EHTTPStatusCode404NotFound = 404, + k_EHTTPStatusCode405MethodNotAllowed = 405, + k_EHTTPStatusCode406NotAcceptable = 406, + k_EHTTPStatusCode407ProxyAuthRequired = 407, + k_EHTTPStatusCode408RequestTimeout = 408, + k_EHTTPStatusCode409Conflict = 409, + k_EHTTPStatusCode410Gone = 410, + k_EHTTPStatusCode411LengthRequired = 411, + k_EHTTPStatusCode412PreconditionFailed = 412, + k_EHTTPStatusCode413RequestEntityTooLarge = 413, + k_EHTTPStatusCode414RequestURITooLong = 414, + k_EHTTPStatusCode415UnsupportedMediaType = 415, + k_EHTTPStatusCode416RequestedRangeNotSatisfiable = 416, + k_EHTTPStatusCode417ExpectationFailed = 417, + k_EHTTPStatusCode4xxUnknown = 418, // 418 is reserved, so we'll use it to mean unknown + k_EHTTPStatusCode429TooManyRequests = 429, + + // Server error codes + k_EHTTPStatusCode500InternalServerError = 500, + k_EHTTPStatusCode501NotImplemented = 501, + k_EHTTPStatusCode502BadGateway = 502, + k_EHTTPStatusCode503ServiceUnavailable = 503, + k_EHTTPStatusCode504GatewayTimeout = 504, + k_EHTTPStatusCode505HTTPVersionNotSupported = 505, + k_EHTTPStatusCode5xxUnknown = 599, +}; + +/* list of possible return values from the ISteamGameCoordinator API */ +enum EGCResults +{ + k_EGCResultOK = 0, + k_EGCResultNoMessage = 1, // There is no message in the queue + k_EGCResultBufferTooSmall = 2, // The buffer is too small for the requested message + k_EGCResultNotLoggedOn = 3, // The client is not logged onto Steam + k_EGCResultInvalidMessage = 4, // Something was wrong with the message being sent with SendMessage +}; + +native bool:SteamWorks_IsVACEnabled(); +native bool:SteamWorks_GetPublicIP(ipaddr[4]); +native SteamWorks_GetPublicIPCell(); +native bool:SteamWorks_IsLoaded(); +native bool:SteamWorks_SetGameData(const String:sData[]); +native bool:SteamWorks_SetGameDescription(const String:sDesc[]); +native bool:SteamWorks_SetMapName(const String:sMapName[]); +native bool:SteamWorks_IsConnected(); +native bool:SteamWorks_SetRule(const String:sKey[], const String:sValue[]); +native bool:SteamWorks_ClearRules(); +native bool:SteamWorks_ForceHeartbeat(); +native bool:SteamWorks_GetUserGroupStatus(client, groupid); +native bool:SteamWorks_GetUserGroupStatusAuthID(authid, groupid); + +native EUserHasLicenseForAppResult:SteamWorks_HasLicenseForApp(client, app); +native EUserHasLicenseForAppResult:SteamWorks_HasLicenseForAppId(authid, app); +native SteamWorks_GetClientSteamID(client, String:sSteamID[], length); + +native bool:SteamWorks_RequestStatsAuthID(authid, appid); +native bool:SteamWorks_RequestStats(client, appid); +native bool:SteamWorks_GetStatCell(client, const String:sKey[], &value); +native bool:SteamWorks_GetStatAuthIDCell(authid, const String:sKey[], &value); +native bool:SteamWorks_GetStatFloat(client, const String:sKey[], &Float:value); +native bool:SteamWorks_GetStatAuthIDFloat(authid, const String:sKey[], &Float:value); + +native Handle:SteamWorks_CreateHTTPRequest(EHTTPMethod:method, const String:sURL[]); +native bool:SteamWorks_SetHTTPRequestContextValue(Handle:hHandle, any:data1, any:data2=0); +native bool:SteamWorks_SetHTTPRequestNetworkActivityTimeout(Handle:hHandle, timeout); +native bool:SteamWorks_SetHTTPRequestHeaderValue(Handle:hHandle, const String:sName[], const String:sValue[]); +native bool:SteamWorks_SetHTTPRequestGetOrPostParameter(Handle:hHandle, const String:sName[], const String:sValue[]); +native bool:SteamWorks_SetHTTPRequestUserAgentInfo(Handle:hHandle, const String:sUserAgentInfo[]); +native bool:SteamWorks_SetHTTPRequestRequiresVerifiedCertificate(Handle:hHandle, bool:bRequireVerifiedCertificate); +native bool:SteamWorks_SetHTTPRequestAbsoluteTimeoutMS(Handle:hHandle, unMilliseconds); + +#if SOURCEMOD_V_MAJOR >= 1 && SOURCEMOD_V_MINOR >= 9 +typeset SteamWorksHTTPRequestCompleted +{ + function void (Handle hRequest, bool bFailure, bool bRequestSuccessful, EHTTPStatusCode eStatusCode); + function void (Handle hRequest, bool bFailure, bool bRequestSuccessful, EHTTPStatusCode eStatusCode, any data1); + function void (Handle hRequest, bool bFailure, bool bRequestSuccessful, EHTTPStatusCode eStatusCode, any data1, any data2); +}; + +typeset SteamWorksHTTPHeadersReceived +{ + function void (Handle hRequest, bool bFailure); + function void (Handle hRequest, bool bFailure, any data1); + function void (Handle hRequest, bool bFailure, any data1, any data2); +}; + +typeset SteamWorksHTTPDataReceived +{ + function void (Handle hRequest, bool bFailure, int offset, int bytesreceived); + function void (Handle hRequest, bool bFailure, int offset, int bytesreceived, any data1); + function void (Handle hRequest, bool bFailure, int offset, int bytesreceived, any data1, any data2); +}; + +typeset SteamWorksHTTPBodyCallback +{ + function void (const char sData[]); + function void (const char sData[], any value); + function void (const int data[], any value, int datalen); +}; + +#else + +funcenum SteamWorksHTTPRequestCompleted +{ + public(Handle:hRequest, bool:bFailure, bool:bRequestSuccessful, EHTTPStatusCode:eStatusCode), + public(Handle:hRequest, bool:bFailure, bool:bRequestSuccessful, EHTTPStatusCode:eStatusCode, any:data1), + public(Handle:hRequest, bool:bFailure, bool:bRequestSuccessful, EHTTPStatusCode:eStatusCode, any:data1, any:data2) +}; + +funcenum SteamWorksHTTPHeadersReceived +{ + public(Handle:hRequest, bool:bFailure), + public(Handle:hRequest, bool:bFailure, any:data1), + public(Handle:hRequest, bool:bFailure, any:data1, any:data2) +}; + +funcenum SteamWorksHTTPDataReceived +{ + public(Handle:hRequest, bool:bFailure, offset, bytesreceived), + public(Handle:hRequest, bool:bFailure, offset, bytesreceived, any:data1), + public(Handle:hRequest, bool:bFailure, offset, bytesreceived, any:data1, any:data2) +}; + +funcenum SteamWorksHTTPBodyCallback +{ + public(const String:sData[]), + public(const String:sData[], any:value), + public(const data[], any:value, datalen) +}; + +#endif + +native bool:SteamWorks_SetHTTPCallbacks(Handle:hHandle, SteamWorksHTTPRequestCompleted:fCompleted = INVALID_FUNCTION, SteamWorksHTTPHeadersReceived:fHeaders = INVALID_FUNCTION, SteamWorksHTTPDataReceived:fData = INVALID_FUNCTION, Handle:hCalling = INVALID_HANDLE); +native bool:SteamWorks_SendHTTPRequest(Handle:hRequest); +native bool:SteamWorks_SendHTTPRequestAndStreamResponse(Handle:hRequest); +native bool:SteamWorks_DeferHTTPRequest(Handle:hRequest); +native bool:SteamWorks_PrioritizeHTTPRequest(Handle:hRequest); +native bool:SteamWorks_GetHTTPResponseHeaderSize(Handle:hRequest, const String:sHeader[], &size); +native bool:SteamWorks_GetHTTPResponseHeaderValue(Handle:hRequest, const String:sHeader[], String:sValue[], size); +native bool:SteamWorks_GetHTTPResponseBodySize(Handle:hRequest, &size); +native bool:SteamWorks_GetHTTPResponseBodyData(Handle:hRequest, String:sBody[], length); +native bool:SteamWorks_GetHTTPStreamingResponseBodyData(Handle:hRequest, cOffset, String:sBody[], length); +native bool:SteamWorks_GetHTTPDownloadProgressPct(Handle:hRequest, &Float:percent); +native bool:SteamWorks_GetHTTPRequestWasTimedOut(Handle:hRequest, &bool:bWasTimedOut); +native bool:SteamWorks_SetHTTPRequestRawPostBody(Handle:hRequest, const String:sContentType[], const String:sBody[], bodylen); +native bool:SteamWorks_SetHTTPRequestRawPostBodyFromFile(Handle:hRequest, const String:sContentType[], const String:sFileName[]); + +native bool:SteamWorks_GetHTTPResponseBodyCallback(Handle:hRequest, SteamWorksHTTPBodyCallback:fCallback, any:data = 0, Handle:hPlugin = INVALID_HANDLE); /* Look up, moved definition for 1.7+ compat. */ +native bool:SteamWorks_WriteHTTPResponseBodyToFile(Handle:hRequest, const String:sFileName[]); + +forward SW_OnValidateClient(ownerauthid, authid); +forward SteamWorks_OnValidateClient(ownerauthid, authid); +forward SteamWorks_SteamServersConnected(); +forward SteamWorks_SteamServersConnectFailure(EResult:result); +forward SteamWorks_SteamServersDisconnected(EResult:result); + +forward Action:SteamWorks_RestartRequested(); +forward SteamWorks_TokenRequested(String:sToken[], maxlen); + +forward SteamWorks_OnClientGroupStatus(authid, groupid, bool:isMember, bool:isOfficer); + +forward EGCResults:SteamWorks_GCSendMessage(unMsgType, const String:pubData[], cubData); +forward SteamWorks_GCMsgAvailable(cubData); +forward EGCResults:SteamWorks_GCRetrieveMessage(punMsgType, const String:pubDest[], cubDest, pcubMsgSize); + +native EGCResults:SteamWorks_SendMessageToGC(unMsgType, const String:pubData[], cubData); + +public Extension:__ext_SteamWorks = +{ + name = "SteamWorks", + file = "SteamWorks.ext", +#if defined AUTOLOAD_EXTENSIONS + autoload = 1, +#else + autoload = 0, +#endif +#if defined REQUIRE_EXTENSIONS + required = 1, +#else + required = 0, +#endif +}; + +#if !defined REQUIRE_EXTENSIONS +public __ext_SteamWorks_SetNTVOptional() +{ + MarkNativeAsOptional("SteamWorks_IsVACEnabled"); + MarkNativeAsOptional("SteamWorks_GetPublicIP"); + MarkNativeAsOptional("SteamWorks_GetPublicIPCell"); + MarkNativeAsOptional("SteamWorks_IsLoaded"); + MarkNativeAsOptional("SteamWorks_SetGameData"); + MarkNativeAsOptional("SteamWorks_SetGameDescription"); + MarkNativeAsOptional("SteamWorks_IsConnected"); + MarkNativeAsOptional("SteamWorks_SetRule"); + MarkNativeAsOptional("SteamWorks_ClearRules"); + MarkNativeAsOptional("SteamWorks_ForceHeartbeat"); + MarkNativeAsOptional("SteamWorks_GetUserGroupStatus"); + MarkNativeAsOptional("SteamWorks_GetUserGroupStatusAuthID"); + + MarkNativeAsOptional("SteamWorks_HasLicenseForApp"); + MarkNativeAsOptional("SteamWorks_HasLicenseForAppId"); + MarkNativeAsOptional("SteamWorks_GetClientSteamID"); + + MarkNativeAsOptional("SteamWorks_RequestStatsAuthID"); + MarkNativeAsOptional("SteamWorks_RequestStats"); + MarkNativeAsOptional("SteamWorks_GetStatCell"); + MarkNativeAsOptional("SteamWorks_GetStatAuthIDCell"); + MarkNativeAsOptional("SteamWorks_GetStatFloat"); + MarkNativeAsOptional("SteamWorks_GetStatAuthIDFloat"); + + MarkNativeAsOptional("SteamWorks_SendMessageToGC"); + + MarkNativeAsOptional("SteamWorks_CreateHTTPRequest"); + MarkNativeAsOptional("SteamWorks_SetHTTPRequestContextValue"); + MarkNativeAsOptional("SteamWorks_SetHTTPRequestNetworkActivityTimeout"); + MarkNativeAsOptional("SteamWorks_SetHTTPRequestHeaderValue"); + MarkNativeAsOptional("SteamWorks_SetHTTPRequestGetOrPostParameter"); + + MarkNativeAsOptional("SteamWorks_SetHTTPCallbacks"); + MarkNativeAsOptional("SteamWorks_SendHTTPRequest"); + MarkNativeAsOptional("SteamWorks_SendHTTPRequestAndStreamResponse"); + MarkNativeAsOptional("SteamWorks_DeferHTTPRequest"); + MarkNativeAsOptional("SteamWorks_PrioritizeHTTPRequest"); + MarkNativeAsOptional("SteamWorks_GetHTTPResponseHeaderSize"); + MarkNativeAsOptional("SteamWorks_GetHTTPResponseHeaderValue"); + MarkNativeAsOptional("SteamWorks_GetHTTPResponseBodySize"); + MarkNativeAsOptional("SteamWorks_GetHTTPResponseBodyData"); + MarkNativeAsOptional("SteamWorks_GetHTTPStreamingResponseBodyData"); + MarkNativeAsOptional("SteamWorks_GetHTTPDownloadProgressPct"); + MarkNativeAsOptional("SteamWorks_SetHTTPRequestRawPostBody"); + MarkNativeAsOptional("SteamWorks_SetHTTPRequestRawPostBodyFromFile"); + + MarkNativeAsOptional("SteamWorks_GetHTTPResponseBodyCallback"); + MarkNativeAsOptional("SteamWorks_WriteHTTPResponseBodyToFile"); +} +#endif diff --git a/addons/sourcemod/scripting/include/admin.inc b/addons/sourcemod/scripting/include/admin.inc index 5052db4..d365dd2 100644 --- a/addons/sourcemod/scripting/include/admin.inc +++ b/addons/sourcemod/scripting/include/admin.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -29,7 +29,7 @@ * * Version: $Id$ */ - + #if defined _admin_included #endinput #endif @@ -40,67 +40,66 @@ */ enum AdminFlag { - Admin_Reservation = 0, /**< Reserved slot */ - Admin_Generic, /**< Generic admin abilities */ - Admin_Kick, /**< Kick another user */ - Admin_Ban, /**< Ban another user */ - Admin_Unban, /**< Unban another user */ - Admin_Slay, /**< Slay/kill/damage another user */ - Admin_Changemap, /**< Change the map */ - Admin_Convars, /**< Change basic convars */ - Admin_Config, /**< Change configuration */ - Admin_Chat, /**< Special chat privileges */ - Admin_Vote, /**< Special vote privileges */ - Admin_Password, /**< Set a server password */ - Admin_RCON, /**< Use RCON */ - Admin_Cheats, /**< Change sv_cheats and use its commands */ - Admin_Root, /**< All access by default */ - Admin_Custom1, /**< First custom flag type */ - Admin_Custom2, /**< Second custom flag type */ - Admin_Custom3, /**< Third custom flag type */ - Admin_Custom4, /**< Fourth custom flag type */ - Admin_Custom5, /**< Fifth custom flag type */ - Admin_Custom6, /**< Sixth custom flag type */ - /* --- */ + Admin_Reservation = 0, /**< Reserved slot */ + Admin_Generic, /**< Generic admin abilities */ + Admin_Kick, /**< Kick another user */ + Admin_Ban, /**< Ban another user */ + Admin_Unban, /**< Unban another user */ + Admin_Slay, /**< Slay/kill/damage another user */ + Admin_Changemap, /**< Change the map */ + Admin_Convars, /**< Change basic convars */ + Admin_Config, /**< Change configuration */ + Admin_Chat, /**< Special chat privileges */ + Admin_Vote, /**< Special vote privileges */ + Admin_Password, /**< Set a server password */ + Admin_RCON, /**< Use RCON */ + Admin_Cheats, /**< Change sv_cheats and use its commands */ + Admin_Root, /**< All access by default */ + Admin_Custom1, /**< First custom flag type */ + Admin_Custom2, /**< Second custom flag type */ + Admin_Custom3, /**< Third custom flag type */ + Admin_Custom4, /**< Fourth custom flag type */ + Admin_Custom5, /**< Fifth custom flag type */ + Admin_Custom6 /**< Sixth custom flag type */ }; -#define AdminFlags_TOTAL 21 /**< Total number of admin flags */ +#define AdminFlags_TOTAL 21 /**< Total number of admin flags */ /** * @section Bitwise values definitions for admin flags. */ -#define ADMFLAG_RESERVATION (1<<0) /**< Convenience macro for Admin_Reservation as a FlagBit */ -#define ADMFLAG_GENERIC (1<<1) /**< Convenience macro for Admin_Generic as a FlagBit */ -#define ADMFLAG_KICK (1<<2) /**< Convenience macro for Admin_Kick as a FlagBit */ -#define ADMFLAG_BAN (1<<3) /**< Convenience macro for Admin_Ban as a FlagBit */ -#define ADMFLAG_UNBAN (1<<4) /**< Convenience macro for Admin_Unban as a FlagBit */ -#define ADMFLAG_SLAY (1<<5) /**< Convenience macro for Admin_Slay as a FlagBit */ -#define ADMFLAG_CHANGEMAP (1<<6) /**< Convenience macro for Admin_Changemap as a FlagBit */ -#define ADMFLAG_CONVARS (1<<7) /**< Convenience macro for Admin_Convars as a FlagBit */ -#define ADMFLAG_CONFIG (1<<8) /**< Convenience macro for Admin_Config as a FlagBit */ -#define ADMFLAG_CHAT (1<<9) /**< Convenience macro for Admin_Chat as a FlagBit */ -#define ADMFLAG_VOTE (1<<10) /**< Convenience macro for Admin_Vote as a FlagBit */ -#define ADMFLAG_PASSWORD (1<<11) /**< Convenience macro for Admin_Password as a FlagBit */ -#define ADMFLAG_RCON (1<<12) /**< Convenience macro for Admin_RCON as a FlagBit */ -#define ADMFLAG_CHEATS (1<<13) /**< Convenience macro for Admin_Cheats as a FlagBit */ -#define ADMFLAG_ROOT (1<<14) /**< Convenience macro for Admin_Root as a FlagBit */ -#define ADMFLAG_CUSTOM1 (1<<15) /**< Convenience macro for Admin_Custom1 as a FlagBit */ -#define ADMFLAG_CUSTOM2 (1<<16) /**< Convenience macro for Admin_Custom2 as a FlagBit */ -#define ADMFLAG_CUSTOM3 (1<<17) /**< Convenience macro for Admin_Custom3 as a FlagBit */ -#define ADMFLAG_CUSTOM4 (1<<18) /**< Convenience macro for Admin_Custom4 as a FlagBit */ -#define ADMFLAG_CUSTOM5 (1<<19) /**< Convenience macro for Admin_Custom5 as a FlagBit */ -#define ADMFLAG_CUSTOM6 (1<<20) /**< Convenience macro for Admin_Custom6 as a FlagBit */ +#define ADMFLAG_RESERVATION (1<<0) /**< Convenience macro for Admin_Reservation as a FlagBit */ +#define ADMFLAG_GENERIC (1<<1) /**< Convenience macro for Admin_Generic as a FlagBit */ +#define ADMFLAG_KICK (1<<2) /**< Convenience macro for Admin_Kick as a FlagBit */ +#define ADMFLAG_BAN (1<<3) /**< Convenience macro for Admin_Ban as a FlagBit */ +#define ADMFLAG_UNBAN (1<<4) /**< Convenience macro for Admin_Unban as a FlagBit */ +#define ADMFLAG_SLAY (1<<5) /**< Convenience macro for Admin_Slay as a FlagBit */ +#define ADMFLAG_CHANGEMAP (1<<6) /**< Convenience macro for Admin_Changemap as a FlagBit */ +#define ADMFLAG_CONVARS (1<<7) /**< Convenience macro for Admin_Convars as a FlagBit */ +#define ADMFLAG_CONFIG (1<<8) /**< Convenience macro for Admin_Config as a FlagBit */ +#define ADMFLAG_CHAT (1<<9) /**< Convenience macro for Admin_Chat as a FlagBit */ +#define ADMFLAG_VOTE (1<<10) /**< Convenience macro for Admin_Vote as a FlagBit */ +#define ADMFLAG_PASSWORD (1<<11) /**< Convenience macro for Admin_Password as a FlagBit */ +#define ADMFLAG_RCON (1<<12) /**< Convenience macro for Admin_RCON as a FlagBit */ +#define ADMFLAG_CHEATS (1<<13) /**< Convenience macro for Admin_Cheats as a FlagBit */ +#define ADMFLAG_ROOT (1<<14) /**< Convenience macro for Admin_Root as a FlagBit */ +#define ADMFLAG_CUSTOM1 (1<<15) /**< Convenience macro for Admin_Custom1 as a FlagBit */ +#define ADMFLAG_CUSTOM2 (1<<16) /**< Convenience macro for Admin_Custom2 as a FlagBit */ +#define ADMFLAG_CUSTOM3 (1<<17) /**< Convenience macro for Admin_Custom3 as a FlagBit */ +#define ADMFLAG_CUSTOM4 (1<<18) /**< Convenience macro for Admin_Custom4 as a FlagBit */ +#define ADMFLAG_CUSTOM5 (1<<19) /**< Convenience macro for Admin_Custom5 as a FlagBit */ +#define ADMFLAG_CUSTOM6 (1<<20) /**< Convenience macro for Admin_Custom6 as a FlagBit */ /** * @endsection */ /** - * @section Hardcoded authentication methods + * @section Hardcoded authentication methods */ -#define AUTHMETHOD_STEAM "steam" /**< SteamID based authentication */ -#define AUTHMETHOD_IP "ip" /**< IP based authentication */ -#define AUTHMETHOD_NAME "name" /**< Name based authentication */ +#define AUTHMETHOD_STEAM "steam" /**< SteamID based authentication */ +#define AUTHMETHOD_IP "ip" /**< IP based authentication */ +#define AUTHMETHOD_NAME "name" /**< Name based authentication */ /** * @endsection @@ -111,8 +110,8 @@ enum AdminFlag */ enum OverrideType { - Override_Command = 1, /**< Command */ - Override_CommandGroup, /**< Command group */ + Override_Command = 1, /**< Command */ + Override_CommandGroup /**< Command group */ }; /** @@ -121,7 +120,7 @@ enum OverrideType enum OverrideRule { Command_Deny = 0, - Command_Allow = 1, + Command_Allow = 1 }; /** @@ -129,24 +128,24 @@ enum OverrideRule */ enum ImmunityType { - Immunity_Default = 1, /**< Deprecated. */ - Immunity_Global, /**< Deprecated. */ + Immunity_Default = 1, /**< Deprecated. */ + Immunity_Global /**< Deprecated. */ }; -/** +/** * Identifies a unique entry in the group permissions cache. These are not Handles. */ enum GroupId { - INVALID_GROUP_ID = -1, /**< An invalid/non-existent group */ + INVALID_GROUP_ID = -1 /**< An invalid/non-existent group */ }; -/** +/** * Identifies a unique entry in the admin permissions cache. These are not Handles. */ enum AdminId { - INVALID_ADMIN_ID = -1, /**< An invalid/non-existent admin */ + INVALID_ADMIN_ID = -1 /**< An invalid/non-existent admin */ }; /** @@ -154,8 +153,8 @@ enum AdminId */ enum AdmAccessMode { - Access_Real, /**< Access the user has inherently */ - Access_Effective, /**< Access the user has from their groups */ + Access_Real, /**< Access the user has inherently */ + Access_Effective /**< Access the user has from their groups */ }; /** @@ -163,9 +162,9 @@ enum AdmAccessMode */ enum AdminCachePart { - AdminCache_Overrides = 0, /**< Global overrides */ - AdminCache_Groups = 1, /**< All groups (automatically invalidates admins too) */ - AdminCache_Admins = 2, /**< All admins */ + AdminCache_Overrides = 0, /**< Global overrides */ + AdminCache_Groups = 1, /**< All groups (automatically invalidates admins too) */ + AdminCache_Admins = 2 /**< All admins */ }; methodmap AdminId { @@ -221,7 +220,7 @@ methodmap AdminId { // @param maxlength Maximum size of the output name buffer. // @return A GroupId index and a name pointer, or // INVALID_GROUP_ID and NULL if an error occurred. - public native GroupId GetGroup(int index, const char[] name, int maxlength); + public native GroupId GetGroup(int index, char[] name, int maxlength); // Sets a password on an admin. // @@ -269,45 +268,45 @@ methodmap AdminId { methodmap GroupId { // Gets whether or not a flag is enabled on a group's flag set. // - // @param flag Admin flag to retrieve. - // @return True if enabled, false otherwise, + // @param flag Admin flag to retrieve. + // @return True if enabled, false otherwise, public native bool HasFlag(AdminFlag flag); // Adds or removes a flag from a group's flag set. // - // @param flag Admin flag to toggle. - // @param enabled True to set the flag, false to unset/disable. + // @param flag Admin flag to toggle. + // @param enabled True to set the flag, false to unset/disable. public native void SetFlag(AdminFlag flag, bool enabled); // Returns the flag set that is added to users from this group. // - // @return Bitstring containing the flags enabled. + // @return Bitstring containing the flags enabled. public native int GetFlags(); // Returns a group that this group is immune to given an index. // - // @param number Index from 0 to N-1, from GroupImmunitiesCount. - // @return GroupId that this group is immune to, or INVALID_GROUP_ID on failure. + // @param number Index from 0 to N-1, from GroupImmunitiesCount. + // @return GroupId that this group is immune to, or INVALID_GROUP_ID on failure. public native GroupId GetGroupImmunity(int index); // Adds immunity to a specific group. // - // @param other Group id to receive immunity to. + // @param other Group id to receive immunity to. public native void AddGroupImmunity(GroupId other); // Retrieves a group-specific command override. // - // @param name String containing command name (case sensitive). - // @param type Override type (specific command or group). - // @param rule Optional pointer to store allow/deny setting. - // @return True if an override exists, false otherwise. + // @param name String containing command name (case sensitive). + // @param type Override type (specific command or group). + // @param rule Optional pointer to store allow/deny setting. + // @return True if an override exists, false otherwise. public native bool GetCommandOverride(const char[] name, OverrideType type, OverrideRule &rule); // Adds a group-specific override type. // - // @param name String containing command name (case sensitive). - // @param type Override type (specific command or group). - // @param rule Override allow/deny setting. + // @param name String containing command name (case sensitive). + // @param type Override type (specific command or group). + // @param rule Override allow/deny setting. public native void AddCommandOverride(const char[] name, OverrideType type, OverrideRule rule); // Number of specific group immunities @@ -325,15 +324,15 @@ methodmap GroupId { /** * Called when part of the cache needs to be rebuilt. * - * @param part Part of the admin cache to rebuild. + * @param part Part of the admin cache to rebuild. */ forward void OnRebuildAdminCache(AdminCachePart part); /** * Tells the admin system to dump a portion of the cache. * - * @param part Part of the cache to dump. Specifying groups also dumps admins. - * @param rebuild If true, the rebuild forwards will fire. + * @param part Part of the cache to dump. Specifying groups also dumps admins. + * @param rebuild If true, the rebuild forwards will fire. */ native void DumpAdminCache(AdminCachePart part, bool rebuild); @@ -341,43 +340,43 @@ native void DumpAdminCache(AdminCachePart part, bool rebuild); * Adds a global command flag override. Any command registered with this name * will assume the new flag. This is applied retroactively as well. * - * @param cmd String containing command name (case sensitive). - * @param type Override type (specific command or group). - * @param flags New admin flag. + * @param cmd String containing command name (case sensitive). + * @param type Override type (specific command or group). + * @param flags New admin flag. */ native void AddCommandOverride(const char[] cmd, OverrideType type, int flags); /** * Returns a command override. * - * @param cmd String containing command name (case sensitive). - * @param type Override type (specific command or group). - * @param flags By-reference cell to store the flag (undefined if not found). - * @return True if there is an override, false otherwise. + * @param cmd String containing command name (case sensitive). + * @param type Override type (specific command or group). + * @param flags By-reference cell to store the flag (undefined if not found). + * @return True if there is an override, false otherwise. */ native bool GetCommandOverride(const char[] cmd, OverrideType type, int &flags); /** * Unsets a command override. * - * @param cmd String containing command name (case sensitive). - * @param type Override type (specific command or group). + * @param cmd String containing command name (case sensitive). + * @param type Override type (specific command or group). */ native void UnsetCommandOverride(const char[] cmd, OverrideType type); /** * Adds a new group. Name must be unique. * - * @param group_name String containing the group name. - * @return A new group id, INVALID_GROUP_ID if it already exists. + * @param group_name String containing the group name. + * @return A new group id, INVALID_GROUP_ID if it already exists. */ native GroupId CreateAdmGroup(const char[] group_name); /** * Finds a group by name. * - * @param group_name String containing the group name. - * @return A group id, or INVALID_GROUP_ID if not found. + * @param group_name String containing the group name. + * @return A group id, or INVALID_GROUP_ID if not found. */ native GroupId FindAdmGroup(const char[] group_name); @@ -385,9 +384,9 @@ native GroupId FindAdmGroup(const char[] group_name); * Adds or removes a flag from a group's flag set. * @note These are called "add flags" because they add to a user's flags. * - * @param id Group id. - * @param flag Admin flag to toggle. - * @param enabled True to set the flag, false to unset/disable. + * @param id Group id. + * @param flag Admin flag to toggle. + * @param enabled True to set the flag, false to unset/disable. */ native void SetAdmGroupAddFlag(GroupId id, AdminFlag flag, bool enabled); @@ -395,9 +394,9 @@ native void SetAdmGroupAddFlag(GroupId id, AdminFlag flag, bool enabled); * Gets the set value of an add flag on a group's flag set. * @note These are called "add flags" because they add to a user's flags. * - * @param id Group id. - * @param flag Admin flag to retrieve. - * @return True if enabled, false otherwise, + * @param id Group id. + * @param flag Admin flag to retrieve. + * @return True if enabled, false otherwise, */ native bool GetAdmGroupAddFlag(GroupId id, AdminFlag flag); @@ -405,19 +404,19 @@ native bool GetAdmGroupAddFlag(GroupId id, AdminFlag flag); * Returns the flag set that is added to a user from their group. * @note These are called "add flags" because they add to a user's flags. * - * @param id GroupId of the group. - * @return Bitstring containing the flags enabled. + * @param id GroupId of the group. + * @return Bitstring containing the flags enabled. */ native int GetAdmGroupAddFlags(GroupId id); /** - * @deprecated Functionality removed. + * @deprecated Functionality removed. */ #pragma deprecated Use SetAdmGroupImmunityLevel() instead. native void SetAdmGroupImmunity(GroupId id, ImmunityType type, bool enabled); /** - * @deprecated Functionality removed. + * @deprecated Functionality removed. */ #pragma deprecated Use GetAdmGroupImmunityLevel() instead. native bool GetAdmGroupImmunity(GroupId id, ImmunityType type); @@ -425,62 +424,63 @@ native bool GetAdmGroupImmunity(GroupId id, ImmunityType type); /** * Adds immunity to a specific group. * - * @param id Group id. - * @param other_id Group id to receive immunity to. + * @param id Group id. + * @param other_id Group id to receive immunity to. */ native void SetAdmGroupImmuneFrom(GroupId id, GroupId other_id); /** * Returns the number of specific group immunities. * - * @param id Group id. - * @return Number of group immunities. + * @param id Group id. + * @return Number of group immunities. */ native int GetAdmGroupImmuneCount(GroupId id); /** * Returns a group that this group is immune to given an index. * - * @param id Group id. - * @param number Index from 0 to N-1, from GetAdmGroupImmuneCount(). - * @return GroupId that this group is immune to, or INVALID_GROUP_ID on failure. + * @param id Group id. + * @param number Index from 0 to N-1, from GetAdmGroupImmuneCount(). + * @return GroupId that this group is immune to, or INVALID_GROUP_ID on failure. */ -native GroupId GetAdmGroupImmuneFrom(GroupId id, int number); +native GroupId GetAdmGroupImmuneFrom(GroupId id, int number); /** * Adds a group-specific override type. * - * @param id Group id. - * @param name String containing command name (case sensitive). - * @param type Override type (specific command or group). - * @param rule Override allow/deny setting. + * @param id Group id. + * @param name String containing command name (case sensitive). + * @param type Override type (specific command or group). + * @param rule Override allow/deny setting. */ native void AddAdmGroupCmdOverride(GroupId id, const char[] name, OverrideType type, OverrideRule rule); /** * Retrieves a group-specific command override. * - * @param id Group id. - * @param name String containing command name (case sensitive). - * @param type Override type (specific command or group). - * @param rule Optional pointer to store allow/deny setting. - * @return True if an override exists, false otherwise. + * @param id Group id. + * @param name String containing command name (case sensitive). + * @param type Override type (specific command or group). + * @param rule Optional pointer to store allow/deny setting. + * @return True if an override exists, false otherwise. */ native bool GetAdmGroupCmdOverride(GroupId id, const char[] name, OverrideType type, OverrideRule &rule); /** - * Registers an authentication identity type. You normally never need to call this except for + * Registers an authentication identity type. You normally never need to call this except for * very specific systems. * - * @param name Codename to use for your authentication type. + * @param name Codename to use for your authentication type. */ native void RegisterAuthIdentType(const char[] name); /** - * Creates a new admin entry in the permissions cache. + * Creates a new admin entry in the permissions cache and returns the generated AdminId index. * - * @param name Name for this entry (does not have to be unique). - * Specify an empty string for an anonymous admin. + * @param name Name for this entry (does not have to be unique). + * Specify an empty string for an anonymous admin. + * @return New AdminId index or INVALID_ADMIN_ID if name is empty */ native AdminId CreateAdmin(const char[] name=""); @@ -489,109 +489,109 @@ native AdminId CreateAdmin(const char[] name=""); * * @note This function can return UTF-8 strings, and will safely chop UTF-8 strings. * - * @param id AdminId of the admin. - * @param name String buffer to store name. - * @param maxlength Maximum size of string buffer. - * @return Number of bytes written. + * @param id AdminId of the admin. + * @param name String buffer to store name. + * @param maxlength Maximum size of string buffer. + * @return Number of bytes written. */ native int GetAdminUsername(AdminId id, char[] name, int maxlength); /** * Binds an admin to an identity for fast lookup later on. The bind must be unique. * - * @param id AdminId of the admin. - * @param auth Auth method to use, predefined or from RegisterAuthIdentType(). - * @param ident String containing the arbitrary, unique identity. - * @return True on success, false if the auth method was not found, - * ident was already taken, or ident invalid for auth method. + * @param id AdminId of the admin. + * @param auth Auth method to use, predefined or from RegisterAuthIdentType(). + * @param ident String containing the arbitrary, unique identity. + * @return True on success, false if the auth method was not found, + * ident was already taken, or ident invalid for auth method. */ native bool BindAdminIdentity(AdminId id, const char[] auth, const char[] ident); /** * Sets whether or not a flag is enabled on an admin. * - * @param id AdminId index of the admin. - * @param flag Admin flag to use. - * @param enabled True to enable, false to disable. + * @param id AdminId index of the admin. + * @param flag Admin flag to use. + * @param enabled True to enable, false to disable. */ native void SetAdminFlag(AdminId id, AdminFlag flag, bool enabled); /** * Returns whether or not a flag is enabled on an admin. * - * @param id AdminId index of the admin. - * @param flag Admin flag to use. - * @param mode Access mode to check. - * @return True if enabled, false otherwise. + * @param id AdminId index of the admin. + * @param flag Admin flag to use. + * @param mode Access mode to check. + * @return True if enabled, false otherwise. */ native bool GetAdminFlag(AdminId id, AdminFlag flag, AdmAccessMode mode=Access_Effective); /** * Returns the bitstring of access flags on an admin. * - * @param id AdminId index of the admin. - * @param mode Access mode to use. - * @return A bitstring containing which flags are enabled. + * @param id AdminId index of the admin. + * @param mode Access mode to use. + * @return A bitstring containing which flags are enabled. */ native int GetAdminFlags(AdminId id, AdmAccessMode mode); /** - * Adds a group to an admin's inherited group list. Any flags the group has + * Adds a group to an admin's inherited group list. Any flags the group has * will be added to the admin's effective flags. * - * @param id AdminId index of the admin. - * @param gid GroupId index of the group. - * @return True on success, false on invalid input or duplicate membership. + * @param id AdminId index of the admin. + * @param gid GroupId index of the group. + * @return True on success, false on invalid input or duplicate membership. */ native bool AdminInheritGroup(AdminId id, GroupId gid); /** * Returns the number of groups this admin is a member of. - * - * @param id AdminId index of the admin. - * @return Number of groups this admin is a member of. + * + * @param id AdminId index of the admin. + * @return Number of groups this admin is a member of. */ native int GetAdminGroupCount(AdminId id); /** * Returns group information from an admin. * - * @param id AdminId index of the admin. - * @param index Group number to retrieve, from 0 to N-1, where N - * is the value of GetAdminGroupCount(id). - * @param name Buffer to store the group's name. - * Note: This will safely chop UTF-8 strings. - * @param maxlength Maximum size of the output name buffer. - * @return A GroupId index and a name pointer, or - * INVALID_GROUP_ID and NULL if an error occurred. + * @param id AdminId index of the admin. + * @param index Group number to retrieve, from 0 to N-1, where N + * is the value of GetAdminGroupCount(id). + * @param name Buffer to store the group's name. + * Note: This will safely chop UTF-8 strings. + * @param maxlength Maximum size of the output name buffer. + * @return A GroupId index and a name pointer, or + * INVALID_GROUP_ID and NULL if an error occurred. */ -native GroupId GetAdminGroup(AdminId id, int index, const char[] name, int maxlength); +native GroupId GetAdminGroup(AdminId id, int index, char[] name, int maxlength); /** * Sets a password on an admin. * - * @param id AdminId index of the admin. - * @param password String containing the password. + * @param id AdminId index of the admin. + * @param password String containing the password. */ native void SetAdminPassword(AdminId id, const char[] password); /** * Gets an admin's password. * - * @param id AdminId index of the admin. - * @param buffer Optional buffer to store the admin's password. - * @param maxlength Maximum size of the output name buffer. - * Note: This will safely chop UTF-8 strings. - * @return True if there was a password set, false otherwise. + * @param id AdminId index of the admin. + * @param buffer Optional buffer to store the admin's password. + * @param maxlength Maximum size of the output name buffer. + * Note: This will safely chop UTF-8 strings. + * @return True if there was a password set, false otherwise. */ native bool GetAdminPassword(AdminId id, char[] buffer="", int maxlength=0); /** * Attempts to find an admin by an auth method and an identity. * - * @param auth Auth method to try. - * @param identity Identity string to look up. - * @return An AdminId index if found, INVALID_ADMIN_ID otherwise. + * @param auth Auth method to try. + * @param identity Identity string to look up. + * @return An AdminId index if found, INVALID_ADMIN_ID otherwise. */ native AdminId FindAdminByIdentity(const char[] auth, const char[] identity); @@ -600,82 +600,82 @@ native AdminId FindAdminByIdentity(const char[] auth, const char[] identity); * * @note This will remove any bindings to a specific user. * - * @param id AdminId index to remove/invalidate. - * @return True on success, false otherwise. + * @param id AdminId index to remove/invalidate. + * @return True on success, false otherwise. */ native bool RemoveAdmin(AdminId id); /** * Converts a flag bit string to a bit array. * - * @param bits Bit string containing the flags. - * @param array Array to write the flags to. Enabled flags will be 'true'. - * @param maxSize Maximum number of flags the array can store. - * @return Number of flags written. + * @param bits Bit string containing the flags. + * @param array Array to write the flags to. Enabled flags will be 'true'. + * @param maxSize Maximum number of flags the array can store. + * @return Number of flags written. */ native int FlagBitsToBitArray(int bits, bool[] array, int maxSize); /** * Converts a flag array to a bit string. * - * @param array Array containing true or false for each AdminFlag. - * @param maxSize Maximum size of the flag array. - * @return A bit string composed of the array bits. + * @param array Array containing true or false for each AdminFlag. + * @param maxSize Maximum size of the flag array. + * @return A bit string composed of the array bits. */ native int FlagBitArrayToBits(const bool[] array, int maxSize); /** * Converts an array of flags to bits. * - * @param array Array containing flags that are enabled. - * @param numFlags Number of flags in the array. - * @return A bit string composed of the array flags. + * @param array Array containing flags that are enabled. + * @param numFlags Number of flags in the array. + * @return A bit string composed of the array flags. */ native int FlagArrayToBits(const AdminFlag[] array, int numFlags); /** * Converts a bit string to an array of flags. * - * @param bits Bit string containing the flags. - * @param array Output array to write flags. - * @param maxSize Maximum size of the flag array. - * @return Number of flags written. + * @param bits Bit string containing the flags. + * @param array Output array to write flags. + * @param maxSize Maximum size of the flag array. + * @return Number of flags written. */ native int FlagBitsToArray(int bits, AdminFlag[] array, int maxSize); /** * Finds a flag by its string name. * - * @param name Flag name (like "kick"), case sensitive. - * @param flag Variable to store flag in. - * @return True on success, false if not found. + * @param name Flag name (like "kick"), case sensitive. + * @param flag Variable to store flag in. + * @return True on success, false if not found. */ native bool FindFlagByName(const char[] name, AdminFlag &flag); /** * Finds a flag by a given character. * - * @param c Flag ASCII character/token. - * @param flag Variable to store flag in. - * @return True on success, false if not found. + * @param c Flag ASCII character/token. + * @param flag Variable to store flag in. + * @return True on success, false if not found. */ native bool FindFlagByChar(int c, AdminFlag &flag); /** * Finds the flag char for a given admin flag. * - * @param flag Flag to look up. - * @param c Variable to store flag char. - * @return True on success, false if not found. + * @param flag Flag to look up. + * @param c Variable to store flag char. + * @return True on success, false if not found. */ native bool FindFlagChar(AdminFlag flag, int &c); /** * Converts a string of flag characters to a bit string. * - * @param flags Flag ASCII string. - * @param numchars Optional variable to store the number of bytes read. - * @return Bit string of ADMFLAG values. + * @param flags Flag ASCII string. + * @param numchars Optional variable to store the number of bytes read. + * @return Bit string of ADMFLAG values. */ native int ReadFlagString(const char[] flags, int &numchars=0); @@ -688,15 +688,15 @@ native int ReadFlagString(const char[] flags, int &numchars=0); * 2. If the targeted AdminId is the same as the targeting AdminId, * (self) targeting succeeds. * 3. If the targeting admin is root, targeting succeeds. - * 4. If the targeted admin has access higher (as interpreted by + * 4. If the targeted admin has access higher (as interpreted by * (sm_immunity_mode) than the targeting admin, then targeting fails. * 5. If the targeted admin has specific immunity from the * targeting admin via group immunities, targeting fails. * 6. Targeting succeeds. * - * @param admin Admin doing the targetting (may be INVALID_ADMIN_ID). - * @param target Target admin (may be INVALID_ADMIN_ID). - * @return True if targetable, false if immune. + * @param admin Admin doing the targetting (may be INVALID_ADMIN_ID). + * @param target Target admin (may be INVALID_ADMIN_ID). + * @return True if targetable, false if immune. */ native bool CanAdminTarget(AdminId admin, AdminId target); @@ -704,50 +704,50 @@ native bool CanAdminTarget(AdminId admin, AdminId target); * Creates an admin auth method. This does not need to be called more than once * per method, ever. * - * @param method Name of the authentication method. - * @return True on success, false on failure. + * @param method Name of the authentication method. + * @return True on success, false on failure. */ native bool CreateAuthMethod(const char[] method); /** * Sets a group's immunity level. * - * @param gid Group Id. - * @param level Immunity level value. - * @return Old immunity level value. + * @param gid Group Id. + * @param level Immunity level value. + * @return Old immunity level value. */ native int SetAdmGroupImmunityLevel(GroupId gid, int level); /** * Gets a group's immunity level (defaults to 0). * - * @param gid Group Id. - * @return Immunity level value. + * @param gid Group Id. + * @return Immunity level value. */ native int GetAdmGroupImmunityLevel(GroupId gid); /** * Sets an admin's immunity level. * - * @param id Admin Id. - * @param level Immunity level value. - * @return Old immunity level value. + * @param id Admin Id. + * @param level Immunity level value. + * @return Old immunity level value. */ native int SetAdminImmunityLevel(AdminId id, int level); /** * Gets an admin's immunity level. * - * @param id Admin Id. - * @return Immunity level value. + * @param id Admin Id. + * @return Immunity level value. */ native int GetAdminImmunityLevel(AdminId id); /** * Converts a flag to its single bit. - * - * @param flag Flag to convert. - * @return Bit representation of the flag. + * + * @param flag Flag to convert. + * @return Bit representation of the flag. */ stock int FlagToBit(AdminFlag flag) { @@ -757,19 +757,19 @@ stock int FlagToBit(AdminFlag flag) /** * Converts a bit to an AdminFlag. * - * @param bit Bit to convert. - * @param flag Stores the converted flag by reference. - * @return True on success, false otherwise. + * @param bit Bit to convert. + * @param flag Stores the converted flag by reference. + * @return True on success, false otherwise. */ stock bool BitToFlag(int bit, AdminFlag &flag) { AdminFlag array[1]; - + if (FlagBitsToArray(bit, array, 1)) { flag = array[0]; return true; } - + return false; } diff --git a/addons/sourcemod/scripting/include/adminmenu.inc b/addons/sourcemod/scripting/include/adminmenu.inc index 2bcffde..e82323e 100644 --- a/addons/sourcemod/scripting/include/adminmenu.inc +++ b/addons/sourcemod/scripting/include/adminmenu.inc @@ -52,32 +52,32 @@ #endif /** Category for player commands. */ -#define ADMINMENU_PLAYERCOMMANDS "PlayerCommands" +#define ADMINMENU_PLAYERCOMMANDS "PlayerCommands" /** Category for server commands. */ -#define ADMINMENU_SERVERCOMMANDS "ServerCommands" +#define ADMINMENU_SERVERCOMMANDS "ServerCommands" /** Category for voting commands. */ -#define ADMINMENU_VOTINGCOMMANDS "VotingCommands" +#define ADMINMENU_VOTINGCOMMANDS "VotingCommands" /** * Called when the admin menu is created and 3rd party plugins can grab * the Handle or add categories. * - * @param topmenu Handle to the admin menu's TopMenu. + * @param topmenu Handle to the admin menu's TopMenu. */ forward void OnAdminMenuCreated(Handle topmenu); /** * Called when the admin menu is ready to have items added. * - * @param topmenu Handle to the admin menu's TopMenu. + * @param topmenu Handle to the admin menu's TopMenu. */ forward void OnAdminMenuReady(Handle topmenu); /** * Retrieves the Handle to the admin top menu. * - * @return Handle to the admin menu's TopMenu, - * or INVALID_HANDLE if not created yet. + * @return Handle to the admin menu's TopMenu, + * or INVALID_HANDLE if not created yet. */ native TopMenu GetAdminTopMenu(); @@ -87,16 +87,16 @@ native TopMenu GetAdminTopMenu(); * Each client is displayed as: name (userid) * Each item contains the userid as a string for its info. * - * @param menu Menu Handle. - * @param source_client Source client, or 0 to ignore immunity. - * @param in_game_only True to only select in-game players. - * @param alive_only True to only select alive players. - * @return Number of clients added. + * @param menu Menu Handle. + * @param source_client Source client, or 0 to ignore immunity. + * @param in_game_only True to only select in-game players. + * @param alive_only True to only select alive players. + * @return Number of clients added. */ native int AddTargetsToMenu(Handle menu, - int source_client, - bool in_game_only=true, - bool alive_only=false); + int source_client, + bool in_game_only=true, + bool alive_only=false); /** * Adds targets to an admin menu. @@ -104,10 +104,10 @@ native int AddTargetsToMenu(Handle menu, * Each client is displayed as: name (userid) * Each item contains the userid as a string for its info. * - * @param menu Menu Handle. - * @param source_client Source client, or 0 to ignore immunity. - * @param flags COMMAND_FILTER flags from commandfilters.inc. - * @return Number of clients added. + * @param menu Menu Handle. + * @param source_client Source client, or 0 to ignore immunity. + * @param flags COMMAND_FILTER flags from commandfilters.inc. + * @return Number of clients added. */ native int AddTargetsToMenu2(Handle menu, int source_client, int flags); @@ -115,9 +115,9 @@ native int AddTargetsToMenu2(Handle menu, int source_client, int flags); * Re-displays the admin menu to a client after selecting an item. * Auto-aborts if the Handle is invalid. * - * @param topmenu TopMenu Handle. - * @param client Client index. - * @return True on success, false on failure. + * @param topmenu TopMenu Handle. + * @param client Client index. + * @return True on success, false on failure. */ stock bool RedisplayAdminMenu(Handle topmenu, int client) { diff --git a/addons/sourcemod/scripting/include/adt_array.inc b/addons/sourcemod/scripting/include/adt_array.inc index b9fb0db..c8fd919 100644 --- a/addons/sourcemod/scripting/include/adt_array.inc +++ b/addons/sourcemod/scripting/include/adt_array.inc @@ -39,13 +39,16 @@ * Given a maximum string size (including the null terminator), * returns the number of cells required to fit that string. * - * @param size Number of bytes. - * @return Minimum number of cells required to fit the byte count. + * @param size Number of bytes. + * @return Minimum number of cells required to fit the byte count. */ stock int ByteCountToCells(int size) { if (!size) + { return 1; + } + return (size + 3) / 4; } @@ -92,7 +95,6 @@ methodmap ArrayList < Handle { // @param value Value to push. // @return Index of the new entry. // @error Invalid Handle or out of memory. - // public native int Push(any value); // Pushes a string onto the end of an array, truncating it if it is too big. @@ -203,11 +205,23 @@ methodmap ArrayList < Handle { // value cannot be located, -1 will be returned. // // @param item Value to search for - // @param block Optionally which block to search in + // @param block Optionally which block to search in // @return Array index, or -1 on failure // @error Invalid block index public native int FindValue(any item, int block=0); + // Sort an ADT Array. Specify the type as Integer, Float, or String. + // + // @param order Sort order to use, same as other sorts. + // @param type Data type stored in the ADT Array + public native void Sort(SortOrder order, SortType type); + + // Custom sorts an ADT Array. You must pass in a comparison function. + // + // @param sortfunc Sort comparison function to use + // @param hndl Optional Handle to pass through the comparison calls. + public native void SortCustom(SortFuncADTArray sortfunc, Handle hndl=INVALID_HANDLE); + // Retrieve the size of the array. property int Length { public native get(); @@ -228,20 +242,20 @@ methodmap ArrayList < Handle { * The "blocksize" determines how many cells each array slot has; it cannot * be changed after creation. * - * @param blocksize The number of cells each member of the array can - * hold. For example, 32 cells is equivalent to: - * new Array[X][32] - * @param startsize Initial size of the array. Note that data will - * NOT be auto-initialized. - * @return New Handle to the array object. + * @param blocksize The number of cells each member of the array can + * hold. For example, 32 cells is equivalent to: + * new Array[X][32] + * @param startsize Initial size of the array. Note that data will + * NOT be auto-initialized. + * @return New Handle to the array object. */ native ArrayList CreateArray(int blocksize=1, int startsize=0); /** * Clears an array of all entries. This is the same as ResizeArray(0). * - * @param array Array Handle. - * @error Invalid Handle. + * @param array Array Handle. + * @error Invalid Handle. */ native void ClearArray(Handle array); @@ -250,9 +264,9 @@ native void ClearArray(Handle array); * be confused with CloneHandle. This is a completely new handle with the same data but * no relation to the original. You MUST close it. * - * @param array Array handle to be cloned - * @return New handle to the cloned array object - * @error Invalid Handle + * @param array Array handle to be cloned + * @return New handle to the cloned array object + * @error Invalid Handle */ native Handle CloneArray(Handle array); @@ -261,18 +275,18 @@ native Handle CloneArray(Handle array); * the array is truncated. If the size is larger than the current size, * the data at the additional indexes will not be initialized. * - * @param array Array Handle. - * @param newsize New size. - * @error Invalid Handle or out of memory. + * @param array Array Handle. + * @param newsize New size. + * @error Invalid Handle or out of memory. */ native void ResizeArray(Handle array, int newsize); /** * Returns the array size. * - * @param array Array Handle. - * @return Number of elements in the array. - * @error Invalid Handle. + * @param array Array Handle. + * @return Number of elements in the array. + * @error Invalid Handle. */ native int GetArraySize(Handle array); @@ -282,10 +296,10 @@ native int GetArraySize(Handle array); * This may safely be used even if the array has a blocksize * greater than 1. * - * @param array Array Handle. - * @param value Value to push. - * @return Index of the new entry. - * @error Invalid Handle or out of memory. + * @param array Array Handle. + * @param value Value to push. + * @return Index of the new entry. + * @error Invalid Handle or out of memory. */ native int PushArrayCell(Handle array, any value); @@ -293,10 +307,10 @@ native int PushArrayCell(Handle array, any value); * Pushes a string onto the end of an array, truncating it * if it is too big. * - * @param array Array Handle. - * @param value String to push. - * @return Index of the new entry. - * @error Invalid Handle or out of memory. + * @param array Array Handle. + * @param value String to push. + * @return Index of the new entry. + * @error Invalid Handle or out of memory. */ native int PushArrayString(Handle array, const char[] value); @@ -305,88 +319,88 @@ native int PushArrayString(Handle array, const char[] value); * are pushed as a block (i.e. the entire array sits at the index), * rather than pushing each cell individually. * - * @param array Array Handle. - * @param values Block of values to copy. - * @param size If not set, the number of elements copied from the array - * will be equal to the blocksize. If set higher than the - * blocksize, the operation will be truncated. - * @return Index of the new entry. - * @error Invalid Handle or out of memory. + * @param array Array Handle. + * @param values Block of values to copy. + * @param size If not set, the number of elements copied from the array + * will be equal to the blocksize. If set higher than the + * blocksize, the operation will be truncated. + * @return Index of the new entry. + * @error Invalid Handle or out of memory. */ native int PushArrayArray(Handle array, const any[] values, int size=-1); /** * Retrieves a cell value from an array. * - * @param array Array Handle. - * @param index Index in the array. - * @param block Optionally specify which block to read from - * (useful if the blocksize > 0). - * @param asChar Optionally read as a byte instead of a cell. - * @return Value read. - * @error Invalid Handle, invalid index, or invalid block. + * @param array Array Handle. + * @param index Index in the array. + * @param block Optionally specify which block to read from + * (useful if the blocksize > 0). + * @param asChar Optionally read as a byte instead of a cell. + * @return Value read. + * @error Invalid Handle, invalid index, or invalid block. */ native any GetArrayCell(Handle array, int index, int block=0, bool asChar=false); /** * Retrieves a string value from an array. * - * @param array Array Handle. - * @param index Index in the array. - * @param buffer Buffer to copy to. - * @param maxlength Maximum size of the buffer. - * @return Number of characters copied. - * @error Invalid Handle or invalid index. + * @param array Array Handle. + * @param index Index in the array. + * @param buffer Buffer to copy to. + * @param maxlength Maximum size of the buffer. + * @return Number of characters copied. + * @error Invalid Handle or invalid index. */ native int GetArrayString(Handle array, int index, char[] buffer, int maxlength); /** * Retrieves an array of cells from an array. * - * @param array Array Handle. - * @param index Index in the array. - * @param buffer Buffer to store the array in. - * @param size If not set, assumes the buffer size is equal to the - * blocksize. Otherwise, the size passed is used. - * @return Number of cells copied. - * @error Invalid Handle or invalid index. + * @param array Array Handle. + * @param index Index in the array. + * @param buffer Buffer to store the array in. + * @param size If not set, assumes the buffer size is equal to the + * blocksize. Otherwise, the size passed is used. + * @return Number of cells copied. + * @error Invalid Handle or invalid index. */ native int GetArrayArray(Handle array, int index, any[] buffer, int size=-1); /** * Sets a cell value in an array. * - * @param array Array Handle. - * @param index Index in the array. - * @param value Cell value to set. - * @param block Optionally specify which block to write to - * (useful if the blocksize > 0). - * @param asChar Optionally set as a byte instead of a cell. - * @error Invalid Handle, invalid index, or invalid block. + * @param array Array Handle. + * @param index Index in the array. + * @param value Cell value to set. + * @param block Optionally specify which block to write to + * (useful if the blocksize > 0). + * @param asChar Optionally set as a byte instead of a cell. + * @error Invalid Handle, invalid index, or invalid block. */ native void SetArrayCell(Handle array, int index, any value, int block=0, bool asChar=false); /** * Sets a string value in an array. * - * @param array Array Handle. - * @param index Index in the array. - * @param value String value to set. - * @return Number of characters copied. - * @error Invalid Handle or invalid index. + * @param array Array Handle. + * @param index Index in the array. + * @param value String value to set. + * @return Number of characters copied. + * @error Invalid Handle or invalid index. */ native int SetArrayString(Handle array, int index, const char[] value); /** * Sets an array of cells in an array. * - * @param array Array Handle. - * @param index Index in the array. - * @param values Array to copy. - * @param size If not set, assumes the buffer size is equal to the - * blocksize. Otherwise, the size passed is used. - * @return Number of cells copied. - * @error Invalid Handle or invalid index. + * @param array Array Handle. + * @param index Index in the array. + * @param values Array to copy. + * @param size If not set, assumes the buffer size is equal to the + * blocksize. Otherwise, the size passed is used. + * @return Number of cells copied. + * @error Invalid Handle or invalid index. */ native int SetArrayArray(Handle array, int index, const any[] values, int size=-1); @@ -395,9 +409,9 @@ native int SetArrayArray(Handle array, int index, const any[] values, int size=- * index are shifted up by one, and the given index is then "free." * After shifting, the contents of the given index is undefined. * - * @param array Array Handle. - * @param index Index in the array to shift up from. - * @error Invalid Handle or invalid index. + * @param array Array Handle. + * @param index Index in the array to shift up from. + * @error Invalid Handle or invalid index. */ native void ShiftArrayUp(Handle array, int index); @@ -406,19 +420,19 @@ native void ShiftArrayUp(Handle array, int index); * on. For example, if item 8 of 10 is removed, the last 3 items will then be * (6,7,8) instead of (7,8,9), and all indexes before 8 will remain unchanged. * - * @param array Array Handle. - * @param index Index in the array to remove at. - * @error Invalid Handle or invalid index. + * @param array Array Handle. + * @param index Index in the array to remove at. + * @error Invalid Handle or invalid index. */ native void RemoveFromArray(Handle array, int index); /** * Swaps two items in the array. * - * @param array Array Handle. - * @param index1 First index. - * @param index2 Second index. - * @error Invalid Handle or invalid index. + * @param array Array Handle. + * @param index1 First index. + * @param index2 Second index. + * @error Invalid Handle or invalid index. */ native void SwapArrayItems(Handle array, int index1, int index2); @@ -426,10 +440,10 @@ native void SwapArrayItems(Handle array, int index1, int index2); * Returns the index for the first occurrence of the provided string. If the string * cannot be located, -1 will be returned. * - * @param array Array Handle. - * @param item String to search for - * @return Array index, or -1 on failure - * @error Invalid Handle + * @param array Array Handle. + * @param item String to search for + * @return Array index, or -1 on failure + * @error Invalid Handle */ native int FindStringInArray(Handle array, const char[] item); @@ -437,19 +451,19 @@ native int FindStringInArray(Handle array, const char[] item); * Returns the index for the first occurrence of the provided value. If the value * cannot be located, -1 will be returned. * - * @param array Array Handle. - * @param item Value to search for - * @param block Optionally which block to search in - * @return Array index, or -1 on failure - * @error Invalid Handle or invalid block + * @param array Array Handle. + * @param item Value to search for + * @param block Optionally which block to search in + * @return Array index, or -1 on failure + * @error Invalid Handle or invalid block */ native int FindValueInArray(Handle array, any item, int block=0); /** * Returns the blocksize the array was created with. * - * @param array Array Handle. - * @return The blocksize of the array. - * @error Invalid Handle + * @param array Array Handle. + * @return The blocksize of the array. + * @error Invalid Handle */ native int GetArrayBlockSize(Handle array); diff --git a/addons/sourcemod/scripting/include/adt_stack.inc b/addons/sourcemod/scripting/include/adt_stack.inc index 4e39316..9be8857 100644 --- a/addons/sourcemod/scripting/include/adt_stack.inc +++ b/addons/sourcemod/scripting/include/adt_stack.inc @@ -129,10 +129,10 @@ methodmap ArrayStack < Handle * The "blocksize" determines how many cells each slot has; it cannot * be changed after creation. * - * @param blocksize The number of cells each entry in the stack can - * hold. For example, 32 cells is equivalent to: - * new Array[X][32] - * @return New stack Handle. + * @param blocksize The number of cells each entry in the stack can + * hold. For example, 32 cells is equivalent to: + * new Array[X][32] + * @return New stack Handle. */ native ArrayStack CreateStack(int blocksize=1); @@ -142,9 +142,9 @@ native ArrayStack CreateStack(int blocksize=1); * This may safely be used even if the stack has a blocksize * greater than 1. * - * @param stack Stack Handle. - * @param value Value to push. - * @error Invalid Handle or out of memory. + * @param stack Stack Handle. + * @param value Value to push. + * @error Invalid Handle or out of memory. */ native void PushStackCell(Handle stack, any value); @@ -152,9 +152,9 @@ native void PushStackCell(Handle stack, any value); * Pushes a copy of a string onto the end of a stack, truncating it if it is * too big. * - * @param stack Stack Handle. - * @param value String to push. - * @error Invalid Handle or out of memory. + * @param stack Stack Handle. + * @param value String to push. + * @error Invalid Handle or out of memory. */ native void PushStackString(Handle stack, const char[] value); @@ -163,66 +163,66 @@ native void PushStackString(Handle stack, const char[] value); * are pushed as a block (i.e. the entire array takes up one stack slot), * rather than pushing each cell individually. * - * @param stack Stack Handle. - * @param values Block of values to copy. - * @param size If not set, the number of elements copied from the array - * will be equal to the blocksize. If set higher than the - * blocksize, the operation will be truncated. - * @error Invalid Handle or out of memory. + * @param stack Stack Handle. + * @param values Block of values to copy. + * @param size If not set, the number of elements copied from the array + * will be equal to the blocksize. If set higher than the + * blocksize, the operation will be truncated. + * @error Invalid Handle or out of memory. */ native void PushStackArray(Handle stack, const any[] values, int size=-1); /** * Pops a cell value from a stack. * - * @param stack Stack Handle. - * @param value Variable to store the value. - * @param block Optionally specify which block to read from - * (useful if the blocksize > 0). - * @param asChar Optionally read as a byte instead of a cell. - * @return True on success, false if the stack is empty. - * @error Invalid Handle. + * @param stack Stack Handle. + * @param value Variable to store the value. + * @param block Optionally specify which block to read from + * (useful if the blocksize > 0). + * @param asChar Optionally read as a byte instead of a cell. + * @return True on success, false if the stack is empty. + * @error Invalid Handle. */ native bool PopStackCell(Handle stack, any &value, int block=0, bool asChar=false); /** * Pops a string value from a stack. * - * @param stack Stack Handle. - * @param buffer Buffer to store string. - * @param maxlength Maximum size of the buffer. - * @return True on success, false if the stack is empty. - * @error Invalid Handle. + * @param stack Stack Handle. + * @param buffer Buffer to store string. + * @param maxlength Maximum size of the buffer. + * @return True on success, false if the stack is empty. + * @error Invalid Handle. */ native bool PopStackString(Handle stack, char[] buffer, int maxlength, int &written=0); /** * Pops an array of cells from a stack. * - * @param stack Stack Handle. - * @param buffer Buffer to store the array in. - * @param size If not set, assumes the buffer size is equal to the - * blocksize. Otherwise, the size passed is used. - * @return True on success, false if the stack is empty. - * @error Invalid Handle. + * @param stack Stack Handle. + * @param buffer Buffer to store the array in. + * @param size If not set, assumes the buffer size is equal to the + * blocksize. Otherwise, the size passed is used. + * @return True on success, false if the stack is empty. + * @error Invalid Handle. */ native bool PopStackArray(Handle stack, any[] buffer, int size=-1); /** * Checks if a stack is empty. * - * @param stack Stack Handle. - * @return True if empty, false if not empty. - * @error Invalid Handle. + * @param stack Stack Handle. + * @return True if empty, false if not empty. + * @error Invalid Handle. */ native bool IsStackEmpty(Handle stack); /** * Pops a value off a stack, ignoring it completely. * - * @param stack Stack Handle. - * @return True if something was popped, false otherwise. - * @error Invalid Handle. + * @param stack Stack Handle. + * @return True if something was popped, false otherwise. + * @error Invalid Handle. */ stock bool PopStack(Handle stack) { @@ -233,8 +233,8 @@ stock bool PopStack(Handle stack) /** * Returns the blocksize the stack was created with. * - * @param stack Stack Handle. - * @return The blocksize of the stack. - * @error Invalid Handle + * @param stack Stack Handle. + * @return The blocksize of the stack. + * @error Invalid Handle */ native int GetStackBlockSize(Handle stack); diff --git a/addons/sourcemod/scripting/include/adt_trie.inc b/addons/sourcemod/scripting/include/adt_trie.inc index 337fe1f..2d262c4 100644 --- a/addons/sourcemod/scripting/include/adt_trie.inc +++ b/addons/sourcemod/scripting/include/adt_trie.inc @@ -124,9 +124,11 @@ methodmap StringMap < Handle } }; -// A StringMapSnapshot is created via StringMap.Snapshot(). It captures the -// keys on a map so they can be read. Snapshots must be freed with delete or -// CloseHandle(). +/** + * A StringMapSnapshot is created via StringMap.Snapshot(). It captures the + * keys on a map so they can be read. Snapshots must be freed with delete or + * CloseHandle(). + */ methodmap StringMapSnapshot < Handle { // Returns the number of keys in the map snapshot. @@ -164,111 +166,111 @@ methodmap StringMapSnapshot < Handle * been internally replaced with hash tables, which have O(1) insertion time * instead of O(n). * - * @return New Map Handle, which must be freed via CloseHandle(). + * @return New Map Handle, which must be freed via CloseHandle(). */ native StringMap CreateTrie(); /** * Sets a value in a hash map, either inserting a new entry or replacing an old one. * - * @param map Map Handle. - * @param key Key string. - * @param value Value to store at this key. - * @param replace If false, operation will fail if the key is already set. - * @return True on success, false on failure. - * @error Invalid Handle. + * @param map Map Handle. + * @param key Key string. + * @param value Value to store at this key. + * @param replace If false, operation will fail if the key is already set. + * @return True on success, false on failure. + * @error Invalid Handle. */ native bool SetTrieValue(Handle map, const char[] key, any value, bool replace=true); /** * Sets an array value in a Map, either inserting a new entry or replacing an old one. * - * @param map Map Handle. - * @param key Key string. - * @param array Array to store. - * @param num_items Number of items in the array. - * @param replace If false, operation will fail if the key is already set. - * @return True on success, false on failure. - * @error Invalid Handle. + * @param map Map Handle. + * @param key Key string. + * @param array Array to store. + * @param num_items Number of items in the array. + * @param replace If false, operation will fail if the key is already set. + * @return True on success, false on failure. + * @error Invalid Handle. */ native bool SetTrieArray(Handle map, const char[] key, const any[] array, int num_items, bool replace=true); /** * Sets a string value in a Map, either inserting a new entry or replacing an old one. * - * @param map Map Handle. - * @param key Key string. - * @param value String to store. - * @param replace If false, operation will fail if the key is already set. - * @return True on success, false on failure. - * @error Invalid Handle. + * @param map Map Handle. + * @param key Key string. + * @param value String to store. + * @param replace If false, operation will fail if the key is already set. + * @return True on success, false on failure. + * @error Invalid Handle. */ native bool SetTrieString(Handle map, const char[] key, const char[] value, bool replace=true); /** * Retrieves a value in a Map. * - * @param map Map Handle. - * @param key Key string. - * @param value Variable to store value. - * @return True on success. False if the key is not set, or the key is set - * as an array or string (not a value). - * @error Invalid Handle. + * @param map Map Handle. + * @param key Key string. + * @param value Variable to store value. + * @return True on success. False if the key is not set, or the key is set + * as an array or string (not a value). + * @error Invalid Handle. */ native bool GetTrieValue(Handle map, const char[] key, any &value); /** * Retrieves an array in a Map. * - * @param map Map Handle. - * @param key Key string. - * @param array Buffer to store array. - * @param max_size Maximum size of array buffer. - * @param size Optional parameter to store the number of elements written to the buffer. - * @return True on success. False if the key is not set, or the key is set - * as a value or string (not an array). - * @error Invalid Handle. + * @param map Map Handle. + * @param key Key string. + * @param array Buffer to store array. + * @param max_size Maximum size of array buffer. + * @param size Optional parameter to store the number of elements written to the buffer. + * @return True on success. False if the key is not set, or the key is set + * as a value or string (not an array). + * @error Invalid Handle. */ native bool GetTrieArray(Handle map, const char[] key, any[] array, int max_size, int &size=0); /** * Retrieves a string in a Map. * - * @param map Map Handle. - * @param key Key string. - * @param value Buffer to store value. - * @param max_size Maximum size of string buffer. - * @param size Optional parameter to store the number of bytes written to the buffer. - * @return True on success. False if the key is not set, or the key is set - * as a value or array (not a string). - * @error Invalid Handle. + * @param map Map Handle. + * @param key Key string. + * @param value Buffer to store value. + * @param max_size Maximum size of string buffer. + * @param size Optional parameter to store the number of bytes written to the buffer. + * @return True on success. False if the key is not set, or the key is set + * as a value or array (not a string). + * @error Invalid Handle. */ native bool GetTrieString(Handle map, const char[] key, char[] value, int max_size, int &size=0); /** * Removes a key entry from a Map. * - * @param map Map Handle. - * @param key Key string. - * @return True on success, false if the value was never set. - * @error Invalid Handle. + * @param map Map Handle. + * @param key Key string. + * @return True on success, false if the value was never set. + * @error Invalid Handle. */ native bool RemoveFromTrie(Handle map, const char[] key); /** * Clears all entries from a Map. * - * @param map Map Handle. - * @error Invalid Handle. + * @param map Map Handle. + * @error Invalid Handle. */ native void ClearTrie(Handle map); /** * Retrieves the number of elements in a map. * - * @param map Map Handle. - * @return Number of elements in the trie. - * @error Invalid Handle. + * @param map Map Handle. + * @return Number of elements in the trie. + * @error Invalid Handle. */ native int GetTrieSize(Handle map); @@ -276,9 +278,9 @@ native int GetTrieSize(Handle map); * Creates a snapshot of all keys in the map. If the map is changed after this * call, the changes are not reflected in the snapshot. Keys are not sorted. * - * @param map Map Handle. - * @return New Map Snapshot Handle, which must be closed via CloseHandle(). - * @error Invalid Handle. + * @param map Map Handle. + * @return New Map Snapshot Handle, which must be closed via CloseHandle(). + * @error Invalid Handle. */ native Handle CreateTrieSnapshot(Handle map); @@ -287,9 +289,9 @@ native Handle CreateTrieSnapshot(Handle map); * different from the size of the map, since the map can change after the * snapshot of its keys was taken. * - * @param snapshot Map snapshot. - * @return Number of keys. - * @error Invalid Handle. + * @param snapshot Map snapshot. + * @return Number of keys. + * @error Invalid Handle. */ native int TrieSnapshotLength(Handle snapshot); @@ -297,21 +299,21 @@ native int TrieSnapshotLength(Handle snapshot); * Returns the buffer size required to store a given key. That is, it returns * the length of the key plus one. * - * @param snapshot Map snapshot. - * @param index Key index (starting from 0). - * @return Buffer size required to store the key string. - * @error Invalid Handle or index out of range. + * @param snapshot Map snapshot. + * @param index Key index (starting from 0). + * @return Buffer size required to store the key string. + * @error Invalid Handle or index out of range. */ native int TrieSnapshotKeyBufferSize(Handle snapshot, int index); /** * Retrieves the key string of a given key in a map snapshot. * - * @param snapshot Map snapshot. - * @param index Key index (starting from 0). - * @param buffer String buffer. - * @param maxlength Maximum buffer length. - * @return Number of bytes written to the buffer. - * @error Invalid Handle or index out of range. + * @param snapshot Map snapshot. + * @param index Key index (starting from 0). + * @param buffer String buffer. + * @param maxlength Maximum buffer length. + * @return Number of bytes written to the buffer. + * @error Invalid Handle or index out of range. */ native int GetTrieSnapshotKey(Handle snapshot, int index, char[] buffer, int maxlength); diff --git a/addons/sourcemod/scripting/include/banning.inc b/addons/sourcemod/scripting/include/banning.inc index ad8c1bc..e22f641 100644 --- a/addons/sourcemod/scripting/include/banning.inc +++ b/addons/sourcemod/scripting/include/banning.inc @@ -35,24 +35,24 @@ #endif #define _banning_included -#define BANFLAG_AUTO (1<<0) /**< Auto-detects whether to ban by steamid or IP */ -#define BANFLAG_IP (1<<1) /**< Always ban by IP address */ -#define BANFLAG_AUTHID (1<<2) /**< Always ban by authstring (for BanIdentity) if possible */ -#define BANFLAG_NOKICK (1<<3) /**< Does not kick the client */ +#define BANFLAG_AUTO (1<<0) /**< Auto-detects whether to ban by steamid or IP */ +#define BANFLAG_IP (1<<1) /**< Always ban by IP address */ +#define BANFLAG_AUTHID (1<<2) /**< Always ban by authstring (for BanIdentity) if possible */ +#define BANFLAG_NOKICK (1<<3) /**< Does not kick the client */ /** * Called for calls to BanClient() with a non-empty command. * - * @param client Client being banned. - * @param time Time the client is being banned for (0 = permanent). - * @param flags One if AUTHID or IP will be enabled. If AUTO is also - * enabled, it means Core autodetected which to use. - * @param reason Reason passed via BanClient(). - * @param kick_message Kick message passed via BanClient(). - * @param command Command string to identify the ban source. - * @param source Source value passed via BanClient(). - * @return Plugin_Handled to block the actual server banning. - * Kicking will still occur. + * @param client Client being banned. + * @param time Time the client is being banned for (0 = permanent). + * @param flags One if AUTHID or IP will be enabled. If AUTO is also + * enabled, it means Core autodetected which to use. + * @param reason Reason passed via BanClient(). + * @param kick_message Kick message passed via BanClient(). + * @param command Command string to identify the ban source. + * @param source Source value passed via BanClient(). + * @return Plugin_Handled to block the actual server banning. + * Kicking will still occur. */ forward Action OnBanClient(int client, int time, @@ -65,13 +65,13 @@ forward Action OnBanClient(int client, /** * Called for calls to BanIdentity() with a non-empty command. * - * @param identity Identity string being banned (authstring or ip). - * @param time Time the client is being banned for (0 = permanent). - * @param flags Ban flags (only IP or AUTHID are valid here). - * @param reason Reason passed via BanIdentity(). - * @param command Command string to identify the ban source. - * @param source Source value passed via BanIdentity(). - * @return Plugin_Handled to block the actual server banning. + * @param identity Identity string being banned (authstring or ip). + * @param time Time the client is being banned for (0 = permanent). + * @param flags Ban flags (only IP or AUTHID are valid here). + * @param reason Reason passed via BanIdentity(). + * @param command Command string to identify the ban source. + * @param source Source value passed via BanIdentity(). + * @return Plugin_Handled to block the actual server banning. */ forward Action OnBanIdentity(const char[] identity, int time, @@ -83,11 +83,11 @@ forward Action OnBanIdentity(const char[] identity, /** * Called for calls to RemoveBan() with a non-empty command. * - * @param identity Identity string being banned (authstring or ip). - * @param flags Ban flags (only IP or AUTHID are valid here). - * @param command Command string to identify the ban source. - * @param source Source value passed via BanIdentity(). - * @return Plugin_Handled to block the actual unbanning. + * @param identity Identity string being banned (authstring or ip). + * @param flags Ban flags (only IP or AUTHID are valid here). + * @param command Command string to identify the ban source. + * @param source Source value passed via BanIdentity(). + * @return Plugin_Handled to block the actual unbanning. */ forward Action OnRemoveBan(const char[] identity, int flags, @@ -97,19 +97,19 @@ forward Action OnRemoveBan(const char[] identity, /** * Bans a client. * - * @param client Client being banned. - * @param time Time (in minutes) to ban (0 = permanent). - * @param flags Flags for controlling the ban mechanism. If AUTHID - * is set and no AUTHID is available, the ban will fail - * unless AUTO is also flagged. - * @param reason Reason to ban the client for. - * @param kick_message Message to display to the user when kicking. - * @param command Command string to identify the source. If this is left - * empty, then the OnBanClient forward will not be called. - * @param source A source value that could be interpreted as a player - * index of any sort (not actually checked by Core). - * @return True on success, false on failure. - * @error Invalid client index or client not in game. + * @param client Client being banned. + * @param time Time (in minutes) to ban (0 = permanent). + * @param flags Flags for controlling the ban mechanism. If AUTHID + * is set and no AUTHID is available, the ban will fail + * unless AUTO is also flagged. + * @param reason Reason to ban the client for. + * @param kick_message Message to display to the user when kicking. + * @param command Command string to identify the source. If this is left + * empty, then the OnBanClient forward will not be called. + * @param source A source value that could be interpreted as a player + * index of any sort (not actually checked by Core). + * @return True on success, false on failure. + * @error Invalid client index or client not in game. */ native bool BanClient(int client, int time, @@ -122,15 +122,15 @@ native bool BanClient(int client, /** * Bans an identity (either an IP address or auth string). * - * @param identity String to ban (ip or authstring). - * @param time Time to ban for (0 = permanent). - * @param flags Flags (only IP and AUTHID are valid flags here). - * @param reason Ban reason string. - * @param command Command string to identify the source. If this is left - * empty, then the OnBanIdentity forward will not be called. - * @param source A source value that could be interpreted as a player - * index of any sort (not actually checked by Core). - * @return True on success, false on failure. + * @param identity String to ban (ip or authstring). + * @param time Time to ban for (0 = permanent). + * @param flags Flags (only IP and AUTHID are valid flags here). + * @param reason Ban reason string. + * @param command Command string to identify the source. If this is left + * empty, then the OnBanIdentity forward will not be called. + * @param source A source value that could be interpreted as a player + * index of any sort (not actually checked by Core). + * @return True on success, false on failure. */ native bool BanIdentity(const char[] identity, int time, @@ -142,13 +142,13 @@ native bool BanIdentity(const char[] identity, /** * Removes a ban that was written to the server (either in memory or on disk). * - * @param identity String to unban (ip or authstring). - * @param flags Flags (only IP and AUTHID are valid flags here). - * @param command Command string to identify the source. If this is left - * empty, then OnRemoveBan will not be called. - * @param source A source value that could be interpreted as a player - * index of any sort (not actually checked by Core). - * @return True on success, false on failure. + * @param identity String to unban (ip or authstring). + * @param flags Flags (only IP and AUTHID are valid flags here). + * @param command Command string to identify the source. If this is left + * empty, then OnRemoveBan will not be called. + * @param source A source value that could be interpreted as a player + * index of any sort (not actually checked by Core). + * @return True on success, false on failure. */ native bool RemoveBan(const char[] identity, int flags, diff --git a/addons/sourcemod/scripting/include/basecomm.inc b/addons/sourcemod/scripting/include/basecomm.inc index 7e5ee2c..7b7a4c7 100644 --- a/addons/sourcemod/scripting/include/basecomm.inc +++ b/addons/sourcemod/scripting/include/basecomm.inc @@ -38,50 +38,50 @@ /** * Called when a client is muted or unmuted * - * @param client Client index - * @param muteState True if client was muted, false otherwise + * @param client Client index + * @param muteState True if client was muted, false otherwise */ - forward void BaseComm_OnClientMute(int client, bool muteState); +forward void BaseComm_OnClientMute(int client, bool muteState); /** * Called when a client is gagged or ungagged * - * @param client Client index - * @param gagState True if client was gaged, false otherwise + * @param client Client index + * @param gagState True if client was gaged, false otherwise */ - forward void BaseComm_OnClientGag(int client, bool gagState); +forward void BaseComm_OnClientGag(int client, bool gagState); /** * Returns whether or not a client is gagged * - * @param client Client index. - * @return True if client is gagged, false otherwise. + * @param client Client index. + * @return True if client is gagged, false otherwise. */ native bool BaseComm_IsClientGagged(int client); /** * Returns whether or not a client is muted * - * @param client Client index. - * @return True if client is muted, false otherwise. + * @param client Client index. + * @return True if client is muted, false otherwise. */ native bool BaseComm_IsClientMuted(int client); /** * Sets a client's gag state * - * @param client Client index. - * @param gagState True to gag client, false to ungag. - * @return True if this caused a change in gag state, false otherwise. + * @param client Client index. + * @param gagState True to gag client, false to ungag. + * @return True if this caused a change in gag state, false otherwise. */ native bool BaseComm_SetClientGag(int client, bool gagState); /** * Sets a client's mute state * - * @param client Client index. - * @param muteState True to mute client, false to unmute. - * @return True if this caused a change in mute state, false otherwise. + * @param client Client index. + * @param muteState True to mute client, false to unmute. + * @return True if this caused a change in mute state, false otherwise. */ native bool BaseComm_SetClientMute(int client, bool muteState); diff --git a/addons/sourcemod/scripting/include/bitbuffer.inc b/addons/sourcemod/scripting/include/bitbuffer.inc index 60a3fe9..635958b 100644 --- a/addons/sourcemod/scripting/include/bitbuffer.inc +++ b/addons/sourcemod/scripting/include/bitbuffer.inc @@ -200,72 +200,72 @@ methodmap BfRead < Handle /** * Writes a single bit to a writable bitbuffer (bf_write). * - * @param bf bf_write handle to write to. - * @param bit Bit to write (true for 1, false for 0). - * @error Invalid or incorrect Handle. + * @param bf bf_write handle to write to. + * @param bit Bit to write (true for 1, false for 0). + * @error Invalid or incorrect Handle. */ native void BfWriteBool(Handle bf, bool bit); /** * Writes a byte to a writable bitbuffer (bf_write). * - * @param bf bf_write handle to write to. - * @param byte Byte to write (value will be written as 8bit). - * @error Invalid or incorrect Handle. + * @param bf bf_write handle to write to. + * @param byte Byte to write (value will be written as 8bit). + * @error Invalid or incorrect Handle. */ native void BfWriteByte(Handle bf, int byte); /** * Writes a byte to a writable bitbuffer (bf_write). * - * @param bf bf_write handle to write to. - * @param chr Character to write. - * @error Invalid or incorrect Handle. + * @param bf bf_write handle to write to. + * @param chr Character to write. + * @error Invalid or incorrect Handle. */ native void BfWriteChar(Handle bf, int chr); /** * Writes a 16bit integer to a writable bitbuffer (bf_write). * - * @param bf bf_write handle to write to. - * @param num Integer to write (value will be written as 16bit). - * @error Invalid or incorrect Handle. + * @param bf bf_write handle to write to. + * @param num Integer to write (value will be written as 16bit). + * @error Invalid or incorrect Handle. */ native void BfWriteShort(Handle bf, int num); /** * Writes a 16bit unsigned integer to a writable bitbuffer (bf_write). * - * @param bf bf_write handle to write to. - * @param num Integer to write (value will be written as 16bit). - * @error Invalid or incorrect Handle. + * @param bf bf_write handle to write to. + * @param num Integer to write (value will be written as 16bit). + * @error Invalid or incorrect Handle. */ native void BfWriteWord(Handle bf, int num); /** * Writes a normal integer to a writable bitbuffer (bf_write). * - * @param bf bf_write handle to write to. - * @param num Integer to write (value will be written as 32bit). - * @error Invalid or incorrect Handle. + * @param bf bf_write handle to write to. + * @param num Integer to write (value will be written as 32bit). + * @error Invalid or incorrect Handle. */ native void BfWriteNum(Handle bf, int num); /** * Writes a floating point number to a writable bitbuffer (bf_write). * - * @param bf bf_write handle to write to. - * @param num Number to write. - * @error Invalid or incorrect Handle. + * @param bf bf_write handle to write to. + * @param num Number to write. + * @error Invalid or incorrect Handle. */ native void BfWriteFloat(Handle bf, float num); /** * Writes a string to a writable bitbuffer (bf_write). * - * @param bf bf_write handle to write to. - * @param string Text string to write. - * @error Invalid or incorrect Handle. + * @param bf bf_write handle to write to. + * @param string Text string to write. + * @error Invalid or incorrect Handle. */ native void BfWriteString(Handle bf, const char[] string); @@ -273,134 +273,134 @@ native void BfWriteString(Handle bf, const char[] string); * Writes an entity to a writable bitbuffer (bf_write). * @note This is a wrapper around BfWriteShort(). * - * @param bf bf_write handle to write to. - * @param ent Entity index to write. - * @error Invalid or incorrect Handle, or invalid entity. + * @param bf bf_write handle to write to. + * @param ent Entity index to write. + * @error Invalid or incorrect Handle, or invalid entity. */ native void BfWriteEntity(Handle bf, int ent); /** * Writes a bit angle to a writable bitbuffer (bf_write). * - * @param bf bf_write handle to write to. - * @param angle Angle to write. - * @param numBits Optional number of bits to use. - * @error Invalid or incorrect Handle. + * @param bf bf_write handle to write to. + * @param angle Angle to write. + * @param numBits Optional number of bits to use. + * @error Invalid or incorrect Handle. */ native void BfWriteAngle(Handle bf, float angle, int numBits=8); /** * Writes a coordinate to a writable bitbuffer (bf_write). * - * @param bf bf_write handle to write to. - * @param coord Coordinate to write. - * @error Invalid or incorrect Handle. + * @param bf bf_write handle to write to. + * @param coord Coordinate to write. + * @error Invalid or incorrect Handle. */ native void BfWriteCoord(Handle bf, float coord); /** * Writes a 3D vector of coordinates to a writable bitbuffer (bf_write). * - * @param bf bf_write handle to write to. - * @param coord Coordinate array to write. - * @error Invalid or incorrect Handle. + * @param bf bf_write handle to write to. + * @param coord Coordinate array to write. + * @error Invalid or incorrect Handle. */ native void BfWriteVecCoord(Handle bf, float coord[3]); /** * Writes a 3D normal vector to a writable bitbuffer (bf_write). * - * @param bf bf_write handle to write to. - * @param vec Vector to write. - * @error Invalid or incorrect Handle. + * @param bf bf_write handle to write to. + * @param vec Vector to write. + * @error Invalid or incorrect Handle. */ native void BfWriteVecNormal(Handle bf, float vec[3]); /** * Writes a 3D angle vector to a writable bitbuffer (bf_write). * - * @param bf bf_write handle to write to. - * @param angles Angle vector to write. - * @error Invalid or incorrect Handle. + * @param bf bf_write handle to write to. + * @param angles Angle vector to write. + * @error Invalid or incorrect Handle. */ native void BfWriteAngles(Handle bf, float angles[3]); /** * Reads a single bit from a readable bitbuffer (bf_read). * - * @param bf bf_read handle to read from. - * @return Bit value read. - * @error Invalid or incorrect Handle. + * @param bf bf_read handle to read from. + * @return Bit value read. + * @error Invalid or incorrect Handle. */ native bool BfReadBool(Handle bf); /** * Reads a byte from a readable bitbuffer (bf_read). * - * @param bf bf_read handle to read from. - * @return Byte value read (read as 8bit). - * @error Invalid or incorrect Handle. + * @param bf bf_read handle to read from. + * @return Byte value read (read as 8bit). + * @error Invalid or incorrect Handle. */ native int BfReadByte(Handle bf); /** * Reads a character from a readable bitbuffer (bf_read). * - * @param bf bf_read handle to read from. - * @return Character value read. - * @error Invalid or incorrect Handle. + * @param bf bf_read handle to read from. + * @return Character value read. + * @error Invalid or incorrect Handle. */ native int BfReadChar(Handle bf); /** * Reads a 16bit integer from a readable bitbuffer (bf_read). * - * @param bf bf_read handle to read from. - * @return Integer value read (read as 16bit). - * @error Invalid or incorrect Handle. + * @param bf bf_read handle to read from. + * @return Integer value read (read as 16bit). + * @error Invalid or incorrect Handle. */ native int BfReadShort(Handle bf); /** * Reads a 16bit unsigned integer from a readable bitbuffer (bf_read). * - * @param bf bf_read handle to read from. - * @return Integer value read (read as 16bit). - * @error Invalid or incorrect Handle. + * @param bf bf_read handle to read from. + * @return Integer value read (read as 16bit). + * @error Invalid or incorrect Handle. */ native int BfReadWord(Handle bf); /** * Reads a normal integer to a readable bitbuffer (bf_read). * - * @param bf bf_read handle to read from. - * @return Integer value read (read as 32bit). - * @error Invalid or incorrect Handle. + * @param bf bf_read handle to read from. + * @return Integer value read (read as 32bit). + * @error Invalid or incorrect Handle. */ native int BfReadNum(Handle bf); /** * Reads a floating point number from a readable bitbuffer (bf_read). * - * @param bf bf_read handle to read from. - * @return Floating point value read. - * @error Invalid or incorrect Handle. + * @param bf bf_read handle to read from. + * @return Floating point value read. + * @error Invalid or incorrect Handle. */ native float BfReadFloat(Handle bf); /** * Reads a string from a readable bitbuffer (bf_read). * - * @param bf bf_read handle to read from. - * @param buffer Destination string buffer. - * @param maxlength Maximum length of output string buffer. - * @param line If true the buffer will be copied until it reaches a '\n' or a null terminator. - * @return Number of bytes written to the buffer. If the bitbuffer stream overflowed, - * that is, had no terminator before the end of the stream, then a negative - * number will be returned equal to the number of characters written to the - * buffer minus 1. The buffer will be null terminated regardless of the - * return value. - * @error Invalid or incorrect Handle. + * @param bf bf_read handle to read from. + * @param buffer Destination string buffer. + * @param maxlength Maximum length of output string buffer. + * @param line If true the buffer will be copied until it reaches a '\n' or a null terminator. + * @return Number of bytes written to the buffer. If the bitbuffer stream overflowed, + * that is, had no terminator before the end of the stream, then a negative + * number will be returned equal to the number of characters written to the + * buffer minus 1. The buffer will be null terminated regardless of the + * return value. + * @error Invalid or incorrect Handle. */ native int BfReadString(Handle bf, char[] buffer, int maxlength, bool line=false); @@ -408,63 +408,63 @@ native int BfReadString(Handle bf, char[] buffer, int maxlength, bool line=false * Reads an entity from a readable bitbuffer (bf_read). * @note This is a wrapper around BfReadShort(). * - * @param bf bf_read handle to read from. - * @return Entity index read. - * @error Invalid or incorrect Handle. + * @param bf bf_read handle to read from. + * @return Entity index read. + * @error Invalid or incorrect Handle. */ native int BfReadEntity(Handle bf); /** * Reads a bit angle from a readable bitbuffer (bf_read). * - * @param bf bf_read handle to read from. - * @param numBits Optional number of bits to use. - * @return Angle read. - * @error Invalid or incorrect Handle. + * @param bf bf_read handle to read from. + * @param numBits Optional number of bits to use. + * @return Angle read. + * @error Invalid or incorrect Handle. */ native float BfReadAngle(Handle bf, int numBits=8); /** * Reads a coordinate from a readable bitbuffer (bf_read). * - * @param bf bf_read handle to read from. - * @return Coordinate read. - * @error Invalid or incorrect Handle. + * @param bf bf_read handle to read from. + * @return Coordinate read. + * @error Invalid or incorrect Handle. */ native float BfReadCoord(Handle bf); /** * Reads a 3D vector of coordinates from a readable bitbuffer (bf_read). * - * @param bf bf_read handle to read from. - * @param coord Destination coordinate array. - * @error Invalid or incorrect Handle. + * @param bf bf_read handle to read from. + * @param coord Destination coordinate array. + * @error Invalid or incorrect Handle. */ native void BfReadVecCoord(Handle bf, float coord[3]); /** * Reads a 3D normal vector from a readable bitbuffer (bf_read). * - * @param bf bf_read handle to read from. - * @param vec Destination vector array. - * @error Invalid or incorrect Handle. + * @param bf bf_read handle to read from. + * @param vec Destination vector array. + * @error Invalid or incorrect Handle. */ native void BfReadVecNormal(Handle bf, float vec[3]); /** * Reads a 3D angle vector from a readable bitbuffer (bf_read). * - * @param bf bf_read handle to read from. - * @param angles Destination angle vector. - * @error Invalid or incorrect Handle. + * @param bf bf_read handle to read from. + * @param angles Destination angle vector. + * @error Invalid or incorrect Handle. */ native void BfReadAngles(Handle bf, float angles[3]); /** * Returns the number of bytes left in a readable bitbuffer (bf_read). * - * @param bf bf_read handle to read from. - * @return Number of bytes left unread. - * @error Invalid or incorrect Handle. + * @param bf bf_read handle to read from. + * @return Number of bytes left unread. + * @error Invalid or incorrect Handle. */ native int BfGetNumBytesLeft(Handle bf); diff --git a/addons/sourcemod/scripting/include/clientprefs.inc b/addons/sourcemod/scripting/include/clientprefs.inc index a5de7b0..218d033 100644 --- a/addons/sourcemod/scripting/include/clientprefs.inc +++ b/addons/sourcemod/scripting/include/clientprefs.inc @@ -40,9 +40,9 @@ */ enum CookieAccess { - CookieAccess_Public, /**< Visible and Changeable by users */ - CookieAccess_Protected, /**< Read only to users */ - CookieAccess_Private, /**< Completely hidden cookie */ + CookieAccess_Public, /**< Visible and Changeable by users */ + CookieAccess_Protected, /**< Read only to users */ + CookieAccess_Private /**< Completely hidden cookie */ }; /** @@ -50,10 +50,10 @@ enum CookieAccess */ enum CookieMenu { - CookieMenu_YesNo, /**< Yes/No menu with "yes"/"no" results saved into the cookie */ - CookieMenu_YesNo_Int, /**< Yes/No menu with 1/0 saved into the cookie */ - CookieMenu_OnOff, /**< On/Off menu with "on"/"off" results saved into the cookie */ - CookieMenu_OnOff_Int, /**< On/Off menu with 1/0 saved into the cookie */ + CookieMenu_YesNo, /**< Yes/No menu with "yes"/"no" results saved into the cookie */ + CookieMenu_YesNo_Int, /**< Yes/No menu with 1/0 saved into the cookie */ + CookieMenu_OnOff, /**< On/Off menu with "on"/"off" results saved into the cookie */ + CookieMenu_OnOff_Int /**< On/Off menu with 1/0 saved into the cookie */ }; enum CookieMenuAction @@ -71,9 +71,26 @@ enum CookieMenuAction * * INPUT : Client index and any data if available. */ - CookieMenuAction_SelectOption = 1, + CookieMenuAction_SelectOption = 1 }; +/** + * Cookie Menu Callback prototype + * + * @param client Client index. + * @param action CookieMenuAction being performed. + * @param info Info data passed. + * @param buffer Outbut buffer. + * @param maxlen Max length of the output buffer. + */ +typedef CookieMenuHandler = function void ( + int client, + CookieMenuAction action, + any info, + char[] buffer, + int maxlen +); + /** * Note: * @@ -82,18 +99,89 @@ enum CookieMenuAction * errors by the clientprefs extension. */ +methodmap Cookie < Handle { + // Creates a new Client preference cookie. + // + // Handles returned can be closed via CloseHandle() when + // no longer needed. + // + // @param name Name of the new preference cookie. + // @param description Optional description of the preference cookie. + // @param access What CookieAccess level to assign to this cookie. + // @return A handle to the newly created cookie. If the cookie already + // exists, a handle to it will still be returned. + // @error Cookie name is blank. + public native Cookie(const char[] name, const char[] description, CookieAccess access); + + // Searches for a Client preference cookie. + // + // Handles returned by Cookie.Find can be closed via CloseHandle() when + // no longer needed. + // + // @param name Name of cookie to find. + // @return A handle to the cookie if it is found. INVALID_HANDLE otherwise. + public static native Cookie Find(const char[] name); + + // Set the value of a Client preference cookie. + // + // @param client Client index. + // @param value String value to set. + // @error Invalid cookie handle or invalid client index. + public native void Set(int client, const char[] value); + + // Retrieve the value of a Client preference cookie. + // + // @param client Client index. + // @param buffer Copyback buffer for value. + // @param maxlen Maximum length of the buffer. + // @error Invalid cookie handle or invalid client index. + public native void Get(int client, char[] buffer, int maxlen); + + // Sets the value of a Client preference cookie based on an authID string. + // + // @param authID String Auth/STEAM ID of player to set. + // @param value String value to set. + // @error Invalid cookie handle. + public native void SetByAuthId(const char[] authID, const char[] value); + + // Add a new prefab item to the client cookie settings menu. + // + // Note: This handles everything automatically and does not require a callback + // + // @param type A CookieMenu prefab menu type. + // @param display Text to show on the menu. + // @param handler Optional handler callback for translations and output on selection + // @param info Info data to pass to the callback. + // @error Invalid cookie handle. + public native void SetPrefabMenu(CookieMenu type, const char[] display, CookieMenuHandler handler=INVALID_FUNCTION, any info=0); + + // Returns the last updated timestamp for a client cookie + // + // @param client Client index. + // @return Last updated timestamp. + public native int GetClientTime(int client); + + // Returns the access level of a cookie + // + // @return CookieAccess access level. + // @error Invalid cookie handle. + property CookieAccess AccessLevel { + public native get(); + } +}; + /** * Creates a new Client preference cookie. * * Handles returned by RegClientCookie can be closed via CloseHandle() when * no longer needed. * - * @param name Name of the new preference cookie. - * @param description Optional description of the preference cookie. - * @param access What CookieAccess level to assign to this cookie. - * @return A handle to the newly created cookie. If the cookie already + * @param name Name of the new preference cookie. + * @param description Optional description of the preference cookie. + * @param access What CookieAccess level to assign to this cookie. + * @return A handle to the newly created cookie. If the cookie already * exists, a handle to it will still be returned. - * @error Cookie name is blank. + * @error Cookie name is blank. */ native Handle RegClientCookie(const char[] name, const char[] description, CookieAccess access); @@ -103,86 +191,69 @@ native Handle RegClientCookie(const char[] name, const char[] description, Cooki * Handles returned by FindClientCookie can be closed via CloseHandle() when * no longer needed. * - * @param name Name of cookie to find. - * @return A handle to the cookie if it is found. INVALID_HANDLE otherwise. + * @param name Name of cookie to find. + * @return A handle to the cookie if it is found. INVALID_HANDLE otherwise. */ native Handle FindClientCookie(const char[] name); /** * Set the value of a Client preference cookie. * - * @param client Client index. - * @param cookie Client preference cookie handle. - * @param value String value to set. - * @error Invalid cookie handle or invalid client index. + * @param client Client index. + * @param cookie Client preference cookie handle. + * @param value String value to set. + * @error Invalid cookie handle or invalid client index. */ native void SetClientCookie(int client, Handle cookie, const char[] value); /** * Retrieve the value of a Client preference cookie. * - * @param client Client index. - * @param cookie Client preference cookie handle. - * @param buffer Copyback buffer for value. - * @param maxlen Maximum length of the buffer. - * @error Invalid cookie handle or invalid client index. + * @param client Client index. + * @param cookie Client preference cookie handle. + * @param buffer Copyback buffer for value. + * @param maxlen Maximum length of the buffer. + * @error Invalid cookie handle or invalid client index. */ native void GetClientCookie(int client, Handle cookie, char[] buffer, int maxlen); /** * Sets the value of a Client preference cookie based on an authID string. * - * @param authID String Auth/STEAM ID of player to set. - * @param cookie Client preference cookie handle. - * @param value String value to set. - * @error Invalid cookie handle. + * @param authID String Auth/STEAM ID of player to set. + * @param cookie Client preference cookie handle. + * @param value String value to set. + * @error Invalid cookie handle. */ native void SetAuthIdCookie(const char[] authID, Handle cookie, const char[] value); /** * Checks if a clients cookies have been loaded from the database. * - * @param client Client index. - * @return True if loaded, false otherwise. - * @error Invalid client index. + * @param client Client index. + * @return True if loaded, false otherwise. + * @error Invalid client index. */ native bool AreClientCookiesCached(int client); /** * Called once a client's saved cookies have been loaded from the database. * - * @param client Client index. + * @param client Client index. */ forward void OnClientCookiesCached(int client); -/** - * Cookie Menu Callback prototype - * - * @param client Client index. - * @param action CookieMenuAction being performed. - * @param info Info data passed. - * @param buffer Outbut buffer. - * @param maxlen Max length of the output buffer. - */ -typedef CookieMenuHandler = function void ( - int client, - CookieMenuAction action, - any info, - char[] buffer, - int maxlen -); - /** * Add a new prefab item to the client cookie settings menu. * * Note: This handles everything automatically and does not require a callback * - * @param cookie Client preference cookie handle. - * @param type A CookieMenu prefab menu type. - * @param display Text to show on the menu. - * @param handler Optional handler callback for translations and output on selection - * @param info Info data to pass to the callback. - * @error Invalid cookie handle. + * @param cookie Client preference cookie handle. + * @param type A CookieMenu prefab menu type. + * @param display Text to show on the menu. + * @param handler Optional handler callback for translations and output on selection + * @param info Info data to pass to the callback. + * @error Invalid cookie handle. */ native void SetCookiePrefabMenu(Handle cookie, CookieMenu type, const char[] display, CookieMenuHandler handler=INVALID_FUNCTION, any info=0); @@ -191,37 +262,37 @@ native void SetCookiePrefabMenu(Handle cookie, CookieMenu type, const char[] dis * * Note: This only adds the top level menu item. You need to handle any submenus from the callback. * - * @param handler A MenuHandler callback function. - * @param info Data to pass to the callback. - * @param display Text to show on the menu. - * @error Invalid cookie handle. + * @param handler A MenuHandler callback function. + * @param info Data to pass to the callback. + * @param display Text to show on the menu. + * @error Invalid cookie handle. */ native void SetCookieMenuItem(CookieMenuHandler handler, any info, const char[] display); /** * Displays the settings menu to a client. * - * @param client Client index. + * @param client Client index. */ native void ShowCookieMenu(int client); /** * Gets a cookie iterator. Must be freed with CloseHandle(). * - * @return A new cookie iterator. + * @return A new cookie iterator. */ native Handle GetCookieIterator(); /** * Reads a cookie iterator, then advances to the next cookie if any. * - * @param iter Cookie iterator Handle. - * @param name Name buffer. - * @param nameLen Name buffer size. - * @param access Access level of the cookie. - * @param desc Cookie description buffer. - * @param descLen Cookie description buffer size. - * @return True on success, false if there are no more commands. + * @param iter Cookie iterator Handle. + * @param name Name buffer. + * @param nameLen Name buffer size. + * @param access Access level of the cookie. + * @param desc Cookie description buffer. + * @param descLen Cookie description buffer size. + * @return True on success, false if there are no more commands. */ native bool ReadCookieIterator(Handle iter, char[] name, @@ -229,22 +300,22 @@ native bool ReadCookieIterator(Handle iter, CookieAccess &access, char[] desc="", int descLen=0); - + /** * Returns the access level of a cookie * - * @param cookie Client preference cookie handle. - * @return CookieAccess access level. - * @error Invalid cookie handle. + * @param cookie Client preference cookie handle. + * @return CookieAccess access level. + * @error Invalid cookie handle. */ native CookieAccess GetCookieAccess(Handle cookie); /** * Returns the last updated timestamp for a client cookie * - * @param client Client index. - * @param cookie Cookie handle. - * @return Last updated timestamp. + * @param client Client index. + * @param cookie Cookie handle. + * @return Last updated timestamp. */ native int GetClientCookieTime(int client, Handle cookie); @@ -270,6 +341,7 @@ public void __ext_cprefs_SetNTVOptional() MarkNativeAsOptional("FindClientCookie"); MarkNativeAsOptional("SetClientCookie"); MarkNativeAsOptional("GetClientCookie"); + MarkNativeAsOptional("SetAuthIdCookie"); MarkNativeAsOptional("AreClientCookiesCached"); MarkNativeAsOptional("SetCookiePrefabMenu"); MarkNativeAsOptional("SetCookieMenuItem"); @@ -278,5 +350,14 @@ public void __ext_cprefs_SetNTVOptional() MarkNativeAsOptional("ReadCookieIterator"); MarkNativeAsOptional("GetCookieAccess"); MarkNativeAsOptional("GetClientCookieTime"); + + MarkNativeAsOptional("Cookie.Cookie"); + MarkNativeAsOptional("Cookie.Find"); + MarkNativeAsOptional("Cookie.Set"); + MarkNativeAsOptional("Cookie.Get"); + MarkNativeAsOptional("Cookie.SetByAuthId"); + MarkNativeAsOptional("Cookie.SetPrefabMenu"); + MarkNativeAsOptional("Cookie.GetClientTime"); + MarkNativeAsOptional("Cookie.AccessLevel.get"); } #endif diff --git a/addons/sourcemod/scripting/include/clients.inc b/addons/sourcemod/scripting/include/clients.inc index 4f22b42..9a2946a 100644 --- a/addons/sourcemod/scripting/include/clients.inc +++ b/addons/sourcemod/scripting/include/clients.inc @@ -40,9 +40,9 @@ */ enum NetFlow { - NetFlow_Outgoing = 0, /**< Outgoing traffic */ - NetFlow_Incoming, /**< Incoming traffic */ - NetFlow_Both, /**< Both values added together */ + NetFlow_Outgoing = 0, /**< Outgoing traffic */ + NetFlow_Incoming, /**< Incoming traffic */ + NetFlow_Both /**< Both values added together */ }; /** @@ -61,7 +61,7 @@ enum AuthIdType // The following are only available on games that support Steam authentication. AuthId_Steam2, /**< Steam2 rendered format, ex "STEAM_1:1:4153990" */ AuthId_Steam3, /**< Steam3 rendered format, ex "[U:1:8307981]" */ - AuthId_SteamID64, /**< A SteamID64 (uint64) as a String, ex "76561197968573709" */ + AuthId_SteamID64 /**< A SteamID64 (uint64) as a String, ex "76561197968573709" */ }; /** @@ -69,10 +69,10 @@ enum AuthIdType * MAXPLAYERS is a hardcoded value as an upper limit. MaxClients changes based on the server. */ -#define MAXPLAYERS 65 /**< Maximum number of players SourceMod supports */ -#define MAX_NAME_LENGTH 32 /**< Maximum buffer required to store a client name */ +#define MAXPLAYERS 65 /**< Maximum number of players SourceMod supports */ +#define MAX_NAME_LENGTH 128 /**< Maximum buffer required to store a client name */ -public const int MaxClients; /**< Maximum number of players the server supports (dynamic) */ +public const int MaxClients; /**< Maximum number of players the server supports (dynamic) */ /** * Called on client connection. If you return true, the client will be allowed in the server. @@ -83,17 +83,17 @@ public const int MaxClients; /**< Maximum number of players the server supports * to the string buffer, it is not defined which plugin's string will be shown to the client, * but it is guaranteed one of them will. * - * @param client Client index. - * @param rejectmsg Buffer to store the rejection message when the connection is refused. - * @param maxlen Maximum number of characters for rejection buffer. - * @return True to validate client's connection, false to refuse it. + * @param client Client index. + * @param rejectmsg Buffer to store the rejection message when the connection is refused. + * @param maxlen Maximum number of characters for rejection buffer. + * @return True to validate client's connection, false to refuse it. */ forward bool OnClientConnect(int client, char[] rejectmsg, int maxlen); /** * Called once a client successfully connects. This callback is paired with OnClientDisconnect. * - * @param client Client index. + * @param client Client index. */ forward void OnClientConnected(int client); @@ -108,21 +108,21 @@ forward void OnClientConnected(int client); * GetClientCount() will include clients as they are passed through this * function, as clients are already in game at this point. * - * @param client Client index. + * @param client Client index. */ forward void OnClientPutInServer(int client); /** * Called when a client is disconnecting from the server. * - * @param client Client index. + * @param client Client index. */ forward void OnClientDisconnect(int client); /** * Called when a client is disconnected from the server. * - * @param client Client index. + * @param client Client index. */ forward void OnClientDisconnect_Post(int client); @@ -132,39 +132,39 @@ forward void OnClientDisconnect_Post(int client); * As of SourceMod 1.3, the client is guaranteed to be in-game. * Use command listeners (console.inc) for more advanced hooks. * - * @param client Client index. - * @param args Number of arguments. - * @return Plugin_Handled blocks the command from being sent, - * and Plugin_Continue resumes normal functionality. + * @param client Client index. + * @param args Number of arguments. + * @return Plugin_Handled blocks the command from being sent, + * and Plugin_Continue resumes normal functionality. */ forward Action OnClientCommand(int client, int args); /** * Called when a client is sending a KeyValues command. * - * @param client Client index. - * @param kv Editable KeyValues data to be sent as the command. - * (This handle should not be stored and will be closed - * after this forward completes.) - * @return Plugin_Handled blocks the command from being sent, - * and Plugin_Continue resumes normal functionality. + * @param client Client index. + * @param kv Editable KeyValues data to be sent as the command. + * (This handle should not be stored and will be closed + * after this forward completes.) + * @return Plugin_Handled blocks the command from being sent, + * and Plugin_Continue resumes normal functionality. */ forward Action OnClientCommandKeyValues(int client, KeyValues kv); /** * Called after a client has sent a KeyValues command. * - * @param client Client index. - * @param kv KeyValues data sent as the command. - * (This handle should not be stored and will be closed - * after this forward completes.) + * @param client Client index. + * @param kv KeyValues data sent as the command. + * (This handle should not be stored and will be closed + * after this forward completes.) */ forward void OnClientCommandKeyValues_Post(int client, KeyValues kv); /** * Called whenever the client's settings are changed. * - * @param client Client index. + * @param client Client index. */ forward void OnClientSettingsChanged(int client); @@ -175,8 +175,8 @@ forward void OnClientSettingsChanged(int client); * * This is called by bots, but the ID will be "BOT". * - * @param client Client index. - * @param auth Client Steam2 id, if available, else engine auth id. + * @param client Client index. + * @param auth Client Steam2 id, if available, else engine auth id. */ forward void OnClientAuthorized(int client, const char[] auth); @@ -193,8 +193,8 @@ forward void OnClientAuthorized(int client, const char[] auth); * This callback is guaranteed to occur on all clients, and always * after each OnClientPutInServer() call. * - * @param client Client index. - * @return Plugin_Handled to block admin checks. + * @param client Client index. + * @return Plugin_Handled to block admin checks. */ forward Action OnClientPreAdminCheck(int client); @@ -210,7 +210,7 @@ forward Action OnClientPreAdminCheck(int client); * * See OnClientPostAdminCheck() for more information. * - * @param client Client index. + * @param client Client index. */ forward void OnClientPostAdminFilter(int client); @@ -221,12 +221,12 @@ forward void OnClientPostAdminFilter(int client); * This callback is guaranteed to occur on all clients, and always * after each OnClientPutInServer() call. * - * @param client Client index. + * @param client Client index. */ forward void OnClientPostAdminCheck(int client); /** - * This function will be deprecated in a future release. Use the MaxClients variable instead. + * This function is deprecated. Use the MaxClients variable instead. * * Returns the maximum number of clients allowed on the server. This may * return 0 if called before OnMapStart(), and thus should not be called @@ -236,8 +236,10 @@ forward void OnClientPostAdminCheck(int client); * SourceTV or TF2's arena mode. Use the "MaxClients" dynamic variable documented at the * top of this file. * - * @return Maximum number of clients allowed. + * @return Maximum number of clients allowed. + * @deprecated Use MaxClients variable instead. */ +#pragma deprecated Use MaxClients variable instead. native int GetMaxClients(); /** @@ -251,52 +253,53 @@ native int GetMaxClients(); * You should not globally cache the value to GetMaxHumanPlayers() because it can change across * game modes. You may still cache it locally. * - * @return Maximum number of humans allowed. + * @return Maximum number of humans allowed. */ native int GetMaxHumanPlayers(); /** * Returns the client count put in the server. * - * @param inGameOnly If false connecting players are also counted. - * @return Client count in the server. + * @param inGameOnly If false connecting players are also counted. + * @return Client count in the server. */ native int GetClientCount(bool inGameOnly=true); /** * Returns the client's name. * - * @param client Player index. - * @param name Buffer to store the client's name. - * @param maxlen Maximum length of string buffer (includes NULL terminator). - * @return True on success, false otherwise. - * @error If the client is not connected an error will be thrown. + * @param client Player index. + * @param name Buffer to store the client's name. + * @param maxlen Maximum length of string buffer (includes NULL terminator). + * @return True on success, false otherwise. + * @error If the client is not connected an error will be thrown. */ native bool GetClientName(int client, char[] name, int maxlen); /** * Retrieves a client's IP address. * - * @param client Player index. - * @param ip Buffer to store the client's ip address. - * @param maxlen Maximum length of string buffer (includes NULL terminator). - * @param remport Remove client's port from the ip string (true by default). - * @return True on success, false otherwise. - * @error If the client is not connected or the index is invalid. + * @param client Player index. + * @param ip Buffer to store the client's ip address. + * @param maxlen Maximum length of string buffer (includes NULL terminator). + * @param remport Remove client's port from the ip string (true by default). + * @return True on success, false otherwise. + * @error If the client is not connected or the index is invalid. */ native bool GetClientIP(int client, char[] ip, int maxlen, bool remport=true); /** * Retrieves a client's authentication string (SteamID). * - * @param client Player index. - * @param auth Buffer to store the client's auth string. - * @param maxlen Maximum length of string buffer (includes NULL terminator). - * @param validate Check backend validation status. - * DO NOT PASS FALSE UNLESS YOU UNDERSTAND THE CONSEQUENCES, - * You WILL KNOW if you need to use this, MOST WILL NOT. - * @return True on success, false otherwise. - * @error If the client is not connected or the index is invalid. + * @param client Player index. + * @param auth Buffer to store the client's auth string. + * @param maxlen Maximum length of string buffer (includes NULL terminator). + * @param validate Check backend validation status. + * DO NOT PASS FALSE UNLESS YOU UNDERSTAND THE CONSEQUENCES, + * You WILL KNOW if you need to use this, MOST WILL NOT. + * @return True on success, false otherwise. + * @error If the client is not connected or the index is invalid. + * @deprecated Use GetClientAuthId */ #pragma deprecated Use GetClientAuthId native bool GetClientAuthString(int client, char[] auth, int maxlen, bool validate=true); @@ -304,15 +307,15 @@ native bool GetClientAuthString(int client, char[] auth, int maxlen, bool valida /** * Retrieves a client's authentication string (SteamID). * - * @param client Player index. - * @param authType Auth id type and format to use. - * @param auth Buffer to store the client's auth id. - * @param maxlen Maximum length of string buffer (includes NULL terminator). - * @param validate Check backend validation status. - * DO NOT PASS FALSE UNLESS YOU UNDERSTAND THE CONSEQUENCES, - * You WILL KNOW if you need to use this, MOST WILL NOT. - * @return True on success, false otherwise. - * @error If the client is not connected or the index is invalid. + * @param client Player index. + * @param authType Auth id type and format to use. + * @param auth Buffer to store the client's auth id. + * @param maxlen Maximum length of string buffer (includes NULL terminator). + * @param validate Check backend validation status. + * DO NOT PASS FALSE UNLESS YOU UNDERSTAND THE CONSEQUENCES, + * You WILL KNOW if you need to use this, MOST WILL NOT. + * @return True on success, false otherwise. + * @error If the client is not connected or the index is invalid. */ native bool GetClientAuthId(int client, AuthIdType authType, char[] auth, int maxlen, bool validate=true); @@ -320,12 +323,12 @@ native bool GetClientAuthId(int client, AuthIdType authType, char[] auth, int ma * Returns the client's Steam account ID, a number uniquely identifying a given Steam account. * This number is the basis for the various display SteamID forms, see the AuthIdType enum for examples. * - * @param client Client Index. - * @param validate Check backend validation status. - * DO NOT PASS FALSE UNLESS YOU UNDERSTAND THE CONSEQUENCES, - * You WILL KNOW if you need to use this, MOST WILL NOT. - * @return Steam account ID or 0 if not available. - * @error If the client is not connected or the index is invalid. + * @param client Client Index. + * @param validate Check backend validation status. + * DO NOT PASS FALSE UNLESS YOU UNDERSTAND THE CONSEQUENCES, + * You WILL KNOW if you need to use this, MOST WILL NOT. + * @return Steam account ID or 0 if not available. + * @error If the client is not connected or the index is invalid. */ native int GetSteamAccountID(int client, bool validate=true); @@ -333,26 +336,26 @@ native int GetSteamAccountID(int client, bool validate=true); * Retrieves a client's user id, which is an index incremented for every client * that joins the server. * - * @param client Player index. - * @return User id of the client. - * @error If the client is not connected or the index is invalid. + * @param client Player index. + * @return User id of the client. + * @error If the client is not connected or the index is invalid. */ native int GetClientUserId(int client); /** * Returns if a certain player is connected. * - * @param client Player index. - * @return True if player is connected to the server, false otherwise. + * @param client Player index. + * @return True if player is connected to the server, false otherwise. */ native bool IsClientConnected(int client); /** * Returns if a certain player has entered the game. * - * @param client Player index (index does not have to be connected). - * @return True if player has entered the game, false otherwise. - * @error Invalid client index. + * @param client Player index (index does not have to be connected). + * @return True if player has entered the game, false otherwise. + * @error Invalid client index. */ native bool IsClientInGame(int client); @@ -360,15 +363,15 @@ native bool IsClientInGame(int client); * Returns if a client is in the "kick queue" (i.e. the client will be kicked * shortly and thus they should not appear as valid). * - * @param client Player index (must be connected). - * @return True if in the kick queue, false otherwise. - * @error Invalid client index. + * @param client Player index (must be connected). + * @return True if in the kick queue, false otherwise. + * @error Invalid client index. */ native bool IsClientInKickQueue(int client); /** * Backwards compatibility stock - use IsClientInGame - * @deprecated Renamed to IsClientInGame + * @deprecated Renamed to IsClientInGame */ #pragma deprecated Use IsClientInGame() instead stock bool IsPlayerInGame(int client) @@ -379,40 +382,40 @@ stock bool IsPlayerInGame(int client) /** * Returns if a certain player has been authenticated. * - * @param client Player index. - * @return True if player has been authenticated, false otherwise. + * @param client Player index. + * @return True if player has been authenticated, false otherwise. */ native bool IsClientAuthorized(int client); /** * Returns if a certain player is a fake client. * - * @param client Player index. - * @return True if player is a fake client, false otherwise. + * @param client Player index. + * @return True if player is a fake client, false otherwise. */ native bool IsFakeClient(int client); /** * Returns if a certain player is the SourceTV bot. * - * @param client Player index. - * @return True if player is the SourceTV bot, false otherwise. + * @param client Player index. + * @return True if player is the SourceTV bot, false otherwise. */ native bool IsClientSourceTV(int client); /** * Returns if a certain player is the Replay bot. * - * @param client Player index. - * @return True if player is the Replay bot, false otherwise. + * @param client Player index. + * @return True if player is the Replay bot, false otherwise. */ native bool IsClientReplay(int client); /** * Returns if a certain player is an observer/spectator. * - * @param client Player index. - * @return True if player is an observer, false otherwise. + * @param client Player index. + * @return True if player is an observer, false otherwise. */ native bool IsClientObserver(int client); @@ -421,49 +424,49 @@ native bool IsClientObserver(int client); * * Note: This function was originally in SDKTools and was moved to core. * - * @param client Player's index. - * @return True if the client is alive, false otherwise. - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @return True if the client is alive, false otherwise. + * @error Invalid client index, client not in game, or no mod support. */ native bool IsPlayerAlive(int client); /** * Retrieves values from client replicated keys. * - * @param client Player's index. - * @param key Key string. - * @param value Buffer to store value. - * @param maxlen Maximum length of valve (UTF-8 safe). - * @return True on success, false otherwise. - * @error Invalid client index, or client not connected. + * @param client Player's index. + * @param key Key string. + * @param value Buffer to store value. + * @param maxlen Maximum length of valve (UTF-8 safe). + * @return True on success, false otherwise. + * @error Invalid client index, or client not connected. */ native bool GetClientInfo(int client, const char[] key, char[] value, int maxlen); /** * Retrieves a client's team index. * - * @param client Player's index. - * @return Team index the client is on (mod specific). - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @return Team index the client is on (mod specific). + * @error Invalid client index, client not in game, or no mod support. */ native int GetClientTeam(int client); /** * Sets a client's AdminId. * - * @param client Player's index. - * @param id AdminId to set. INVALID_ADMIN_ID removes admin permissions. - * @param temp True if the id should be freed on disconnect. - * @error Invalid client index, client not connected, or bogus AdminId. + * @param client Player's index. + * @param id AdminId to set. INVALID_ADMIN_ID removes admin permissions. + * @param temp True if the id should be freed on disconnect. + * @error Invalid client index, client not connected, or bogus AdminId. */ native void SetUserAdmin(int client, AdminId id, bool temp=false); /** * Retrieves a client's AdminId. * - * @param client Player's index. - * @return AdminId of the client, or INVALID_ADMIN_ID if none. - * @error Invalid client index, or client not connected. + * @param client Player's index. + * @return AdminId of the client, or INVALID_ADMIN_ID if none. + * @error Invalid client index, or client not connected. */ native AdminId GetUserAdmin(int client); @@ -471,9 +474,9 @@ native AdminId GetUserAdmin(int client); * Sets access flags on a client. If the client is not an admin, * a temporary, anonymous AdminId is given. * - * @param client Player's index. - * @param ... Flags to set on the client. - * @error Invalid client index, or client not connected. + * @param client Player's index. + * @param ... Flags to set on the client. + * @error Invalid client index, or client not connected. */ native void AddUserFlags(int client, AdminFlag ...); @@ -481,9 +484,9 @@ native void AddUserFlags(int client, AdminFlag ...); * Removes flags from a client. If the client is not an admin, * this has no effect. * - * @param client Player's index. - * @param ... Flags to remove from the client. - * @error Invalid client index, or client not connected. + * @param client Player's index. + * @param ... Flags to remove from the client. + * @error Invalid client index, or client not connected. */ native void RemoveUserFlags(int client, AdminFlag ...); @@ -491,8 +494,8 @@ native void RemoveUserFlags(int client, AdminFlag ...); * Sets access flags on a client using bits instead of flags. If the * client is not an admin, and flags not 0, a temporary, anonymous AdminId is given. * - * @param client Player's index. - * @param flags Bitstring of flags to set on client. + * @param client Player's index. + * @param flags Bitstring of flags to set on client. */ native void SetUserFlagBits(int client, int flags); @@ -500,9 +503,9 @@ native void SetUserFlagBits(int client, int flags); * Returns client access flags. If the client is not an admin, * the result is always 0. * - * @param client Player's index. - * @return Flags - * @error Invalid client index, or client not connected. + * @param client Player's index. + * @return Flags + * @error Invalid client index, or client not connected. */ native int GetUserFlagBits(int client); @@ -510,10 +513,10 @@ native int GetUserFlagBits(int client); * Returns whether a user can target another user. * This is a helper function for CanAdminTarget. * - * @param client Player's index. - * @param target Target player's index. - * @return True if target is targettable by the player, false otherwise. - * @error Invalid or unconnected player indexers. + * @param client Player's index. + * @param target Target player's index. + * @return True if target is targettable by the player, false otherwise. + * @error Invalid or unconnected player indexers. */ native bool CanUserTarget(int client, int target); @@ -523,9 +526,9 @@ native bool CanUserTarget(int client, int target); * * Note: This function is based on the internal cache only. * - * @param client Client index. - * @return True if access was changed, false if it did not. - * @error Invalid client index or client not in-game AND authorized. + * @param client Client index. + * @return True if access was changed, false if it did not. + * @error Invalid client index or client not in-game AND authorized. */ native bool RunAdminCacheChecks(int client); @@ -535,215 +538,215 @@ native bool RunAdminCacheChecks(int client); * * Note: This must be sent even if no admin id was assigned. * - * @param client Client index. - * @error Invalid client index or client not in-game AND authorized. + * @param client Client index. + * @error Invalid client index or client not in-game AND authorized. */ native void NotifyPostAdminCheck(int client); /** * Creates a fake client. * - * @param name Name to use. - * @return Client index on success, 0 otherwise. + * @param name Name to use. + * @return Client index on success, 0 otherwise. */ native int CreateFakeClient(const char[] name); /** * Sets a convar value on a fake client. * - * @param client Client index. - * @param cvar ConVar name. - * @param value ConVar value. - * @error Invalid client index, client not connected, - * or client not a fake client. + * @param client Client index. + * @param cvar ConVar name. + * @param value ConVar value. + * @error Invalid client index, client not connected, + * or client not a fake client. */ native void SetFakeClientConVar(int client, const char[] cvar, const char[] value); /** * Returns the client's health. * - * @param client Player's index. - * @return Health value. - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @return Health value. + * @error Invalid client index, client not in game, or no mod support. */ native int GetClientHealth(int client); /** * Returns the client's model name. * - * @param client Player's index. - * @param model Buffer to store the client's model name. - * @param maxlen Maximum length of string buffer (includes NULL terminator). - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @param model Buffer to store the client's model name. + * @param maxlen Maximum length of string buffer (includes NULL terminator). + * @error Invalid client index, client not in game, or no mod support. */ native void GetClientModel(int client, char[] model, int maxlen); /** * Returns the client's weapon name. * - * @param client Player's index. - * @param weapon Buffer to store the client's weapon name. - * @param maxlen Maximum length of string buffer (includes NULL terminator). - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @param weapon Buffer to store the client's weapon name. + * @param maxlen Maximum length of string buffer (includes NULL terminator). + * @error Invalid client index, client not in game, or no mod support. */ native void GetClientWeapon(int client, char[] weapon, int maxlen); /** * Returns the client's max size vector. * - * @param client Player's index. - * @param vec Destination vector to store the client's max size. - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @param vec Destination vector to store the client's max size. + * @error Invalid client index, client not in game, or no mod support. */ native void GetClientMaxs(int client, float vec[3]); /** * Returns the client's min size vector. * - * @param client Player's index. - * @param vec Destination vector to store the client's min size. - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @param vec Destination vector to store the client's min size. + * @error Invalid client index, client not in game, or no mod support. */ native void GetClientMins(int client, float vec[3]); /** * Returns the client's position angle. * - * @param client Player's index. - * @param ang Destination vector to store the client's position angle. - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @param ang Destination vector to store the client's position angle. + * @error Invalid client index, client not in game, or no mod support. */ native void GetClientAbsAngles(int client, float ang[3]); /** * Returns the client's origin vector. * - * @param client Player's index. - * @param vec Destination vector to store the client's origin vector. - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @param vec Destination vector to store the client's origin vector. + * @error Invalid client index, client not in game, or no mod support. */ native void GetClientAbsOrigin(int client, float vec[3]); /** * Returns the client's armor. * - * @param client Player's index. - * @return Armor value. - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @return Armor value. + * @error Invalid client index, client not in game, or no mod support. */ native int GetClientArmor(int client); /** * Returns the client's death count. * - * @param client Player's index. - * @return Death count. - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @return Death count. + * @error Invalid client index, client not in game, or no mod support. */ native int GetClientDeaths(int client); /** * Returns the client's frag count. * - * @param client Player's index. - * @return Frag count. - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @return Frag count. + * @error Invalid client index, client not in game, or no mod support. */ native int GetClientFrags(int client); /** * Returns the client's send data rate in bytes/sec. * - * @param client Player's index. - * @return Data rate. - * @error Invalid client index, client not connected, or fake client. + * @param client Player's index. + * @return Data rate. + * @error Invalid client index, client not connected, or fake client. */ native int GetClientDataRate(int client); /** * Returns if a client is timing out * - * @param client Player's index. - * @return True if client is timing out, false otherwise. - * @error Invalid client index, client not connected, or fake client. + * @param client Player's index. + * @return True if client is timing out, false otherwise. + * @error Invalid client index, client not connected, or fake client. */ native bool IsClientTimingOut(int client); /** * Returns the client's connection time in seconds. * - * @param client Player's index. - * @return Connection time. - * @error Invalid client index, client not connected, or fake client. + * @param client Player's index. + * @return Connection time. + * @error Invalid client index, client not connected, or fake client. */ native float GetClientTime(int client); /** * Returns the client's current latency (RTT), more accurate than GetAvgLatency but jittering. * - * @param client Player's index. - * @param flow Traffic flowing direction. - * @return Latency, or -1 if network info is not available. - * @error Invalid client index, client not connected, or fake client. + * @param client Player's index. + * @param flow Traffic flowing direction. + * @return Latency, or -1 if network info is not available. + * @error Invalid client index, client not connected, or fake client. */ native float GetClientLatency(int client, NetFlow flow); /** * Returns the client's average packet latency in seconds. * - * @param client Player's index. - * @param flow Traffic flowing direction. - * @return Latency, or -1 if network info is not available. - * @error Invalid client index, client not connected, or fake client. + * @param client Player's index. + * @param flow Traffic flowing direction. + * @return Latency, or -1 if network info is not available. + * @error Invalid client index, client not connected, or fake client. */ native float GetClientAvgLatency(int client, NetFlow flow); /** * Returns the client's average packet loss, values go from 0 to 1 (for percentages). * - * @param client Player's index. - * @param flow Traffic flowing direction. - * @return Average packet loss, or -1 if network info is not available. - * @error Invalid client index, client not connected, or fake client. + * @param client Player's index. + * @param flow Traffic flowing direction. + * @return Average packet loss, or -1 if network info is not available. + * @error Invalid client index, client not connected, or fake client. */ native float GetClientAvgLoss(int client, NetFlow flow); /** * Returns the client's average packet choke, values go from 0 to 1 (for percentages). * - * @param client Player's index. - * @param flow Traffic flowing direction. - * @return Average packet loss, or -1 if network info is not available. - * @error Invalid client index, client not connected, or fake client. + * @param client Player's index. + * @param flow Traffic flowing direction. + * @return Average packet loss, or -1 if network info is not available. + * @error Invalid client index, client not connected, or fake client. */ native float GetClientAvgChoke(int client, NetFlow flow); /** * Returns the client's data flow in bytes/sec. * - * @param client Player's index. - * @param flow Traffic flowing direction. - * @return Data flow. - * @error Invalid client index, client not connected, or fake client. + * @param client Player's index. + * @param flow Traffic flowing direction. + * @return Data flow. + * @error Invalid client index, client not connected, or fake client. */ native float GetClientAvgData(int client, NetFlow flow); /** * Returns the client's average packet frequency in packets/sec. * - * @param client Player's index. - * @param flow Traffic flowing direction. - * @return Packet frequency. - * @error Invalid client index, client not connected, or fake client. + * @param client Player's index. + * @param flow Traffic flowing direction. + * @return Packet frequency. + * @error Invalid client index, client not connected, or fake client. */ native float GetClientAvgPackets(int client, NetFlow flow); /** * Translates an userid index to the real player index. * - * @param userid Userid value. - * @return Client value. - * @error Returns 0 if invalid userid. + * @param userid Userid value. + * @return Client value. + * @error Returns 0 if invalid userid. */ native int GetClientOfUserId(int userid); @@ -759,11 +762,11 @@ native int GetClientOfUserId(int userid); * * Note: IsClientInKickQueue() will return true before the kick occurs. * - * @param client Client index. - * @param format Optional formatting rules for disconnect reason. + * @param client Client index. + * @param format Optional formatting rules for disconnect reason. * Note that a period is automatically appended to the string by the engine. - * @param ... Variable number of format parameters. - * @error Invalid client index, or client not connected. + * @param ... Variable number of format parameters. + * @error Invalid client index, or client not connected. */ native void KickClient(int client, const char[] format="", any ...); @@ -774,11 +777,11 @@ native void KickClient(int client, const char[] format="", any ...); * doubt, create a short (0.1 second) timer to kick the client in the next * available frame. * - * @param client Client index. - * @param format Optional formatting rules for disconnect reason. + * @param client Client index. + * @param format Optional formatting rules for disconnect reason. * Note that a period is automatically appended to the string by the engine. - * @param ... Variable number of format parameters. - * @error Invalid client index, or client not connected. + * @param ... Variable number of format parameters. + * @error Invalid client index, or client not connected. */ native void KickClientEx(int client, const char[] format="", any ...); @@ -786,26 +789,26 @@ native void KickClientEx(int client, const char[] format="", any ...); * Changes a client's team through the mod's generic team changing function. * On CS:S, this will kill the player. * - * @param client Client index. - * @param team Mod-specific team index. - * @error Invalid client index, client not connected, or lack of - * mod support. + * @param client Client index. + * @param team Mod-specific team index. + * @error Invalid client index, client not connected, or lack of + * mod support. */ native void ChangeClientTeam(int client, int team); /** * Returns the clients unique serial identifier. * - * @param client Client index. - * @return Serial number. - * @error Invalid client index, or client not connected. + * @param client Client index. + * @return Serial number. + * @error Invalid client index, or client not connected. */ native int GetClientSerial(int client); /** * Returns the client index by its serial number. * - * @param serial Serial number. - * @return Client index, or 0 for invalid serial. + * @param serial Serial number. + * @return Client index, or 0 for invalid serial. */ native int GetClientFromSerial(int serial); diff --git a/addons/sourcemod/scripting/include/colorvariables.inc b/addons/sourcemod/scripting/include/colorvariables.inc index 9ff1d83..36d7202 100644 --- a/addons/sourcemod/scripting/include/colorvariables.inc +++ b/addons/sourcemod/scripting/include/colorvariables.inc @@ -1,19 +1,8 @@ -// https://github.com/nikooo777/ckSurf -// ===================================== -// ===== ! ! ! W A R N I N G ! ! ! ===== -// ===================================== -// In case you want to update this file from the source below, -// note that additional color names(aliases) were added for ckSurf. -// Please don't forget to readd them after updating this file. -// ===================================== /CK - - #if defined _colorvariables_included #endinput #endif #define _colorvariables_included "1.3" -// Source: https://raw.githubusercontent.com/Drixevel/Chat-Processor/master/scripting/include/colorvariables.inc // Author: Raska aka KissLick // Syntax update: Keith Warren (Drixevel) (redwerewolf on Allied Mods) @@ -508,7 +497,9 @@ stock void CSayText2(int iClient, char[] sMessage, int iAuthor, bool bChat = tru stock void CAddWhiteSpace(char[] sBuffer, int iSize) { - if (!IsSource2009()) { + EngineVersion iEngineVersion = GetEngineVersion(); + + if (!IsSource2009() && !(iEngineVersion == Engine_Left4Dead) && !(iEngineVersion == Engine_Left4Dead2)) { Format(sBuffer, iSize, " %s", sBuffer); } } @@ -975,34 +966,24 @@ stock void AddColors(Handle hTrie) SetTrieString(hTrie, "yellow", "\x07FFFF00"); SetTrieString(hTrie, "yellowgreen", "\x079ACD32"); } else { - SetTrieString(hTrie, "default", "\x01"); // "\x01" "{default}" - SetTrieString(hTrie, "teamcolor", "\x03"); // "\x03" "{lightgreen}" "\x03" "{orange}" "\x03" "{blue}" "\x03" "{purple}" - - SetTrieString(hTrie, "red", "\x07"); // "\x07" "{red}" - SetTrieString(hTrie, "lightred", "\x0F"); // "\x0F" "{lightred}" - SetTrieString(hTrie, "darkred", "\x02"); // "\x02" "{darkred}" - SetTrieString(hTrie, "bluegrey", "\x0A"); // "\x0A" "{lightblue}" - SetTrieString(hTrie, "blue", "\x0B"); // "\x0B" "{steelblue}" - SetTrieString(hTrie, "darkblue", "\x0C"); // "\x0C" "{darkblue}" + SetTrieString(hTrie, "default", "\x01"); + SetTrieString(hTrie, "teamcolor", "\x03"); + + SetTrieString(hTrie, "red", "\x07"); + SetTrieString(hTrie, "lightred", "\x0F"); + SetTrieString(hTrie, "darkred", "\x02"); + SetTrieString(hTrie, "bluegrey", "\x0A"); + SetTrieString(hTrie, "blue", "\x0B"); + SetTrieString(hTrie, "darkblue", "\x0C"); SetTrieString(hTrie, "purple", "\x03"); - SetTrieString(hTrie, "orchid", "\x0E"); // "\x0E" "{pink}" - SetTrieString(hTrie, "yellow", "\x09"); // "\x09" "{yellow}" + SetTrieString(hTrie, "orchid", "\x0E"); + SetTrieString(hTrie, "yellow", "\x09"); SetTrieString(hTrie, "gold", "\x10"); - SetTrieString(hTrie, "lightgreen", "\x05"); // "\x05" "{olive}" - SetTrieString(hTrie, "green", "\x04"); // "\x04" "{green}" - SetTrieString(hTrie, "lime", "\x06"); // "\x06" "{lime}" - SetTrieString(hTrie, "grey", "\x08"); // "\x08" "{grey}" + SetTrieString(hTrie, "lightgreen", "\x05"); + SetTrieString(hTrie, "green", "\x04"); + SetTrieString(hTrie, "lime", "\x06"); + SetTrieString(hTrie, "grey", "\x08"); SetTrieString(hTrie, "grey2", "\x0D"); - - // Additional color names for ckSurf backwards compatibility - SetTrieString(hTrie, "bluegray", "\x0A"); // using bluegrey - SetTrieString(hTrie, "gray", "\x08"); // using gray - SetTrieString(hTrie, "gray2", "\x0D"); // using gray2 - SetTrieString(hTrie, "orange", "\x10"); // using gold - SetTrieString(hTrie, "steelblue", "\x0D"); // using grey2 - SetTrieString(hTrie, "pink", "\x0E"); // using orchid - SetTrieString(hTrie, "lightblue", "\x0A"); // using bluegrey - SetTrieString(hTrie, "olive", "\x05"); // using lightgreen } SetTrieString(hTrie, "engine 1", "\x01"); @@ -1053,4 +1034,4 @@ stock void SendPlayerMessage(int iClient, char[] sMessage, int iAuthor = 0) } else { CSayText2(iClient, sMessage, iAuthor); } -} \ No newline at end of file +} diff --git a/addons/sourcemod/scripting/include/commandfilters.inc b/addons/sourcemod/scripting/include/commandfilters.inc index 2a9e285..714502b 100644 --- a/addons/sourcemod/scripting/include/commandfilters.inc +++ b/addons/sourcemod/scripting/include/commandfilters.inc @@ -35,23 +35,23 @@ #endif #define _commandfilters_included -#define MAX_TARGET_LENGTH 64 +#define MAX_TARGET_LENGTH 64 -#define COMMAND_FILTER_ALIVE (1<<0) /**< Only allow alive players */ -#define COMMAND_FILTER_DEAD (1<<1) /**< Only filter dead players */ -#define COMMAND_FILTER_CONNECTED (1<<2) /**< Allow players not fully in-game */ -#define COMMAND_FILTER_NO_IMMUNITY (1<<3) /**< Ignore immunity rules */ -#define COMMAND_FILTER_NO_MULTI (1<<4) /**< Do not allow multiple target patterns */ -#define COMMAND_FILTER_NO_BOTS (1<<5) /**< Do not allow bots to be targetted */ +#define COMMAND_FILTER_ALIVE (1<<0) /**< Only allow alive players */ +#define COMMAND_FILTER_DEAD (1<<1) /**< Only filter dead players */ +#define COMMAND_FILTER_CONNECTED (1<<2) /**< Allow players not fully in-game */ +#define COMMAND_FILTER_NO_IMMUNITY (1<<3) /**< Ignore immunity rules */ +#define COMMAND_FILTER_NO_MULTI (1<<4) /**< Do not allow multiple target patterns */ +#define COMMAND_FILTER_NO_BOTS (1<<5) /**< Do not allow bots to be targetted */ -#define COMMAND_TARGET_NONE 0 /**< No target was found */ -#define COMMAND_TARGET_NOT_ALIVE -1 /**< Single client is not alive */ -#define COMMAND_TARGET_NOT_DEAD -2 /**< Single client is not dead */ -#define COMMAND_TARGET_NOT_IN_GAME -3 /**< Single client is not in game */ -#define COMMAND_TARGET_IMMUNE -4 /**< Single client is immune */ -#define COMMAND_TARGET_EMPTY_FILTER -5 /**< A multi-filter (such as @all) had no targets */ -#define COMMAND_TARGET_NOT_HUMAN -6 /**< Target was not human */ -#define COMMAND_TARGET_AMBIGUOUS -7 /**< Partial name had too many targets */ +#define COMMAND_TARGET_NONE 0 /**< No target was found */ +#define COMMAND_TARGET_NOT_ALIVE -1 /**< Single client is not alive */ +#define COMMAND_TARGET_NOT_DEAD -2 /**< Single client is not dead */ +#define COMMAND_TARGET_NOT_IN_GAME -3 /**< Single client is not in game */ +#define COMMAND_TARGET_IMMUNE -4 /**< Single client is immune */ +#define COMMAND_TARGET_EMPTY_FILTER -5 /**< A multi-filter (such as @all) had no targets */ +#define COMMAND_TARGET_NOT_HUMAN -6 /**< Target was not human */ +#define COMMAND_TARGET_AMBIGUOUS -7 /**< Partial name had too many targets */ /** * Processes a generic command target string, and resolves it to a list @@ -61,28 +61,28 @@ * as that file is guaranteed to contain all of the translatable phrases that * ProcessTargetString() will return. * - * @param pattern Pattern to find clients against. - * @param admin Admin performing the action, or 0 if the server. - * @param targets Array to hold targets. - * @param max_targets Maximum size of the targets array. - * @param filter_flags Filter flags. - * @param target_name Buffer to store the target name. - * @param tn_maxlength Maximum length of the target name buffer. - * @param tn_is_ml OUTPUT: Will be true if the target name buffer is an ML phrase, - * false if it is a normal string. - * @return If a multi-target pattern was used, the number of clients found - * is returned. If a single-target pattern was used, 1 is returned - * if one valid client is found. Otherwise, a COMMAND_TARGET reason - * for failure is returned. + * @param pattern Pattern to find clients against. + * @param admin Admin performing the action, or 0 if the server. + * @param targets Array to hold targets. + * @param max_targets Maximum size of the targets array. + * @param filter_flags Filter flags. + * @param target_name Buffer to store the target name. + * @param tn_maxlength Maximum length of the target name buffer. + * @param tn_is_ml OUTPUT: Will be true if the target name buffer is an ML phrase, + * false if it is a normal string. + * @return If a multi-target pattern was used, the number of clients found + * is returned. If a single-target pattern was used, 1 is returned + * if one valid client is found. Otherwise, a COMMAND_TARGET reason + * for failure is returned. */ native int ProcessTargetString(const char[] pattern, - int admin, - int[] targets, - int max_targets, - int filter_flags, - char[] target_name, - int tn_maxlength, - bool &tn_is_ml); + int admin, + int[] targets, + int max_targets, + int filter_flags, + char[] target_name, + int tn_maxlength, + bool &tn_is_ml); /** * Replies to a client with a given message describing a targetting @@ -90,8 +90,8 @@ native int ProcessTargetString(const char[] pattern, * * Note: The translation phrases are found in common.phrases.txt. * - * @param client Client index, or 0 for server. - * @param reason COMMAND_TARGET reason. + * @param client Client index, or 0 for server. + * @param reason COMMAND_TARGET reason. */ stock void ReplyToTargetError(int client, int reason) { @@ -139,7 +139,10 @@ stock void ReplyToTargetError(int client, int reason) * @param clients Array to fill with unique, valid client indexes. * @return True if pattern was recognized, false otherwise. */ -typedef MultiTargetFilter = function bool (const char[] pattern, Handle clients); +typeset MultiTargetFilter { + function bool (const char[] pattern, Handle clients); + function bool (const char[] pattern, ArrayList clients); +} /** * Adds a multi-target filter function for ProcessTargetString(). diff --git a/addons/sourcemod/scripting/include/commandline.inc b/addons/sourcemod/scripting/include/commandline.inc index 5ff7d22..33e4a13 100644 --- a/addons/sourcemod/scripting/include/commandline.inc +++ b/addons/sourcemod/scripting/include/commandline.inc @@ -31,56 +31,56 @@ */ #if defined _commandline_included_ - #endinput + #endinput #endif #define _commandline_included_ /** * Gets the full command line the server was launched with. * - * @param commandLine Buffer to store the command line in. - * @param maxlen Maximum length of the command line buffer. - * @return True if the command line is valid; otherwise, false. - * @error No command line available, or no mod support. + * @param commandLine Buffer to store the command line in. + * @param maxlen Maximum length of the command line buffer. + * @return True if the command line is valid; otherwise, false. + * @error No command line available, or no mod support. */ native bool GetCommandLine(char[] commandLine, int maxlen); /** * Gets the value of a command line parameter the server was launched with. * - * @param param The command line parameter to get the value of. - * @param value Buffer to store the parameter value in. - * @param maxlen Maximum length of the value buffer. - * @param defValue The default value to return if the parameter wasn't specified. - * @error No command line available, or no mod support. + * @param param The command line parameter to get the value of. + * @param value Buffer to store the parameter value in. + * @param maxlen Maximum length of the value buffer. + * @param defValue The default value to return if the parameter wasn't specified. + * @error No command line available, or no mod support. */ native void GetCommandLineParam(const char[] param, char[] value, int maxlen, const char[] defValue=""); /** * Gets the value of a command line parameter the server was launched with. * - * @param param The command line parameter to get the value of. - * @param defValue The default value to return if the parameter wasn't specified. - * @return The integer value of the command line parameter value. - * @error No command line available, or no mod support. + * @param param The command line parameter to get the value of. + * @param defValue The default value to return if the parameter wasn't specified. + * @return The integer value of the command line parameter value. + * @error No command line available, or no mod support. */ native int GetCommandLineParamInt(const char[] param, int defValue=0); /** * Gets the value of a command line parameter the server was launched with. * - * @param param The command line parameter to get the value of. - * @param defValue The default value to return if the parameter wasn't specified. - * @return The floating point value of the command line parameter value. - * @error No command line available, or no mod support. + * @param param The command line parameter to get the value of. + * @param defValue The default value to return if the parameter wasn't specified. + * @return The floating point value of the command line parameter value. + * @error No command line available, or no mod support. */ native float GetCommandLineParamFloat(const char[] param, float defValue=0.0); /** * Determines if a specific command line parameter is present. * - * @param param The command line parameter to test. - * @return True if the command line parameter is specified; otherwise, false. - * @error No command line available, or no mod support. + * @param param The command line parameter to test. + * @return True if the command line parameter is specified; otherwise, false. + * @error No command line available, or no mod support. */ native bool FindCommandLineParam(const char[] param); diff --git a/addons/sourcemod/scripting/include/console.inc b/addons/sourcemod/scripting/include/console.inc index 1ba4d00..3b0693c 100644 --- a/addons/sourcemod/scripting/include/console.inc +++ b/addons/sourcemod/scripting/include/console.inc @@ -35,14 +35,14 @@ #endif #define _console_included -#define INVALID_FCVAR_FLAGS (-1) +#define INVALID_FCVAR_FLAGS (-1) /** * Console variable query helper values. */ enum QueryCookie { - QUERYCOOKIE_FAILED = 0, + QUERYCOOKIE_FAILED = 0 }; /** @@ -51,7 +51,7 @@ enum QueryCookie enum ReplySource { SM_REPLY_TO_CONSOLE = 0, - SM_REPLY_TO_CHAT = 1, + SM_REPLY_TO_CHAT = 1 }; /** @@ -65,25 +65,25 @@ enum ReplySource #define FCVAR_LAUNCHER (1<<1) // Same value as FCVAR_DEVELOPMENTONLY, which is what most usages of this were intending to use. -#define FCVAR_NONE 0 // The default, no flags at all -#define FCVAR_UNREGISTERED (1<<0) // If this is set, don't add to linked list, etc. -#define FCVAR_DEVELOPMENTONLY (1<<1) // Hidden in released products. Flag is removed automatically if ALLOW_DEVELOPMENT_CVARS is defined. (OB+) -#define FCVAR_GAMEDLL (1<<2) // Defined by the game DLL. -#define FCVAR_CLIENTDLL (1<<3) // Defined by the client DLL. -#define FCVAR_MATERIAL_SYSTEM (1<<4) // Defined by the material system. (EP1-only) -#define FCVAR_HIDDEN (1<<4) // Hidden. Doesn't appear in find or autocomplete. Like DEVELOPMENTONLY, but can't be compiled out.1 (OB+) -#define FCVAR_PROTECTED (1<<5) // It's a server cvar, but we don't send the data since it's a password, etc. +#define FCVAR_NONE 0 // The default, no flags at all +#define FCVAR_UNREGISTERED (1<<0) // If this is set, don't add to linked list, etc. +#define FCVAR_DEVELOPMENTONLY (1<<1) // Hidden in released products. Flag is removed automatically if ALLOW_DEVELOPMENT_CVARS is defined. (OB+) +#define FCVAR_GAMEDLL (1<<2) // Defined by the game DLL. +#define FCVAR_CLIENTDLL (1<<3) // Defined by the client DLL. +#define FCVAR_MATERIAL_SYSTEM (1<<4) // Defined by the material system. (EP1-only) +#define FCVAR_HIDDEN (1<<4) // Hidden. Doesn't appear in find or autocomplete. Like DEVELOPMENTONLY, but can't be compiled out.1 (OB+) +#define FCVAR_PROTECTED (1<<5) // It's a server cvar, but we don't send the data since it's a password, etc. // Sends 1 if it's not bland/zero, 0 otherwise as value. -#define FCVAR_SPONLY (1<<6) // This cvar cannot be changed by clients connected to a multiplayer server. -#define FCVAR_ARCHIVE (1<<7) // Set to cause it to be saved to vars.rc -#define FCVAR_NOTIFY (1<<8) // Notifies players when changed. -#define FCVAR_USERINFO (1<<9) // Changes the client's info string. -#define FCVAR_PRINTABLEONLY (1<<10) // This cvar's string cannot contain unprintable characters (e.g., used for player name, etc.) -#define FCVAR_UNLOGGED (1<<11) // If this is a FCVAR_SERVER, don't log changes to the log file / console if we are creating a log -#define FCVAR_NEVER_AS_STRING (1<<12) // Never try to print that cvar. -#define FCVAR_REPLICATED (1<<13) // Server setting enforced on clients. -#define FCVAR_CHEAT (1<<14) // Only useable in singleplayer / debug / multiplayer & sv_cheats -#define FCVAR_SS (1<<15) // causes varnameN where N 2 through max splitscreen slots for mod to be autogenerated (L4D+) +#define FCVAR_SPONLY (1<<6) // This cvar cannot be changed by clients connected to a multiplayer server. +#define FCVAR_ARCHIVE (1<<7) // Set to cause it to be saved to vars.rc +#define FCVAR_NOTIFY (1<<8) // Notifies players when changed. +#define FCVAR_USERINFO (1<<9) // Changes the client's info string. +#define FCVAR_PRINTABLEONLY (1<<10) // This cvar's string cannot contain unprintable characters (e.g., used for player name, etc.) +#define FCVAR_UNLOGGED (1<<11) // If this is a FCVAR_SERVER, don't log changes to the log file / console if we are creating a log +#define FCVAR_NEVER_AS_STRING (1<<12) // Never try to print that cvar. +#define FCVAR_REPLICATED (1<<13) // Server setting enforced on clients. +#define FCVAR_CHEAT (1<<14) // Only useable in singleplayer / debug / multiplayer & sv_cheats +#define FCVAR_SS (1<<15) // causes varnameN where N 2 through max splitscreen slots for mod to be autogenerated (L4D+) #define FCVAR_DEMO (1<<16) // Record this cvar when starting a demo file. #define FCVAR_DONTRECORD (1<<17) // Don't record these command in demo files. #define FCVAR_SS_ADDED (1<<18) // This is one of the "added" FCVAR_SS variables for the splitscreen players (L4D+) @@ -109,8 +109,8 @@ enum ReplySource /** * Executes a server command as if it were on the server console (or RCON) * - * @param format Formatting rules. - * @param ... Variable number of format parameters. + * @param format Formatting rules. + * @param ... Variable number of format parameters. */ native void ServerCommand(const char[] format, any ...); @@ -123,18 +123,18 @@ native void ServerCommand(const char[] format, any ...); * the response. * Also, on L4D2 this will not print the command output to the server console. * - * @param buffer String to store command result into. - * @param maxlen Length of buffer. - * @param format Formatting rules. - * @param ... Variable number of format parameters. + * @param buffer String to store command result into. + * @param maxlen Length of buffer. + * @param format Formatting rules. + * @param ... Variable number of format parameters. */ native void ServerCommandEx(char[] buffer, int maxlen, const char[] format, any ...); /** * Inserts a server command at the beginning of the server command buffer. * - * @param format Formatting rules. - * @param ... Variable number of format parameters. + * @param format Formatting rules. + * @param ... Variable number of format parameters. */ native void InsertServerCommand(const char[] format, any ...); @@ -147,10 +147,10 @@ native void ServerExecute(); * Executes a client command. Note that this will not work on clients unless * they have cl_restrict_server_commands set to 0. * - * @param client Index of the client. - * @param fmt Format of the client command. - * @param ... Format parameters - * @error Invalid client index, or client not connected. + * @param client Index of the client. + * @param fmt Format of the client command. + * @param ... Format parameters + * @error Invalid client index, or client not connected. */ native void ClientCommand(int client, const char[] fmt, any ...); @@ -163,10 +163,10 @@ native void ClientCommand(int client, const char[] fmt, any ...); * a hook where this matters (for example, a "say" hook), you should use * FakeClientCommandEx() instead. * - * @param client Index of the client. - * @param fmt Format of the client command. - * @param ... Format parameters - * @error Invalid client index, or client not connected. + * @param client Index of the client. + * @param fmt Format of the client command. + * @param ... Format parameters + * @error Invalid client index, or client not connected. */ native void FakeClientCommand(int client, const char[] fmt, any ...); @@ -175,38 +175,38 @@ native void FakeClientCommand(int client, const char[] fmt, any ...); * execution of the client command is delayed by one frame to prevent any * re-entrancy issues that might surface with FakeClientCommand(). * - * @param client Index of the client. - * @param fmt Format of the client command. - * @param ... Format parameters - * @error Invalid client index, or client not connected. + * @param client Index of the client. + * @param fmt Format of the client command. + * @param ... Format parameters + * @error Invalid client index, or client not connected. */ native void FakeClientCommandEx(int client, const char[] fmt, any ...); /** * Executes a KeyValues client command on the server without being networked. * - * @param client Index of the client. - * @param kv KeyValues data to be sent. - * @error Invalid client index, client not connected, - * or unsupported on current game. + * @param client Index of the client. + * @param kv KeyValues data to be sent. + * @error Invalid client index, client not connected, + * or unsupported on current game. */ native void FakeClientCommandKeyValues(int client, KeyValues kv); /** * Sends a message to the server console. * - * @param format Formatting rules. - * @param ... Variable number of format parameters. + * @param format Formatting rules. + * @param ... Variable number of format parameters. */ native void PrintToServer(const char[] format, any ...); /** * Sends a message to a client's console. * - * @param client Client index. - * @param format Formatting rules. - * @param ... Variable number of format parameters. - * @error If the client is not connected an error will be thrown. + * @param client Client index. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @error If the client is not connected an error will be thrown. */ native void PrintToConsole(int client, const char[] format, any ...); @@ -214,8 +214,8 @@ native void PrintToConsole(int client, const char[] format, any ...); /** * Sends a message to every client's console. * - * @param format Formatting rules. - * @param ... Variable number of format parameters. + * @param format Formatting rules. + * @param ... Variable number of format parameters. */ stock void PrintToConsoleAll(const char[] format, any ...) { @@ -233,23 +233,23 @@ stock void PrintToConsoleAll(const char[] format, any ...) } /** - * Reples to a message in a command. + * Replies to a message in a command. * * A client index of 0 will use PrintToServer(). * If the command was from the console, PrintToConsole() is used. * If the command was from chat, PrintToChat() is used. * - * @param client Client index, or 0 for server. - * @param format Formatting rules. - * @param ... Variable number of format parameters. - * @error If the client is not connected or invalid. + * @param client Client index, or 0 for server. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @error If the client is not connected or invalid. */ native void ReplyToCommand(int client, const char[] format, any ...); /** * Returns the current reply source of a command. * - * @return ReplySource value. + * @return ReplySource value. */ native ReplySource GetCmdReplySource(); @@ -259,8 +259,8 @@ native ReplySource GetCmdReplySource(); * Only use this if you know what you are doing. You should save the old value * and restore it once you are done. * - * @param source New ReplySource value. - * @return Old ReplySource value. + * @param source New ReplySource value. + * @return Old ReplySource value. */ native ReplySource SetCmdReplySource(ReplySource source); @@ -269,7 +269,7 @@ native ReplySource SetCmdReplySource(ReplySource source); * * This function is only meaningful inside say or say_team hooks. * - * @return True if a chat trigger, false otherwise. + * @return True if a chat trigger, false otherwise. */ native bool IsChatTrigger(); @@ -279,10 +279,10 @@ native bool IsChatTrigger(); * in their chat text, except for the originating client, who receives * the message based on the current ReplySource. * - * @param client Client index doing the action, or 0 for server. - * @param tag Tag to prepend to the message. - * @param format Formatting rules. - * @param ... Variable number of format parameters. + * @param client Client index doing the action, or 0 for server. + * @param tag Tag to prepend to the message. + * @param format Formatting rules. + * @param ... Variable number of format parameters. * @error */ native void ShowActivity2(int client, const char[] tag, const char[] format, any ...); @@ -296,9 +296,9 @@ native void ShowActivity2(int client, const char[] tag, const char[] format, any * for these cases, then this function will suffice. Otherwise, * ShowActivity2() is slightly more useful. * - * @param client Client index doing the action, or 0 for server. - * @param format Formatting rules. - * @param ... Variable number of format parameters. + * @param client Client index doing the action, or 0 for server. + * @param format Formatting rules. + * @param ... Variable number of format parameters. * @error */ native void ShowActivity(int client, const char[] format, any ...); @@ -307,10 +307,10 @@ native void ShowActivity(int client, const char[] format, any ...); * Same as ShowActivity(), except the tag parameter is used instead of * "[SM] " (note that you must supply any spacing). * - * @param client Client index doing the action, or 0 for server. - * @param tag Tag to display with. - * @param format Formatting rules. - * @param ... Variable number of format parameters. + * @param client Client index doing the action, or 0 for server. + * @param tag Tag to display with. + * @param format Formatting rules. + * @param ... Variable number of format parameters. * @error */ native void ShowActivityEx(int client, const char[] tag, const char[] format, any ...); @@ -336,9 +336,9 @@ native bool FormatActivitySource(int client, int target, const char[] namebuf, i /** * Called when a server-only command is invoked. * - * @param args Number of arguments that were in the argument string. - * @return An Action value. Not handling the command - * means that Source will report it as "not found." + * @param args Number of arguments that were in the argument string. + * @return An Action value. Not handling the command + * means that Source will report it as "not found." */ typedef SrvCmd = function Action (int args); @@ -347,21 +347,21 @@ typedef SrvCmd = function Action (int args); * * Server commands are case sensitive. * - * @param cmd Name of the command to hook or create. - * @param callback A function to use as a callback for when the command is invoked. - * @param description Optional description to use for command creation. - * @param flags Optional flags to use for command creation. - * @error Command name is the same as an existing convar. + * @param cmd Name of the command to hook or create. + * @param callback A function to use as a callback for when the command is invoked. + * @param description Optional description to use for command creation. + * @param flags Optional flags to use for command creation. + * @error Command name is the same as an existing convar. */ native void RegServerCmd(const char[] cmd, SrvCmd callback, const char[] description="", int flags=0); /** * Called when a generic console command is invoked. * - * @param client Index of the client, or 0 from the server. - * @param args Number of arguments that were in the argument string. - * @return An Action value. Not handling the command - * means that Source will report it as "not found." + * @param client Index of the client, or 0 from the server. + * @param args Number of arguments that were in the argument string. + * @return An Action value. Not handling the command + * means that Source will report it as "not found." */ typedef ConCmd = function Action (int client, int args); @@ -372,11 +372,11 @@ typedef ConCmd = function Action (int client, int args); * a client may enter the command in any case. SourceMod corrects for this automatically, * and you should only hook the "real" version of the command. * - * @param cmd Name of the command to hook or create. - * @param callback A function to use as a callback for when the command is invoked. - * @param description Optional description to use for command creation. - * @param flags Optional flags to use for command creation. - * @error Command name is the same as an existing convar. + * @param cmd Name of the command to hook or create. + * @param callback A function to use as a callback for when the command is invoked. + * @param description Optional description to use for command creation. + * @param flags Optional flags to use for command creation. + * @error Command name is the same as an existing convar. */ native void RegConsoleCmd(const char[] cmd, ConCmd callback, const char[] description="", int flags=0); @@ -387,14 +387,14 @@ native void RegConsoleCmd(const char[] cmd, ConCmd callback, const char[] descri * * Admin commands are case sensitive from both the client and server. * - * @param cmd String containing command to register. - * @param callback A function to use as a callback for when the command is invoked. - * @param adminflags Administrative flags (bitstring) to use for permissions. - * @param description Optional description to use for help. - * @param group String containing the command group to use. If empty, - * the plugin's filename will be used instead. - * @param flags Optional console flags. - * @error Command name is the same as an existing convar. + * @param cmd String containing command to register. + * @param callback A function to use as a callback for when the command is invoked. + * @param adminflags Administrative flags (bitstring) to use for permissions. + * @param description Optional description to use for help. + * @param group String containing the command group to use. If empty, + * the plugin's filename will be used instead. + * @param flags Optional console flags. + * @error Command name is the same as an existing convar. */ native void RegAdminCmd(const char[] cmd, ConCmd callback, @@ -407,7 +407,7 @@ native void RegAdminCmd(const char[] cmd, * Returns the number of arguments from the current console or server command. * @note Unlike the HL2 engine call, this does not include the command itself. * - * @return Number of arguments to the current command. + * @return Number of arguments to the current command. */ native int GetCmdArgs(); @@ -416,10 +416,10 @@ native int GetCmdArgs(); * server command. * @note Argument indexes start at 1; 0 retrieves the command name. * - * @param argnum Argument number to retrieve. - * @param buffer Buffer to use for storing the string. - * @param maxlength Maximum length of the buffer. - * @return Length of string written to buffer. + * @param argnum Argument number to retrieve. + * @param buffer Buffer to use for storing the string. + * @param maxlength Maximum length of the buffer. + * @return Length of string written to buffer. */ native int GetCmdArg(int argnum, char[] buffer, int maxlength); @@ -427,16 +427,62 @@ native int GetCmdArg(int argnum, char[] buffer, int maxlength); * Retrieves the entire command argument string in one lump from the current * console or server command. * - * @param buffer Buffer to use for storing the string. - * @param maxlength Maximum length of the buffer. - * @return Length of string written to buffer. + * @param buffer Buffer to use for storing the string. + * @param maxlength Maximum length of the buffer. + * @return Length of string written to buffer. */ native int GetCmdArgString(char[] buffer, int maxlength); +methodmap CommandIterator < Handle { + // Creates a new CommandIterator. Must be freed with delete or + // CloseHandle(). + // + // The CommandIterator can be used to iterate commands created by + // SourceMod plugins and allows inspection of properties associated + // with the command. + // + // @return New CommandIterator Handle. + public native CommandIterator(); + + // Determines if there is a next command. If one is found, the + // iterator is advanced to it. + // + // @return true if found and iterator is advanced. + public native bool Next(); + + // Retrieves the command's description. + // + // @param buffer Buffer to copy to. + // @param maxlen Maximum size of the buffer. + // @error Invalid iterator position. + public native void GetDescription(char[] buffer, int maxlen); + + // Retrieves the command's name. + // + // @param buffer Buffer to copy to. + // @param maxlen Maximum size of the buffer. + // @error Invalid iterator position. + public native void GetName(char[] buffer, int maxlen); + + // Retrieves the plugin handle of the command's creator + // + // @error Invalid iterator position. + property Handle Plugin { + public native get(); + } + + // Retrieves the command's default flags + // + // @error Invalid iterator position. + property int Flags { + public native get(); + } +} + /** * Gets a command iterator. Must be freed with CloseHandle(). * - * @return A new command iterator. + * @return A new command iterator. */ native Handle GetCommandIterator(); @@ -444,13 +490,13 @@ native Handle GetCommandIterator(); * Reads a command iterator, then advances to the next command if any. * Only SourceMod specific commands are returned. * - * @param iter Command iterator Handle. - * @param name Name buffer. - * @param nameLen Name buffer size. - * @param eflags Effective default flags of a command. - * @param desc Command description buffer. - * @param descLen Command description buffer size. - * @return True on success, false if there are no more commands. + * @param iter Command iterator Handle. + * @param name Name buffer. + * @param nameLen Name buffer size. + * @param eflags Effective default flags of a command. + * @param desc Command description buffer. + * @param descLen Command description buffer size. + * @return True on success, false if there are no more commands. */ native bool ReadCommandIterator(Handle iter, char[] name, @@ -465,16 +511,16 @@ native bool ReadCommandIterator(Handle iter, * commands. This feature essentially allows you to create custom * flags using the override system. * - * @param client Client index. - * @param command Command name. If the command is not found, the default - * flags are used. - * @param flags Flag string to use as a default, if the command or override - * is not found. - * @param override_only If true, SourceMod will not attempt to find a matching - * command, and it will only use the default flags specified. - * Otherwise, SourceMod will ignore the default flags if - * there is a matching admin command. - * @return True if the client has access, false otherwise. + * @param client Client index. + * @param command Command name. If the command is not found, the default + * flags are used. + * @param flags Flag string to use as a default, if the command or override + * is not found. + * @param override_only If true, SourceMod will not attempt to find a matching + * command, and it will only use the default flags specified. + * Otherwise, SourceMod will ignore the default flags if + * there is a matching admin command. + * @return True if the client has access, false otherwise. */ native bool CheckCommandAccess(int client, const char[] command, @@ -487,16 +533,16 @@ native bool CheckCommandAccess(int client, * commands. This feature essentially allows you to create custom flags * using the override system. * - * @param id AdminId of the admin. - * @param command Command name. If the command is not found, the default - * flags are used. - * @param flags Flag string to use as a default, if the command or override - * is not found. - * @param override_only If true, SourceMod will not attempt to find a matching - * command, and it will only use the default flags specified. - * Otherwise, SourceMod will ignore the default flags if - * there is a matching admin command. - * @return True if the admin has access, false otherwise. + * @param id AdminId of the admin. + * @param command Command name. If the command is not found, the default + * flags are used. + * @param flags Flag string to use as a default, if the command or override + * is not found. + * @param override_only If true, SourceMod will not attempt to find a matching + * command, and it will only use the default flags specified. + * Otherwise, SourceMod will ignore the default flags if + * there is a matching admin command. + * @return True if the admin has access, false otherwise. */ native bool CheckAccess(AdminId id, const char[] command, @@ -506,18 +552,18 @@ native bool CheckAccess(AdminId id, /** * Returns the bitstring of flags of a command. * - * @param name Name of the command. - * @return A bitstring containing the FCVAR_* flags that are enabled - * or INVALID_FCVAR_FLAGS if command not found. + * @param name Name of the command. + * @return A bitstring containing the FCVAR_* flags that are enabled + * or INVALID_FCVAR_FLAGS if command not found. */ native int GetCommandFlags(const char[] name); /** * Sets the bitstring of flags of a command. * - * @param name Name of the command. - * @param flags A bitstring containing the FCVAR_* flags to enable. - * @return True on success, otherwise false. + * @param name Name of the command. + * @param flags A bitstring containing the FCVAR_* flags to enable. + * @return True on success, otherwise false. */ native bool SetCommandFlags(const char[] name, int flags); @@ -526,38 +572,38 @@ native bool SetCommandFlags(const char[] name, int flags); * ConCommands. If a Handle is returned, the next entry must be read * via FindNextConCommand(). The order of the list is undefined. * - * @param buffer Buffer to store entry name. - * @param max_size Maximum size of the buffer. - * @param isCommand Variable to store whether the entry is a command. - * If it is not a command, it is a ConVar. - * @param flags Variable to store entry flags. - * @param description Buffer to store the description, empty if no description present. - * @param descrmax_size Maximum size of the description buffer. - * @return On success, a ConCmdIter Handle is returned, which - * can be read via FindNextConCommand(), and must be - * closed via CloseHandle(). Additionally, the output - * parameters will be filled with information of the - * first ConCommandBase entry. - * On failure, INVALID_HANDLE is returned, and the - * contents of outputs is undefined. + * @param buffer Buffer to store entry name. + * @param max_size Maximum size of the buffer. + * @param isCommand Variable to store whether the entry is a command. + * If it is not a command, it is a ConVar. + * @param flags Variable to store entry flags. + * @param description Buffer to store the description, empty if no description present. + * @param descrmax_size Maximum size of the description buffer. + * @return On success, a ConCmdIter Handle is returned, which + can be read via FindNextConCommand(), and must be + closed via CloseHandle(). Additionally, the output + parameters will be filled with information of the + first ConCommandBase entry. + On failure, INVALID_HANDLE is returned, and the + contents of outputs is undefined. */ native Handle FindFirstConCommand(char[] buffer, int max_size, bool &isCommand, int &flags=0, char[] description="", int descrmax_size=0); /** * Reads the next entry in a ConCommandBase iterator. * - * @param search ConCmdIter Handle to search. - * @param buffer Buffer to store entry name. - * @param max_size Maximum size of the buffer. - * @param isCommand Variable to store whether the entry is a command. - * If it is not a command, it is a ConVar. - * @param flags Variable to store entry flags. - * @param description Buffer to store the description, empty if no description present. - * @param descrmax_size Maximum size of the description buffer. - * @return On success, the outputs are filled, the iterator is - * advanced to the next entry, and true is returned. - * If no more entries exist, false is returned, and the - * contents of outputs is undefined. + * @param search ConCmdIter Handle to search. + * @param buffer Buffer to store entry name. + * @param max_size Maximum size of the buffer. + * @param isCommand Variable to store whether the entry is a command. + If it is not a command, it is a ConVar. + * @param flags Variable to store entry flags. + * @param description Buffer to store the description, empty if no description present. + * @param descrmax_size Maximum size of the description buffer. + * @return On success, the outputs are filled, the iterator is + advanced to the next entry, and true is returned. + If no more entries exist, false is returned, and the + contents of outputs is undefined. */ native bool FindNextConCommand(Handle search, char[] buffer, int max_size, bool &isCommand, int &flags=0, char[] description="", int descrmax_size=0); @@ -568,14 +614,14 @@ native bool FindNextConCommand(Handle search, char[] buffer, int max_size, bool * Note: Tags are automatically removed when a plugin unloads. * Note: Currently, this function does nothing because of bugs in the Valve master. * - * @param tag Tag string to append. + * @param tag Tag string to append. */ native void AddServerTag(const char[] tag); /** * Removes a tag previously added by the calling plugin. * - * @param tag Tag string to remove. + * @param tag Tag string to remove. */ native void RemoveServerTag(const char[] tag); @@ -601,7 +647,7 @@ native void RemoveServerTag(const char[] tag); * @param command Command name, lower case. To get name as typed, use * GetCmdArg() and specify argument 0. * @param argc Argument count. - * @return Action to take (see extended notes above). + * @return Action to take (see extended notes above). */ typedef CommandListener = function Action (int client, const char[] command, int argc); @@ -619,7 +665,7 @@ typedef CommandListener = function Action (int client, const char[] command, int * FEATURECAP_COMMANDLISTENER. * * @param callback Callback. - * @param command Command, or if not specified, a global listener. + * @param command Command, or if not specified, a global listener. * The command is case insensitive. * @return True if this feature is available on the current game, * false otherwise. @@ -629,18 +675,18 @@ native bool AddCommandListener(CommandListener callback, const char[] command="" /** * Removes a previously added command listener, in reverse order of being added. * - * @param callback Callback. - * @param command Command, or if not specified, a global listener. + * @param callback Callback. + * @param command Command, or if not specified, a global listener. * The command is case insensitive. - * @error Callback has no active listeners. + * @error Callback has no active listeners. */ native void RemoveCommandListener(CommandListener callback, const char[] command=""); /** * Returns true if the supplied command exists. * - * @param command Command to find. - * @return True if command is found, false otherwise. + * @param command Command to find. + * @return True if command is found, false otherwise. */ stock bool CommandExists(const char[] command) { @@ -649,20 +695,20 @@ stock bool CommandExists(const char[] command) /** * Global listener for the chat commands. * - * @param client Client index. - * @param command Command name. - * @param sArgs Chat argument string. + * @param client Client index. + * @param command Command name. + * @param sArgs Chat argument string. * - * @return An Action value. Returning Plugin_Handled bypasses the game function call. - Returning Plugin_Stop bypasses the post hook as well as the game function. + * @return An Action value. Returning Plugin_Handled bypasses the game function call. + * Returning Plugin_Stop bypasses the post hook as well as the game function. */ forward Action OnClientSayCommand(int client, const char[] command, const char[] sArgs); /** * Global post listener for the chat commands. * - * @param client Client index. - * @param command Command name. - * @param sArgs Chat argument string. + * @param client Client index. + * @param command Command name. + * @param sArgs Chat argument string. */ forward void OnClientSayCommand_Post(int client, const char[] command, const char[] sArgs); diff --git a/addons/sourcemod/scripting/include/convars.inc b/addons/sourcemod/scripting/include/convars.inc index 6896ce1..7bc9f77 100644 --- a/addons/sourcemod/scripting/include/convars.inc +++ b/addons/sourcemod/scripting/include/convars.inc @@ -31,7 +31,7 @@ */ #if defined _convars_included - #endinput + #endinput #endif #define _convars_included @@ -49,31 +49,35 @@ enum ConVarBounds */ enum ConVarQueryResult { - ConVarQuery_Okay = 0, //< Retrieval of client convar value was successful. */ - ConVarQuery_NotFound, //< Client convar was not found. */ - ConVarQuery_NotValid, //< A console command with the same name was found, but there is no convar. */ - ConVarQuery_Protected //< Client convar was found, but it is protected. The server cannot retrieve its value. */ + ConVarQuery_Okay = 0, //< Retrieval of client convar value was successful. */ + ConVarQuery_NotFound, //< Client convar was not found. */ + ConVarQuery_NotValid, //< A console command with the same name was found, but there is no convar. */ + ConVarQuery_Protected //< Client convar was found, but it is protected. The server cannot retrieve its value. */ }; -// Called when a console variable's value is changed. -// -// @param convar Handle to the convar that was changed. -// @param oldValue String containing the value of the convar before it was changed. -// @param newValue String containing the new value of the convar. +/** + * Called when a console variable's value is changed. + * + * @param convar Handle to the convar that was changed. + * @param oldValue String containing the value of the convar before it was changed. + * @param newValue String containing the new value of the convar. + */ typedef ConVarChanged = function void (ConVar convar, const char[] oldValue, const char[] newValue); -// Creates a new console variable. -// -// @param name Name of new convar. -// @param defaultValue String containing the default value of new convar. -// @param description Optional description of the convar. -// @param flags Optional bitstring of flags determining how the convar should be handled. See FCVAR_* constants for more details. -// @param hasMin Optional boolean that determines if the convar has a minimum value. -// @param min Minimum floating point value that the convar can have if hasMin is true. -// @param hasMax Optional boolean that determines if the convar has a maximum value. -// @param max Maximum floating point value that the convar can have if hasMax is true. -// @return A handle to the newly created convar. If the convar already exists, a handle to it will still be returned. -// @error Convar name is blank or is the same as an existing console command. +/** + * Creates a new console variable. + * + * @param name Name of new convar. + * @param defaultValue String containing the default value of new convar. + * @param description Optional description of the convar. + * @param flags Optional bitstring of flags determining how the convar should be handled. See FCVAR_* constants for more details. + * @param hasMin Optional boolean that determines if the convar has a minimum value. + * @param min Minimum floating point value that the convar can have if hasMin is true. + * @param hasMax Optional boolean that determines if the convar has a maximum value. + * @param max Maximum floating point value that the convar can have if hasMax is true. + * @return A handle to the newly created convar. If the convar already exists, a handle to it will still be returned. + * @error Convar name is blank or is the same as an existing console command. + */ native ConVar CreateConVar( const char[] name, const char[] defaultValue, @@ -82,10 +86,12 @@ native ConVar CreateConVar( bool hasMin=false, float min=0.0, bool hasMax=false, float max=0.0); -// Searches for a console variable. -// -// @param name Name of convar to find. -// @return A ConVar object if found; null otherwise. +/** + * Searches for a console variable. + * + * @param name Name of convar to find. + * @return A ConVar object if found; null otherwise. + */ native ConVar FindConVar(const char[] name); // A ConVar is a configurable, named setting in the srcds console. @@ -242,27 +248,27 @@ methodmap ConVar < Handle /** * Creates a hook for when a console variable's value is changed. * - * @param convar Handle to the convar. - * @param callback An OnConVarChanged function pointer. - * @error Invalid or corrupt Handle or invalid callback function. + * @param convar Handle to the convar. + * @param callback An OnConVarChanged function pointer. + * @error Invalid or corrupt Handle or invalid callback function. */ native void HookConVarChange(Handle convar, ConVarChanged callback); /** * Removes a hook for when a console variable's value is changed. * - * @param convar Handle to the convar. - * @param callback An OnConVarChanged function pointer. - * @error Invalid or corrupt Handle, invalid callback function, or no active hook on convar. + * @param convar Handle to the convar. + * @param callback An OnConVarChanged function pointer. + * @error Invalid or corrupt Handle, invalid callback function, or no active hook on convar. */ native void UnhookConVarChange(Handle convar, ConVarChanged callback); /** * Returns the boolean value of a console variable. * - * @param convar Handle to the convar. - * @return The boolean value of the convar. - * @error Invalid or corrupt Handle. + * @param convar Handle to the convar. + * @return The boolean value of the convar. + * @error Invalid or corrupt Handle. */ native bool GetConVarBool(Handle convar); @@ -272,23 +278,23 @@ native bool GetConVarBool(Handle convar); * Note: The replicate and notify params are only relevant for the original, Dark Messiah, and * Episode 1 engines. Newer engines automatically do these things when the convar value is changed. * - * @param convar Handle to the convar. - * @param value New boolean value. - * @param replicate If set to true, the new convar value will be set on all clients. - * This will only work if the convar has the FCVAR_REPLICATED flag - * and actually exists on clients. - * @param notify If set to true, clients will be notified that the convar has changed. - * This will only work if the convar has the FCVAR_NOTIFY flag. - * @error Invalid or corrupt Handle. + * @param convar Handle to the convar. + * @param value New boolean value. + * @param replicate If set to true, the new convar value will be set on all clients. + * This will only work if the convar has the FCVAR_REPLICATED flag + * and actually exists on clients. + * @param notify If set to true, clients will be notified that the convar has changed. + * This will only work if the convar has the FCVAR_NOTIFY flag. + * @error Invalid or corrupt Handle. */ native void SetConVarBool(Handle convar, bool value, bool replicate=false, bool notify=false); /** * Returns the integer value of a console variable. * - * @param convar Handle to the convar. - * @return The integer value of the convar. - * @error Invalid or corrupt Handle. + * @param convar Handle to the convar. + * @return The integer value of the convar. + * @error Invalid or corrupt Handle. */ native int GetConVarInt(Handle convar); @@ -298,23 +304,23 @@ native int GetConVarInt(Handle convar); * Note: The replicate and notify params are only relevant for the original, Dark Messiah, and * Episode 1 engines. Newer engines automatically do these things when the convar value is changed. * - * @param convar Handle to the convar. - * @param value New integer value. - * @param replicate If set to true, the new convar value will be set on all clients. - * This will only work if the convar has the FCVAR_REPLICATED flag - * and actually exists on clients. - * @param notify If set to true, clients will be notified that the convar has changed. - * This will only work if the convar has the FCVAR_NOTIFY flag. - * @error Invalid or corrupt Handle. + * @param convar Handle to the convar. + * @param value New integer value. + * @param replicate If set to true, the new convar value will be set on all clients. + * This will only work if the convar has the FCVAR_REPLICATED flag + * and actually exists on clients. + * @param notify If set to true, clients will be notified that the convar has changed. + * This will only work if the convar has the FCVAR_NOTIFY flag. + * @error Invalid or corrupt Handle. */ native void SetConVarInt(Handle convar, int value, bool replicate=false, bool notify=false); /** * Returns the floating point value of a console variable. * - * @param convar Handle to the convar. - * @return The floating point value of the convar. - * @error Invalid or corrupt Handle. + * @param convar Handle to the convar. + * @return The floating point value of the convar. + * @error Invalid or corrupt Handle. */ native float GetConVarFloat(Handle convar); @@ -324,24 +330,24 @@ native float GetConVarFloat(Handle convar); * Note: The replicate and notify params are only relevant for the original, Dark Messiah, and * Episode 1 engines. Newer engines automatically do these things when the convar value is changed. * - * @param convar Handle to the convar. - * @param value New floating point value. - * @param replicate If set to true, the new convar value will be set on all clients. - * This will only work if the convar has the FCVAR_REPLICATED flag - * and actually exists on clients. - * @param notify If set to true, clients will be notified that the convar has changed. - * This will only work if the convar has the FCVAR_NOTIFY flag. - * @error Invalid or corrupt Handle. + * @param convar Handle to the convar. + * @param value New floating point value. + * @param replicate If set to true, the new convar value will be set on all clients. + * This will only work if the convar has the FCVAR_REPLICATED flag + * and actually exists on clients. + * @param notify If set to true, clients will be notified that the convar has changed. + * This will only work if the convar has the FCVAR_NOTIFY flag. + * @error Invalid or corrupt Handle. */ native void SetConVarFloat(Handle convar, float value, bool replicate=false, bool notify=false); /** * Retrieves the string value of a console variable. * - * @param convar Handle to the convar. - * @param value Buffer to store the value of the convar. - * @param maxlength Maximum length of string buffer. - * @error Invalid or corrupt Handle. + * @param convar Handle to the convar. + * @param value Buffer to store the value of the convar. + * @param maxlength Maximum length of string buffer. + * @error Invalid or corrupt Handle. */ native void GetConVarString(Handle convar, char[] value, int maxlength); @@ -351,14 +357,14 @@ native void GetConVarString(Handle convar, char[] value, int maxlength); * Note: The replicate and notify params are only relevant for the original, Dark Messiah, and * Episode 1 engines. Newer engines automatically do these things when the convar value is changed. * - * @param convar Handle to the convar. - * @param value New string value. - * @param replicate If set to true, the new convar value will be set on all clients. - * This will only work if the convar has the FCVAR_REPLICATED flag - * and actually exists on clients. - * @param notify If set to true, clients will be notified that the convar has changed. - * This will only work if the convar has the FCVAR_NOTIFY flag. - * @error Invalid or corrupt Handle. + * @param convar Handle to the convar. + * @param value New string value. + * @param replicate If set to true, the new convar value will be set on all clients. + * This will only work if the convar has the FCVAR_REPLICATED flag + * and actually exists on clients. + * @param notify If set to true, clients will be notified that the convar has changed. + * This will only work if the convar has the FCVAR_NOTIFY flag. + * @error Invalid or corrupt Handle. */ native void SetConVarString(Handle convar, const char[] value, bool replicate=false, bool notify=false); @@ -368,85 +374,85 @@ native void SetConVarString(Handle convar, const char[] value, bool replicate=fa * Note: The replicate and notify params are only relevant for the original, Dark Messiah, and * Episode 1 engines. Newer engines automatically do these things when the convar value is changed. * - * @param convar Handle to the convar. - * @param replicate If set to true, the new convar value will be set on all clients. - * This will only work if the convar has the FCVAR_REPLICATED flag - * and actually exists on clients. - * @param notify If set to true, clients will be notified that the convar has changed. - * This will only work if the convar has the FCVAR_NOTIFY flag. - * @error Invalid or corrupt Handle. + * @param convar Handle to the convar. + * @param replicate If set to true, the new convar value will be set on all clients. + * This will only work if the convar has the FCVAR_REPLICATED flag + * and actually exists on clients. + * @param notify If set to true, clients will be notified that the convar has changed. + * This will only work if the convar has the FCVAR_NOTIFY flag. + * @error Invalid or corrupt Handle. */ native void ResetConVar(Handle convar, bool replicate=false, bool notify=false); /** * Retrieves the default string value of a console variable. * - * @param convar Handle to the convar. - * @param value Buffer to store the default value of the convar. - * @param maxlength Maximum length of string buffer. - * @return Number of bytes written to the buffer (UTF-8 safe). - * @error Invalid or corrupt Handle. + * @param convar Handle to the convar. + * @param value Buffer to store the default value of the convar. + * @param maxlength Maximum length of string buffer. + * @return Number of bytes written to the buffer (UTF-8 safe). + * @error Invalid or corrupt Handle. */ native int GetConVarDefault(Handle convar, char[] value, int maxlength); /** * Returns the bitstring of flags on a console variable. * - * @param convar Handle to the convar. - * @return A bitstring containing the FCVAR_* flags that are enabled. - * @error Invalid or corrupt Handle. + * @param convar Handle to the convar. + * @return A bitstring containing the FCVAR_* flags that are enabled. + * @error Invalid or corrupt Handle. */ native int GetConVarFlags(Handle convar); /** * Sets the bitstring of flags on a console variable. * - * @param convar Handle to the convar. - * @param flags A bitstring containing the FCVAR_* flags to enable. - * @error Invalid or corrupt Handle. + * @param convar Handle to the convar. + * @param flags A bitstring containing the FCVAR_* flags to enable. + * @error Invalid or corrupt Handle. */ native void SetConVarFlags(Handle convar, int flags); /** * Retrieves the specified bound of a console variable. * - * @param convar Handle to the convar. - * @param type Type of bound to retrieve, ConVarBound_Lower or ConVarBound_Upper. - * @param value By-reference cell to store the specified floating point bound value. - * @return True if the convar has the specified bound set, false otherwise. - * @error Invalid or corrupt Handle. + * @param convar Handle to the convar. + * @param type Type of bound to retrieve, ConVarBound_Lower or ConVarBound_Upper. + * @param value By-reference cell to store the specified floating point bound value. + * @return True if the convar has the specified bound set, false otherwise. + * @error Invalid or corrupt Handle. */ native bool GetConVarBounds(Handle convar, ConVarBounds type, float &value); /** * Sets the specified bound of a console variable. * - * @param convar Handle to the convar. - * @param type Type of bound to set, ConVarBound_Lower or ConVarBound_Upper - * @param set If set to true, convar will use specified bound. If false, bound will be removed. - * @param value Floating point value to use as the specified bound. - * @error Invalid or corrupt Handle. + * @param convar Handle to the convar. + * @param type Type of bound to set, ConVarBound_Lower or ConVarBound_Upper + * @param set If set to true, convar will use specified bound. If false, bound will be removed. + * @param value Floating point value to use as the specified bound. + * @error Invalid or corrupt Handle. */ native void SetConVarBounds(Handle convar, ConVarBounds type, bool set, float value=0.0); /** * Retrieves the name of a console variable. * - * @param convar Handle to the convar. - * @param name Buffer to store the name of the convar. - * @param maxlength Maximum length of string buffer. - * @error Invalid or corrupt Handle. + * @param convar Handle to the convar. + * @param name Buffer to store the name of the convar. + * @param maxlength Maximum length of string buffer. + * @error Invalid or corrupt Handle. */ native void GetConVarName(Handle convar, char[] name, int maxlength); /** * Replicates a convar value to a specific client. This does not change the actual convar value. * - * @param client Client index - * @param convar ConVar handle - * @param value String value to send - * @return True on success, false on failure - * @error Invalid client index, client not in game, or client is fake + * @param client Client index + * @param convar ConVar handle + * @param value String value to send + * @return True on success, false on failure + * @error Invalid client index, client not in game, or client is fake */ native bool SendConVarValue(int client, Handle convar, const char[] value); @@ -454,43 +460,43 @@ typeset ConVarQueryFinished { // Called when a query to retrieve a client's console variable has finished. // - // @param cookie Unique identifier of query. - // @param client Player index. - // @param result Result of query that tells one whether or not query was successful. - // See ConVarQueryResult enum for more details. - // @param convarName Name of client convar that was queried. - // @param convarValue Value of client convar that was queried if successful. This will be "" if it was not. - // @param value Value that was passed when query was started. + // @param cookie Unique identifier of query. + // @param client Player index. + // @param result Result of query that tells one whether or not query was successful. + // See ConVarQueryResult enum for more details. + // @param convarName Name of client convar that was queried. + // @param convarValue Value of client convar that was queried if successful. This will be "" if it was not. + // @param value Value that was passed when query was started. function void (QueryCookie cookie, int client, ConVarQueryResult result, const char[] cvarName, const char[] cvarValue, any value); // Called when a query to retrieve a client's console variable has finished. // - // @param cookie Unique identifier of query. - // @param client Player index. - // @param result Result of query that tells one whether or not query was successful. - // See ConVarQueryResult enum for more details. - // @param convarName Name of client convar that was queried. - // @param convarValue Value of client convar that was queried if successful. This will be "" if it was not. + // @param cookie Unique identifier of query. + // @param client Player index. + // @param result Result of query that tells one whether or not query was successful. + // See ConVarQueryResult enum for more details. + // @param convarName Name of client convar that was queried. + // @param convarValue Value of client convar that was queried if successful. This will be "" if it was not. function void (QueryCookie cookie, int client, ConVarQueryResult result, const char[] cvarName, const char[] cvarValue); }; /** * Starts a query to retrieve the value of a client's console variable. * - * @param client Player index. - * @param cvarName Name of client convar to query. - * @param callback A function to use as a callback when the query has finished. - * @param value Optional value to pass to the callback function. - * @return A cookie that uniquely identifies the query. - * Returns QUERYCOOKIE_FAILED on failure, such as when used on a bot. + * @param client Player index. + * @param cvarName Name of client convar to query. + * @param callback A function to use as a callback when the query has finished. + * @param value Optional value to pass to the callback function. + * @return A cookie that uniquely identifies the query. + * Returns QUERYCOOKIE_FAILED on failure, such as when used on a bot. */ native QueryCookie QueryClientConVar(int client, const char[] cvarName, ConVarQueryFinished callback, any value=0); /** * Returns true if the supplied character is valid in a ConVar name. * - * @param c Character to validate. - * @return True is valid for ConVars, false otherwise + * @param c Character to validate. + * @return True is valid for ConVars, false otherwise */ stock bool IsValidConVarChar(int c) { diff --git a/addons/sourcemod/scripting/include/core.inc b/addons/sourcemod/scripting/include/core.inc index 85d9502..8fed55c 100644 --- a/addons/sourcemod/scripting/include/core.inc +++ b/addons/sourcemod/scripting/include/core.inc @@ -38,7 +38,7 @@ #include /** If this gets changed, you need to update Core's check. */ -#define SOURCEMOD_PLUGINAPI_VERSION 5 +#define SOURCEMOD_PLUGINAPI_VERSION 5 struct PlVers { @@ -53,10 +53,10 @@ struct PlVers */ enum Action { - Plugin_Continue = 0, /**< Continue with the original action */ - Plugin_Changed = 1, /**< Inputs or outputs have been overridden with new values */ - Plugin_Handled = 3, /**< Handle the action at the end (don't call it) */ - Plugin_Stop = 4, /**< Immediately stop the hook chain and handle the original */ + Plugin_Continue = 0, /**< Continue with the original action */ + Plugin_Changed = 1, /**< Inputs or outputs have been overridden with new values */ + Plugin_Handled = 3, /**< Handle the action at the end (don't call it) */ + Plugin_Stop = 4 /**< Immediately stop the hook chain and handle the original */ }; /** @@ -82,17 +82,17 @@ public PlVers __version = */ enum PluginStatus { - Plugin_Running=0, /**< Plugin is running */ + Plugin_Running=0, /**< Plugin is running */ /* All states below are "temporarily" unexecutable */ - Plugin_Paused, /**< Plugin is loaded but paused */ - Plugin_Error, /**< Plugin is loaded but errored/locked */ + Plugin_Paused, /**< Plugin is loaded but paused */ + Plugin_Error, /**< Plugin is loaded but errored/locked */ /* All states below do not have all natives */ - Plugin_Loaded, /**< Plugin has passed loading and can be finalized */ - Plugin_Failed, /**< Plugin has a fatal failure */ - Plugin_Created, /**< Plugin is created but not initialized */ - Plugin_Uncompiled, /**< Plugin is not yet compiled by the JIT */ - Plugin_BadLoad, /**< Plugin failed to load */ - Plugin_Evicted /**< Plugin was unloaded due to an error */ + Plugin_Loaded, /**< Plugin has passed loading and can be finalized */ + Plugin_Failed, /**< Plugin has a fatal failure */ + Plugin_Created, /**< Plugin is created but not initialized */ + Plugin_Uncompiled, /**< Plugin is not yet compiled by the JIT */ + Plugin_BadLoad, /**< Plugin failed to load */ + Plugin_Evicted /**< Plugin was unloaded due to an error */ }; /** @@ -112,11 +112,11 @@ enum PluginStatus */ enum PluginInfo { - PlInfo_Name, /**< Plugin name */ - PlInfo_Author, /**< Plugin author */ - PlInfo_Description, /**< Plugin description */ - PlInfo_Version, /**< Plugin version */ - PlInfo_URL, /**< Plugin URL */ + PlInfo_Name, /**< Plugin name */ + PlInfo_Author, /**< Plugin author */ + PlInfo_Description, /**< Plugin description */ + PlInfo_Version, /**< Plugin version */ + PlInfo_URL /**< Plugin URL */ }; /** @@ -124,10 +124,10 @@ enum PluginInfo */ struct Extension { - public const char[] name; /**< Short name */ - public const char[] file; /**< Default file name */ - public bool autoload; /**< Whether or not to auto-load */ - public bool required; /**< Whether or not to require */ + public const char[] name; /**< Short name */ + public const char[] file; /**< Default file name */ + public bool autoload; /**< Whether or not to auto-load */ + public bool required; /**< Whether or not to require */ }; /** @@ -135,13 +135,13 @@ struct Extension */ struct SharedPlugin { - public const char[] name; /**< Short name */ - public const char[] file; /**< File name */ - public bool required; /**< Whether or not to require */ + public const char[] name; /**< Short name */ + public const char[] file; /**< File name */ + public bool required; /**< Whether or not to require */ }; -public float NULL_VECTOR[3]; /**< Pass this into certain functions to act as a C++ NULL */ -public const char NULL_STRING[1]; /**< pass this into certain functions to act as a C++ NULL */ +public float NULL_VECTOR[3]; /**< Pass this into certain functions to act as a C++ NULL */ +public const char NULL_STRING[1]; /**< pass this into certain functions to act as a C++ NULL */ /** * Check if the given vector is the NULL_VECTOR. @@ -177,7 +177,7 @@ native int VerifyCoreVersion(); * or otherwise non-existent, the plugin will still work. Calling * removed natives results in a run-time error. * - * @param name Native name. + * @param name Native name. */ native void MarkNativeAsOptional(const char[] name); @@ -187,7 +187,7 @@ public void __ext_core_SetNTVOptional() MarkNativeAsOptional("RequireFeature"); MarkNativeAsOptional("AddCommandListener"); MarkNativeAsOptional("RemoveCommandListener"); - + MarkNativeAsOptional("BfWriteBool"); MarkNativeAsOptional("BfWriteByte"); MarkNativeAsOptional("BfWriteChar"); @@ -246,8 +246,8 @@ public void __ext_core_SetNTVOptional() MarkNativeAsOptional("BfRead.ReadVecCoord"); MarkNativeAsOptional("BfRead.ReadVecNormal"); MarkNativeAsOptional("BfRead.ReadAngles"); - MarkNativeAsOptional("BfRead.GetNumBytesLeft"); - + MarkNativeAsOptional("BfRead.BytesLeft.get"); + MarkNativeAsOptional("PbReadInt"); MarkNativeAsOptional("PbReadFloat"); MarkNativeAsOptional("PbReadBool"); @@ -279,6 +279,7 @@ public void __ext_core_SetNTVOptional() MarkNativeAsOptional("PbAddMessage"); MarkNativeAsOptional("Protobuf.ReadInt"); + MarkNativeAsOptional("Protobuf.ReadInt64"); MarkNativeAsOptional("Protobuf.ReadFloat"); MarkNativeAsOptional("Protobuf.ReadBool"); MarkNativeAsOptional("Protobuf.ReadString"); @@ -288,6 +289,7 @@ public void __ext_core_SetNTVOptional() MarkNativeAsOptional("Protobuf.ReadVector2D"); MarkNativeAsOptional("Protobuf.GetRepeatedFieldCount"); MarkNativeAsOptional("Protobuf.SetInt"); + MarkNativeAsOptional("Protobuf.SetInt64"); MarkNativeAsOptional("Protobuf.SetFloat"); MarkNativeAsOptional("Protobuf.SetBool"); MarkNativeAsOptional("Protobuf.SetString"); @@ -296,6 +298,7 @@ public void __ext_core_SetNTVOptional() MarkNativeAsOptional("Protobuf.SetVector"); MarkNativeAsOptional("Protobuf.SetVector2D"); MarkNativeAsOptional("Protobuf.AddInt"); + MarkNativeAsOptional("Protobuf.AddInt64"); MarkNativeAsOptional("Protobuf.AddFloat"); MarkNativeAsOptional("Protobuf.AddBool"); MarkNativeAsOptional("Protobuf.AddString"); @@ -307,7 +310,7 @@ public void __ext_core_SetNTVOptional() MarkNativeAsOptional("Protobuf.ReadMessage"); MarkNativeAsOptional("Protobuf.ReadRepeatedMessage"); MarkNativeAsOptional("Protobuf.AddMessage"); - + VerifyCoreVersion(); } diff --git a/addons/sourcemod/scripting/include/csgocolors.inc b/addons/sourcemod/scripting/include/csgocolors.inc new file mode 100644 index 0000000..74eda93 --- /dev/null +++ b/addons/sourcemod/scripting/include/csgocolors.inc @@ -0,0 +1,559 @@ +/************************************************************************** +* * +* Colored Chat Functions * +* Author: exvel, Editor: Popoklopsi, Powerlord, Bara * +* Version: 1.1.3 * +* * +**************************************************************************/ + + +#if defined _colors_included +#endinput +#endif +#define _colors_included + +#define MAX_MESSAGE_LENGTH 250 +#define MAX_COLORS 16 + +#define SERVER_INDEX 0 +#define NO_INDEX -1 +#define NO_PLAYER -2 + +enum Colors +{ + Color_Default = 0, + Color_Darkred, + Color_Pink, + Color_Green, + Color_Lightgreen, + Color_Lime, + Color_Red, + Color_Grey, + Color_Olive, + Color_A, + Color_Lightblue, + Color_Blue, + Color_D, + Color_Purple, + Color_Darkrange, + Color_Orange +} + +/* Colors' properties */ +new String:CTag[][] = {"{normal}", "{darkred}", "{pink}", "{green}", "{lightgreen}", "{lime}", "{red}", "{grey}", "{olive}", "{a}", "{lightblue}", "{blue}", "{d}", "{purple}", "{darkorange}", "{orange}"}; +new String:CTagCode[][] = {"\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07", "\x08", "\x09", "\x0A", "\x0B", "\x0C", "\x0D", "\x0E", "\x0F", "\x10"}; +new bool:CTagReqSayText2[] = {false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false}; +new bool:CEventIsHooked = false; +new bool:CSkipList[MAXPLAYERS+1] = {false,...}; + +/* Game default profile */ +new bool:CProfile_Colors[] = {true, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false}; +new CProfile_TeamIndex[] = {NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX}; +new bool:CProfile_SayText2 = false; + +/** +* Prints a message to a specific client in the chat area. +* Supports color tags. +* +* @param client Client index. +* @param szMessage Message (formatting rules). +* @return No return +* +* On error/Errors: If the client is not connected an error will be thrown. +*/ +stock CPrintToChat(client, const String:szMessage[], any:...) +{ + if (client <= 0 || client > MaxClients) + ThrowError("Invalid client index %d", client); + + if (!IsClientInGame(client)) + ThrowError("Client %d is not in game", client); + + decl String:szBuffer[MAX_MESSAGE_LENGTH]; + decl String:szCMessage[MAX_MESSAGE_LENGTH]; + + SetGlobalTransTarget(client); + + Format(szBuffer, sizeof(szBuffer), "\x01%s", szMessage); + VFormat(szCMessage, sizeof(szCMessage), szBuffer, 3); + + new index = CFormat(szCMessage, sizeof(szCMessage)); + + if (index == NO_INDEX) + PrintToChat(client, "%s", szCMessage); + else + CSayText2(client, index, szCMessage); +} + +stock CReplyToCommand(client, const String:szMessage[], any:...) +{ + + decl String:szCMessage[MAX_MESSAGE_LENGTH]; + VFormat(szCMessage, sizeof(szCMessage), szMessage, 3); + + if (client == 0) + { + CRemoveTags(szCMessage, sizeof(szCMessage)); + PrintToServer("%s", szCMessage); + } + else if (GetCmdReplySource() == SM_REPLY_TO_CONSOLE) + { + CRemoveTags(szCMessage, sizeof(szCMessage)); + PrintToConsole(client, "%s", szCMessage); + } + else + { + CPrintToChat(client, "%s", szCMessage); + } +} + + +/** +* Prints a message to all clients in the chat area. +* Supports color tags. +* +* @param client Client index. +* @param szMessage Message (formatting rules) +* @return No return +*/ +stock CPrintToChatAll(const String:szMessage[], any:...) +{ + decl String:szBuffer[MAX_MESSAGE_LENGTH]; + + for (new i = 1; i <= MaxClients; i++) + { + if (IsClientInGame(i) && !IsFakeClient(i) && !CSkipList[i]) + { + SetGlobalTransTarget(i); + VFormat(szBuffer, sizeof(szBuffer), szMessage, 2); + + CPrintToChat(i, "%s", szBuffer); + } + + CSkipList[i] = false; + } +} + +/** +* Prints a message to a specific client in the chat area. +* Supports color tags and teamcolor tag. +* +* @param client Client index. +* @param author Author index whose color will be used for teamcolor tag. +* @param szMessage Message (formatting rules). +* @return No return +* +* On error/Errors: If the client or author are not connected an error will be thrown. +*/ +stock CPrintToChatEx(client, author, const String:szMessage[], any:...) +{ + if (client <= 0 || client > MaxClients) + ThrowError("Invalid client index %d", client); + + if (!IsClientInGame(client)) + ThrowError("Client %d is not in game", client); + + if (author < 0 || author > MaxClients) + ThrowError("Invalid client index %d", author); + + decl String:szBuffer[MAX_MESSAGE_LENGTH]; + decl String:szCMessage[MAX_MESSAGE_LENGTH]; + + SetGlobalTransTarget(client); + + Format(szBuffer, sizeof(szBuffer), "\x01%s", szMessage); + VFormat(szCMessage, sizeof(szCMessage), szBuffer, 4); + + new index = CFormat(szCMessage, sizeof(szCMessage), author); + + if (index == NO_INDEX) + PrintToChat(client, "%s", szCMessage); + else + CSayText2(client, author, szCMessage); +} + +/** +* Prints a message to all clients in the chat area. +* Supports color tags and teamcolor tag. +* +* @param author Author index whos color will be used for teamcolor tag. +* @param szMessage Message (formatting rules). +* @return No return +* +* On error/Errors: If the author is not connected an error will be thrown. +*/ +stock CPrintToChatAllEx(author, const String:szMessage[], any:...) +{ + if (author < 0 || author > MaxClients) + ThrowError("Invalid client index %d", author); + + if (!IsClientInGame(author)) + ThrowError("Client %d is not in game", author); + + decl String:szBuffer[MAX_MESSAGE_LENGTH]; + + for (new i = 1; i <= MaxClients; i++) + { + if (IsClientInGame(i) && !IsFakeClient(i) && !CSkipList[i]) + { + SetGlobalTransTarget(i); + VFormat(szBuffer, sizeof(szBuffer), szMessage, 3); + + CPrintToChatEx(i, author, "%s", szBuffer); + } + + CSkipList[i] = false; + } +} + +/** +* Removes color tags from the string. +* +* @param szMessage String. +* @return No return +*/ +stock CRemoveTags(String:szMessage[], maxlength) +{ + for (new i = 0; i < MAX_COLORS; i++) + ReplaceString(szMessage, maxlength, CTag[i], "", false); + + ReplaceString(szMessage, maxlength, "{teamcolor}", "", false); +} + +/** +* Checks whether a color is allowed or not +* +* @param tag Color Tag. +* @return True when color is supported, otherwise false +*/ +stock CColorAllowed(Colors:color) +{ + if (!CEventIsHooked) + { + CSetupProfile(); + + CEventIsHooked = true; + } + + return CProfile_Colors[color]; +} + +/** +* Replace the color with another color +* Handle with care! +* +* @param color color to replace. +* @param newColor color to replace with. +* @noreturn +*/ +stock CReplaceColor(Colors:color, Colors:newColor) +{ + if (!CEventIsHooked) + { + CSetupProfile(); + + CEventIsHooked = true; + } + + CProfile_Colors[color] = CProfile_Colors[newColor]; + CProfile_TeamIndex[color] = CProfile_TeamIndex[newColor]; + + CTagReqSayText2[color] = CTagReqSayText2[newColor]; + Format(CTagCode[color], sizeof(CTagCode[]), CTagCode[newColor]) +} + +/** +* This function should only be used right in front of +* CPrintToChatAll or CPrintToChatAllEx and it tells +* to those funcions to skip specified client when printing +* message to all clients. After message is printed client will +* no more be skipped. +* +* @param client Client index +* @return No return +*/ +stock CSkipNextClient(client) +{ + if (client <= 0 || client > MaxClients) + ThrowError("Invalid client index %d", client); + + CSkipList[client] = true; +} + +/** +* Replaces color tags in a string with color codes +* +* @param szMessage String. +* @param maxlength Maximum length of the string buffer. +* @return Client index that can be used for SayText2 author index +* +* On error/Errors: If there is more then one team color is used an error will be thrown. +*/ +stock CFormat(String:szMessage[], maxlength, author=NO_INDEX) +{ + decl String:szGameName[30]; + + GetGameFolderName(szGameName, sizeof(szGameName)); + + /* Hook event for auto profile setup on map start */ + if (!CEventIsHooked) + { + CSetupProfile(); + HookEvent("server_spawn", CEvent_MapStart, EventHookMode_PostNoCopy); + + CEventIsHooked = true; + } + + new iRandomPlayer = NO_INDEX; + + // On CS:GO set invisible precolor + if (StrEqual(szGameName, "csgo", false)) + Format(szMessage, maxlength, " \x01\x0B\x01%s", szMessage); + + /* If author was specified replace {teamcolor} tag */ + if (author != NO_INDEX) + { + if (CProfile_SayText2) + { + ReplaceString(szMessage, maxlength, "{teamcolor}", "\x03", false); + + iRandomPlayer = author; + } + /* If saytext2 is not supported by game replace {teamcolor} with green tag */ + else + ReplaceString(szMessage, maxlength, "{teamcolor}", CTagCode[Color_Green], false); + } + else + ReplaceString(szMessage, maxlength, "{teamcolor}", "", false); + + /* For other color tags we need a loop */ + for (new i = 0; i < MAX_COLORS; i++) + { + /* If tag not found - skip */ + if (StrContains(szMessage, CTag[i], false) == -1) + continue; + + /* If tag is not supported by game replace it with green tag */ + else if (!CProfile_Colors[i]) + ReplaceString(szMessage, maxlength, CTag[i], CTagCode[Color_Green], false); + + /* If tag doesn't need saytext2 simply replace */ + else if (!CTagReqSayText2[i]) + ReplaceString(szMessage, maxlength, CTag[i], CTagCode[i], false); + + /* Tag needs saytext2 */ + else + { + /* If saytext2 is not supported by game replace tag with green tag */ + if (!CProfile_SayText2) + ReplaceString(szMessage, maxlength, CTag[i], CTagCode[Color_Green], false); + + /* Game supports saytext2 */ + else + { + /* If random player for tag wasn't specified replace tag and find player */ + if (iRandomPlayer == NO_INDEX) + { + /* Searching for valid client for tag */ + iRandomPlayer = CFindRandomPlayerByTeam(CProfile_TeamIndex[i]); + + /* If player not found replace tag with green color tag */ + if (iRandomPlayer == NO_PLAYER) + ReplaceString(szMessage, maxlength, CTag[i], CTagCode[Color_Green], false); + + /* If player was found simply replace */ + else + ReplaceString(szMessage, maxlength, CTag[i], CTagCode[i], false); + + } + /* If found another team color tag throw error */ + else + { + //ReplaceString(szMessage, maxlength, CTag[i], ""); + ThrowError("Using two team colors in one message is not allowed"); + } + } + + } + } + + return iRandomPlayer; +} + +/** +* Founds a random player with specified team +* +* @param color_team Client team. +* @return Client index or NO_PLAYER if no player found +*/ +stock CFindRandomPlayerByTeam(color_team) +{ + if (color_team == SERVER_INDEX) + return 0; + else + { + for (new i = 1; i <= MaxClients; i++) + { + if (IsClientInGame(i) && GetClientTeam(i) == color_team) + return i; + } + } + + return NO_PLAYER; +} + +/** +* Sends a SayText2 usermessage to a client +* +* @param szMessage Client index +* @param maxlength Author index +* @param szMessage Message +* @return No return. +*/ +stock CSayText2(client, author, const String:szMessage[]) +{ + new Handle:hBuffer = StartMessageOne("SayText2", client, USERMSG_RELIABLE|USERMSG_BLOCKHOOKS); + + if(GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && GetUserMessageType() == UM_Protobuf) + { + PbSetInt(hBuffer, "ent_idx", author); + PbSetBool(hBuffer, "chat", true); + PbSetString(hBuffer, "msg_name", szMessage); + PbAddString(hBuffer, "params", ""); + PbAddString(hBuffer, "params", ""); + PbAddString(hBuffer, "params", ""); + PbAddString(hBuffer, "params", ""); + } + else + { + BfWriteByte(hBuffer, author); + BfWriteByte(hBuffer, true); + BfWriteString(hBuffer, szMessage); + } + + EndMessage(); +} + +/** +* Creates game color profile +* This function must be edited if you want to add more games support +* +* @return No return. +*/ +stock CSetupProfile() +{ + decl String:szGameName[30]; + GetGameFolderName(szGameName, sizeof(szGameName)); + + if (StrEqual(szGameName, "cstrike", false)) + { + CProfile_Colors[Color_Lightgreen] = true; + CProfile_Colors[Color_Red] = true; + CProfile_Colors[Color_Blue] = true; + CProfile_Colors[Color_Olive] = true; + CProfile_TeamIndex[Color_Lightgreen] = SERVER_INDEX; + CProfile_TeamIndex[Color_Red] = 2; + CProfile_TeamIndex[Color_Blue] = 3; + CProfile_SayText2 = true; + } + else if (StrEqual(szGameName, "csgo", false)) + { + CProfile_Colors[Color_Default] = true; + CProfile_Colors[Color_Darkred] = true; + CProfile_Colors[Color_Pink] = true; + CProfile_Colors[Color_Green] = true; + CProfile_Colors[Color_Lightgreen] = true; + CProfile_Colors[Color_Lime] = true; + CProfile_Colors[Color_Red] = true; + CProfile_Colors[Color_Grey] = true; + CProfile_Colors[Color_Olive] = true; + CProfile_Colors[Color_A] = true; + CProfile_Colors[Color_Lightblue] = true; + CProfile_Colors[Color_Blue] = true; + CProfile_Colors[Color_D] = true; + CProfile_Colors[Color_Purple] = true; + CProfile_Colors[Color_Darkrange] = true; + CProfile_Colors[Color_Orange] = true; + CProfile_Colors[Color_Red] = true; + CProfile_Colors[Color_Blue] = true; + CProfile_Colors[Color_Olive] = true; + CProfile_Colors[Color_Darkred] = true; + CProfile_Colors[Color_Lime] = true; + CProfile_Colors[Color_Purple] = true; + CProfile_Colors[Color_Grey] = true; + CProfile_Colors[Color_Orange] = true; + CProfile_TeamIndex[Color_Red] = 2; + CProfile_TeamIndex[Color_Blue] = 3; + CProfile_SayText2 = true; + } + else if (StrEqual(szGameName, "tf", false)) + { + CProfile_Colors[Color_Lightgreen] = true; + CProfile_Colors[Color_Red] = true; + CProfile_Colors[Color_Blue] = true; + CProfile_Colors[Color_Olive] = true; + CProfile_TeamIndex[Color_Lightgreen] = SERVER_INDEX; + CProfile_TeamIndex[Color_Red] = 2; + CProfile_TeamIndex[Color_Blue] = 3; + CProfile_SayText2 = true; + } + else if (StrEqual(szGameName, "left4dead", false) || StrEqual(szGameName, "left4dead2", false)) + { + CProfile_Colors[Color_Lightgreen] = true; + CProfile_Colors[Color_Red] = true; + CProfile_Colors[Color_Blue] = true; + CProfile_Colors[Color_Olive] = true; + CProfile_TeamIndex[Color_Lightgreen] = SERVER_INDEX; + CProfile_TeamIndex[Color_Red] = 3; + CProfile_TeamIndex[Color_Blue] = 2; + CProfile_SayText2 = true; + } + else if (StrEqual(szGameName, "hl2mp", false)) + { + /* hl2mp profile is based on mp_teamplay convar */ + if (GetConVarBool(FindConVar("mp_teamplay"))) + { + CProfile_Colors[Color_Red] = true; + CProfile_Colors[Color_Blue] = true; + CProfile_Colors[Color_Olive] = true; + CProfile_TeamIndex[Color_Red] = 3; + CProfile_TeamIndex[Color_Blue] = 2; + CProfile_SayText2 = true; + } + else + { + CProfile_SayText2 = false; + CProfile_Colors[Color_Olive] = true; + } + } + else if (StrEqual(szGameName, "dod", false)) + { + CProfile_Colors[Color_Olive] = true; + CProfile_SayText2 = false; + } + /* Profile for other games */ + else + { + if (GetUserMessageId("SayText2") == INVALID_MESSAGE_ID) + { + CProfile_SayText2 = false; + } + else + { + CProfile_Colors[Color_Red] = true; + CProfile_Colors[Color_Blue] = true; + CProfile_TeamIndex[Color_Red] = 2; + CProfile_TeamIndex[Color_Blue] = 3; + CProfile_SayText2 = true; + } + } +} + +public Action:CEvent_MapStart(Handle:event, const String:name[], bool:dontBroadcast) +{ + CSetupProfile(); + + for (new i = 1; i <= MaxClients; i++) + CSkipList[i] = false; +} + diff --git a/addons/sourcemod/scripting/include/cstrike.inc b/addons/sourcemod/scripting/include/cstrike.inc index d9d953e..4894840 100644 --- a/addons/sourcemod/scripting/include/cstrike.inc +++ b/addons/sourcemod/scripting/include/cstrike.inc @@ -31,22 +31,22 @@ */ #if defined _cstrike_included - #endinput + #endinput #endif #define _cstrike_included -#define CS_TEAM_NONE 0 /**< No team yet. */ -#define CS_TEAM_SPECTATOR 1 /**< Spectators. */ -#define CS_TEAM_T 2 /**< Terrorists. */ -#define CS_TEAM_CT 3 /**< Counter-Terrorists. */ +#define CS_TEAM_NONE 0 /**< No team yet. */ +#define CS_TEAM_SPECTATOR 1 /**< Spectators. */ +#define CS_TEAM_T 2 /**< Terrorists. */ +#define CS_TEAM_CT 3 /**< Counter-Terrorists. */ -#define CS_SLOT_PRIMARY 0 /**< Primary weapon slot. */ -#define CS_SLOT_SECONDARY 1 /**< Secondary weapon slot. */ -#define CS_SLOT_KNIFE 2 /**< Knife slot. */ -#define CS_SLOT_GRENADE 3 /**< Grenade slot (will only return one grenade). */ -#define CS_SLOT_C4 4 /**< C4 slot. */ +#define CS_SLOT_PRIMARY 0 /**< Primary weapon slot. */ +#define CS_SLOT_SECONDARY 1 /**< Secondary weapon slot. */ +#define CS_SLOT_KNIFE 2 /**< Knife slot. */ +#define CS_SLOT_GRENADE 3 /**< Grenade slot (will only return one grenade). */ +#define CS_SLOT_C4 4 /**< C4 slot. */ -#define CS_DMG_HEADSHOT (1 << 30) /**< Headshot */ +#define CS_DMG_HEADSHOT (1 << 30) /**< Headshot */ enum CSRoundEndReason { @@ -70,8 +70,8 @@ enum CSRoundEndReason // The below only exist on CS:GO CSRoundEnd_TerroristsSurrender, /**< Terrorists Surrender */ CSRoundEnd_CTSurrender, /**< CTs Surrender */ - CSRoundEnd_TerroristsPlanted, /**< Terrorists Planted the bomb */ - CSRoundEnd_CTsReachedHostage, /**< CTs Reached the hostage */ + CSRoundEnd_TerroristsPlanted, /**< Terrorists Planted the bomb */ + CSRoundEnd_CTsReachedHostage /**< CTs Reached the hostage */ }; enum CSWeaponID @@ -141,6 +141,19 @@ enum CSWeaponID CSWeapon_CZ75A = 63, CSWeapon_REVOLVER = 64, CSWeapon_TAGGRENADE = 68, + CSWeapon_FISTS = 69, + CSWeapon_BREACHCHARGE = 70, + CSWeapon_TABLET = 72, + CSWeapon_MELEE = 74, + CSWeapon_AXE = 75, + CSWeapon_HAMMER = 76, + CSWeapon_SPANNER = 78, + CSWeapon_KNIFE_GHOST = 80, + CSWeapon_FIREBOMB = 81, + CSWeapon_DIVERSION = 82, + CSWeapon_FRAGGRENADE = 83, + CSWeapon_SNOWBALL = 84, + CSWeapon_BUMPMINE = 85, CSWeapon_MAX_WEAPONS_NO_KNIFES, // Max without the knife item defs, useful when treating all knives as a regular knife. CSWeapon_BAYONET = 500, CSWeapon_KNIFE_FLIP = 505, @@ -152,6 +165,14 @@ enum CSWeaponID CSWeapon_KNIFE_SURVIVAL_BOWIE = 514, CSWeapon_KNIFE_BUTTERFLY = 515, CSWeapon_KNIFE_PUSH = 516, + CSWeapon_KNIFE_CORD = 517, + CSWeapon_KNIFE_CANIS = 518, + CSWeapon_KNIFE_URSUS = 519, + CSWeapon_KNIFE_GYPSY_JACKKNIFE = 520, + CSWeapon_KNIFE_OUTDOOR = 521, + CSWeapon_KNIFE_STILETTO = 522, + CSWeapon_KNIFE_WIDOWMAKER = 523, + CSWeapon_KNIFE_SKELETON = 525, CSWeapon_MAX_WEAPONS //THIS MUST BE LAST, EASY WAY TO CREATE LOOPS. When looping, do CS_IsValidWeaponID(i), to check. }; @@ -160,8 +181,8 @@ enum CSWeaponID * Return Plugin_Continue to allow the purchase or return a * higher action to deny. * - * @param client Client index - * @param weapon User input for weapon name + * @param client Client index + * @param weapon User input for weapon name */ forward Action CS_OnBuyCommand(int client, const char[] weapon); @@ -170,8 +191,8 @@ forward Action CS_OnBuyCommand(int client, const char[] weapon); * Return Plugin_Continue to allow the call or return a * higher action to block. * - * @param client Client index - * @param weaponIndex Weapon index + * @param client Client index + * @param weaponIndex Weapon index */ forward Action CS_OnCSWeaponDrop(int client, int weaponIndex); @@ -182,11 +203,11 @@ forward Action CS_OnCSWeaponDrop(int client, int weaponIndex); * * @note This can be called multiple times per weapon purchase * - * @param client Client index - * @param weapon Weapon classname - * @param price Buffer param for the price of the weapon + * @param client Client index + * @param weapon Weapon classname + * @param price Buffer param for the price of the weapon * - * @note Not all "weapons" call GetWeaponPrice. Example: c4, knife, vest, vest helmet, night vision. + * @note Not all "weapons" call GetWeaponPrice. Example: c4, knife, vest, vest helmet, night vision. */ forward Action CS_OnGetWeaponPrice(int client, const char[] weapon, int &price); @@ -196,171 +217,173 @@ forward Action CS_OnGetWeaponPrice(int client, const char[] weapon, int &price); * using the given delay and reason, or return Plugin_Handled or a higher * action to block TerminateRound from firing. * - * @param delay Time (in seconds) until new round starts - * @param reason Reason for round end + * @param delay Time (in seconds) until new round starts + * @param reason Reason for round end */ forward Action CS_OnTerminateRound(float &delay, CSRoundEndReason &reason); /** * Respawns a player. * - * @param client Player's index. - * @error Invalid client index, client not in game. + * @param client Player's index. + * @error Invalid client index, client not in game. */ native void CS_RespawnPlayer(int client); /** * Switches the player's team. * - * @param client Player's index. - * @param team Team index. - * @error Invalid client index, client not in game. + * @param client Player's index. + * @param team Team index. + * @error Invalid client index, client not in game. */ native void CS_SwitchTeam(int client, int team); /** * Forces a player to drop or toss their weapon * - * @param client Player's index. - * @param weaponIndex Index of weapon to drop. - * @param toss True to toss weapon (with velocity) or false to just drop weapon - * @param blockhook Set to true to stop the corresponding CS_OnCSWeaponDrop - * - * @error Invalid client index, client not in game, or invalid weapon index. + * @param client Player's index. + * @param weaponIndex Index of weapon to drop. + * @param toss True to toss weapon (with velocity) or false to just drop weapon + * @param blockhook Set to true to stop the corresponding CS_OnCSWeaponDrop + * @error Invalid client index, client not in game, or invalid weapon index. */ native void CS_DropWeapon(int client, int weaponIndex, bool toss, bool blockhook = false); /** * Forces round to end with a reason * - * @param delay Time (in seconds) to delay before new round starts - * @param reason Reason for the round ending - * @param blockhook Set to true to stop the corresponding CS_OnTerminateRound - * forward from being called. + * @param delay Time (in seconds) to delay before new round starts + * @param reason Reason for the round ending + * @param blockhook Set to true to stop the corresponding CS_OnTerminateRound + * forward from being called. */ native void CS_TerminateRound(float delay, CSRoundEndReason reason, bool blockhook = false); /** * Gets a weapon name from a weapon alias * - * @param alias Weapons alias to get weapon name for. - * @param weapon Buffer to store weapons name - * @param size Size of buffer to store the weapons name. + * @param alias Weapons alias to get weapon name for. + * @param weapon Buffer to store weapons name + * @param size Size of buffer to store the weapons name. * - * @note Will set the buffer to the original alias if it is not an alias to a weapon. + * @note Will set the buffer to the original alias if it is not an alias to a weapon. */ native void CS_GetTranslatedWeaponAlias(const char[] alias, char[] weapon, int size); /** * Gets a weapon's price * - * @param client Client to check weapon price for. - * @param id Weapon id for the weapon to check - * @param defaultprice Set to true to get defaultprice. - * @return Returns price of the weapon (even if modified) + * @param client Client to check weapon price for. + * @param id Weapon id for the weapon to check + * @param defaultprice Set to true to get defaultprice. + * @return Returns price of the weapon (even if modified) + * @error Invalid client, failing to get weapon info, or failing to get price offset. * - * @error Invalid client, failing to get weapon info, or failing to get price offset. - * @note c4, knife and shield will always return 0. vest, vest helmet and night vision will always return default price. + * @note c4, knife and shield will always return 0. vest, vest helmet and night vision will always return default price. */ native int CS_GetWeaponPrice(int client, CSWeaponID id, bool defaultprice = false); /** * Gets a clients clan tag - * @param client Client index to get clan tag for. - * @param buffer Buffer to store clients clan tag in. - * @param size Size of the buffer. - * @return Number of non-null bytes written. * - * @error Invalid client. + * @param client Client index to get clan tag for. + * @param buffer Buffer to store clients clan tag in. + * @param size Size of the buffer. + * @return Number of non-null bytes written. + * @error Invalid client. */ native int CS_GetClientClanTag(int client, char[] buffer, int size); /** * Sets a clients clan tag - * @param client Client index to set clan tag for. - * @param tag Tag to set clients clan tag as. * - * @error Invalid client. + * @param client Client index to set clan tag for. + * @param tag Tag to set clients clan tag as. + * @error Invalid client. */ native void CS_SetClientClanTag(int client, const char[] tag); /** * Gets a team's score - * @param team Team index to get score for. - * @return Returns the internal team score. * - * @error Invalid team index. + * @param team Team index to get score for. + * @return Returns the internal team score. + * @error Invalid team index. */ native int CS_GetTeamScore(int team); /** * Sets a team's score - * @param team Team index to set score for. - * @param value Value to set teams score as. * - * @error Invalid team index. - * @note This will update the scoreboard only after the scoreboard update function is called. Use SetTeamScore plus this to update the scoreboard instantly and save values correctly. + * @param team Team index to set score for. + * @param value Value to set teams score as. + * @error Invalid team index. + * + * @note This will update the scoreboard only after the scoreboard update function is called. + * Use SetTeamScore plus this to update the scoreboard instantly and save values correctly. */ native void CS_SetTeamScore(int team, int value); /** * Gets a client's mvp count - * @param client Client index to get mvp count of. - * @return Returns the client's internal MVP count. * - * @error Invalid client. + * @param client Client index to get mvp count of. + * @return Returns the client's internal MVP count. + * @error Invalid client. */ native int CS_GetMVPCount(int client); /** * Sets a client's mvp count - * @param client Client index to set mvp count for. - * @param value Value to set client's mvp count as. * - * @error Invalid client. + * @param client Client index to set mvp count for. + * @param value Value to set client's mvp count as. + * @error Invalid client. */ native void CS_SetMVPCount(int client, int value); /** * Gets a client's contribution score (CS:GO only) - * @param client Client index to get score of. - * @return Returns the client's score. * - * @error Invalid client. + * @param client Client index to get score of. + * @return Returns the client's score. + * @error Invalid client. */ native int CS_GetClientContributionScore(int client); /** * Sets a client's contribution score (CS:GO only) - * @param client Client index to set score for. - * @param value Value to set client's score as. * - * @error Invalid client. + * @param client Client index to set score for. + * @param value Value to set client's score as. + * @error Invalid client. */ native void CS_SetClientContributionScore(int client, int value); /** * Gets a client's assists (CS:GO only) - * @param client Client index to get assists of. - * @return Returns the client's assists. * - * @error Invalid client. + * @param client Client index to get assists of. + * @return Returns the client's assists. + * @error Invalid client. */ native int CS_GetClientAssists(int client); /** * Sets a client's assists (CS:GO only) - * @param client Client index to set assists for. - * @param value Value to set client's assists as. * - * @error Invalid client. + * @param client Client index to set assists for. + * @param value Value to set client's assists as. + * @error Invalid client. */ native void CS_SetClientAssists(int client, int value); /** * Gets a weaponID from a alias - * @param alias Weapon alias to attempt to get an id for. - * @return Returns a weapon id or 0 if failed to find a match. + * + * @param alias Weapon alias to attempt to get an id for. + * @return Returns a weapon id or 0 if failed to find a match. * * @note For best results use CS_GetTranslatedWeaponAlias on the weapon name before passing it. */ @@ -368,17 +391,19 @@ native CSWeaponID CS_AliasToWeaponID(const char[] alias); /** * Gets a alias from a weaponID - * @param weaponID WeaponID to get alias for. - * @param destination Destination string to hold the weapon alias. - * @param len Length of the destination array. - * @return Returns number of cells written. + * + * @param weaponID WeaponID to get alias for. + * @param destination Destination string to hold the weapon alias. + * @param len Length of the destination array. + * @return Returns number of cells written. */ native int CS_WeaponIDToAlias(CSWeaponID weaponID, char[] destination, int len); /** * Returns weather a WeaponID is valid on the current mod (css or csgo) - * @param weaponID WeaponID to check - * @return Returns true if its a valid WeaponID false otherwise. + * + * @param weaponID WeaponID to check + * @return Returns true if its a valid WeaponID false otherwise. * * @note This will return false always for CSWeapon_NONE. Should only be called after OnMapStart since weapon info isnt intialized before. */ @@ -387,30 +412,30 @@ native bool CS_IsValidWeaponID(CSWeaponID id); /** * Sets a player's model based on their current class * - * @param client Player's index. - * @error Invalid client index, client not in game. + * @param client Player's index. + * @error Invalid client index, client not in game. */ native void CS_UpdateClientModel(int client); /** * Returns a CSWeaponID equivalent based on the item definition index. * - * @param iDefIndex Definition index to get the CSWeaponID value for. - * @return Returns CSWeaponID value for the definition index. - * - * @error Invalid definition index. - * @note In most cases the id will be the item definition index. Works for CS:GO ONLY. + * @param iDefIndex Definition index to get the CSWeaponID value for. + * @return Returns CSWeaponID value for the definition index. + * @error Invalid definition index. + * + * @note In most cases the id will be the item definition index. Works for CS:GO ONLY. */ native CSWeaponID CS_ItemDefIndexToID(int iDefIndex); /** * Returns a item definition index equivalent based on the CSWeaponID. * - * @param id CSWeaponID to get the item definition for. - * @return Returns item definition index value for the weapon id. - * - * @error Invalid weapon id. - * @note In most cases the item deinition index will be the id. Works for CS:GO ONLY. + * @param id CSWeaponID to get the item definition for. + * @return Returns item definition index value for the weapon id. + * @error Invalid weapon id. + * + * @note In most cases the item deinition index will be the id. Works for CS:GO ONLY. */ native int CS_WeaponIDToItemDefIndex(CSWeaponID id); diff --git a/addons/sourcemod/scripting/include/datapack.inc b/addons/sourcemod/scripting/include/datapack.inc index 9af8dd4..b3d4e89 100644 --- a/addons/sourcemod/scripting/include/datapack.inc +++ b/addons/sourcemod/scripting/include/datapack.inc @@ -39,7 +39,7 @@ /** * Opaque handle to a datapack position. */ - enum DataPackPos: {}; +enum DataPackPos: {}; // A DataPack allows serializing multiple variables into a single stream. methodmap DataPack < Handle @@ -49,55 +49,59 @@ methodmap DataPack < Handle // Packs a normal cell into a data pack. // - // @param cell Cell to add. - public native void WriteCell(any cell); + // @param cell Cell to add. + // @param insert Determines whether mid-pack writes will insert instead of overwrite. + public native void WriteCell(any cell, bool insert = false); // Packs a float into a data pack. // - // @param val Float to add. - public native void WriteFloat(float val); + // @param val Float to add. + // @param insert Determines whether mid-pack writes will insert instead of overwrite. + public native void WriteFloat(float val, bool insert = false); // Packs a string into a data pack. // - // @param str String to add. - public native void WriteString(const char[] str); + // @param str String to add. + // @param insert Determines whether mid-pack writes will insert instead of overwrite. + public native void WriteString(const char[] str, bool insert = false); // Packs a function pointer into a data pack. // - // @param fktptr Function pointer to add. - public native void WriteFunction(Function fktptr); + // @param fktptr Function pointer to add. + // @param insert Determines whether mid-pack writes will insert instead of overwrite. + public native void WriteFunction(Function fktptr, bool insert = false); // Reads a cell from a data pack. // - // @param pack Handle to the data pack. + // @return A cell at this position public native any ReadCell(); // Reads a float from a data pack. // - // @param pack Handle to the data pack. + // @return Float at this position public native float ReadFloat(); // Reads a string from a data pack. // - // @param buffer Destination string buffer. - // @param maxlen Maximum length of output string buffer. + // @param buffer Destination string buffer. + // @param maxlen Maximum length of output string buffer. public native void ReadString(char[] buffer, int maxlen); // Reads a function pointer from a data pack. // - // @return Function pointer. + // @return Function pointer. public native Function ReadFunction(); // Resets the position in a data pack. // - // @param clear If true, clears the contained data. + // @param clear If true, clears the contained data. public native void Reset(bool clear=false); // Returns whether or not a specified number of bytes from the data pack // position to the end can be read. // - // @param bytes Number of bytes to simulate reading. - public native bool IsReadable(int bytes); + // @param unused Unused variable. Exists for backwards compatability. + public native bool IsReadable(int unused = 0); // The read or write position in a data pack. property DataPackPos Position { @@ -109,117 +113,117 @@ methodmap DataPack < Handle /** * Creates a new data pack. * - * @return A Handle to the data pack. Must be closed with CloseHandle(). + * @return A Handle to the data pack. Must be closed with CloseHandle(). */ native DataPack CreateDataPack(); /** * Packs a normal cell into a data pack. * - * @param pack Handle to the data pack. - * @param cell Cell to add. - * @error Invalid handle. + * @param pack Handle to the data pack. + * @param cell Cell to add. + * @error Invalid handle. */ native void WritePackCell(Handle pack, any cell); /** * Packs a float into a data pack. * - * @param pack Handle to the data pack. - * @param val Float to add. - * @error Invalid handle. + * @param pack Handle to the data pack. + * @param val Float to add. + * @error Invalid handle. */ native void WritePackFloat(Handle pack, float val); /** * Packs a string into a data pack. * - * @param pack Handle to the data pack. - * @param str String to add. - * @error Invalid handle. + * @param pack Handle to the data pack. + * @param str String to add. + * @error Invalid handle. */ native void WritePackString(Handle pack, const char[] str); /** * Packs a function pointer into a data pack. * - * @param pack Handle to the data pack. - * @param fktptr Function pointer to add. - * @error Invalid handle. + * @param pack Handle to the data pack. + * @param fktptr Function pointer to add. + * @error Invalid handle. */ native void WritePackFunction(Handle pack, Function fktptr); /** * Reads a cell from a data pack. * - * @param pack Handle to the data pack. - * @return Cell value. - * @error Invalid handle, or bounds error. + * @param pack Handle to the data pack. + * @return Cell value. + * @error Invalid handle, or bounds error. */ native any ReadPackCell(Handle pack); /** * Reads a float from a data pack. * - * @param pack Handle to the data pack. - * @return Float value. - * @error Invalid handle, or bounds error. + * @param pack Handle to the data pack. + * @return Float value. + * @error Invalid handle, or bounds error. */ native float ReadPackFloat(Handle pack); /** * Reads a string from a data pack. * - * @param pack Handle to the data pack. - * @param buffer Destination string buffer. - * @param maxlen Maximum length of output string buffer. - * @error Invalid handle, or bounds error. + * @param pack Handle to the data pack. + * @param buffer Destination string buffer. + * @param maxlen Maximum length of output string buffer. + * @error Invalid handle, or bounds error. */ native void ReadPackString(Handle pack, char[] buffer, int maxlen); /** * Reads a function pointer from a data pack. * - * @param pack Handle to the data pack. - * @return Function pointer. - * @error Invalid handle, or bounds error. + * @param pack Handle to the data pack. + * @return Function pointer. + * @error Invalid handle, or bounds error. */ native Function ReadPackFunction(Handle pack); /** * Resets the position in a data pack. * - * @param pack Handle to the data pack. - * @param clear If true, clears the contained data. - * @error Invalid handle. + * @param pack Handle to the data pack. + * @param clear If true, clears the contained data. + * @error Invalid handle. */ native void ResetPack(Handle pack, bool clear=false); /** * Returns the read or write position in a data pack. * - * @param pack Handle to the data pack. - * @return Position in the data pack, only usable with calls to SetPackPosition. - * @error Invalid handle. + * @param pack Handle to the data pack. + * @return Position in the data pack, only usable with calls to SetPackPosition. + * @error Invalid handle. */ native DataPackPos GetPackPosition(Handle pack); /** * Sets the read/write position in a data pack. * - * @param pack Handle to the data pack. - * @param position New position to set. Must have been previously retrieved from a call to GetPackPosition. - * @error Invalid handle, or position is beyond the pack bounds. + * @param pack Handle to the data pack. + * @param position New position to set. Must have been previously retrieved from a call to GetPackPosition. + * @error Invalid handle, or position is beyond the pack bounds. */ native void SetPackPosition(Handle pack, DataPackPos position); /** * Returns whether or not a specified number of bytes from the data pack - * position to the end can be read. + * position to the end can be read. * - * @param pack Handle to the data pack. - * @param bytes Number of bytes to simulate reading. - * @return True if can be read, false otherwise. - * @error Invalid handle. + * @param pack Handle to the data pack. + * @param bytes Number of bytes to simulate reading. + * @return True if can be read, false otherwise. + * @error Invalid handle. */ native bool IsPackReadable(Handle pack, int bytes); diff --git a/addons/sourcemod/scripting/include/dbi.inc b/addons/sourcemod/scripting/include/dbi.inc index e15f3e4..e43a23c 100644 --- a/addons/sourcemod/scripting/include/dbi.inc +++ b/addons/sourcemod/scripting/include/dbi.inc @@ -40,10 +40,10 @@ */ enum DBResult { - DBVal_Error = 0, /**< Column number/field is invalid. */ - DBVal_TypeMismatch = 1, /**< You cannot retrieve this data with this type. */ - DBVal_Null = 2, /**< Field has no data (NULL) */ - DBVal_Data = 3, /**< Field has data */ + DBVal_Error = 0, /**< Column number/field is invalid. */ + DBVal_TypeMismatch = 1, /**< You cannot retrieve this data with this type. */ + DBVal_Null = 2, /**< Field has no data (NULL) */ + DBVal_Data = 3 /**< Field has data */ }; /** @@ -51,9 +51,9 @@ enum DBResult */ enum DBBindType { - DBBind_Int = 0, /**< Bind an integer. */ - DBBind_Float = 1, /**< Bind a float. */ - DBBind_String = 2, /**< Bind a string. */ + DBBind_Int = 0, /**< Bind an integer. */ + DBBind_Float = 1, /**< Bind a float. */ + DBBind_String = 2 /**< Bind a string. */ }; /** @@ -61,9 +61,9 @@ enum DBBindType */ enum DBPriority { - DBPrio_High = 0, /**< High priority. */ - DBPrio_Normal = 1, /**< Normal priority. */ - DBPrio_Low = 2, /**< Low priority. */ + DBPrio_High = 0, /**< High priority. */ + DBPrio_Normal = 1, /**< Normal priority. */ + DBPrio_Low = 2 /**< Low priority. */ }; // A Driver represents a database backend, currently MySQL or SQLite. @@ -192,8 +192,7 @@ methodmap DBResultSet < Handle // @return Number of bytes written. // @error Invalid field index, invalid type conversion requested // from the database, or no current result set. - public native int FetchString(int field, char[] buffer, int maxlength, - DBResult &result=DBVal_Error); + public native int FetchString(int field, char[] buffer, int maxlength, DBResult &result=DBVal_Error); // Fetches a float from a field in the current row of a result set. // If the result is NULL, a value of 0.0 will be returned. A NULL @@ -257,14 +256,16 @@ typeset SQLTxnSuccess function void (Database db, any data, int numQueries, DBResultSet[] results, any[] queryData); } -// Callback for a failed transaction. -// -// @param db Database handle. -// @param data Data value passed to SQL_ExecuteTransaction(). -// @param numQueries Number of queries executed in the transaction. -// @param error Error message. -// @param failIndex Index of the query that failed, or -1 if something else. -// @param queryData An array of each data value passed to SQL_AddQuery(). +/** + * Callback for a failed transaction. + * + * @param db Database handle. + * @param data Data value passed to SQL_ExecuteTransaction(). + * @param numQueries Number of queries executed in the transaction. + * @param error Error message. + * @param failIndex Index of the query that failed, or -1 if something else. + * @param queryData An array of each data value passed to SQL_AddQuery(). + */ typedef SQLTxnFailure = function void (Database db, any data, int numQueries, const char[] error, int failIndex, any[] queryData); // A Transaction is a collection of SQL statements that must all execute @@ -315,23 +316,27 @@ methodmap DBStatement < Handle public native void BindString(int param, const char[] value, bool copy); }; -// Callback for receiving asynchronous database connections. -// -// @param db Handle to the database connection. -// @param error Error string if there was an error. The error could be -// empty even if an error condition exists, so it is important -// to check the actual Handle value instead. -// @param data Data passed in via the original threaded invocation. +/** + * Callback for receiving asynchronous database connections. + * + * @param db Handle to the database connection. + * @param error Error string if there was an error. The error could be + * empty even if an error condition exists, so it is important + * to check the actual Handle value instead. + * @param data Data passed in via the original threaded invocation. + */ typedef SQLConnectCallback = function void (Database db, const char[] error, any data); -// Callback for receiving asynchronous database query results. -// -// @param db Cloned handle to the database connection. -// @param results Result object, or null on failure. -// @param error Error string if there was an error. The error could be -// empty even if an error condition exists, so it is important -// to check the actual results value instead. -// @param data Data passed in via the original threaded invocation. +/** + * Callback for receiving asynchronous database query results. + * + * @param db Cloned handle to the database connection. + * @param results Result object, or null on failure. + * @param error Error string if there was an error. The error could be + * empty even if an error condition exists, so it is important + * to check the actual results value instead. + * @param data Data passed in via the original threaded invocation. + */ typedef SQLQueryCallback = function void (Database db, DBResultSet results, const char[] error, any data); // A Database represents a live connection to a database, either over the @@ -340,9 +345,9 @@ methodmap Database < Handle { // Connects to a database asynchronously, so the game thread is not blocked. // - // @param callback Callback. If no driver was found, the owner is null. - // @param name Database configuration name. - // @param data Extra data value to pass to the callback. + // @param callback Callback. If no driver was found, the owner is null. + // @param name Database configuration name. + // @param data Extra data value to pass to the callback. public static native void Connect(SQLConnectCallback callback, const char[] name="default", any data=0); // Returns the driver for this database connection. @@ -372,22 +377,22 @@ methodmap Database < Handle // encloses the string in ''. While drivers tend to allow " instead, the string // may be not be escaped (for example, on SQLite)! // - // @param string String to quote. - // @param buffer Buffer to store quoted string in. - // @param maxlength Maximum length of the buffer. - // @param written Optionally returns the number of bytes written. - // @return True on success, false if buffer is not big enough. - // The buffer must be at least 2*strlen(string)+1. + // @param string String to quote. + // @param buffer Buffer to store quoted string in. + // @param maxlength Maximum length of the buffer. + // @param written Optionally returns the number of bytes written. + // @return True on success, false if buffer is not big enough. + // The buffer must be at least 2*strlen(string)+1. public native bool Escape(const char[] string, char[] buffer, int maxlength, int &written=0); // Formats a string according to the SourceMod format rules (see documentation). // All format specifiers are escaped (see SQL_EscapeString) unless the '!' flag is used. // - // @param buffer Destination string buffer. - // @param maxlength Maximum length of output string buffer. - // @param format Formatting rules. - // @param ... Variable number of format parameters. - // @return Number of cells written. + // @param buffer Destination string buffer. + // @param maxlength Maximum length of output string buffer. + // @param format Formatting rules. + // @param ... Variable number of format parameters. + // @return Number of cells written. public native int Format(const char[] buffer, int maxlength, const char[] format, any ...); // Returns whether a database is the same connection as another database. @@ -415,11 +420,11 @@ methodmap Database < Handle // automatically closed. When the transaction completes, the optional // callback is invoked. // - // @param txn A transaction handle. - // @param onSuccess An optional callback to receive a successful transaction. - // @param onError An optional callback to receive an error message. - // @param data An optional value to pass to callbacks. - // @param prio Priority queue to use. + // @param txn A transaction handle. + // @param onSuccess An optional callback to receive a successful transaction. + // @param onError An optional callback to receive an error message. + // @param data An optional value to pass to callbacks. + // @param prio Priority queue to use. public native void Execute(Transaction txn, SQLTxnSuccess onSuccess = INVALID_FUNCTION, SQLTxnFailure onError = INVALID_FUNCTION, @@ -430,24 +435,24 @@ methodmap Database < Handle /** * Creates an SQL connection from a named configuration. * - * @param confname Named configuration. - * @param persistent True to re-use a previous persistent connection if - * possible, false otherwise. - * @param error Error buffer. - * @param maxlength Maximum length of the error buffer. - * @return A database connection Handle, or INVALID_HANDLE on failure. + * @param confname Named configuration. + * @param persistent True to re-use a previous persistent connection if + * possible, false otherwise. + * @param error Error buffer. + * @param maxlength Maximum length of the error buffer. + * @return A database connection Handle, or INVALID_HANDLE on failure. */ native Database SQL_Connect(const char[] confname, bool persistent, char[] error, int maxlength); /** * Creates a default SQL connection. * - * @param error Error buffer. - * @param maxlength Maximum length of the error buffer. - * @param persistent True to re-use a previous persistent connection - * if possible, false otherwise. - * @return A database connection Handle, or INVALID_HANDLE on failure. - * On failure the error buffer will be filled with a message. + * @param error Error buffer. + * @param maxlength Maximum length of the error buffer. + * @param persistent True to re-use a previous persistent connection + * if possible, false otherwise. + * @return A database connection Handle, or INVALID_HANDLE on failure. + * On failure the error buffer will be filled with a message. */ stock Database SQL_DefConnect(char[] error, int maxlength, bool persistent=true) { @@ -466,19 +471,19 @@ stock Database SQL_DefConnect(char[] error, int maxlength, bool persistent=true) * In general it is discouraged to use this function. Connections should go through * databases.cfg for greatest flexibility on behalf of users. * - * @param keyvalues Key/value pairs from a KeyValues handle, describing the connection. - * @param error Error buffer. - * @param maxlength Maximum length of the error buffer. - * @param persistent True to re-use a previous persistent connection if - * possible, false otherwise. - * @return A database connection Handle, or INVALID_HANDLE on failure. - * On failure the error buffer will be filled with a message. - * @error Invalid KeyValues handle. + * @param keyvalues Key/value pairs from a KeyValues handle, describing the connection. + * @param error Error buffer. + * @param maxlength Maximum length of the error buffer. + * @param persistent True to re-use a previous persistent connection if + * possible, false otherwise. + * @return A database connection Handle, or INVALID_HANDLE on failure. + * On failure the error buffer will be filled with a message. + * @error Invalid KeyValues handle. */ native Database SQL_ConnectCustom(Handle keyvalues, - char[] error, - int maxlength, - bool persistent); + char[] error, + int maxlength, + bool persistent); /** * Grabs a handle to an SQLite database, creating one if it does not exist. @@ -489,15 +494,13 @@ native Database SQL_ConnectCustom(Handle keyvalues, * As a precaution, you should always create some sort of unique prefix to your table names so * there are no conflicts, and you should never drop or modify tables that you do not own. * - * @param database Database name. - * @param error Error buffer. - * @param maxlength Maximum length of the error buffer. - * @return A database connection Handle, or INVALID_HANDLE on failure. - * On failure the error buffer will be filled with a message. + * @param database Database name. + * @param error Error buffer. + * @param maxlength Maximum length of the error buffer. + * @return A database connection Handle, or INVALID_HANDLE on failure. + * On failure the error buffer will be filled with a message. */ -stock Database SQLite_UseDatabase(const char[] database, - char[] error, - int maxlength) +stock Database SQLite_UseDatabase(const char[] database, char[] error, int maxlength) { KeyValues kv = new KeyValues(""); kv.SetString("driver", "sqlite"); @@ -512,6 +515,7 @@ stock Database SQLite_UseDatabase(const char[] database, /** * This function is deprecated. Use SQL_ConnectCustom or SQLite_UseDatabase instead. + * @deprecated */ #pragma deprecated Use SQL_ConnectCustom instead. native Handle SQL_ConnectEx(Handle driver, @@ -528,8 +532,8 @@ native Handle SQL_ConnectEx(Handle driver, /** * Returns if a named configuration is present in databases.cfg. * - * @param name Configuration name. - * @return True if it exists, false otherwise. + * @param name Configuration name. + * @return True if it exists, false otherwise. */ native bool SQL_CheckConfig(const char[] name); @@ -539,19 +543,19 @@ native bool SQL_CheckConfig(const char[] name); * If the driver is not found, SourceMod will attempt * to load an extension named dbi..ext.[dll|so]. * - * @param name Driver identification string, or an empty - * string to return the default driver. - * @return Driver Handle, or INVALID_HANDLE on failure. + * @param name Driver identification string, or an empty + * string to return the default driver. + * @return Driver Handle, or INVALID_HANDLE on failure. */ native Handle SQL_GetDriver(const char[] name=""); /** * Reads the driver of an opened database. * - * @param database Database Handle. - * @param ident Option buffer to store the identification string. - * @param ident_length Maximum length of the buffer. - * @return Driver Handle. + * @param database Database Handle. + * @param ident Option buffer to store the identification string. + * @param ident_length Maximum length of the buffer. + * @return Driver Handle. */ native Handle SQL_ReadDriver(Handle database, char[] ident="", int ident_length=0); @@ -560,10 +564,10 @@ native Handle SQL_ReadDriver(Handle database, char[] ident="", int ident_length= * * Example: "mysql", "sqlite" * - * @param driver Driver Handle, or INVALID_HANDLE for the default driver. - * @param ident Identification string buffer. - * @param maxlength Maximum length of the buffer. - * @error Invalid Handle other than INVALID_HANDLE. + * @param driver Driver Handle, or INVALID_HANDLE for the default driver. + * @param ident Identification string buffer. + * @param maxlength Maximum length of the buffer. + * @error Invalid Handle other than INVALID_HANDLE. */ native void SQL_GetDriverIdent(Handle driver, char[] ident, int maxlength); @@ -572,10 +576,10 @@ native void SQL_GetDriverIdent(Handle driver, char[] ident, int maxlength); * * Example: "MySQL", "SQLite" * - * @param driver Driver Handle, or INVALID_HANDLE for the default driver. - * @param product Product string buffer. - * @param maxlength Maximum length of the buffer. - * @error Invalid Handle other than INVALID_HANDLE. + * @param driver Driver Handle, or INVALID_HANDLE for the default driver. + * @param product Product string buffer. + * @param maxlength Maximum length of the buffer. + * @error Invalid Handle other than INVALID_HANDLE. */ native void SQL_GetDriverProduct(Handle driver, char[] product, int maxlength); @@ -594,29 +598,29 @@ native bool SQL_SetCharset(Handle database, const char[] charset); /** * Returns the number of affected rows from the last query. * - * @param hndl A database OR statement Handle. - * @return Number of rows affected by the last query. - * @error Invalid database or statement Handle. + * @param hndl A database OR statement Handle. + * @return Number of rows affected by the last query. + * @error Invalid database or statement Handle. */ native int SQL_GetAffectedRows(Handle hndl); /** * Returns the last query's insertion id. * - * @param hndl A database, query, OR statement Handle. - * @return Last query's insertion id. - * @error Invalid database, query, or statement Handle. + * @param hndl A database, query, OR statement Handle. + * @return Last query's insertion id. + * @error Invalid database, query, or statement Handle. */ native int SQL_GetInsertId(Handle hndl); /** * Returns the error reported by the last query. * - * @param hndl A database, query, OR statement Handle. - * @param error Error buffer. - * @param maxlength Maximum length of the buffer. - * @return True if there was an error, false otherwise. - * @error Invalid database, query, or statement Handle. + * @param hndl A database, query, OR statement Handle. + * @param error Error buffer. + * @param maxlength Maximum length of the buffer. + * @return True if there was an error, false otherwise. + * @error Invalid database, query, or statement Handle. */ native bool SQL_GetError(Handle hndl, char[] error, int maxlength); @@ -634,14 +638,14 @@ native bool SQL_GetError(Handle hndl, char[] error, int maxlength); * encloses the string in ''. While drivers tend to allow " instead, the string * may be not be escaped (for example, on SQLite)! * - * @param database A database Handle. - * @param string String to quote. - * @param buffer Buffer to store quoted string in. - * @param maxlength Maximum length of the buffer. - * @param written Optionally returns the number of bytes written. - * @return True on success, false if buffer is not big enough. - * The buffer must be at least 2*strlen(string)+1. - * @error Invalid database or statement Handle. + * @param database A database Handle. + * @param string String to quote. + * @param buffer Buffer to store quoted string in. + * @param maxlength Maximum length of the buffer. + * @param written Optionally returns the number of bytes written. + * @return True on success, false if buffer is not big enough. + * The buffer must be at least 2*strlen(string)+1. + * @error Invalid database or statement Handle. */ native bool SQL_EscapeString(Handle database, const char[] string, @@ -653,19 +657,20 @@ native bool SQL_EscapeString(Handle database, * Formats a string according to the SourceMod format rules (see documentation). * All format specifiers are escaped (see SQL_EscapeString) unless the '!' flag is used. * - * @param database A database Handle. - * @param buffer Destination string buffer. - * @param maxlength Maximum length of output string buffer. - * @param format Formatting rules. - * @param ... Variable number of format parameters. - * @return Number of cells written. + * @param database A database Handle. + * @param buffer Destination string buffer. + * @param maxlength Maximum length of output string buffer. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @return Number of cells written. */ native int SQL_FormatQuery(Handle database, const char[] buffer, int maxlength, const char[] format, any ...); /** - * This is a backwards compatibility stock. You should use SQL_EscapeString() - * instead, as this function will probably be deprecated in SourceMod 1.1. + * This function is deprecated. Use SQL_EscapeString instead. + * @deprecated */ +#pragma deprecated Use SQL_EscapeString instead. stock bool SQL_QuoteString(Handle database, const char[] string, char[] buffer, @@ -678,14 +683,14 @@ stock bool SQL_QuoteString(Handle database, /** * Executes a query and ignores the result set. * - * @param database A database Handle. - * @param query Query string. - * @param len Optional parameter to specify the query length, in - * bytes. This can be used to send binary queries that - * have a premature terminator. - * @return True if query succeeded, false otherwise. Use - * SQL_GetError to find the last error. - * @error Invalid database Handle. + * @param database A database Handle. + * @param query Query string. + * @param len Optional parameter to specify the query length, in + * bytes. This can be used to send binary queries that + * have a premature terminator. + * @return True if query succeeded, false otherwise. Use + * SQL_GetError to find the last error. + * @error Invalid database Handle. */ native bool SQL_FastQuery(Handle database, const char[] query, int len=-1); @@ -693,14 +698,14 @@ native bool SQL_FastQuery(Handle database, const char[] query, int len=-1); * Executes a simple query and returns a new query Handle for * receiving the results. * - * @param database A database Handle. - * @param query Query string. - * @param len Optional parameter to specify the query length, in - * bytes. This can be used to send binary queries that - * have a premature terminator. - * @return A new Query Handle on success, INVALID_HANDLE - * otherwise. The Handle must be freed with CloseHandle(). - * @error Invalid database Handle. + * @param database A database Handle. + * @param query Query string. + * @param len Optional parameter to specify the query length, in + * bytes. This can be used to send binary queries that + * have a premature terminator. + * @return A new Query Handle on success, INVALID_HANDLE + * otherwise. The Handle must be freed with CloseHandle(). + * @error Invalid database Handle. */ native DBResultSet SQL_Query(Handle database, const char[] query, int len=-1); @@ -712,13 +717,13 @@ native DBResultSet SQL_Query(Handle database, const char[] query, int len=-1); * * Statement handles will work in any function that accepts a Query handle. * - * @param database A database Handle. - * @param query Query string. - * @param error Error buffer. - * @param maxlength Maximum size of the error buffer. - * @return A new statement Handle on success, INVALID_HANDLE - * otherwise. The Handle must be freed with CloseHandle(). - * @error Invalid database Handle. + * @param database A database Handle. + * @param query Query string. + * @param error Error buffer. + * @param maxlength Maximum size of the error buffer. + * @return A new statement Handle on success, INVALID_HANDLE + * otherwise. The Handle must be freed with CloseHandle(). + * @error Invalid database Handle. */ native DBStatement SQL_PrepareQuery(Handle database, const char[] query, char[] error, int maxlength); @@ -730,9 +735,9 @@ native DBStatement SQL_PrepareQuery(Handle database, const char[] query, char[] * query. If this is the case, all result sets must be processed before * another query is made. * - * @param query A query Handle. - * @return True if there was another result set, false otherwise. - * @error Invalid query Handle. + * @param query A query Handle. + * @return True if there was another result set, false otherwise. + * @error Invalid query Handle. */ native bool SQL_FetchMoreResults(Handle query); @@ -741,50 +746,50 @@ native bool SQL_FetchMoreResults(Handle query); * return true even if 0 results were returned, but false * on queries like UPDATE, INSERT, or DELETE. * - * @param query A query (or statement) Handle. - * @return True if there is a result set, false otherwise. - * @error Invalid query Handle. + * @param query A query (or statement) Handle. + * @return True if there is a result set, false otherwise. + * @error Invalid query Handle. */ native bool SQL_HasResultSet(Handle query); /** * Retrieves the number of rows in the last result set. * - * @param query A query (or statement) Handle. - * @return Number of rows in the current result set. - * @error Invalid query Handle. + * @param query A query (or statement) Handle. + * @return Number of rows in the current result set. + * @error Invalid query Handle. */ native int SQL_GetRowCount(Handle query); /** * Retrieves the number of fields in the last result set. * - * @param query A query (or statement) Handle. - * @return Number of fields in the current result set. - * @error Invalid query Handle. + * @param query A query (or statement) Handle. + * @return Number of fields in the current result set. + * @error Invalid query Handle. */ native int SQL_GetFieldCount(Handle query); /** * Retrieves the name of a field by index. * - * @param query A query (or statement) Handle. - * @param field Field number (starting from 0). - * @param name Name buffer. - * @param maxlength Maximum length of the name buffer. - * @error Invalid query Handle, invalid field index, or - * no current result set. + * @param query A query (or statement) Handle. + * @param field Field number (starting from 0). + * @param name Name buffer. + * @param maxlength Maximum length of the name buffer. + * @error Invalid query Handle, invalid field index, or + * no current result set. */ native void SQL_FieldNumToName(Handle query, int field, char[] name, int maxlength); /** * Retrieves a field index by name. * - * @param query A query (or statement) Handle. - * @param name Name of the field (case sensitive). - * @param field Variable to store field index in. - * @return True if found, false if not found. - * @error Invalid query Handle or no current result set. + * @param query A query (or statement) Handle. + * @param name Name of the field (case sensitive). + * @param field Variable to store field index in. + * @return True if found, false if not found. + * @error Invalid query Handle or no current result set. */ native bool SQL_FieldNameToNum(Handle query, const char[] name, int &field); @@ -795,27 +800,27 @@ native bool SQL_FieldNameToNum(Handle query, const char[] name, int &field); * If this function fails, SQL_MoreResults() can be used to * tell if there was an error or the result set is finished. * - * @param query A query (or statement) Handle. - * @return True if a row was fetched, false otherwise. - * @error Invalid query Handle. + * @param query A query (or statement) Handle. + * @return True if a row was fetched, false otherwise. + * @error Invalid query Handle. */ native bool SQL_FetchRow(Handle query); /** * Returns if there are more rows. * - * @param query A query (or statement) Handle. - * @return True if there are more rows, false otherwise. - * @error Invalid query Handle. + * @param query A query (or statement) Handle. + * @return True if there are more rows, false otherwise. + * @error Invalid query Handle. */ native bool SQL_MoreRows(Handle query); /** * Rewinds a result set back to the first result. * - * @param query A query (or statement) Handle. - * @return True on success, false otherwise. - * @error Invalid query Handle or no current result set. + * @param query A query (or statement) Handle. + * @return True on success, false otherwise. + * @error Invalid query Handle or no current result set. */ native bool SQL_Rewind(Handle query); @@ -824,15 +829,15 @@ native bool SQL_Rewind(Handle query); * If the result is NULL, an empty string will be returned. A NULL * check can be done with the result parameter, or SQL_IsFieldNull(). * - * @param query A query (or statement) Handle. - * @param field The field index (starting from 0). - * @param buffer String buffer. - * @param maxlength Maximum size of the string buffer. - * @param result Optional variable to store the status of the return value. - * @return Number of bytes written. - * @error Invalid query Handle or field index, invalid - * type conversion requested from the database, - * or no current result set. + * @param query A query (or statement) Handle. + * @param field The field index (starting from 0). + * @param buffer String buffer. + * @param maxlength Maximum size of the string buffer. + * @param result Optional variable to store the status of the return value. + * @return Number of bytes written. + * @error Invalid query Handle or field index, invalid + * type conversion requested from the database, + * or no current result set. */ native int SQL_FetchString(Handle query, int field, char[] buffer, int maxlength, DBResult &result=DBVal_Error); @@ -841,13 +846,13 @@ native int SQL_FetchString(Handle query, int field, char[] buffer, int maxlength * If the result is NULL, a value of 0.0 will be returned. A NULL * check can be done with the result parameter, or SQL_IsFieldNull(). * - * @param query A query (or statement) Handle. - * @param field The field index (starting from 0). - * @param result Optional variable to store the status of the return value. - * @return A float value. - * @error Invalid query Handle or field index, invalid - * type conversion requested from the database, - * or no current result set. + * @param query A query (or statement) Handle. + * @param field The field index (starting from 0). + * @param result Optional variable to store the status of the return value. + * @return A float value. + * @error Invalid query Handle or field index, invalid + * type conversion requested from the database, + * or no current result set. */ native float SQL_FetchFloat(Handle query, int field, DBResult &result=DBVal_Error); @@ -856,13 +861,13 @@ native float SQL_FetchFloat(Handle query, int field, DBResult &result=DBVal_Erro * If the result is NULL, a value of 0 will be returned. A NULL * check can be done with the result parameter, or SQL_IsFieldNull(). * - * @param query A query (or statement) Handle. - * @param field The field index (starting from 0). - * @param result Optional variable to store the status of the return value. - * @return An integer value. - * @error Invalid query Handle or field index, invalid - * type conversion requested from the database, - * or no current result set. + * @param query A query (or statement) Handle. + * @param field The field index (starting from 0). + * @param result Optional variable to store the status of the return value. + * @return An integer value. + * @error Invalid query Handle or field index, invalid + * type conversion requested from the database, + * or no current result set. */ native int SQL_FetchInt(Handle query, int field, DBResult &result=DBVal_Error); @@ -870,11 +875,11 @@ native int SQL_FetchInt(Handle query, int field, DBResult &result=DBVal_Error); * Returns whether a field's data in the current row of a result set is * NULL or not. NULL is an SQL type which means "no data." * - * @param query A query (or statement) Handle. - * @param field The field index (starting from 0). - * @return True if data is NULL, false otherwise. - * @error Invalid query Handle or field index, or no - * current result set. + * @param query A query (or statement) Handle. + * @param field The field index (starting from 0). + * @return True if data is NULL, false otherwise. + * @error Invalid query Handle or field index, or no + * current result set. */ native bool SQL_IsFieldNull(Handle query, int field); @@ -884,59 +889,59 @@ native bool SQL_IsFieldNull(Handle query, int field); * bytes to use. Note that the return value does not include the null * terminator. * - * @param query A query (or statement) Handle. - * @param field The field index (starting from 0). - * @return Number of bytes for the field's data size. - * @error Invalid query Handle or field index or no - * current result set. + * @param query A query (or statement) Handle. + * @param field The field index (starting from 0). + * @return Number of bytes for the field's data size. + * @error Invalid query Handle or field index or no + * current result set. */ native int SQL_FetchSize(Handle query, int field); /** * Binds a parameter in a prepared statement to a given integer value. * - * @param statement A statement (prepared query) Handle. - * @param param The parameter index (starting from 0). - * @param number The number to bind. - * @param signed True to bind the number as signed, false to - * bind it as unsigned. - * @error Invalid statement Handle or parameter index, or - * SQL error. + * @param statement A statement (prepared query) Handle. + * @param param The parameter index (starting from 0). + * @param number The number to bind. + * @param signed True to bind the number as signed, false to + * bind it as unsigned. + * @error Invalid statement Handle or parameter index, or + * SQL error. */ native void SQL_BindParamInt(Handle statement, int param, int number, bool signed=true); /** * Binds a parameter in a prepared statement to a given float value. * - * @param statement A statement (prepared query) Handle. - * @param param The parameter index (starting from 0). - * @param value The float number to bind. - * @error Invalid statement Handle or parameter index, or - * SQL error. + * @param statement A statement (prepared query) Handle. + * @param param The parameter index (starting from 0). + * @param value The float number to bind. + * @error Invalid statement Handle or parameter index, or + * SQL error. */ native void SQL_BindParamFloat(Handle statement, int param, float value); /** * Binds a parameter in a prepared statement to a given string value. * - * @param statement A statement (prepared query) Handle. - * @param param The parameter index (starting from 0). - * @param value The string to bind. - * @param copy Whether or not SourceMod should copy the value - * locally if necessary. If the string contents - * won't change before calling SQL_Execute(), this - * can be set to false for optimization. - * @error Invalid statement Handle or parameter index, or - * SQL error. + * @param statement A statement (prepared query) Handle. + * @param param The parameter index (starting from 0). + * @param value The string to bind. + * @param copy Whether or not SourceMod should copy the value + * locally if necessary. If the string contents + * won't change before calling SQL_Execute(), this + * can be set to false for optimization. + * @error Invalid statement Handle or parameter index, or + * SQL error. */ native void SQL_BindParamString(Handle statement, int param, const char[] value, bool copy); /** * Executes a prepared statement. All parameters must be bound beforehand. * - * @param statement A statement (prepared query) Handle. - * @return True on success, false on failure. - * @error Invalid statement Handle. + * @param statement A statement (prepared query) Handle. + * @return True on success, false on failure. + * @error Invalid statement Handle. */ native bool SQL_Execute(Handle statement); @@ -954,38 +959,40 @@ native bool SQL_Execute(Handle statement); * If the lock cannot be acquired, the main thread will pause until the * threaded operation has concluded. * - * @param database A database Handle. - * @error Invalid database Handle. + * @param database A database Handle. + * @error Invalid database Handle. */ native void SQL_LockDatabase(Handle database); /** * Unlocks a database so threading operations may continue. * - * @param database A database Handle. - * @error Invalid database Handle. + * @param database A database Handle. + * @error Invalid database Handle. */ native void SQL_UnlockDatabase(Handle database); -// General callback for threaded SQL stuff. -// -// @param owner Parent object of the Handle (or INVALID_HANDLE if none). -// @param hndl Handle to the child object (or INVALID_HANDLE if none). -// @param error Error string if there was an error. The error could be -// empty even if an error condition exists, so it is important -// to check the actual Handle value instead. -// @param data Data passed in via the original threaded invocation. +/** + * General callback for threaded SQL stuff. + * + * @param owner Parent object of the Handle (or INVALID_HANDLE if none). + * @param hndl Handle to the child object (or INVALID_HANDLE if none). + * @param error Error string if there was an error. The error could be + * empty even if an error condition exists, so it is important + * to check the actual Handle value instead. + * @param data Data passed in via the original threaded invocation. + */ typedef SQLTCallback = function void (Handle owner, Handle hndl, const char[] error, any data); /** * Tells whether two database handles both point to the same database * connection. * - * @param hndl1 First database Handle. - * @param hndl2 Second database Handle. - * @return True if the Handles point to the same - * connection, false otherwise. - * @error Invalid Handle. + * @param hndl1 First database Handle. + * @param hndl2 Second database Handle. + * @return True if the Handles point to the same + * connection, false otherwise. + * @error Invalid Handle. */ native bool SQL_IsSameConnection(Handle hndl1, Handle hndl2); @@ -997,10 +1004,10 @@ native bool SQL_IsSameConnection(Handle hndl1, Handle hndl2); * don't (or you mix threaded/non-threaded queries), you should see * SQL_LockDatabase(). * - * @param callback Callback; new Handle will be in hndl, owner is the driver. - * If no driver was found, the owner is INVALID_HANDLE. - * @param name Database name. - * @param data Extra data value to pass to the callback. + * @param callback Callback; new Handle will be in hndl, owner is the driver. + * If no driver was found, the owner is INVALID_HANDLE. + * @param name Database name. + * @param data Extra data value to pass to the callback. */ native void SQL_TConnect(SQLTCallback callback, const char[] name="default", any data=0); @@ -1015,13 +1022,13 @@ native void SQL_TConnect(SQLTCallback callback, const char[] name="default", any * The query Handle returned through the callback is temporary and destroyed * at the end of the callback. If you need to hold onto it, use CloneHandle(). * - * @param database A database Handle. - * @param callback Callback; database is in "owner" and the query Handle - * is passed in "hndl". - * @param query Query string. - * @param data Extra data value to pass to the callback. - * @param prio Priority queue to use. - * @error Invalid database Handle. + * @param database A database Handle. + * @param callback Callback; database is in "owner" and the query Handle + * is passed in "hndl". + * @param query Query string. + * @param data Extra data value to pass to the callback. + * @param prio Priority queue to use. + * @error Invalid database Handle. */ native void SQL_TQuery(Handle database, SQLTCallback callback, const char[] query, any data=0, DBPriority prio=DBPrio_Normal); @@ -1038,7 +1045,7 @@ native Transaction SQL_CreateTransaction(); * * @param txn A transaction handle. * @param query Query string. - * @param data Extra data value to pass to the final callback. + * @param data Extra data value to pass to the final callback. * @return The index of the query in the transaction's query list. * @error Invalid transaction handle. */ diff --git a/addons/sourcemod/scripting/include/dhooks.inc b/addons/sourcemod/scripting/include/dhooks.inc index 4d79a21..9c7ba66 100644 --- a/addons/sourcemod/scripting/include/dhooks.inc +++ b/addons/sourcemod/scripting/include/dhooks.inc @@ -72,6 +72,14 @@ enum HookType HookType_Raw }; +enum CallingConvention +{ + CallConv_CDECL, + CallConv_THISCALL, + CallConv_STDCALL, + CallConv_FASTCALL, +}; + enum MRESReturn { MRES_ChangedHandled = -2, // Use changed values and return MRES_Handled @@ -91,11 +99,50 @@ enum DHookPassFlag DHookPass_OASSIGNOP = (1<<4), /**< Object has an assignment operator */ }; +enum DHookRegister +{ + // Don't change the register and use the default for the calling convention. + DHookRegister_Default, + + // 8-bit general purpose registers + DHookRegister_AL, + DHookRegister_CL, + DHookRegister_DL, + DHookRegister_BL, + DHookRegister_AH, + DHookRegister_CH, + DHookRegister_DH, + DHookRegister_BH, + + // 32-bit general purpose registers + DHookRegister_EAX, + DHookRegister_ECX, + DHookRegister_EDX, + DHookRegister_EBX, + DHookRegister_ESP, + DHookRegister_EBP, + DHookRegister_ESI, + DHookRegister_EDI, + + // 128-bit XMM registers + DHookRegister_XMM0, + DHookRegister_XMM1, + DHookRegister_XMM2, + DHookRegister_XMM3, + DHookRegister_XMM4, + DHookRegister_XMM5, + DHookRegister_XMM6, + DHookRegister_XMM7, + + // 80-bit FPU registers + DHookRegister_ST0 +}; + typeset ListenCB { //Deleted function void (int entity); - + //Created function void (int entity, const char[] classname); }; @@ -108,42 +155,42 @@ typeset DHookCallback { //Function Example: void Ham::Test() with this pointer ignore function MRESReturn (); - + //Function Example: void Ham::Test() with this pointer passed function MRESReturn (int pThis); - + //Function Example: void Ham::Test(int cake) with this pointer ignore function MRESReturn (Handle hParams); - + //Function Example: void Ham::Test(int cake) with this pointer passed function MRESReturn (int pThis, Handle hParams); - + //Function Example: int Ham::Test() with this pointer ignore function MRESReturn (Handle hReturn); - + //Function Example: int Ham::Test() with this pointer passed function MRESReturn (int pThis, Handle hReturn); - + //Function Example: int Ham::Test(int cake) with this pointer ignore function MRESReturn (Handle hReturn, Handle hParams); - + //Function Example: int Ham::Test(int cake) with this pointer passed function MRESReturn (int pThis, Handle hReturn, Handle hParams); - + //Address NOW - + //Function Example: void Ham::Test() with this pointer passed function MRESReturn (Address pThis); - + //Function Example: void Ham::Test(int cake) with this pointer passed function MRESReturn (Address pThis, Handle hParams); - + //Function Example: int Ham::Test() with this pointer passed function MRESReturn (Address pThis, Handle hReturn); - + //Function Example: int Ham::Test(int cake) with this pointer passed function MRESReturn (Address pThis, Handle hReturn, Handle hParams); - + }; /* Adds an entity listener hook @@ -170,190 +217,256 @@ native bool DHookRemoveEntityListener(ListenType type, ListenCB callback); * @param hooktype Type of hook * @param returntype Type type of return * @param thistype Type of this pointer or ignore (ignore can be used if not needed) + * @param callback Optional callback function, if not set here must be set when hooking. + * + * @return Returns setup handle for the hook. + * @error Failed to create hook setup handle or invalid callback function. +*/ +native Handle DHookCreate(int offset, HookType hooktype, ReturnType returntype, ThisPointerType thistype, DHookCallback callback=INVALID_FUNCTION); + +/** + * Creates a detour + * + * @param funcaddr The address of the function to detour. + * Can be Address_Null if you want to load the address from gamedata using DHookSetFromConf. + * @param callConv Calling convention of the function. + * @param returnType Type of the return value. + * @param thisType Type of this pointer or ignore (ignore can be used if not needed) + * + * @return Setup handle for the detour. + * @error Failed to create detour setup handle. + */ +native Handle DHookCreateDetour(Address funcaddr, CallingConvention callConv, ReturnType returntype, ThisPointerType thisType); + +/** + * Setup a detour or hook for a function as described in a "Functions" section in gamedata. + * + * @param gameconf GameConfig handle + * @param name Name of the function in the gamedata to load. + * + * @return Setup handle for the detour or INVALID_HANDLE if offset/signature/address wasn't found. + * @error Failed to create detour setup handle, invalid gamedata handle, invalid callback function or failed to find function in gamedata. + */ +native Handle DHookCreateFromConf(Handle gameconf, const char[] name); + +/** + * Load details for a vhook or detour from a gamedata file. + * + * @param setup Hook setup handle to set the offset or address on. + * @param gameconf GameConfig handle + * @param source Whether to look in Offsets or Signatures. + * @param name Name of the property to find. + * + * @return True on success, false if nothing was found. + * @error Invalid setup or gamedata handle. + */ +native bool DHookSetFromConf(Handle setup, Handle gameconf, SDKFuncConfSource source, const char[] name); + +/** + * Enable the detour of the function described in the hook setup handle. + * + * @param setup Hook setup handle + * @param post True to make the hook a post hook. (If you need to change the retunr value or need the return value use a post hook! If you need to change params and return use a pre and post hook!) * @param callback Callback function * - * @return Returns setup handle for the hook or INVALID_HANDLE. -*/ -native Handle DHookCreate(int offset, HookType hooktype, ReturnType returntype, ThisPointerType thistype, DHookCallback callback); + * @return True if detour was enabled, false otherwise. + * @error Hook handle is not setup for a detour. + */ +native bool DHookEnableDetour(Handle setup, bool post, DHookCallback callback); -/* Adds param to a hook setup +/** + * Disable the detour of the function described in the hook setup handle. + * + * @param setup Hook setup handle + * @param post True to disable a post hook. + * @param callback Callback function * - * @param setup Setup handle to add the param to. - * @param type Param type - * @param size Used for Objects (not Object ptr) to define the size of the object. - * @param flag Used to change the pass type. + * @return True if detour was disabled, false otherwise. + * @error Hook handle is not setup for a detour or function is not detoured. + */ +native bool DHookDisableDetour(Handle setup, bool post, DHookCallback callback); + +/* Adds param to a hook setup * + * @param setup Setup handle to add the param to. + * @param type Param type + * @param size Used for Objects (not Object ptr) to define the size of the object. + * @param flag Used to change the pass type. + * @param custom_register The register this argument is passed in instead of the stack. + * * @error Invalid setup handle or too many params added (request upping the max in thread) * @noreturn */ -native void DHookAddParam(Handle setup, HookParamType type, int size=-1, DHookPassFlag flag=DHookPass_ByVal); -//native DHookAddParam(Handle:setup, HookParamType:type); +native void DHookAddParam(Handle setup, HookParamType type, int size=-1, DHookPassFlag flag=DHookPass_ByVal, DHookRegister custom_register=DHookRegister_Default); /* Hook entity - * + * * @param setup Setup handle to use to add the hook. - * @param post True to make the hook a post hook. (If you need to change the retunr value or need the return value use a post hook! If you need to change params and return use a pre and post hook!) + * @param post True to make the hook a post hook. (If you need to change the return value or need the return value use a post hook! If you need to change params and return use a pre and post hook!) * @param entity Entity index to hook on. * @param removalcb Callback for when the hook is removed (Entity hooks are auto-removed on entity destroyed and will call this callback) - * - * @error Invalid setup handle, invalid entity or invalid hook type. + * @param callback Optional callback function, if not set here must be set when creating the hook. + * + * @error Invalid setup handle, invalid entity, invalid hook type or invalid callback. * @return -1 on fail a hookid on success */ -native int DHookEntity(Handle setup, bool post, int entity, DHookRemovalCB removalcb=INVALID_FUNCTION); +native int DHookEntity(Handle setup, bool post, int entity, DHookRemovalCB removalcb=INVALID_FUNCTION, DHookCallback callback=INVALID_FUNCTION); /* Hook gamerules - * + * * @param setup Setup handle to use to add the hook. - * @param post True to make the hook a post hook. (If you need to change the retunr value or need the return value use a post hook! If you need to change params and return use a pre and post hook!) + * @param post True to make the hook a post hook. (If you need to change the return value or need the return value use a post hook! If you need to change params and return use a pre and post hook!) * @param removalcb Callback for when the hook is removed (Game rules hooks are auto-removed on map end and will call this callback) - * - * @error Invalid setup handle, failing to get gamerules pointer or invalid hook type. + * @param callback Optional callback function, if not set here must be set when creating the hook. + * + * @error Invalid setup handle, failing to get gamerules pointer, invalid hook type or invalid callback. * @return -1 on fail a hookid on success */ -native int DHookGamerules(Handle setup, bool post, DHookRemovalCB removalcb=INVALID_FUNCTION); +native int DHookGamerules(Handle setup, bool post, DHookRemovalCB removalcb=INVALID_FUNCTION, DHookCallback callback=INVALID_FUNCTION); /* Hook a raw pointer - * + * * @param setup Setup handle to use to add the hook. - * @param post True to make the hook a post hook. (If you need to change the retunr value or need the return value use a post hook! If you need to change params and return use a pre and post hook!) + * @param post True to make the hook a post hook. (If you need to change the return value or need the return value use a post hook! If you need to change params and return use a pre and post hook!) * @param addr This pointer address. * @param removalcb Callback for when the hook is removed (Entity hooks are auto-removed on entity destroyed and will call this callback) - * - * @error Invalid setup handle, invalid address or invalid hook type. + * @param callback Optional callback function, if not set here must be set when creating the hook. + * + * @error Invalid setup handle, invalid address, invalid hook type or invalid callback. * @return -1 on fail a hookid on success */ -native int DHookRaw(Handle setup, bool post, Address addr, DHookRemovalCB removalcb=INVALID_FUNCTION); +native int DHookRaw(Handle setup, bool post, Address addr, DHookRemovalCB removalcb=INVALID_FUNCTION, DHookCallback callback=INVALID_FUNCTION); /* Remove hook by hook id - * + * * @param hookid Hook id to remove - * + * * @return true on success false otherwise * @note This will not fire the removal callback! */ native bool DHookRemoveHookID(int hookid); /* Get param value (Only use for: int, entity, bool or float param types) - * + * * @param hParams Handle to params structure * @param num Param number to get. (Example if the function has 2 params and you need the value of the first param num would be 1. 0 Will return the number of params stored) - * + * * @error Invalid handle. Invalid param number. Invalid param type. * @return value if num greater than 0. If 0 returns paramcount. */ native any DHookGetParam(Handle hParams, int num); /* Get vector param value - * + * * @param hParams Handle to params structure * @param num Param number to get. (Example if the function has 2 params and you need the value of the first param num would be 1.) * @param vec Vector buffer to store result. - * + * * @error Invalid handle. Invalid param number. Invalid param type. * @noreturn */ native void DHookGetParamVector(Handle hParams, int num, float vec[3]); /* Get string param value - * + * * @param hParams Handle to params structure * @param num Param number to get. (Example if the function has 2 params and you need the value of the first param num would be 1.) * @param buffer String buffer to store result * @param size Buffer size - * + * * @error Invalid handle. Invalid param number. Invalid param type. * @noreturn */ native void DHookGetParamString(Handle hParams, int num, char[] buffer, int size); /* Set param value (Only use for: int, entity, bool or float param types) - * + * * @param hParams Handle to params structure * @params num Param number to set (Example if the function has 2 params and you need to set the value of the first param num would be 1.) * @param value Value to set it as (only pass int, bool, float or entity index) - * + * * @error Invalid handle. Invalid param number. Invalid param type. * @noreturn */ native void DHookSetParam(Handle hParams, int num, any value); /* Set vector param value - * + * * @param hParams Handle to params structure * @params num Param number to set (Example if the function has 2 params and you need to set the value of the first param num would be 1.) * @param vec Value to set vector as. - * + * * @error Invalid handle. Invalid param number. Invalid param type. * @noreturn */ native void DHookSetParamVector(Handle hParams, int num, float vec[3]); /* Set string param value - * + * * @param hParams Handle to params structure * @params num Param number to set (Example if the function has 2 params and you need to set the value of the first param num would be 1.) * @param value Value to set string as. - * + * * @error Invalid handle. Invalid param number. Invalid param type. * @noreturn */ native void DHookSetParamString(Handle hParams, int num, char[] value); /* Get return value (Only use for: int, entity, bool or float return types) - * + * * @param hReturn Handle to return structure - * + * * @error Invalid Handle, invalid type. * @return Returns default value if prehook returns actual value if post hook. */ native any DHookGetReturn(Handle hReturn); /* Get return vector value - * + * * @param hReturn Handle to return structure * @param vec Vector buffer to store result in. (In pre hooks will be default value (0.0,0.0,0.0)) - * + * * @error Invalid Handle, invalid type. * @noreturn */ native void DHookGetReturnVector(Handle hReturn, float vec[3]); /* Get return string value - * + * * @param hReturn Handle to return structure * @param buffer String buffer to store result in. (In pre hooks will be default value "") * @param size String buffer size - * + * * @error Invalid Handle, invalid type. * @noreturn */ native void DHookGetReturnString(Handle hReturn, char[] buffer, int size); /* Set return value (Only use for: int, entity, bool or float return types) - * + * * @param hReturn Handle to return structure * @param value Value to set return as - * + * * @error Invalid Handle, invalid type. * @noreturn */ native void DHookSetReturn(Handle hReturn, any value); /* Set return vector value - * + * * @param hReturn Handle to return structure * @param vec Value to set return vector as - * + * * @error Invalid Handle, invalid type. * @noreturn */ native void DHookSetReturnVector(Handle hReturn, float vec[3]); /* Set return string value - * + * * @param hReturn Handle to return structure * @param value Value to set return string as - * + * * @error Invalid Handle, invalid type. * @noreturn */ @@ -458,6 +571,11 @@ public __ext_dhooks_SetNTVOptional() MarkNativeAsOptional("DHookAddEntityListener"); MarkNativeAsOptional("DHookRemoveEntityListener"); MarkNativeAsOptional("DHookCreate"); + MarkNativeAsOptional("DHookCreateDetour"); + MarkNativeAsOptional("DHookCreateFromConf"); + MarkNativeAsOptional("DHookSetFromConf"); + MarkNativeAsOptional("DHookEnableDetour"); + MarkNativeAsOptional("DHookDisableDetour"); MarkNativeAsOptional("DHookAddParam"); MarkNativeAsOptional("DHookEntity"); MarkNativeAsOptional("DHookGamerules"); diff --git a/addons/sourcemod/scripting/include/discord.inc b/addons/sourcemod/scripting/include/discord.inc index a7eed9f..70f4552 100644 --- a/addons/sourcemod/scripting/include/discord.inc +++ b/addons/sourcemod/scripting/include/discord.inc @@ -30,6 +30,8 @@ typedef OnGetReactions = function void (DiscordBot bot, ArrayList Users, char[] typedef OnMessageSent = function void(DiscordBot bot, char[] channel, DiscordMessage message, any data); +typedef OnMessageDeleted = function void(DiscordBot bot, any data); + //hMemberList is JSON array containing guild members typedef OnGetMembers = function void(DiscordBot bot, char[] guild, Handle hMemberList); @@ -65,7 +67,7 @@ methodmap Role < Handle { public bool Mentionable() { return JsonObjectGetBool(this, "mentionable"); } -} +}; methodmap RoleList < Handle { property int Size { @@ -82,7 +84,7 @@ methodmap RoleList < Handle { return this.GetRole(i); } -} +}; /* { @@ -114,7 +116,7 @@ methodmap DiscordUser < Handle { public native void GetEmail(char[] buffer, int maxlength); public native bool IsBot(); -} +}; /* @@ -130,10 +132,10 @@ methodmap DiscordMessage < Handle { public native void GetContent(char[] buffer, int maxlength); public native void GetChannelID(char[] buffer, int maxlength); -} +}; #include #include #include #include -#include \ No newline at end of file +#include diff --git a/addons/sourcemod/scripting/include/discord/GuildMember.inc b/addons/sourcemod/scripting/include/discord/GuildMember.inc index fa8934a..7168ee8 100644 --- a/addons/sourcemod/scripting/include/discord/GuildMember.inc +++ b/addons/sourcemod/scripting/include/discord/GuildMember.inc @@ -26,4 +26,4 @@ methodmap DiscordGuildUser < Handle { public bool IsMute() { return JsonObjectGetBool(this, "mute"); } -} \ No newline at end of file +}; diff --git a/addons/sourcemod/scripting/include/discord/bot.inc b/addons/sourcemod/scripting/include/discord/bot.inc index 63062f7..b36a77a 100644 --- a/addons/sourcemod/scripting/include/discord/bot.inc +++ b/addons/sourcemod/scripting/include/discord/bot.inc @@ -58,7 +58,7 @@ methodmap DiscordBot < StringMap { * Checks if the bot is listening to channel for messages * @param DiscordChannel Channel */ - public bool IsListeningToChannelID(char[] id) { + public bool IsListeningToChannelID(const char[] id) { Handle hChannels = this.GetListeningChannels(); if(hChannels == null) return false; @@ -105,7 +105,7 @@ methodmap DiscordBot < StringMap { * Stops the bot from listening to that channel id for messages * @param DiscordChannel Channel */ - public void StopListeningToChannelID(char[] id) { + public void StopListeningToChannelID(const char[] id) { Handle channels = this.GetListeningChannels(); if(channels == null) return; @@ -122,7 +122,7 @@ methodmap DiscordBot < StringMap { delete channels; } - public DiscordChannel GetListeningChannelByID(char[] id) { + public DiscordChannel GetListeningChannelByID(const char[] id) { Handle channels = this.GetListeningChannels(); if(channels == null) return null; @@ -163,39 +163,39 @@ methodmap DiscordBot < StringMap { } - public native void AddReactionID(char[] channel, char[] messageid, char[] emoji); + public native void AddReactionID(const char[] channel, const char[] messageid, const char[] emoji); - public void AddReaction(DiscordChannel channel, char[] messageid, char[] emoji) { + public void AddReaction(DiscordChannel channel, const char[] messageid, const char[] emoji) { char channelid[64]; channel.GetID(channelid, sizeof(channelid)); this.AddReactionID(channelid, messageid, emoji); } - public native void DeleteReactionID(char[] channel, char[] messageid, char[] emoji, char[] user); + public native void DeleteReactionID(const char[] channel, const char[] messageid, const char[] emoji, const char[] user); - public void DeleteReaction(DiscordChannel channel, char[] messageid, char[] emoji, char[] user) { + public void DeleteReaction(DiscordChannel channel, const char[] messageid, const char[] emoji, const char[] user) { char chid[64]; channel.GetID(chid, sizeof(chid)); this.DeleteReactionID(chid, messageid, emoji, user); } - public void DeleteReactionSelf(DiscordChannel channel, char[] messageid, char[] emoji) { + public void DeleteReactionSelf(DiscordChannel channel, const char[] messageid, const char[] emoji) { this.DeleteReaction(channel, messageid, emoji, "@me"); } - public void DeleteReactionAll(DiscordChannel channel, char[] messageid, char[] emoji) { + public void DeleteReactionAll(DiscordChannel channel, const char[] messageid, const char[] emoji) { this.DeleteReaction(channel, messageid, emoji, "@all"); } - public void DeleteReactionSelfID(char[] channel, char[] messageid, char[] emoji) { + public void DeleteReactionSelfID(const char[] channel, const char[] messageid, const char[] emoji) { this.DeleteReactionID(channel, messageid, emoji, "@me"); } - public void DeleteReactionAllID(char[] channel, char[] messageid, char[] emoji) { + public void DeleteReactionAllID(const char[] channel, const char[] messageid, const char[] emoji) { this.DeleteReactionID(channel, messageid, emoji, "@all"); } - public native void GetReactionID(char[] channel, char[] messageid, char[] emoji, OnGetReactions fCallback=INVALID_FUNCTION, any data=0); + public native void GetReactionID(const char[] channel, const char[] messageid, const char[] emoji, OnGetReactions fCallback=INVALID_FUNCTION, any data=0); - public void GetReaction(DiscordChannel channel, char[] messageid, char[] emoji, OnGetReactions fCallback=INVALID_FUNCTION, any data=0) { + public void GetReaction(DiscordChannel channel, const char[] messageid, const char[] emoji, OnGetReactions fCallback=INVALID_FUNCTION, any data=0) { char id[64]; channel.GetID(id, sizeof(id)); this.GetReactionID(id, messageid, emoji, fCallback, data); @@ -207,6 +207,10 @@ methodmap DiscordBot < StringMap { public native void SendMessageToChannelID(char[] channel, char[] message, OnMessageSent fCallback=INVALID_FUNCTION, any data=0); + public native void DeleteMessageID(char[] channel, char[] message, OnMessageDeleted fCallback=INVALID_FUNCTION, any data=0); + public native void DeleteMessage(DiscordChannel channel, DiscordMessage message, OnMessageDeleted fCallback=INVALID_FUNCTION, any data=0); + + public native void GetGuilds(DiscordGuildsRetrieve fCallback = INVALID_FUNCTION, DiscordGuildsRetrievedAll fCallbackAll = INVALID_FUNCTION, any data=0); public native void GetGuildChannels(char[] guild, DiscordGuildChannelsRetrieve fCallback = INVALID_FUNCTION, DiscordGuildChannelsRetrieveAll fCallbackAll = INVALID_FUNCTION, any data=0); @@ -224,4 +228,4 @@ methodmap DiscordBot < StringMap { public native void GetGuildMembersAll(char[] guild, OnGetMembers fCallback, int perPage=250, char[] afterUserID=""); public native void GetGuildRoles(char[] guild, DiscordGuildGetRoles fCallback, any data); -} \ No newline at end of file +}; diff --git a/addons/sourcemod/scripting/include/discord/channel.inc b/addons/sourcemod/scripting/include/discord/channel.inc index ce0b5b0..cb56bdf 100644 --- a/addons/sourcemod/scripting/include/discord/channel.inc +++ b/addons/sourcemod/scripting/include/discord/channel.inc @@ -1,3 +1,12 @@ +enum +{ + GUILD_TEXT = 0, + DM, + GUILD_VOICE, + GROUP_DM, + GUILD_CATEGORY +}; + methodmap DiscordChannel < StringMap { public DiscordChannel() { Handle hObj = json_object(); @@ -18,10 +27,6 @@ methodmap DiscordChannel < StringMap { JsonObjectGetString(this, "name", buffer, maxlength); } - public void GetType(char[] buffer, int maxlength) { - JsonObjectGetString(this, "type", buffer, maxlength); - } - property int Position { public get() { return JsonObjectGetInt(this, "position"); @@ -42,10 +47,16 @@ methodmap DiscordChannel < StringMap { JsonObjectGetString(this, "last_message_id", buffer, maxlength); } - public void SetLastMessageID(char[] id) { + public void SetLastMessageID(const char[] id) { json_object_set_new(this, "last_message_id", json_string(id)); } + property int Type { + public get() { + return JsonObjectGetInt(this, "type"); + } + } + property int Bitrate { public get() { return JsonObjectGetInt(this, "bitrate"); @@ -60,10 +71,7 @@ methodmap DiscordChannel < StringMap { property bool IsText { public get() { - char type[8]; - this.GetType(type, sizeof(type)); - if(StrEqual(type, "text", false)) return true; - return false; + return this.Type == GUILD_TEXT; } } -} \ No newline at end of file +}; diff --git a/addons/sourcemod/scripting/include/discord/message_embed.inc b/addons/sourcemod/scripting/include/discord/message_embed.inc index 6479508..45da67e 100644 --- a/addons/sourcemod/scripting/include/discord/message_embed.inc +++ b/addons/sourcemod/scripting/include/discord/message_embed.inc @@ -3,23 +3,86 @@ methodmap MessageEmbed < Handle { Handle hObj = json_object(); return view_as(hObj); } - + public bool GetColor(char[] buffer, int maxlength) { return JsonObjectGetString(this, "color", buffer, maxlength); } - - public void SetColor(char[] color) { + + public void SetColor(const char[] color) { json_object_set_new(this, "color", json_string(color)); } - + public bool GetTitle(char[] buffer, int maxlength) { return JsonObjectGetString(this, "title", buffer, maxlength); } - - public void SetTitle(char[] title) { + + public void SetTitle(const char[] title) { json_object_set_new(this, "title", json_string(title)); } - + + public bool GetTitleLink(char[] buffer, int maxlength) { + return JsonObjectGetString(this, "title_link", buffer, maxlength); + } + + public void SetTitleLink(const char[] title_link) { + json_object_set_new(this, "title_link", json_string(title_link)); + } + + public bool GetImage(char[] buffer, int maxlength) { + return JsonObjectGetString(this, "image_url", buffer, maxlength); + } + + public void SetImage(const char[] image_url) { + json_object_set_new(this, "image_url", json_string(image_url)); + } + + public bool GetAuthor(char[] buffer, int maxlength) { + return JsonObjectGetString(this, "author_name", buffer, maxlength); + } + + public void SetAuthor(const char[] author_name) { + json_object_set_new(this, "author_name", json_string(author_name)); + } + + public bool GetAuthorLink(char[] buffer, int maxlength) { + return JsonObjectGetString(this, "author_link", buffer, maxlength); + } + + public void SetAuthorLink(const char[] author_link) { + json_object_set_new(this, "author_link", json_string(author_link)); + } + + public bool GetAuthorIcon(char[] buffer, int maxlength) { + return JsonObjectGetString(this, "author_icon", buffer, maxlength); + } + + public void SetAuthorIcon(const char[] author_icon) { + json_object_set_new(this, "author_icon", json_string(author_icon)); + } + + public bool GetThumb(char[] buffer, int maxlength) { + return JsonObjectGetString(this, "thumb_url", buffer, maxlength); + } + + public void SetThumb(const char[] thumb_url) { + json_object_set_new(this, "thumb_url", json_string(thumb_url)); + } + + public bool GetFooter(char[] buffer, int maxlength) { + return JsonObjectGetString(this, "footer", buffer, maxlength); + } + + public void SetFooter(const char[] footer) { + json_object_set_new(this, "footer", json_string(footer)); + } + + public bool GetFooterIcon(char[] buffer, int maxlength) { + return JsonObjectGetString(this, "footer_icon", buffer, maxlength); + } + + public void SetFooterIcon(const char[] footer_icon) { + json_object_set_new(this, "footer_icon", json_string(footer_icon)); + } /** * Note: Setting Fields will delete the handle! */ @@ -27,13 +90,13 @@ methodmap MessageEmbed < Handle { public get() { return json_object_get(this, "fields"); } - + public set(Handle value) { json_object_set_new(this, "fields", value); } } - - public void AddField(char[] name, char[] value, bool inline) { + + public void AddField(const char[] name, const char[] value, bool inline) { Handle hObj = json_object(); json_object_set_new(hObj, "name", json_string(name)); json_object_set_new(hObj, "value", json_string(value)); @@ -45,21 +108,21 @@ methodmap MessageEmbed < Handle { json_array_append_new(hArray, hObj); this.Fields = hArray; } - + //Below don't support Slack Mode public bool GetDescription(char[] buffer, int maxlength) { return JsonObjectGetString(this, "description", buffer, maxlength); } - - public void SetDescription(char[] description) { + + public void SetDescription(const char[] description) { json_object_set_new(this, "description", json_string(description)); } - + public bool GetURL(char[] buffer, int maxlength) { return JsonObjectGetString(this, "url", buffer, maxlength); } - - public void SetURL(char[] url) { + + public void SetURL(const char[] url) { json_object_set_new(this, "url", json_string(url)); } -} \ No newline at end of file +}; diff --git a/addons/sourcemod/scripting/include/discord/stocks.inc b/addons/sourcemod/scripting/include/discord/stocks.inc index 69f3fa4..f63164b 100644 --- a/addons/sourcemod/scripting/include/discord/stocks.inc +++ b/addons/sourcemod/scripting/include/discord/stocks.inc @@ -79,4 +79,4 @@ stock float JsonObjectGetFloat(Handle hJson, char[] key, float defaultValue=0.0) } CloseHandle(hObject); return value; -} \ No newline at end of file +} diff --git a/addons/sourcemod/scripting/include/discord/webhook.inc b/addons/sourcemod/scripting/include/discord/webhook.inc index 2aaac74..dd532b8 100644 --- a/addons/sourcemod/scripting/include/discord/webhook.inc +++ b/addons/sourcemod/scripting/include/discord/webhook.inc @@ -4,14 +4,14 @@ methodmap DiscordWebHook < Handle { json_object_set_new(mp, "__url", json_string(url)); Handle data = json_object(); json_object_set_new(mp, "__data", data); - + return view_as(mp); } - + public void GetUrl(char[] buffer, int maxlength) { JsonObjectGetString(this, "__url", buffer, maxlength); } - + /** * Gets/Sets if the hook should be sent as Slack. * Note: color is different for slack than discord msg. @@ -22,42 +22,42 @@ methodmap DiscordWebHook < Handle { public get() { return JsonObjectGetBool(this, "__slack", false); } - + public set(bool value) { json_object_set_new(this, "__slack", (value) ? json_true() : json_false()); } } - + property Handle Data { public get() { return json_object_get(this, "__data"); } - + public set(Handle value) { json_object_set_new(this, "__data", value); } } - + public void UpdateDataObject(char[] key, Handle hObject) { Handle data = this.Data; json_object_set_new(data, key, hObject); delete data; } - + public bool GetDataBool(char[] key, bool defaultValue=false) { Handle data = this.Data; bool value = JsonObjectGetBool(data, key, defaultValue); delete data; return value; } - + public bool GetDataString(char[] key, char[] buffer, int maxlength) { Handle data = this.Data; bool success = JsonObjectGetString(data, key, buffer, maxlength); delete data; return success; } - + /** * Note: Deletes the MessageEmbed Object! */ @@ -65,70 +65,78 @@ methodmap DiscordWebHook < Handle { //this.UpdateDataObject("embeds", Object); Handle data = this.Data; Handle hArray = json_object_get(data, "embeds"); - + if(hArray == null) { hArray = json_array(); json_object_set(data, "embeds", hArray); } - + json_array_append_new(hArray, Object); delete hArray; delete data; - + } - + property bool tts { public get() { return this.GetDataBool("tts", false); } - + public set(bool value) { this.UpdateDataObject("tts", json_boolean(value)); } } - + public bool GetUsername(char[] buffer, int maxlength) { return this.GetDataString("username", buffer, maxlength); } - - public void SetUsername(char[] name) { + + public void SetUsername(const char[] name) { this.UpdateDataObject("username", json_string(name)); } - + + public bool GetAvatar(char[] buffer, int maxlength) { + return this.GetDataString("icon_url", buffer, maxlength); + } + + public void SetAvatar(const char[] icon_url) { + this.UpdateDataObject("icon_url", json_string(icon_url)); + } + public bool GetContent(char[] buffer, int maxlength) { return this.GetDataString("content", buffer, maxlength); } - - public void SetContent(char[] content) { + + public void SetContent(const char[] content) { this.UpdateDataObject("content", json_string(content)); } - + /*property Handle OnComplete { public get() { Handle fForward = null; if(!GetTrieValue(this, "callback", fForward)) { return null; } - + return fForward; } - + public set(Handle value) { SetTrieValue(this, "callback", value); SetTrieValue(this, "plugin", GetMyHandle()); } } - + property Handle CallbackPlugin { public get() { Handle value = null; if(!GetTrieValue(this, "plugin", value)) { return null; } - + return value; } }*/ - + public native void Send(); -} \ No newline at end of file +}; diff --git a/addons/sourcemod/scripting/include/entity.inc b/addons/sourcemod/scripting/include/entity.inc index 2e9a679..a0f9116 100644 --- a/addons/sourcemod/scripting/include/entity.inc +++ b/addons/sourcemod/scripting/include/entity.inc @@ -40,40 +40,39 @@ */ enum PropType { - Prop_Send = 0, /**< This property is networked. */ - Prop_Data = 1, /**< This property is for save game data fields. */ + Prop_Send = 0, /**< This property is networked. */ + Prop_Data = 1 /**< This property is for save game data fields. */ }; /** * @section For more information on these, see the HL2SDK (public/edict.h) */ -#define FL_EDICT_CHANGED (1<<0) /**< Game DLL sets this when the entity state changes - Mutually exclusive with FL_EDICT_PARTIAL_CHANGE. */ -#define FL_EDICT_FREE (1<<1) /**< this edict if free for reuse */ -#define FL_EDICT_FULL (1<<2) /**< this is a full server entity */ -#define FL_EDICT_FULLCHECK (0<<0) /**< call ShouldTransmit() each time, this is a fake flag */ -#define FL_EDICT_ALWAYS (1<<3) /**< always transmit this entity */ -#define FL_EDICT_DONTSEND (1<<4) /**< don't transmit this entity */ -#define FL_EDICT_PVSCHECK (1<<5) /**< always transmit entity, but cull against PVS */ -#define FL_EDICT_PENDING_DORMANT_CHECK (1<<6) -#define FL_EDICT_DIRTY_PVS_INFORMATION (1<<7) -#define FL_FULL_EDICT_CHANGED (1<<8) +#define FL_EDICT_CHANGED (1<<0) /**< Game DLL sets this when the entity state changes + Mutually exclusive with FL_EDICT_PARTIAL_CHANGE. */ +#define FL_EDICT_FREE (1<<1) /**< this edict if free for reuse */ +#define FL_EDICT_FULL (1<<2) /**< this is a full server entity */ +#define FL_EDICT_FULLCHECK (0<<0) /**< call ShouldTransmit() each time, this is a fake flag */ +#define FL_EDICT_ALWAYS (1<<3) /**< always transmit this entity */ +#define FL_EDICT_DONTSEND (1<<4) /**< don't transmit this entity */ +#define FL_EDICT_PVSCHECK (1<<5) /**< always transmit entity, but cull against PVS */ +#define FL_EDICT_PENDING_DORMANT_CHECK (1<<6) +#define FL_EDICT_DIRTY_PVS_INFORMATION (1<<7) +#define FL_FULL_EDICT_CHANGED (1<<8) enum PropFieldType { - PropField_Unsupported, /**< The type is unsupported. */ - PropField_Integer, /**< Valid for SendProp and Data fields */ - PropField_Float, /**< Valid for SendProp and Data fields */ - PropField_Entity, /**< Valid for Data fields only (SendProp shows as int) */ - PropField_Vector, /**< Valid for SendProp and Data fields */ - PropField_String, /**< Valid for SendProp and Data fields */ - PropField_String_T, /**< Valid for Data fields. Read only. - Note that the size of a string_t is dynamic, and - thus FindDataMapOffs() will return the constant size - of the string_t container (which is 32 bits right now). - */ - PropField_Variant, /**< Valid for Data fields only Type is not known at the field level, - (for this call), but dependent on current field value. */ + PropField_Unsupported, /**< The type is unsupported. */ + PropField_Integer, /**< Valid for SendProp and Data fields */ + PropField_Float, /**< Valid for SendProp and Data fields */ + PropField_Entity, /**< Valid for Data fields only (SendProp shows as int) */ + PropField_Vector, /**< Valid for SendProp and Data fields */ + PropField_String, /**< Valid for SendProp and Data fields */ + PropField_String_T, /**< Valid for Data fields. Read only. + Note that the size of a string_t is dynamic, and + thus FindDataMapOffs() will return the constant size + of the string_t container (which is 32 bits right now). */ + PropField_Variant /**< Valid for Data fields only Type is not known at the field level, + (for this call), but dependent on current field value. */ }; /** @@ -87,7 +86,7 @@ enum PropFieldType * networked entities (maximum edicts), rather than total * maximum entities. * - * @return Maximum number of networked entities. + * @return Maximum number of networked entities. */ native int GetMaxEntities(); @@ -98,7 +97,7 @@ native int GetMaxEntities(); * of networked entities (current edicts), rather than total * count of current entities. * - * @return Number of entities in the server. + * @return Number of entities in the server. */ native int GetEntityCount(); @@ -106,75 +105,75 @@ native int GetEntityCount(); * Returns whether or not an entity is valid. Returns false * if there is no matching CBaseEntity for this entity index. * - * @param entity Index of the entity. - * @return True if valid, false otherwise. + * @param entity Index of the entity. + * @return True if valid, false otherwise. */ native bool IsValidEntity(int entity); /** * Returns whether or not an edict index is valid. * - * @param edict Index of the edict. - * @return True if valid, false otherwise. + * @param edict Index of the edict. + * @return True if valid, false otherwise. */ native bool IsValidEdict(int edict); /** * Returns whether or not an entity has a valid networkable edict. * - * @param edict Index of the entity. - * @return True if networkable, false if invalid or not networkable. + * @param entity Index of the entity. + * @return True if networkable, false if invalid or not networkable. */ -native bool IsEntNetworkable(int entiy); +native bool IsEntNetworkable(int entity); /** * Creates a new edict (the basis of a networkable entity) * - * @return Index of the edict, 0 on failure. + * @return Index of the edict, 0 on failure. */ native int CreateEdict(); /** * Removes an edict from the world. * - * @param edict Index of the edict. - * @error Invalid edict index. + * @param edict Index of the edict. + * @error Invalid edict index. */ native void RemoveEdict(int edict); /** * Marks an entity for deletion. * - * @param entity Index of the entity. - * @error Invalid entity index. + * @param entity Index of the entity. + * @error Invalid entity index. */ native void RemoveEntity(int entity); /** * Returns the flags on an edict. These are not the same as entity flags. * - * @param edict Index of the entity. - * @return Edict flags. - * @error Invalid edict index. + * @param edict Index of the entity. + * @return Edict flags. + * @error Invalid edict index. */ native int GetEdictFlags(int edict); /** * Sets the flags on an edict. These are not the same as entity flags. * - * @param edict Index of the entity. - * @param flags Flags to set. - * @error Invalid edict index. + * @param edict Index of the entity. + * @param flags Flags to set. + * @error Invalid edict index. */ native void SetEdictFlags(int edict, int flags); /** * Retrieves an edict classname. * - * @param edict Index of the entity. - * @param clsname Buffer to store the classname. - * @param maxlength Maximum length of the buffer. - * @return True on success, false if there is no classname set. + * @param edict Index of the entity. + * @param clsname Buffer to store the classname. + * @param maxlength Maximum length of the buffer. + * @return True on success, false if there is no classname set. */ native bool GetEdictClassname(int edict, char[] clsname, int maxlength); @@ -182,11 +181,11 @@ native bool GetEdictClassname(int edict, char[] clsname, int maxlength); * Retrieves an entity's networkable serverclass name. * This is not the same as the classname and is used for networkable state changes. * - * @param edict Index of the entity. - * @param clsname Buffer to store the serverclass name. - * @param maxlength Maximum length of the buffer. - * @return True on success, false if the edict is not networkable. - * @error Invalid edict index. + * @param edict Index of the entity. + * @param clsname Buffer to store the serverclass name. + * @param maxlength Maximum length of the buffer. + * @return True on success, false if the edict is not networkable. + * @error Invalid edict index. */ native bool GetEntityNetClass(int edict, char[] clsname, int maxlength); @@ -216,10 +215,10 @@ native bool GetEntityNetClass(int edict, char[] clsname, int maxlength); * and wish for it to be immediately changed over the network. By default this * is not done for offset setting functions. * - * @param edict Index to the edict. - * @param offset Offset to mark as changed. If 0, - * the entire edict is marked as changed. - * @error Invalid entity or offset out of bounds. + * @param edict Index to the edict. + * @param offset Offset to mark as changed. If 0, + * the entire edict is marked as changed. + * @error Invalid entity or offset out of bounds. */ native void ChangeEdictState(int edict, int offset = 0); @@ -227,11 +226,11 @@ native void ChangeEdictState(int edict, int offset = 0); * Peeks into an entity's object data and retrieves the integer value at * the given offset. * - * @param entity Edict index. - * @param offset Offset to use. - * @param size Number of bytes to read (valid values are 1, 2, or 4). - * @return Value at the given memory location. - * @error Invalid entity or offset out of reasonable bounds. + * @param entity Edict index. + * @param offset Offset to use. + * @param size Number of bytes to read (valid values are 1, 2, or 4). + * @return Value at the given memory location. + * @error Invalid entity or offset out of reasonable bounds. */ native int GetEntData(int entity, int offset, int size=4); @@ -239,12 +238,12 @@ native int GetEntData(int entity, int offset, int size=4); * Peeks into an entity's object data and sets the integer value at * the given offset. * - * @param entity Edict index. - * @param offset Offset to use. - * @param value Value to set. - * @param size Number of bytes to write (valid values are 1, 2, or 4). - * @param changeState If true, change will be sent over the network. - * @error Invalid entity or offset out of reasonable bounds. + * @param entity Edict index. + * @param offset Offset to use. + * @param value Value to set. + * @param size Number of bytes to write (valid values are 1, 2, or 4). + * @param changeState If true, change will be sent over the network. + * @error Invalid entity or offset out of reasonable bounds. */ native void SetEntData(int entity, int offset, any value, int size=4, bool changeState=false); @@ -252,10 +251,10 @@ native void SetEntData(int entity, int offset, any value, int size=4, bool chang * Peeks into an entity's object data and retrieves the float value at * the given offset. * - * @param entity Edict index. - * @param offset Offset to use. - * @return Value at the given memory location. - * @error Invalid entity or offset out of reasonable bounds. + * @param entity Edict index. + * @param offset Offset to use. + * @return Value at the given memory location. + * @error Invalid entity or offset out of reasonable bounds. */ native float GetEntDataFloat(int entity, int offset); @@ -263,11 +262,11 @@ native float GetEntDataFloat(int entity, int offset); * Peeks into an entity's object data and sets the float value at * the given offset. * - * @param entity Edict index. - * @param offset Offset to use. - * @param value Value to set. - * @param changeState If true, change will be sent over the network. - * @error Invalid entity or offset out of reasonable bounds. + * @param entity Edict index. + * @param offset Offset to use. + * @param value Value to set. + * @param changeState If true, change will be sent over the network. + * @error Invalid entity or offset out of reasonable bounds. */ native void SetEntDataFloat(int entity, int offset, float value, bool changeState=false); @@ -281,10 +280,11 @@ native void SetEntDataFloat(int entity, int offset, float value, bool changeStat * Note: This function makes no attempt to validate the returned * entity, and in fact, it could be garbage or completely unexpected. * - * @param entity Edict index. - * @param offset Offset to use. - * @return Entity index at the given location, or 0 if none. - * @error Invalid entity or offset out of reasonable bounds. + * @param entity Edict index. + * @param offset Offset to use. + * @return Entity index at the given location, or 0 if none. + * @error Invalid entity or offset out of reasonable bounds. + * @deprecated Use GetEntDataEnt2() instead. */ #pragma deprecated Use GetEntDataEnt2() instead. native int GetEntDataEnt(int entity, int offset); @@ -297,11 +297,12 @@ native int GetEntDataEnt(int entity, int offset); * 0 is also the world entity index. Thus, a property cannot * be set to the world entity using this native. * - * @param entity Edict index. - * @param offset Offset to use. - * @param other Entity index to set, or 0 to clear. - * @param changeState If true, change will be sent over the network. - * @error Invalid entity or offset out of reasonable bounds. + * @param entity Edict index. + * @param offset Offset to use. + * @param other Entity index to set, or 0 to clear. + * @param changeState If true, change will be sent over the network. + * @error Invalid entity or offset out of reasonable bounds. + * @deprecated Use SetEntDataEnt2() instead. */ #pragma deprecated Use SetEntDataEnt2() instead. native void SetEntDataEnt(int entity, int offset, int other, bool changeState=false); @@ -314,11 +315,11 @@ native void SetEntDataEnt(int entity, int offset, int other, bool changeState=fa * handles" (which usually looks like m_h* in properties). These * are not SourceMod Handles, but internal Source structures. * - * @param entity Edict index. - * @param offset Offset to use. - * @return Entity index at the given location. If there is no entity, - * or the stored entity is invalid, then -1 is returned. - * @error Invalid input entity, or offset out of reasonable bounds. + * @param entity Edict index. + * @param offset Offset to use. + * @return Entity index at the given location. If there is no entity, + * or the stored entity is invalid, then -1 is returned. + * @error Invalid input entity, or offset out of reasonable bounds. */ native int GetEntDataEnt2(int entity, int offset); @@ -330,11 +331,11 @@ native int GetEntDataEnt2(int entity, int offset); * handles" (which usually looks like m_h* in properties). These * are not SourceMod Handles, but internal Source structures. * - * @param entity Edict index. - * @param offset Offset to use. - * @param other Entity index to set, or -1 to clear. - * @param changeState If true, change will be sent over the network. - * @error Invalid input entity, or offset out of reasonable bounds. + * @param entity Edict index. + * @param offset Offset to use. + * @param other Entity index to set, or -1 to clear. + * @param changeState If true, change will be sent over the network. + * @error Invalid input entity, or offset out of reasonable bounds. */ native void SetEntDataEnt2(int entity, int offset, int other, bool changeState=false); @@ -342,12 +343,12 @@ native void SetEntDataEnt2(int entity, int offset, int other, bool changeState=f * Peeks into an entity's object data and retrieves the vector at the * given offset. * @note Both a Vector and a QAngle are three floats. This is a - * convenience function and will work with both types. + * convenience function and will work with both types. * - * @param entity Edict index. - * @param offset Offset to use. - * @param vec Vector buffer to store data in. - * @error Invalid entity or offset out of reasonable bounds. + * @param entity Edict index. + * @param offset Offset to use. + * @param vec Vector buffer to store data in. + * @error Invalid entity or offset out of reasonable bounds. */ native void GetEntDataVector(int entity, int offset, float vec[3]); @@ -355,13 +356,13 @@ native void GetEntDataVector(int entity, int offset, float vec[3]); * Peeks into an entity's object data and sets the vector at the given * offset. * @note Both a Vector and a QAngle are three floats. This is a - * convenience function and will work with both types. + * convenience function and will work with both types. * - * @param entity Edict index. - * @param offset Offset to use. - * @param vec Vector to set. - * @param changeState If true, change will be sent over the network. - * @error Invalid entity or offset out of reasonable bounds. + * @param entity Edict index. + * @param offset Offset to use. + * @param vec Vector to set. + * @param changeState If true, change will be sent over the network. + * @error Invalid entity or offset out of reasonable bounds. */ native void SetEntDataVector(int entity, int offset, const float vec[3], bool changeState=false); @@ -369,12 +370,12 @@ native void SetEntDataVector(int entity, int offset, const float vec[3], bool ch * Peeks into an entity's object data and retrieves the string at * the given offset. * - * @param entity Edict index. - * @param offset Offset to use. - * @param buffer Destination string buffer. - * @param maxlen Maximum length of output string buffer. - * @return Number of non-null bytes written. - * @error Invalid entity or offset out of reasonable bounds. + * @param entity Edict index. + * @param offset Offset to use. + * @param buffer Destination string buffer. + * @param maxlen Maximum length of output string buffer. + * @return Number of non-null bytes written. + * @error Invalid entity or offset out of reasonable bounds. */ native int GetEntDataString(int entity, int offset, char[] buffer, int maxlen); @@ -382,13 +383,13 @@ native int GetEntDataString(int entity, int offset, char[] buffer, int maxlen); * Peeks into an entity's object data and sets the string at * the given offset. * - * @param entity Edict index. - * @param offset Offset to use. - * @param buffer String to set. - * @param maxlen Maximum length of bytes to write. - * @param changeState If true, change will be sent over the network. - * @return Number of non-null bytes written. - * @error Invalid entity or offset out of reasonable bounds. + * @param entity Edict index. + * @param offset Offset to use. + * @param buffer String to set. + * @param maxlen Maximum length of bytes to write. + * @param changeState If true, change will be sent over the network. + * @return Number of non-null bytes written. + * @error Invalid entity or offset out of reasonable bounds. */ native int SetEntDataString(int entity, int offset, const char[] buffer, int maxlen, bool changeState=false); @@ -406,9 +407,10 @@ native int SetEntDataString(int entity, int offset, const char[] buffer, int max * should use FindSendPropInfo() instead. An example of such a property is * CTFPlayer::DT_LocalPlayer.m_nDisguiseClass on Team Fortress. * - * @param cls Classname. - * @param prop Property name. - * @return An offset, or -1 on failure. + * @param cls Classname. + * @param prop Property name. + * @return An offset, or -1 on failure. + * @deprecated Use FindSendPropInfo instead, or HasEntProp if you just want to check for existence. */ #pragma deprecated Use FindSendPropInfo instead, or HasEntProp if you just want to check for existence. native int FindSendPropOffs(const char[] cls, const char[] prop); @@ -417,18 +419,18 @@ native int FindSendPropOffs(const char[] cls, const char[] prop); * Given a ServerClass name, finds a networkable send property offset. * This information is cached for future calls. * - * @param cls Classname. - * @param prop Property name. - * @param type Optional parameter to store the type. - * @param num_bits Optional parameter to store the number of bits the field - * uses, if applicable (otherwise 0 is stored). The number - * of bits varies for integers and floats, and is always 0 - * for strings. - * @param local_offset Optional parameter to store the local offset, as - * FindSendPropOffs() would return. - * @return On success, returns an absolutely computed offset. - * If no offset is available, 0 is returned. - * If the property is not found, -1 is returned. + * @param cls Classname. + * @param prop Property name. + * @param type Optional parameter to store the type. + * @param num_bits Optional parameter to store the number of bits the field + * uses, if applicable (otherwise 0 is stored). The number + * of bits varies for integers and floats, and is always 0 + * for strings. + * @param local_offset Optional parameter to store the local offset, as + * FindSendPropOffs() would return. + * @return On success, returns an absolutely computed offset. + * If no offset is available, 0 is returned. + * If the property is not found, -1 is returned. */ native int FindSendPropInfo(const char[] cls, const char[] prop, @@ -440,13 +442,14 @@ native int FindSendPropInfo(const char[] cls, * Given an entity, finds a datamap property offset. * This information is cached for future calls. * - * @param entity Entity index. - * @param prop Property name. - * @param type Optional parameter to store the type. - * @param num_bits Optional parameter to store the number of bits the field - * uses. The bit count will either be 1 (for boolean) or - * divisible by 8 (including 0 if unknown). - * @return An offset, or -1 on failure. + * @param entity Entity index. + * @param prop Property name. + * @param type Optional parameter to store the type. + * @param num_bits Optional parameter to store the number of bits the field + * uses. The bit count will either be 1 (for boolean) or + * divisible by 8 (including 0 if unknown). + * @return An offset, or -1 on failure. + * @deprecated Use FindDataMapInfo instead, or HasEntProp if you just want to check for existence. */ #pragma deprecated Use FindDataMapInfo instead, or HasEntProp if you just want to check for existence. native int FindDataMapOffs(int entity, @@ -458,15 +461,15 @@ native int FindDataMapOffs(int entity, * Given an entity, finds a nested datamap property offset. * This information is cached for future calls. * - * @param entity Entity index. - * @param prop Property name. - * @param type Optional parameter to store the type. - * @param num_bits Optional parameter to store the number of bits the field - * uses. The bit count will either be 1 (for boolean) or - * divisible by 8 (including 0 if unknown). - * @param local_offset Optional parameter to store the local offset, as - * FindDataMapOffs() would return. - * @return An offset, or -1 on failure. + * @param entity Entity index. + * @param prop Property name. + * @param type Optional parameter to store the type. + * @param num_bits Optional parameter to store the number of bits the field + * uses. The bit count will either be 1 (for boolean) or + * divisible by 8 (including 0 if unknown). + * @param local_offset Optional parameter to store the local offset, as + * FindDataMapOffs() would return. + * @return An offset, or -1 on failure. */ native int FindDataMapInfo(int entity, const char[] prop, @@ -477,12 +480,12 @@ native int FindDataMapInfo(int entity, /** * Wrapper function for finding a send property for a particular entity. * - * @param ent Entity index. - * @param prop Property name. - * @param actual Defaults to false for backwards compatibility. - * If true, the newer FindSendPropInfo() function - * is used instead. - * @return An offset, or -1 on failure. + * @param ent Entity index. + * @param prop Property name. + * @param actual Defaults to false for backwards compatibility. + * If true, the newer FindSendPropInfo() function + * is used instead. + * @return An offset, or -1 on failure. */ stock int GetEntSendPropOffs(int ent, const char[] prop, bool actual=false) { @@ -499,32 +502,35 @@ stock int GetEntSendPropOffs(int ent, const char[] prop, bool actual=false) if (actual) { return offset; - } else { - return local; } + + return local; } /** * Checks if an entity property exists on an entity. * - * @param entity Entity/edict index. - * @param type Property type. - * @param prop Property name. - * @return Whether the property exists on the entity. - * @error Invalid entity. + * @param entity Entity/edict index. + * @param type Property type. + * @param prop Property name. + * @return Whether the property exists on the entity. + * @error Invalid entity. */ stock bool HasEntProp(int entity, PropType type, const char[] prop) { - if (type == Prop_Data) { + if (type == Prop_Data) + { return (FindDataMapInfo(entity, prop) != -1); } - if (type != Prop_Send) { + if (type != Prop_Send) + { return false; } char cls[64]; - if (!GetEntityNetClass(entity, cls, sizeof(cls))) { + if (!GetEntityNetClass(entity, cls, sizeof(cls))) + { return false; } @@ -537,15 +543,15 @@ stock bool HasEntProp(int entity, PropType type, const char[] prop) * This function is considered safer and more robust over GetEntData, * because it performs strict offset checking and typing rules. * - * @param entity Entity/edict index. - * @param type Property type. - * @param prop Property name. - * @param size Number of bytes to write (valid values are 1, 2, or 4). - * This value is auto-detected, and the size parameter is - * only used as a fallback in case detection fails. - * @param element Element # (starting from 0) if property is an array. - * @return Value at the given property offset. - * @error Invalid entity or property not found. + * @param entity Entity/edict index. + * @param type Property type. + * @param prop Property name. + * @param size Number of bytes to write (valid values are 1, 2, or 4). + * This value is auto-detected, and the size parameter is + * only used as a fallback in case detection fails. + * @param element Element # (starting from 0) if property is an array. + * @return Value at the given property offset. + * @error Invalid entity or property not found. */ native int GetEntProp(int entity, PropType type, const char[] prop, int size=4, int element=0); @@ -555,15 +561,15 @@ native int GetEntProp(int entity, PropType type, const char[] prop, int size=4, * This function is considered safer and more robust over SetEntData, * because it performs strict offset checking and typing rules. * - * @param entity Entity/edict index. - * @param type Property type. - * @param prop Property name. - * @param value Value to set. - * @param size Number of bytes to write (valid values are 1, 2, or 4). - * This value is auto-detected, and the size parameter is - * only used as a fallback in case detection fails. - * @param element Element # (starting from 0) if property is an array. - * @error Invalid entity or offset out of reasonable bounds. + * @param entity Entity/edict index. + * @param type Property type. + * @param prop Property name. + * @param value Value to set. + * @param size Number of bytes to write (valid values are 1, 2, or 4). + * This value is auto-detected, and the size parameter is + * only used as a fallback in case detection fails. + * @param element Element # (starting from 0) if property is an array. + * @error Invalid entity or offset out of reasonable bounds. */ native void SetEntProp(int entity, PropType type, const char[] prop, any value, int size=4, int element=0); @@ -573,12 +579,12 @@ native void SetEntProp(int entity, PropType type, const char[] prop, any value, * This function is considered safer and more robust over GetEntDataFloat, * because it performs strict offset checking and typing rules. * - * @param entity Entity/edict index. - * @param type Property type. - * @param prop Property name. - * @param element Element # (starting from 0) if property is an array. - * @return Value at the given property offset. - * @error Invalid entity or offset out of reasonable bounds. + * @param entity Entity/edict index. + * @param type Property type. + * @param prop Property name. + * @param element Element # (starting from 0) if property is an array. + * @return Value at the given property offset. + * @error Invalid entity or offset out of reasonable bounds. */ native float GetEntPropFloat(int entity, PropType type, const char[] prop, int element=0); @@ -588,12 +594,12 @@ native float GetEntPropFloat(int entity, PropType type, const char[] prop, int e * This function is considered safer and more robust over SetEntDataFloat, * because it performs strict offset checking and typing rules. * - * @param entity Entity/edict index. - * @param type Property type. - * @param prop Property name. - * @param value Value to set. - * @param element Element # (starting from 0) if property is an array. - * @error Invalid entity or offset out of reasonable bounds. + * @param entity Entity/edict index. + * @param type Property type. + * @param prop Property name. + * @param value Value to set. + * @param element Element # (starting from 0) if property is an array. + * @error Invalid entity or offset out of reasonable bounds. */ native void SetEntPropFloat(int entity, PropType type, const char[] prop, float value, int element=0); @@ -603,14 +609,14 @@ native void SetEntPropFloat(int entity, PropType type, const char[] prop, float * This function is considered safer and more robust over GetEntDataEnt*, * because it performs strict offset checking and typing rules. * - * @param entity Entity/edict index. - * @param type Property type. - * @param prop Property name. - * @param element Element # (starting from 0) if property is an array. - * @return Entity index at the given property. - * If there is no entity, or the entity is not valid, - * then -1 is returned. - * @error Invalid entity or offset out of reasonable bounds. + * @param entity Entity/edict index. + * @param type Property type. + * @param prop Property name. + * @param element Element # (starting from 0) if property is an array. + * @return Entity index at the given property. + * If there is no entity, or the entity is not valid, + * then -1 is returned. + * @error Invalid entity or offset out of reasonable bounds. */ native int GetEntPropEnt(int entity, PropType type, const char[] prop, int element=0); @@ -620,12 +626,12 @@ native int GetEntPropEnt(int entity, PropType type, const char[] prop, int eleme * This function is considered safer and more robust over SetEntDataEnt*, * because it performs strict offset checking and typing rules. * - * @param entity Entity/edict index. - * @param type Property type. - * @param prop Property name. - * @param other Entity index to set, or -1 to unset. - * @param element Element # (starting from 0) if property is an array. - * @error Invalid entity or offset out of reasonable bounds. + * @param entity Entity/edict index. + * @param type Property type. + * @param prop Property name. + * @param other Entity index to set, or -1 to unset. + * @param element Element # (starting from 0) if property is an array. + * @error Invalid entity or offset out of reasonable bounds. */ native void SetEntPropEnt(int entity, PropType type, const char[] prop, int other, int element=0); @@ -635,13 +641,13 @@ native void SetEntPropEnt(int entity, PropType type, const char[] prop, int othe * This function is considered safer and more robust over GetEntDataVector, * because it performs strict offset checking and typing rules. * - * @param entity Entity/edict index. - * @param type Property type. - * @param prop Property name. - * @param vec Vector buffer to store data in. - * @param element Element # (starting from 0) if property is an array. - * @error Invalid entity, property not found, or property not - * actually a vector data type. + * @param entity Entity/edict index. + * @param type Property type. + * @param prop Property name. + * @param vec Vector buffer to store data in. + * @param element Element # (starting from 0) if property is an array. + * @error Invalid entity, property not found, or property not + * actually a vector data type. */ native void GetEntPropVector(int entity, PropType type, const char[] prop, float vec[3], int element=0); @@ -651,84 +657,86 @@ native void GetEntPropVector(int entity, PropType type, const char[] prop, float * This function is considered safer and more robust over SetEntDataVector, * because it performs strict offset checking and typing rules. * - * @param entity Entity/edict index. - * @param type Property type. - * @param prop Property name. - * @param vec Vector to set. - * @param element Element # (starting from 0) if property is an array. - * @error Invalid entity, property not found, or property not - * actually a vector data type. + * @param entity Entity/edict index. + * @param type Property type. + * @param prop Property name. + * @param vec Vector to set. + * @param element Element # (starting from 0) if property is an array. + * @error Invalid entity, property not found, or property not + * actually a vector data type. */ native void SetEntPropVector(int entity, PropType type, const char[] prop, const float vec[3], int element=0); /** * Gets a network property as a string. * - * @param entity Edict index. - * @param type Property type. - * @param prop Property to use. - * @param buffer Destination string buffer. - * @param maxlen Maximum length of output string buffer. - * @param element Element # (starting from 0) if property is an array. - * @return Number of non-null bytes written. - * @error Invalid entity, offset out of reasonable bounds, or property is not a valid string. + * @param entity Edict index. + * @param type Property type. + * @param prop Property to use. + * @param buffer Destination string buffer. + * @param maxlen Maximum length of output string buffer. + * @param element Element # (starting from 0) if property is an array. + * @return Number of non-null bytes written. + * @error Invalid entity, offset out of reasonable bounds, or property is not a valid string. */ native int GetEntPropString(int entity, PropType type, const char[] prop, char[] buffer, int maxlen, int element=0); /** * Sets a network property as a string. * - * @param entity Edict index. - * @param type Property type. - * @param prop Property to use. - * @param buffer String to set. - * @param element Element # (starting from 0) if property is an array. - * @return Number of non-null bytes written. - * @error Invalid entity, offset out of reasonable bounds, or property is not a valid string. + * @param entity Edict index. + * @param type Property type. + * @param prop Property to use. + * @param buffer String to set. + * @param element Element # (starting from 0) if property is an array. + * @return Number of non-null bytes written. + * @error Invalid entity, offset out of reasonable bounds, or property is not a valid string. */ native int SetEntPropString(int entity, PropType type, const char[] prop, const char[] buffer, int element=0); /** * Retrieves the count of values that an entity property's array can store. * - * @param entity Entity/edict index. - * @param type Property type. - * @param prop Property name. - * @return Size of array (in elements) or 1 if property is not an array. - * @error Invalid entity or property not found. + * @param entity Entity/edict index. + * @param type Property type. + * @param prop Property name. + * @return Size of array (in elements) or 1 if property is not an array. + * @error Invalid entity or property not found. */ native int GetEntPropArraySize(int entity, PropType type, const char[] prop); /** * Copies an array of cells from an entity at a given offset. * - * @param entity Entity index. - * @param offset Offset to use. - * @param array Array to read into. - * @param arraySize Number of values to read. - * @param dataSize Size of each value in bytes (1, 2, or 4). - * @error Invalid entity or offset out of reasonable bounds. + * @param entity Entity index. + * @param offset Offset to use. + * @param array Array to read into. + * @param arraySize Number of values to read. + * @param dataSize Size of each value in bytes (1, 2, or 4). + * @error Invalid entity or offset out of reasonable bounds. */ stock void GetEntDataArray(int entity, int offset, int[] array, int arraySize, int dataSize=4) { - for (int i=0; i(GetEntProp(entity, Prop_Data, datamap)); } /** * Sets an entity's movetype. * - * @param entity Entity index. - * @param mt Movetype, see enum above. - * @error Invalid entity index, or lack of mod compliance. + * @param entity Entity index. + * @param mt Movetype, see enum above. + * @error Invalid entity index, or lack of mod compliance. */ stock void SetEntityMoveType(int entity, MoveType mt) { static bool gotconfig = false; static char datamap[32]; - + if (!gotconfig) { - Handle gc = LoadGameConfigFile("core.games"); - bool exists = GameConfGetKeyValue(gc, "m_MoveType", datamap, sizeof(datamap)); - CloseHandle(gc); - + GameData gc = new GameData("core.games"); + bool exists = gc.GetKeyValue("m_MoveType", datamap, sizeof(datamap)); + delete gc; + if (!exists) { strcopy(datamap, sizeof(datamap), "m_MoveType"); } - + gotconfig = true; } - + SetEntProp(entity, Prop_Data, datamap, mt); } /** * Gets an entity's render mode. * - * @param entity Entity index. - * @return RenderMode value. - * @error Invalid entity index, or lack of mod compliance. + * @param entity Entity index. + * @return RenderMode value. + * @error Invalid entity index, or lack of mod compliance. */ stock RenderMode GetEntityRenderMode(int entity) { static bool gotconfig = false; static char prop[32]; - + if (!gotconfig) { - Handle gc = LoadGameConfigFile("core.games"); - bool exists = GameConfGetKeyValue(gc, "m_nRenderMode", prop, sizeof(prop)); - CloseHandle(gc); - + GameData gc = new GameData("core.games"); + bool exists = gc.GetKeyValue("m_nRenderMode", prop, sizeof(prop)); + delete gc; + if (!exists) { strcopy(prop, sizeof(prop), "m_nRenderMode"); } - + gotconfig = true; } - + return view_as(GetEntProp(entity, Prop_Send, prop, 1)); } /** * Sets an entity's render mode. * - * @param entity Entity index. - * @param mode RenderMode value. - * @error Invalid entity index, or lack of mod compliance. + * @param entity Entity index. + * @param mode RenderMode value. + * @error Invalid entity index, or lack of mod compliance. */ stock void SetEntityRenderMode(int entity, RenderMode mode) { static bool gotconfig = false; static char prop[32]; - + if (!gotconfig) { - Handle gc = LoadGameConfigFile("core.games"); - bool exists = GameConfGetKeyValue(gc, "m_nRenderMode", prop, sizeof(prop)); - CloseHandle(gc); - + GameData gc = new GameData("core.games"); + bool exists = gc.GetKeyValue("m_nRenderMode", prop, sizeof(prop)); + delete gc; + if (!exists) { strcopy(prop, sizeof(prop), "m_nRenderMode"); } - + gotconfig = true; } - + SetEntProp(entity, Prop_Send, prop, mode, 1); } /** * Gets an entity's render Fx. * - * @param entity Entity index. - * @return RenderFx value. - * @error Invalid entity index, or lack of mod compliance. + * @param entity Entity index. + * @return RenderFx value. + * @error Invalid entity index, or lack of mod compliance. */ stock RenderFx GetEntityRenderFx(int entity) { static bool gotconfig = false; static char prop[32]; - + if (!gotconfig) { - Handle gc = LoadGameConfigFile("core.games"); - bool exists = GameConfGetKeyValue(gc, "m_nRenderFX", prop, sizeof(prop)); - CloseHandle(gc); - + GameData gc = new GameData("core.games"); + bool exists = gc.GetKeyValue("m_nRenderFX", prop, sizeof(prop)); + delete gc; + if (!exists) { strcopy(prop, sizeof(prop), "m_nRenderFX"); } - + gotconfig = true; } - + return view_as(GetEntProp(entity, Prop_Send, prop, 1)); } /** * Sets an entity's render Fx. * - * @param entity Entity index. - * @param fx RenderFx value. - * @error Invalid entity index, or lack of mod compliance. + * @param entity Entity index. + * @param fx RenderFx value. + * @error Invalid entity index, or lack of mod compliance. */ stock void SetEntityRenderFx(int entity, RenderFx fx) { static bool gotconfig = false; static char prop[32]; - + if (!gotconfig) { - Handle gc = LoadGameConfigFile("core.games"); - bool exists = GameConfGetKeyValue(gc, "m_nRenderFX", prop, sizeof(prop)); - CloseHandle(gc); - + GameData gc = new GameData("core.games"); + bool exists = gc.GetKeyValue("m_nRenderFX", prop, sizeof(prop)); + delete gc; + if (!exists) { strcopy(prop, sizeof(prop), "m_nRenderFX"); } - + gotconfig = true; } - + SetEntProp(entity, Prop_Send, prop, fx, 1); } /** * Gets an entity's color. * - * @param entity Entity index. - * @param r Amount of red (0-255) - * @param g Amount of green (0-255) - * @param b Amount of blue (0-255) - * @param a Amount of alpha (0-255) - * @error Invalid entity index, or lack of mod compliance. + * @param entity Entity index. + * @param r Amount of red (0-255) + * @param g Amount of green (0-255) + * @param b Amount of blue (0-255) + * @param a Amount of alpha (0-255) + * @error Invalid entity index, or lack of mod compliance. */ stock void GetEntityRenderColor(int entity, int &r, int &g, int &b, int &a) { static bool gotconfig = false; static char prop[32]; - + if (!gotconfig) { - Handle gc = LoadGameConfigFile("core.games"); - bool exists = GameConfGetKeyValue(gc, "m_clrRender", prop, sizeof(prop)); - CloseHandle(gc); - + GameData gc = new GameData("core.games"); + bool exists = gc.GetKeyValue("m_clrRender", prop, sizeof(prop)); + delete gc; + if (!exists) { strcopy(prop, sizeof(prop), "m_clrRender"); } - + gotconfig = true; } - + int offset = GetEntSendPropOffs(entity, prop); - + if (offset <= 0) { ThrowError("GetEntityRenderColor not supported by this mod"); } - + r = GetEntData(entity, offset, 1); g = GetEntData(entity, offset + 1, 1); b = GetEntData(entity, offset + 2, 1); @@ -411,39 +411,39 @@ stock void GetEntityRenderColor(int entity, int &r, int &g, int &b, int &a) /** * Sets an entity's color. * - * @param entity Entity index - * @param r Amount of red (0-255) - * @param g Amount of green (0-255) - * @param b Amount of blue (0-255) - * @param a Amount of alpha (0-255) - * @error Invalid entity index, or lack of mod compliance. + * @param entity Entity index + * @param r Amount of red (0-255) + * @param g Amount of green (0-255) + * @param b Amount of blue (0-255) + * @param a Amount of alpha (0-255) + * @error Invalid entity index, or lack of mod compliance. */ stock void SetEntityRenderColor(int entity, int r=255, int g=255, int b=255, int a=255) { static bool gotconfig = false; static char prop[32]; - + if (!gotconfig) { - Handle gc = LoadGameConfigFile("core.games"); - bool exists = GameConfGetKeyValue(gc, "m_clrRender", prop, sizeof(prop)); - CloseHandle(gc); - + GameData gc = new GameData("core.games"); + bool exists = gc.GetKeyValue("m_clrRender", prop, sizeof(prop)); + delete gc; + if (!exists) { strcopy(prop, sizeof(prop), "m_clrRender"); } - + gotconfig = true; } - + int offset = GetEntSendPropOffs(entity, prop); - + if (offset <= 0) { ThrowError("SetEntityRenderColor not supported by this mod"); } - + SetEntData(entity, offset, r, 1, true); SetEntData(entity, offset + 1, g, 1, true); SetEntData(entity, offset + 2, b, 1, true); @@ -454,104 +454,104 @@ stock void SetEntityRenderColor(int entity, int r=255, int g=255, int b=255, int * Gets an entity's gravity. * * @param entity Entity index. - * @return Entity's m_flGravity value. - * @error Invalid entity index, or lack of mod compliance. + * @return Entity's m_flGravity value. + * @error Invalid entity index, or lack of mod compliance. */ stock float GetEntityGravity(int entity) { static bool gotconfig = false; static char datamap[32]; - + if (!gotconfig) { - Handle gc = LoadGameConfigFile("core.games"); - bool exists = GameConfGetKeyValue(gc, "m_flGravity", datamap, sizeof(datamap)); - CloseHandle(gc); - + GameData gc = new GameData("core.games"); + bool exists = gc.GetKeyValue("m_flGravity", datamap, sizeof(datamap)); + delete gc; + if (!exists) { strcopy(datamap, sizeof(datamap), "m_flGravity"); } - + gotconfig = true; } - + return GetEntPropFloat(entity, Prop_Data, datamap); } /** * Sets an entity's gravity. * - * @param entity Entity index. - * @param amount Gravity to set (default = 1.0, half = 0.5, double = 2.0). - * @error Invalid entity index, or lack of mod compliance. + * @param entity Entity index. + * @param amount Gravity to set (default = 1.0, half = 0.5, double = 2.0). + * @error Invalid entity index, or lack of mod compliance. */ stock void SetEntityGravity(int entity, float amount) { static bool gotconfig = false; static char datamap[32]; - + if (!gotconfig) { - Handle gc = LoadGameConfigFile("core.games"); - bool exists = GameConfGetKeyValue(gc, "m_flGravity", datamap, sizeof(datamap)); - CloseHandle(gc); - + GameData gc = new GameData("core.games"); + bool exists = gc.GetKeyValue("m_flGravity", datamap, sizeof(datamap)); + delete gc; + if (!exists) { strcopy(datamap, sizeof(datamap), "m_flGravity"); } - + gotconfig = true; } - + SetEntPropFloat(entity, Prop_Data, datamap, amount); } /** * Sets an entity's health * - * @param entity Entity index. - * @param amount Health amount. - * @error Invalid entity index, or lack of mod compliance. + * @param entity Entity index. + * @param amount Health amount. + * @error Invalid entity index, or lack of mod compliance. */ stock void SetEntityHealth(int entity, int amount) { static bool gotconfig = false; static char prop[32]; - + if (!gotconfig) { - Handle gc = LoadGameConfigFile("core.games"); - bool exists = GameConfGetKeyValue(gc, "m_iHealth", prop, sizeof(prop)); - CloseHandle(gc); - + GameData gc = new GameData("core.games"); + bool exists = gc.GetKeyValue("m_iHealth", prop, sizeof(prop)); + delete gc; + if (!exists) { strcopy(prop, sizeof(prop), "m_iHealth"); } - + gotconfig = true; } - + char cls[64]; PropFieldType type; int offset; - + if (!GetEntityNetClass(entity, cls, sizeof(cls))) { ThrowError("SetEntityHealth not supported by this mod: Could not get serverclass name"); return; } - + offset = FindSendPropInfo(cls, prop, type); - + if (offset <= 0) { ThrowError("SetEntityHealth not supported by this mod"); return; } - + /* Dark Messiah uses a float for the health instead an integer */ if (type == PropField_Float) { @@ -566,29 +566,29 @@ stock void SetEntityHealth(int entity, int amount) /** * Get's a users current pressed buttons * - * @param client Client index - * @return Bitsum of buttons - * @error Invalid client index, client not in game, - * or lack of mod compliance. + * @param client Client index + * @return Bitsum of buttons + * @error Invalid client index, client not in game, + * or lack of mod compliance. */ stock int GetClientButtons(int client) { static bool gotconfig = false; static char datamap[32]; - + if (!gotconfig) { - Handle gc = LoadGameConfigFile("core.games"); - bool exists = GameConfGetKeyValue(gc, "m_nButtons", datamap, sizeof(datamap)); - CloseHandle(gc); - + GameData gc = new GameData("core.games"); + bool exists = gc.GetKeyValue("m_nButtons", datamap, sizeof(datamap)); + delete gc; + if (!exists) { strcopy(datamap, sizeof(datamap), "m_nButtons"); } - + gotconfig = true; } - + return GetEntProp(client, Prop_Data, datamap); } diff --git a/addons/sourcemod/scripting/include/events.inc b/addons/sourcemod/scripting/include/events.inc index dea14a3..6bba666 100644 --- a/addons/sourcemod/scripting/include/events.inc +++ b/addons/sourcemod/scripting/include/events.inc @@ -40,9 +40,9 @@ */ enum EventHookMode { - EventHookMode_Pre, //< Hook callback fired before event is fired */ - EventHookMode_Post, //< Hook callback fired after event is fired */ - EventHookMode_PostNoCopy //< Hook callback fired after event is fired, but event data won't be copied */ + EventHookMode_Pre, //< Hook callback fired before event is fired */ + EventHookMode_Post, //< Hook callback fired after event is fired */ + EventHookMode_PostNoCopy //< Hook callback fired after event is fired, but event data won't be copied */ }; /** @@ -52,20 +52,22 @@ typeset EventHook { // Called when a game event is fired. // - // @param event Handle to event. This could be INVALID_HANDLE if every plugin hooking - // this event has set the hook mode EventHookMode_PostNoCopy. - // @param name String containing the name of the event. - // @param dontBroadcast True if event was not broadcast to clients, false otherwise. - // @return Ignored for post hooks. Plugin_Handled will block event if hooked as pre. + // @param event Handle to event. This could be INVALID_HANDLE if every plugin hooking + // this event has set the hook mode EventHookMode_PostNoCopy. + // @param name String containing the name of the event. + // @param dontBroadcast True if event was not broadcast to clients, false otherwise. + // May not correspond to the real value. Use the property BroadcastDisabled. + // @return Ignored for post hooks. Plugin_Handled will block event if hooked as pre. /// function Action (Event event, const char[] name, bool dontBroadcast); + // // Called when a game event is fired. // - // @param event Handle to event. This could be INVALID_HANDLE if every plugin hooking - // this event has set the hook mode EventHookMode_PostNoCopy. - // @param name String containing the name of the event. - // @param dontBroadcast True if event was not broadcast to clients, false otherwise. + // @param event Handle to event. This could be INVALID_HANDLE if every plugin hooking + // this event has set the hook mode EventHookMode_PostNoCopy. + // @param name String containing the name of the event. + // @param dontBroadcast True if event was not broadcast to clients, false otherwise. /// function void (Event event, const char[] name, bool dontBroadcast); }; @@ -83,7 +85,7 @@ methodmap Event < Handle // // Unlike Fire, this function DOES NOT close the event Handle. // - // @param client Index of client to receive the event.. + // @param client Index of client to receive the event.. public native void FireToClient(int client); // Cancels a previously created game event that has not been fired. This @@ -160,37 +162,38 @@ methodmap Event < Handle // or HookEventEx callbacks. property bool BroadcastDisabled { public native set(bool dontBroadcast); + public native get(); } } /** * Creates a hook for when a game event is fired. * - * @param name Name of event. - * @param callback An EventHook function pointer. - * @param mode Optional EventHookMode determining the type of hook. - * @error Invalid event name or invalid callback function. + * @param name Name of event. + * @param callback An EventHook function pointer. + * @param mode Optional EventHookMode determining the type of hook. + * @error Invalid event name or invalid callback function. */ native void HookEvent(const char[] name, EventHook callback, EventHookMode mode=EventHookMode_Post); /** * Creates a hook for when a game event is fired. * - * @param name Name of event. - * @param callback An EventHook function pointer. - * @param mode Optional EventHookMode determining the type of hook. - * @return True if event exists and was hooked successfully, false otherwise. - * @error Invalid callback function. + * @param name Name of event. + * @param callback An EventHook function pointer. + * @param mode Optional EventHookMode determining the type of hook. + * @return True if event exists and was hooked successfully, false otherwise. + * @error Invalid callback function. */ native bool HookEventEx(const char[] name, EventHook callback, EventHookMode mode=EventHookMode_Post); /** * Removes a hook for when a game event is fired. * - * @param name Name of event. - * @param callback An EventHook function pointer. - * @param mode Optional EventHookMode determining the type of hook. - * @error Invalid callback function or no active hook for specified event. + * @param name Name of event. + * @param callback An EventHook function pointer. + * @param mode Optional EventHookMode determining the type of hook. + * @error Invalid callback function or no active hook for specified event. */ native void UnhookEvent(const char[] name, EventHook callback, EventHookMode mode=EventHookMode_Post); @@ -200,11 +203,11 @@ native void UnhookEvent(const char[] name, EventHook callback, EventHookMode mod * The Handle should not be closed via CloseHandle(). It must be closed via * event.Fire() or event.Cancel(). * - * @param name Name of event. - * @param force If set to true, this forces the event to be created even if it's not being hooked. - * Note that this will not force it if the event doesn't exist at all. - * @return Handle to event. INVALID_HANDLE is returned if the event doesn't exist or isn't - being hooked (unless force is true). + * @param name Name of event. + * @param force If set to true, this forces the event to be created even if it's not being hooked. + * Note that this will not force it if the event doesn't exist at all. + * @return Handle to event. INVALID_HANDLE is returned if the event doesn't exist or isn't + * being hooked (unless force is true). */ native Event CreateEvent(const char[] name, bool force=false); @@ -213,49 +216,49 @@ native Event CreateEvent(const char[] name, bool force=false); * * This function closes the event Handle after completing. * - * @param event Handle to the event. - * @param dontBroadcast Optional boolean that determines if event should be broadcast to clients. - * @error Invalid or corrupt Handle. + * @param event Handle to the event. + * @param dontBroadcast Optional boolean that determines if event should be broadcast to clients. + * @error Invalid or corrupt Handle. */ native void FireEvent(Handle event, bool dontBroadcast=false); /** * Cancels a previously created game event that has not been fired. * - * @param event Handled to the event. - * @error Invalid or corrupt Handle. + * @param event Handled to the event. + * @error Invalid or corrupt Handle. */ native void CancelCreatedEvent(Handle event); /** * Returns the boolean value of a game event's key. * - * @param event Handle to the event. - * @param key Name of event key. - * @param defValue Optional default value to use if the key is not found. - * @return The boolean value of the specified event key. - * @error Invalid or corrupt Handle. + * @param event Handle to the event. + * @param key Name of event key. + * @param defValue Optional default value to use if the key is not found. + * @return The boolean value of the specified event key. + * @error Invalid or corrupt Handle. */ native bool GetEventBool(Handle event, const char[] key, bool defValue=false); /** * Sets the boolean value of a game event's key. * - * @param event Handle to the event. - * @param key Name of event key. - * @param value New boolean value. - * @error Invalid or corrupt Handle. + * @param event Handle to the event. + * @param key Name of event key. + * @param value New boolean value. + * @error Invalid or corrupt Handle. */ native void SetEventBool(Handle event, const char[] key, bool value); /** * Returns the integer value of a game event's key. * - * @param event Handle to the event. - * @param key Name of event key. - * @param defValue Optional default value to use if the key is not found. - * @return The integer value of the specified event key. - * @error Invalid or corrupt Handle. + * @param event Handle to the event. + * @param key Name of event key. + * @param defValue Optional default value to use if the key is not found. + * @return The integer value of the specified event key. + * @error Invalid or corrupt Handle. */ native int GetEventInt(Handle event, const char[] key, int defValue=0); @@ -267,63 +270,63 @@ native int GetEventInt(Handle event, const char[] key, int defValue=0); * integers, and only refer to how much data will actually be sent * over the network (if applicable). * - * @param event Handle to the event. - * @param key Name of event key. - * @param value New integer value. - * @error Invalid or corrupt Handle. + * @param event Handle to the event. + * @param key Name of event key. + * @param value New integer value. + * @error Invalid or corrupt Handle. */ native void SetEventInt(Handle event, const char[] key, int value); /** * Returns the floating point value of a game event's key. * - * @param event Handle to the event. - * @param key Name of event key. - * @param defValue Optional default value to use if the key is not found. - * @return The floating point value of the specified event key. - * @error Invalid or corrupt Handle. + * @param event Handle to the event. + * @param key Name of event key. + * @param defValue Optional default value to use if the key is not found. + * @return The floating point value of the specified event key. + * @error Invalid or corrupt Handle. */ native float GetEventFloat(Handle event, const char[] key, float defValue=0.0); /** * Sets the floating point value of a game event's key. * - * @param event Handle to the event. - * @param key Name of event key. - * @param value New floating point value. - * @error Invalid or corrupt Handle. + * @param event Handle to the event. + * @param key Name of event key. + * @param value New floating point value. + * @error Invalid or corrupt Handle. */ native void SetEventFloat(Handle event, const char[] key, float value); /** * Retrieves the string value of a game event's key. * - * @param event Handle to the event. - * @param key Name of event key. - * @param value Buffer to store the value of the specified event key. - * @param maxlength Maximum length of string buffer. - * @param defValue Optional default value to use if the key is not found. - * @error Invalid or corrupt Handle. + * @param event Handle to the event. + * @param key Name of event key. + * @param value Buffer to store the value of the specified event key. + * @param maxlength Maximum length of string buffer. + * @param defValue Optional default value to use if the key is not found. + * @error Invalid or corrupt Handle. */ native void GetEventString(Handle event, const char[] key, char[] value, int maxlength, const char[] defvalue=""); /** * Sets the string value of a game event's key. * - * @param event Handle to the event. - * @param key Name of event key. - * @param value New string value. - * @error Invalid or corrupt Handle. + * @param event Handle to the event. + * @param key Name of event key. + * @param value New string value. + * @error Invalid or corrupt Handle. */ native void SetEventString(Handle event, const char[] key, const char[] value); /** * Retrieves the name of a game event. * - * @param event Handle to the event. - * @param name Buffer to store the name of the event. - * @param maxlength Maximum length of string buffer. - * @error Invalid or corrupt Handle. + * @param event Handle to the event. + * @param name Buffer to store the name of the event. + * @param maxlength Maximum length of string buffer. + * @error Invalid or corrupt Handle. */ native void GetEventName(Handle event, char[] name, int maxlength); diff --git a/addons/sourcemod/scripting/include/files.inc b/addons/sourcemod/scripting/include/files.inc index 31fa1f9..fd292ba 100644 --- a/addons/sourcemod/scripting/include/files.inc +++ b/addons/sourcemod/scripting/include/files.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -39,13 +39,13 @@ * @global All paths in SourceMod natives are relative to the mod folder * unless otherwise noted. * - * Most functions in SourceMod (at least, ones that deal with direct + * Most functions in SourceMod (at least, ones that deal with direct * file manipulation) will support an alternate path specification. * - * If the path starts with the string "file://" and the PathType is - * not relative, then the "file://" portion is stripped off, and the - * rest of the path is used without any modification (except for - * correcting slashes). This can be used to override the path + * If the path starts with the string "file://" and the PathType is + * not relative, then the "file://" portion is stripped off, and the + * rest of the path is used without any modification (except for + * correcting slashes). This can be used to override the path * builder to supply alternate absolute paths. Examples: * * file://C:/Temp/file.txt @@ -57,9 +57,9 @@ */ enum FileType { - FileType_Unknown = 0, /* Unknown file type (device/socket) */ - FileType_Directory = 1, /* File is a directory */ - FileType_File = 2, /* File is a file */ + FileType_Unknown = 0, /* Unknown file type (device/socket) */ + FileType_Directory = 1, /* File is a directory */ + FileType_File = 2 /* File is a file */ }; /** @@ -67,23 +67,23 @@ enum FileType */ enum FileTimeMode { - FileTime_LastAccess = 0, /* Last access (does not work on FAT) */ - FileTime_Created = 1, /* Creation (does not work on FAT) */ - FileTime_LastChange = 2, /* Last modification */ + FileTime_LastAccess = 0, /* Last access (does not work on FAT) */ + FileTime_Created = 1, /* Creation (does not work on FAT) */ + FileTime_LastChange = 2 /* Last modification */ }; -#define PLATFORM_MAX_PATH 256 /**< Maximum path length. */ +#define PLATFORM_MAX_PATH 256 /**< Maximum path length. */ -#define SEEK_SET 0 /**< Seek from start. */ -#define SEEK_CUR 1 /**< Seek from current position. */ -#define SEEK_END 2 /**< Seek from end position. */ +#define SEEK_SET 0 /**< Seek from start. */ +#define SEEK_CUR 1 /**< Seek from current position. */ +#define SEEK_END 2 /**< Seek from end position. */ /** * Path types. */ enum PathType { - Path_SM, /**< SourceMod root folder */ + Path_SM, /**< SourceMod root folder */ }; // A DirectoryListing iterates over the contents of a directory. To obtain a @@ -92,9 +92,9 @@ methodmap DirectoryListing < Handle { // Reads the current directory entry as a local filename, then moves to the // next file. - // + // // Note: Both the '.' and '..' automatic directory entries will be retrieved. - // + // // @param buffer String buffer to hold directory name. // @param maxlength Maximum size of string buffer. // @param type Optional variable to store the file type. @@ -104,7 +104,7 @@ methodmap DirectoryListing < Handle // A File object can be obtained by calling OpenFile(). File objects should be // closed with delete or Close(). Note that, "delete file" does not -// actually a file, it just closes it. +// actually delete the file, it just closes the handle. methodmap File < Handle { // Close the file handle. This is the same as using CloseHandle() or delete. @@ -113,15 +113,15 @@ methodmap File < Handle } // Reads a line of text from a file. - // + // // @param buffer String buffer to hold the line. - // @param maxlength Maximum size of string buffer. + // @param maxlength Maximum size of string buffer. // @return True on success, false otherwise. public native bool ReadLine(char[] buffer, int maxlength); // Reads binary data from a file. - // - // @param items Array to store each item read. + // + // @param items Array to store each item read. // @param num_items Number of items to read into the array. // @param size Size of each element, in bytes, to be read. // Valid sizes are 1, 2, or 4. @@ -129,40 +129,40 @@ methodmap File < Handle public native int Read(int[] items, int num_items, int size); // Reads a UTF8 or ANSI string from a file. - // + // // @param buffer Buffer to store the string. // @param max_size Maximum size of the string buffer. - // @param read_count If -1, reads until a null terminator is encountered in - // the file. Otherwise, read_count bytes are read - // into the buffer provided. In this case the buffer - // is not explicitly null terminated, and the buffer + // @param read_count If -1, reads until a null terminator is encountered in + // the file. Otherwise, read_count bytes are read + // into the buffer provided. In this case the buffer + // is not explicitly null terminated, and the buffer // will contain any null terminators read from the file. - // @return Number of characters written to the buffer, or -1 + // @return Number of characters written to the buffer, or -1 // if an error was encountered. // @error read_count > max_size. public native int ReadString(char[] buffer, int max_size, int read_count=-1); // Writes binary data to a file. // - // @param items Array of items to write. The data is read directly. - // That is, in 1 or 2-byte mode, the lower byte(s) in - // each cell are used directly, rather than performing + // @param items Array of items to write. The data is read directly. + // That is, in 1 or 2-byte mode, the lower byte(s) in + // each cell are used directly, rather than performing // any casts from a 4-byte number to a smaller number. // @param num_items Number of items in the array. - // @param size Size of each item in the array in bytes. + // @param size Size of each item in the array in bytes. // Valid sizes are 1, 2, or 4. // @return True on success, false on error. public native bool Write(const int[] items, int num_items, int size); // Writes a binary string to a file. - // + // // @param buffer String to write. // @param term True to append NUL terminator, false otherwise. // @return True on success, false on error. public native bool WriteString(const char[] buffer, bool term); // Writes a line of text to a text file. A newline is automatically appended. - // + // // @param hndl Handle to the file. // @param format Formatting rules. // @param ... Variable number of format parameters. @@ -222,7 +222,7 @@ methodmap File < Handle public native bool WriteInt32(int data); // Tests if the end of file has been reached. - // + // // @return True if end of file has been reached, false otherwise. public native bool EndOfFile(); @@ -233,6 +233,13 @@ methodmap File < Handle // @return True on success, false otherwise. public native bool Seek(int position, int where); + // Flushes a file's buffered output; any buffered output + // is immediately written to the file. + // + // @return True on success or use_valve_fs specified with OpenFile, + // otherwise false on failure. + public native bool Flush(); + // Get the current position in the file; returns -1 on failure. property int Position { public native get(); @@ -240,16 +247,16 @@ methodmap File < Handle } /** - * Builds a path relative to the SourceMod folder. This should be used instead of - * directly referencing addons/sourcemod, in case users change the name of their + * Builds a path relative to the SourceMod folder. This should be used instead of + * directly referencing addons/sourcemod, in case users change the name of their * folder layout. * - * @param type Type of path to build as the base. - * @param buffer Buffer to store the path. - * @param maxlength Maximum length of buffer. - * @param fmt Format string. - * @param ... Format arguments. - * @return Number of bytes written to buffer (not including null terminator). + * @param type Type of path to build as the base. + * @param buffer Buffer to store the path. + * @param maxlength Maximum length of buffer. + * @param fmt Format string. + * @param ... Format arguments. + * @return Number of bytes written to buffer (not including null terminator). */ native int BuildPath(PathType type, char[] buffer, int maxlength, const char[] fmt, any ...); @@ -260,13 +267,13 @@ native int BuildPath(PathType type, char[] buffer, int maxlength, const char[] f * @note Directories Handles can be cloned. * @note OpenDirectory() supports the "file://" notation. * - * @param path Path to open. + * @param path Path to open. * @param use_valve_fs If true, the Valve file system will be used instead. * This can be used to find files existing in any of * the Valve search paths, rather than solely files * existing directly in the gamedir. - * @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths. - * @return A Handle to the directory, null on error. + * @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths. + * @return A Handle to the directory, null on error. */ native DirectoryListing OpenDirectory(const char[] path, bool use_valve_fs=false, const char[] valve_path_id="GAME"); @@ -275,13 +282,13 @@ native DirectoryListing OpenDirectory(const char[] path, bool use_valve_fs=false * * @note Contents of buffers are undefined when returning false. * @note Both the '.' and '..' automatic directory entries will be retrieved for Windows and Linux. - * - * @param dir Handle to a directory. - * @param buffer String buffer to hold directory name. - * @param maxlength Maximum size of string buffer. - * @param type Optional variable to store the file type. - * @return True on success, false if there are no more files to read. - * @error Invalid or corrupt Handle. + * + * @param dir Handle to a directory. + * @param buffer String buffer to hold directory name. + * @param maxlength Maximum size of string buffer. + * @param type Optional variable to store the file type. + * @return True on success, false if there are no more files to read. + * @error Invalid or corrupt Handle. */ native bool ReadDirEntry(Handle dir, char[] buffer, int maxlength, FileType &type=FileType_Unknown); @@ -310,227 +317,229 @@ native bool ReadDirEntry(Handle dir, char[] buffer, int maxlength, FileType &typ * Example: "rb" opens a binary file for writing; "at" opens a text file for * appending. * - * @param file File to open. - * @param mode Open mode. + * @param file File to open. + * @param mode Open mode. * @param use_valve_fs If true, the Valve file system will be used instead. * This can be used to find files existing in valve - * search paths, rather than solely files existing directly - * in the gamedir. - * @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths. - * @return A File handle, or null if the file could not be opened. + * search paths, rather than solely files existing directly + * in the gamedir. + * @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths. + * @return A File handle, or null if the file could not be opened. */ native File OpenFile(const char[] file, const char[] mode, bool use_valve_fs=false, const char[] valve_path_id="GAME"); /** * Deletes a file. * - * @param path Path of the file to delete. + * @param path Path of the file to delete. * @param use_valve_fs If true, the Valve file system will be used instead. * This can be used to delete files existing in the Valve * search path, rather than solely files existing directly - * in the gamedir. - * @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths. - * @return True on success, false on failure or if file not immediately removed. + * in the gamedir. + * @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths. + * @return True on success, false on failure or if file not immediately removed. */ native bool DeleteFile(const char[] path, bool use_valve_fs=false, const char[] valve_path_id="DEFAULT_WRITE_PATH"); /** * Reads a line from a text file. * - * @param hndl Handle to the file. - * @param buffer String buffer to hold the line. - * @param maxlength Maximum size of string buffer. - * @return True on success, false otherwise. + * @param hndl Handle to the file. + * @param buffer String buffer to hold the line. + * @param maxlength Maximum size of string buffer. + * @return True on success, false otherwise. */ native bool ReadFileLine(Handle hndl, char[] buffer, int maxlength); /** * Reads binary data from a file. * - * @param hndl Handle to the file. - * @param items Array to store each item read. - * @param num_items Number of items to read into the array. - * @param size Size of each element, in bytes, to be read. - * Valid sizes are 1, 2, or 4. - * @return Number of elements read, or -1 on error. + * @param hndl Handle to the file. + * @param items Array to store each item read. + * @param num_items Number of items to read into the array. + * @param size Size of each element, in bytes, to be read. + * Valid sizes are 1, 2, or 4. + * @return Number of elements read, or -1 on error. */ native int ReadFile(Handle hndl, int[] items, int num_items, int size); /** * Reads a UTF8 or ANSI string from a file. * - * @param hndl Handle to the file. - * @param buffer Buffer to store the string. - * @param max_size Maximum size of the string buffer. - * @param read_count If -1, reads until a null terminator is encountered in - * the file. Otherwise, read_count bytes are read - * into the buffer provided. In this case the buffer - * is not explicitly null terminated, and the buffer - * will contain any null terminators read from the file. - * @return Number of characters written to the buffer, or -1 - * if an error was encountered. - * @error Invalid Handle, or read_count > max_size. + * @param hndl Handle to the file. + * @param buffer Buffer to store the string. + * @param max_size Maximum size of the string buffer. + * @param read_count If -1, reads until a null terminator is encountered in + * the file. Otherwise, read_count bytes are read + * into the buffer provided. In this case the buffer + * is not explicitly null terminated, and the buffer + * will contain any null terminators read from the file. + * @return Number of characters written to the buffer, or -1 + * if an error was encountered. + * @error Invalid Handle, or read_count > max_size. */ native int ReadFileString(Handle hndl, char[] buffer, int max_size, int read_count=-1); /** * Writes binary data to a file. * - * @param hndl Handle to the file. - * @param items Array of items to write. The data is read directly. - * That is, in 1 or 2-byte mode, the lower byte(s) in - * each cell are used directly, rather than performing - * any casts from a 4-byte number to a smaller number. - * @param num_items Number of items in the array. - * @param size Size of each item in the array in bytes. - * Valid sizes are 1, 2, or 4. - * @return True on success, false on error. - * @error Invalid Handle. + * @param hndl Handle to the file. + * @param items Array of items to write. The data is read directly. + * That is, in 1 or 2-byte mode, the lower byte(s) in + * each cell are used directly, rather than performing + * any casts from a 4-byte number to a smaller number. + * @param num_items Number of items in the array. + * @param size Size of each item in the array in bytes. + * Valid sizes are 1, 2, or 4. + * @return True on success, false on error. + * @error Invalid Handle. */ native bool WriteFile(Handle hndl, const int[] items, int num_items, int size); /** * Writes a binary string to a file. * - * @param hndl Handle to the file. - * @param buffer String to write. - * @param term True to append NUL terminator, false otherwise. - * @return True on success, false on error. - * @error Invalid Handle. + * @param hndl Handle to the file. + * @param buffer String to write. + * @param term True to append NUL terminator, false otherwise. + * @return True on success, false on error. + * @error Invalid Handle. */ native bool WriteFileString(Handle hndl, const char[] buffer, bool term); /** * Writes a line of text to a text file. A newline is automatically appended. * - * @param hndl Handle to the file. - * @param format Formatting rules. - * @param ... Variable number of format parameters. - * @return True on success, false otherwise. - * @error Invalid Handle. + * @param hndl Handle to the file. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @return True on success, false otherwise. + * @error Invalid Handle. */ native bool WriteFileLine(Handle hndl, const char[] format, any ...); /** * Reads a single binary cell from a file. * - * @param hndl Handle to the file. - * @param data Variable to store the data read. - * @param size Size of the data to read in bytes. Valid - * sizes are 1, 2, or 4 bytes. - * @return Number of elements read (max 1), or -1 on error. - * @error Invalid Handle. + * @param hndl Handle to the file. + * @param data Variable to store the data read. + * @param size Size of the data to read in bytes. Valid + * sizes are 1, 2, or 4 bytes. + * @return Number of elements read (max 1), or -1 on error. + * @error Invalid Handle. */ stock int ReadFileCell(Handle hndl, int &data, int size) { int ret; int array[1]; - + if ((ret = ReadFile(hndl, array, 1, size)) == 1) + { data = array[0]; - + } + return ret; } /** * Writes a single binary cell to a file. * - * @param hndl Handle to the file. - * @param data Cell to write to the file. - * @param size Size of the data to read in bytes. Valid - * sizes are 1, 2, or 4 bytes. If the size - * is less than 4 bytes, the data is truncated - * rather than casted. That is, only the lower - * bits will be read. - * @return True on success, false on error. - * @error Invalid Handle. + * @param hndl Handle to the file. + * @param data Cell to write to the file. + * @param size Size of the data to read in bytes. Valid + * sizes are 1, 2, or 4 bytes. If the size + * is less than 4 bytes, the data is truncated + * rather than casted. That is, only the lower + * bits will be read. + * @return True on success, false on error. + * @error Invalid Handle. */ stock bool WriteFileCell(Handle hndl, int data, int size) { int array[1]; - array[0] = data; + return WriteFile(hndl, array, 1, size); } - + /** * Tests if the end of file has been reached. * - * @param file Handle to the file. - * @return True if end of file has been reached, false otherwise. - * @error Invalid Handle. + * @param file Handle to the file. + * @return True if end of file has been reached, false otherwise. + * @error Invalid Handle. */ native bool IsEndOfFile(Handle file); /** * Sets the file position indicator. * - * @param file Handle to the file. - * @param position Position relative to what is specified in whence. - * @param where SEEK_ constant value of where to see from. - * @return True on success, false otherwise. - * @error Invalid Handle. + * @param file Handle to the file. + * @param position Position relative to what is specified in whence. + * @param where SEEK_ constant value of where to see from. + * @return True on success, false otherwise. + * @error Invalid Handle. */ native bool FileSeek(Handle file, int position, int where); /** * Get current position in the file. * - * @param file Handle to the file. - * @return Value for the file position indicator. - * @error Invalid Handle. + * @param file Handle to the file. + * @return Value for the file position indicator. + * @error Invalid Handle. */ native int FilePosition(Handle file); /** * Checks if a file exists. * - * @param path Path to the file. - * @param use_valve_fs If true, the Valve file system will be used instead. - * This can be used to find files existing in any of - * the Valve search paths, rather than solely files - * existing directly in the gamedir. - * @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths. - * @return True if the file exists, false otherwise. + * @param path Path to the file. + * @param use_valve_fs If true, the Valve file system will be used instead. + * This can be used to find files existing in any of + * the Valve search paths, rather than solely files + * existing directly in the gamedir. + * @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths. + * @return True if the file exists, false otherwise. */ native bool FileExists(const char[] path, bool use_valve_fs=false, const char[] valve_path_id="GAME"); /** * Renames a file. * - * @param newpath New path to the file. - * @param oldpath Path to the existing file. + * @param newpath New path to the file. + * @param oldpath Path to the existing file. * @param use_valve_fs If true, the Valve file system will be used instead. * This can be used to rename files in the game's * Valve search paths, rather than directly in the gamedir. - * @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths. - * @return True on success or use_valve_fs specified, false otherwise. + * @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths. + * @return True on success or use_valve_fs specified, false otherwise. */ native bool RenameFile(const char[] newpath, const char[] oldpath, bool use_valve_fs=false, const char[] valve_path_id="DEFAULT_WRITE_PATH"); /** * Checks if a directory exists. * - * @param path Path to the directory. + * @param path Path to the directory. * @param use_valve_fs If true, the Valve file system will be used instead. * This can be used to find files existing in any of * the Valve search paths, rather than solely files * existing directly in the gamedir. - * @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths. - * @return True if the directory exists, false otherwise. + * @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths. + * @return True if the directory exists, false otherwise. */ native bool DirExists(const char[] path, bool use_valve_fs=false, const char[] valve_path_id="GAME"); /** * Get the file size in bytes. * - * @param path Path to the file. - * @param use_valve_fs If true, the Valve file system will be used instead. - * This can be used to find files existing in any of - * the Valve search paths, rather than solely files - * existing directly in the gamedir. - * @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths. - * @return File size in bytes, -1 if file not found. + * @param path Path to the file. + * @param use_valve_fs If true, the Valve file system will be used instead. + * This can be used to find files existing in any of + * the Valve search paths, rather than solely files + * existing directly in the gamedir. + * @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for all search paths. + * @return File size in bytes, -1 if file not found. */ native int FileSize(const char[] path, bool use_valve_fs=false, const char[] valve_path_id="GAME"); @@ -538,8 +547,8 @@ native int FileSize(const char[] path, bool use_valve_fs=false, const char[] val * Flushes a file's buffered output; any buffered output * is immediately written to the file. * - * @param file Handle to the file. - * @return True on success or use_valve_fs specified with OpenFile, + * @param file Handle to the file. + * @return True on success or use_valve_fs specified with OpenFile, * otherwise false on failure. */ native bool FlushFile(Handle file); @@ -548,71 +557,72 @@ native bool FlushFile(Handle file); * Removes a directory. * @note On most Operating Systems you cannot remove a directory which has files inside it. * - * @param path Path to the directory. - * @return True on success, false otherwise. + * @param path Path to the directory. + * @return True on success, false otherwise. */ native bool RemoveDir(const char[] path); -#define FPERM_U_READ 0x0100 /* User can read. */ -#define FPERM_U_WRITE 0x0080 /* User can write. */ -#define FPERM_U_EXEC 0x0040 /* User can exec. */ -#define FPERM_G_READ 0x0020 /* Group can read. */ -#define FPERM_G_WRITE 0x0010 /* Group can write. */ -#define FPERM_G_EXEC 0x0008 /* Group can exec. */ -#define FPERM_O_READ 0x0004 /* Anyone can read. */ -#define FPERM_O_WRITE 0x0002 /* Anyone can write. */ -#define FPERM_O_EXEC 0x0001 /* Anyone can exec. */ +#define FPERM_U_READ 0x0100 /* User can read. */ +#define FPERM_U_WRITE 0x0080 /* User can write. */ +#define FPERM_U_EXEC 0x0040 /* User can exec. */ +#define FPERM_G_READ 0x0020 /* Group can read. */ +#define FPERM_G_WRITE 0x0010 /* Group can write. */ +#define FPERM_G_EXEC 0x0008 /* Group can exec. */ +#define FPERM_O_READ 0x0004 /* Anyone can read. */ +#define FPERM_O_WRITE 0x0002 /* Anyone can write. */ +#define FPERM_O_EXEC 0x0001 /* Anyone can exec. */ /** * Creates a directory. * - * @param path Path to create. - * @param mode Permissions (default is o=rx,g=rx,u=rwx). Note that folders must have - * the execute bit set on Linux. On Windows, the mode is ignored. + * @param path Path to create. + * @param mode Permissions (default is o=rx,g=rx,u=rwx). Note that folders must have + * the execute bit set on Linux. On Windows, the mode is ignored. * @param use_valve_fs If true, the Valve file system will be used instead. * This can be used to create folders in the game's * Valve search paths, rather than directly in the gamedir. - * @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for default. + * @param valve_path_id If use_valve_fs, a search path from gameinfo or NULL_STRING for default. * In this case, mode is ignored. + * @return True on success, false otherwise. */ native bool CreateDirectory(const char[] path, int mode, bool use_valve_fs=false, const char[] valve_path_id="DEFAULT_WRITE_PATH"); /** * Changes a file or directories permissions. * - * @param path Path to the file. - * @param mode Permissions to set. - * @return True on success, false otherwise. + * @param path Path to the file. + * @param mode Permissions to set. + * @return True on success, false otherwise. */ native bool SetFilePermissions(const char[] path, int mode); /** * Returns a file timestamp as a unix timestamp. * - * @param file File name. - * @param tmode Time mode. - * @return Time value, or -1 on failure. + * @param file File name. + * @param tmode Time mode. + * @return Time value, or -1 on failure. */ native int GetFileTime(const char[] file, FileTimeMode tmode); /** - * Same as LogToFile(), except uses an open file Handle. The file must + * Same as LogToFile(), except uses an open file Handle. The file must * be opened in text appending mode. * - * @param hndl Handle to the file. - * @param message Message format. - * @param ... Message format parameters. - * @error Invalid Handle. + * @param hndl Handle to the file. + * @param message Message format. + * @param ... Message format parameters. + * @error Invalid Handle. */ native void LogToOpenFile(Handle hndl, const char[] message, any ...); /** - * Same as LogToFileEx(), except uses an open file Handle. The file must + * Same as LogToFileEx(), except uses an open file Handle. The file must * be opened in text appending mode. * - * @param hndl Handle to the file. - * @param message Message format. - * @param ... Message format parameters. - * @error Invalid Handle. + * @param hndl Handle to the file. + * @param message Message format. + * @param ... Message format parameters. + * @error Invalid Handle. */ native void LogToOpenFileEx(Handle hndl, const char[] message, any ...); diff --git a/addons/sourcemod/scripting/include/float.inc b/addons/sourcemod/scripting/include/float.inc index 19e06b3..8005e05 100644 --- a/addons/sourcemod/scripting/include/float.inc +++ b/addons/sourcemod/scripting/include/float.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -29,7 +29,7 @@ * * Version: $Id$ */ - + #if defined _float_included #endinput #endif @@ -39,8 +39,8 @@ /** * Converts an integer into a floating point value. * - * @param value Integer to convert. - * @return Floating point value. + * @param value Integer to convert. + * @return Floating point value. */ native float float(int value); #endif @@ -48,85 +48,101 @@ native float float(int value); /** * Multiplies two floats together. * - * @param oper1 First value. - * @param oper2 Second value. - * @return oper1*oper2. + * Note: This native is internal implementation. For multiplication use the '*' operator. + * + * @param oper1 First value. + * @param oper2 Second value. + * @return oper1*oper2. + * @deprecated This native is internal implementation. For multiplication use the '*' operator. */ +#pragma deprecated This native is internal implementation. For multiplication use the '*' operator. native float FloatMul(float oper1, float oper2); /** * Divides the dividend by the divisor. * - * @param dividend First value. - * @param divisor Second value. - * @return dividend/divisor. + * Note: This native is internal implementation. For division use the '/' operator. + * + * @param dividend First value. + * @param divisor Second value. + * @return dividend/divisor. + * @deprecated This native is internal implementation. For division use the '/' operator. */ +#pragma deprecated This native is internal implementation. For division use the '/' operator. native float FloatDiv(float dividend, float divisor); /** * Adds two floats together. * - * @param oper1 First value. - * @param oper2 Second value. - * @return oper1+oper2. + * Note: This native is internal implementation. For addition use the '+' operator. + * + * @param oper1 First value. + * @param oper2 Second value. + * @return oper1+oper2. + * @deprecated This native is internal implementation. For addition use the '+' operator. */ +#pragma deprecated This native is internal implementation. For addition use the '+' operator. native float FloatAdd(float oper1, float oper2); /** * Subtracts oper2 from oper1. * - * @param oper1 First value. - * @param oper2 Second value. - * @return oper1-oper2. + * Note: This native is internal implementation. For subtraction use the '-' operator. + * + * @param oper1 First value. + * @param oper2 Second value. + * @return oper1-oper2. + * @deprecated This native is internal implementation. For subtraction use the '-' operator. */ +#pragma deprecated This native is internal implementation. For subtraction use the '-' operator. native float FloatSub(float oper1, float oper2); /** * Returns the decimal part of a float. * - * @param value Input value. - * @return Decimal part. + * @param value Input value. + * @return Decimal part. */ native float FloatFraction(float value); /** * Rounds a float to the closest integer to zero. * - * @param value Input value to be rounded. - * @return Rounded value. + * @param value Input value to be rounded. + * @return Rounded value. */ native int RoundToZero(float value); /** * Rounds a float to the next highest integer value. * - * @param value Input value to be rounded. - * @return Rounded value. + * @param value Input value to be rounded. + * @return Rounded value. */ native int RoundToCeil(float value); /** * Rounds a float to the next lowest integer value. * - * @param value Input value to be rounded. - * @return Rounded value. + * @param value Input value to be rounded. + * @return Rounded value. */ native int RoundToFloor(float value); /** * Standard IEEE rounding. * - * @param value Input value to be rounded. - * @return Rounded value. + * @param value Input value to be rounded. + * @return Rounded value. */ native int RoundToNearest(float value); /** * Compares two floats. * - * @param fOne First value. - * @param fTwo Second value. - * @return Returns 1 if the first argument is greater than the second argument. + * @param fOne First value. + * @param fTwo Second value. + * @return Returns 1 if the first argument is greater than the second argument. * Returns -1 if the first argument is smaller than the second argument. * Returns 0 if both arguments are equal. */ @@ -135,107 +151,107 @@ native int FloatCompare(float fOne, float fTwo); /** * Returns the square root of the input value, equivalent to floatpower(value, 0.5). * - * @param value Input value. - * @return Square root of the value. + * @param value Input value. + * @return Square root of the value. */ native float SquareRoot(float value); /** * Returns the value raised to the power of the exponent. * - * @param value Value to be raised. - * @param exponent Value to raise the base. - * @return value^exponent. + * @param value Value to be raised. + * @param exponent Value to raise the base. + * @return value^exponent. */ native float Pow(float value, float exponent); /** * Returns the value of raising the input by e. * - * @param value Input value. - * @return exp(value). + * @param value Input value. + * @return exp(value). */ native float Exponential(float value); /** * Returns the logarithm of any base specified. * - * @param value Input value. - * @param base Logarithm base to use, default is 10. - * @return log(value)/log(base). + * @param value Input value. + * @param base Logarithm base to use, default is 10. + * @return log(value)/log(base). */ native float Logarithm(float value, float base=10.0); /** * Returns the sine of the argument. * - * @param value Input value in radians. - * @return sin(value). + * @param value Input value in radians. + * @return sin(value). */ native float Sine(float value); /** * Returns the cosine of the argument. * - * @param value Input value in radians. - * @return cos(value). + * @param value Input value in radians. + * @return cos(value). */ native float Cosine(float value); /** * Returns the tangent of the argument. * - * @param value Input value in radians. - * @return tan(value). + * @param value Input value in radians. + * @return tan(value). */ native float Tangent(float value); /** * Returns an absolute value. * - * @param value Input value. - * @return Absolute value of the input. + * @param value Input value. + * @return Absolute value of the input. */ native float FloatAbs(float value); /** * Returns the arctangent of the input value. * - * @param angle Input value. - * @return atan(value) in radians. + * @param angle Input value. + * @return atan(value) in radians. */ native float ArcTangent(float angle); /** * Returns the arccosine of the input value. * - * @param angle Input value. - * @return acos(value) in radians. + * @param angle Input value. + * @return acos(value) in radians. */ native float ArcCosine(float angle); /** * Returns the arcsine of the input value. * - * @param angle Input value. - * @return asin(value) in radians. + * @param angle Input value. + * @return asin(value) in radians. */ native float ArcSine(float angle); /** * Returns the arctangent2 of the input values. * - * @param x Horizontal value. - * @param y Vertical value. - * @return atan2(value) in radians. + * @param x Horizontal value. + * @param y Vertical value. + * @return atan2(value) in radians. */ native float ArcTangent2(float x, float y); /** * Rounds a floating point number using the "round to nearest" algorithm. * - * @param value Floating point value to round. - * @return The value rounded to the nearest integer. + * @param value Floating point value to round. + * @return The value rounded to the nearest integer. */ stock int RoundFloat(float value) { @@ -248,6 +264,12 @@ stock int RoundFloat(float value) #if !defined __sourcepawn2__ #pragma rational Float +// Internal aliases for backwards compatability. +native float __FLOAT_MUL__(float a, float b) = FloatMul; +native float __FLOAT_DIV__(float a, float b) = FloatDiv; +native float __FLOAT_ADD__(float a, float b) = FloatAdd; +native float __FLOAT_SUB__(float a, float b) = FloatSub; + native bool __FLOAT_GT__(float a, float b); native bool __FLOAT_GE__(float a, float b); native bool __FLOAT_LT__(float a, float b); @@ -280,37 +302,39 @@ stock float operator--(float oper) stock float operator-(float oper) { - return oper^view_as(cellmin); /* IEEE values are sign/magnitude */ + return oper^view_as(cellmin); /* IEEE values are sign/magnitude */ } +// The stocks below are int->float converting versions of the above natives. + stock float operator*(float oper1, int oper2) { - return FloatMul(oper1, float(oper2)); /* "*" is commutative */ + return __FLOAT_MUL__(oper1, float(oper2)); /* "*" is commutative */ } stock float operator/(float oper1, int oper2) { - return FloatDiv(oper1, float(oper2)); + return __FLOAT_DIV__(oper1, float(oper2)); } stock float operator/(int oper1, float oper2) { - return FloatDiv(float(oper1), oper2); + return __FLOAT_DIV__(float(oper1), oper2); } stock float operator+(float oper1, int oper2) { - return FloatAdd(oper1, float(oper2)); /* "+" is commutative */ + return __FLOAT_ADD__(oper1, float(oper2)); /* "+" is commutative */ } stock float operator-(float oper1, int oper2) { - return FloatSub(oper1, float(oper2)); + return __FLOAT_SUB__(oper1, float(oper2)); } stock float operator-(int oper1, float oper2) { - return FloatSub(float(oper1), oper2); + return __FLOAT_SUB__(float(oper1), oper2); } stock bool operator==(float oper1, int oper2) @@ -376,8 +400,8 @@ forward operator%(int oper1, float oper2); /** * Converts degrees to radians. * - * @param angle Degrees. - * @return Radians. + * @param angle Degrees. + * @return Radians. */ stock float DegToRad(float angle) { @@ -387,8 +411,8 @@ stock float DegToRad(float angle) /** * Converts radians to degrees. * - * @param angle Radians. - * @return Degrees. + * @param angle Radians. + * @return Degrees. */ stock float RadToDeg(float angle) { @@ -400,7 +424,7 @@ stock float RadToDeg(float angle) * * Note: Uniform random number streams are seeded automatically per-plugin. * - * @return Random integer. + * @return Random integer. */ native int GetURandomInt(); @@ -409,7 +433,7 @@ native int GetURandomInt(); * * Note: Uniform random number streams are seeded automatically per-plugin. * - * @return Uniform random floating-point number. + * @return Uniform random floating-point number. */ native float GetURandomFloat(); @@ -417,8 +441,8 @@ native float GetURandomFloat(); * Seeds a plugin's uniform random number stream. This is done automatically, * so normally it is totally unnecessary to call this. * - * @param seeds Array of numbers to use as seeding data. - * @param numSeeds Number of seeds in the seeds array. + * @param seeds Array of numbers to use as seeding data. + * @param numSeeds Number of seeds in the seeds array. */ native void SetURandomSeed(const int[] seeds, int numSeeds); diff --git a/addons/sourcemod/scripting/include/functions.inc b/addons/sourcemod/scripting/include/functions.inc index 3f6da19..490012b 100644 --- a/addons/sourcemod/scripting/include/functions.inc +++ b/addons/sourcemod/scripting/include/functions.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -29,27 +29,27 @@ * * Version: $Id$ */ - + #if defined _functions_included #endinput #endif #define _functions_included - -#define SP_PARAMFLAG_BYREF (1<<0) /**< Internal use only. */ + +#define SP_PARAMFLAG_BYREF (1<<0) /**< Internal use only. */ /** * Describes the various ways to pass parameters to functions or forwards. */ enum ParamType { - Param_Any = 0, /**< Any data type can be pushed */ - Param_Cell = (1<<1), /**< Only basic cells can be pushed */ - Param_Float = (2<<1), /**< Only floats can be pushed */ - Param_String = (3<<1)|SP_PARAMFLAG_BYREF, /**< Only strings can be pushed */ - Param_Array = (4<<1)|SP_PARAMFLAG_BYREF, /**< Only arrays can be pushed */ - Param_VarArgs = (5<<1), /**< Same as "..." in plugins, anything can be pushed, but it will always be byref */ - Param_CellByRef = (1<<1)|SP_PARAMFLAG_BYREF, /**< Only a cell by reference can be pushed */ - Param_FloatByRef = (2<<1)|SP_PARAMFLAG_BYREF /**< Only a float by reference can be pushed */ + Param_Any = 0, /**< Any data type can be pushed */ + Param_Cell = (1<<1), /**< Only basic cells can be pushed */ + Param_Float = (2<<1), /**< Only floats can be pushed */ + Param_String = (3<<1)|SP_PARAMFLAG_BYREF, /**< Only strings can be pushed */ + Param_Array = (4<<1)|SP_PARAMFLAG_BYREF, /**< Only arrays can be pushed */ + Param_VarArgs = (5<<1), /**< Same as "..." in plugins, anything can be pushed, but it will always be byref */ + Param_CellByRef = (1<<1)|SP_PARAMFLAG_BYREF, /**< Only a cell by reference can be pushed */ + Param_FloatByRef = (2<<1)|SP_PARAMFLAG_BYREF /**< Only a float by reference can be pushed */ }; /** @@ -57,21 +57,21 @@ enum ParamType */ enum ExecType { - ET_Ignore = 0, /**< Ignore all return values, return 0 */ - ET_Single = 1, /**< Only return the last exec, ignore all others */ - ET_Event = 2, /**< Acts as an event with the Actions defined in core.inc, no mid-Stops allowed, returns highest */ - ET_Hook = 3 /**< Acts as a hook with the Actions defined in core.inc, mid-Stops allowed, returns highest */ + ET_Ignore = 0, /**< Ignore all return values, return 0 */ + ET_Single = 1, /**< Only return the last exec, ignore all others */ + ET_Event = 2, /**< Acts as an event with the Actions defined in core.inc, no mid-Stops allowed, returns highest */ + ET_Hook = 3 /**< Acts as a hook with the Actions defined in core.inc, mid-Stops allowed, returns highest */ }; /** * @section Flags that are used with Call_PushArrayEx() and Call_PushStringEx() */ - -#define SM_PARAM_COPYBACK (1<<0) /**< Copy an array/reference back after call */ -#define SM_PARAM_STRING_UTF8 (1<<0) /**< String should be UTF-8 handled */ -#define SM_PARAM_STRING_COPY (1<<1) /**< String should be copied into the plugin */ -#define SM_PARAM_STRING_BINARY (1<<2) /**< Treat the string as a binary string */ +#define SM_PARAM_COPYBACK (1<<0) /**< Copy an array/reference back after call */ + +#define SM_PARAM_STRING_UTF8 (1<<0) /**< String should be UTF-8 handled */ +#define SM_PARAM_STRING_COPY (1<<1) /**< String should be copied into the plugin */ +#define SM_PARAM_STRING_BINARY (1<<2) /**< Treat the string as a binary string */ /** * @endsection @@ -80,45 +80,113 @@ enum ExecType /** * @section Error codes */ -#define SP_ERROR_NONE 0 /**< No error occurred */ -#define SP_ERROR_FILE_FORMAT 1 /**< File format unrecognized */ -#define SP_ERROR_DECOMPRESSOR 2 /**< A decompressor was not found */ -#define SP_ERROR_HEAPLOW 3 /**< Not enough space left on the heap */ -#define SP_ERROR_PARAM 4 /**< Invalid parameter or parameter type */ -#define SP_ERROR_INVALID_ADDRESS 5 /**< A memory address was not valid */ -#define SP_ERROR_NOT_FOUND 6 /**< The object in question was not found */ -#define SP_ERROR_INDEX 7 /**< Invalid index parameter */ -#define SP_ERROR_STACKLOW 8 /**< Not enough space left on the stack */ -#define SP_ERROR_NOTDEBUGGING 9 /**< Debug mode was not on or debug section not found */ -#define SP_ERROR_INVALID_INSTRUCTION 10 /**< Invalid instruction was encountered */ -#define SP_ERROR_MEMACCESS 11 /**< Invalid memory access */ -#define SP_ERROR_STACKMIN 12 /**< Stack went beyond its minimum value */ -#define SP_ERROR_HEAPMIN 13 /**< Heap went beyond its minimum value */ -#define SP_ERROR_DIVIDE_BY_ZERO 14 /**< Division by zero */ -#define SP_ERROR_ARRAY_BOUNDS 15 /**< Array index is out of bounds */ -#define SP_ERROR_INSTRUCTION_PARAM 16 /**< Instruction had an invalid parameter */ -#define SP_ERROR_STACKLEAK 17 /**< A native leaked an item on the stack */ -#define SP_ERROR_HEAPLEAK 18 /**< A native leaked an item on the heap */ -#define SP_ERROR_ARRAY_TOO_BIG 19 /**< A dynamic array is too big */ -#define SP_ERROR_TRACKER_BOUNDS 20 /**< Tracker stack is out of bounds */ -#define SP_ERROR_INVALID_NATIVE 21 /**< Native was pending or invalid */ -#define SP_ERROR_PARAMS_MAX 22 /**< Maximum number of parameters reached */ -#define SP_ERROR_NATIVE 23 /**< Error originates from a native */ -#define SP_ERROR_NOT_RUNNABLE 24 /**< Function or plugin is not runnable */ -#define SP_ERROR_ABORTED 25 /**< Function call was aborted */ +#define SP_ERROR_NONE 0 /**< No error occurred */ +#define SP_ERROR_FILE_FORMAT 1 /**< File format unrecognized */ +#define SP_ERROR_DECOMPRESSOR 2 /**< A decompressor was not found */ +#define SP_ERROR_HEAPLOW 3 /**< Not enough space left on the heap */ +#define SP_ERROR_PARAM 4 /**< Invalid parameter or parameter type */ +#define SP_ERROR_INVALID_ADDRESS 5 /**< A memory address was not valid */ +#define SP_ERROR_NOT_FOUND 6 /**< The object in question was not found */ +#define SP_ERROR_INDEX 7 /**< Invalid index parameter */ +#define SP_ERROR_STACKLOW 8 /**< Not enough space left on the stack */ +#define SP_ERROR_NOTDEBUGGING 9 /**< Debug mode was not on or debug section not found */ +#define SP_ERROR_INVALID_INSTRUCTION 10 /**< Invalid instruction was encountered */ +#define SP_ERROR_MEMACCESS 11 /**< Invalid memory access */ +#define SP_ERROR_STACKMIN 12 /**< Stack went beyond its minimum value */ +#define SP_ERROR_HEAPMIN 13 /**< Heap went beyond its minimum value */ +#define SP_ERROR_DIVIDE_BY_ZERO 14 /**< Division by zero */ +#define SP_ERROR_ARRAY_BOUNDS 15 /**< Array index is out of bounds */ +#define SP_ERROR_INSTRUCTION_PARAM 16 /**< Instruction had an invalid parameter */ +#define SP_ERROR_STACKLEAK 17 /**< A native leaked an item on the stack */ +#define SP_ERROR_HEAPLEAK 18 /**< A native leaked an item on the heap */ +#define SP_ERROR_ARRAY_TOO_BIG 19 /**< A dynamic array is too big */ +#define SP_ERROR_TRACKER_BOUNDS 20 /**< Tracker stack is out of bounds */ +#define SP_ERROR_INVALID_NATIVE 21 /**< Native was pending or invalid */ +#define SP_ERROR_PARAMS_MAX 22 /**< Maximum number of parameters reached */ +#define SP_ERROR_NATIVE 23 /**< Error originates from a native */ +#define SP_ERROR_NOT_RUNNABLE 24 /**< Function or plugin is not runnable */ +#define SP_ERROR_ABORTED 25 /**< Function call was aborted */ /** * @endsection */ +methodmap GlobalForward < Handle { + // Creates a global forward. + // + // @note The name used to create the forward is used as its public function in all target plugins. + // @note This is ideal for global, static forwards that are never changed. + // @note Global forwards cannot be cloned. + // @note Use CloseHandle() to destroy these. + // + // @param name Name of public function to use in forward. + // @param type Execution type to be used. + // @param ... Variable number of parameter types (up to 32). + // @return Handle to new global forward. + // @error More than 32 paramater types passed. + public native GlobalForward(const char[] name, ExecType type, ParamType ...); + + // Returns the number of functions in a global or private forward's call list. + property int FunctionCount { + public native get(); + } +}; + +methodmap PrivateForward < GlobalForward { + // Creates a private forward. + // + // @note No functions are automatically added. Use AddToForward() to do this. + // @note Private forwards can be cloned. + // @note Use CloseHandle() to destroy these. + // + // @param type Execution type to be used. + // @param ... Variable number of parameter types (up to 32). + // @return Handle to new private forward. + // @error More than 32 paramater types passed. + public native PrivateForward(ExecType type, ParamType ...); + + // Adds a function to a private forward's call list. + // + // @note Cannot be used during an incomplete call. + // + // @param plugin Handle of the plugin that contains the function. + // Pass INVALID_HANDLE to specify the calling plugin. + // @param func Function to add to forward. + // @return True on success, false otherwise. + // @error Invalid or corrupt private forward handle, invalid or corrupt plugin handle, or invalid function. + public native bool AddFunction(Handle plugin, Function func); + + // Removes a function from a private forward's call list. + // + // @note Only removes one instance. + // @note Functions will be removed automatically if their parent plugin is unloaded. + // + // @param plugin Handle of the plugin that contains the function. + // Pass INVALID_HANDLE to specify the calling plugin. + // @param func Function to remove from forward. + // @return True on success, false otherwise. + // @error Invalid or corrupt private forward handle, invalid or corrupt plugin handle, or invalid function. + public native bool RemoveFunction(Handle plugin, Function func); + + // Removes all instances of a plugin from a private forward's call list. + // + // @note Functions will be removed automatically if their parent plugin is unloaded. + // + // @param plugin Handle of the plugin to remove instances of. + // Pass INVALID_HANDLE to specify the calling plugin. + // @return Number of functions removed from forward. + // @error Invalid or corrupt private forward handle or invalid or corrupt plugin handle. + public native int RemoveAllFunctions(Handle plugin); +}; + /** - * Gets a function id from a function name. + * Gets a function id from a function name. * - * @param plugin Handle of the plugin that contains the function. - Pass INVALID_HANDLE to search in the calling plugin. - * @param name Name of the function. - * @return Function id or INVALID_FUNCTION if not found. - * @error Invalid or corrupt plugin handle. + * @param plugin Handle of the plugin that contains the function. + * Pass INVALID_HANDLE to search in the calling plugin. + * @param name Name of the function. + * @return Function id or INVALID_FUNCTION if not found. + * @error Invalid or corrupt plugin handle. */ native Function GetFunctionByName(Handle plugin, const char[] name); @@ -130,13 +198,13 @@ native Function GetFunctionByName(Handle plugin, const char[] name); * @note Global forwards cannot be cloned. * @note Use CloseHandle() to destroy these. * - * @param name Name of public function to use in forward. - * @param type Execution type to be used. - * @param ... Variable number of parameter types (up to 32). - * @return Handle to new global forward. - * @error More than 32 paramater types passed. + * @param name Name of public function to use in forward. + * @param type Execution type to be used. + * @param ... Variable number of parameter types (up to 32). + * @return Handle to new global forward. + * @error More than 32 paramater types passed. */ -native Handle CreateGlobalForward(const char[] name, ExecType type, ParamType ...); +native GlobalForward CreateGlobalForward(const char[] name, ExecType type, ParamType ...); /** * Creates a private forward. @@ -145,19 +213,19 @@ native Handle CreateGlobalForward(const char[] name, ExecType type, ParamType .. * @note Private forwards can be cloned. * @note Use CloseHandle() to destroy these. * - * @param type Execution type to be used. - * @param ... Variable number of parameter types (up to 32). - * @return Handle to new private forward. - * @error More than 32 paramater types passed. + * @param type Execution type to be used. + * @param ... Variable number of parameter types (up to 32). + * @return Handle to new private forward. + * @error More than 32 paramater types passed. */ -native Handle CreateForward(ExecType type, ParamType ...); +native PrivateForward CreateForward(ExecType type, ParamType ...); /** * Returns the number of functions in a global or private forward's call list. * - * @param fwd Handle to global or private forward. - * @return Number of functions in forward. - * @error Invalid or corrupt forward handle. + * @param fwd Handle to global or private forward. + * @return Number of functions in forward. + * @error Invalid or corrupt forward handle. */ native int GetForwardFunctionCount(Handle fwd); @@ -166,12 +234,12 @@ native int GetForwardFunctionCount(Handle fwd); * * @note Cannot be used during an incomplete call. * - * @param fwd Handle to private forward. - * @param plugin Handle of the plugin that contains the function. - * Pass INVALID_HANDLE to specify the calling plugin. - * @param func Function to add to forward. - * @return True on success, false otherwise. - * @error Invalid or corrupt private forward handle, invalid or corrupt plugin handle, or invalid function. + * @param fwd Handle to private forward. + * @param plugin Handle of the plugin that contains the function. + * Pass INVALID_HANDLE to specify the calling plugin. + * @param func Function to add to forward. + * @return True on success, false otherwise. + * @error Invalid or corrupt private forward handle, invalid or corrupt plugin handle, or invalid function. */ native bool AddToForward(Handle fwd, Handle plugin, Function func); @@ -181,12 +249,12 @@ native bool AddToForward(Handle fwd, Handle plugin, Function func); * @note Only removes one instance. * @note Functions will be removed automatically if their parent plugin is unloaded. * - * @param fwd Handle to private forward. - * @param plugin Handle of the plugin that contains the function. - * Pass INVALID_HANDLE to specify the calling plugin. - * @param func Function to remove from forward. - * @return True on success, false otherwise. - * @error Invalid or corrupt private forward handle, invalid or corrupt plugin handle, or invalid function. + * @param fwd Handle to private forward. + * @param plugin Handle of the plugin that contains the function. + * Pass INVALID_HANDLE to specify the calling plugin. + * @param func Function to remove from forward. + * @return True on success, false otherwise. + * @error Invalid or corrupt private forward handle, invalid or corrupt plugin handle, or invalid function. */ native bool RemoveFromForward(Handle fwd, Handle plugin, Function func); @@ -195,11 +263,11 @@ native bool RemoveFromForward(Handle fwd, Handle plugin, Function func); * * @note Functions will be removed automatically if their parent plugin is unloaded. * - * @param fwd Handle to private forward. - * @param plugin Handle of the plugin to remove instances of. - * Pass INVALID_HANDLE to specify the calling plugin. - * @return Number of functions removed from forward. - * @error Invalid or corrupt private forward handle or invalid or corrupt plugin handle. + * @param fwd Handle to private forward. + * @param plugin Handle of the plugin to remove instances of. + * Pass INVALID_HANDLE to specify the calling plugin. + * @return Number of functions removed from forward. + * @error Invalid or corrupt private forward handle or invalid or corrupt plugin handle. */ native int RemoveAllFromForward(Handle fwd, Handle plugin); @@ -208,8 +276,8 @@ native int RemoveAllFromForward(Handle fwd, Handle plugin); * * @note Cannot be used during an incomplete call. * - * @param fwd Handle to global or private forward. - * @error Invalid or corrupt forward handle or called before another call has completed. + * @param fwd Handle to global or private forward. + * @error Invalid or corrupt forward handle or called before another call has completed. */ native void Call_StartForward(Handle fwd); @@ -218,10 +286,10 @@ native void Call_StartForward(Handle fwd); * * @note Cannot be used during an incomplete call. * - * @param plugin Handle of the plugin that contains the function. - * Pass INVALID_HANDLE to specify the calling plugin. - * @param func Function to call. - * @error Invalid or corrupt plugin handle, invalid function, or called before another call has completed. + * @param plugin Handle of the plugin that contains the function. + * Pass INVALID_HANDLE to specify the calling plugin. + * @param func Function to call. + * @error Invalid or corrupt plugin handle, invalid function, or called before another call has completed. */ native void Call_StartFunction(Handle plugin, Function func); @@ -230,8 +298,8 @@ native void Call_StartFunction(Handle plugin, Function func); * * @note Cannot be used before a call has been started. * - * @param value Cell value to push. - * @error Called before a call has been started. + * @param value Cell value to push. + * @error Called before a call has been started. */ native void Call_PushCell(any value); @@ -240,8 +308,8 @@ native void Call_PushCell(any value); * * @note Cannot be used before a call has been started. * - * @param value Cell reference to push. - * @error Called before a call has been started. + * @param value Cell reference to push. + * @error Called before a call has been started. */ native void Call_PushCellRef(any &value); @@ -250,8 +318,8 @@ native void Call_PushCellRef(any &value); * * @note Cannot be used before a call has been started. * - * @param value Floating point value to push. - * @error Called before a call has been started. + * @param value Floating point value to push. + * @error Called before a call has been started. */ native void Call_PushFloat(float value); @@ -260,8 +328,8 @@ native void Call_PushFloat(float value); * * @note Cannot be used before a call has been started. * - * @param value Floating point reference to push. - * @error Called before a call has been started. + * @param value Floating point reference to push. + * @error Called before a call has been started. */ native void Call_PushFloatRef(float &value); @@ -271,9 +339,9 @@ native void Call_PushFloatRef(float &value); * @note Changes to array are not copied back to caller. Use PushArrayEx() to do this. * @note Cannot be used before a call has been started. * - * @param value Array to push. - * @param size Size of array. - * @error Called before a call has been started. + * @param value Array to push. + * @param size Size of array. + * @error Called before a call has been started. */ native void Call_PushArray(const any[] value, int size); @@ -282,11 +350,11 @@ native void Call_PushArray(const any[] value, int size); * * @note Cannot be used before a call has been started. * - * @param value Array to push. - * @param size Size of array. - * @param cpflags Whether or not changes should be copied back to the input array. - * See SP_PARAM_* constants for details. - * @error Called before a call has been started. + * @param value Array to push. + * @param size Size of array. + * @param cpflags Whether or not changes should be copied back to the input array. + * See SP_PARAM_* constants for details. + * @error Called before a call has been started. */ native void Call_PushArrayEx(any[] value, int size, int cpflags); @@ -296,7 +364,7 @@ native void Call_PushArrayEx(any[] value, int size, int cpflags); * * @note Cannot be used before a call has been started. * - * @error Called before a call has been started. + * @error Called before a call has been started. */ native void Call_PushNullVector(); @@ -306,8 +374,8 @@ native void Call_PushNullVector(); * @note Changes to string are not copied back to caller. Use PushStringEx() to do this. * @note Cannot be used before a call has been started. * - * @param value String to push. - * @error Called before a call has been started. + * @param value String to push. + * @error Called before a call has been started. */ native void Call_PushString(const char[] value); @@ -316,14 +384,14 @@ native void Call_PushString(const char[] value); * * @note Cannot be used before a call has been started. * - * @param value String to push. - * @param length Length of string buffer. - * @param szflags Flags determining how string should be handled. - * See SM_PARAM_STRING_* constants for details. - * The default (0) is to push ASCII. - * @param cpflags Whether or not changes should be copied back to the input array. - * See SM_PARAM_* constants for details. - * @error Called before a call has been started. + * @param value String to push. + * @param length Length of string buffer. + * @param szflags Flags determining how string should be handled. + * See SM_PARAM_STRING_* constants for details. + * The default (0) is to push ASCII. + * @param cpflags Whether or not changes should be copied back to the input array. + * See SM_PARAM_* constants for details. + * @error Called before a call has been started. */ native void Call_PushStringEx(char[] value, int length, int szflags, int cpflags); @@ -333,7 +401,7 @@ native void Call_PushStringEx(char[] value, int length, int szflags, int cpflags * * @note Cannot be used before a call has been started. * - * @error Called before a call has been started. + * @error Called before a call has been started. */ native void Call_PushNullString(); @@ -342,9 +410,9 @@ native void Call_PushNullString(); * * @note Cannot be used before a call has been started. * - * @param result Return value of function or forward's call list. - * @return SP_ERROR_NONE on success, any other integer on failure. - * @error Called before a call has been started. + * @param result Return value of function or forward's call list. + * @return SP_ERROR_NONE on success, any other integer on failure. + * @error Called before a call has been started. */ native int Call_Finish(any &result=0); @@ -352,87 +420,104 @@ native int Call_Finish(any &result=0); * Cancels a call to a function or forward's call list. * * @note Cannot be used before a call has been started. - * - * @error Called before a call has been started. - */ -native void Call_Cancel(); - -/** - * Defines a native function. - * - * It is not necessary to validate the parameter count * - * @param plugin Handle of the calling plugin. - * @param numParams Number of parameters passed to the native. - * @return Value for the native call to return. + * @error Called before a call has been started. */ -typedef NativeCall = function int (Handle plugin, int numParams); +native void Call_Cancel(); -/** - * Creates a dynamic native. This should only be called in AskPluginLoad(), or +typeset NativeCall +{ + /** + * Defines a native function. + * + * It is not necessary to validate the parameter count + * + * @param plugin Handle of the calling plugin. + * @param numParams Number of parameters passed to the native. + * @return Value for the native call to return. + */ + function int (Handle plugin, int numParams); + + /** + * Defines a native function. + * + * It is not necessary to validate the parameter count + * + * @param plugin Handle of the calling plugin. + * @param numParams Number of parameters passed to the native. + * @return Value for the native call to return. + */ + function any (Handle plugin, int numParams); +} + +/** + * Creates a dynamic native. This should only be called in AskPluginLoad(), or * else you risk not having your native shared with other plugins. * - * @param name Name of the dynamic native; must be unique among - * all other registered dynamic natives. - * @param func Function to use as the dynamic native. + * @param name Name of the dynamic native; must be unique among + * all other registered dynamic natives. + * @param func Function to use as the dynamic native. */ native void CreateNative(const char[] name, NativeCall func); /** * Throws an error in the calling plugin of a native, instead of your own plugin. * - * @param error Error code to use. - * @param fmt Error message format. - * @param ... Format arguments. + * @param error Error code to use. + * @param fmt Error message format. + * @param ... Format arguments. */ native int ThrowNativeError(int error, const char[] fmt, any ...); /** - * Retrieves the string length from a native parameter string. This is useful + * Retrieves the string length from a native parameter string. This is useful for * fetching the entire string using dynamic arrays. + * * @note If this function succeeds, Get/SetNativeString will also succeed. * - * @param param Parameter number, starting from 1. - * @param length Stores the length of the string. - * @return SP_ERROR_NONE on success, any other integer on failure. - * @error Invalid parameter number or calling from a non-native function. + * @param param Parameter number, starting from 1. + * @param length Stores the length of the string. + * @return SP_ERROR_NONE on success, any other integer on failure. + * @error Invalid parameter number or calling from a non-native function. */ native int GetNativeStringLength(int param, int &length); /** * Retrieves a string from a native parameter. + * * @note Output conditions are undefined on failure. * - * @param param Parameter number, starting from 1. - * @param buffer Buffer to store the string in. - * @param maxlength Maximum length of the buffer. - * @param bytes Optionally store the number of bytes written. - * @return SP_ERROR_NONE on success, any other integer on failure. - * @error Invalid parameter number or calling from a non-native function. + * @param param Parameter number, starting from 1. + * @param buffer Buffer to store the string in. + * @param maxlength Maximum length of the buffer. + * @param bytes Optionally store the number of bytes written. + * @return SP_ERROR_NONE on success, any other integer on failure. + * @error Invalid parameter number or calling from a non-native function. */ native int GetNativeString(int param, char[] buffer, int maxlength, int &bytes=0); /** * Sets a string in a native parameter. + * * @note Output conditions are undefined on failure. * - * @param param Parameter number, starting from 1. - * @param source Source string to use. - * @param maxlength Maximum number of bytes to write. - * @param utf8 If false, string will not be written - * with UTF8 safety. - * @param bytes Optionally store the number of bytes written. - * @return SP_ERROR_NONE on success, any other integer on failure. - * @error Invalid parameter number or calling from a non-native function. + * @param param Parameter number, starting from 1. + * @param source Source string to use. + * @param maxlength Maximum number of bytes to write. + * @param utf8 If false, string will not be written + * with UTF8 safety. + * @param bytes Optionally store the number of bytes written. + * @return SP_ERROR_NONE on success, any other integer on failure. + * @error Invalid parameter number or calling from a non-native function. */ native int SetNativeString(int param, const char[] source, int maxlength, bool utf8=true, int &bytes=0); /** * Gets a cell from a native parameter. * - * @param param Parameter number, starting from 1. - * @return Cell value at the parameter number. - * @error Invalid parameter number or calling from a non-native function. + * @param param Parameter number, starting from 1. + * @return Cell value at the parameter number. + * @error Invalid parameter number or calling from a non-native function. */ native any GetNativeCell(int param); @@ -448,56 +533,56 @@ native Function GetNativeFunction(int param); /** * Gets a cell from a native parameter, by reference. * - * @param param Parameter number, starting from 1. - * @return Cell value at the parameter number. - * @error Invalid parameter number or calling from a non-native function. + * @param param Parameter number, starting from 1. + * @return Cell value at the parameter number. + * @error Invalid parameter number or calling from a non-native function. */ native any GetNativeCellRef(int param); /** * Sets a cell from a native parameter, by reference. * - * @param param Parameter number, starting from 1. - * @param value Cell value at the parameter number to set by reference. - * @error Invalid parameter number or calling from a non-native function. + * @param param Parameter number, starting from 1. + * @param value Cell value at the parameter number to set by reference. + * @error Invalid parameter number or calling from a non-native function. */ native void SetNativeCellRef(int param, any value); /** * Gets an array from a native parameter (always by reference). * - * @param param Parameter number, starting from 1. - * @param local Local array to copy into. - * @param size Maximum size of local array. - * @return SP_ERROR_NONE on success, anything else on failure. - * @error Invalid parameter number or calling from a non-native function. + * @param param Parameter number, starting from 1. + * @param local Local array to copy into. + * @param size Maximum size of local array. + * @return SP_ERROR_NONE on success, anything else on failure. + * @error Invalid parameter number or calling from a non-native function. */ native int GetNativeArray(int param, any[] local, int size); /** * Copies a local array into a native parameter array (always by reference). - * - * @param param Parameter number, starting from 1. - * @param local Local array to copy from. - * @param size Size of the local array to copy. - * @return SP_ERROR_NONE on success, anything else on failure. - * @error Invalid parameter number or calling from a non-native function. + * + * @param param Parameter number, starting from 1. + * @param local Local array to copy from. + * @param size Size of the local array to copy. + * @return SP_ERROR_NONE on success, anything else on failure. + * @error Invalid parameter number or calling from a non-native function. */ native int SetNativeArray(int param, const any[] local, int size); /** * Check if the native parameter is the NULL_VECTOR. * - * @param param Parameter number, starting from 1. - * @return True if NULL_VECTOR, false otherwise. + * @param param Parameter number, starting from 1. + * @return True if NULL_VECTOR, false otherwise. */ native bool IsNativeParamNullVector(int param); /** * Check if the native parameter is the NULL_STRING. * - * @param param Parameter number, starting from 1. - * @return True if NULL_STRING, false otherwise. + * @param param Parameter number, starting from 1. + * @return True if NULL_STRING, false otherwise. */ native bool IsNativeParamNullString(int param); @@ -506,20 +591,20 @@ native bool IsNativeParamNullString(int param); * * @note All parameter indexes start at 1. * @note If the input and output buffers overlap, the contents - * of the output buffer at the end is undefined. - * - * @param out_param Output parameter number to write to. If 0, out_string is used. - * @param fmt_param Format parameter number. If 0, fmt_string is used. - * @param vararg_param First variable parameter number. - * @param out_len Output string buffer maximum length (always required). - * @param written Optionally stores the number of bytes written. - * @param out_string Output string buffer to use if out_param is not used. - * @param fmt_string Format string to use if fmt_param is not used. - * @return SP_ERROR_NONE on success, anything else on failure. - */ -native int FormatNativeString(int out_param, - int fmt_param, - int vararg_param, + * of the output buffer at the end is undefined. + * + * @param out_param Output parameter number to write to. If 0, out_string is used. + * @param fmt_param Format parameter number. If 0, fmt_string is used. + * @param vararg_param First variable parameter number. + * @param out_len Output string buffer maximum length (always required). + * @param written Optionally stores the number of bytes written. + * @param out_string Output string buffer to use if out_param is not used. + * @param fmt_string Format string to use if fmt_param is not used. + * @return SP_ERROR_NONE on success, anything else on failure. + */ +native int FormatNativeString(int out_param, + int fmt_param, + int vararg_param, int out_len, int &written=0, char[] out_string="", @@ -528,14 +613,17 @@ native int FormatNativeString(int out_param, /** * Defines a RequestFrame Callback. * - * @param data Data passed to the RequestFrame native. + * @param data Data passed to the RequestFrame native. */ -typedef RequestFrameCallback = function void (any data); +typeset RequestFrameCallback { + function void (); + function void (any data); +} /** * Creates a single use Next Frame hook. * - * @param Function Function to call on the next frame. - * @param data Value to be passed on the invocation of the Function. + * @param Function Function to call on the next frame. + * @param data Value to be passed on the invocation of the Function. */ native void RequestFrame(RequestFrameCallback Function, any data=0); diff --git a/addons/sourcemod/scripting/include/geoip.inc b/addons/sourcemod/scripting/include/geoip.inc index 7906977..be6653d 100644 --- a/addons/sourcemod/scripting/include/geoip.inc +++ b/addons/sourcemod/scripting/include/geoip.inc @@ -31,7 +31,7 @@ */ #if defined _geoip_included - #endinput + #endinput #endif #define _geoip_included @@ -44,28 +44,28 @@ /** * Gets the two character country code from an IP address. (US, CA, etc) * - * @param ip Ip to determine the country code. - * @param ccode Destination string buffer to store the code. - * @return True on success, false if no country found. + * @param ip Ip to determine the country code. + * @param ccode Destination string buffer to store the code. + * @return True on success, false if no country found. */ native bool GeoipCode2(const char[] ip, char ccode[3]); /** * Gets the three character country code from an IP address. (USA, CAN, etc) * - * @param ip Ip to determine the country code. - * @param ccode Destination string buffer to store the code. - * @return True on success, false if no country found. + * @param ip Ip to determine the country code. + * @param ccode Destination string buffer to store the code. + * @return True on success, false if no country found. */ native bool GeoipCode3(const char[] ip, char ccode[4]); /** * Gets the full country name. (max length of output string is 45) * - * @param ip Ip to determine the country code. - * @param name Destination string buffer to store the country name. - * @param maxlength Maximum length of output string buffer. - * @return True on success, false if no country found. + * @param ip Ip to determine the country code. + * @param name Destination string buffer to store the country name. + * @param maxlength Maximum length of output string buffer. + * @return True on success, false if no country found. */ native bool GeoipCountry(const char[] ip, char[] name, int maxlength); diff --git a/addons/sourcemod/scripting/include/halflife.inc b/addons/sourcemod/scripting/include/halflife.inc index 7db3395..c9c9912 100644 --- a/addons/sourcemod/scripting/include/halflife.inc +++ b/addons/sourcemod/scripting/include/halflife.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -35,61 +35,61 @@ #endif #define _halflife_included -#define SOURCE_SDK_UNKNOWN 0 /**< Could not determine the engine version */ -#define SOURCE_SDK_ORIGINAL 10 /**< Original Source engine (still used by "The Ship") */ -#define SOURCE_SDK_DARKMESSIAH 15 /**< Modified version of original engine used by Dark Messiah (no SDK) */ -#define SOURCE_SDK_EPISODE1 20 /**< SDK+Engine released after Episode 1 */ -#define SOURCE_SDK_EPISODE2 30 /**< SDK+Engine released after Episode 2/Orange Box */ -#define SOURCE_SDK_BLOODYGOODTIME 32 /**< Modified version of ep2 engine used by Bloody Good Time (no SDK) */ -#define SOURCE_SDK_EYE 33 /**< Modified version of ep2 engine used by E.Y.E Divine Cybermancy (no SDK) */ -#define SOURCE_SDK_CSS 34 /**< Sometime-older version of Source 2009 SDK+Engine, used for Counter-Strike: Source */ -#define SOURCE_SDK_EPISODE2VALVE 35 /**< SDK+Engine released after Episode 2/Orange Box, "Source 2009" or "Source MP" */ -#define SOURCE_SDK_LEFT4DEAD 40 /**< Engine released after Left 4 Dead (no SDK yet) */ -#define SOURCE_SDK_LEFT4DEAD2 50 /**< Engine released after Left 4 Dead 2 (no SDK yet) */ -#define SOURCE_SDK_ALIENSWARM 60 /**< SDK+Engine released after Alien Swarm */ -#define SOURCE_SDK_CSGO 80 /**< Engine released after CS:GO (no SDK yet) */ -#define SOURCE_SDK_DOTA 90 /**< Engine released after Dota 2 (no SDK) */ - -#define MOTDPANEL_TYPE_TEXT 0 /**< Treat msg as plain text */ -#define MOTDPANEL_TYPE_INDEX 1 /**< Msg is auto determined by the engine */ -#define MOTDPANEL_TYPE_URL 2 /**< Treat msg as an URL link */ -#define MOTDPANEL_TYPE_FILE 3 /**< Treat msg as a filename to be opened */ +#define SOURCE_SDK_UNKNOWN 0 /**< Could not determine the engine version */ +#define SOURCE_SDK_ORIGINAL 10 /**< Original Source engine (still used by "The Ship") */ +#define SOURCE_SDK_DARKMESSIAH 15 /**< Modified version of original engine used by Dark Messiah (no SDK) */ +#define SOURCE_SDK_EPISODE1 20 /**< SDK+Engine released after Episode 1 */ +#define SOURCE_SDK_EPISODE2 30 /**< SDK+Engine released after Episode 2/Orange Box */ +#define SOURCE_SDK_BLOODYGOODTIME 32 /**< Modified version of ep2 engine used by Bloody Good Time (no SDK) */ +#define SOURCE_SDK_EYE 33 /**< Modified version of ep2 engine used by E.Y.E Divine Cybermancy (no SDK) */ +#define SOURCE_SDK_CSS 34 /**< Sometime-older version of Source 2009 SDK+Engine, used for Counter-Strike: Source */ +#define SOURCE_SDK_EPISODE2VALVE 35 /**< SDK+Engine released after Episode 2/Orange Box, "Source 2009" or "Source MP" */ +#define SOURCE_SDK_LEFT4DEAD 40 /**< Engine released after Left 4 Dead (no SDK yet) */ +#define SOURCE_SDK_LEFT4DEAD2 50 /**< Engine released after Left 4 Dead 2 (no SDK yet) */ +#define SOURCE_SDK_ALIENSWARM 60 /**< SDK+Engine released after Alien Swarm */ +#define SOURCE_SDK_CSGO 80 /**< Engine released after CS:GO (no SDK yet) */ +#define SOURCE_SDK_DOTA 90 /**< Engine released after Dota 2 (no SDK) */ + +#define MOTDPANEL_TYPE_TEXT 0 /**< Treat msg as plain text */ +#define MOTDPANEL_TYPE_INDEX 1 /**< Msg is auto determined by the engine */ +#define MOTDPANEL_TYPE_URL 2 /**< Treat msg as an URL link */ +#define MOTDPANEL_TYPE_FILE 3 /**< Treat msg as a filename to be opened */ enum DialogType { - DialogType_Msg = 0, /**< just an on screen message */ - DialogType_Menu, /**< an options menu */ - DialogType_Text, /**< a richtext dialog */ - DialogType_Entry, /**< an entry box */ - DialogType_AskConnect /**< ask the client to connect to a specified IP */ + DialogType_Msg = 0, /**< just an on screen message */ + DialogType_Menu, /**< an options menu */ + DialogType_Text, /**< a richtext dialog */ + DialogType_Entry, /**< an entry box */ + DialogType_AskConnect /**< ask the client to connect to a specified IP */ }; enum EngineVersion { - Engine_Unknown, /**< Could not determine the engine version */ - Engine_Original, /**< Original Source Engine (used by The Ship) */ - Engine_SourceSDK2006, /**< Episode 1 Source Engine (second major SDK) */ - Engine_SourceSDK2007, /**< Orange Box Source Engine (third major SDK) */ - Engine_Left4Dead, /**< Left 4 Dead */ - Engine_DarkMessiah, /**< Dark Messiah Multiplayer (based on original engine) */ - Engine_Left4Dead2 = 7, /**< Left 4 Dead 2 */ - Engine_AlienSwarm, /**< Alien Swarm (and Alien Swarm SDK) */ - Engine_BloodyGoodTime, /**< Bloody Good Time */ - Engine_EYE, /**< E.Y.E Divine Cybermancy */ - Engine_Portal2, /**< Portal 2 */ - Engine_CSGO, /**< Counter-Strike: Global Offensive */ - Engine_CSS, /**< Counter-Strike: Source */ - Engine_DOTA, /**< Dota 2 */ - Engine_HL2DM, /**< Half-Life 2 Deathmatch */ - Engine_DODS, /**< Day of Defeat: Source */ - Engine_TF2, /**< Team Fortress 2 */ - Engine_NuclearDawn, /**< Nuclear Dawn */ - Engine_SDK2013, /**< Source SDK 2013 */ - Engine_Blade, /**< Blade Symphony */ - Engine_Insurgency, /**< Insurgency (2013 Retail version)*/ - Engine_Contagion, /**< Contagion */ - Engine_BlackMesa, /**< Black Mesa Multiplayer */ - Engine_DOI, /**< Day of Infamy */ + Engine_Unknown, /**< Could not determine the engine version */ + Engine_Original, /**< Original Source Engine (used by The Ship) */ + Engine_SourceSDK2006, /**< Episode 1 Source Engine (second major SDK) */ + Engine_SourceSDK2007, /**< Orange Box Source Engine (third major SDK) */ + Engine_Left4Dead, /**< Left 4 Dead */ + Engine_DarkMessiah, /**< Dark Messiah Multiplayer (based on original engine) */ + Engine_Left4Dead2 = 7, /**< Left 4 Dead 2 */ + Engine_AlienSwarm, /**< Alien Swarm (and Alien Swarm SDK) */ + Engine_BloodyGoodTime, /**< Bloody Good Time */ + Engine_EYE, /**< E.Y.E Divine Cybermancy */ + Engine_Portal2, /**< Portal 2 */ + Engine_CSGO, /**< Counter-Strike: Global Offensive */ + Engine_CSS, /**< Counter-Strike: Source */ + Engine_DOTA, /**< Dota 2 */ + Engine_HL2DM, /**< Half-Life 2 Deathmatch */ + Engine_DODS, /**< Day of Defeat: Source */ + Engine_TF2, /**< Team Fortress 2 */ + Engine_NuclearDawn, /**< Nuclear Dawn */ + Engine_SDK2013, /**< Source SDK 2013 */ + Engine_Blade, /**< Blade Symphony */ + Engine_Insurgency, /**< Insurgency (2013 Retail version)*/ + Engine_Contagion, /**< Contagion */ + Engine_BlackMesa, /**< Black Mesa Multiplayer */ + Engine_DOI /**< Day of Infamy */ }; enum FindMapResult @@ -116,233 +116,236 @@ enum FindMapResult /** * Logs a generic message to the HL2 logs. * - * @param format String format. - * @param ... Format arguments. + * @param format String format. + * @param ... Format arguments. */ native void LogToGame(const char[] format, any ...); /** * Sets the seed value for the global Half-Life 2 Random Stream. * - * @param seed Seed value. + * @param seed Seed value. */ native void SetRandomSeed(int seed); /** * Returns a random floating point number from the Half-Life 2 Random Stream. * - * @param fMin Minimum random bound. - * @param fMax Maximum random bound. - * @return A random number between (inclusive) fMin and fMax. + * @param fMin Minimum random bound. + * @param fMax Maximum random bound. + * @return A random number between (inclusive) fMin and fMax. */ native float GetRandomFloat(float fMin=0.0, float fMax=1.0); /** * Returns a random number from the Half-Life 2 Random Stream. * - * @param nmin Minimum random bound. - * @param nmax Maximum random bound. - * @return A random number between (inclusive) nmin and nmax. + * @param nmin Minimum random bound. + * @param nmax Maximum random bound. + * @return A random number between (inclusive) nmin and nmax. */ native int GetRandomInt(int nmin, int nmax); /** * Returns whether a map is valid or not. - * - * @param map Map name, excluding .bsp extension. - * @return True if valid, false otherwise. + * + * @param map Map name, excluding .bsp extension. + * @return True if valid, false otherwise. */ native bool IsMapValid(const char[] map); /** * Returns whether a full or partial map name is found or can be resolved - * - * @param map Map name (usually same as map path relative to maps/ dir, - * excluding .bsp extension). - * @param foundmap Resolved map name. If the return is FindMap_FuzzyMatch - * or FindMap_NonCanonical the buffer will be the full path. - * @param maxlen Maximum length to write to map var. - * @return Result of the find operation. Not all result types are supported on all games. + * + * @param map Map name (usually same as map path relative to maps/ dir, + * excluding .bsp extension). + * @param foundmap Resolved map name. If the return is FindMap_FuzzyMatch + * or FindMap_NonCanonical the buffer will be the full path. + * @param maxlen Maximum length to write to map var. + * @return Result of the find operation. Not all result types are supported on all games. */ native FindMapResult FindMap(const char[] map, char[] foundmap, int maxlen); /** * Get the display name of a workshop map. - * + * * Note: You do not need to call FindMap first. This native will call FindMap internally. - * - * @param map Map name (usually same as map path relative to maps/ dir, - * excluding .bsp extension). - * @param displayName Map's display name, i.e. cp_mymapname or de_mymapname. - * If FindMap returns FindMap_PossiblyAvailable or FindMap_NotFound, - * the map cannot be resolved and this native will return false, - * but displayName will be a copy of map. - * @param maxlen Maximum length to write to displayName var. - * @return true if FindMap returns FindMap_Found, FindMap_FuzzyMatch, or - * FindMap_NonCanonical. - * false if FindMap returns FindMap_PossiblyAvailable or FindMap_NotFound. + * + * @param map Map name (usually same as map path relative to maps/ dir, + * excluding .bsp extension). + * @param displayName Map's display name, i.e. cp_mymapname or de_mymapname. + * If FindMap returns FindMap_PossiblyAvailable or FindMap_NotFound, + * the map cannot be resolved and this native will return false, + * but displayName will be a copy of map. + * @param maxlen Maximum length to write to displayName var. + * @return true if FindMap returns FindMap_Found, FindMap_FuzzyMatch, or + * FindMap_NonCanonical. + * false if FindMap returns FindMap_PossiblyAvailable or FindMap_NotFound. */ native bool GetMapDisplayName(const char[] map, char[] displayName, int maxlen); /** * Returns whether the server is dedicated. * - * @return True if dedicated, false otherwise. + * @return True if dedicated, false otherwise. */ native bool IsDedicatedServer(); /** * Returns a high-precision time value for profiling the engine. * - * @return A floating point time value. + * @return A floating point time value. */ native float GetEngineTime(); -/** +/** * Returns the game time based on the game tick. * - * @return Game tick time. + * @return Game tick time. */ native float GetGameTime(); -/** +/** * Returns the game's internal tick count. * - * @return Game tick count. + * @return Game tick count. */ native int GetGameTickCount(); -/** +/** * Returns the time the Game took processing the last frame. * - * @return Game frame time. + * @return Game frame time. */ native float GetGameFrameTime(); /** * Returns the game description from the mod. * - * @param buffer Buffer to store the description. - * @param maxlength Maximum size of the buffer. - * @param original If true, retrieves the original game description, - * ignoring any potential hooks from plugins. - * @return Number of bytes written to the buffer (UTF-8 safe). + * @param buffer Buffer to store the description. + * @param maxlength Maximum size of the buffer. + * @param original If true, retrieves the original game description, + * ignoring any potential hooks from plugins. + * @return Number of bytes written to the buffer (UTF-8 safe). */ native int GetGameDescription(char[] buffer, int maxlength, bool original=false); /** * Returns the name of the game's directory. * - * @param buffer Buffer to store the directory name. - * @param maxlength Maximum size of the buffer. - * @return Number of bytes written to the buffer (UTF-8 safe). + * @param buffer Buffer to store the directory name. + * @param maxlength Maximum size of the buffer. + * @return Number of bytes written to the buffer (UTF-8 safe). */ native int GetGameFolderName(char[] buffer, int maxlength); /** * Returns the current map name. * - * @param buffer Buffer to store map name. - * @param maxlength Maximum length of buffer. - * @return Number of bytes written (UTF-8 safe). + * @param buffer Buffer to store map name. + * @param maxlength Maximum length of buffer. + * @return Number of bytes written (UTF-8 safe). */ native int GetCurrentMap(char[] buffer, int maxlength); /** * Precaches a given model. * - * @param model Name of the model to precache. - * @param preload If preload is true the file will be precached before level startup. - * @return Returns the model index, 0 for error. + * @param model Name of the model to precache. + * @param preload If preload is true the file will be precached before level startup. + * @return Returns the model index, 0 for error. */ native int PrecacheModel(const char[] model, bool preload=false); /** * Precaches a given sentence file. * - * @param file Name of the sentence file to precache. - * @param preload If preload is true the file will be precached before level startup. - * @return Returns a sentence file index. + * @param file Name of the sentence file to precache. + * @param preload If preload is true the file will be precached before level startup. + * @return Returns a sentence file index. */ native int PrecacheSentenceFile(const char[] file, bool preload=false); /** * Precaches a given decal. * - * @param decal Name of the decal to precache. - * @param preload If preload is true the file will be precached before level startup. - * @return Returns a decal index. + * @param decal Name of the decal to precache. + * @param preload If preload is true the file will be precached before level startup. + * @return Returns a decal index. */ native int PrecacheDecal(const char[] decal, bool preload=false); /** * Precaches a given generic file. * - * @param generic Name of the generic file to precache. - * @param preload If preload is true the file will be precached before level startup. - * @return Returns a generic file index. + * @param generic Name of the generic file to precache. + * @param preload If preload is true the file will be precached before level startup. + * @return Returns a generic file index. */ native int PrecacheGeneric(const char[] generic, bool preload=false); /** * Returns if a given model is precached. * - * @param model Name of the model to check. - * @return True if precached, false otherwise. + * @param model Name of the model to check. + * @return True if precached, false otherwise. */ native bool IsModelPrecached(const char[] model); /** * Returns if a given decal is precached. * - * @param decal Name of the decal to check. - * @return True if precached, false otherwise. + * @param decal Name of the decal to check. + * @return True if precached, false otherwise. */ native bool IsDecalPrecached(const char[] decal); /** * Returns if a given generic file is precached. * - * @param generic Name of the generic file to check. - * @return True if precached, false otherwise. + * @param generic Name of the generic file to check. + * @return True if precached, false otherwise. */ native bool IsGenericPrecached(const char[] generic); /** * Precaches a given sound. * - * @param sound Name of the sound to precache. - * @param preload If preload is true the file will be precached before level startup. - * @return True if successfully precached, false otherwise. + * @param sound Name of the sound to precache. + * @param preload If preload is true the file will be precached before level startup. + * @return True if successfully precached, false otherwise. */ native bool PrecacheSound(const char[] sound, bool preload=false); /** * Returns if a given sound is precached. * - * @param sound Name of the sound to check. - * @return True if precached, false otherwise. + * @param sound Name of the sound to check. + * @return True if precached, false otherwise. + * @deprecated Doesn't work correctly, always returns true. */ +#pragma deprecated Doesn't work correctly, always returns true. native bool IsSoundPrecached(const char[] sound); /** * Creates different types of ingame messages. * - * @param client Index of the client. - * @param kv KeyValues handle to set the menu keys and options. (Check iserverplugin.h for more information). - * @param type Message type to display ingame. - * @error Invalid client index, or client not connected. + * @param client Index of the client. + * @param kv KeyValues handle to set the menu keys and options. (Check iserverplugin.h for more information). + * @param type Message type to display ingame. + * @error Invalid client index, or client not connected. */ native void CreateDialog(int client, Handle kv, DialogType type); /** - * Guesses the SDK version a mod was compiled against. If nothing + * Guesses the SDK version a mod was compiled against. If nothing * specific is known about the game, the engine version is used instead. * - * The return values are guaranteed to increase chronologically (that is, + * The return values are guaranteed to increase chronologically (that is, * a later release will have a higher value). * - * @return SOURCE_SDK version code. + * @return SOURCE_SDK version code. + * @deprecated See GetEngineVersion() */ #pragma deprecated See GetEngineVersion() native int GuessSDKVersion(); @@ -353,30 +356,30 @@ native int GuessSDKVersion(); * The engine version values are not guaranteed to be in any particular order, * and should only be compared by (in)equality. * - * @return An EngineVersion value. + * @return An EngineVersion value. */ native EngineVersion GetEngineVersion(); /** * Prints a message to a specific client in the chat area. * - * @param client Client index. - * @param format Formatting rules. - * @param ... Variable number of format parameters. - * @error If the client is not connected an error will be thrown. + * @param client Client index. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @error If the client is not connected an error will be thrown. */ native void PrintToChat(int client, const char[] format, any ...); /** * Prints a message to all clients in the chat area. * - * @param format Formatting rules. - * @param ... Variable number of format parameters. + * @param format Formatting rules. + * @param ... Variable number of format parameters. */ stock void PrintToChatAll(const char[] format, any ...) { char buffer[254]; - + for (int i = 1; i <= MaxClients; i++) { if (IsClientInGame(i)) @@ -391,18 +394,18 @@ stock void PrintToChatAll(const char[] format, any ...) /** * Prints a message to a specific client in the center of the screen. * - * @param client Client index. - * @param format Formatting rules. - * @param ... Variable number of format parameters. - * @error If the client is not connected an error will be thrown. + * @param client Client index. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @error If the client is not connected an error will be thrown. */ native void PrintCenterText(int client, const char[] format, any ...); /** * Prints a message to all clients in the center of the screen. * - * @param format Formatting rules. - * @param ... Variable number of format parameters. + * @param format Formatting rules. + * @param ... Variable number of format parameters. */ stock void PrintCenterTextAll(const char[] format, any ...) { @@ -422,23 +425,23 @@ stock void PrintCenterTextAll(const char[] format, any ...) /** * Prints a message to a specific client with a hint box. * - * @param client Client index. - * @param format Formatting rules. - * @param ... Variable number of format parameters. - * @error If the client is not connected an error will be thrown. + * @param client Client index. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @error If the client is not connected an error will be thrown. */ native void PrintHintText(int client, const char[] format, any ...); /** * Prints a message to all clients with a hint box. * - * @param format Formatting rules. - * @param ... Variable number of format parameters. + * @param format Formatting rules. + * @param ... Variable number of format parameters. */ stock void PrintHintTextToAll(const char[] format, any ...) { char buffer[254]; - + for (int i = 1; i <= MaxClients; i++) { if (IsClientInGame(i)) @@ -453,130 +456,130 @@ stock void PrintHintTextToAll(const char[] format, any ...) /** * Shows a VGUI panel to a specific client. * - * @param client Client index. - * @param name Panel type name (Check viewport_panel_names.h to see a list of - * some panel names). - * @param Kv KeyValues handle with all the data for the panel setup (Depends - * on the panel type and may be unused). - * @param show True to show the panel, or false to remove it from the client screen. - * @error If the client is not connected an error will be thrown. + * @param client Client index. + * @param name Panel type name (Check viewport_panel_names.h to see a list of + * some panel names). + * @param Kv KeyValues handle with all the data for the panel setup (Depends + * on the panel type and may be unused). + * @param show True to show the panel, or false to remove it from the client screen. + * @error If the client is not connected an error will be thrown. */ native void ShowVGUIPanel(int client, const char[] name, Handle Kv=INVALID_HANDLE, bool show=true); /** - * Creates a HUD synchronization object. This object is used to automatically assign and - * re-use channels for a set of messages. + * Creates a HUD synchronization object. This object is used to automatically assign and + * re-use channels for a set of messages. * - * The HUD has a hardcoded number of channels (usually 6) for displaying - * text. You can use any channel for any area of the screen. Text on - * different channels can overlap, but text on the same channel will + * The HUD has a hardcoded number of channels (usually 6) for displaying + * text. You can use any channel for any area of the screen. Text on + * different channels can overlap, but text on the same channel will * erase the old text first. This overlapping and overwriting gets problematic. * - * A HUD synchronization object automatically selects channels for you based on + * A HUD synchronization object automatically selects channels for you based on * the following heuristics: - * - If channel X was last used by the object, and hasn't been modified again, + * - If channel X was last used by the object, and hasn't been modified again, * channel X gets re-used. * - Otherwise, a new channel is chosen based on the least-recently-used channel. * - * This ensures that if you display text on a sync object, that the previous text - * displayed on it will always be cleared first. This is because your new text - * will either overwrite the old text on the same channel, or because another + * This ensures that if you display text on a sync object, that the previous text + * displayed on it will always be cleared first. This is because your new text + * will either overwrite the old text on the same channel, or because another * channel has already erased your text. * - * Note that messages can still overlap if they are on different synchronization + * Note that messages can still overlap if they are on different synchronization * objects, or they are displayed to manual channels. * - * These are particularly useful for displaying repeating or refreshing HUD text, in - * addition to displaying multiple message sets in one area of the screen (for example, - * center-say messages that may pop up randomly that you don't want to overlap each + * These are particularly useful for displaying repeating or refreshing HUD text, in + * addition to displaying multiple message sets in one area of the screen (for example, + * center-say messages that may pop up randomly that you don't want to overlap each * other). * - * @return New HUD synchronization object. - * The Handle can be closed with CloseHandle(). - * If HUD text is not supported on this mod, then - * INVALID_HANDLE is returned. + * @return New HUD synchronization object. + * The Handle can be closed with CloseHandle(). + * If HUD text is not supported on this mod, then + * INVALID_HANDLE is returned. */ native Handle CreateHudSynchronizer(); /** - * Sets the HUD parameters for drawing text. These parameters are stored - * globally, although nothing other than this function and SetHudTextParamsEx + * Sets the HUD parameters for drawing text. These parameters are stored + * globally, although nothing other than this function and SetHudTextParamsEx * modify them. * - * You must call this function before drawing text. If you are drawing - * text to multiple clients, you can set the parameters once, since - * they won't be modified. However, as soon as you pass control back + * You must call this function before drawing text. If you are drawing + * text to multiple clients, you can set the parameters once, since + * they won't be modified. However, as soon as you pass control back * to other plugins, you must reset the parameters next time you draw. * - * @param x x coordinate, from 0 to 1. -1.0 is the center. - * @param y y coordinate, from 0 to 1. -1.0 is the center. - * @param holdTime Number of seconds to hold the text. - * @param r Red color value. - * @param g Green color value. - * @param b Blue color value. - * @param a Alpha transparency value. - * @param effect 0/1 causes the text to fade in and fade out. - * 2 causes the text to flash[?]. - * @param fxTime Duration of chosen effect (may not apply to all effects). - * @param fadeIn Number of seconds to spend fading in. - * @param fadeOut Number of seconds to spend fading out. + * @param x x coordinate, from 0 to 1. -1.0 is the center. + * @param y y coordinate, from 0 to 1. -1.0 is the center. + * @param holdTime Number of seconds to hold the text. + * @param r Red color value. + * @param g Green color value. + * @param b Blue color value. + * @param a Alpha transparency value. + * @param effect 0/1 causes the text to fade in and fade out. + * 2 causes the text to flash[?]. + * @param fxTime Duration of chosen effect (may not apply to all effects). + * @param fadeIn Number of seconds to spend fading in. + * @param fadeOut Number of seconds to spend fading out. */ native void SetHudTextParams(float x, float y, float holdTime, int r, int g, int b, int a, int effect = 0, float fxTime=6.0, float fadeIn=0.1, float fadeOut=0.2); - + /** - * Sets the HUD parameters for drawing text. These parameters are stored + * Sets the HUD parameters for drawing text. These parameters are stored * globally, although nothing other than this function and SetHudTextParams * modify them. * - * This is the same as SetHudTextParams(), except it lets you set the alternate - * color for when effects require it. - * - * @param x x coordinate, from 0 to 1. -1.0 is the center. - * @param y y coordinate, from 0 to 1. -1.0 is the center. - * @param holdTime Number of seconds to hold the text. - * @param color1 First color set, array values being [red, green, blue, alpha] - * @param color2 Second color set, array values being [red, green, blue, alpha] - * @param effect 0/1 causes the text to fade in and fade out. - * 2 causes the text to flash[?]. - * @param fxTime Duration of chosen effect (may not apply to all effects). - * @param fadeIn Number of seconds to spend fading in. - * @param fadeOut Number of seconds to spend fading out. - */ -native void SetHudTextParamsEx(float x, float y, float holdTime, int color1[4], - int color2[4]={255,255,255,0}, int effect = 0, float fxTime=6.0, + * This is the same as SetHudTextParams(), except it lets you set the alternate + * color for when effects require it. + * + * @param x x coordinate, from 0 to 1. -1.0 is the center. + * @param y y coordinate, from 0 to 1. -1.0 is the center. + * @param holdTime Number of seconds to hold the text. + * @param color1 First color set, array values being [red, green, blue, alpha] + * @param color2 Second color set, array values being [red, green, blue, alpha] + * @param effect 0/1 causes the text to fade in and fade out. + * 2 causes the text to flash[?]. + * @param fxTime Duration of chosen effect (may not apply to all effects). + * @param fadeIn Number of seconds to spend fading in. + * @param fadeOut Number of seconds to spend fading out. + */ +native void SetHudTextParamsEx(float x, float y, float holdTime, int color1[4], + int color2[4]={255,255,255,0}, int effect = 0, float fxTime=6.0, float fadeIn=0.1, float fadeOut=0.2); /** - * Shows a synchronized HUD message to a client. + * Shows a synchronized HUD message to a client. * * As of this writing, only TF, HL2MP, and SourceForts support HUD Text. * - * @param client Client index to send the message to. - * @param sync Synchronization object. - * @param message Message text or formatting rules. - * @param ... Message formatting parameters. - * @return -1 on failure, anything else on success. - * This function fails if the mod does not support it. - * @error Client not in-game, or sync object not valid. + * @param client Client index to send the message to. + * @param sync Synchronization object. + * @param message Message text or formatting rules. + * @param ... Message formatting parameters. + * @return -1 on failure, anything else on success. + * This function fails if the mod does not support it. + * @error Client not in-game, or sync object not valid. */ native int ShowSyncHudText(int client, Handle sync, const char[] message, any ...); /** - * Clears the text on a synchronized HUD channel. + * Clears the text on a synchronized HUD channel. * - * This is not the same as sending "" because it guarantees that it won't - * overwrite text on another channel. For example, consider the scenario: + * This is not the same as sending "" because it guarantees that it won't + * overwrite text on another channel. For example, consider the scenario: * * 1. Your synchronized message goes to channel 3. * 2. Someone else's non-synchronized message goes to channel 3. * - * If you were to simply send "" on your synchronized message, + * If you were to simply send "" on your synchronized message, * then someone else's text could be overwritten. * - * @param client Client index to send the message to. - * @param sync Synchronization object. - * @error Client not in-game, or sync object not valid. + * @param client Client index to send the message to. + * @param sync Synchronization object. + * @error Client not in-game, or sync object not valid. */ native void ClearSyncHud(int client, Handle sync); @@ -584,30 +587,30 @@ native void ClearSyncHud(int client, Handle sync); * Shows a HUD message to a client on the given channel. * * As of this writing, only TF, HL2MP, and SourceForts support HUD Text. - * - * @param client Client index to send the message to. - * @param channel A channel number. - * If -1, then a channel will automatically be selected - * based on the least-recently-used channel. If the - * channel is any other number, it will be modulo'd with - * the channel count to get a final channel number. - * @param message Message text or formatting rules. - * @param ... Message formatting parameters. - * @return -1 on failure (lack of mod support). - * Any other return value is the channel number that was - * used to render the text. + * + * @param client Client index to send the message to. + * @param channel A channel number. + * If -1, then a channel will automatically be selected + * based on the least-recently-used channel. If the + * channel is any other number, it will be modulo'd with + * the channel count to get a final channel number. + * @param message Message text or formatting rules. + * @param ... Message formatting parameters. + * @return -1 on failure (lack of mod support). + * Any other return value is the channel number that was + * used to render the text. */ native int ShowHudText(int client, int channel, const char[] message, any ...); /** * Shows a MOTD panel to a specific client. * - * @param client Client index. - * @param title Title of the panel (printed on the top border of the window). - * @param msg Contents of the panel, it can be treated as an url, filename or plain text - * depending on the type parameter (WARNING: msg has to be 192 bytes maximum!) - * @param type Determines the way to treat the message body of the panel. - * @error If the client is not connected an error will be thrown. + * @param client Client index. + * @param title Title of the panel (printed on the top border of the window). + * @param msg Contents of the panel, it can be treated as an url, filename or plain text + * depending on the type parameter (WARNING: msg has to be 192 bytes maximum!) + * @param type Determines the way to treat the message body of the panel. + * @error If the client is not connected an error will be thrown. */ stock void ShowMOTDPanel(int client, const char[] title, const char[] msg, int type=MOTDPANEL_TYPE_INDEX) { @@ -625,10 +628,10 @@ stock void ShowMOTDPanel(int client, const char[] title, const char[] msg, int t /** * Displays a panel asking the client to connect to a specified IP. * - * @param client Client index. - * @param time Duration to hold the panel on the client's screen. - * @param ip Destination IP. - * @param password Password to connect to the destination IP. The client will be able to see this. + * @param client Client index. + * @param time Duration to hold the panel on the client's screen. + * @param ip Destination IP. + * @param password Password to connect to the destination IP. The client will be able to see this. */ stock void DisplayAskConnectBox(int client, float time, const char[] ip, const char[] password = "") { @@ -645,42 +648,41 @@ stock void DisplayAskConnectBox(int client, float time, const char[] ip, const c /** * Converts an entity index into a serial encoded entity reference. * - * @param entity Entity index. - * @return Entity reference. + * @param entity Entity index. + * @return Entity reference. */ native int EntIndexToEntRef(int entity); /** * Retrieves the entity index from a reference. * - * @param ref Entity reference. - * @return Entity index. + * @param ref Entity reference. + * @return Entity index. */ native int EntRefToEntIndex(int ref); /** * Converts a reference into a backwards compatible version. * - * @param ref Entity reference. - * @return Bcompat reference. + * @param ref Entity reference. + * @return Bcompat reference. */ native int MakeCompatEntRef(int ref); - enum ClientRangeType { RangeType_Visibility = 0, - RangeType_Audibility, + RangeType_Audibility } /** * Find clients that are potentially in range of a position. * - * @param origin Coordinates from which to test range. - * @param rangeType Range type to use for filtering clients. - * @param clients Array to which found client indexes will be written. - * @param size Maximum size of clients array. - * @return Number of client indexes written to clients array. + * @param origin Coordinates from which to test range. + * @param rangeType Range type to use for filtering clients. + * @param clients Array to which found client indexes will be written. + * @param size Maximum size of clients array. + * @return Number of client indexes written to clients array. */ native int GetClientsInRange(float origin[3], ClientRangeType rangeType, int[] clients, int size); @@ -690,17 +692,17 @@ native int GetClientsInRange(float origin[3], ClientRangeType rangeType, int[] c * Note: If called before server is connected to Steam, auth id * will be invalid ([I:0:1], 1, etc.) * - * @param authType Auth id type and format to use. - * (Only AuthId_Steam3 and AuthId_SteamID64 are supported) - * @param auth Buffer to store the server's auth id. - * @param maxlen Maximum length of string buffer (includes NULL terminator). - * @error Invalid AuthIdType given. + * @param authType Auth id type and format to use. + * (Only AuthId_Steam3 and AuthId_SteamID64 are supported) + * @param auth Buffer to store the server's auth id. + * @param maxlen Maximum length of string buffer (includes NULL terminator). + * @error Invalid AuthIdType given. */ native void GetServerAuthId(AuthIdType authType, char[] auth, int maxlen); /** * Returns the server's Steam account ID. * - * @return Steam account ID or 0 if not available. + * @return Steam account ID or 0 if not available. */ native int GetServerSteamAccountId(); diff --git a/addons/sourcemod/scripting/include/handles.inc b/addons/sourcemod/scripting/include/handles.inc index 57763b8..a6f7ebe 100644 --- a/addons/sourcemod/scripting/include/handles.inc +++ b/addons/sourcemod/scripting/include/handles.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -40,19 +40,19 @@ */ enum Handle // Tag disables introducing "Handle" as a symbol. { - INVALID_HANDLE = 0, + INVALID_HANDLE = 0 }; /** - * Closes a Handle. If the handle has multiple copies open, + * Closes a Handle. If the handle has multiple copies open, * it is not destroyed unless all copies are closed. - * + * * @note Closing a Handle has a different meaning for each Handle type. Make * sure you read the documentation on whatever provided the Handle. * - * @param hndl Handle to close. - * @error Invalid handles will cause a run time error. + * @param hndl Handle to close. + * @error Invalid handles will cause a run time error. */ native void CloseHandle(Handle hndl); @@ -60,38 +60,39 @@ native void CloseHandle(Handle hndl); * Clones a Handle. When passing handles in between plugins, caching handles * can result in accidental invalidation when one plugin releases the Handle, or is its owner * is unloaded from memory. To prevent this, the Handle may be "cloned" with a new owner. - * + * * @note Usually, you will be cloning Handles for other plugins. This means that if you clone - * the Handle without specifying the new owner, it will assume the identity of your original calling - * plugin, which is not very useful. You should either specify that the receiving plugin should - * clone the handle on its own, or you should explicitly clone the Handle using the receiving plugin's - * identity Handle. + * the Handle without specifying the new owner, it will assume the identity of your original + * calling plugin, which is not very useful. You should either specify that the receiving + * plugin should clone the handle on its own, or you should explicitly clone the Handle + * using the receiving plugin's identity Handle. * - * @param hndl Handle to clone/duplicate. - * @param plugin Optional Handle to another plugin to mark as the new owner. - * If no owner is passed, the owner becomes the calling plugin. - * @return Handle on success, INVALID_HANDLE if not cloneable. - * @error Invalid handles will cause a run time error. + * @param hndl Handle to clone/duplicate. + * @param plugin Optional Handle to another plugin to mark as the new owner. + * If no owner is passed, the owner becomes the calling plugin. + * @return Handle on success, INVALID_HANDLE if not cloneable. + * @error Invalid handles will cause a run time error. */ native Handle CloneHandle(Handle hndl, Handle plugin=INVALID_HANDLE); using __intrinsics__.Handle; /** - * Do not use this function. Returns if a Handle and its contents - * are readable, whereas INVALID_HANDLE only checks for the absence + * Do not use this function. Returns if a Handle and its contents + * are readable, whereas INVALID_HANDLE only checks for the absence * of a Handle. * - * This function is intended only for tests where the validity of a - * Handle can absolutely not be known. + * This function is intended only for tests where the validity of a + * Handle can absolutely not be known. * - * Do not use this to check the return values of functions, or to - * check if timers should be closed (except in very rare cases). - * This function is for very specific usage and using it for general + * Do not use this to check the return values of functions, or to + * check if timers should be closed (except in very rare cases). + * This function is for very specific usage and using it for general * purpose routines can and will hide very subtle bugs. * - * @param hndl Handle to test for validity. - * @return True if handle is valid, false otherwise. + * @param hndl Handle to test for validity. + * @return True if handle is valid, false otherwise. + * @deprecated Do not use this function. */ #pragma deprecated Do not use this function. native bool IsValidHandle(Handle hndl); diff --git a/addons/sourcemod/scripting/include/helpers.inc b/addons/sourcemod/scripting/include/helpers.inc index 34614f1..47ade5b 100644 --- a/addons/sourcemod/scripting/include/helpers.inc +++ b/addons/sourcemod/scripting/include/helpers.inc @@ -36,38 +36,26 @@ #define _helpers_included /** - * Formats a user's info as log text. This is usually not needed because - * %L can be used to auto-format client information into a string. + * This function is deprecated. Use the %L format specifier instead. + * + * Formats a user's info as log text. * - * @param client Client index. - * @param buffer Buffer for text. - * @param maxlength Maximum length of text. + * @param client Client index. + * @param buffer Buffer for text. + * @param maxlength Maximum length of text. + * @deprecated Use the %L format specifier instead. */ +#pragma deprecated Use the %L format specifier instead. stock void FormatUserLogText(int client, char[] buffer, int maxlength) { - char auth[32]; - char name[MAX_NAME_LENGTH]; - - int userid = GetClientUserId(client); - if (!GetClientAuthString(client, auth, sizeof(auth))) - { - strcopy(auth, sizeof(auth), "UNKNOWN"); - } - if (!GetClientName(client, name, sizeof(name))) - { - strcopy(name, sizeof(name), "UNKNOWN"); - } - - /** Currently, no team stuff ... */ - - Format(buffer, maxlength, "\"%s<%d><%s><>\"", name, userid, auth); + FormatEx(buffer, maxlength, "\"%L\"", client); } /** * Returns plugin handle from plugin filename. * - * @param filename Filename of the plugin to search for. - * @return Handle to plugin if found, INVALID_HANDLE otherwise. + * @param filename Filename of the plugin to search for. + * @return Handle to plugin if found, INVALID_HANDLE otherwise. */ stock Handle FindPluginByFile(const char[] filename) { @@ -94,7 +82,7 @@ stock Handle FindPluginByFile(const char[] filename) } /** - * @deprecated Use FindTarget() or ProcessTargetString(). + * @deprecated Use FindTarget() or ProcessTargetString(). */ #pragma deprecated Use FindTarget() or ProcessTargetString() stock int SearchForClients(const char[] pattern, int[] clients, int maxClients) @@ -102,24 +90,34 @@ stock int SearchForClients(const char[] pattern, int[] clients, int maxClients) int total = 0; if (maxClients == 0) + { return 0; + } - if (pattern[0] == '#') { + if (pattern[0] == '#') + { int input = StringToInt(pattern[1]); if (!input) { char name[MAX_NAME_LENGTH]; - for (int i=1; i<=MaxClients; i++) { + for (int i=1; i<=MaxClients; i++) + { if (!IsClientInGame(i)) + { continue; + } GetClientName(i, name, sizeof(name)); - if (strcmp(name, pattern, false) == 0) { + if (strcmp(name, pattern, false) == 0) + { clients[0] = i; return 1; } } - } else { + } + else + { int client = GetClientOfUserId(input); - if (client) { + if (client) + { clients[0] = client; return 1; } @@ -130,12 +128,18 @@ stock int SearchForClients(const char[] pattern, int[] clients, int maxClients) for (int i=1; i<=MaxClients; i++) { if (!IsClientInGame(i)) + { continue; + } + GetClientName(i, name, sizeof(name)); - if (StrContains(name, pattern, false) != -1) { + if (StrContains(name, pattern, false) != -1) + { clients[total++] = i; if (total >= maxClients) + { break; + } } } @@ -146,11 +150,15 @@ stock int SearchForClients(const char[] pattern, int[] clients, int maxClients) * Wraps ProcessTargetString() and handles producing error messages for * bad targets. * - * @param client Client who issued command - * @param target Client's target argument - * @param nobots Optional. Set to true if bots should NOT be targetted - * @param immunity Optional. Set to false to ignore target immunity. - * @return Index of target client, or -1 on error. + * Note that you should use LoadTranslations("common.phrases") in OnPluginStart(). + * "common.phrases" contains all of the translatable phrases that FindTarget() will + * reply with in the event a target is not found (error). + * + * @param client Client who issued command + * @param target Client's target argument + * @param nobots Optional. Set to true if bots should NOT be targetted + * @param immunity Optional. Set to false to ignore target immunity. + * @return Index of target client, or -1 on error. */ stock int FindTarget(int client, const char[] target, bool nobots = false, bool immunity = true) { @@ -163,6 +171,7 @@ stock int FindTarget(int client, const char[] target, bool nobots = false, bool { flags |= COMMAND_FILTER_NO_BOTS; } + if (!immunity) { flags |= COMMAND_FILTER_NO_IMMUNITY; @@ -180,11 +189,9 @@ stock int FindTarget(int client, const char[] target, bool nobots = false, bool { return target_list[0]; } - else - { - ReplyToTargetError(client, target_count); - return -1; - } + + ReplyToTargetError(client, target_count); + return -1; } /** @@ -197,83 +204,84 @@ stock int FindTarget(int client, const char[] target, bool nobots = false, bool * parameter is used to store a timestamp of the file. If specified, the file will only be reloaded if it * has changed. * - * @param array Valid array handle, should be created with CreateArray(33) or larger. - * @param fileTime Variable containing the "last changed" time of the file. Used to avoid needless reloading. - * @param fileCvar CVAR set to the file to be loaded. Optional. - * @return Number of maps loaded or 0 if in error. + * @param array Valid array handle, should be created with CreateArray(33) or larger. + * @param fileTime Variable containing the "last changed" time of the file. Used to avoid needless reloading. + * @param fileCvar CVAR set to the file to be loaded. Optional. + * @return Number of maps loaded or 0 if in error. + * @deprecated Use ReadMapList() instead. */ #pragma deprecated Use ReadMapList() instead. - stock int LoadMaps(Handle array, int &fileTime = 0, Handle fileCvar = INVALID_HANDLE) - { - char mapPath[256], mapFile[64]; - bool fileFound = false; - - if (fileCvar != INVALID_HANDLE) - { - GetConVarString(fileCvar, mapFile, 64); - BuildPath(Path_SM, mapPath, sizeof(mapPath), mapFile); - fileFound = FileExists(mapPath); - } +stock int LoadMaps(Handle array, int &fileTime = 0, Handle fileCvar = INVALID_HANDLE) +{ + char mapPath[256], mapFile[64]; + bool fileFound = false; + + if (fileCvar != INVALID_HANDLE) + { + GetConVarString(fileCvar, mapFile, 64); + BuildPath(Path_SM, mapPath, sizeof(mapPath), mapFile); + fileFound = FileExists(mapPath); + } - if (!fileFound) - { - Handle mapCycleFile = FindConVar("mapcyclefile"); - GetConVarString(mapCycleFile, mapPath, sizeof(mapPath)); - fileFound = FileExists(mapPath); - } - - if (!fileFound) - { - LogError("Failed to find a file to load maps from. No maps loaded."); - ClearArray(array); - - return 0; - } + if (!fileFound) + { + Handle mapCycleFile = FindConVar("mapcyclefile"); + GetConVarString(mapCycleFile, mapPath, sizeof(mapPath)); + fileFound = FileExists(mapPath); + } + + if (!fileFound) + { + LogError("Failed to find a file to load maps from. No maps loaded."); + ClearArray(array); + + return 0; + } - // If the file hasn't changed, there's no reason to reload - // all of the maps. - int newTime = GetFileTime(mapPath, FileTime_LastChange); - if (fileTime == newTime) - { - return GetArraySize(array); - } - - fileTime = newTime; - - ClearArray(array); + // If the file hasn't changed, there's no reason to reload + // all of the maps. + int newTime = GetFileTime(mapPath, FileTime_LastChange); + if (fileTime == newTime) + { + return GetArraySize(array); + } + + fileTime = newTime; + + ClearArray(array); - File file = OpenFile(mapPath, "rt"); - if (!file) { - LogError("Could not open file: %s", mapPath); - return 0; - } + File file = OpenFile(mapPath, "rt"); + if (!file) { + LogError("Could not open file: %s", mapPath); + return 0; + } LogMessage("Loading maps from file: %s", mapPath); int len; - char buffer[64]; - while (!file.EndOfFile() && file.ReadLine(buffer, sizeof(buffer))) - { - TrimString(buffer); + char buffer[64]; + while (!file.EndOfFile() && file.ReadLine(buffer, sizeof(buffer))) + { + TrimString(buffer); - if ((len = StrContains(buffer, ".bsp", false)) != -1) - { - buffer[len] = '\0'; - } + if ((len = StrContains(buffer, ".bsp", false)) != -1) + { + buffer[len] = '\0'; + } - if (buffer[0] == '\0' || !IsValidConVarChar(buffer[0]) || !IsMapValid(buffer)) - { - continue; - } - - if (FindStringInArray(array, buffer) != -1) - { - continue; - } + if (buffer[0] == '\0' || !IsValidConVarChar(buffer[0]) || !IsMapValid(buffer)) + { + continue; + } + + if (FindStringInArray(array, buffer) != -1) + { + continue; + } - PushArrayString(array, buffer); - } + PushArrayString(array, buffer); + } file.Close(); - return GetArraySize(array); + return GetArraySize(array); } diff --git a/addons/sourcemod/scripting/include/keyvalues.inc b/addons/sourcemod/scripting/include/keyvalues.inc index d8fb4c8..7318507 100644 --- a/addons/sourcemod/scripting/include/keyvalues.inc +++ b/addons/sourcemod/scripting/include/keyvalues.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -29,7 +29,7 @@ * * Version: $Id$ */ - + #if defined _keyvalues_included #endinput #endif @@ -40,23 +40,23 @@ */ enum KvDataTypes { - KvData_None = 0, /**< Type could not be identified, or no type */ - KvData_String, /**< String value */ - KvData_Int, /**< Integer value */ - KvData_Float, /**< Floating point value */ - KvData_Ptr, /**< Pointer value (sometimes called "long") */ - KvData_WString, /**< Wide string value */ - KvData_Color, /**< Color value */ - KvData_UInt64, /**< Large integer value */ + KvData_None = 0, /**< Type could not be identified, or no type */ + KvData_String, /**< String value */ + KvData_Int, /**< Integer value */ + KvData_Float, /**< Floating point value */ + KvData_Ptr, /**< Pointer value (sometimes called "long") */ + KvData_WString, /**< Wide string value */ + KvData_Color, /**< Color value */ + KvData_UInt64, /**< Large integer value */ /* --- */ - KvData_NUMTYPES, + KvData_NUMTYPES }; methodmap KeyValues < Handle { // Creates a new KeyValues structure. The Handle must be closed with // CloseHandle() or delete. - // + // // @param name Name of the root section. // @param firstKey If non-empty, specifies the first key value. // @param firstValue If firstKey is non-empty, specifies the first key's value. @@ -71,7 +71,7 @@ methodmap KeyValues < Handle // Exports a KeyValues tree to a string. The string is dumped from the current position. // // @param buffer Buffer to write to. - // @param maxlength Max length of buffer. + // @param maxlength Max length of buffer. // @return Number of bytes that can be written to buffer. public native int ExportToString(char[] buffer, int maxlength); @@ -89,7 +89,7 @@ methodmap KeyValues < Handle // Converts a given string to a KeyValues tree. The string is read into // the current postion of the tree. - // + // // @param buffer String buffer to load into the KeyValues. // @param resourceName The resource name of the KeyValues, used for error tracking purposes. // @return True on success, false otherwise. @@ -98,7 +98,7 @@ methodmap KeyValues < Handle // Imports subkeys in the given KeyValues, at the current position in that // KeyValues, into the current position in this KeyValues. Note that this // copies keys; it does not embed a reference to them. - // + // // @param other Origin KeyValues Handle. public native void Import(KeyValues other); @@ -145,13 +145,13 @@ methodmap KeyValues < Handle } // Sets a vector value of a KeyValues key. - // + // // @param key Name of the key, or NULL_STRING. // @param vec Vector value. public native void SetVector(const char[] key, const float vec[3]); // Retrieves a string value from a KeyValues key. - // + // // @param key Name of the key, or NULL_STRING. // @param value Buffer to store key value in. // @param maxlength Maximum length of the value buffer. @@ -159,7 +159,7 @@ methodmap KeyValues < Handle public native void GetString(const char[] key, char[] value, int maxlength, const char[] defvalue=""); // Retrieves an integer value from a KeyValues key. - // + // // @param key Name of the key, or NULL_STRING. // @param defvalue Optional default value to use if the key is not found. // @return Integer value of the key. @@ -176,9 +176,9 @@ methodmap KeyValues < Handle // // @param key Name of the key, or NULL_STRING. // @param r Red value, set by reference. - // @param g Green value, set by reference. - // @param b Blue value, set by reference. - // @param a Alpha value, set by reference. + // @param g Green value, set by reference. + // @param b Blue value, set by reference. + // @param a Alpha value, set by reference. public native void GetColor(const char[] key, int &r, int &g, int &b, int &a); // Retrieves a set of color values from a KeyValues key. @@ -231,13 +231,13 @@ methodmap KeyValues < Handle // Sets the current position in the KeyValues tree to the next sub key. // This native does NOT add to the internal traversal stack, and thus // GoBack() is not needed for each successive call to this function. - // + // // @param keyOnly If false, non-keys will be traversed (values). // @return True on success, false if there was no next sub key. public native bool GotoNextKey(bool keyOnly=true); // Saves the current position in the traversal stack onto the traversal - // stack. This can be useful if you wish to use KvGotoNextKey() and + // stack. This can be useful if you wish to use KvGotoNextKey() and // have the previous key saved for backwards traversal. // // @param kv KeyValues Handle. @@ -260,9 +260,9 @@ methodmap KeyValues < Handle // Removes the current sub-key and attempts to set the position // to the sub-key after the removed one. If no such sub-key exists, // the position will be the parent key in the traversal stack. - // Given the sub-key having position "N" in the traversal stack, the + // Given the sub-key having position "N" in the traversal stack, the // removal will always take place from position "N-1." - // + // // @param kv KeyValues Handle. // @return 1 if removal succeeded and there was another key. // 0 if the current node was not contained in the @@ -271,7 +271,7 @@ methodmap KeyValues < Handle // thus the state is as if KvGoBack() was called. public native int DeleteThis(); - // Sets the position back to the top node, emptying the entire node + // Sets the position back to the top node, emptying the entire node // traversal history. This can be used instead of looping KvGoBack() // if recursive iteration is not important. // @@ -279,14 +279,14 @@ methodmap KeyValues < Handle public native void Rewind(); // Retrieves the current section name. - // + // // @param section Buffer to store the section name. // @param maxlength Maximum length of the name buffer. // @return True on success, false on failure. public native bool GetSectionName(char[] section, int maxlength); // Sets the current section name. - // + // // @param section Section name. public native void SetSectionName(const char[] section); @@ -299,14 +299,14 @@ methodmap KeyValues < Handle // Sets whether or not the KeyValues parser will read escape sequences. // For example, \n would be read as a literal newline. This defaults // to false for new KeyValues structures. - // + // // @param useEscapes Whether or not to read escape sequences. public native void SetEscapeSequences(bool useEscapes); // Returns the position in the jump stack; I.e. the number of calls // required for KvGoBack to return to the root node. If at the root node, // 0 is returned. - // + // // @return Number of non-root nodes in the jump stack. public native int NodesInStack(); @@ -319,14 +319,14 @@ methodmap KeyValues < Handle public native bool FindKeyById(int id, char[] name, int maxlength); // Finds a KeyValues id inside a KeyValues tree. - // + // // @param key Key name. // @param id Id of the found KeyValue. // @return True on success, false if key not found. public native bool GetNameSymbol(const char[] key, int &id); // Retrieves the current section id. - // + // // @param kv KeyValues Handle. // @param id Id of the current section. // @return True on success, false on failure. @@ -336,161 +336,161 @@ methodmap KeyValues < Handle /** * Creates a new KeyValues structure. The Handle must always be closed. * - * @param name Name of the root section. - * @param firstKey If non-empty, specifies the first key value. - * @param firstValue If firstKey is non-empty, specifies the first key's value. - * @return A Handle to a new KeyValues structure. + * @param name Name of the root section. + * @param firstKey If non-empty, specifies the first key value. + * @param firstValue If firstKey is non-empty, specifies the first key's value. + * @return A Handle to a new KeyValues structure. */ native KeyValues CreateKeyValues(const char[] name, const char[] firstKey="", const char[] firstValue=""); -/** +/** * Sets a string value of a KeyValues key. * - * @param kv KeyValues Handle. - * @param key Name of the key, or NULL_STRING. - * @param value String value. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param key Name of the key, or NULL_STRING. + * @param value String value. + * @error Invalid Handle. */ native void KvSetString(Handle kv, const char[] key, const char[] value); -/** +/** * Sets an integer value of a KeyValues key. * - * @param kv KeyValues Handle. - * @param key Name of the key, or NULL_STRING. - * @param value Value number. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param key Name of the key, or NULL_STRING. + * @param value Value number. + * @error Invalid Handle. */ native void KvSetNum(Handle kv, const char[] key, int value); -/** +/** * Sets a large integer value of a KeyValues key. * - * @param kv KeyValues Handle. - * @param key Name of the key, or NULL_STRING. - * @param value Large integer value (0=High bits, 1=Low bits) - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param key Name of the key, or NULL_STRING. + * @param value Large integer value (0=High bits, 1=Low bits) + * @error Invalid Handle. */ native void KvSetUInt64(Handle kv, const char[] key, const int value[2]); -/** +/** * Sets a floating point value of a KeyValues key. * - * @param kv KeyValues Handle. - * @param key Name of the key, or NULL_STRING. - * @param value Floating point value. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param key Name of the key, or NULL_STRING. + * @param value Floating point value. + * @error Invalid Handle. */ native void KvSetFloat(Handle kv, const char[] key, float value); -/** +/** * Sets a set of color values of a KeyValues key. * - * @param kv KeyValues Handle. - * @param key Name of the key, or NULL_STRING. - * @param r Red value. - * @param g Green value. - * @param b Blue value. - * @param a Alpha value. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param key Name of the key, or NULL_STRING. + * @param r Red value. + * @param g Green value. + * @param b Blue value. + * @param a Alpha value. + * @error Invalid Handle. */ native void KvSetColor(Handle kv, const char[] key, int r, int g, int b, int a=0); -/** +/** * Sets a vector value of a KeyValues key. * - * @param kv KeyValues Handle. - * @param key Name of the key, or NULL_STRING. - * @param vec Vector value. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param key Name of the key, or NULL_STRING. + * @param vec Vector value. + * @error Invalid Handle. */ native void KvSetVector(Handle kv, const char[] key, const float vec[3]); -/** +/** * Retrieves a string value from a KeyValues key. * - * @param kv KeyValues Handle. - * @param key Name of the key, or NULL_STRING. - * @param value Buffer to store key value in. - * @param maxlength Maximum length of the value buffer. - * @param defvalue Optional default value to use if the key is not found. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param key Name of the key, or NULL_STRING. + * @param value Buffer to store key value in. + * @param maxlength Maximum length of the value buffer. + * @param defvalue Optional default value to use if the key is not found. + * @error Invalid Handle. */ native void KvGetString(Handle kv, const char[] key, char[] value, int maxlength, const char[] defvalue=""); -/** +/** * Retrieves an integer value from a KeyValues key. * - * @param kv KeyValues Handle. - * @param key Name of the key, or NULL_STRING. - * @param defvalue Optional default value to use if the key is not found. - * @return Integer value of the key. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param key Name of the key, or NULL_STRING. + * @param defvalue Optional default value to use if the key is not found. + * @return Integer value of the key. + * @error Invalid Handle. */ native int KvGetNum(Handle kv, const char[] key, int defvalue=0); -/** +/** * Retrieves a floating point value from a KeyValues key. * - * @param kv KeyValues Handle. - * @param key Name of the key, or NULL_STRING. - * @param defvalue Optional default value to use if the key is not found. - * @return Floating point value of the key. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param key Name of the key, or NULL_STRING. + * @param defvalue Optional default value to use if the key is not found. + * @return Floating point value of the key. + * @error Invalid Handle. */ native float KvGetFloat(Handle kv, const char[] key, float defvalue=0.0); -/** +/** * Retrieves a set of color values from a KeyValues key. * - * @param kv KeyValues Handle. - * @param key Name of the key, or NULL_STRING. - * @param r Red value, set by reference. - * @param g Green value, set by reference. - * @param b Blue value, set by reference. - * @param a Alpha value, set by reference. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param key Name of the key, or NULL_STRING. + * @param r Red value, set by reference. + * @param g Green value, set by reference. + * @param b Blue value, set by reference. + * @param a Alpha value, set by reference. + * @error Invalid Handle. */ native void KvGetColor(Handle kv, const char[] key, int &r, int &g, int &b, int &a); -/** +/** * Retrieves a large integer value from a KeyValues key. * - * @param kv KeyValues Handle. - * @param key Name of the key, or NULL_STRING. - * @param value Array to represent the large integer. - * @param defvalue Optional default value to use if the key is not found. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param key Name of the key, or NULL_STRING. + * @param value Array to represent the large integer. + * @param defvalue Optional default value to use if the key is not found. + * @error Invalid Handle. */ native void KvGetUInt64(Handle kv, const char[] key, int value[2], int defvalue[2]={0,0}); -/** +/** * Retrieves a vector value from a KeyValues key. * - * @param kv KeyValues Handle. - * @param key Name of the key, or NULL_STRING. - * @param vec Destination vector to store the value in. - * @param defvalue Optional default value to use if the key is not found. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param key Name of the key, or NULL_STRING. + * @param vec Destination vector to store the value in. + * @param defvalue Optional default value to use if the key is not found. + * @error Invalid Handle. */ native void KvGetVector(Handle kv, const char[] key, float vec[3], const float defvalue[3]={0.0, 0.0, 0.0}); /** * Sets the current position in the KeyValues tree to the given key. * - * @param kv KeyValues Handle. - * @param key Name of the key. - * @param create If true, and the key does not exist, it will be created. - * @return True if the key exists, false if it does not and was not created. + * @param kv KeyValues Handle. + * @param key Name of the key. + * @param create If true, and the key does not exist, it will be created. + * @return True if the key exists, false if it does not and was not created. */ native bool KvJumpToKey(Handle kv, const char[] key, bool create=false); /** * Sets the current position in the KeyValues tree to the given key. * - * @param kv KeyValues Handle. - * @param id KeyValues id. - * @return True if the key exists, false if it does not. + * @param kv KeyValues Handle. + * @param id KeyValues id. + * @return True if the key exists, false if it does not. */ native bool KvJumpToKeySymbol(Handle kv, int id); @@ -498,10 +498,10 @@ native bool KvJumpToKeySymbol(Handle kv, int id); * Sets the current position in the KeyValues tree to the first sub key. * This native adds to the internal traversal stack. * - * @param kv KeyValues Handle. - * @param keyOnly If false, non-keys will be traversed (values). - * @return True on success, false if there was no first sub key. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param keyOnly If false, non-keys will be traversed (values). + * @return True on success, false if there was no first sub key. + * @error Invalid Handle. */ native bool KvGotoFirstSubKey(Handle kv, bool keyOnly=true); @@ -510,30 +510,30 @@ native bool KvGotoFirstSubKey(Handle kv, bool keyOnly=true); * This native does NOT add to the internal traversal stack, and thus * KvGoBack() is not needed for each successive call to this function. * - * @param kv KeyValues Handle. - * @param keyOnly If false, non-keys will be traversed (values). - * @return True on success, false if there was no next sub key. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param keyOnly If false, non-keys will be traversed (values). + * @return True on success, false if there was no next sub key. + * @error Invalid Handle. */ native bool KvGotoNextKey(Handle kv, bool keyOnly=true); /** * Saves the current position in the traversal stack onto the traversal - * stack. This can be useful if you wish to use KvGotoNextKey() and + * stack. This can be useful if you wish to use KvGotoNextKey() and * have the previous key saved for backwards traversal. * - * @param kv KeyValues Handle. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @error Invalid Handle. */ native void KvSavePosition(Handle kv); /** * Removes the given key from the current position. * - * @param kv KeyValues Handle. - * @param key Name of the key. - * @return True on success, false if key did not exist. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param key Name of the key. + * @return True on success, false if key did not exist. + * @error Invalid Handle. */ native bool KvDeleteKey(Handle kv, const char[] key); @@ -541,16 +541,16 @@ native bool KvDeleteKey(Handle kv, const char[] key); * Removes the current sub-key and attempts to set the position * to the sub-key after the removed one. If no such sub-key exists, * the position will be the parent key in the traversal stack. - * Given the sub-key having position "N" in the traversal stack, the + * Given the sub-key having position "N" in the traversal stack, the * removal will always take place from position "N-1." * - * @param kv KeyValues Handle. - * @return 1 if removal succeeded and there was another key. - * 0 if the current node was not contained in the - * previous node, or no previous node exists. - * -1 if removal succeeded and there were no more keys, - * thus the state is as if KvGoBack() was called. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @return 1 if removal succeeded and there was another key. + * 0 if the current node was not contained in the + * previous node, or no previous node exists. + * -1 if removal succeeded and there were no more keys, + * thus the state is as if KvGoBack() was called. + * @error Invalid Handle. */ native int KvDeleteThis(Handle kv); @@ -560,49 +560,49 @@ native int KvDeleteThis(Handle kv); * once for each successful Jump call, in order to return to the top node. * This function pops one node off the internal traversal stack. * - * @param kv KeyValues Handle. - * @return True on success, false if there is no higher node. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @return True on success, false if there is no higher node. + * @error Invalid Handle. */ native bool KvGoBack(Handle kv); /** - * Sets the position back to the top node, emptying the entire node + * Sets the position back to the top node, emptying the entire node * traversal history. This can be used instead of looping KvGoBack() * if recursive iteration is not important. * - * @param kv KeyValues Handle. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @error Invalid Handle. */ native void KvRewind(Handle kv); /** * Retrieves the current section name. - * - * @param kv KeyValues Handle. - * @param section Buffer to store the section name. - * @param maxlength Maximum length of the name buffer. - * @return True on success, false on failure. - * @error Invalid Handle. + * + * @param kv KeyValues Handle. + * @param section Buffer to store the section name. + * @param maxlength Maximum length of the name buffer. + * @return True on success, false on failure. + * @error Invalid Handle. */ native bool KvGetSectionName(Handle kv, char[] section, int maxlength); /** * Sets the current section name. - * - * @param kv KeyValues Handle. - * @param section Section name. - * @error Invalid Handle. + * + * @param kv KeyValues Handle. + * @param section Section name. + * @error Invalid Handle. */ native void KvSetSectionName(Handle kv, const char[] section); /** * Returns the data type at a key. * - * @param kv KeyValues Handle. - * @param key Key name. - * @return KvDataType value of the key. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param key Key name. + * @return KvDataType value of the key. + * @error Invalid Handle. */ native KvDataTypes KvGetDataType(Handle kv, const char[] key); @@ -610,10 +610,10 @@ native KvDataTypes KvGetDataType(Handle kv, const char[] key); * Converts a KeyValues tree to a file. The tree is dumped * from the current position. * - * @param kv KeyValues Handle. - * @param file File to dump write to. - * @return True on success, false otherwise. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param file File to dump write to. + * @return True on success, false otherwise. + * @error Invalid Handle. */ native bool KeyValuesToFile(Handle kv, const char[] file); @@ -621,10 +621,10 @@ native bool KeyValuesToFile(Handle kv, const char[] file); * Converts a file to a KeyValues tree. The file is read into * the current position of the tree. * - * @param kv KeyValues Handle. - * @param file File to read from. - * @return True on success, false otherwise. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param file File to read from. + * @return True on success, false otherwise. + * @error Invalid Handle. */ native bool FileToKeyValues(Handle kv, const char[] file); @@ -632,11 +632,11 @@ native bool FileToKeyValues(Handle kv, const char[] file); * Converts a given string to a KeyValues tree. The string is read into * the current postion of the tree. * - * @param kv KeyValues Handle. - * @param buffer String buffer to load into the KeyValues. - * @param resourceName The resource name of the KeyValues, used for error tracking purposes. - * @return True on success, false otherwise. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param buffer String buffer to load into the KeyValues. + * @param resourceName The resource name of the KeyValues, used for error tracking purposes. + * @return True on success, false otherwise. + * @error Invalid Handle. */ native bool StringToKeyValues(Handle kv, const char[] buffer, const char[] resourceName="StringToKeyValues"); @@ -645,9 +645,9 @@ native bool StringToKeyValues(Handle kv, const char[] buffer, const char[] resou * For example, \n would be read as a literal newline. This defaults * to false for new KeyValues structures. * - * @param kv KeyValues Handle. - * @param useEscapes Whether or not to read escape sequences. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param useEscapes Whether or not to read escape sequences. + * @error Invalid Handle. */ native void KvSetEscapeSequences(Handle kv, bool useEscapes); @@ -656,9 +656,9 @@ native void KvSetEscapeSequences(Handle kv, bool useEscapes); * required for KvGoBack to return to the root node. If at the root node, * 0 is returned. * - * @param kv KeyValues Handle. - * @return Number of non-root nodes in the jump stack. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @return Number of non-root nodes in the jump stack. + * @error Invalid Handle. */ native int KvNodesInStack(Handle kv); @@ -667,41 +667,41 @@ native int KvNodesInStack(Handle kv); * the destination KeyValues. * NOTE: All KeyValues are processed from the current location not the root one. * - * @param origin Origin KeyValues Handle. - * @param dest Destination KeyValues Handle. - * @error Invalid Handle. + * @param origin Origin KeyValues Handle. + * @param dest Destination KeyValues Handle. + * @error Invalid Handle. */ native void KvCopySubkeys(Handle origin, Handle dest); -/** +/** * Finds a KeyValues name by id. * - * @param kv KeyValues Handle. - * @param id KeyValues id. - * @param name Buffer to store the name. - * @param maxlength Maximum length of the value buffer. - * @return True on success, false if id not found. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param id KeyValues id. + * @param name Buffer to store the name. + * @param maxlength Maximum length of the value buffer. + * @return True on success, false if id not found. + * @error Invalid Handle. */ native bool KvFindKeyById(Handle kv, int id, char[] name, int maxlength); -/** +/** * Finds a KeyValues id inside a KeyValues tree. * - * @param kv KeyValues Handle. - * @param key Key name. - * @param id Id of the found KeyValue. - * @return True on success, false if key not found. - * @error Invalid Handle. + * @param kv KeyValues Handle. + * @param key Key name. + * @param id Id of the found KeyValue. + * @return True on success, false if key not found. + * @error Invalid Handle. */ native bool KvGetNameSymbol(Handle kv, const char[] key, int &id); /** * Retrieves the current section id. - * - * @param kv KeyValues Handle. - * @param id Id of the current section. - * @return True on success, false on failure. - * @error Invalid Handle. + * + * @param kv KeyValues Handle. + * @param id Id of the current section. + * @return True on success, false on failure. + * @error Invalid Handle. */ native bool KvGetSectionSymbol(Handle kv, int &id); diff --git a/addons/sourcemod/scripting/include/lang.inc b/addons/sourcemod/scripting/include/lang.inc index 76243c6..440b795 100644 --- a/addons/sourcemod/scripting/include/lang.inc +++ b/addons/sourcemod/scripting/include/lang.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -35,13 +35,13 @@ #endif #define _lang_included -#define LANG_SERVER 0 /**< Translate using the server's language */ +#define LANG_SERVER 0 /**< Translate using the server's language */ /** * Loads a translation file for the plugin calling this native. * If no extension is specified, .txt is assumed. * - * @param file Translation file. + * @param file Translation file. */ native void LoadTranslations(const char[] file); @@ -51,67 +51,67 @@ native void LoadTranslations(const char[] file); * indexes can be specified but the error will occur during translation, * not during this function call. * - * @param client Client index or LANG_SERVER. + * @param client Client index or LANG_SERVER. */ native void SetGlobalTransTarget(int client); /** * Retrieves the language number of a client. * - * @param client Client index. - * @return Language number client is using. - * @error Invalid client index or client not connected. + * @param client Client index. + * @return Language number client is using. + * @error Invalid client index or client not connected. */ native int GetClientLanguage(int client); /** * Retrieves the server's language. * - * @return Language number server is using. + * @return Language number server is using. */ native int GetServerLanguage(); /** * Returns the number of languages known in languages.cfg. * - * @return Language count. + * @return Language count. */ native int GetLanguageCount(); /** * Retrieves info about a given language number. * - * @param language Language number. - * @param code Language code buffer (2-3 characters usually). - * @param codeLen Maximum length of the language code buffer. - * @param name Language name buffer. - * @param nameLen Maximum length of the language name buffer. - * @error Invalid language number. + * @param language Language number. + * @param code Language code buffer (2-3 characters usually). + * @param codeLen Maximum length of the language code buffer. + * @param name Language name buffer. + * @param nameLen Maximum length of the language name buffer. + * @error Invalid language number. */ native void GetLanguageInfo(int language, char[] code="", int codeLen=0, char[] name="", int nameLen=0); /** * Sets the language number of a client. * - * @param client Client index. - * @param language Language number. - * @error Invalid client index or client not connected. + * @param client Client index. + * @param language Language number. + * @error Invalid client index or client not connected. */ native void SetClientLanguage(int client, int language); /** * Retrieves the language number from a language code. * - * @param code Language code (2-3 characters usually). - * @return Language number. -1 if not found. + * @param code Language code (2-3 characters usually). + * @return Language number. -1 if not found. */ native int GetLanguageByCode(const char[] code); /** * Retrieves the language number from a language name. * - * @param name Language name (case insensitive). - * @return Language number. -1 if not found. + * @param name Language name (case insensitive). + * @return Language number. -1 if not found. */ native int GetLanguageByName(const char[] name); @@ -119,16 +119,16 @@ native int GetLanguageByName(const char[] name); * Determines if the specified phrase exists within the plugin's * translation cache. * - * @param phrase Phrase to look for. - * @return True if phrase exists. + * @param phrase Phrase to look for. + * @return True if phrase exists. */ native bool TranslationPhraseExists(const char[] phrase); /** * Determines if there is a translation for the specified language. * - * @param phrase Phrase to check. - * @param language Language number. - * @return True if translation exists. + * @param phrase Phrase to check. + * @param language Language number. + * @return True if translation exists. */ native bool IsTranslatedForLanguage(const char[] phrase, int language); diff --git a/addons/sourcemod/scripting/include/logging.inc b/addons/sourcemod/scripting/include/logging.inc index 0fac733..2ab337c 100644 --- a/addons/sourcemod/scripting/include/logging.inc +++ b/addons/sourcemod/scripting/include/logging.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -29,77 +29,77 @@ * * Version: $Id$ */ - + #if defined _sm_logging_included #endinput #endif #define _sm_logging_included /** - * Logs a plugin message to the SourceMod logs. The log message will be + * Logs a plugin message to the SourceMod logs. The log message will be * prefixed by the plugin's logtag (filename). * - * @param format String format. - * @param ... Format arguments. + * @param format String format. + * @param ... Format arguments. */ native void LogMessage(const char[] format, any ...); /** - * Logs a message to any file. The log message will be in the normal + * Logs a message to any file. The log message will be in the normal * SourceMod format, with the plugin logtag prepended. * - * @param file File to write the log message in. - * @param format String format. - * @param ... Format arguments. - * @error File could not be opened/written. + * @param file File to write the log message in. + * @param format String format. + * @param ... Format arguments. + * @error File could not be opened/written. */ native void LogToFile(const char[] file, const char[] format, any ...); /** * Same as LogToFile(), except no plugin logtag is prepended. * - * @param file File to write the log message in. - * @param format String format. - * @param ... Format arguments. - * @error File could not be opened/written. + * @param file File to write the log message in. + * @param format String format. + * @param ... Format arguments. + * @error File could not be opened/written. */ native void LogToFileEx(const char[] file, const char[] format, any ...); /** - * Logs an action from a command or event whereby interception and routing may + * Logs an action from a command or event whereby interception and routing may * be important. This is intended to be a logging version of ShowActivity(). * - * @param client Client performing the action, 0 for server, or -1 if not - * applicable. - * @param target Client being targetted, or -1 if not applicable. - * @param message Message format. - * @param ... Message formatting parameters. + * @param client Client performing the action, 0 for server, or -1 if not + * applicable. + * @param target Client being targetted, or -1 if not applicable. + * @param message Message format. + * @param ... Message formatting parameters. */ native void LogAction(int client, int target, const char[] message, any ...); /** * Logs a plugin error message to the SourceMod logs. * - * @param format String format. - * @param ... Format arguments. + * @param format String format. + * @param ... Format arguments. */ native void LogError(const char[] format, any ...); /** * Called when an action is going to be logged. * - * @param source Handle to the object logging the action, or INVALID_HANDLE - * if Core is logging the action. - * @param ident Type of object logging the action (plugin, ext, or core). - * @param client Client the action is from; 0 for server, -1 if not applicable. - * @param target Client the action is targetting, or -1 if not applicable. - * @param message Message that is being logged. - * @return Plugin_Continue will perform the default logging behavior. - * Plugin_Handled will stop Core from logging the message. - * Plugin_Stop is the same as Handled, but prevents any other - * plugins from handling the message. + * @param source Handle to the object logging the action, or INVALID_HANDLE + * if Core is logging the action. + * @param ident Type of object logging the action (plugin, ext, or core). + * @param client Client the action is from; 0 for server, -1 if not applicable. + * @param target Client the action is targetting, or -1 if not applicable. + * @param message Message that is being logged. + * @return Plugin_Continue will perform the default logging behavior. + * Plugin_Handled will stop Core from logging the message. + * Plugin_Stop is the same as Handled, but prevents any other + * plugins from handling the message. */ -forward Action OnLogAction(Handle source, +forward Action OnLogAction(Handle source, Identity ident, int client, int target, @@ -108,28 +108,28 @@ forward Action OnLogAction(Handle source, /** * Called when a game log message is received. * - * Any Log*() functions called within this callback will not recursively + * Any Log*() functions called within this callback will not recursively * pass through. That is, they will log directly, bypassing this callback. * - * Note that this does not capture log messages from the engine. It only + * Note that this does not capture log messages from the engine. It only * captures log messages being sent from the game/mod itself. * - * @param message Message contents. - * @return Plugin_Handled or Plugin_Stop will prevent the message - * from being written to the log file. + * @param message Message contents. + * @return Plugin_Handled or Plugin_Stop will prevent the message + * from being written to the log file. */ typedef GameLogHook = function Action (const char[] message); /** * Adds a game log hook. * - * @param hook Hook function. + * @param hook Hook function. */ native void AddGameLogHook(GameLogHook hook); /** * Removes a game log hook. * - * @param hook Hook function. + * @param hook Hook function. */ native void RemoveGameLogHook(GameLogHook hook); diff --git a/addons/sourcemod/scripting/include/mapchooser.inc b/addons/sourcemod/scripting/include/mapchooser.inc index 0fe7def..89d73c7 100644 --- a/addons/sourcemod/scripting/include/mapchooser.inc +++ b/addons/sourcemod/scripting/include/mapchooser.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -30,71 +30,72 @@ * Version: $Id$ */ #if defined _mapchooser_included_ - #endinput + #endinput #endif #define _mapchooser_included_ enum NominateResult { - Nominate_Added, /** The map was added to the nominate list */ - Nominate_Replaced, /** A clients existing nomination was replaced */ - Nominate_AlreadyInVote, /** Specified map was already in the vote */ - Nominate_InvalidMap, /** Mapname specified wasn't a valid map */ - Nominate_VoteFull, /** This will only occur if force was set to false */ + Nominate_Added, /** The map was added to the nominate list */ + Nominate_Replaced, /** A clients existing nomination was replaced */ + Nominate_AlreadyInVote, /** Specified map was already in the vote */ + Nominate_InvalidMap, /** Mapname specified wasn't a valid map */ + Nominate_VoteFull /** This will only occur if force was set to false */ }; enum MapChange { - MapChange_Instant, /** Change map as soon as the voting results have come in */ - MapChange_RoundEnd, /** Change map at the end of the round */ - MapChange_MapEnd, /** Change the sm_nextmap cvar */ + MapChange_Instant, /** Change map as soon as the voting results have come in */ + MapChange_RoundEnd, /** Change map at the end of the round */ + MapChange_MapEnd /** Change the sm_nextmap cvar */ }; /** * Attempt to add a map to the mapchooser map list. * - * @param map Map to add. - * @param force Should we force the map in even if it requires overwriting an existing nomination? - * @param owner Client index of the nominator. If the client disconnects the nomination will be removed. Use 0 for constant nominations - * @return Nominate Result of the outcome + * @param map Map to add. + * @param force Should we force the map in even if it requires overwriting an existing nomination? + * @param owner Client index of the nominator. If the client disconnects the nomination will be removed. + * Use 0 for constant nominations + * @return Nominate Result of the outcome */ native NominateResult NominateMap(const char[] map, bool force, int owner); /** * Attempt to remove a map from the mapchooser map list. * - * @param map Map to remove. - * @return True if the nomination was found and removed, or false if the nomination was not found. + * @param map Map to remove. + * @return True if the nomination was found and removed, or false if the nomination was not found. */ native bool RemoveNominationByMap(const char[] map); /** * Attempt to remove a map from the mapchooser map list. * - * @param owner Client index of the nominator. - * @return True if the nomination was found and removed, or false if the nomination was not found. + * @param owner Client index of the nominator. + * @return True if the nomination was found and removed, or false if the nomination was not found. */ native bool RemoveNominationByOwner(int owner); /** * Gets the current list of excluded maps. * - * @param array An ADT array handle to add the map strings to. + * @param array An ADT array handle to add the map strings to. */ native void GetExcludeMapList(ArrayList array); /** * Gets the current list of nominated maps. * - * @param maparray An ADT array handle to add the map strings to. - * @param ownerarray An optional ADT array handle to add the nominator client indexes to. + * @param maparray An ADT array handle to add the map strings to. + * @param ownerarray An optional ADT array handle to add the nominator client indexes to. */ native void GetNominatedMapList(ArrayList maparray, ArrayList ownerarray = null); /** * Checks if MapChooser will allow a vote * - * @return True if a vote can be held, or false if mapchooser is already holding a vote. + * @return True if a vote can be held, or false if mapchooser is already holding a vote. */ native bool CanMapChooserStartVote(); @@ -104,22 +105,22 @@ native bool CanMapChooserStartVote(); * Note: If no input array is specified mapchooser will use its internal list. This includes * any nominations and excluded maps (as per mapchoosers convars). * - * @param when MapChange consant of when the resulting mapchange should occur. - * @param inputarray ADT array list of maps to add to the vote. + * @param when MapChange consant of when the resulting mapchange should occur. + * @param inputarray ADT array list of maps to add to the vote. */ native void InitiateMapChooserVote(MapChange when, ArrayList inputarray=null); /** * Checks if MapChooser's end of map vote has completed. * - * @return True if complete, false otherwise. + * @return True if complete, false otherwise. */ native bool HasEndOfMapVoteFinished(); /** * Checks if MapChooser is set to run an end of map vote. * - * @return True if enabled, false otherwise. + * @return True if enabled, false otherwise. */ native bool EndOfMapVoteEnabled(); @@ -134,7 +135,7 @@ forward void OnNominationRemoved(const char[] map, int owner); */ forward void OnMapVoteStarted(); -public SharedPlugin __pl_mapchooser = +public SharedPlugin __pl_mapchooser = { name = "mapchooser", file = "mapchooser.smx", diff --git a/addons/sourcemod/scripting/include/menus.inc b/addons/sourcemod/scripting/include/menus.inc index a200116..5cdfb7a 100644 --- a/addons/sourcemod/scripting/include/menus.inc +++ b/addons/sourcemod/scripting/include/menus.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -29,7 +29,7 @@ * * Version: $Id$ */ - + #if defined _menus_included #endinput #endif @@ -40,9 +40,9 @@ */ enum MenuStyle { - MenuStyle_Default = 0, /**< The "default" menu style for the mod */ - MenuStyle_Valve = 1, /**< The Valve provided menu style (Used on HL2DM) */ - MenuStyle_Radio = 2, /**< The simpler menu style commonly used on CS:S */ + MenuStyle_Default = 0, /**< The "default" menu style for the mod */ + MenuStyle_Valve = 1, /**< The Valve provided menu style (Used on HL2DM) */ + MenuStyle_Radio = 2 /**< The simpler menu style commonly used on CS:S */ }; /** @@ -50,64 +50,62 @@ enum MenuStyle */ enum MenuAction { - MenuAction_Start = (1<<0), /**< A menu has been started (nothing passed) */ - MenuAction_Display = (1<<1), /**< A menu is about to be displayed (param1=client, param2=MenuPanel Handle) */ - MenuAction_Select = (1<<2), /**< An item was selected (param1=client, param2=item) */ - MenuAction_Cancel = (1<<3), /**< The menu was cancelled (param1=client, param2=reason) */ - MenuAction_End = (1<<4), /**< A menu display has fully ended. - param1 is the MenuEnd reason, and if it's MenuEnd_Cancelled, then - param2 is the MenuCancel reason from MenuAction_Cancel. - */ - MenuAction_VoteEnd = (1<<5), /**< (VOTE ONLY): A vote sequence has succeeded (param1=chosen item) - This is not called if SetVoteResultCallback has been used on the menu. */ - MenuAction_VoteStart = (1<<6), /**< (VOTE ONLY): A vote sequence has started (nothing passed) */ - MenuAction_VoteCancel = (1<<7), /**< (VOTE ONLY): A vote sequence has been cancelled (param1=reason) */ - MenuAction_DrawItem = (1<<8), /**< An item is being drawn; return the new style (param1=client, param2=item) */ - MenuAction_DisplayItem = (1<<9),/**< Item text is being drawn to the display (param1=client, param2=item) - To change the text, use RedrawMenuItem(). - If you do so, return its return value. Otherwise, return 0. - */ + MenuAction_Start = (1<<0), /**< A menu has been started (nothing passed) */ + MenuAction_Display = (1<<1), /**< A menu is about to be displayed (param1=client, param2=MenuPanel Handle) */ + MenuAction_Select = (1<<2), /**< An item was selected (param1=client, param2=item) */ + MenuAction_Cancel = (1<<3), /**< The menu was cancelled (param1=client, param2=reason) */ + MenuAction_End = (1<<4), /**< A menu display has fully ended. + param1 is the MenuEnd reason, and if it's MenuEnd_Cancelled, then + param2 is the MenuCancel reason from MenuAction_Cancel. */ + MenuAction_VoteEnd = (1<<5), /**< (VOTE ONLY): A vote sequence has succeeded (param1=chosen item) + This is not called if SetVoteResultCallback has been used on the menu. */ + MenuAction_VoteStart = (1<<6), /**< (VOTE ONLY): A vote sequence has started (nothing passed) */ + MenuAction_VoteCancel = (1<<7), /**< (VOTE ONLY): A vote sequence has been cancelled (param1=reason) */ + MenuAction_DrawItem = (1<<8), /**< An item is being drawn; return the new style (param1=client, param2=item) */ + MenuAction_DisplayItem = (1<<9) /**< Item text is being drawn to the display (param1=client, param2=item) + To change the text, use RedrawMenuItem(). + If you do so, return its return value. Otherwise, return 0. */ }; /** Default menu actions */ -#define MENU_ACTIONS_DEFAULT MenuAction_Select|MenuAction_Cancel|MenuAction_End +#define MENU_ACTIONS_DEFAULT MenuAction_Select|MenuAction_Cancel|MenuAction_End /** All menu actions */ -#define MENU_ACTIONS_ALL view_as(0xFFFFFFFF) +#define MENU_ACTIONS_ALL view_as(0xFFFFFFFF) -#define MENU_NO_PAGINATION 0 /**< Menu should not be paginated (10 items max) */ -#define MENU_TIME_FOREVER 0 /**< Menu should be displayed as long as possible */ +#define MENU_NO_PAGINATION 0 /**< Menu should not be paginated (10 items max) */ +#define MENU_TIME_FOREVER 0 /**< Menu should be displayed as long as possible */ -#define ITEMDRAW_DEFAULT (0) /**< Item should be drawn normally */ -#define ITEMDRAW_DISABLED (1<<0) /**< Item is drawn but not selectable */ -#define ITEMDRAW_RAWLINE (1<<1) /**< Item should be a raw line, without a slot */ -#define ITEMDRAW_NOTEXT (1<<2) /**< No text should be drawn */ -#define ITEMDRAW_SPACER (1<<3) /**< Item should be drawn as a spacer, if possible */ -#define ITEMDRAW_IGNORE ((1<<1)|(1<<2)) /**< Item should be completely ignored (rawline + notext) */ -#define ITEMDRAW_CONTROL (1<<4) /**< Item is control text (back/next/exit) */ +#define ITEMDRAW_DEFAULT (0) /**< Item should be drawn normally */ +#define ITEMDRAW_DISABLED (1<<0) /**< Item is drawn but not selectable */ +#define ITEMDRAW_RAWLINE (1<<1) /**< Item should be a raw line, without a slot */ +#define ITEMDRAW_NOTEXT (1<<2) /**< No text should be drawn */ +#define ITEMDRAW_SPACER (1<<3) /**< Item should be drawn as a spacer, if possible */ +#define ITEMDRAW_IGNORE ((1<<1)|(1<<2)) /**< Item should be completely ignored (rawline + notext) */ +#define ITEMDRAW_CONTROL (1<<4) /**< Item is control text (back/next/exit) */ -#define MENUFLAG_BUTTON_EXIT (1<<0) /**< Menu has an "exit" button (default if paginated) */ -#define MENUFLAG_BUTTON_EXITBACK (1<<1) /**< Menu has an "exit back" button */ -#define MENUFLAG_NO_SOUND (1<<2) /**< Menu will not have any select sounds */ -#define MENUFLAG_BUTTON_NOVOTE (1<<3) /**< Menu has a "No Vote" button at slot 1 */ +#define MENUFLAG_BUTTON_EXIT (1<<0) /**< Menu has an "exit" button (default if paginated) */ +#define MENUFLAG_BUTTON_EXITBACK (1<<1) /**< Menu has an "exit back" button */ +#define MENUFLAG_NO_SOUND (1<<2) /**< Menu will not have any select sounds */ +#define MENUFLAG_BUTTON_NOVOTE (1<<3) /**< Menu has a "No Vote" button at slot 1 */ -#define VOTEINFO_CLIENT_INDEX 0 /**< Client index */ -#define VOTEINFO_CLIENT_ITEM 1 /**< Item the client selected, or -1 for none */ -#define VOTEINFO_ITEM_INDEX 0 /**< Item index */ -#define VOTEINFO_ITEM_VOTES 1 /**< Number of votes for the item */ +#define VOTEINFO_CLIENT_INDEX 0 /**< Client index */ +#define VOTEINFO_CLIENT_ITEM 1 /**< Item the client selected, or -1 for none */ +#define VOTEINFO_ITEM_INDEX 0 /**< Item index */ +#define VOTEINFO_ITEM_VOTES 1 /**< Number of votes for the item */ -#define VOTEFLAG_NO_REVOTES (1<<0) /**< Players cannot change their votes */ +#define VOTEFLAG_NO_REVOTES (1<<0) /**< Players cannot change their votes */ /** * Reasons a menu can be cancelled (MenuAction_Cancel). */ enum { - MenuCancel_Disconnected = -1, /**< Client dropped from the server */ - MenuCancel_Interrupted = -2, /**< Client was interrupted with another menu */ - MenuCancel_Exit = -3, /**< Client exited via "exit" */ - MenuCancel_NoDisplay = -4, /**< Menu could not be displayed to the client */ - MenuCancel_Timeout = -5, /**< Menu timed out */ - MenuCancel_ExitBack = -6, /**< Client selected "exit back" on a paginated menu */ + MenuCancel_Disconnected = -1, /**< Client dropped from the server */ + MenuCancel_Interrupted = -2, /**< Client was interrupted with another menu */ + MenuCancel_Exit = -3, /**< Client exited via "exit" */ + MenuCancel_NoDisplay = -4, /**< Menu could not be displayed to the client */ + MenuCancel_Timeout = -5, /**< Menu timed out */ + MenuCancel_ExitBack = -6 /**< Client selected "exit back" on a paginated menu */ }; /** @@ -115,8 +113,8 @@ enum */ enum { - VoteCancel_Generic = -1, /**< Vote was generically cancelled. */ - VoteCancel_NoVotes = -2, /**< Vote did not receive any votes. */ + VoteCancel_Generic = -1, /**< Vote was generically cancelled. */ + VoteCancel_NoVotes = -2 /**< Vote did not receive any votes. */ }; /** @@ -124,12 +122,12 @@ enum */ enum { - MenuEnd_Selected = 0, /**< Menu item was selected */ - MenuEnd_VotingDone = -1, /**< Voting finished */ - MenuEnd_VotingCancelled = -2, /**< Voting was cancelled */ - MenuEnd_Cancelled = -3, /**< Menu was cancelled (reason in param2) */ - MenuEnd_Exit = -4, /**< Menu was cleanly exited via "exit" */ - MenuEnd_ExitBack = -5, /**< Menu was cleanly exited via "back" */ + MenuEnd_Selected = 0, /**< Menu item was selected */ + MenuEnd_VotingDone = -1, /**< Voting finished */ + MenuEnd_VotingCancelled = -2, /**< Voting was cancelled */ + MenuEnd_Cancelled = -3, /**< Menu was cancelled (reason in param2) */ + MenuEnd_Exit = -4, /**< Menu was cleanly exited via "exit" */ + MenuEnd_ExitBack = -5 /**< Menu was cleanly exited via "back" */ }; /** @@ -137,19 +135,19 @@ enum */ enum MenuSource { - MenuSource_None = 0, /**< No menu is being displayed */ - MenuSource_External = 1, /**< External menu */ - MenuSource_Normal = 2, /**< A basic menu is being displayed */ - MenuSource_RawPanel = 3, /**< A display is active, but it is not tied to a menu */ + MenuSource_None = 0, /**< No menu is being displayed */ + MenuSource_External = 1, /**< External menu */ + MenuSource_Normal = 2, /**< A basic menu is being displayed */ + MenuSource_RawPanel = 3 /**< A display is active, but it is not tied to a menu */ }; /** * Called when a menu action is completed. * - * @param menu The menu being acted upon. - * @param action The action of the menu. - * @param param1 First action parameter (usually the client). - * @param param2 Second action parameter (usually the item). + * @param menu The menu being acted upon. + * @param action The action of the menu. + * @param param1 First action parameter (usually the client). + * @param param2 Second action parameter (usually the item). */ typedef MenuHandler = function int (Menu menu, MenuAction action, int param1, int param2); @@ -158,8 +156,8 @@ typedef MenuHandler = function int (Menu menu, MenuAction action, int param1, in methodmap Panel < Handle { // Constructor for a new Panel. - // - // @param hStyle MenuStyle Handle, or null to use the default style. + // + // @param hStyle MenuStyle Handle, or null to use the default style. public native Panel(Handle hStyle = null); // Sets the panel's title. @@ -171,7 +169,7 @@ methodmap Panel < Handle // Draws an item on a panel. If the item takes up a slot, the position // is returned. // - // @param text Display text to use. If not a raw line, + // @param text Display text to use. If not a raw line, // the style may automatically add color markup. // No numbering or newlines are needed. // @param style ITEMDRAW style flags. @@ -193,7 +191,7 @@ methodmap Panel < Handle public native bool CanDrawFlags(int style); // Sets the selectable key map of a panel. This is not supported by - // all styles (only by Radio, as of this writing). + // all styles (only by Radio, as of this writing). // // @param keys An integer where each bit N allows key // N+1 to be selected. If no keys are selectable, @@ -202,7 +200,7 @@ methodmap Panel < Handle public native bool SetKeys(int keys); // Sends a panel to a client. Unlike full menus, the handler - // function will only receive the following actions, both of + // function will only receive the following actions, both of // which will have null for a menu, and the client as param1. // // MenuAction_Select (param2 will be the key pressed) @@ -216,8 +214,8 @@ methodmap Panel < Handle // @return True on success, false on failure. public native bool Send(int client, MenuHandler handler, int time); - // Returns the amount of text the menu can still hold. If this is - // limit is reached or overflowed, the text is silently truncated. + // Returns the amount of text the menu can still hold. If this is + // limit is reached or overflowed, the text is silently truncated. // // Radio menus: Currently 511 characters (512 bytes). // Valve menus: Currently -1 (no meaning). @@ -242,9 +240,9 @@ methodmap Panel < Handle methodmap Menu < Handle { // Creates a new, empty menu using the default style. - // + // // @param handler Function which will receive menu actions. - // @param actions Optionally set which actions to receive. Select, + // @param actions Optionally set which actions to receive. Select, // Cancel, and End will always be received regardless // of whether they are set or not. They are also // the only default actions. @@ -272,7 +270,7 @@ methodmap Menu < Handle // // @param info Item information string. // @param display Default item display string. - // @param style Drawing style flags. Anything other than DEFAULT or + // @param style Drawing style flags. Anything other than DEFAULT or // DISABLED will be completely ignored when paginating. // @return True on success, false on failure. // @error Item limit reached. @@ -284,7 +282,7 @@ methodmap Menu < Handle // @param position Position, starting from 0. // @param info Item information string. // @param display Default item display string. - // @param style Drawing style flags. Anything other than DEFAULT or + // @param style Drawing style flags. Anything other than DEFAULT or // DISABLED will be completely ignored when paginating. // @return True on success, false on failure. // @error Invalid menu position. @@ -310,7 +308,7 @@ methodmap Menu < Handle // @param dispBuf Display buffer. // @param dispBufLen Maximum length of the display buffer. // @return True on success, false if position is invalid. - public native bool GetItem(int position, char[] infoBuf, int infoBufLen, + public native bool GetItem(int position, char[] infoBuf, int infoBufLen, int &style=0, char[] dispBuf="", int dispBufLen=0); // Sets the menu's default title/instruction message. @@ -321,7 +319,6 @@ methodmap Menu < Handle // Returns the text of a menu's title. // - // @param menu Menu Handle. // @param buffer Buffer to store title. // @param maxlength Maximum length of the buffer. // @return Number of bytes written. @@ -330,7 +327,6 @@ methodmap Menu < Handle // Creates a raw MenuPanel based off the menu's style. // The Handle must be freed with CloseHandle(). // - // @param menu Menu Handle. // @return A new MenuPanel Handle. public native Panel ToPanel(); @@ -344,8 +340,8 @@ methodmap Menu < Handle // If any vote is in progress on a menu, it will be cancelled. public native void Cancel(); - // Broadcasts a menu to a list of clients. The most selected item will be - // returned through MenuAction_End. On a tie, a random item will be returned + // Broadcasts a menu to a list of clients. The most selected item will be + // returned through MenuAction_End. On a tie, a random item will be returned // from a list of the tied items. // // Note that MenuAction_VoteEnd and MenuAction_VoteStart are both @@ -371,15 +367,17 @@ methodmap Menu < Handle int[] players = new int[MaxClients]; for (int i = 1; i <= MaxClients; i++) { if (!IsClientInGame(i) || IsFakeClient(i)) + { continue; + } players[total++] = i; } return this.DisplayVote(players, total, time, flags); } // Get or set the menu's pagination. - // - // If pagination is MENU_NO_PAGINATION, and the exit button flag is set, + // + // If pagination is MENU_NO_PAGINATION, and the exit button flag is set, // then the exit button flag is removed. It can be re-applied if desired. property int Pagination { public native get(); @@ -401,10 +399,10 @@ methodmap Menu < Handle public native set(bool value); } - // Controls whether or not the menu has an "exit back" button. By default, - // menus do not have an exit back button. - // - // Exit Back buttons appear as "Back" on page 1 of paginated menus and have + // Controls whether or not the menu has an "exit back" button. By default, + // menus do not have an exit back button. + // + // Exit Back buttons appear as "Back" on page 1 of paginated menus and have // functionality defined by the user in MenuEnd_ExitBack. property bool ExitBackButton { public native get(); @@ -434,7 +432,7 @@ methodmap Menu < Handle } // Returns the first item on the page of a currently selected menu. - // + // // This is only valid inside a MenuAction_Select callback. property int Selection { public native get(); @@ -443,155 +441,155 @@ methodmap Menu < Handle /** * Creates a new, empty menu using the default style. - * - * @param handler Function which will receive menu actions. - * @param actions Optionally set which actions to receive. Select, - * Cancel, and End will always be received regardless - * of whether they are set or not. They are also - * the only default actions. - * @return A new menu Handle. + * + * @param handler Function which will receive menu actions. + * @param actions Optionally set which actions to receive. Select, + * Cancel, and End will always be received regardless + * of whether they are set or not. They are also + * the only default actions. + * @return A new menu Handle. */ native Menu CreateMenu(MenuHandler handler, MenuAction actions=MENU_ACTIONS_DEFAULT); /** * Displays a menu to a client. * - * @param menu Menu Handle. - * @param client Client index. - * @param time Maximum time to leave menu on the screen. - * @return True on success, false on failure. - * @error Invalid Handle or client not in game. + * @param menu Menu Handle. + * @param client Client index. + * @param time Maximum time to leave menu on the screen. + * @return True on success, false on failure. + * @error Invalid Handle or client not in game. */ native bool DisplayMenu(Handle menu, int client, int time); /** * Displays a menu to a client, starting from the given item. * - * @param menu Menu Handle. - * @param client Client index. - * @param first_item First item to begin drawing from. - * @param time Maximum time to leave menu on the screen. - * @return True on success, false on failure. - * @error Invalid Handle or client not in game. + * @param menu Menu Handle. + * @param client Client index. + * @param first_item First item to begin drawing from. + * @param time Maximum time to leave menu on the screen. + * @return True on success, false on failure. + * @error Invalid Handle or client not in game. */ native bool DisplayMenuAtItem(Handle menu, int client, int first_item, int time); /** * Appends a new item to the end of a menu. * - * @param menu Menu Handle. - * @param info Item information string. - * @param display Default item display string. - * @param style Drawing style flags. Anything other than DEFAULT or - * DISABLED will be completely ignored when paginating. - * @return True on success, false on failure. - * @error Invalid Handle or item limit reached. + * @param menu Menu Handle. + * @param info Item information string. + * @param display Default item display string. + * @param style Drawing style flags. Anything other than DEFAULT or + * DISABLED will be completely ignored when paginating. + * @return True on success, false on failure. + * @error Invalid Handle or item limit reached. */ -native bool AddMenuItem(Handle menu, - const char[] info, - const char[] display, +native bool AddMenuItem(Handle menu, + const char[] info, + const char[] display, int style=ITEMDRAW_DEFAULT); /** * Inserts an item into the menu before a certain position; the new item will * be at the given position and all next items pushed forward. * - * @param menu Menu Handle. - * @param position Position, starting from 0. - * @param info Item information string. - * @param display Default item display string. - * @param style Drawing style flags. Anything other than DEFAULT or - * DISABLED will be completely ignored when paginating. - * @return True on success, false on failure. - * @error Invalid Handle or menu position. + * @param menu Menu Handle. + * @param position Position, starting from 0. + * @param info Item information string. + * @param display Default item display string. + * @param style Drawing style flags. Anything other than DEFAULT or + * DISABLED will be completely ignored when paginating. + * @return True on success, false on failure. + * @error Invalid Handle or menu position. */ native bool InsertMenuItem(Handle menu, - position, - const char[] info, - const char[] display, + position, + const char[] info, + const char[] display, int style=ITEMDRAW_DEFAULT); /** * Removes an item from the menu. * - * @param menu Menu Handle. - * @param position Position, starting from 0. - * @return True on success, false on failure. - * @error Invalid Handle or menu position. + * @param menu Menu Handle. + * @param position Position, starting from 0. + * @return True on success, false on failure. + * @error Invalid Handle or menu position. */ native bool RemoveMenuItem(Handle menu, int position); /** * Removes all items from a menu. * - * @param menu Menu Handle. - * @error Invalid Handle or menu position. + * @param menu Menu Handle. + * @error Invalid Handle or menu position. */ native void RemoveAllMenuItems(Handle menu); /** * Retrieves information about a menu item. * - * @param menu Menu Handle. - * @param position Position, starting from 0. - * @param infoBuf Info buffer. - * @param infoBufLen Maximum length of the info buffer. - * @param style By-reference variable to store drawing flags. - * @param dispBuf Display buffer. - * @param dispBufLen Maximum length of the display buffer. - * @return True on success, false if position is invalid. - * @error Invalid Handle. + * @param menu Menu Handle. + * @param position Position, starting from 0. + * @param infoBuf Info buffer. + * @param infoBufLen Maximum length of the info buffer. + * @param style By-reference variable to store drawing flags. + * @param dispBuf Display buffer. + * @param dispBufLen Maximum length of the display buffer. + * @return True on success, false if position is invalid. + * @error Invalid Handle. */ -native bool GetMenuItem(Handle menu, - int position, - char[] infoBuf, - int infoBufLen, - int &style=0, +native bool GetMenuItem(Handle menu, + int position, + char[] infoBuf, + int infoBufLen, + int &style=0, char[] dispBuf="", int dispBufLen=0); - + /** * Returns the first item on the page of a currently selected menu. * * This is only valid inside a MenuAction_Select callback. * - * @return First item number on the page the client was viewing - * before selecting the item in the callback. This can - * be used to re-display the menu from the original - * position. - * @error Not called from inside a MenuAction_Select callback. + * @return First item number on the page the client was viewing + * before selecting the item in the callback. This can + * be used to re-display the menu from the original + * position. + * @error Not called from inside a MenuAction_Select callback. */ native int GetMenuSelectionPosition(); /** * Returns the number of items in a menu. * - * @param menu Menu Handle. - * @return Number of items in the menu. - * @error Invalid Handle. + * @param menu Menu Handle. + * @return Number of items in the menu. + * @error Invalid Handle. */ native int GetMenuItemCount(Handle menu); /** * Sets whether the menu should be paginated or not. * - * If itemsPerPage is MENU_NO_PAGINATION, and the exit button flag is set, + * If itemsPerPage is MENU_NO_PAGINATION, and the exit button flag is set, * then the exit button flag is removed. It can be re-applied if desired. * - * @param menu Handle to the menu. - * @param itemsPerPage Number of items per page, or MENU_NO_PAGINATION. - * @return True on success, false if pagination is too high or - * low. - * @error Invalid Handle. + * @param menu Handle to the menu. + * @param itemsPerPage Number of items per page, or MENU_NO_PAGINATION. + * @return True on success, false if pagination is too high or + * low. + * @error Invalid Handle. */ native bool SetMenuPagination(Handle menu, int itemsPerPage); /** * Returns a menu's pagination setting. * - * @param menu Handle to the menu. - * @return Pagination setting. - * @error Invalid Handle. + * @param menu Handle to the menu. + * @return Pagination setting. + * @error Invalid Handle. */ native int GetMenuPagination(Handle menu); @@ -599,30 +597,30 @@ native int GetMenuPagination(Handle menu); * Returns a menu's MenuStyle Handle. The Handle * is global and cannot be freed. * - * @param menu Handle to the menu. - * @return Handle to the menu's draw style. - * @error Invalid Handle. + * @param menu Handle to the menu. + * @return Handle to the menu's draw style. + * @error Invalid Handle. */ native Handle GetMenuStyle(Handle menu); /** * Sets the menu's default title/instruction message. * - * @param menu Menu Handle. - * @param fmt Message string format - * @param ... Message string arguments. - * @error Invalid Handle. + * @param menu Menu Handle. + * @param fmt Message string format + * @param ... Message string arguments. + * @error Invalid Handle. */ native void SetMenuTitle(Handle menu, const char[] fmt, any ...); /** * Returns the text of a menu's title. * - * @param menu Menu Handle. - * @param buffer Buffer to store title. - * @param maxlength Maximum length of the buffer. - * @return Number of bytes written. - * @error Invalid Handle/ + * @param menu Menu Handle. + * @param buffer Buffer to store title. + * @param maxlength Maximum length of the buffer. + * @return Number of bytes written. + * @error Invalid Handle/ */ native int GetMenuTitle(Handle menu, char[] buffer, int maxlength); @@ -630,9 +628,9 @@ native int GetMenuTitle(Handle menu, char[] buffer, int maxlength); * Creates a raw MenuPanel based off the menu's style. * The Handle must be freed with CloseHandle(). * - * @param menu Menu Handle. - * @return A new MenuPanel Handle. - * @error Invalid Handle. + * @param menu Menu Handle. + * @return A new MenuPanel Handle. + * @error Invalid Handle. */ native Panel CreatePanelFromMenu(Handle menu); @@ -640,53 +638,53 @@ native Panel CreatePanelFromMenu(Handle menu); * Returns whether or not the menu has an exit button. * By default, menus have an exit button. * - * @param menu Menu Handle. - * @return True if the menu has an exit button; false otherwise. - * @error Invalid Handle. + * @param menu Menu Handle. + * @return True if the menu has an exit button; false otherwise. + * @error Invalid Handle. */ native bool GetMenuExitButton(Handle menu); /** - * Sets whether or not the menu has an exit button. By default, paginated menus + * Sets whether or not the menu has an exit button. By default, paginated menus * have an exit button. * - * If a menu's pagination is changed to MENU_NO_PAGINATION, and the pagination - * was previously a different value, then the Exit button status is changed to + * If a menu's pagination is changed to MENU_NO_PAGINATION, and the pagination + * was previously a different value, then the Exit button status is changed to * false. It must be explicitly re-enabled afterwards. * - * If a non-paginated menu has an exit button, then at most 9 items will be + * If a non-paginated menu has an exit button, then at most 9 items will be * displayed. * - * @param menu Menu Handle. - * @param button True to enable the button, false to remove it. - * @return True if allowed; false on failure. - * @error Invalid Handle. + * @param menu Menu Handle. + * @param button True to enable the button, false to remove it. + * @return True if allowed; false on failure. + * @error Invalid Handle. */ native bool SetMenuExitButton(Handle menu, bool button); /** - * Returns whether or not the menu has an "exit back" button. By default, - * menus do not have an exit back button. + * Returns whether or not the menu has an "exit back" button. By default, + * menus do not have an exit back button. * - * Exit Back buttons appear as "Back" on page 1 of paginated menus and have + * Exit Back buttons appear as "Back" on page 1 of paginated menus and have * functionality defined by the user in MenuEnd_ExitBack. * - * @param menu Menu Handle. - * @return True if the menu has an exit back button; false otherwise. - * @error Invalid Handle. + * @param menu Menu Handle. + * @return True if the menu has an exit back button; false otherwise. + * @error Invalid Handle. */ native bool GetMenuExitBackButton(Handle menu); /** - * Sets whether or not the menu has an "exit back" button. By default, menus + * Sets whether or not the menu has an "exit back" button. By default, menus * do not have an exit back button. * - * Exit Back buttons appear as "Back" on page 1 of paginated menus and have + * Exit Back buttons appear as "Back" on page 1 of paginated menus and have * functionality defined by the user in MenuEnd_ExitBack. * - * @param menu Menu Handle. - * @param button True to enable the button, false to remove it. - * @error Invalid Handle. + * @param menu Menu Handle. + * @param button True to enable the button, false to remove it. + * @error Invalid Handle. */ native void SetMenuExitBackButton(Handle menu, bool button); @@ -694,10 +692,10 @@ native void SetMenuExitBackButton(Handle menu, bool button); * Sets whether or not the menu has a "no vote" button in slot 1. * By default, menus do not have a no vote button. * - * @param menu Menu Handle. - * @param button True to enable the button, false to remove it. - * @return True if allowed; false on failure. - * @error Invalid Handle. + * @param menu Menu Handle. + * @param button True to enable the button, false to remove it. + * @return True if allowed; false on failure. + * @error Invalid Handle. */ native bool SetMenuNoVoteButton(Handle menu, bool button); @@ -711,17 +709,17 @@ native bool SetMenuNoVoteButton(Handle menu, bool button); * * If any vote is in progress on a menu, it will be cancelled. * - * @param menu Menu Handle. - * @error Invalid Handle. + * @param menu Menu Handle. + * @error Invalid Handle. */ native void CancelMenu(Handle menu); /** * Retrieves a menu's option flags. * - * @param menu Menu Handle. - * @return A bitstring of MENUFLAG bits. - * @error Invalid Handle. + * @param menu Menu Handle. + * @return A bitstring of MENUFLAG bits. + * @error Invalid Handle. */ native int GetMenuOptionFlags(Handle menu); @@ -732,61 +730,61 @@ native int GetMenuOptionFlags(Handle menu); * See SetMenuExitButton() for information on Exit buttons. * See SetMenuExitBackButton() for information on Exit Back buttons. * - * @param menu Menu Handle. - * @param flags A new bitstring of MENUFLAG bits. - * @error Invalid Handle. + * @param menu Menu Handle. + * @param flags A new bitstring of MENUFLAG bits. + * @error Invalid Handle. */ native void SetMenuOptionFlags(Handle menu, int flags); /** * Returns whether a vote is in progress. * - * @param menu Deprecated; no longer used. - * @return True if a vote is in progress, false otherwise. + * @param menu Deprecated; no longer used. + * @return True if a vote is in progress, false otherwise. */ native bool IsVoteInProgress(Handle menu=INVALID_HANDLE); /** * Cancels the vote in progress. * - * @error If no vote is in progress. + * @error If no vote is in progress. */ native void CancelVote(); /** - * Broadcasts a menu to a list of clients. The most selected item will be - * returned through MenuAction_End. On a tie, a random item will be returned + * Broadcasts a menu to a list of clients. The most selected item will be + * returned through MenuAction_End. On a tie, a random item will be returned * from a list of the tied items. * * Note that MenuAction_VoteEnd and MenuAction_VoteStart are both * default callbacks and do not need to be enabled. * - * @param menu Menu Handle. - * @param clients Array of clients to broadcast to. - * @param numClients Number of clients in the array. - * @param time Maximum time to leave menu on the screen. - * @param flags Optional voting flags. - * @return True on success, false if this menu already has a vote session - * in progress. - * @error Invalid Handle, or a vote is already in progress. + * @param menu Menu Handle. + * @param clients Array of clients to broadcast to. + * @param numClients Number of clients in the array. + * @param time Maximum time to leave menu on the screen. + * @param flags Optional voting flags. + * @return True on success, false if this menu already has a vote session + * in progress. + * @error Invalid Handle, or a vote is already in progress. */ native bool VoteMenu(Handle menu, int[] clients, int numClients, int time, int flags=0); /** * Sends a vote menu to all clients. See VoteMenu() for more information. * - * @param menu Menu Handle. - * @param time Maximum time to leave menu on the screen. - * @param flags Optional voting flags. - * @return True on success, false if this menu already has a vote session - * in progress. - * @error Invalid Handle. + * @param menu Menu Handle. + * @param time Maximum time to leave menu on the screen. + * @param flags Optional voting flags. + * @return True on success, false if this menu already has a vote session + * in progress. + * @error Invalid Handle. */ stock bool VoteMenuToAll(Handle menu, int time, int flags=0) { int total; int[] players = new int[MaxClients]; - + for (int i=1; i<=MaxClients; i++) { if (!IsClientInGame(i) || IsFakeClient(i)) @@ -795,20 +793,20 @@ stock bool VoteMenuToAll(Handle menu, int time, int flags=0) } players[total++] = i; } - + return VoteMenu(menu, players, total, time, flags); } /** * Callback for when a vote has ended and results are available. * - * @param menu The menu being voted on. - * @param num_votes Number of votes tallied in total. - * @param num_clients Number of clients who could vote. - * @param client_info Array of clients. Use VOTEINFO_CLIENT_ defines. - * @param num_items Number of unique items that were selected. - * @param item_info Array of items, sorted by count. Use VOTEINFO_ITEM - * defines. + * @param menu The menu being voted on. + * @param num_votes Number of votes tallied in total. + * @param num_clients Number of clients who could vote. + * @param client_info Array of clients. Use VOTEINFO_CLIENT_ defines. + * @param num_items Number of unique items that were selected. + * @param item_info Array of items, sorted by count. Use VOTEINFO_ITEM + * defines. */ typeset VoteHandler { @@ -837,9 +835,9 @@ typeset VoteHandler * Sets an advanced vote handling callback. If this callback is set, * MenuAction_VoteEnd will not be called. * - * @param menu Menu Handle. - * @param callback Callback function. - * @error Invalid Handle or callback. + * @param menu Menu Handle. + * @param callback Callback function. + * @error Invalid Handle or callback. */ native void SetVoteResultCallback(Handle menu, VoteHandler callback); @@ -848,113 +846,113 @@ native void SetVoteResultCallback(Handle menu, VoteHandler callback); * a publicly invocable menu. This number is the time remaining until * (last_vote + sm_vote_delay). * - * @return Number of seconds to wait, or 0 for none. + * @return Number of seconds to wait, or 0 for none. */ native int CheckVoteDelay(); /** - * Returns whether a client is in the pool of clients allowed - * to participate in the current vote. This is determined by + * Returns whether a client is in the pool of clients allowed + * to participate in the current vote. This is determined by * the client list passed to VoteMenu(). * - * @param client Client index. - * @return True if client is allowed to vote, false otherwise. - * @error If no vote is in progress or client index is invalid. + * @param client Client index. + * @return True if client is allowed to vote, false otherwise. + * @error If no vote is in progress or client index is invalid. */ native bool IsClientInVotePool(int client); /** * Redraws the current vote menu to a client in the voting pool. * - * @param client Client index. - * @param revotes True to allow revotes, false otherwise. - * @return True on success, false if the client is in the vote pool - * but cannot vote again. - * @error No vote in progress, int client is not in the voting pool, - * or client index is invalid. + * @param client Client index. + * @param revotes True to allow revotes, false otherwise. + * @return True on success, false if the client is in the vote pool + * but cannot vote again. + * @error No vote in progress, int client is not in the voting pool, + * or client index is invalid. */ native bool RedrawClientVoteMenu(int client, bool revotes=true); /** * Returns a style's global Handle. * - * @param style Menu Style. - * @return A Handle, or INVALID_HANDLE if not found or unusable. + * @param style Menu Style. + * @return A Handle, or INVALID_HANDLE if not found or unusable. */ native Handle GetMenuStyleHandle(MenuStyle style); /** - * Creates a MenuPanel from a MenuStyle. Panels are used for drawing raw + * Creates a MenuPanel from a MenuStyle. Panels are used for drawing raw * menus without any extra helper functions. The Handle must be closed * with CloseHandle(). * - * @param hStyle MenuStyle Handle, or INVALID_HANDLE to use the default style. - * @return A new MenuPanel Handle. - * @error Invalid Handle other than INVALID_HANDLE. + * @param hStyle MenuStyle Handle, or INVALID_HANDLE to use the default style. + * @return A new MenuPanel Handle. + * @error Invalid Handle other than INVALID_HANDLE. */ native Panel CreatePanel(Handle hStyle=INVALID_HANDLE); -/** - * Creates a Menu from a MenuStyle. The Handle must be closed with +/** + * Creates a Menu from a MenuStyle. The Handle must be closed with * CloseHandle(). * - * @param hStyle MenuStyle Handle, or INVALID_HANDLE to use the default style. - * @param handler Function which will receive menu actions. - * @param actions Optionally set which actions to receive. Select, - * Cancel, and End will always be received regardless - * of whether they are set or not. They are also - * the only default actions. - * @return A new menu Handle. - * @error Invalid Handle other than INVALID_HANDLE. + * @param hStyle MenuStyle Handle, or INVALID_HANDLE to use the default style. + * @param handler Function which will receive menu actions. + * @param actions Optionally set which actions to receive. Select, + * Cancel, and End will always be received regardless + * of whether they are set or not. They are also + * the only default actions. + * @return A new menu Handle. + * @error Invalid Handle other than INVALID_HANDLE. */ native Menu CreateMenuEx(Handle hStyle=INVALID_HANDLE, MenuHandler handler, MenuAction actions=MENU_ACTIONS_DEFAULT); /** * Returns whether a client is viewing a menu. * - * @param client Client index. - * @param hStyle MenuStyle Handle, or INVALID_HANDLE to use the default style. - * @return A MenuSource value. - * @error Invalid Handle other than null. + * @param client Client index. + * @param hStyle MenuStyle Handle, or INVALID_HANDLE to use the default style. + * @return A MenuSource value. + * @error Invalid Handle other than null. */ native MenuSource GetClientMenu(int client, Handle hStyle=null); -/** +/** * Cancels a menu on a client. This will only affect non-external menus. * - * @param hStyle MenuStyle Handle, or INVALID_HANDLE to use the default style. - * @param client Client index. - * @param autoIgnore If true, no menus can be re-drawn on the client during - * the cancellation process. - * @return True if a menu was cancelled, false otherwise. + * @param client Client index. + * @param autoIgnore If true, no menus can be re-drawn on the client during + * the cancellation process. + * @param hStyle MenuStyle Handle, or INVALID_HANDLE to use the default style. + * @return True if a menu was cancelled, false otherwise. */ native bool CancelClientMenu(int client, bool autoIgnore=false, Handle hStyle=INVALID_HANDLE); /** * Returns a style's maximum items per page. * - * @param hStyle MenuStyle Handle, or INVALID_HANDLE to use the default style. - * @return Maximum items per page. - * @error Invalid Handle other than INVALID_HANDLE. + * @param hStyle MenuStyle Handle, or INVALID_HANDLE to use the default style. + * @return Maximum items per page. + * @error Invalid Handle other than INVALID_HANDLE. */ native int GetMaxPageItems(Handle hStyle=INVALID_HANDLE); /** * Returns a MenuPanel's parent style. * - * @param panel A MenuPanel Handle. - * @return The MenuStyle Handle that created the panel. - * @error Invalid Handle. + * @param panel A MenuPanel Handle. + * @return The MenuStyle Handle that created the panel. + * @error Invalid Handle. */ native Handle GetPanelStyle(Handle panel); /** * Sets the panel's title. * - * @param panel A MenuPanel Handle. - * @param text Text to set as the title. - * @param onlyIfEmpty If true, the title will only be set if no title is set. - * @error Invalid Handle. + * @param panel A MenuPanel Handle. + * @param text Text to set as the title. + * @param onlyIfEmpty If true, the title will only be set if no title is set. + * @error Invalid Handle. */ native void SetPanelTitle(Handle panel, const char[] text, bool onlyIfEmpty=false); @@ -962,24 +960,24 @@ native void SetPanelTitle(Handle panel, const char[] text, bool onlyIfEmpty=fals * Draws an item on a panel. If the item takes up a slot, the position * is returned. * - * @param panel A MenuPanel Handle. - * @param text Display text to use. If not a raw line, - * the style may automatically add color markup. - * No numbering or newlines are needed. - * @param style ITEMDRAW style flags. - * @return A slot position, or 0 if item was a rawline or could not be drawn. - * @error Invalid Handle. + * @param panel A MenuPanel Handle. + * @param text Display text to use. If not a raw line, + * the style may automatically add color markup. + * No numbering or newlines are needed. + * @param style ITEMDRAW style flags. + * @return A slot position, or 0 if item was a rawline or could not be drawn. + * @error Invalid Handle. */ native int DrawPanelItem(Handle panel, const char[] text, int style=ITEMDRAW_DEFAULT); /** * Draws a raw line of text on a panel, without any markup other than a newline. * - * @param panel A MenuPanel Handle, or INVALID_HANDLE if inside a - * MenuAction_DisplayItem callback. - * @param text Display text to use. - * @return True on success, false if raw lines are not supported. - * @error Invalid Handle. + * @param panel A MenuPanel Handle, or INVALID_HANDLE if inside a + * MenuAction_DisplayItem callback. + * @param text Display text to use. + * @return True on success, false if raw lines are not supported. + * @error Invalid Handle. */ native bool DrawPanelText(Handle panel, const char[] text); @@ -987,28 +985,28 @@ native bool DrawPanelText(Handle panel, const char[] text); * Returns whether or not the given drawing flags are supported by * the menu style. * - * @param panel A MenuPanel Handle. - * @param style ITEMDRAW style flags. - * @return True if item is drawable, false otherwise. - * @error Invalid Handle. + * @param panel A MenuPanel Handle. + * @param style ITEMDRAW style flags. + * @return True if item is drawable, false otherwise. + * @error Invalid Handle. */ native bool CanPanelDrawFlags(Handle panel, int style); /** * Sets the selectable key map of a panel. This is not supported by - * all styles (only by Radio, as of this writing). + * all styles (only by Radio, as of this writing). * - * @param panel A MenuPanel Handle. - * @param keys An integer where each bit N allows key - * N+1 to be selected. If no keys are selectable, - * then key 0 (bit 9) is automatically set. - * @return True if supported, false otherwise. + * @param panel A MenuPanel Handle. + * @param keys An integer where each bit N allows key + * N+1 to be selected. If no keys are selectable, + * then key 0 (bit 9) is automatically set. + * @return True if supported, false otherwise. */ native bool SetPanelKeys(Handle panel, int keys); /** * Sends a panel to a client. Unlike full menus, the handler - * function will only receive the following actions, both of + * function will only receive the following actions, both of * which will have INVALID_HANDLE for a menu, and the client * as param1. * @@ -1017,35 +1015,35 @@ native bool SetPanelKeys(Handle panel, int keys); * * Also, if the menu fails to display, no callbacks will be called. * - * @param panel A MenuPanel Handle. - * @param client A client to draw to. - * @param handler The MenuHandler function to catch actions with. - * @param time Time to hold the menu for. - * @return True on success, false on failure. - * @error Invalid Handle. + * @param panel A MenuPanel Handle. + * @param client A client to draw to. + * @param handler The MenuHandler function to catch actions with. + * @param time Time to hold the menu for. + * @return True on success, false on failure. + * @error Invalid Handle. */ native bool SendPanelToClient(Handle panel, int client, MenuHandler handler, int time); /** - * @brief Returns the amount of text the menu can still hold. If this is - * limit is reached or overflowed, the text is silently truncated. + * @brief Returns the amount of text the menu can still hold. If this is + * limit is reached or overflowed, the text is silently truncated. * * Radio menus: Currently 511 characters (512 bytes). * Valve menus: Currently -1 (no meaning). * - * @param panel A MenuPanel Handle. - * @return Number of characters that the menu can still hold, - * or -1 if there is no known limit. - * @error Invalid Handle. + * @param panel A MenuPanel Handle. + * @return Number of characters that the menu can still hold, + * or -1 if there is no known limit. + * @error Invalid Handle. */ native int GetPanelTextRemaining(Handle panel); /** * @brief Returns the current key position. * - * @param panel A MenuPanel Handle. - * @return Current key position starting at 1. - * @error Invalid Handle. + * @param panel A MenuPanel Handle. + * @return Current key position starting at 1. + * @error Invalid Handle. */ native int GetPanelCurrentKey(Handle panel); @@ -1053,48 +1051,48 @@ native int GetPanelCurrentKey(Handle panel); * @brief Sets the next key position. This cannot be used * to traverse backwards. * - * @param panel A MenuPanel Handle. - * @param key Key that is greater or equal to - * GetPanelCurrentKey(). - * @return True on success, false otherwise. - * @error Invalid Handle. + * @param panel A MenuPanel Handle. + * @param key Key that is greater or equal to + * GetPanelCurrentKey(). + * @return True on success, false otherwise. + * @error Invalid Handle. */ native bool SetPanelCurrentKey(Handle panel, int key); /** * @brief Redraws menu text from inside a MenuAction_DisplayItem callback. - * - * @param text Menu text to draw. - * @return Item position; must be returned via the callback. + * + * @param text Menu text to draw. + * @return Item position; must be returned via the callback. */ native int RedrawMenuItem(const char[] text); /** - * This function is provided for legacy code only. Some older plugins may use - * network messages instead of the panel API. This function wraps the panel - * API for eased portability into the SourceMod menu system. + * This function is provided for legacy code only. Some older plugins may use + * network messages instead of the panel API. This function wraps the panel + * API for eased portability into the SourceMod menu system. * - * This function is only usable with the Radio Menu style. You do not need to - * split up your menu into multiple packets; SourceMod will break the string + * This function is only usable with the Radio Menu style. You do not need to + * split up your menu into multiple packets; SourceMod will break the string * up internally. * - * @param client Client index. - * @param str Full menu string as would be passed over the network. - * @param time Time to hold the menu for. - * @param keys Selectable key bitstring. - * @param handler Optional handler function, with the same rules as - * SendPanelToClient(). - * @return True on success, false on failure. - * @error Invalid client index, or radio menus not supported. + * @param client Client index. + * @param str Full menu string as would be passed over the network. + * @param time Time to hold the menu for. + * @param keys Selectable key bitstring. + * @param handler Optional handler function, with the same rules as + * SendPanelToClient(). + * @return True on success, false on failure. + * @error Invalid client index, or radio menus not supported. */ native bool InternalShowMenu(int client, const char[] str, int time, int keys=-1, MenuHandler handler=INVALID_FUNCTION); /** * Retrieves voting information from MenuAction_VoteEnd. * - * @param param2 Second parameter of MenuAction_VoteEnd. - * @param winningVotes Number of votes received by the winning option. - * @param totalVotes Number of total votes received. + * @param param2 Second parameter of MenuAction_VoteEnd. + * @param winningVotes Number of votes received by the winning option. + * @param totalVotes Number of total votes received. */ stock void GetMenuVoteInfo(int param2, int &winningVotes, int &totalVotes) { @@ -1103,12 +1101,12 @@ stock void GetMenuVoteInfo(int param2, int &winningVotes, int &totalVotes) } /** - * Quick stock to determine whether voting is allowed. This doesn't let you - * fine-tune a reason for not voting, so it's not recommended for lazily + * Quick stock to determine whether voting is allowed. This doesn't let you + * fine-tune a reason for not voting, so it's not recommended for lazily * telling clients that voting isn't allowed. - * - * @return True if voting is allowed, false if voting is in progress - * or the cooldown is active. + * + * @return True if voting is allowed, false if voting is in progress + * or the cooldown is active. */ stock bool IsNewVoteAllowed() { @@ -1116,6 +1114,6 @@ stock bool IsNewVoteAllowed() { return false; } - + return true; } diff --git a/addons/sourcemod/scripting/include/multicolors/colors.inc b/addons/sourcemod/scripting/include/multicolors/colors.inc new file mode 100644 index 0000000..53233a2 --- /dev/null +++ b/addons/sourcemod/scripting/include/multicolors/colors.inc @@ -0,0 +1,946 @@ +/************************************************************************** + * * + * Colored Chat Functions * + * Author: exvel, Editor: Popoklopsi, Powerlord, Bara * + * Version: 2.0.0-MC * + * * + **************************************************************************/ + + +#if defined _colors_included + #endinput +#endif +#define _colors_included + +#define MAX_MESSAGE_LENGTH 250 +#define MAX_COLORS 18 + +#define SERVER_INDEX 0 +#define NO_INDEX -1 +#define NO_PLAYER -2 + +enum C_Colors +{ + Color_Default = 0, + Color_Darkred, + Color_Green, + Color_Lightgreen, + Color_Red, + Color_Blue, + Color_Olive, + Color_Lime, + Color_Lightred, + Color_Purple, + Color_Grey, + Color_Yellow, + Color_Orange, + Color_Bluegrey, + Color_Lightblue, + Color_Darkblue, + Color_Grey2, + Color_Orchid, + Color_Lightred2 +} + +/* C_Colors' properties */ +char C_Tag[][] = {"{default}", "{darkred}", "{green}", "{lightgreen}", "{red}", "{blue}", "{olive}", "{lime}", "{lightred}", "{purple}", "{grey}", "{yellow}", "{orange}", "{bluegrey}", "{lightblue}", "{darkblue}", "{grey2}", "{orchid}", "{lightred2}"}; +char C_TagCode[][] = {"\x01", "\x02", "\x04", "\x03", "\x03", "\x03", "\x05", "\x06", "\x07", "\x03", "\x08", "\x09", "\x10", "\x0A", "\x0B", "\x0C", "\x0D", "\x0E", "\x0F"}; +bool C_TagReqSayText2[] = {false, false, false, true, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false}; +bool C_EventIsHooked = false; +bool C_SkipList[MAXPLAYERS+1] = {false,...}; + +/* Game default profile */ +bool C_Profile_Colors[] = {true, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false}; +int C_Profile_TeamIndex[] = {NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX, NO_INDEX}; +bool C_Profile_SayText2 = false; + +static Handle sm_show_activity = null; + +/** + * Prints a message to a specific client in the chat area. + * Supports color tags. + * + * @param client Client index. + * @param szMessage Message (formatting rules). + * @return No return + * + * On error/Errors: If the client is not connected an error will be thrown. + */ +stock void C_PrintToChat(int client, const char[] szMessage, any ...) +{ + if (client <= 0 || client > MaxClients) + ThrowError("Invalid client index %d", client); + + if (!IsClientInGame(client)) + ThrowError("Client %d is not in game", client); + + char szBuffer[MAX_MESSAGE_LENGTH]; + char szCMessage[MAX_MESSAGE_LENGTH]; + + SetGlobalTransTarget(client); + + Format(szBuffer, sizeof(szBuffer), "\x01%s", szMessage); + VFormat(szCMessage, sizeof(szCMessage), szBuffer, 3); + + int index = C_Format(szCMessage, sizeof(szCMessage)); + + if (index == NO_INDEX) + PrintToChat(client, "%s", szCMessage); + else + C_SayText2(client, index, szCMessage); +} + +/** + * Reples to a message in a command. A client index of 0 will use PrintToServer(). + * If the command was from the console, PrintToConsole() is used. If the command was from chat, C_PrintToChat() is used. + * Supports color tags. + * + * @param client Client index, or 0 for server. + * @param szMessage Formatting rules. + * @param ... Variable number of format parameters. + * @return No return + * + * On error/Errors: If the client is not connected or invalid. + */ +stock void C_ReplyToCommand(int client, const char[] szMessage, any ...) +{ + char szCMessage[MAX_MESSAGE_LENGTH]; + SetGlobalTransTarget(client); + VFormat(szCMessage, sizeof(szCMessage), szMessage, 3); + + if (client == 0) + { + C_RemoveTags(szCMessage, sizeof(szCMessage)); + PrintToServer("%s", szCMessage); + } + else if (GetCmdReplySource() == SM_REPLY_TO_CONSOLE) + { + C_RemoveTags(szCMessage, sizeof(szCMessage)); + PrintToConsole(client, "%s", szCMessage); + } + else + { + C_PrintToChat(client, "%s", szCMessage); + } +} + +/** + * Reples to a message in a command. A client index of 0 will use PrintToServer(). + * If the command was from the console, PrintToConsole() is used. If the command was from chat, C_PrintToChat() is used. + * Supports color tags. + * + * @param client Client index, or 0 for server. + * @param author Author index whose color will be used for teamcolor tag. + * @param szMessage Formatting rules. + * @param ... Variable number of format parameters. + * @return No return + * + * On error/Errors: If the client is not connected or invalid. + */ +stock void C_ReplyToCommandEx(int client, int author, const char[] szMessage, any ...) +{ + char szCMessage[MAX_MESSAGE_LENGTH]; + SetGlobalTransTarget(client); + VFormat(szCMessage, sizeof(szCMessage), szMessage, 4); + + if (client == 0) + { + C_RemoveTags(szCMessage, sizeof(szCMessage)); + PrintToServer("%s", szCMessage); + } + else if (GetCmdReplySource() == SM_REPLY_TO_CONSOLE) + { + C_RemoveTags(szCMessage, sizeof(szCMessage)); + PrintToConsole(client, "%s", szCMessage); + } + else + { + C_PrintToChatEx(client, author, "%s", szCMessage); + } +} + +/** + * Prints a message to all clients in the chat area. + * Supports color tags. + * + * @param client Client index. + * @param szMessage Message (formatting rules) + * @return No return + */ +stock void C_PrintToChatAll(const char[] szMessage, any ...) +{ + char szBuffer[MAX_MESSAGE_LENGTH]; + + MuCo_LoopClients(i) + { + if (i > 0 && IsClientInGame(i) && !IsFakeClient(i) && !C_SkipList[i]) + { + SetGlobalTransTarget(i); + VFormat(szBuffer, sizeof(szBuffer), szMessage, 2); + + C_PrintToChat(i, "%s", szBuffer); + } + + C_SkipList[i] = false; + } +} + +/** + * Prints a message to a specific client in the chat area. + * Supports color tags and teamcolor tag. + * + * @param client Client index. + * @param author Author index whose color will be used for teamcolor tag. + * @param szMessage Message (formatting rules). + * @return No return + * + * On error/Errors: If the client or author are not connected an error will be thrown. + */ +stock void C_PrintToChatEx(int client, int author, const char[] szMessage, any ...) +{ + if (client <= 0 || client > MaxClients) + ThrowError("Invalid client index %d", client); + + if (!IsClientInGame(client)) + ThrowError("Client %d is not in game", client); + + if (author < 0 || author > MaxClients) + ThrowError("Invalid client index %d", author); + + char szBuffer[MAX_MESSAGE_LENGTH]; + char szCMessage[MAX_MESSAGE_LENGTH]; + + SetGlobalTransTarget(client); + + Format(szBuffer, sizeof(szBuffer), "\x01%s", szMessage); + VFormat(szCMessage, sizeof(szCMessage), szBuffer, 4); + + int index = C_Format(szCMessage, sizeof(szCMessage), author); + + if (index == NO_INDEX) + PrintToChat(client, "%s", szCMessage); + else + C_SayText2(client, author, szCMessage); +} + +/** + * Prints a message to all clients in the chat area. + * Supports color tags and teamcolor tag. + * + * @param author Author index whos color will be used for teamcolor tag. + * @param szMessage Message (formatting rules). + * @return No return + * + * On error/Errors: If the author is not connected an error will be thrown. + */ +stock void C_PrintToChatAllEx(int author, const char[] szMessage, any ...) +{ + if (author < 0 || author > MaxClients) + ThrowError("Invalid client index %d", author); + + if (!IsClientInGame(author)) + ThrowError("Client %d is not in game", author); + + char szBuffer[MAX_MESSAGE_LENGTH]; + + MuCo_LoopClients(i) + { + if (i > 0 && IsClientInGame(i) && !IsFakeClient(i) && !C_SkipList[i]) + { + SetGlobalTransTarget(i); + VFormat(szBuffer, sizeof(szBuffer), szMessage, 3); + + C_PrintToChatEx(i, author, "%s", szBuffer); + } + + C_SkipList[i] = false; + } +} + +/** + * Removes color tags from the string. + * + * @param szMessage String. + * @return No return + */ +stock void C_RemoveTags(char[] szMessage, int maxlength) +{ + for (int i = 0; i < MAX_COLORS; i++) + ReplaceString(szMessage, maxlength, C_Tag[i], "", false); + + ReplaceString(szMessage, maxlength, "{teamcolor}", "", false); +} + +/** + * Checks whether a color is allowed or not + * + * @param tag Color Tag. + * @return True when color is supported, otherwise false + */ +stock bool C_ColorAllowed(C_Colors color) +{ + if (!C_EventIsHooked) + { + C_SetupProfile(); + + C_EventIsHooked = true; + } + + return C_Profile_Colors[color]; +} + +/** + * Replace the color with another color + * Handle with care! + * + * @param color color to replace. + * @param newColor color to replace with. + * @noreturn + */ +stock void C_ReplaceColor(C_Colors color, C_Colors newColor) +{ + if (!C_EventIsHooked) + { + C_SetupProfile(); + + C_EventIsHooked = true; + } + + C_Profile_Colors[color] = C_Profile_Colors[newColor]; + C_Profile_TeamIndex[color] = C_Profile_TeamIndex[newColor]; + + C_TagReqSayText2[color] = C_TagReqSayText2[newColor]; + Format(C_TagCode[color], sizeof(C_TagCode[]), C_TagCode[newColor]); +} + +/** + * This function should only be used right in front of + * C_PrintToChatAll or C_PrintToChatAllEx and it tells + * to those funcions to skip specified client when printing + * message to all clients. After message is printed client will + * no more be skipped. + * + * @param client Client index + * @return No return + */ +stock void C_SkipNextClient(int client) +{ + if (client <= 0 || client > MaxClients) + ThrowError("Invalid client index %d", client); + + C_SkipList[client] = true; +} + +/** + * Replaces color tags in a string with color codes + * + * @param szMessage String. + * @param maxlength Maximum length of the string buffer. + * @return Client index that can be used for SayText2 author index + * + * On error/Errors: If there is more then one team color is used an error will be thrown. + */ +stock int C_Format(char[] szMessage, int maxlength, int author = NO_INDEX) +{ + /* Hook event for auto profile setup on map start */ + if (!C_EventIsHooked) + { + C_SetupProfile(); + HookEvent("server_spawn", C_Event_MapStart, EventHookMode_PostNoCopy); + + C_EventIsHooked = true; + } + + int iRandomPlayer = NO_INDEX; + + // On CS:GO set invisible precolor + if (GetEngineVersion() == Engine_CSGO) + { + Format(szMessage, maxlength, " %s", szMessage); + } + + /* If author was specified replace {teamcolor} tag */ + if (author != NO_INDEX) + { + if (C_Profile_SayText2) + { + ReplaceString(szMessage, maxlength, "{teamcolor}", "\x03", false); + + iRandomPlayer = author; + } + /* If saytext2 is not supported by game replace {teamcolor} with green tag */ + else + ReplaceString(szMessage, maxlength, "{teamcolor}", C_TagCode[Color_Green], false); + } + else + ReplaceString(szMessage, maxlength, "{teamcolor}", "", false); + + /* For other color tags we need a loop */ + for (int i = 0; i < MAX_COLORS; i++) + { + /* If tag not found - skip */ + if (StrContains(szMessage, C_Tag[i], false) == -1) + continue; + + /* If tag is not supported by game replace it with green tag */ + else if (!C_Profile_Colors[i]) + ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[Color_Green], false); + + /* If tag doesn't need saytext2 simply replace */ + else if (!C_TagReqSayText2[i]) + ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[i], false); + + /* Tag needs saytext2 */ + else + { + /* If saytext2 is not supported by game replace tag with green tag */ + if (!C_Profile_SayText2) + ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[Color_Green], false); + + /* Game supports saytext2 */ + else + { + /* If random player for tag wasn't specified replace tag and find player */ + if (iRandomPlayer == NO_INDEX) + { + /* Searching for valid client for tag */ + iRandomPlayer = C_FindRandomPlayerByTeam(C_Profile_TeamIndex[i]); + + /* If player not found replace tag with green color tag */ + if (iRandomPlayer == NO_PLAYER) + ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[Color_Green], false); + + /* If player was found simply replace */ + else + ReplaceString(szMessage, maxlength, C_Tag[i], C_TagCode[i], false); + + } + /* If found another team color tag throw error */ + else + { + //ReplaceString(szMessage, maxlength, C_Tag[i], ""); + ThrowError("Using two team colors in one message is not allowed"); + } + } + + } + } + + return iRandomPlayer; +} + +/** + * Founds a random player with specified team + * + * @param color_team Client team. + * @return Client index or NO_PLAYER if no player found + */ +stock int C_FindRandomPlayerByTeam(int color_team) +{ + if (color_team == SERVER_INDEX) + return 0; + else + { + MuCo_LoopClients(i) + { + if (i > 0 && IsClientInGame(i) && GetClientTeam(i) == color_team) + return i; + } + } + + return NO_PLAYER; +} + +/** + * Sends a SayText2 usermessage to a client + * + * @param szMessage Client index + * @param maxlength Author index + * @param szMessage Message + * @return No return. + */ +stock void C_SayText2(int client, int author, const char[] szMessage) +{ + Handle hBuffer = StartMessageOne("SayText2", client, USERMSG_RELIABLE|USERMSG_BLOCKHOOKS); + + if(GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && GetUserMessageType() == UM_Protobuf) + { + PbSetInt(hBuffer, "ent_idx", author); + PbSetBool(hBuffer, "chat", true); + PbSetString(hBuffer, "msg_name", szMessage); + PbAddString(hBuffer, "params", ""); + PbAddString(hBuffer, "params", ""); + PbAddString(hBuffer, "params", ""); + PbAddString(hBuffer, "params", ""); + } + else + { + BfWriteByte(hBuffer, author); + BfWriteByte(hBuffer, true); + BfWriteString(hBuffer, szMessage); + } + + EndMessage(); +} + +/** + * Creates game color profile + * This function must be edited if you want to add more games support + * + * @return No return. + */ +stock void C_SetupProfile() +{ + EngineVersion engine = GetEngineVersion(); + + if (engine == Engine_CSS) + { + C_Profile_Colors[Color_Lightgreen] = true; + C_Profile_Colors[Color_Red] = true; + C_Profile_Colors[Color_Blue] = true; + C_Profile_Colors[Color_Olive] = true; + C_Profile_TeamIndex[Color_Lightgreen] = SERVER_INDEX; + C_Profile_TeamIndex[Color_Red] = 2; + C_Profile_TeamIndex[Color_Blue] = 3; + C_Profile_SayText2 = true; + } + else if (engine == Engine_CSGO) + { + C_Profile_Colors[Color_Red] = true; + C_Profile_Colors[Color_Blue] = true; + C_Profile_Colors[Color_Olive] = true; + C_Profile_Colors[Color_Darkred] = true; + C_Profile_Colors[Color_Lime] = true; + C_Profile_Colors[Color_Lightred] = true; + C_Profile_Colors[Color_Purple] = true; + C_Profile_Colors[Color_Grey] = true; + C_Profile_Colors[Color_Yellow] = true; + C_Profile_Colors[Color_Orange] = true; + C_Profile_Colors[Color_Bluegrey] = true; + C_Profile_Colors[Color_Lightblue] = true; + C_Profile_Colors[Color_Darkblue] = true; + C_Profile_Colors[Color_Grey2] = true; + C_Profile_Colors[Color_Orchid] = true; + C_Profile_Colors[Color_Lightred2] = true; + C_Profile_TeamIndex[Color_Red] = 2; + C_Profile_TeamIndex[Color_Blue] = 3; + C_Profile_SayText2 = true; + } + else if (engine == Engine_TF2) + { + C_Profile_Colors[Color_Lightgreen] = true; + C_Profile_Colors[Color_Red] = true; + C_Profile_Colors[Color_Blue] = true; + C_Profile_Colors[Color_Olive] = true; + C_Profile_TeamIndex[Color_Lightgreen] = SERVER_INDEX; + C_Profile_TeamIndex[Color_Red] = 2; + C_Profile_TeamIndex[Color_Blue] = 3; + C_Profile_SayText2 = true; + } + else if (engine == Engine_Left4Dead || engine == Engine_Left4Dead2) + { + C_Profile_Colors[Color_Lightgreen] = true; + C_Profile_Colors[Color_Red] = true; + C_Profile_Colors[Color_Blue] = true; + C_Profile_Colors[Color_Olive] = true; + C_Profile_TeamIndex[Color_Lightgreen] = SERVER_INDEX; + C_Profile_TeamIndex[Color_Red] = 3; + C_Profile_TeamIndex[Color_Blue] = 2; + C_Profile_SayText2 = true; + } + else if (engine == Engine_HL2DM) + { + /* hl2mp profile is based on mp_teamplay convar */ + if (GetConVarBool(FindConVar("mp_teamplay"))) + { + C_Profile_Colors[Color_Red] = true; + C_Profile_Colors[Color_Blue] = true; + C_Profile_Colors[Color_Olive] = true; + C_Profile_TeamIndex[Color_Red] = 3; + C_Profile_TeamIndex[Color_Blue] = 2; + C_Profile_SayText2 = true; + } + else + { + C_Profile_SayText2 = false; + C_Profile_Colors[Color_Olive] = true; + } + } + else if (engine == Engine_DODS) + { + C_Profile_Colors[Color_Olive] = true; + C_Profile_SayText2 = false; + } + /* Profile for other games */ + else + { + if (GetUserMessageId("SayText2") == INVALID_MESSAGE_ID) + { + C_Profile_SayText2 = false; + } + else + { + C_Profile_Colors[Color_Red] = true; + C_Profile_Colors[Color_Blue] = true; + C_Profile_TeamIndex[Color_Red] = 2; + C_Profile_TeamIndex[Color_Blue] = 3; + C_Profile_SayText2 = true; + } + } +} + +public Action C_Event_MapStart(Event event, const char[] name, bool dontBroadcast) +{ + C_SetupProfile(); + + MuCo_LoopClients(i) + C_SkipList[i] = false; +} + +/** + * Displays usage of an admin command to users depending on the + * setting of the sm_show_activity cvar. + * + * This version does not display a message to the originating client + * if used from chat triggers or menus. If manual replies are used + * for these cases, then this function will suffice. Otherwise, + * C_ShowActivity2() is slightly more useful. + * Supports color tags. + * + * @param client Client index doing the action, or 0 for server. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @noreturn + * @error + */ +stock int C_ShowActivity(int client, const char[] format, any ...) +{ + if (sm_show_activity == null) + sm_show_activity = FindConVar("sm_show_activity"); + + char tag[] = "[SM] "; + + char szBuffer[MAX_MESSAGE_LENGTH]; + //char szCMessage[MAX_MESSAGE_LENGTH]; + int value = GetConVarInt(sm_show_activity); + ReplySource replyto = GetCmdReplySource(); + + char name[MAX_NAME_LENGTH] = "Console"; + char sign[MAX_NAME_LENGTH] = "ADMIN"; + bool display_in_chat = false; + if (client != 0) + { + if (client < 0 || client > MaxClients || !IsClientConnected(client)) + ThrowError("Client index %d is invalid", client); + + GetClientName(client, name, sizeof(name)); + AdminId id = GetUserAdmin(client); + if (id == INVALID_ADMIN_ID + || !GetAdminFlag(id, Admin_Generic, Access_Effective)) + { + sign = "PLAYER"; + } + + /* Display the message to the client? */ + if (replyto == SM_REPLY_TO_CONSOLE) + { + SetGlobalTransTarget(client); + VFormat(szBuffer, sizeof(szBuffer), format, 3); + + C_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToConsole(client, "%s%s\n", tag, szBuffer); + display_in_chat = true; + } + } + else + { + SetGlobalTransTarget(LANG_SERVER); + VFormat(szBuffer, sizeof(szBuffer), format, 3); + + C_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToServer("%s%s\n", tag, szBuffer); + } + + if (!value) + { + return 1; + } + + MuCo_LoopClients(i) + { + if (i == 0 + || !IsClientInGame(i) + || IsFakeClient(i) + || (display_in_chat && i == client)) + { + continue; + } + AdminId id = GetUserAdmin(i); + SetGlobalTransTarget(i); + if (id == INVALID_ADMIN_ID + || !GetAdminFlag(id, Admin_Generic, Access_Effective)) + { + /* Treat this as a normal user. */ + if ((value & 1) | (value & 2)) + { + char newsign[MAX_NAME_LENGTH]; + newsign = sign; + if ((value & 2) || (i == client)) + { + newsign = name; + } + VFormat(szBuffer, sizeof(szBuffer), format, 3); + + C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + else + { + /* Treat this as an admin user */ + bool is_root = GetAdminFlag(id, Admin_Root, Access_Effective); + if ((value & 4) + || (value & 8) + || ((value & 16) && is_root)) + { + char newsign[MAX_NAME_LENGTH]; + newsign = sign; + if ((value & 8) || ((value & 16) && is_root) || (i == client)) + { + newsign = name; + } + VFormat(szBuffer, sizeof(szBuffer), format, 3); + + C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + } + + return 1; +} + +/** + * Same as C_ShowActivity(), except the tag parameter is used instead of "[SM] " (note that you must supply any spacing). + * Supports color tags. + * + * @param client Client index doing the action, or 0 for server. + * @param tags Tag to display with. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @noreturn + * @error + */ +stock int C_ShowActivityEx(int client, const char[] tag, const char[] format, any ...) +{ + if (sm_show_activity == null) + sm_show_activity = FindConVar("sm_show_activity"); + + char szBuffer[MAX_MESSAGE_LENGTH]; + //char szCMessage[MAX_MESSAGE_LENGTH]; + int value = GetConVarInt(sm_show_activity); + ReplySource replyto = GetCmdReplySource(); + + char name[MAX_NAME_LENGTH] = "Console"; + char sign[MAX_NAME_LENGTH] = "ADMIN"; + bool display_in_chat = false; + if (client != 0) + { + if (client < 0 || client > MaxClients || !IsClientConnected(client)) + ThrowError("Client index %d is invalid", client); + + GetClientName(client, name, sizeof(name)); + AdminId id = GetUserAdmin(client); + if (id == INVALID_ADMIN_ID + || !GetAdminFlag(id, Admin_Generic, Access_Effective)) + { + sign = "PLAYER"; + } + + /* Display the message to the client? */ + if (replyto == SM_REPLY_TO_CONSOLE) + { + SetGlobalTransTarget(client); + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + C_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToConsole(client, "%s%s\n", tag, szBuffer); + display_in_chat = true; + } + } + else + { + SetGlobalTransTarget(LANG_SERVER); + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + C_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToServer("%s%s\n", tag, szBuffer); + } + + if (!value) + { + return 1; + } + + MuCo_LoopClients(i) + { + if (i == 0 + || !IsClientInGame(i) + || IsFakeClient(i) + || (display_in_chat && i == client)) + { + continue; + } + AdminId id = GetUserAdmin(i); + SetGlobalTransTarget(i); + if (id == INVALID_ADMIN_ID + || !GetAdminFlag(id, Admin_Generic, Access_Effective)) + { + /* Treat this as a normal user. */ + if ((value & 1) | (value & 2)) + { + char newsign[MAX_NAME_LENGTH]; + newsign = sign; + if ((value & 2) || (i == client)) + { + newsign = name; + } + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + else + { + /* Treat this as an admin user */ + bool is_root = GetAdminFlag(id, Admin_Root, Access_Effective); + if ((value & 4) + || (value & 8) + || ((value & 16) && is_root)) + { + char newsign[MAX_NAME_LENGTH]; + newsign = sign; + if ((value & 8) || ((value & 16) && is_root) || (i == client)) + { + newsign = name; + } + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + } + + return 1; +} + +/** + * Displays usage of an admin command to users depending on the setting of the sm_show_activity cvar. + * All users receive a message in their chat text, except for the originating client, + * who receives the message based on the current ReplySource. + * Supports color tags. + * + * @param client Client index doing the action, or 0 for server. + * @param tags Tag to prepend to the message. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @noreturn + * @error + */ +stock int C_ShowActivity2(int client, const char[] tag, const char[] format, any ...) +{ + if (sm_show_activity == null) + sm_show_activity = FindConVar("sm_show_activity"); + + char szBuffer[MAX_MESSAGE_LENGTH]; + //char szCMessage[MAX_MESSAGE_LENGTH]; + int value = GetConVarInt(sm_show_activity); + // ReplySource replyto = GetCmdReplySource(); + + char name[MAX_NAME_LENGTH] = "Console"; + char sign[MAX_NAME_LENGTH] = "ADMIN"; + if (client != 0) + { + if (client < 0 || client > MaxClients || !IsClientConnected(client)) + ThrowError("Client index %d is invalid", client); + + GetClientName(client, name, sizeof(name)); + AdminId id = GetUserAdmin(client); + if (id == INVALID_ADMIN_ID + || !GetAdminFlag(id, Admin_Generic, Access_Effective)) + { + sign = "PLAYER"; + } + + SetGlobalTransTarget(client); + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + /* We don't display directly to the console because the chat text + * simply gets added to the console, so we don't want it to print + * twice. + */ + C_PrintToChatEx(client, client, "%s%s", tag, szBuffer); + } + else + { + SetGlobalTransTarget(LANG_SERVER); + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + C_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToServer("%s%s\n", tag, szBuffer); + } + + if (!value) + { + return 1; + } + + MuCo_LoopClients(i) + { + if (i == 0 + || !IsClientInGame(i) + || IsFakeClient(i) + || i == client) + { + continue; + } + AdminId id = GetUserAdmin(i); + SetGlobalTransTarget(i); + if (id == INVALID_ADMIN_ID + || !GetAdminFlag(id, Admin_Generic, Access_Effective)) + { + /* Treat this as a normal user. */ + if ((value & 1) | (value & 2)) + { + char newsign[MAX_NAME_LENGTH]; + newsign = sign; + if ((value & 2)) + { + newsign = name; + } + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + else + { + /* Treat this as an admin user */ + bool is_root = GetAdminFlag(id, Admin_Root, Access_Effective); + if ((value & 4) + || (value & 8) + || ((value & 16) && is_root)) + { + char newsign[MAX_NAME_LENGTH]; + newsign = sign; + if ((value & 8) || ((value & 16) && is_root)) + { + newsign = name; + } + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + C_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + } + + return 1; +} diff --git a/addons/sourcemod/scripting/include/multicolors/morecolors.inc b/addons/sourcemod/scripting/include/multicolors/morecolors.inc new file mode 100644 index 0000000..f609632 --- /dev/null +++ b/addons/sourcemod/scripting/include/multicolors/morecolors.inc @@ -0,0 +1,959 @@ +// MOAR COLORS +// By Dr. McKay +// Inspired by: https://forums.alliedmods.net/showthread.php?t=96831 + +#if defined _more_colors_included + #endinput +#endif +#define _more_colors_included + +#pragma newdecls optional +#include + +#define MORE_COLORS_VERSION "2.0.0-MC" +#define MC_MAX_MESSAGE_LENGTH 256 +#define MAX_BUFFER_LENGTH (MC_MAX_MESSAGE_LENGTH * 4) + +#define MCOLOR_RED 0xFF4040 +#define MCOLOR_BLUE 0x99CCFF +#define MCOLOR_GRAY 0xCCCCCC +#define MCOLOR_GREEN 0x3EFF3E + +#define MC_GAME_DODS 0 + +bool MC_SkipList[MAXPLAYERS + 1]; +Handle MC_Trie; +int MC_TeamColors[][] = {{0xCCCCCC, 0x4D7942, 0xFF4040}}; // Multi-dimensional array for games that don't support SayText2. First index is the game index (as defined by the GAME_ defines), second index is team. 0 = spectator, 1 = team1, 2 = team2 + +static Handle sm_show_activity = INVALID_HANDLE; + +/** + * Prints a message to a specific client in the chat area. + * Supports color tags. + * + * @param client Client index. + * @param message Message (formatting rules). + * + * On error/Errors: If the client is not connected an error will be thrown. + */ +stock void MC_PrintToChat(int client, const char[] message, any ...) { + MC_CheckTrie(); + if(client <= 0 || client > MaxClients) { + ThrowError("Invalid client index %i", client); + } + if(!IsClientInGame(client)) { + ThrowError("Client %i is not in game", client); + } + char buffer[MAX_BUFFER_LENGTH], buffer2[MAX_BUFFER_LENGTH]; + SetGlobalTransTarget(client); + Format(buffer, sizeof(buffer), "\x01%s", message); + VFormat(buffer2, sizeof(buffer2), buffer, 3); + MC_ReplaceColorCodes(buffer2); + MC_SendMessage(client, buffer2); +} + +/** + * Prints a message to all clients in the chat area. + * Supports color tags. + * + * @param client Client index. + * @param message Message (formatting rules). + */ +stock void MC_PrintToChatAll(const char[] message, any ...) { + MC_CheckTrie(); + char buffer[MAX_BUFFER_LENGTH], buffer2[MAX_BUFFER_LENGTH]; + MuCo_LoopClients(i) { + if(i == 0 || !IsClientInGame(i) || MC_SkipList[i]) { + MC_SkipList[i] = false; + continue; + } + SetGlobalTransTarget(i); + Format(buffer, sizeof(buffer), "\x01%s", message); + VFormat(buffer2, sizeof(buffer2), buffer, 2); + MC_ReplaceColorCodes(buffer2); + MC_SendMessage(i, buffer2); + } +} + +/** + * Prints a message to a specific client in the chat area. + * Supports color tags and teamcolor tag. + * + * @param client Client index. + * @param author Author index whose color will be used for teamcolor tag. + * @param message Message (formatting rules). + * + * On error/Errors: If the client or author are not connected an error will be thrown + */ +stock void MC_PrintToChatEx(int client, int author, const char[] message, any ...) { + MC_CheckTrie(); + if(client <= 0 || client > MaxClients) { + ThrowError("Invalid client index %i", client); + } + if(!IsClientInGame(client)) { + ThrowError("Client %i is not in game", client); + } + if(author <= 0 || author > MaxClients) { + ThrowError("Invalid client index %i", author); + } + if(!IsClientInGame(author)) { + ThrowError("Client %i is not in game", author); + } + char buffer[MAX_BUFFER_LENGTH], buffer2[MAX_BUFFER_LENGTH]; + SetGlobalTransTarget(client); + Format(buffer, sizeof(buffer), "\x01%s", message); + VFormat(buffer2, sizeof(buffer2), buffer, 4); + MC_ReplaceColorCodes(buffer2, author); + MC_SendMessage(client, buffer2, author); +} + +/** + * Prints a message to all clients in the chat area. + * Supports color tags and teamcolor tag. + * + * @param author Author index whose color will be used for teamcolor tag. + * @param message Message (formatting rules). + * + * On error/Errors: If the author is not connected an error will be thrown. + */ +stock void MC_PrintToChatAllEx(int author, const char[] message, any ...) { + MC_CheckTrie(); + if(author <= 0 || author > MaxClients) { + ThrowError("Invalid client index %i", author); + } + if(!IsClientInGame(author)) { + ThrowError("Client %i is not in game", author); + } + char buffer[MAX_BUFFER_LENGTH], buffer2[MAX_BUFFER_LENGTH]; + MuCo_LoopClients(i) { + if(i == 0 || !IsClientInGame(i) || MC_SkipList[i]) { + MC_SkipList[i] = false; + continue; + } + SetGlobalTransTarget(i); + Format(buffer, sizeof(buffer), "\x01%s", message); + VFormat(buffer2, sizeof(buffer2), buffer, 3); + MC_ReplaceColorCodes(buffer2, author); + MC_SendMessage(i, buffer2, author); + } +} + +/** + * Sends a SayText2 usermessage + * + * @param client Client to send usermessage to + * @param message Message to send + */ +stock void MC_SendMessage(int client, const char[] message, int author = 0) { + if(author == 0) { + author = client; + } + char buffer[MC_MAX_MESSAGE_LENGTH]; + strcopy(buffer, sizeof(buffer), message); + UserMsg index = GetUserMessageId("SayText2"); + if(index == INVALID_MESSAGE_ID) { + if(GetEngineVersion() == Engine_DODS) { + int team = GetClientTeam(author); + if(team == 0) { + ReplaceString(buffer, sizeof(buffer), "\x03", "\x04", false); // Unassigned gets green + } else { + char temp[16]; + Format(temp, sizeof(temp), "\x07%06X", MC_TeamColors[MC_GAME_DODS][team - 1]); + ReplaceString(buffer, sizeof(buffer), "\x03", temp, false); + } + } + PrintToChat(client, "%s", buffer); + return; + } + Handle buf = StartMessageOne("SayText2", client, USERMSG_RELIABLE|USERMSG_BLOCKHOOKS); + if(GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && GetUserMessageType() == UM_Protobuf) { + PbSetInt(buf, "ent_idx", author); + PbSetBool(buf, "chat", true); + PbSetString(buf, "msg_name", buffer); + PbAddString(buf, "params", ""); + PbAddString(buf, "params", ""); + PbAddString(buf, "params", ""); + PbAddString(buf, "params", ""); + } else { + BfWriteByte(buf, author); // Message author + BfWriteByte(buf, true); // Chat message + BfWriteString(buf, buffer); // Message text + } + EndMessage(); +} + +/** + * This function should only be used right in front of + * MC_PrintToChatAll or MC_PrintToChatAllEx. It causes those functions + * to skip the specified client when printing the message. + * After printing the message, the client will no longer be skipped. + * + * @param client Client index + */ +stock void MC_SkipNextClient(int client) { + if(client <= 0 || client > MaxClients) { + ThrowError("Invalid client index %i", client); + } + MC_SkipList[client] = true; +} + +/** + * Checks if the colors trie is initialized and initializes it if it's not (used internally) + * + * @return No return + */ +stock void MC_CheckTrie() { + if(MC_Trie == INVALID_HANDLE) { + MC_Trie = MC_InitColorTrie(); + } +} + +/** + * Replaces color tags in a string with color codes (used internally by MC_PrintToChat, MC_PrintToChatAll, MC_PrintToChatEx, and MC_PrintToChatAllEx + * + * @param buffer String. + * @param author Optional client index to use for {teamcolor} tags, or 0 for none + * @param removeTags Optional boolean value to determine whether we're replacing tags with colors, or just removing tags, used by MC_RemoveTags + * @param maxlen Optional value for max buffer length, used by MC_RemoveTags + * + * On error/Errors: If the client index passed for author is invalid or not in game. + */ +stock void MC_ReplaceColorCodes(char[] buffer, int author = 0, bool removeTags = false, int maxlen = MAX_BUFFER_LENGTH) { + MC_CheckTrie(); + if(!removeTags) { + ReplaceString(buffer, maxlen, "{default}", "\x01", false); + } else { + ReplaceString(buffer, maxlen, "{default}", "", false); + ReplaceString(buffer, maxlen, "{teamcolor}", "", false); + } + if(author != 0 && !removeTags) { + if(author < 0 || author > MaxClients) { + ThrowError("Invalid client index %i", author); + } + if(!IsClientInGame(author)) { + ThrowError("Client %i is not in game", author); + } + ReplaceString(buffer, maxlen, "{teamcolor}", "\x03", false); + } + int cursor = 0; + int value; + char tag[32], buff[32]; + char[] output = new char[maxlen]; + + strcopy(output, maxlen, buffer); + // Since the string's size is going to be changing, output will hold the replaced string and we'll search buffer + + Handle regex = CompileRegex("{[#a-zA-Z0-9]+}"); + for(int i = 0; i < 1000; i++) { // The RegEx extension is quite flaky, so we have to loop here :/. This loop is supposed to be infinite and broken by return, but conditions have been added to be safe. + if(MatchRegex(regex, buffer[cursor]) < 1) { + CloseHandle(regex); + strcopy(buffer, maxlen, output); + return; + } + GetRegexSubString(regex, 0, tag, sizeof(tag)); + MC_StrToLower(tag); + cursor = StrContains(buffer[cursor], tag, false) + cursor + 1; + strcopy(buff, sizeof(buff), tag); + ReplaceString(buff, sizeof(buff), "{", ""); + ReplaceString(buff, sizeof(buff), "}", ""); + + if (buff[0] == '#') { + if(strlen(buff) == 7) { + Format(buff, sizeof(buff), "\x07%s", buff[1]); + } else if (strlen(buff) == 9) { + Format(buff, sizeof(buff), "\x08%s", buff[1]); + } else { + continue; + } + + if (removeTags) { + ReplaceString(output, maxlen, tag, "", false); + } else { + ReplaceString(output, maxlen, tag, buff, false); + } + } else if(!GetTrieValue(MC_Trie, buff, value)) { + continue; + } + + if(removeTags) { + ReplaceString(output, maxlen, tag, "", false); + } else { + Format(buff, sizeof(buff), "\x07%06X", value); + ReplaceString(output, maxlen, tag, buff, false); + } + } + LogError("[MORE COLORS] Infinite loop broken."); +} + +/** + * Gets a part of a string + * + * @param input String to get the part from + * @param output Buffer to write to + * @param maxlen Max length of output buffer + * @param start Position to start at + * @param numChars Number of characters to return, or 0 for the end of the string + */ +stock void CSubString(const char[] input, char[] output, int maxlen, int start, int numChars = 0) { + int i = 0; + for(;;) { + if(i == maxlen - 1 || i >= numChars || input[start + i] == '\0') { + output[i] = '\0'; + return; + } + output[i] = input[start + i]; + i++; + } +} + +/** + * Converts a string to lowercase + * + * @param buffer String to convert + */ +stock void MC_StrToLower(char[] buffer) { + int len = strlen(buffer); + for(int i = 0; i < len; i++) { + buffer[i] = CharToLower(buffer[i]); + } +} + +/** + * Adds a color to the colors trie + * + * @param name Color name, without braces + * @param color Hexadecimal representation of the color (0xRRGGBB) + * @return True if color was added successfully, false if a color already exists with that name + */ +stock bool MC_AddColor(const char[] name, int color) { + MC_CheckTrie(); + int value; + if(GetTrieValue(MC_Trie, name, value)) { + return false; + } + char newName[64]; + strcopy(newName, sizeof(newName), name); + MC_StrToLower(newName); + SetTrieValue(MC_Trie, newName, color); + return true; +} + +/** + * Removes color tags from a message + * + * @param message Message to remove tags from + * @param maxlen Maximum buffer length + */ +stock void MC_RemoveTags(char[] message, int maxlen) { + MC_ReplaceColorCodes(message, 0, true, maxlen); +} + +/** + * Replies to a command with colors + * + * @param client Client to reply to + * @param message Message (formatting rules) + */ +stock void MC_ReplyToCommand(int client, const char[] message, any ...) { + char buffer[MAX_BUFFER_LENGTH]; + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), message, 3); + if(client == 0) { + MC_RemoveTags(buffer, sizeof(buffer)); + PrintToServer("%s", buffer); + } if(GetCmdReplySource() == SM_REPLY_TO_CONSOLE) { + MC_RemoveTags(buffer, sizeof(buffer)); + PrintToConsole(client, "%s", buffer); + } else { + MC_PrintToChat(client, "%s", buffer); + } +} + +/** + * Replies to a command with colors + * + * @param client Client to reply to + * @param author Client to use for {teamcolor} + * @param message Message (formatting rules) + */ +stock void MC_ReplyToCommandEx(int client, int author, const char[] message, any ...) { + char buffer[MAX_BUFFER_LENGTH]; + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), message, 4); + if(client == 0) { + MC_RemoveTags(buffer, sizeof(buffer)); + PrintToServer("%s", buffer); + } if(GetCmdReplySource() == SM_REPLY_TO_CONSOLE) { + MC_RemoveTags(buffer, sizeof(buffer)); + PrintToConsole(client, "%s", buffer); + } else { + MC_PrintToChatEx(client, author, "%s", buffer); + } +} + +/** + * Displays usage of an admin command to users depending on the + * setting of the sm_show_activity cvar. + * + * This version does not display a message to the originating client + * if used from chat triggers or menus. If manual replies are used + * for these cases, then this function will suffice. Otherwise, + * MC_ShowActivity2() is slightly more useful. + * Supports color tags. + * + * @param client Client index doing the action, or 0 for server. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @error + */ +stock int MC_ShowActivity(int client, const char[] format, any ...) +{ + if (sm_show_activity == INVALID_HANDLE) + sm_show_activity = FindConVar("sm_show_activity"); + + char tag[] = "[SM] "; + + char szBuffer[MC_MAX_MESSAGE_LENGTH]; + //char szCMessage[MC_MAX_MESSAGE_LENGTH]; + int value = GetConVarInt(sm_show_activity); + ReplySource replyto = GetCmdReplySource(); + + char name[MAX_NAME_LENGTH] = "Console"; + char sign[MAX_NAME_LENGTH] = "ADMIN"; + bool display_in_chat = false; + if (client != 0) + { + if (client < 0 || client > MaxClients || !IsClientConnected(client)) + ThrowError("Client index %d is invalid", client); + + GetClientName(client, name, sizeof(name)); + AdminId id = GetUserAdmin(client); + if (id == INVALID_ADMIN_ID + || !GetAdminFlag(id, Admin_Generic, Access_Effective)) + { + sign = "PLAYER"; + } + + /* Display the message to the client? */ + if (replyto == SM_REPLY_TO_CONSOLE) + { + SetGlobalTransTarget(client); + VFormat(szBuffer, sizeof(szBuffer), format, 3); + + MC_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToConsole(client, "%s%s\n", tag, szBuffer); + display_in_chat = true; + } + } + else + { + SetGlobalTransTarget(LANG_SERVER); + VFormat(szBuffer, sizeof(szBuffer), format, 3); + + MC_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToServer("%s%s\n", tag, szBuffer); + } + + if (!value) + { + return 1; + } + + MuCo_LoopClients(i) + { + if (i == 0 + || !IsClientInGame(i) + || IsFakeClient(i) + || (display_in_chat && i == client)) + { + continue; + } + AdminId id = GetUserAdmin(i); + SetGlobalTransTarget(i); + if (id == INVALID_ADMIN_ID + || !GetAdminFlag(id, Admin_Generic, Access_Effective)) + { + /* Treat this as a normal user. */ + if ((value & 1) | (value & 2)) + { + char newsign[MAX_NAME_LENGTH]; + newsign = sign; + if ((value & 2) || (i == client)) + { + newsign = name; + } + VFormat(szBuffer, sizeof(szBuffer), format, 3); + + MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + else + { + /* Treat this as an admin user */ + bool is_root = GetAdminFlag(id, Admin_Root, Access_Effective); + if ((value & 4) + || (value & 8) + || ((value & 16) && is_root)) + { + char newsign[MAX_NAME_LENGTH]; + newsign = sign; + if ((value & 8) || ((value & 16) && is_root) || (i == client)) + { + newsign = name; + } + VFormat(szBuffer, sizeof(szBuffer), format, 3); + + MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + } + + return 1; +} + +/** + * Same as MC_ShowActivity(), except the tag parameter is used instead of "[SM] " (note that you must supply any spacing). + * Supports color tags. + * + * @param client Client index doing the action, or 0 for server. + * @param tags Tag to display with. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @error + */ +stock int MC_ShowActivityEx(int client, const char[] tag, const char[] format, any ...) +{ + if (sm_show_activity == INVALID_HANDLE) + sm_show_activity = FindConVar("sm_show_activity"); + + char szBuffer[MC_MAX_MESSAGE_LENGTH]; + //char szCMessage[MC_MAX_MESSAGE_LENGTH]; + int value = GetConVarInt(sm_show_activity); + ReplySource replyto = GetCmdReplySource(); + + char name[MAX_NAME_LENGTH] = "Console"; + char sign[MAX_NAME_LENGTH] = "ADMIN"; + bool display_in_chat = false; + if (client != 0) + { + if (client < 0 || client > MaxClients || !IsClientConnected(client)) + ThrowError("Client index %d is invalid", client); + + GetClientName(client, name, sizeof(name)); + AdminId id = GetUserAdmin(client); + if (id == INVALID_ADMIN_ID + || !GetAdminFlag(id, Admin_Generic, Access_Effective)) + { + sign = "PLAYER"; + } + + /* Display the message to the client? */ + if (replyto == SM_REPLY_TO_CONSOLE) + { + SetGlobalTransTarget(client); + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + MC_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToConsole(client, "%s%s\n", tag, szBuffer); + display_in_chat = true; + } + } + else + { + SetGlobalTransTarget(LANG_SERVER); + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + MC_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToServer("%s%s\n", tag, szBuffer); + } + + if (!value) + { + return 1; + } + + MuCo_LoopClients(i) + { + if (i == 0 + || !IsClientInGame(i) + || IsFakeClient(i) + || (display_in_chat && i == client)) + { + continue; + } + AdminId id = GetUserAdmin(i); + SetGlobalTransTarget(i); + if (id == INVALID_ADMIN_ID + || !GetAdminFlag(id, Admin_Generic, Access_Effective)) + { + /* Treat this as a normal user. */ + if ((value & 1) | (value & 2)) + { + char newsign[MAX_NAME_LENGTH]; + newsign = sign; + if ((value & 2) || (i == client)) + { + newsign = name; + } + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + else + { + /* Treat this as an admin user */ + bool is_root = GetAdminFlag(id, Admin_Root, Access_Effective); + if ((value & 4) + || (value & 8) + || ((value & 16) && is_root)) + { + char newsign[MAX_NAME_LENGTH]; + newsign = sign; + if ((value & 8) || ((value & 16) && is_root) || (i == client)) + { + newsign = name; + } + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + } + + return 1; +} + +/** + * Displays usage of an admin command to users depending on the setting of the sm_show_activity cvar. + * All users receive a message in their chat text, except for the originating client, + * who receives the message based on the current ReplySource. + * Supports color tags. + * + * @param client Client index doing the action, or 0 for server. + * @param tags Tag to prepend to the message. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @error + */ +stock int MC_ShowActivity2(int client, const char[] tag, const char[] format, any ...) +{ + if (sm_show_activity == INVALID_HANDLE) + sm_show_activity = FindConVar("sm_show_activity"); + + char szBuffer[MC_MAX_MESSAGE_LENGTH]; + //char szCMessage[MC_MAX_MESSAGE_LENGTH]; + int value = GetConVarInt(sm_show_activity); + // ReplySource replyto = GetCmdReplySource(); + + char name[MAX_NAME_LENGTH] = "Console"; + char sign[MAX_NAME_LENGTH] = "ADMIN"; + if (client != 0) + { + if (client < 0 || client > MaxClients || !IsClientConnected(client)) + ThrowError("Client index %d is invalid", client); + + GetClientName(client, name, sizeof(name)); + AdminId id = GetUserAdmin(client); + if (id == INVALID_ADMIN_ID + || !GetAdminFlag(id, Admin_Generic, Access_Effective)) + { + sign = "PLAYER"; + } + + SetGlobalTransTarget(client); + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + /* We don't display directly to the console because the chat text + * simply gets added to the console, so we don't want it to print + * twice. + */ + MC_PrintToChatEx(client, client, "%s%s", tag, szBuffer); + } + else + { + SetGlobalTransTarget(LANG_SERVER); + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + MC_RemoveTags(szBuffer, sizeof(szBuffer)); + PrintToServer("%s%s\n", tag, szBuffer); + } + + if (!value) + { + return 1; + } + + MuCo_LoopClients(i) + { + if (i == 0 + || !IsClientInGame(i) + || IsFakeClient(i) + || i == client) + { + continue; + } + AdminId id = GetUserAdmin(i); + SetGlobalTransTarget(i); + if (id == INVALID_ADMIN_ID + || !GetAdminFlag(id, Admin_Generic, Access_Effective)) + { + /* Treat this as a normal user. */ + if ((value & 1) | (value & 2)) + { + char newsign[MAX_NAME_LENGTH]; + newsign = sign; + if ((value & 2)) + { + newsign = name; + } + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + else + { + /* Treat this as an admin user */ + bool is_root = GetAdminFlag(id, Admin_Root, Access_Effective); + if ((value & 4) + || (value & 8) + || ((value & 16) && is_root)) + { + char newsign[MAX_NAME_LENGTH]; + newsign = sign; + if ((value & 8) || ((value & 16) && is_root)) + { + newsign = name; + } + VFormat(szBuffer, sizeof(szBuffer), format, 4); + + MC_PrintToChatEx(i, client, "%s%s: %s", tag, newsign, szBuffer); + } + } + } + + return 1; +} + +/** + * Determines whether a color name exists + * + * @param color The color name to check + * @return True if the color exists, false otherwise + */ +stock bool CColorExists(const char[] color) { + MC_CheckTrie(); + int temp; + return GetTrieValue(MC_Trie, color, temp); +} + +/** + * Returns the hexadecimal representation of a client's team color (will NOT initialize the trie) + * + * @param client Client to get the team color for + * @return Client's team color in hexadecimal, or green if unknown + * On error/Errors: If the client index passed is invalid or not in game. + */ +stock int CGetTeamColor(int client) { + if(client <= 0 || client > MaxClients) { + ThrowError("Invalid client index %i", client); + } + if(!IsClientInGame(client)) { + ThrowError("Client %i is not in game", client); + } + int value; + switch(GetClientTeam(client)) { + case 1: { + value = MCOLOR_GRAY; + } + case 2: { + value = MCOLOR_RED; + } + case 3: { + value = MCOLOR_BLUE; + } + default: { + value = MCOLOR_GREEN; + } + } + return value; +} + +stock Handle MC_InitColorTrie() { + Handle hTrie = CreateTrie(); + SetTrieValue(hTrie, "aliceblue", 0xF0F8FF); + SetTrieValue(hTrie, "allies", 0x4D7942); // same as Allies team in DoD:S + SetTrieValue(hTrie, "ancient", 0xEB4B4B); // same as Ancient item rarity in Dota 2 + SetTrieValue(hTrie, "antiquewhite", 0xFAEBD7); + SetTrieValue(hTrie, "aqua", 0x00FFFF); + SetTrieValue(hTrie, "aquamarine", 0x7FFFD4); + SetTrieValue(hTrie, "arcana", 0xADE55C); // same as Arcana item rarity in Dota 2 + SetTrieValue(hTrie, "axis", 0xFF4040); // same as Axis team in DoD:S + SetTrieValue(hTrie, "azure", 0x007FFF); + SetTrieValue(hTrie, "beige", 0xF5F5DC); + SetTrieValue(hTrie, "bisque", 0xFFE4C4); + SetTrieValue(hTrie, "black", 0x000000); + SetTrieValue(hTrie, "blanchedalmond", 0xFFEBCD); + SetTrieValue(hTrie, "blue", 0x99CCFF); // same as BLU/Counter-Terrorist team color + SetTrieValue(hTrie, "blueviolet", 0x8A2BE2); + SetTrieValue(hTrie, "brown", 0xA52A2A); + SetTrieValue(hTrie, "burlywood", 0xDEB887); + SetTrieValue(hTrie, "cadetblue", 0x5F9EA0); + SetTrieValue(hTrie, "chartreuse", 0x7FFF00); + SetTrieValue(hTrie, "chocolate", 0xD2691E); + SetTrieValue(hTrie, "collectors", 0xAA0000); // same as Collector's item quality in TF2 + SetTrieValue(hTrie, "common", 0xB0C3D9); // same as Common item rarity in Dota 2 + SetTrieValue(hTrie, "community", 0x70B04A); // same as Community item quality in TF2 + SetTrieValue(hTrie, "coral", 0xFF7F50); + SetTrieValue(hTrie, "cornflowerblue", 0x6495ED); + SetTrieValue(hTrie, "cornsilk", 0xFFF8DC); + SetTrieValue(hTrie, "corrupted", 0xA32C2E); // same as Corrupted item quality in Dota 2 + SetTrieValue(hTrie, "crimson", 0xDC143C); + SetTrieValue(hTrie, "cyan", 0x00FFFF); + SetTrieValue(hTrie, "darkblue", 0x00008B); + SetTrieValue(hTrie, "darkcyan", 0x008B8B); + SetTrieValue(hTrie, "darkgoldenrod", 0xB8860B); + SetTrieValue(hTrie, "darkgray", 0xA9A9A9); + SetTrieValue(hTrie, "darkgrey", 0xA9A9A9); + SetTrieValue(hTrie, "darkgreen", 0x006400); + SetTrieValue(hTrie, "darkkhaki", 0xBDB76B); + SetTrieValue(hTrie, "darkmagenta", 0x8B008B); + SetTrieValue(hTrie, "darkolivegreen", 0x556B2F); + SetTrieValue(hTrie, "darkorange", 0xFF8C00); + SetTrieValue(hTrie, "darkorchid", 0x9932CC); + SetTrieValue(hTrie, "darkred", 0x8B0000); + SetTrieValue(hTrie, "darksalmon", 0xE9967A); + SetTrieValue(hTrie, "darkseagreen", 0x8FBC8F); + SetTrieValue(hTrie, "darkslateblue", 0x483D8B); + SetTrieValue(hTrie, "darkslategray", 0x2F4F4F); + SetTrieValue(hTrie, "darkslategrey", 0x2F4F4F); + SetTrieValue(hTrie, "darkturquoise", 0x00CED1); + SetTrieValue(hTrie, "darkviolet", 0x9400D3); + SetTrieValue(hTrie, "deeppink", 0xFF1493); + SetTrieValue(hTrie, "deepskyblue", 0x00BFFF); + SetTrieValue(hTrie, "dimgray", 0x696969); + SetTrieValue(hTrie, "dimgrey", 0x696969); + SetTrieValue(hTrie, "dodgerblue", 0x1E90FF); + SetTrieValue(hTrie, "exalted", 0xCCCCCD); // same as Exalted item quality in Dota 2 + SetTrieValue(hTrie, "firebrick", 0xB22222); + SetTrieValue(hTrie, "floralwhite", 0xFFFAF0); + SetTrieValue(hTrie, "forestgreen", 0x228B22); + SetTrieValue(hTrie, "frozen", 0x4983B3); // same as Frozen item quality in Dota 2 + SetTrieValue(hTrie, "fuchsia", 0xFF00FF); + SetTrieValue(hTrie, "fullblue", 0x0000FF); + SetTrieValue(hTrie, "fullred", 0xFF0000); + SetTrieValue(hTrie, "gainsboro", 0xDCDCDC); + SetTrieValue(hTrie, "genuine", 0x4D7455); // same as Genuine item quality in TF2 + SetTrieValue(hTrie, "ghostwhite", 0xF8F8FF); + SetTrieValue(hTrie, "gold", 0xFFD700); + SetTrieValue(hTrie, "goldenrod", 0xDAA520); + SetTrieValue(hTrie, "gray", 0xCCCCCC); // same as spectator team color + SetTrieValue(hTrie, "grey", 0xCCCCCC); + SetTrieValue(hTrie, "green", 0x3EFF3E); + SetTrieValue(hTrie, "greenyellow", 0xADFF2F); + SetTrieValue(hTrie, "haunted", 0x38F3AB); // same as Haunted item quality in TF2 + SetTrieValue(hTrie, "honeydew", 0xF0FFF0); + SetTrieValue(hTrie, "hotpink", 0xFF69B4); + SetTrieValue(hTrie, "immortal", 0xE4AE33); // same as Immortal item rarity in Dota 2 + SetTrieValue(hTrie, "indianred", 0xCD5C5C); + SetTrieValue(hTrie, "indigo", 0x4B0082); + SetTrieValue(hTrie, "ivory", 0xFFFFF0); + SetTrieValue(hTrie, "khaki", 0xF0E68C); + SetTrieValue(hTrie, "lavender", 0xE6E6FA); + SetTrieValue(hTrie, "lavenderblush", 0xFFF0F5); + SetTrieValue(hTrie, "lawngreen", 0x7CFC00); + SetTrieValue(hTrie, "legendary", 0xD32CE6); // same as Legendary item rarity in Dota 2 + SetTrieValue(hTrie, "lemonchiffon", 0xFFFACD); + SetTrieValue(hTrie, "lightblue", 0xADD8E6); + SetTrieValue(hTrie, "lightcoral", 0xF08080); + SetTrieValue(hTrie, "lightcyan", 0xE0FFFF); + SetTrieValue(hTrie, "lightgoldenrodyellow", 0xFAFAD2); + SetTrieValue(hTrie, "lightgray", 0xD3D3D3); + SetTrieValue(hTrie, "lightgrey", 0xD3D3D3); + SetTrieValue(hTrie, "lightgreen", 0x99FF99); + SetTrieValue(hTrie, "lightpink", 0xFFB6C1); + SetTrieValue(hTrie, "lightsalmon", 0xFFA07A); + SetTrieValue(hTrie, "lightseagreen", 0x20B2AA); + SetTrieValue(hTrie, "lightskyblue", 0x87CEFA); + SetTrieValue(hTrie, "lightslategray", 0x778899); + SetTrieValue(hTrie, "lightslategrey", 0x778899); + SetTrieValue(hTrie, "lightsteelblue", 0xB0C4DE); + SetTrieValue(hTrie, "lightyellow", 0xFFFFE0); + SetTrieValue(hTrie, "lime", 0x00FF00); + SetTrieValue(hTrie, "limegreen", 0x32CD32); + SetTrieValue(hTrie, "linen", 0xFAF0E6); + SetTrieValue(hTrie, "magenta", 0xFF00FF); + SetTrieValue(hTrie, "maroon", 0x800000); + SetTrieValue(hTrie, "mediumaquamarine", 0x66CDAA); + SetTrieValue(hTrie, "mediumblue", 0x0000CD); + SetTrieValue(hTrie, "mediumorchid", 0xBA55D3); + SetTrieValue(hTrie, "mediumpurple", 0x9370D8); + SetTrieValue(hTrie, "mediumseagreen", 0x3CB371); + SetTrieValue(hTrie, "mediumslateblue", 0x7B68EE); + SetTrieValue(hTrie, "mediumspringgreen", 0x00FA9A); + SetTrieValue(hTrie, "mediumturquoise", 0x48D1CC); + SetTrieValue(hTrie, "mediumvioletred", 0xC71585); + SetTrieValue(hTrie, "midnightblue", 0x191970); + SetTrieValue(hTrie, "mintcream", 0xF5FFFA); + SetTrieValue(hTrie, "mistyrose", 0xFFE4E1); + SetTrieValue(hTrie, "moccasin", 0xFFE4B5); + SetTrieValue(hTrie, "mythical", 0x8847FF); // same as Mythical item rarity in Dota 2 + SetTrieValue(hTrie, "navajowhite", 0xFFDEAD); + SetTrieValue(hTrie, "navy", 0x000080); + SetTrieValue(hTrie, "normal", 0xB2B2B2); // same as Normal item quality in TF2 + SetTrieValue(hTrie, "oldlace", 0xFDF5E6); + SetTrieValue(hTrie, "olive", 0x9EC34F); + SetTrieValue(hTrie, "olivedrab", 0x6B8E23); + SetTrieValue(hTrie, "orange", 0xFFA500); + SetTrieValue(hTrie, "orangered", 0xFF4500); + SetTrieValue(hTrie, "orchid", 0xDA70D6); + SetTrieValue(hTrie, "palegoldenrod", 0xEEE8AA); + SetTrieValue(hTrie, "palegreen", 0x98FB98); + SetTrieValue(hTrie, "paleturquoise", 0xAFEEEE); + SetTrieValue(hTrie, "palevioletred", 0xD87093); + SetTrieValue(hTrie, "papayawhip", 0xFFEFD5); + SetTrieValue(hTrie, "peachpuff", 0xFFDAB9); + SetTrieValue(hTrie, "peru", 0xCD853F); + SetTrieValue(hTrie, "pink", 0xFFC0CB); + SetTrieValue(hTrie, "plum", 0xDDA0DD); + SetTrieValue(hTrie, "powderblue", 0xB0E0E6); + SetTrieValue(hTrie, "purple", 0x800080); + SetTrieValue(hTrie, "rare", 0x4B69FF); // same as Rare item rarity in Dota 2 + SetTrieValue(hTrie, "red", 0xFF4040); // same as RED/Terrorist team color + SetTrieValue(hTrie, "rosybrown", 0xBC8F8F); + SetTrieValue(hTrie, "royalblue", 0x4169E1); + SetTrieValue(hTrie, "saddlebrown", 0x8B4513); + SetTrieValue(hTrie, "salmon", 0xFA8072); + SetTrieValue(hTrie, "sandybrown", 0xF4A460); + SetTrieValue(hTrie, "seagreen", 0x2E8B57); + SetTrieValue(hTrie, "seashell", 0xFFF5EE); + SetTrieValue(hTrie, "selfmade", 0x70B04A); // same as Self-Made item quality in TF2 + SetTrieValue(hTrie, "sienna", 0xA0522D); + SetTrieValue(hTrie, "silver", 0xC0C0C0); + SetTrieValue(hTrie, "skyblue", 0x87CEEB); + SetTrieValue(hTrie, "slateblue", 0x6A5ACD); + SetTrieValue(hTrie, "slategray", 0x708090); + SetTrieValue(hTrie, "slategrey", 0x708090); + SetTrieValue(hTrie, "snow", 0xFFFAFA); + SetTrieValue(hTrie, "springgreen", 0x00FF7F); + SetTrieValue(hTrie, "steelblue", 0x4682B4); + SetTrieValue(hTrie, "strange", 0xCF6A32); // same as Strange item quality in TF2 + SetTrieValue(hTrie, "tan", 0xD2B48C); + SetTrieValue(hTrie, "teal", 0x008080); + SetTrieValue(hTrie, "thistle", 0xD8BFD8); + SetTrieValue(hTrie, "tomato", 0xFF6347); + SetTrieValue(hTrie, "turquoise", 0x40E0D0); + SetTrieValue(hTrie, "uncommon", 0xB0C3D9); // same as Uncommon item rarity in Dota 2 + SetTrieValue(hTrie, "unique", 0xFFD700); // same as Unique item quality in TF2 + SetTrieValue(hTrie, "unusual", 0x8650AC); // same as Unusual item quality in TF2 + SetTrieValue(hTrie, "valve", 0xA50F79); // same as Valve item quality in TF2 + SetTrieValue(hTrie, "vintage", 0x476291); // same as Vintage item quality in TF2 + SetTrieValue(hTrie, "violet", 0xEE82EE); + SetTrieValue(hTrie, "wheat", 0xF5DEB3); + SetTrieValue(hTrie, "white", 0xFFFFFF); + SetTrieValue(hTrie, "whitesmoke", 0xF5F5F5); + SetTrieValue(hTrie, "yellow", 0xFFFF00); + SetTrieValue(hTrie, "yellowgreen", 0x9ACD32); + return hTrie; +} diff --git a/addons/sourcemod/scripting/include/nextmap.inc b/addons/sourcemod/scripting/include/nextmap.inc index e61e7b8..1039e25 100644 --- a/addons/sourcemod/scripting/include/nextmap.inc +++ b/addons/sourcemod/scripting/include/nextmap.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -31,52 +31,52 @@ */ #if defined _nextmap_included_ - #endinput + #endinput #endif #define _nextmap_included_ /** - * Sets SourceMod's internal nextmap. + * Sets SourceMod's internal nextmap. * Equivalent to changing sm_nextmap but with an added validity check. * - * @param map Next map to set. - * @return True if the nextmap was set, false if map was invalid. + * @param map Next map to set. + * @return True if the nextmap was set, false if map was invalid. */ native bool SetNextMap(const char[] map); /** * Returns SourceMod's internal nextmap. * - * @param map Buffer to store the nextmap name. - * @param maxlen Maximum length of the map buffer. - * @return True if a Map was found and copied, false if no nextmap is set (map will be unchanged). + * @param map Buffer to store the nextmap name. + * @param maxlen Maximum length of the map buffer. + * @return True if a Map was found and copied, false if no nextmap is set (map will be unchanged). */ native bool GetNextMap(char[] map, int maxlen); /** * Changes the current map and records the reason for the change with maphistory * - * @param map Map to change to. - * @param reason Reason for change. + * @param map Map to change to. + * @param reason Reason for change. */ native void ForceChangeLevel(const char[] map, const char[] reason); /** * Gets the current number of maps in the map history * - * @return Number of maps. + * @return Number of maps. */ native int GetMapHistorySize(); /** * Retrieves a map from the map history list. - * - * @param item Item number. Must be 0 or greater and less than GetMapHistorySize(). - * @param map Buffer to store the map name. - * @param mapLen Length of map buffer. - * @param reason Buffer to store the change reason. - * @param reasonLen Length of the reason buffer. - * @param startTime Time the map started. - * @error Invalid item number. + * + * @param item Item number. Must be 0 or greater and less than GetMapHistorySize(). + * @param map Buffer to store the map name. + * @param mapLen Length of map buffer. + * @param reason Buffer to store the change reason. + * @param reasonLen Length of the reason buffer. + * @param startTime Time the map started. + * @error Invalid item number. */ native void GetMapHistory(int item, char[] map, int mapLen, char[] reason, int reasonLen, int &startTime); diff --git a/addons/sourcemod/scripting/include/profiler.inc b/addons/sourcemod/scripting/include/profiler.inc index 82c2498..df5b956 100644 --- a/addons/sourcemod/scripting/include/profiler.inc +++ b/addons/sourcemod/scripting/include/profiler.inc @@ -1,7 +1,7 @@ /** * vim: set ts=4 : * ============================================================================= - * SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved. + * SourceMod (C)2004-2018 AlliedModders LLC. All rights reserved. * ============================================================================= * * This file is part of the SourceMod/SourcePawn SDK. @@ -38,28 +38,54 @@ /** * ONLY AVAILABLE ON WINDOWS RIGHT NOW K. */ - + +methodmap Profiler < Handle +{ + // Creates a new profile object. The Handle must be freed + // using delete or CloseHandle(). + // + // @return A new Profiler Handle. + public native Profiler(); + + // Starts a cycle for profiling. + public native void Start(); + + // Stops a cycle for profiling. + // + // @error Profiler was never started. + public native void Stop(); + + // Returns the amount of high-precision time in seconds + // that passed during the profiler's last start/stop + // cycle. + // + // @return Time elapsed in seconds. + property float Time { + public native get(); + } +}; + /** * Creates a new profile object. The Handle must be freed - * using CloseHandle(). + * using delete or CloseHandle(). * - * @return Handle to the profiler object. + * @return Handle to the profiler object. */ -native Handle CreateProfiler(); +native Profiler CreateProfiler(); /** * Starts profiling. * - * @param prof Profiling object. - * @error Invalid Handle. + * @param prof Profiling object. + * @error Invalid Handle. */ native void StartProfiling(Handle prof); /** * Stops profiling. * - * @param prof Profiling object. - * @error Invalid Handle or profiling was never started. + * @param prof Profiling object. + * @error Invalid Handle or profiling was never started. */ native void StopProfiling(Handle prof); @@ -68,9 +94,9 @@ native void StopProfiling(Handle prof); * that passed during the profiler's last start/stop * cycle. * - * @param prof Profiling object. - * @return Time elapsed in seconds. - * @error Invalid Handle. + * @param prof Profiling object. + * @return Time elapsed in seconds. + * @error Invalid Handle. */ native float GetProfilerTime(Handle prof); diff --git a/addons/sourcemod/scripting/include/protobuf.inc b/addons/sourcemod/scripting/include/protobuf.inc index 9e692b0..80c4337 100644 --- a/addons/sourcemod/scripting/include/protobuf.inc +++ b/addons/sourcemod/scripting/include/protobuf.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -29,9 +29,9 @@ * * Version: $Id$ */ - + #if defined _protobuf_included -#endinput + #endinput #endif #define _protobuf_included @@ -40,13 +40,21 @@ methodmap Protobuf < Handle { // Reads an int32, uint32, sint32, fixed32, sfixed32, or enum value from a protobuf message. - // + // // @param field Field name. // @param index Index into repeated field. // @return Integer value read. // @error Non-existent field, or incorrect field type. public native int ReadInt(const char[] field, int index = PB_FIELD_NOT_REPEATED); + // Reads an int64, uint64, sint64, fixed64, sfixed64 from a protobuf message. + // + // @param field Field name. + // @param value Array to represent the large integer (0=High bits, 1=Low bits). + // @param index Index into repeated field. + // @error Non-existent field, or incorrect field type. + public native void ReadInt64(const char[] field, int value[2], int index = PB_FIELD_NOT_REPEATED); + // Reads a float or downcasted double from a protobuf message. // // @param field Field name. @@ -56,7 +64,7 @@ methodmap Protobuf < Handle public native float ReadFloat(const char[] field, int index = PB_FIELD_NOT_REPEATED); // Reads a bool from a protobuf message. - // + // // @param field Field name. // @param index Index into repeated field. // @return Boolean value read. @@ -64,7 +72,7 @@ methodmap Protobuf < Handle public native bool ReadBool(const char[] field, int index = PB_FIELD_NOT_REPEATED); // Reads a string from a protobuf message. - // + // // @param field Field name. // @param buffer Destination string buffer. // @param maxlength Maximum length of output string buffer. @@ -73,7 +81,7 @@ methodmap Protobuf < Handle public native void ReadString(const char[] field, char[] buffer, int maxlength, int index = PB_FIELD_NOT_REPEATED); // Reads an RGBA color value from a protobuf message. - // + // // @param field Field name. // @param buffer Destination color buffer. // @param index Index into repeated field. @@ -89,7 +97,7 @@ methodmap Protobuf < Handle public native void ReadAngle(const char[] field, float buffer[3], int index = PB_FIELD_NOT_REPEATED); // Reads an XYZ vector value from a protobuf message. - // + // // @param pb protobuf handle. // @param field Field name. // @param buffer Destination vector buffer. @@ -109,16 +117,31 @@ methodmap Protobuf < Handle // // @param field Field name. // @return Number of elements in the field. - // @error Non-existent field, or incorrect field type. + // @error Non-existent field, or non-repeated field. public native int GetRepeatedFieldCount(const char[] field); + // Returns whether or not the named, non-repeated field has a value set. + // + // @param field Field name. + // @return True if value has been set, else false. + // @error Non-existent field, or repeated field. + public native bool HasField(const char[] field); + // Sets an int32, uint32, sint32, fixed32, sfixed32, or enum value on a protobuf message. // // @param field Field name. // @param value Integer value to set. // @param index Index into repeated field. // @error Non-existent field, or incorrect field type. - public native int SetInt(const char[] field, int value, int index = PB_FIELD_NOT_REPEATED); + public native void SetInt(const char[] field, int value, int index = PB_FIELD_NOT_REPEATED); + + // Sets an int64, uint64, sint64, fixed64, sfixed64 on a protobuf message. + // + // @param field Field name. + // @param value Large integer value to set (0=High bits, 1=Low bits). + // @param index Index into repeated field. + // @error Non-existent field, or incorrect field type. + public native void SetInt64(const char[] field, int value[2], int index = PB_FIELD_NOT_REPEATED); // Sets a float or double on a protobuf message. // @@ -129,7 +152,7 @@ methodmap Protobuf < Handle public native void SetFloat(const char[] field, float value, int index = PB_FIELD_NOT_REPEATED); // Sets a bool on a protobuf message. - // + // // @param field Field name. // @param value Boolean value to set. // @param index Index into repeated field. @@ -145,7 +168,7 @@ methodmap Protobuf < Handle public native void SetString(const char[] field, const char[] value, int index = PB_FIELD_NOT_REPEATED); // Sets an RGBA color on a protobuf message. - // + // // @param field Field name. // @param color Color value to set. // @param index Index into repeated field. @@ -153,7 +176,7 @@ methodmap Protobuf < Handle public native void SetColor(const char[] field, const int color[4], int index = PB_FIELD_NOT_REPEATED); // Sets an XYZ angle on a protobuf message. - // + // // @param field Field name. // @param angle Angle value to set. // @param index Index into repeated field. @@ -161,7 +184,7 @@ methodmap Protobuf < Handle public native void SetAngle(const char[] field, const float angle[3], int index = PB_FIELD_NOT_REPEATED); // Sets an XYZ vector on a protobuf message. - // + // // @param field Field name. // @param vec Vector value to set. // @param index Index into repeated field. @@ -183,8 +206,15 @@ methodmap Protobuf < Handle // @error Non-existent field, or incorrect field type. public native void AddInt(const char[] field, int value); + // Add an int64, uint64, sint64, fixed64, sfixed64 to a protobuf message repeated field. + // + // @param field Field name. + // @param value Large integer value to add (0=High bits, 1=Low bits). + // @error Non-existent field, or incorrect field type. + public native void AddInt64(const char[] field, int value[2]); + // Add a float or double to a protobuf message repeated field. - // + // // @param field Field name. // @param value Float value to add. // @error Non-existent field, or incorrect field type. @@ -205,14 +235,14 @@ methodmap Protobuf < Handle public native void AddString(const char[] field, const char[] value); // Add an RGBA color to a protobuf message repeated field. - // + // // @param field Field name. // @param color Color value to add. // @error Non-existent field, or incorrect field type. public native void AddColor(const char[] field, const int color[4]); // Add an XYZ angle to a protobuf message repeated field. - // + // // @param field Field name. // @param angle Angle value to add. // @error Non-existent field, or incorrect field type. @@ -266,307 +296,307 @@ methodmap Protobuf < Handle /** * Reads an int32, uint32, sint32, fixed32, sfixed32, or enum value from a protobuf message. * - * @param pb protobuf handle. - * @param field Field name. - * @param index Index into repeated field. - * @return Integer value read. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param index Index into repeated field. + * @return Integer value read. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native int PbReadInt(Handle pb, const char[] field, int index = PB_FIELD_NOT_REPEATED); /** * Reads a float or downcasted double from a protobuf message. * - * @param pb protobuf handle. - * @param field Field name. - * @param index Index into repeated field. - * @return Float value read. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param index Index into repeated field. + * @return Float value read. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native float PbReadFloat(Handle pb, const char[] field, int index = PB_FIELD_NOT_REPEATED); /** * Reads a bool from a protobuf message. * - * @param pb protobuf handle. - * @param field Field name. - * @param index Index into repeated field. - * @return Boolean value read. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param index Index into repeated field. + * @return Boolean value read. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native bool PbReadBool(Handle pb, const char[] field, int index = PB_FIELD_NOT_REPEATED); /** * Reads a string from a protobuf message. * - * @param pb protobuf handle. - * @param field Field name. - * @param buffer Destination string buffer. - * @param maxlength Maximum length of output string buffer. - * @param index Index into repeated field. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param buffer Destination string buffer. + * @param maxlength Maximum length of output string buffer. + * @param index Index into repeated field. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbReadString(Handle pb, const char[] field, char[] buffer, int maxlength, int index = PB_FIELD_NOT_REPEATED); /** * Reads an RGBA color value from a protobuf message. * - * @param pb protobuf handle. - * @param field Field name. - * @param buffer Destination color buffer. - * @param index Index into repeated field. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param buffer Destination color buffer. + * @param index Index into repeated field. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbReadColor(Handle pb, const char[] field, int buffer[4], int index = PB_FIELD_NOT_REPEATED); /** * Reads an XYZ angle value from a protobuf message. * - * @param pb protobuf handle. - * @param field Field name. - * @param buffer Destination angle buffer. - * @param index Index into repeated field. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param buffer Destination angle buffer. + * @param index Index into repeated field. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbReadAngle(Handle pb, const char[] field, float buffer[3], int index = PB_FIELD_NOT_REPEATED); /** * Reads an XYZ vector value from a protobuf message. * - * @param pb protobuf handle. - * @param field Field name. - * @param buffer Destination vector buffer. - * @param index Index into repeated field. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param buffer Destination vector buffer. + * @param index Index into repeated field. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbReadVector(Handle pb, const char[] field, float buffer[3], int index = PB_FIELD_NOT_REPEATED); /** * Reads an XY vector value from a protobuf message. * - * @param pb protobuf handle. - * @param field Field name. - * @param buffer Destination vector buffer. - * @param index Index into repeated field. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param buffer Destination vector buffer. + * @param index Index into repeated field. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbReadVector2D(Handle pb, const char[] field, float buffer[2], int index = PB_FIELD_NOT_REPEATED); /** * Gets the number of elements in a repeated field of a protobuf message. * - * @param pb protobuf handle. - * @param field Field name. - * @return Number of elements in the field. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @return Number of elements in the field. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native int PbGetRepeatedFieldCount(Handle pb, const char[] field); /** * Sets an int32, uint32, sint32, fixed32, sfixed32, or enum value on a protobuf message. * - * @param pb protobuf handle. - * @param field Field name. - * @param value Integer value to set. - * @param index Index into repeated field. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param value Integer value to set. + * @param index Index into repeated field. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbSetInt(Handle pb, const char[] field, int value, int index = PB_FIELD_NOT_REPEATED); /** * Sets a float or double on a protobuf message. * - * @param pb protobuf handle. - * @param field Field name. - * @param value Float value to set. - * @param index Index into repeated field. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param value Float value to set. + * @param index Index into repeated field. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbSetFloat(Handle pb, const char[] field, float value, int index = PB_FIELD_NOT_REPEATED); /** * Sets a bool on a protobuf message. * - * @param pb protobuf handle. - * @param field Field name. - * @param value Boolean value to set. - * @param index Index into repeated field. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param value Boolean value to set. + * @param index Index into repeated field. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbSetBool(Handle pb, const char[] field, bool value, int index = PB_FIELD_NOT_REPEATED); /** * Sets a string on a protobuf message. * - * @param pb protobuf handle. - * @param field Field name. - * @param value String value to set. - * @param index Index into repeated field. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param value String value to set. + * @param index Index into repeated field. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbSetString(Handle pb, const char[] field, const char[] value, int index = PB_FIELD_NOT_REPEATED); /** * Sets an RGBA color on a protobuf message. * - * @param pb protobuf handle. - * @param field Field name. - * @param color Color value to set. - * @param index Index into repeated field. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param color Color value to set. + * @param index Index into repeated field. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbSetColor(Handle pb, const char[] field, const int color[4], int index = PB_FIELD_NOT_REPEATED); /** * Sets an XYZ angle on a protobuf message. * - * @param pb protobuf handle. - * @param field Field name. - * @param angle Angle value to set. - * @param index Index into repeated field. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param angle Angle value to set. + * @param index Index into repeated field. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbSetAngle(Handle pb, const char[] field, const float angle[3], int index = PB_FIELD_NOT_REPEATED); /** * Sets an XYZ vector on a protobuf message. * - * @param pb protobuf handle. - * @param field Field name. - * @param vec Vector value to set. - * @param index Index into repeated field. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param vec Vector value to set. + * @param index Index into repeated field. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbSetVector(Handle pb, const char[] field, const float vec[3], int index = PB_FIELD_NOT_REPEATED); /** * Sets an XY vector on a protobuf message. * - * @param pb protobuf handle. - * @param field Field name. - * @param vec Vector value to set. - * @param index Index into repeated field. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param vec Vector value to set. + * @param index Index into repeated field. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbSetVector2D(Handle pb, const char[] field, const float vec[2], int index = PB_FIELD_NOT_REPEATED); /** * Add an int32, uint32, sint32, fixed32, sfixed32, or enum value to a protobuf message repeated field. * - * @param pb protobuf handle. - * @param field Field name. - * @param value Integer value to add. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param value Integer value to add. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbAddInt(Handle pb, const char[] field, int value); /** * Add a float or double to a protobuf message repeated field. * - * @param pb protobuf handle. - * @param field Field name. - * @param value Float value to add. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param value Float value to add. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbAddFloat(Handle pb, const char[] field, float value); /** * Add a bool to a protobuf message repeated field. * - * @param pb protobuf handle. - * @param field Field name. - * @param value Boolean value to add. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param value Boolean value to add. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbAddBool(Handle pb, const char[] field, bool value); /** * Add a string to a protobuf message repeated field. * - * @param pb protobuf handle. - * @param field Field name. - * @param value String value to add. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param value String value to add. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbAddString(Handle pb, const char[] field, const char[] value); /** * Add an RGBA color to a protobuf message repeated field. * - * @param pb protobuf handle. - * @param field Field name. - * @param color Color value to add. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param color Color value to add. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbAddColor(Handle pb, const char[] field, const int color[4]); /** * Add an XYZ angle to a protobuf message repeated field. * - * @param pb protobuf handle. - * @param field Field name. - * @param angle Angle value to add. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param angle Angle value to add. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbAddAngle(Handle pb, const char[] field, const float angle[3]); /** * Add an XYZ vector to a protobuf message repeated field. * - * @param pb protobuf handle. - * @param field Field name. - * @param vec Vector value to add. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param vec Vector value to add. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbAddVector(Handle pb, const char[] field, const float vec[3]); /** * Add an XY vector to a protobuf message repeated field. * - * @param pb protobuf handle. - * @param field Field name. - * @param vec Vector value to add. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + * @param pb protobuf handle. + * @param field Field name. + * @param vec Vector value to add. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. */ native void PbAddVector2D(Handle pb, const char[] field, const float vec[2]); /** * Removes a value by index from a protobuf message repeated field. * - * @param pb protobuf handle. - * @param field Field name. - * @param index Index into repeated field. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. - */ + * @param pb protobuf handle. + * @param field Field name. + * @param index Index into repeated field. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + */ native void PbRemoveRepeatedFieldValue(Handle pb, const char[] field, int index); /** * Retrieve a handle to an embedded protobuf message in a protobuf message. * - * @param pb protobuf handle. - * @param field Field name. - * @return protobuf handle to embedded message. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. - */ + * @param pb protobuf handle. + * @param field Field name. + * @return protobuf handle to embedded message. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + */ native Handle PbReadMessage(Handle pb, const char[] field); /** * Retrieve a handle to an embedded protobuf message in a protobuf message repeated field. * - * @param pb protobuf handle. - * @param field Field name. - * @param index Index in the repeated field. - * @return protobuf handle to embedded message. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. - */ + * @param pb protobuf handle. + * @param field Field name. + * @param index Index in the repeated field. + * @return protobuf handle to embedded message. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + */ native Handle PbReadRepeatedMessage(Handle pb, const char[] field, int index); /** * Adds an embedded protobuf message to a protobuf message repeated field. * - * @param pb protobuf handle. - * @param field Field name. - * @return protobuf handle to added, embedded message. - * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. - */ + * @param pb protobuf handle. + * @param field Field name. + * @return protobuf handle to added, embedded message. + * @error Invalid or incorrect Handle, non-existent field, or incorrect field type. + */ native Handle PbAddMessage(Handle pb, const char[] field); diff --git a/addons/sourcemod/scripting/include/regex.inc b/addons/sourcemod/scripting/include/regex.inc index 5e7e9ee..88ae11e 100644 --- a/addons/sourcemod/scripting/include/regex.inc +++ b/addons/sourcemod/scripting/include/regex.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -31,12 +31,12 @@ */ #if defined _regex_included - #endinput + #endinput #endif #define _regex_included /** - * @section Flags for compiling regex expressions. These come directly from the + * @section Flags for compiling regex expressions. These come directly from the * pcre library and can be used in MatchRegex and CompileRegex. */ #define PCRE_CASELESS 0x00000001 /* Ignore Case */ @@ -44,12 +44,12 @@ #define PCRE_DOTALL 0x00000004 /* Single line (affects . so that it matches any character, even new line characters). */ #define PCRE_EXTENDED 0x00000008 /* Pattern extension (ignore whitespace and # comments). */ #define PCRE_ANCHORED 0x00000010 /* Force pattern anchoring. */ -#define PCRE_DOLLAR_ENDONLY 0x00000020 /* $ not to match newline at end. */ +#define PCRE_DOLLAR_ENDONLY 0x00000020 /* $ not to match newline at end. */ #define PCRE_UNGREEDY 0x00000200 /* Invert greediness of quantifiers */ -#define PCRE_NOTEMPTY 0x00000400 /* An empty string is not a valid match. */ +#define PCRE_NOTEMPTY 0x00000400 /* An empty string is not a valid match. */ #define PCRE_UTF8 0x00000800 /* Use UTF-8 Chars */ #define PCRE_NO_UTF8_CHECK 0x00002000 /* Do not check the pattern for UTF-8 validity (only relevant if PCRE_UTF8 is set) */ -#define PCRE_UCP 0x20000000 /* Use Unicode properties for \ed, \ew, etc. */ +#define PCRE_UCP 0x20000000 /* Use Unicode properties for \ed, \ew, etc. */ /** @@ -57,26 +57,26 @@ */ enum RegexError { - REGEX_ERROR_NONE = 0, /* No error */ - - REGEX_ERROR_ASSERT = 1, /* internal error ? */ - REGEX_ERROR_BADBR, /* invalid repeat counts in {} */ - REGEX_ERROR_BADPAT, /* pattern error */ - REGEX_ERROR_BADRPT, /* ? * + invalid */ - REGEX_ERROR_EBRACE, /* unbalanced {} */ - REGEX_ERROR_EBRACK, /* unbalanced [] */ - REGEX_ERROR_ECOLLATE, /* collation error - not relevant */ - REGEX_ERROR_ECTYPE, /* bad class */ - REGEX_ERROR_EESCAPE, /* bad escape sequence */ - REGEX_ERROR_EMPTY, /* empty expression */ - REGEX_ERROR_EPAREN, /* unbalanced () */ - REGEX_ERROR_ERANGE, /* bad range inside [] */ - REGEX_ERROR_ESIZE, /* expression too big */ - REGEX_ERROR_ESPACE, /* failed to get memory */ - REGEX_ERROR_ESUBREG, /* bad back reference */ - REGEX_ERROR_INVARG, /* bad argument */ - - REGEX_ERROR_NOMATCH = -1, /* No match was found */ + REGEX_ERROR_NONE = 0, /* No error */ + + REGEX_ERROR_ASSERT = 1, /* internal error ? */ + REGEX_ERROR_BADBR, /* invalid repeat counts in {} */ + REGEX_ERROR_BADPAT, /* pattern error */ + REGEX_ERROR_BADRPT, /* ? * + invalid */ + REGEX_ERROR_EBRACE, /* unbalanced {} */ + REGEX_ERROR_EBRACK, /* unbalanced [] */ + REGEX_ERROR_ECOLLATE, /* collation error - not relevant */ + REGEX_ERROR_ECTYPE, /* bad class */ + REGEX_ERROR_EESCAPE, /* bad escape sequence */ + REGEX_ERROR_EMPTY, /* empty expression */ + REGEX_ERROR_EPAREN, /* unbalanced () */ + REGEX_ERROR_ERANGE, /* bad range inside [] */ + REGEX_ERROR_ESIZE, /* expression too big */ + REGEX_ERROR_ESPACE, /* failed to get memory */ + REGEX_ERROR_ESUBREG, /* bad back reference */ + REGEX_ERROR_INVARG, /* bad argument */ + + REGEX_ERROR_NOMATCH = -1, /* No match was found */ REGEX_ERROR_NULL = -2, REGEX_ERROR_BADOPTION = -3, REGEX_ERROR_BADMAGIC = -4, @@ -84,7 +84,7 @@ enum RegexError REGEX_ERROR_NOMEMORY = -6, REGEX_ERROR_NOSUBSTRING = -7, REGEX_ERROR_MATCHLIMIT = -8, - REGEX_ERROR_CALLOUT = -9, /* Never used by PCRE itself */ + REGEX_ERROR_CALLOUT = -9, /* Never used by PCRE itself */ REGEX_ERROR_BADUTF8 = -10, REGEX_ERROR_BADUTF8_OFFSET = -11, REGEX_ERROR_PARTIAL = -12, @@ -97,7 +97,7 @@ enum RegexError REGEX_ERROR_DFA_WSSIZE = -19, REGEX_ERROR_DFA_RECURSE = -20, REGEX_ERROR_RECURSIONLIMIT = -21, - REGEX_ERROR_NULLWSLIMIT = -22, /* No longer actually used */ + REGEX_ERROR_NULLWSLIMIT = -22, /* No longer actually used */ REGEX_ERROR_BADNEWLINE = -23, REGEX_ERROR_BADOFFSET = -24, REGEX_ERROR_SHORTUTF8 = -25, @@ -107,7 +107,7 @@ enum RegexError REGEX_ERROR_BADENDIANNESS = -29, REGEX_ERROR_DFA_BADRESTART = -30, REGEX_ERROR_JIT_BADOPTION = -31, - REGEX_ERROR_BADLENGTH = -32, + REGEX_ERROR_BADLENGTH = -32 }; // Regular expression objects are used to match or decompose strings based on @@ -115,112 +115,109 @@ enum RegexError methodmap Regex < Handle { // Compile a regular expression. - // - // @param pattern The regular expression pattern. - // @param flags General flags for the regular expression. - // @param error Error message encountered, if applicable. - // @param maxLen Maximum string length of the error buffer. - // @param errcode Regex type error code encountered, if applicable. + // + // @param pattern The regular expression pattern. + // @param flags General flags for the regular expression. + // @param error Error message encountered, if applicable. + // @param maxLen Maximum string length of the error buffer. + // @param errcode Regex type error code encountered, if applicable. public native Regex(const char[] pattern, int flags = 0, char[] error="", int maxLen = 0, RegexError &errcode = REGEX_ERROR_NONE); // Matches a string against a pre-compiled regular expression pattern. - // - // @param str The string to check. - // @param regex Regex Handle from CompileRegex() - // @param ret Error code, if applicable. - // @param offset Offset in the string to start searching from. MatchOffset returns the offset of the match. - // @return Number of captures found or -1 on failure. - // - // @note Use the regex handle passed to this function to extract - // matches with GetSubString(). + // + // @param str The string to check. + // @param ret Error code, if applicable. + // @param offset Offset in the string to start searching from. MatchOffset returns the offset of the match. + // @return Number of captures found or -1 on failure. + // + // @note Use the regex handle passed to this function to extract + // matches with GetSubString(). public native int Match(const char[] str, RegexError &ret = REGEX_ERROR_NONE, int offset = 0); - + // Gets all matches from a string against a pre-compiled regular expression pattern. - // - // @param str The string to check. - // @param regex Regex Handle from CompileRegex() - // @param ret Error code, if applicable. - // @return Number of matches found or -1 on failure. - // - // @note Use GetSubString() and loop from 0 -> totalmatches - 1. + // + // @param str The string to check. + // @param ret Error code, if applicable. + // @return Number of matches found or -1 on failure. + // + // @note Use GetSubString() and loop from 0 -> totalmatches - 1. public native int MatchAll(const char[] str, RegexError &ret = REGEX_ERROR_NONE); // Returns a matched substring from a regex handle. - // + // // Substring ids start at 0 and end at captures-1, where captures is the // number returned by Regex.Match or Regex.CaptureCount. // - // @param regex The regex handle to extract data from. - // @param str_id The index of the expression to get - starts at 0, and ends at captures - 1. - // @param buffer The buffer to set to the matching substring. - // @param maxlen The maximum string length of the buffer. - // @param match Match to get the captures for - starts at 0, and ends at MatchCount() -1 - // @return True if a substring was found, False on fail/error + // @param str_id The index of the expression to get - starts at 0, and ends at captures - 1. + // @param buffer The buffer to set to the matching substring. + // @param maxlen The maximum string length of the buffer. + // @param match Match to get the captures for - starts at 0, and ends at MatchCount() -1 + // @return True if a substring was found, False on fail/error // - // @note str_id = 0 is the full captured string, anything else is the capture group index. - // if Regex.Match is used match can only be 0 + // @note str_id = 0 is the full captured string, anything else is the capture group index. + // if Regex.Match is used match can only be 0 public native bool GetSubString(int str_id, char[] buffer, int maxlen, int match = 0); - + // Returns number of matches // // When using Match this is always 1 or 0 (unless an error occured) - // @return Total number of matches found. + // @return Total number of matches found. public native int MatchCount(); - + // Returns number of captures for a match // - // @param match Match to get the number of captures for. Match starts at 0, and ends at MatchCount() -1 - // @return Number of captures in the match. + // @param match Match to get the number of captures for. Match starts at 0, and ends at MatchCount() -1 + // @return Number of captures in the match. // - // @note Use GetSubString() and loop from 1 -> captures -1 for str_id to get all captures + // @note Use GetSubString() and loop from 1 -> captures -1 for str_id to get all captures public native int CaptureCount(int match = 0); - + // Returns the string offset of a match. // - // @param match Match to get the offset of. Match starts at 0, and ends at MatchCount() -1 - // @return Offset of the match in the string. - public native int MatchOffset(int match = 0) + // @param match Match to get the offset of. Match starts at 0, and ends at MatchCount() -1 + // @return Offset of the match in the string. + public native int MatchOffset(int match = 0); }; /** - * Precompile a regular expression. Use this if you intend on using the + * Precompile a regular expression. Use this if you intend on using the * same expression multiple times. Pass the regex handle returned here to * MatchRegex to check for matches. * - * @param pattern The regular expression pattern. - * @param flags General flags for the regular expression. - * @param error Error message encountered, if applicable. - * @param maxLen Maximum string length of the error buffer. - * @param errcode Regex type error code encountered, if applicable. - * @return Valid regex handle on success, INVALID_HANDLE on failure. + * @param pattern The regular expression pattern. + * @param flags General flags for the regular expression. + * @param error Error message encountered, if applicable. + * @param maxLen Maximum string length of the error buffer. + * @param errcode Regex type error code encountered, if applicable. + * @return Valid regex handle on success, INVALID_HANDLE on failure. */ native Regex CompileRegex(const char[] pattern, int flags = 0, char[] error="", int maxLen = 0, RegexError &errcode = REGEX_ERROR_NONE); /** * Matches a string against a pre-compiled regular expression pattern. * - * @param str The string to check. - * @param regex Regex Handle from CompileRegex() - * @param ret Error code, if applicable. - * @return Number of captures found or -1 on failure. + * @param regex Regex Handle from CompileRegex() + * @param str The string to check. + * @param ret Error code, if applicable. + * @return Number of captures found or -1 on failure. * - * @note Use the regex handle passed to this function to extract - * matches with GetRegexSubString(). + * @note Use the regex handle passed to this function to extract + * matches with GetRegexSubString(). */ native int MatchRegex(Handle regex, const char[] str, RegexError &ret = REGEX_ERROR_NONE); /** * Returns a matched substring from a regex handle. - * Substring ids start at 0 and end at captures-1, where captures is the number returned + * Substring ids start at 0 and end at captures-1, where captures is the number returned * by MatchRegex. * - * @param regex The regex handle to extract data from. - * @param str_id The index of the expression to get - starts at 0, and ends at captures - 1. - * @param buffer The buffer to set to the matching substring. - * @param maxlen The maximum string length of the buffer. - * @return True if a substring was found, False on fail/error + * @param regex The regex handle to extract data from. + * @param str_id The index of the expression to get - starts at 0, and ends at captures - 1. + * @param buffer The buffer to set to the matching substring. + * @param maxlen The maximum string length of the buffer. + * @return True if a substring was found, False on fail/error * - * @note str_id = 0 is the full captured string, anything else is the capture group index. + * @note str_id = 0 is the full captured string, anything else is the capture group index. * */ native bool GetRegexSubString(Handle regex, int str_id, char[] buffer, int maxlen); @@ -228,27 +225,29 @@ native bool GetRegexSubString(Handle regex, int str_id, char[] buffer, int maxle /** * Matches a string against a regular expression pattern. * - * @note If you intend on using the same regular expression pattern - * multiple times, consider using CompileRegex and MatchRegex - * instead of making this function reparse the expression each time. + * @note If you intend on using the same regular expression pattern + * multiple times, consider using CompileRegex and MatchRegex + * instead of making this function reparse the expression each time. * - * @param str The string to check. - * @param pattern The regular expression pattern. - * @param flags General flags for the regular expression. - * @param error Error message, if applicable. - * @param maxLen Maximum length of the error buffer. - * @return Number of substrings found or -1 on failure. + * @param str The string to check. + * @param pattern The regular expression pattern. + * @param flags General flags for the regular expression. + * @param error Error message, if applicable. + * @param maxLen Maximum length of the error buffer. + * @return Number of substrings found or -1 on failure. */ stock int SimpleRegexMatch(const char[] str, const char[] pattern, int flags = 0, char[] error="", int maxLen = 0) { Regex regex = new Regex(pattern, flags, error, maxLen); if (!regex) - return -1; - + { + return -1; + } + int substrings = regex.Match(str); delete regex; - return substrings; + return substrings; } /** @@ -258,7 +257,7 @@ stock int SimpleRegexMatch(const char[] str, const char[] pattern, int flags = 0 /** * Do not edit below this line! */ -public Extension __ext_regex = +public Extension __ext_regex = { name = "Regex Extension", file = "regex.ext", @@ -273,3 +272,19 @@ public Extension __ext_regex = required = 0, #endif }; + +#if !defined REQUIRE_EXTENSIONS +public void __ext_regex_SetNTVOptional() +{ + MarkNativeAsOptional("CompileRegex"); + MarkNativeAsOptional("MatchRegex"); + MarkNativeAsOptional("GetRegexSubString"); + MarkNativeAsOptional("Regex.Regex"); + MarkNativeAsOptional("Regex.Match"); + MarkNativeAsOptional("Regex.MatchAll"); + MarkNativeAsOptional("Regex.GetSubString"); + MarkNativeAsOptional("Regex.MatchCount"); + MarkNativeAsOptional("Regex.CaptureCount"); + MarkNativeAsOptional("Regex.MatchOffset"); +} +#endif diff --git a/addons/sourcemod/scripting/include/sdkhooks.inc b/addons/sourcemod/scripting/include/sdkhooks.inc index f58c128..0c8ba4e 100644 --- a/addons/sourcemod/scripting/include/sdkhooks.inc +++ b/addons/sourcemod/scripting/include/sdkhooks.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -35,45 +35,70 @@ // this is obviously _not_ a robust check, but it will solve most conflict and is clean #if !defined DMG_GENERIC -#define DMG_GENERIC 0 /**< generic damage was done */ -#define DMG_CRUSH (1 << 0) /**< crushed by falling or moving object. - NOTE: It's assumed crush damage is occurring as a result of physics collision, so no extra physics force is generated by crush damage. - DON'T use DMG_CRUSH when damaging entities unless it's the result of a physics collision. You probably want DMG_CLUB instead. */ -#define DMG_BULLET (1 << 1) /**< shot */ -#define DMG_SLASH (1 << 2) /**< cut, clawed, stabbed */ -#define DMG_BURN (1 << 3) /**< heat burned */ -#define DMG_VEHICLE (1 << 4) /**< hit by a vehicle */ -#define DMG_FALL (1 << 5) /**< fell too far */ -#define DMG_BLAST (1 << 6) /**< explosive blast damage */ -#define DMG_CLUB (1 << 7) /**< crowbar, punch, headbutt */ -#define DMG_SHOCK (1 << 8) /**< electric shock */ -#define DMG_SONIC (1 << 9) /**< sound pulse shockwave */ -#define DMG_ENERGYBEAM (1 << 10) /**< laser or other high energy beam */ -#define DMG_PREVENT_PHYSICS_FORCE (1 << 11) /**< Prevent a physics force */ -#define DMG_NEVERGIB (1 << 12) /**< with this bit OR'd in, no damage type will be able to gib victims upon death */ -#define DMG_ALWAYSGIB (1 << 13) /**< with this bit OR'd in, any damage type can be made to gib victims upon death. */ -#define DMG_DROWN (1 << 14) /**< Drowning */ -#define DMG_PARALYZE (1 << 15) /**< slows affected creature down */ -#define DMG_NERVEGAS (1 << 16) /**< nerve toxins, very bad */ -#define DMG_POISON (1 << 17) /**< blood poisoning - heals over time like drowning damage */ -#define DMG_RADIATION (1 << 18) /**< radiation exposure */ -#define DMG_DROWNRECOVER (1 << 19) /**< drowning recovery */ -#define DMG_ACID (1 << 20) /**< toxic chemicals or acid burns */ -#define DMG_SLOWBURN (1 << 21) /**< in an oven */ -#define DMG_REMOVENORAGDOLL (1 << 22) /**< with this bit OR'd in, no ragdoll will be created, and the target will be quietly removed. - use this to kill an entity that you've already got a server-side ragdoll for */ -#define DMG_PHYSGUN (1 << 23) /**< Hit by manipulator. Usually doesn't do any damage. */ -#define DMG_PLASMA (1 << 24) /**< Shot by Cremator */ -#define DMG_AIRBOAT (1 << 25) /**< Hit by the airboat's gun */ -#define DMG_DISSOLVE (1 << 26) /**< Dissolving! */ -#define DMG_BLAST_SURFACE (1 << 27) /**< A blast on the surface of water that cannot harm things underwater */ -#define DMG_DIRECT (1 << 28) -#define DMG_BUCKSHOT (1 << 29) /**< not quite a bullet. Little, rounder, different. */ +#define DMG_GENERIC 0 /**< generic damage was done */ +#define DMG_CRUSH (1 << 0) /**< crushed by falling or moving object. + NOTE: It's assumed crush damage is occurring as a result of physics collision, + so no extra physics force is generated by crush damage. + DON'T use DMG_CRUSH when damaging entities unless it's the result of a physics + collision. You probably want DMG_CLUB instead. */ +#define DMG_BULLET (1 << 1) /**< shot */ +#define DMG_SLASH (1 << 2) /**< cut, clawed, stabbed */ +#define DMG_BURN (1 << 3) /**< heat burned */ +#define DMG_VEHICLE (1 << 4) /**< hit by a vehicle */ +#define DMG_FALL (1 << 5) /**< fell too far */ +#define DMG_BLAST (1 << 6) /**< explosive blast damage */ +#define DMG_CLUB (1 << 7) /**< crowbar, punch, headbutt */ +#define DMG_SHOCK (1 << 8) /**< electric shock */ +#define DMG_SONIC (1 << 9) /**< sound pulse shockwave */ +#define DMG_ENERGYBEAM (1 << 10) /**< laser or other high energy beam */ +#define DMG_PREVENT_PHYSICS_FORCE (1 << 11) /**< Prevent a physics force */ +#define DMG_NEVERGIB (1 << 12) /**< with this bit OR'd in, no damage type will be able to gib victims upon death */ +#define DMG_ALWAYSGIB (1 << 13) /**< with this bit OR'd in, any damage type can be made to gib victims upon death. */ +#define DMG_DROWN (1 << 14) /**< Drowning */ +#define DMG_PARALYZE (1 << 15) /**< slows affected creature down */ +#define DMG_NERVEGAS (1 << 16) /**< nerve toxins, very bad */ +#define DMG_POISON (1 << 17) /**< blood poisoning - heals over time like drowning damage */ +#define DMG_RADIATION (1 << 18) /**< radiation exposure */ +#define DMG_DROWNRECOVER (1 << 19) /**< drowning recovery */ +#define DMG_ACID (1 << 20) /**< toxic chemicals or acid burns */ +#define DMG_SLOWBURN (1 << 21) /**< in an oven */ +#define DMG_REMOVENORAGDOLL (1 << 22) /**< with this bit OR'd in, no ragdoll will be created, and the target will be quietly removed. + use this to kill an entity that you've already got a server-side ragdoll for */ +#define DMG_PHYSGUN (1 << 23) /**< Hit by manipulator. Usually doesn't do any damage. */ +#define DMG_PLASMA (1 << 24) /**< Shot by Cremator */ +#define DMG_AIRBOAT (1 << 25) /**< Hit by the airboat's gun */ +#define DMG_DISSOLVE (1 << 26) /**< Dissolving! */ +#define DMG_BLAST_SURFACE (1 << 27) /**< A blast on the surface of water that cannot harm things underwater */ +#define DMG_DIRECT (1 << 28) +#define DMG_BUCKSHOT (1 << 29) /**< not quite a bullet. Little, rounder, different. */ #endif #if !defined DMG_CRIT - // TF2 crits and minicrits - #define DMG_CRIT DMG_ACID + #define DMG_CRIT DMG_ACID /**< TF2 crits and minicrits */ +#endif + +#if !defined DMG_RADIUS_MAX + #define DMG_RADIUS_MAX DMG_ENERGYBEAM /**< No damage falloff */ +#endif + +#if !defined DMG_NOCLOSEDISTANCEMOD + #define DMG_NOCLOSEDISTANCEMOD DMG_POISON /**< Don't do damage falloff too close */ +#endif + +#if !defined DMG_HALF_FALLOFF + #define DMG_HALF_FALLOFF DMG_RADIATION /**< 50% damage falloff */ +#endif + +#if !defined DMG_USEDISTANCEMOD + #define DMG_USEDISTANCEMOD DMG_SLOWBURN /**< Do damage falloff */ +#endif + +#if !defined DMG_IGNITE + #define DMG_IGNITE DMG_PLASMA /**< Ignite victim */ +#endif + +#if !defined DMG_USE_HITLOCATIONS + #define DMG_USE_HITLOCATIONS DMG_AIRBOAT /**< Do hit location damage (Like the sniperrifle and ambassador) */ #endif enum SDKHookType @@ -121,7 +146,7 @@ enum SDKHookType SDKHook_BlockedPost, SDKHook_OnTakeDamageAlive, SDKHook_OnTakeDamageAlivePost, - SDKHook_CanBeAutobalanced, + SDKHook_CanBeAutobalanced }; /* @@ -129,70 +154,70 @@ enum SDKHookType SDKHook_Blocked, SDKHook_BlockedPost, - + SDKHook_CanBeAutobalanced, - + SDKHook_EndTouch, SDKHook_EndTouchPost, - + SDKHook_FireBulletsPost, - + SDKHook_GetMaxHealth, (ep2v and later) - + SDKHook_GroundEntChangedPost, - + SDKHook_OnTakeDamage, SDKHook_OnTakeDamagePost, - + SDKHook_OnTakeDamageAlive, SDKHook_OnTakeDamageAlivePost, - + SDKHook_PreThink, SDKHook_PreThinkPost, - + SDKHook_PostThink, SDKHook_PostThinkPost, - + SDKHook_Reload, SDKHook_ReloadPost, - + SDKHook_SetTransmit, - + SDKHook_ShouldCollide, - + SDKHook_Spawn, SDKHook_SpawnPost, - + SDKHook_StartTouch, SDKHook_StartTouchPost, - + SDKHook_Think, SDKHook_ThinkPost, - + SDKHook_Touch, SDKHook_TouchPost, - + SDKHook_TraceAttack, SDKHook_TraceAttackPost, - + SDKHook_Use, SDKHook_UsePost, - + SDKHook_VPhysicsUpdate, SDKHook_VPhysicsUpdatePost, - + SDKHook_WeaponCanSwitchTo, SDKHook_WeaponCanSwitchToPost, - + SDKHook_WeaponCanUse, SDKHook_WeaponCanUsePost, - + SDKHook_WeaponDrop, SDKHook_WeaponDropPost, - + SDKHook_WeaponEquip, SDKHook_WeaponEquipPost, - + SDKHook_WeaponSwitch, SDKHook_WeaponSwitchPost */ @@ -210,184 +235,198 @@ typeset SDKHookCB // PreThink/Post // PostThink/Post function void (int client); - + // Spawn function Action (int entity); - + // GroundEntChanged // SpawnPost // Think/Post // VPhysicsUpdate/Post function void (int entity); - + // EndTouch // StartTouch // Touch // Blocked function Action (int entity, int other); - + // EndTouchPost // StartTouchPost // TouchPost function void (int entity, int other); - + // SetTransmit function Action (int entity, int client); - + // WeaponCanSwitchTo // WeaponCanUse // WeaponDrop // WeaponEquip // WeaponSwitch function Action (int client, int weapon); - + // WeaponCanSwitchToPost // WeaponCanUsePost // WeaponDropPost // WeaponEquipPost // WeaponSwitchPost function void (int client, int weapon); - + // GetMaxHealth (ep2v and later) function Action (int entity, int &maxhealth); - + // OnTakeDamage // OnTakeDamageAlive - // Note: The weapon parameter is not used by all games and damage sources. - // Note: Force application is dependent on game and damage type(s) // SDKHooks 1.0+ function Action (int victim, int &attacker, int &inflictor, float &damage, int &damagetype); + + // OnTakeDamage + // OnTakeDamageAlive + // Note: The weapon parameter is not used by all games and damage sources. + // Note: Force application is dependent on game and damage type(s) // SDKHooks 2.0+ function Action (int victim, int &attacker, int &inflictor, float &damage, int &damagetype, int &weapon, float damageForce[3], float damagePosition[3]); + + // OnTakeDamage + // OnTakeDamageAlive + // Note: The weapon parameter is not used by all games and damage sources. + // Note: Force application is dependent on game and damage type(s) // SDKHooks 2.1+ (can check for support at runtime using GetFeatureStatus on SDKHook_DmgCustomInOTD capability. // DON'T attempt to access 'damagecustom' var if feature status != available function Action (int victim, int &attacker, int &inflictor, float &damage, int &damagetype, int &weapon, float damageForce[3], float damagePosition[3], int damagecustom); - + // OnTakeDamagePost // OnTakeDamageAlivePost function void (int victim, int attacker, int inflictor, float damage, int damagetype); + + // OnTakeDamagePost + // OnTakeDamageAlivePost function void (int victim, int attacker, int inflictor, float damage, int damagetype, int weapon, const float damageForce[3], const float damagePosition[3]); - function void (int victim, int attacker, int inflictor, float damage, int damagetype, int weapon, + + // OnTakeDamagePost + // OnTakeDamageAlivePost + function void (int victim, int attacker, int inflictor, float damage, int damagetype, int weapon, const float damageForce[3], const float damagePosition[3], int damagecustom); - + // FireBulletsPost function void (int client, int shots, const char[] weaponname); - + // TraceAttack function Action (int victim, int &attacker, int &inflictor, float &damage, int &damagetype, int &ammotype, int hitbox, int hitgroup); - + // TraceAttackPost function void (int victim, int attacker, int inflictor, float damage, int damagetype, int ammotype, int hitbox, int hitgroup); - + // ShouldCollide function bool (int entity, int collisiongroup, int contentsmask, bool originalResult); - + // Use function Action (int entity, int activator, int caller, UseType type, float value); - + // UsePost function void (int entity, int activator, int caller, UseType type, float value); - + // Reload function Action (int weapon); - + // Reload post function void (int weapon, bool bSuccessful); - + // CanBeAutobalanced function bool (int client, bool origRet); }; /** - * @brief When an entity is created + * When an entity is created * - * @param entity Entity index - * @param classname Class name + * @param entity Entity index + * @param classname Class name */ forward void OnEntityCreated(int entity, const char[] classname); /** - * @brief When an entity is destroyed + * When an entity is destroyed * - * @param entity Entity index + * @param entity Entity index */ forward void OnEntityDestroyed(int entity); /** - * @brief When the game description is retrieved + * When the game description is retrieved * - * @note Not supported on ep2v. + * @note Not supported on ep2v. * - * @param gameDesc Game description - * @return Plugin_Changed if gameDesc has been edited, else no change. + * @param gameDesc Game description + * @return Plugin_Changed if gameDesc has been edited, else no change. */ forward Action OnGetGameDescription(char gameDesc[64]); /** - * @brief When the level is initialized + * When the level is initialized * - * @param mapName Name of the map - * @param mapEntities Entities of the map - * @return Plugin_Changed if mapEntities has been edited, else no change. + * @param mapName Name of the map + * @param mapEntities Entities of the map + * @return Plugin_Changed if mapEntities has been edited, else no change. */ forward Action OnLevelInit(const char[] mapName, char mapEntities[2097152]); /** - * @brief Hooks an entity + * Hooks an entity * - * @param entity Entity index - * @param type Type of function to hook - * @param callback Function to call when hook is called + * @param entity Entity index + * @param type Type of function to hook + * @param callback Function to call when hook is called */ native void SDKHook(int entity, SDKHookType type, SDKHookCB callback); /** - * @brief Hooks an entity + * Hooks an entity * - * @param entity Entity index - * @param type Type of function to hook - * @param callback Function to call when hook is called - * @return bool Hook Successful + * @param entity Entity index + * @param type Type of function to hook + * @param callback Function to call when hook is called + * @return Hook Successful */ native bool SDKHookEx(int entity, SDKHookType type, SDKHookCB callback); /** - * @brief Unhooks an entity + * Unhooks an entity * - * @param entity Entity index - * @param type Type of function to unhook - * @param callback Callback function to unhook + * @param entity Entity index + * @param type Type of function to unhook + * @param callback Callback function to unhook */ native void SDKUnhook(int entity, SDKHookType type, SDKHookCB callback); /** - * @brief Applies damage to an entity + * Applies damage to an entity * * @note Force application is dependent on game and damage type(s) * - * @param entity Entity index taking damage - * @param inflictor Inflictor entity index - * @param attacker Attacker entity index - * @param damage Amount of damage - * @param damageType Bitfield of damage types - * @param weapon Weapon index (orangebox and later) or -1 for unspecified - * @param damageForce Velocity of damage force - * @param damagePosition Origin of damage + * @param entity Entity index taking damage + * @param inflictor Inflictor entity index + * @param attacker Attacker entity index + * @param damage Amount of damage + * @param damageType Bitfield of damage types + * @param weapon Weapon index (orangebox and later) or -1 for unspecified + * @param damageForce Velocity of damage force + * @param damagePosition Origin of damage */ native void SDKHooks_TakeDamage(int entity, int inflictor, int attacker, float damage, int damageType=DMG_GENERIC, int weapon=-1, const float damageForce[3]=NULL_VECTOR, const float damagePosition[3]=NULL_VECTOR); /** - * @brief Forces a client to drop the specified weapon + * Forces a client to drop the specified weapon * - * @param client Client index. - * @param weapon Weapon entity index. - * @param vecTarget Location to toss weapon to, or NULL_VECTOR for default. - * @param vecVelocity Velocity at which to toss weapon, or NULL_VECTOR for default. - * @error Invalid client or weapon entity, weapon not owned by client. + * @param client Client index. + * @param weapon Weapon entity index. + * @param vecTarget Location to toss weapon to, or NULL_VECTOR for default. + * @param vecVelocity Velocity at which to toss weapon, or NULL_VECTOR for default. + * @error Invalid client or weapon entity, weapon not owned by client. */ native void SDKHooks_DropWeapon(int client, int weapon, const float vecTarget[3]=NULL_VECTOR, const float vecVelocity[3]=NULL_VECTOR); @@ -395,7 +434,7 @@ native void SDKHooks_DropWeapon(int client, int weapon, const float vecTarget[3] /** * Do not edit below this line! */ -public Extension __ext_sdkhooks = +public Extension __ext_sdkhooks = { name = "SDKHooks", file = "sdkhooks.ext", diff --git a/addons/sourcemod/scripting/include/sdktools.inc b/addons/sourcemod/scripting/include/sdktools.inc index 74cb5aa..e5dffba 100644 --- a/addons/sourcemod/scripting/include/sdktools.inc +++ b/addons/sourcemod/scripting/include/sdktools.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -31,7 +31,7 @@ */ #if defined _sdktools_included - #endinput + #endinput #endif #define _sdktools_included @@ -55,86 +55,86 @@ enum SDKCallType { - SDKCall_Static, /**< Static call */ - SDKCall_Entity, /**< CBaseEntity call */ - SDKCall_Player, /**< CBasePlayer call */ - SDKCall_GameRules, /**< CGameRules call */ - SDKCall_EntityList, /**< CGlobalEntityList call */ - SDKCall_Raw, /**< |this| pointer with an arbitrary address */ + SDKCall_Static, /**< Static call */ + SDKCall_Entity, /**< CBaseEntity call */ + SDKCall_Player, /**< CBasePlayer call */ + SDKCall_GameRules, /**< CGameRules call */ + SDKCall_EntityList, /**< CGlobalEntityList call */ + SDKCall_Raw /**< |this| pointer with an arbitrary address */ }; enum SDKLibrary { - SDKLibrary_Server, /**< server.dll/server_i486.so */ - SDKLibrary_Engine, /**< engine.dll/engine_*.so */ + SDKLibrary_Server, /**< server.dll/server_i486.so */ + SDKLibrary_Engine /**< engine.dll/engine_*.so */ }; enum SDKFuncConfSource { - SDKConf_Virtual = 0, /**< Read a virtual index from the Offsets section */ - SDKConf_Signature = 1, /**< Read a signature from the Signatures section */ - SDKConf_Address = 2, /**< Read an address from the Addresses section */ + SDKConf_Virtual = 0, /**< Read a virtual index from the Offsets section */ + SDKConf_Signature = 1, /**< Read a signature from the Signatures section */ + SDKConf_Address = 2 /**< Read an address from the Addresses section */ }; enum SDKType { - SDKType_CBaseEntity, /**< CBaseEntity (always as pointer) */ - SDKType_CBasePlayer, /**< CBasePlayer (always as pointer) */ - SDKType_Vector, /**< Vector (pointer, byval, or byref) */ - SDKType_QAngle, /**< QAngles (pointer, byval, or byref) */ - SDKType_PlainOldData, /**< Integer/generic data <=32bit (any) */ - SDKType_Float, /**< Float (any) */ - SDKType_Edict, /**< edict_t (always as pointer) */ - SDKType_String, /**< NULL-terminated string (always as pointer) */ - SDKType_Bool, /**< Boolean (any) */ + SDKType_CBaseEntity, /**< CBaseEntity (always as pointer) */ + SDKType_CBasePlayer, /**< CBasePlayer (always as pointer) */ + SDKType_Vector, /**< Vector (pointer, byval, or byref) */ + SDKType_QAngle, /**< QAngles (pointer, byval, or byref) */ + SDKType_PlainOldData, /**< Integer/generic data <=32bit (any) */ + SDKType_Float, /**< Float (any) */ + SDKType_Edict, /**< edict_t (always as pointer) */ + SDKType_String, /**< NULL-terminated string (always as pointer) */ + SDKType_Bool /**< Boolean (any) */ }; enum SDKPassMethod { - SDKPass_Pointer, /**< Pass as a pointer */ - SDKPass_Plain, /**< Pass as plain data */ - SDKPass_ByValue, /**< Pass an object by value */ - SDKPass_ByRef, /**< Pass an object by reference */ + SDKPass_Pointer, /**< Pass as a pointer */ + SDKPass_Plain, /**< Pass as plain data */ + SDKPass_ByValue, /**< Pass an object by value */ + SDKPass_ByRef /**< Pass an object by reference */ }; -#define VDECODE_FLAG_ALLOWNULL (1<<0) /**< Allow NULL for pointers */ -#define VDECODE_FLAG_ALLOWNOTINGAME (1<<1) /**< Allow players not in game */ -#define VDECODE_FLAG_ALLOWWORLD (1<<2) /**< Allow World entity */ -#define VDECODE_FLAG_BYREF (1<<3) /**< Floats/ints by reference */ +#define VDECODE_FLAG_ALLOWNULL (1<<0) /**< Allow NULL for pointers */ +#define VDECODE_FLAG_ALLOWNOTINGAME (1<<1) /**< Allow players not in game */ +#define VDECODE_FLAG_ALLOWWORLD (1<<2) /**< Allow World entity */ +#define VDECODE_FLAG_BYREF (1<<3) /**< Floats/ints by reference */ -#define VENCODE_FLAG_COPYBACK (1<<0) /**< Copy back data once done */ +#define VENCODE_FLAG_COPYBACK (1<<0) /**< Copy back data once done */ /** * Starts the preparation of an SDK call. * - * @param type Type of function call this will be. + * @param type Type of function call this will be. */ native void StartPrepSDKCall(SDKCallType type); /** * Sets the virtual index of the SDK call if it is virtual. * - * @param vtblidx Virtual table index. + * @param vtblidx Virtual table index. */ native void PrepSDKCall_SetVirtual(int vtblidx); /** * Finds an address in a library and sets it as the address to use for the SDK call. * - * @param lib Library to use. - * @param signature Binary data to search for in the library. If it starts with '@', - * the bytes parameter is ignored and the signature is interpreted - * as a symbol lookup in the library. - * @param bytes Number of bytes in the binary search string. - * @return True on success, false if nothing was found. + * @param lib Library to use. + * @param signature Binary data to search for in the library. If it starts with '@', + * the bytes parameter is ignored and the signature is interpreted + * as a symbol lookup in the library. + * @param bytes Number of bytes in the binary search string. + * @return True on success, false if nothing was found. */ native bool PrepSDKCall_SetSignature(SDKLibrary lib, const char[] signature, int bytes); /** * Uses the given function address for the SDK call. * - * @param addr Address of function to use. - * @return True on success, false on failure. + * @param addr Address of function to use. + * @return True on success, false on failure. */ native bool PrepSDKCall_SetAddress(Address addr); @@ -142,39 +142,39 @@ native bool PrepSDKCall_SetAddress(Address addr); * Finds an address or virtual function index in a GameConfig file and sets it as * the calling information for the SDK call. * - * @param gameconf GameConfig Handle, or INVALID_HANDLE to use sdktools.games.txt. - * @param source Whether to look in Offsets or Signatures. - * @param name Name of the property to find. - * @return True on success, false if nothing was found. + * @param gameconf GameConfig Handle, or INVALID_HANDLE to use sdktools.games.txt. + * @param source Whether to look in Offsets or Signatures. + * @param name Name of the property to find. + * @return True on success, false if nothing was found. */ native bool PrepSDKCall_SetFromConf(Handle gameconf, SDKFuncConfSource source, const char[] name); /** * Sets the return information of an SDK call. Do not call this if there is no return data. - * This must be called if there is a return value (i.e. it is not necessarily safe to ignore + * This must be called if there is a return value (i.e. it is not necessarily safe to ignore * the data). * - * @param type Data type to convert to/from. - * @param pass How the data is passed in C++. - * @param decflags Flags on decoding from the plugin to C++. - * @param encflags Flags on encoding from C++ to the plugin. + * @param type Data type to convert to/from. + * @param pass How the data is passed in C++. + * @param decflags Flags on decoding from the plugin to C++. + * @param encflags Flags on encoding from C++ to the plugin. */ native void PrepSDKCall_SetReturnInfo(SDKType type, SDKPassMethod pass, int decflags=0, int encflags=0); /** * Adds a parameter to the calling convention. This should be called in normal ascending order. * - * @param type Data type to convert to/from. - * @param pass How the data is passed in C++. - * @param decflags Flags on decoding from the plugin to C++. - * @param encflags Flags on encoding from C++ to the plugin. + * @param type Data type to convert to/from. + * @param pass How the data is passed in C++. + * @param decflags Flags on decoding from the plugin to C++. + * @param encflags Flags on encoding from C++ to the plugin. */ native void PrepSDKCall_AddParameter(SDKType type, SDKPassMethod pass, int decflags=0, int encflags=0); /** * Finalizes an SDK call preparation and returns the resultant Handle. * - * @return A new SDKCall Handle on success, or INVALID_HANDLE on failure. + * @return A new SDKCall Handle on success, or INVALID_HANDLE on failure. */ native Handle EndPrepSDKCall(); @@ -186,24 +186,24 @@ native Handle EndPrepSDKCall(); * If the return value is a Vector or QAngles, the SECOND parameter must be a Float[3]. * If the return value is a string, the THIRD parameter must be a String buffer, and the * FOURTH parameter must be the maximum length. - * All parameters must be passed after the above is followed. Failure to follow these + * All parameters must be passed after the above is followed. Failure to follow these * rules will result in crashes or wildly unexpected behavior! * * If the return value is a float or integer, the return value will be this value. * If the return value is a CBaseEntity, CBasePlayer, or edict, the return value will - * always be the entity index, or -1 for NULL. + * always be the entity index, or -1 for NULL. * - * @param call SDKCall Handle. - * @param ... Call Parameters. - * @return Simple return value, if any. - * @error Invalid Handle or internal decoding error. + * @param call SDKCall Handle. + * @param ... Call Parameters. + * @return Simple return value, if any. + * @error Invalid Handle or internal decoding error. */ native any SDKCall(Handle call, any ...); /** * Returns the entity index of the player resource/manager entity. * - * @return Index of resource entity or -1 if not found. + * @return Index of resource entity or -1 if not found. */ native int GetPlayerResourceEntity(); @@ -212,7 +212,7 @@ native int GetPlayerResourceEntity(); /** * Do not edit below this line! */ -public Extension __ext_sdktools = +public Extension __ext_sdktools = { name = "SDKTools", file = "sdktools.ext", diff --git a/addons/sourcemod/scripting/include/sdktools_client.inc b/addons/sourcemod/scripting/include/sdktools_client.inc index 786a659..23da412 100644 --- a/addons/sourcemod/scripting/include/sdktools_client.inc +++ b/addons/sourcemod/scripting/include/sdktools_client.inc @@ -31,20 +31,20 @@ */ #if defined _sdktools_client_included - #endinput + #endinput #endif #define _sdktools_client_included /** * Sets the client to an inactive state waiting for a new map * - * @param client The client index + * @param client The client index */ native void InactivateClient(int client); /** * Reconnect a client without dropping the netchannel * - * @param client The client index + * @param client The client index */ native void ReconnectClient(int client); diff --git a/addons/sourcemod/scripting/include/sdktools_engine.inc b/addons/sourcemod/scripting/include/sdktools_engine.inc index 127a7e6..95da43a 100644 --- a/addons/sourcemod/scripting/include/sdktools_engine.inc +++ b/addons/sourcemod/scripting/include/sdktools_engine.inc @@ -31,36 +31,36 @@ */ #if defined _sdktools_engine_included - #endinput + #endinput #endif #define _sdktools_engine_included -#define MAX_LIGHTSTYLES 64 +#define MAX_LIGHTSTYLES 64 /** * Sets a client's "viewing entity." * - * @param client Client index. - * @param entity Entity index. - * @error Invalid client or entity, lack of mod support, or client not in - * game. + * @param client Client index. + * @param entity Entity index. + * @error Invalid client or entity, lack of mod support, or client not in + * game. */ native void SetClientViewEntity(int client, int entity); /** * Sets a light style. * - * @param style Light style (from 0 to MAX_LIGHTSTYLES-1) - * @param value Light value string (see world.cpp/light.cpp in dlls) - * @error Light style index is out of range. + * @param style Light style (from 0 to MAX_LIGHTSTYLES-1) + * @param value Light value string (see world.cpp/light.cpp in dlls) + * @error Light style index is out of range. */ native void SetLightStyle(int style, const char[] value); /** * Returns the client's eye position. * - * @param client Player's index. - * @param pos Destination vector to store the client's eye position. - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @param pos Destination vector to store the client's eye position. + * @error Invalid client index, client not in game, or no mod support. */ native void GetClientEyePosition(int client, float pos[3]); diff --git a/addons/sourcemod/scripting/include/sdktools_entinput.inc b/addons/sourcemod/scripting/include/sdktools_entinput.inc index 4f33856..64454b3 100644 --- a/addons/sourcemod/scripting/include/sdktools_entinput.inc +++ b/addons/sourcemod/scripting/include/sdktools_entinput.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -31,21 +31,21 @@ */ #if defined _sdktools_entinput_included - #endinput + #endinput #endif #define _sdktools_entinput_included /** - * Invokes a named input method on an entity. + * Invokes a named input method on an entity. * * After completion (successful or not), the current global variant is re-initialized. * - * @param dest Destination entity index. - * @param input Input action. - * @param activator Entity index which initiated the sequence of actions (-1 for a NULL entity). - * @param caller Entity index from which this event is sent (-1 for a NULL entity). - * @param outputid Unknown. - * @return True if successful otherwise false. - * @error Invalid entity index or no mod support. + * @param dest Destination entity index. + * @param input Input action. + * @param activator Entity index which initiated the sequence of actions (-1 for a NULL entity). + * @param caller Entity index from which this event is sent (-1 for a NULL entity). + * @param outputid Unknown. + * @return True if successful otherwise false. + * @error Invalid entity index or no mod support. */ -native bool AcceptEntityInput(int dest, const char[] input, int activator=-1, int caller=-1, int outputid=0); \ No newline at end of file +native bool AcceptEntityInput(int dest, const char[] input, int activator=-1, int caller=-1, int outputid=0); diff --git a/addons/sourcemod/scripting/include/sdktools_entoutput.inc b/addons/sourcemod/scripting/include/sdktools_entoutput.inc index b8c5bd5..eb5a915 100644 --- a/addons/sourcemod/scripting/include/sdktools_entoutput.inc +++ b/addons/sourcemod/scripting/include/sdktools_entoutput.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -31,20 +31,20 @@ */ #if defined _sdktools_entoutput_included - #endinput + #endinput #endif #define _sdktools_entoutput_included /** * Called when an entity output is fired. * - * @param output Name of the output that fired. - * @param caller Entity index of the caller. - * @param activator Entity index of the activator. - * @param delay Delay in seconds? before the event gets fired. - * @return Anything other than Plugin_Continue will supress this event, - * returning Plugin_Continue will allow it to propagate the results - * of this output to any entity inputs. + * @param output Name of the output that fired. + * @param caller Entity index of the caller. + * @param activator Entity index of the activator. + * @param delay Delay in seconds? before the event gets fired. + * @return Anything other than Plugin_Continue will supress this event, + * returning Plugin_Continue will allow it to propagate the results + * of this output to any entity inputs. */ typeset EntityOutput { @@ -55,54 +55,54 @@ typeset EntityOutput /** * Add an entity output hook on a entity classname * - * @param classname The classname to hook. - * @param output The output name to hook. - * @param callback An EntityOutput function pointer. - * @error Entity Outputs disabled. + * @param classname The classname to hook. + * @param output The output name to hook. + * @param callback An EntityOutput function pointer. + * @error Entity Outputs disabled. */ native void HookEntityOutput(const char[] classname, const char[] output, EntityOutput callback); /** * Remove an entity output hook. - * @param classname The classname to hook. - * @param output The output name to hook. - * @param callback An EntityOutput function pointer. - * @return True on success, false if no valid hook was found. - * @error Entity Outputs disabled. + * @param classname The classname to hook. + * @param output The output name to hook. + * @param callback An EntityOutput function pointer. + * @return True on success, false if no valid hook was found. + * @error Entity Outputs disabled. */ native bool UnhookEntityOutput(const char[] classname, const char[] output, EntityOutput callback); /** - * Add an entity output hook on a single entity instance + * Add an entity output hook on a single entity instance * - * @param entity The entity on which to add a hook. - * @param output The output name to hook. - * @param callback An EntityOutput function pointer. - * @param once Only fire this hook once and then remove itself. - * @error Entity Outputs disabled or Invalid Entity index. + * @param entity The entity on which to add a hook. + * @param output The output name to hook. + * @param callback An EntityOutput function pointer. + * @param once Only fire this hook once and then remove itself. + * @error Entity Outputs disabled or Invalid Entity index. */ native void HookSingleEntityOutput(int entity, const char[] output, EntityOutput callback, bool once=false); /** - * Remove a single entity output hook. + * Remove a single entity output hook. * - * @param entity The entity on which to remove the hook. - * @param output The output name to hook. - * @param callback An EntityOutput function pointer. - * @return True on success, false if no valid hook was found. - * @error Entity Outputs disabled or Invalid Entity index. + * @param entity The entity on which to remove the hook. + * @param output The output name to hook. + * @param callback An EntityOutput function pointer. + * @return True on success, false if no valid hook was found. + * @error Entity Outputs disabled or Invalid Entity index. */ native bool UnhookSingleEntityOutput(int entity, const char[] output, EntityOutput callback); /** - * Fire a named output on an entity. + * Fire a named output on an entity. * * After completion (successful or not), the current global variant is re-initialized. * - * @param caller Entity index from where the output is fired. - * @param output Output name. - * @param activator Entity index which initiated the sequence of actions (-1 for a NULL entity). - * @param delay Delay before firing the output. - * @error Invalid entity index or no mod support. + * @param caller Entity index from where the output is fired. + * @param output Output name. + * @param activator Entity index which initiated the sequence of actions (-1 for a NULL entity). + * @param delay Delay before firing the output. + * @error Invalid entity index or no mod support. */ -native void FireEntityOutput(int caller, const char[] output, int activator=-1, float delay=0.0); \ No newline at end of file +native void FireEntityOutput(int caller, const char[] output, int activator=-1, float delay=0.0); diff --git a/addons/sourcemod/scripting/include/sdktools_functions.inc b/addons/sourcemod/scripting/include/sdktools_functions.inc index ccf472a..3be387e 100644 --- a/addons/sourcemod/scripting/include/sdktools_functions.inc +++ b/addons/sourcemod/scripting/include/sdktools_functions.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -31,175 +31,175 @@ */ #if defined _sdktools_functions_included - #endinput + #endinput #endif #define _sdktools_functions_included /** * Removes a player's item. * - * @param client Client index. - * @param item CBaseCombatWeapon entity index. - * @return True on success, false otherwise. - * @error Invalid client or entity, lack of mod support, or client not in - * game. + * @param client Client index. + * @param item CBaseCombatWeapon entity index. + * @return True on success, false otherwise. + * @error Invalid client or entity, lack of mod support, or client not in + * game. */ native bool RemovePlayerItem(int client, int item); /** * Gives a named item to a player. * - * @param client Client index. - * @param item Item classname (such as weapon_ak47). - * @param iSubType Unknown. - * @return Entity index on success, or -1 on failure. - * @error Invalid client or client not in game, or lack of mod support. + * @param client Client index. + * @param item Item classname (such as weapon_ak47). + * @param iSubType Unknown. + * @return Entity index on success, or -1 on failure. + * @error Invalid client or client not in game, or lack of mod support. */ native int GivePlayerItem(int client, const char[] item, int iSubType=0); /** - * Returns the weapon in a player's slot. + * Returns the weapon in a player's slot. * - * @param client Client index. - * @param slot Slot index (mod specific). - * @return Entity index on success, -1 if no weapon existed. - * @error Invalid client or client not in game, or lack of mod support. + * @param client Client index. + * @param slot Slot index (mod specific). + * @return Entity index on success, -1 if no weapon existed. + * @error Invalid client or client not in game, or lack of mod support. */ native int GetPlayerWeaponSlot(int client, int slot); /** * Ignites an entity on fire. * - * @param entity Entity index. - * @param time Number of seconds to set on fire. - * @param npc True to only affect NPCs. - * @param size Unknown. - * @param level Unknown. - * @error Invalid entity or client not in game, or lack of mod support. + * @param entity Entity index. + * @param time Number of seconds to set on fire. + * @param npc True to only affect NPCs. + * @param size Unknown. + * @param level Unknown. + * @error Invalid entity or client not in game, or lack of mod support. */ native void IgniteEntity(int entity, float time, bool npc=false, float size=0.0, bool level=false); /** * Extinguishes an entity that is on fire. * - * @param entity Entity index. - * @error Invalid entity or client not in game, or lack of mod support. + * @param entity Entity index. + * @error Invalid entity or client not in game, or lack of mod support. */ native void ExtinguishEntity(int entity); /** * Teleports an entity. * - * @param entity Client index. - * @param origin New origin, or NULL_VECTOR for no change. - * @param angles New angles, or NULL_VECTOR for no change. - * @param velocity New velocity, or NULL_VECTOR for no change. - * @error Invalid entity or client not in game, or lack of mod support. + * @param entity Client index. + * @param origin New origin, or NULL_VECTOR for no change. + * @param angles New angles, or NULL_VECTOR for no change. + * @param velocity New velocity, or NULL_VECTOR for no change. + * @error Invalid entity or client not in game, or lack of mod support. */ native void TeleportEntity(int entity, const float origin[3], const float angles[3], const float velocity[3]); /** * Forces a player to commit suicide. * - * @param client Client index. - * @error Invalid client or client not in game, or lack of mod support. + * @param client Client index. + * @error Invalid client or client not in game, or lack of mod support. */ native void ForcePlayerSuicide(int client); /** * Slaps a player in a random direction. * - * @param client Client index. - * @param health Health to subtract. - * @param sound False to disable the sound effects. - * @error Invalid client or client not in game, or lack of mod support. + * @param client Client index. + * @param health Health to subtract. + * @param sound False to disable the sound effects. + * @error Invalid client or client not in game, or lack of mod support. */ native void SlapPlayer(int client, int health=5, bool sound=true); /** * Searches for an entity by classname. * - * @param startEnt The entity index after which to begin searching from. - * Use -1 to start from the first entity. - * @param classname Classname of the entity to find. - * @return Entity index >= 0 if found, -1 otherwise. - * @error Lack of mod support. + * @param startEnt The entity index after which to begin searching from. + * Use -1 to start from the first entity. + * @param classname Classname of the entity to find. + * @return Entity index >= 0 if found, -1 otherwise. + * @error Lack of mod support. */ native int FindEntityByClassname(int startEnt, const char[] classname); /** * Returns the client's eye angles. * - * @param client Player's index. - * @param ang Destination vector to store the client's eye angles. - * @return True on success, false on failure. - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @param ang Destination vector to store the client's eye angles. + * @return True on success, false on failure. + * @error Invalid client index, client not in game, or no mod support. */ native bool GetClientEyeAngles(int client, float ang[3]); /** * Creates an entity by string name, but does not spawn it (see DispatchSpawn). - * If ForceEdictIndex is not -1, then it will use the edict by that index. If the index is + * If ForceEdictIndex is not -1, then it will use the edict by that index. If the index is * invalid or there is already an edict using that index, it will error out. * - * @param classname Entity classname. - * @param ForceEdictIndex Edict index used by the created entity (ignored on Orangebox and above). - * @return Entity index on success, or -1 on failure. - * @error Invalid edict index, or no mod support. + * @param classname Entity classname. + * @param ForceEdictIndex Edict index used by the created entity (ignored on Orangebox and above). + * @return Entity index on success, or -1 on failure. + * @error Invalid edict index, or no mod support. */ native int CreateEntityByName(const char[] classname, int ForceEdictIndex=-1); /** * Spawns an entity into the game. * - * @param entity Entity index of the created entity. - * @return True on success, false otherwise. - * @error Invalid entity index, or no mod support. + * @param entity Entity index of the created entity. + * @return True on success, false otherwise. + * @error Invalid entity index, or no mod support. */ native bool DispatchSpawn(int entity); /** * Dispatches a KeyValue into given entity using a string value. * - * @param entity Destination entity index. - * @param keyName Name of the key. - * @param value String value. - * @return True on success, false otherwise. - * @error Invalid entity index, or no mod support. + * @param entity Destination entity index. + * @param keyName Name of the key. + * @param value String value. + * @return True on success, false otherwise. + * @error Invalid entity index, or no mod support. */ native bool DispatchKeyValue(int entity, const char[] keyName, const char[] value); /** * Dispatches a KeyValue into given entity using a floating point value. * - * @param entity Destination entity index. - * @param keyName Name of the key. - * @param value Floating point value. - * @return True on success, false otherwise. - * @error Invalid entity index, or no mod support. + * @param entity Destination entity index. + * @param keyName Name of the key. + * @param value Floating point value. + * @return True on success, false otherwise. + * @error Invalid entity index, or no mod support. */ native bool DispatchKeyValueFloat(int entity, const char[] keyName, float value); /** * Dispatches a KeyValue into given entity using a vector value. * - * @param entity Destination entity index. - * @param keyName Name of the key. - * @param vec Vector value. - * @return True on success, false otherwise. - * @error Invalid entity index, or no mod support. + * @param entity Destination entity index. + * @param keyName Name of the key. + * @param vec Vector value. + * @return True on success, false otherwise. + * @error Invalid entity index, or no mod support. */ native bool DispatchKeyValueVector(int entity, const char[] keyName, const float vec[3]); /** * Returns the entity a client is aiming at. * - * @param client Client performing the aiming. - * @param only_clients True to exclude all entities but clients. - * @return Entity index being aimed at. - * -1 if no entity is being aimed at. - * -2 if the function is not supported. - * @error Invalid client index or client not in game. + * @param client Client performing the aiming. + * @param only_clients True to exclude all entities but clients. + * @return Entity index being aimed at. + * -1 if no entity is being aimed at. + * -2 if the function is not supported. + * @error Invalid client index or client not in game. */ native int GetClientAimTarget(int client, bool only_clients=true); @@ -207,7 +207,7 @@ native int GetClientAimTarget(int client, bool only_clients=true); * Returns the total number of teams in a game. * Note: This native should not be called before OnMapStart. * - * @return Total number of teams. + * @return Total number of teams. */ native int GetTeamCount(); @@ -215,10 +215,10 @@ native int GetTeamCount(); * Retrieves the team name based on a team index. * Note: This native should not be called before OnMapStart. * - * @param index Team index. - * @param name Buffer to store string in. - * @param maxlength Maximum length of string buffer. - * @error Invalid team index. + * @param index Team index. + * @param name Buffer to store string in. + * @param maxlength Maximum length of string buffer. + * @error Invalid team index. */ native void GetTeamName(int index, char[] name, int maxlength); @@ -226,9 +226,9 @@ native void GetTeamName(int index, char[] name, int maxlength); * Returns the score of a team based on a team index. * Note: This native should not be called before OnMapStart. * - * @param index Team index. - * @return Score. - * @error Invalid team index. + * @param index Team index. + * @return Score. + * @error Invalid team index. */ native int GetTeamScore(int index); @@ -236,9 +236,9 @@ native int GetTeamScore(int index); * Sets the score of a team based on a team index. * Note: This native should not be called before OnMapStart. * - * @param index Team index. - * @param value New score value. - * @error Invalid team index. + * @param index Team index. + * @param value New score value. + * @error Invalid team index. */ native void SetTeamScore(int index, int value); @@ -246,75 +246,75 @@ native void SetTeamScore(int index, int value); * Retrieves the number of players in a certain team. * Note: This native should not be called before OnMapStart. * - * @param index Team index. - * @return Number of players in the team. - * @error Invalid team index. + * @param index Team index. + * @return Number of players in the team. + * @error Invalid team index. */ native int GetTeamClientCount(int index); /** * Returns the entity index of a team. * - * @param teamIndex Team index. - * @return Entity index of team. - * @error Invalid team index. + * @param teamIndex Team index. + * @return Entity index of team. + * @error Invalid team index. */ native int GetTeamEntity(int teamIndex); /** * Sets the model to a given entity. * - * @param entity Entity index. - * @param model Model name. - * @error Invalid entity index, or no mod support. + * @param entity Entity index. + * @param model Model name. + * @error Invalid entity index, or no mod support. */ native void SetEntityModel(int entity, const char[] model); /** * Retrieves the decal file name associated with a given client. * - * @param client Player's index. - * @param hex Buffer to store the logo filename. - * @param maxlength Maximum length of string buffer. - * @return True on success, otherwise false. - * @error Invalid client or client not in game. + * @param client Player's index. + * @param hex Buffer to store the logo filename. + * @param maxlength Maximum length of string buffer. + * @return True on success, otherwise false. + * @error Invalid client or client not in game. */ native bool GetPlayerDecalFile(int client, char[] hex, int maxlength); /** * Retrieves the jingle file name associated with a given client. * - * @param client Player's index. - * @param hex Buffer to store the jingle filename. - * @param maxlength Maximum length of string buffer. - * @return True on success, otherwise false. - * @error Invalid client or client not in game. + * @param client Player's index. + * @param hex Buffer to store the jingle filename. + * @param maxlength Maximum length of string buffer. + * @return True on success, otherwise false. + * @error Invalid client or client not in game. */ native bool GetPlayerJingleFile(int client, char[] hex, int maxlength); /** * Returns the average server network traffic in bytes/sec. * - * @param in Buffer to store the input traffic velocity. - * @param out Buffer to store the output traffic velocity. + * @param in Buffer to store the input traffic velocity. + * @param out Buffer to store the output traffic velocity. */ native void GetServerNetStats(float &inAmount, float &outAmout); /** * Equip's a player's weapon. * - * @param client Client index. - * @param weapon CBaseCombatWeapon entity index. - * @error Invalid client or entity, lack of mod support, or client not in - * game. + * @param client Client index. + * @param weapon CBaseCombatWeapon entity index. + * @error Invalid client or entity, lack of mod support, or client not in + * game. */ native void EquipPlayerWeapon(int client, int weapon); /** * Activates an entity (CBaseAnimating::Activate) * - * @param entity Entity index. - * @error Invalid entity or lack of mod support. + * @param entity Entity index. + * @error Invalid entity or lack of mod support. */ native void ActivateEntity(int entity); @@ -322,18 +322,18 @@ native void ActivateEntity(int entity); * Sets values to client info buffer keys and notifies the engine of the change. * The change does not get propagated to mods until the next frame. * - * @param client Player's index. - * @param key Key string. - * @param value Value string. - * @error Invalid client index, or client not connected. + * @param client Player's index. + * @param key Key string. + * @param value Value string. + * @error Invalid client index, or client not connected. */ native void SetClientInfo(int client, const char[] key, const char[] value); /** * Changes a client's name. * - * @param client Player's index. - * @param name New name. + * @param client Player's index. + * @param name New name. * @error Invalid client index, or client not connected. */ native void SetClientName(int client, const char[] name); @@ -346,7 +346,6 @@ native void SetClientName(int client, const char[] name); * @param amount Amount of ammo to give. Is capped at ammotype's limit. * @param ammotype Type of ammo to give to player. * @param suppressSound If true, don't play the ammo pickup sound. - * - * @return Amount of ammo actually given. + * @return Amount of ammo actually given. */ native int GivePlayerAmmo(int client, int amount, int ammotype, bool suppressSound=false); diff --git a/addons/sourcemod/scripting/include/sdktools_gamerules.inc b/addons/sourcemod/scripting/include/sdktools_gamerules.inc index af498ec..dc69355 100644 --- a/addons/sourcemod/scripting/include/sdktools_gamerules.inc +++ b/addons/sourcemod/scripting/include/sdktools_gamerules.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -31,165 +31,165 @@ */ #if defined _sdktools_gamerules_included - #endinput + #endinput #endif #define _sdktools_gamerules_included enum RoundState { // initialize the game, create teams RoundState_Init, - + //Before players have joined the game. Periodically checks to see if enough players are ready //to start a game. Also reverts to this when there are no active players RoundState_Pregame, - + //The game is about to start, wait a bit and spawn everyone RoundState_StartGame, - + //All players are respawned, frozen in place RoundState_Preround, - + //Round is on, playing normally RoundState_RoundRunning, - + //Someone has won the round RoundState_TeamWin, - + //Noone has won, manually restart the game, reset scores RoundState_Restart, - + //Noone has won, restart the game RoundState_Stalemate, - + //Game is over, showing the scoreboard etc RoundState_GameOver, - + //Game is over, doing bonus round stuff RoundState_Bonus, - + //Between rounds - RoundState_BetweenRounds, + RoundState_BetweenRounds }; /** * Retrieves an integer value from a property of the gamerules entity. - * - * @param prop Property name. - * @param size Number of bytes to read (valid values are 1, 2, or 4). - * This value is auto-detected, and the size parameter is - * only used as a fallback in case detection fails. - * @param element Element # (starting from 0) if property is an array. - * @return Value at the given property offset. - * @error Not supported. + * + * @param prop Property name. + * @param size Number of bytes to read (valid values are 1, 2, or 4). + * This value is auto-detected, and the size parameter is + * only used as a fallback in case detection fails. + * @param element Element # (starting from 0) if property is an array. + * @return Value at the given property offset. + * @error Not supported. */ native int GameRules_GetProp(const char[] prop, int size=4, int element=0); /** * Sets an integer value for a property of the gamerules entity. * - * @param prop Property name. - * @param value Value to set. - * @param size Number of bytes to write (valid values are 1, 2, or 4). - * This value is auto-detected, and the size parameter is - * only used as a fallback in case detection fails. - * @param element Element # (starting from 0) if property is an array. - * @param changeState This parameter is ignored. - * @error Not supported. + * @param prop Property name. + * @param value Value to set. + * @param size Number of bytes to write (valid values are 1, 2, or 4). + * This value is auto-detected, and the size parameter is + * only used as a fallback in case detection fails. + * @param element Element # (starting from 0) if property is an array. + * @param changeState This parameter is ignored. + * @error Not supported. */ native void GameRules_SetProp(const char[] prop, any value, int size=4, int element=0, bool changeState=false); /** * Retrieves a float value from a property of the gamerules entity. - * - * @param prop Property name. - * @param element Element # (starting from 0) if property is an array. - * @return Value at the given property offset. - * @error Not supported. + * + * @param prop Property name. + * @param element Element # (starting from 0) if property is an array. + * @return Value at the given property offset. + * @error Not supported. */ native float GameRules_GetPropFloat(const char[] prop, int element=0); /** * Sets a float value for a property of the gamerules entity. - * - * @param prop Property name. - * @param value Value to set. - * @param element Element # (starting from 0) if property is an array. - * @param changeState This parameter is ignored. - * @error Not supported. + * + * @param prop Property name. + * @param value Value to set. + * @param element Element # (starting from 0) if property is an array. + * @param changeState This parameter is ignored. + * @error Not supported. */ native void GameRules_SetPropFloat(const char[] prop, float value, int element=0, bool changeState=false); /** * Retrieves a entity index from a property of the gamerules entity. - * - * @param prop Property name. - * @param element Element # (starting from 0) if property is an array. - * @return Entity index at the given property. - * If there is no entity, or the entity is not valid, - * then -1 is returned. - * @error Not supported. + * + * @param prop Property name. + * @param element Element # (starting from 0) if property is an array. + * @return Entity index at the given property. + * If there is no entity, or the entity is not valid, + * then -1 is returned. + * @error Not supported. */ native int GameRules_GetPropEnt(const char[] prop, int element=0); /** * Sets an entity index for a property of the gamerules entity. - * - * @param prop Property name. - * @param other Entity index to set, or -1 to unset. - * @param element Element # (starting from 0) if property is an array. - * @param changeState This parameter is ignored. - * @error Not supported. + * + * @param prop Property name. + * @param other Entity index to set, or -1 to unset. + * @param element Element # (starting from 0) if property is an array. + * @param changeState This parameter is ignored. + * @error Not supported. */ native void GameRules_SetPropEnt(const char[] prop, int other, int element=0, bool changeState=false); /** * Retrieves a vector of floats from the gamerules entity, given a named network property. - * - * @param prop Property name. - * @param vec Vector buffer to store data in. - * @param element Element # (starting from 0) if property is an array. - * @error Not supported. + * + * @param prop Property name. + * @param vec Vector buffer to store data in. + * @param element Element # (starting from 0) if property is an array. + * @error Not supported. */ native void GameRules_GetPropVector(const char[] prop, float vec[3], int element=0); /** * Sets a vector of floats in the gamerules entity, given a named network property. * - * @param prop Property name. - * @param vec Vector to set. - * @param element Element # (starting from 0) if property is an array. - * @param changeState This parameter is ignored. - * @error Not supported. + * @param prop Property name. + * @param vec Vector to set. + * @param element Element # (starting from 0) if property is an array. + * @param changeState This parameter is ignored. + * @error Not supported. */ native void GameRules_SetPropVector(const char[] prop, const float vec[3], int element=0, bool changeState=false); /** * Gets a gamerules property as a string. - * - * @param prop Property to use. - * @param buffer Destination string buffer. - * @param maxlen Maximum length of output string buffer. - * @return Number of non-null bytes written. - * @error Not supported. + * + * @param prop Property to use. + * @param buffer Destination string buffer. + * @param maxlen Maximum length of output string buffer. + * @return Number of non-null bytes written. + * @error Not supported. */ native int GameRules_GetPropString(const char[] prop, char[] buffer, int maxlen); /** * Sets a gamerules property as a string. * - * @param prop Property to use. - * @param buffer String to set. - * @param changeState This parameter is ignored. - * @return Number of non-null bytes written. - * @error Not supported. + * @param prop Property to use. + * @param buffer String to set. + * @param changeState This parameter is ignored. + * @return Number of non-null bytes written. + * @error Not supported. */ native int GameRules_SetPropString(const char[] prop, const char[] buffer, bool changeState=false); /** * Gets the current round state. * - * @return Round state. - * @error Game doesn't support round state. + * @return Round state. + * @error Game doesn't support round state. */ stock RoundState GameRules_GetRoundState() { diff --git a/addons/sourcemod/scripting/include/sdktools_hooks.inc b/addons/sourcemod/scripting/include/sdktools_hooks.inc index 63d53aa..aa20e3b 100644 --- a/addons/sourcemod/scripting/include/sdktools_hooks.inc +++ b/addons/sourcemod/scripting/include/sdktools_hooks.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -31,66 +31,65 @@ */ #if defined _sdktools_hooks_included - #endinput + #endinput #endif #define _sdktools_hooks_included -#define FEATURECAP_PLAYERRUNCMD_11PARAMS "SDKTools PlayerRunCmd 11Params" +#define FEATURECAP_PLAYERRUNCMD_11PARAMS "SDKTools PlayerRunCmd 11Params" /** - * @brief Called when a clients movement buttons are being processed + * Called when a clients movement buttons are being processed * - * @param client Index of the client. - * @param buttons Copyback buffer containing the current commands (as bitflags - see entity_prop_stocks.inc). - * @param impulse Copyback buffer containing the current impulse command. - * @param vel Players desired velocity. - * @param angles Players desired view angles. - * @param weapon Entity index of the new weapon if player switches weapon, 0 otherwise. - * @param subtype Weapon subtype when selected from a menu. - * @param cmdnum Command number. Increments from the first command sent. - * @param tickcount Tick count. A client's prediction based on the server's GetGameTickCount value. - * @param seed Random seed. Used to determine weapon recoil, spread, and other predicted elements. - * @param mouse Mouse direction (x, y). - * @return Plugin_Handled to block the commands from being processed, Plugin_Continue otherwise. + * @param client Index of the client. + * @param buttons Copyback buffer containing the current commands (as bitflags - see entity_prop_stocks.inc). + * @param impulse Copyback buffer containing the current impulse command. + * @param vel Players desired velocity. + * @param angles Players desired view angles. + * @param weapon Entity index of the new weapon if player switches weapon, 0 otherwise. + * @param subtype Weapon subtype when selected from a menu. + * @param cmdnum Command number. Increments from the first command sent. + * @param tickcount Tick count. A client's prediction based on the server's GetGameTickCount value. + * @param seed Random seed. Used to determine weapon recoil, spread, and other predicted elements. + * @param mouse Mouse direction (x, y). + * @return Plugin_Handled to block the commands from being processed, Plugin_Continue otherwise. * - * @note To see if all 11 params are available, use FeatureType_Capability and - * FEATURECAP_PLAYERRUNCMD_11PARAMS. + * @note To see if all 11 params are available, use FeatureType_Capability and FEATURECAP_PLAYERRUNCMD_11PARAMS. */ forward Action OnPlayerRunCmd(int client, int &buttons, int &impulse, float vel[3], float angles[3], int &weapon, int &subtype, int &cmdnum, int &tickcount, int &seed, int mouse[2]); /** - * @brief Called after a clients movement buttons were processed. + * Called after a clients movement buttons were processed. * - * @param client Index of the client. - * @param buttons The current commands (as bitflags - see entity_prop_stocks.inc). - * @param impulse The current impulse command. - * @param vel Players desired velocity. - * @param angles Players desired view angles. - * @param weapon Entity index of the new weapon if player switches weapon, 0 otherwise. - * @param subtype Weapon subtype when selected from a menu. - * @param cmdnum Command number. Increments from the first command sent. - * @param tickcount Tick count. A client's prediction based on the server's GetGameTickCount value. - * @param seed Random seed. Used to determine weapon recoil, spread, and other predicted elements. - * @param mouse Mouse direction (x, y). + * @param client Index of the client. + * @param buttons The current commands (as bitflags - see entity_prop_stocks.inc). + * @param impulse The current impulse command. + * @param vel Players desired velocity. + * @param angles Players desired view angles. + * @param weapon Entity index of the new weapon if player switches weapon, 0 otherwise. + * @param subtype Weapon subtype when selected from a menu. + * @param cmdnum Command number. Increments from the first command sent. + * @param tickcount Tick count. A client's prediction based on the server's GetGameTickCount value. + * @param seed Random seed. Used to determine weapon recoil, spread, and other predicted elements. + * @param mouse Mouse direction (x, y). */ forward void OnPlayerRunCmdPost(int client, int buttons, int impulse, const float vel[3], const float angles[3], int weapon, int subtype, int cmdnum, int tickcount, int seed, const int mouse[2]); /** - * @brief Called when a client requests a file from the server. + * Called when a client requests a file from the server. * - * @param client Client index. - * @param sFile Requested file path. + * @param client Client index. + * @param sFile Requested file path. * - * @return Plugin_Handled to block the transfer, Plugin_Continue to let it proceed. + * @return Plugin_Handled to block the transfer, Plugin_Continue to let it proceed. */ forward Action OnFileSend(int client, const char[] sFile); /** - * @brief Called when a client sends a file to the server. + * Called when a client sends a file to the server. * - * @param client Client index. - * @param sFile Requested file path. + * @param client Client index. + * @param sFile Requested file path. * - * @return Plugin_Handled to block the transfer, Plugin_Continue to let it proceed. + * @return Plugin_Handled to block the transfer, Plugin_Continue to let it proceed. */ forward Action OnFileReceive(int client, const char[] sFile); diff --git a/addons/sourcemod/scripting/include/sdktools_sound.inc b/addons/sourcemod/scripting/include/sdktools_sound.inc index 79668b2..41c87de 100644 --- a/addons/sourcemod/scripting/include/sdktools_sound.inc +++ b/addons/sourcemod/scripting/include/sdktools_sound.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -31,40 +31,40 @@ */ #if defined _sdktools_sound_included - #endinput + #endinput #endif #define _sdktools_sound_included /** * Sound should be from the target client. */ -#define SOUND_FROM_PLAYER -2 +#define SOUND_FROM_PLAYER -2 /** * Sound should be from the listen server player. */ -#define SOUND_FROM_LOCAL_PLAYER -1 +#define SOUND_FROM_LOCAL_PLAYER -1 /** * Sound is from the world. */ -#define SOUND_FROM_WORLD 0 +#define SOUND_FROM_WORLD 0 /** * Sound channels. */ enum { - SNDCHAN_REPLACE = -1, /**< Unknown */ - SNDCHAN_AUTO = 0, /**< Auto */ - SNDCHAN_WEAPON = 1, /**< Weapons */ - SNDCHAN_VOICE = 2, /**< Voices */ - SNDCHAN_ITEM = 3, /**< Items */ - SNDCHAN_BODY = 4, /**< Player? */ - SNDCHAN_STREAM = 5, /**< "Stream channel from the static or dynamic area" */ - SNDCHAN_STATIC = 6, /**< "Stream channel from the static area" */ - SNDCHAN_VOICE_BASE = 7, /**< "Channel for network voice data" */ - SNDCHAN_USER_BASE = 135 /**< Anything >= this is allocated to game code */ + SNDCHAN_REPLACE = -1, /**< Unknown */ + SNDCHAN_AUTO = 0, /**< Auto */ + SNDCHAN_WEAPON = 1, /**< Weapons */ + SNDCHAN_VOICE = 2, /**< Voices */ + SNDCHAN_ITEM = 3, /**< Items */ + SNDCHAN_BODY = 4, /**< Player? */ + SNDCHAN_STREAM = 5, /**< "Stream channel from the static or dynamic area" */ + SNDCHAN_STATIC = 6, /**< "Stream channel from the static area" */ + SNDCHAN_VOICE_BASE = 7, /**< "Channel for network voice data" */ + SNDCHAN_USER_BASE = 135 /**< Anything >= this is allocated to game code */ }; /** @@ -72,15 +72,15 @@ enum */ enum { - SND_NOFLAGS= 0, /**< Nothing */ - SND_CHANGEVOL = 1, /**< Change sound volume */ - SND_CHANGEPITCH = 2, /**< Change sound pitch */ - SND_STOP = 3, /**< Stop the sound */ - SND_SPAWNING = 4, /**< Used in some cases for ambients */ - SND_DELAY = 5, /**< Sound has an initial delay */ - SND_STOPLOOPING = 6, /**< Stop looping all sounds on the entity */ - SND_SPEAKER = 7, /**< Being played by a mic through a speaker */ - SND_SHOULDPAUSE = 8, /**< Pause if game is paused */ + SND_NOFLAGS= 0, /**< Nothing */ + SND_CHANGEVOL = 1, /**< Change sound volume */ + SND_CHANGEPITCH = 2, /**< Change sound pitch */ + SND_STOP = 3, /**< Stop the sound */ + SND_SPAWNING = 4, /**< Used in some cases for ambients */ + SND_DELAY = 5, /**< Sound has an initial delay */ + SND_STOPLOOPING = 6, /**< Stop looping all sounds on the entity */ + SND_SPEAKER = 7, /**< Being played by a mic through a speaker */ + SND_SHOULDPAUSE = 8 /**< Pause if game is paused */ }; /** @@ -88,52 +88,53 @@ enum */ enum { - SNDLEVEL_NONE = 0, /**< None */ - SNDLEVEL_RUSTLE = 20, /**< Rustling leaves */ - SNDLEVEL_WHISPER = 25, /**< Whispering */ - SNDLEVEL_LIBRARY = 30, /**< In a library */ - SNDLEVEL_FRIDGE = 45, /**< Refrigerator */ - SNDLEVEL_HOME = 50, /**< Average home (3.9 attn) */ - SNDLEVEL_CONVO = 60, /**< Normal conversation (2.0 attn) */ - SNDLEVEL_DRYER = 60, /**< Clothes dryer */ - SNDLEVEL_DISHWASHER = 65, /**< Dishwasher/washing machine (1.5 attn) */ - SNDLEVEL_CAR = 70, /**< Car or vacuum cleaner (1.0 attn) */ - SNDLEVEL_NORMAL = 75, /**< Normal sound level */ - SNDLEVEL_TRAFFIC = 75, /**< Busy traffic (0.8 attn) */ - SNDLEVEL_MINIBIKE = 80, /**< Mini-bike, alarm clock (0.7 attn) */ - SNDLEVEL_SCREAMING = 90, /**< Screaming child (0.5 attn) */ - SNDLEVEL_TRAIN = 100, /**< Subway train, pneumatic drill (0.4 attn) */ - SNDLEVEL_HELICOPTER = 105, /**< Helicopter */ - SNDLEVEL_SNOWMOBILE = 110, /**< Snow mobile */ - SNDLEVEL_AIRCRAFT = 120, /**< Auto horn, aircraft */ - SNDLEVEL_RAIDSIREN = 130, /**< Air raid siren */ - SNDLEVEL_GUNFIRE = 140, /**< Gunshot, jet engine (0.27 attn) */ - SNDLEVEL_ROCKET = 180, /**< Rocket launching (0.2 attn) */ + SNDLEVEL_NONE = 0, /**< None */ + SNDLEVEL_RUSTLE = 20, /**< Rustling leaves */ + SNDLEVEL_WHISPER = 25, /**< Whispering */ + SNDLEVEL_LIBRARY = 30, /**< In a library */ + SNDLEVEL_FRIDGE = 45, /**< Refrigerator */ + SNDLEVEL_HOME = 50, /**< Average home (3.9 attn) */ + SNDLEVEL_CONVO = 60, /**< Normal conversation (2.0 attn) */ + SNDLEVEL_DRYER = 60, /**< Clothes dryer */ + SNDLEVEL_DISHWASHER = 65, /**< Dishwasher/washing machine (1.5 attn) */ + SNDLEVEL_CAR = 70, /**< Car or vacuum cleaner (1.0 attn) */ + SNDLEVEL_NORMAL = 75, /**< Normal sound level */ + SNDLEVEL_TRAFFIC = 75, /**< Busy traffic (0.8 attn) */ + SNDLEVEL_MINIBIKE = 80, /**< Mini-bike, alarm clock (0.7 attn) */ + SNDLEVEL_SCREAMING = 90, /**< Screaming child (0.5 attn) */ + SNDLEVEL_TRAIN = 100, /**< Subway train, pneumatic drill (0.4 attn) */ + SNDLEVEL_HELICOPTER = 105, /**< Helicopter */ + SNDLEVEL_SNOWMOBILE = 110, /**< Snow mobile */ + SNDLEVEL_AIRCRAFT = 120, /**< Auto horn, aircraft */ + SNDLEVEL_RAIDSIREN = 130, /**< Air raid siren */ + SNDLEVEL_GUNFIRE = 140, /**< Gunshot, jet engine (0.27 attn) */ + SNDLEVEL_ROCKET = 180 /**< Rocket launching (0.2 attn) */ }; -#define SNDVOL_NORMAL 1.0 /**< Normal volume */ -#define SNDPITCH_NORMAL 100 /**< Normal pitch */ -#define SNDPITCH_LOW 95 /**< A low pitch */ -#define SNDPITCH_HIGH 120 /**< A high pitch */ -#define SNDATTN_NONE 0.0 /**< No attenuation */ -#define SNDATTN_NORMAL 0.8 /**< Normal attenuation */ -#define SNDATTN_STATIC 1.25 /**< Static attenuation? */ -#define SNDATTN_RICOCHET 1.5 /**< Ricochet effect */ -#define SNDATTN_IDLE 2.0 /**< Idle attenuation? */ - +#define SNDVOL_NORMAL 1.0 /**< Normal volume */ +#define SNDPITCH_NORMAL 100 /**< Normal pitch */ +#define SNDPITCH_LOW 95 /**< A low pitch */ +#define SNDPITCH_HIGH 120 /**< A high pitch */ +#define SNDATTN_NONE 0.0 /**< No attenuation */ +#define SNDATTN_NORMAL 0.8 /**< Normal attenuation */ +#define SNDATTN_STATIC 1.25 /**< Static attenuation? */ +#define SNDATTN_RICOCHET 1.5 /**< Ricochet effect */ +#define SNDATTN_IDLE 2.0 /**< Idle attenuation? */ + /** * Prefetches a sound. * - * @param name Sound file name relative to the "sounds" folder. + * @param name Sound file name relative to the "sound" folder. */ native void PrefetchSound(const char[] name); /** - * This function is not known to work, and may crash. You should + * This function is not known to work, and may crash. You should * not use it. It is provided for backwards compatibility only. * - * @param name Sound file name relative to the "sounds" folder. - * @return Duration in seconds. + * @param name Sound file name relative to the "sound" folder. + * @return Duration in seconds. + * @deprecated Does not work, may crash. */ #pragma deprecated Does not work, may crash. native float GetSoundDuration(const char[] name); @@ -141,14 +142,14 @@ native float GetSoundDuration(const char[] name); /** * Emits an ambient sound. * - * @param name Sound file name relative to the "sounds" folder. - * @param pos Origin of sound. - * @param entity Entity index to associate sound with. - * @param level Sound level (from 0 to 255). - * @param flags Sound flags. - * @param vol Volume (from 0.0 to 1.0). - * @param pitch Pitch (from 0 to 255). - * @param delay Play delay. + * @param name Sound file name relative to the "sound" folder. + * @param pos Origin of sound. + * @param entity Entity index to associate sound with. + * @param level Sound level (from 0 to 255). + * @param flags Sound flags. + * @param vol Volume (from 0.0 to 1.0). + * @param pitch Pitch (from 0 to 255). + * @param delay Play delay. */ native void EmitAmbientSound(const char[] name, const float pos[3], @@ -162,43 +163,43 @@ native void EmitAmbientSound(const char[] name, /** * Fades a client's volume level toward silence or a given percentage. * - * @param client Client index. - * @param percent Fade percentage. - * @param outtime Fade out time, in seconds. - * @param holdtime Hold time, in seconds. - * @param intime Fade in time, in seconds. - * @error Invalid client index or client not in game. + * @param client Client index. + * @param percent Fade percentage. + * @param outtime Fade out time, in seconds. + * @param holdtime Hold time, in seconds. + * @param intime Fade in time, in seconds. + * @error Invalid client index or client not in game. */ native void FadeClientVolume(int client, float percent, float outtime, float holdtime, float intime); /** * Stops a sound. * - * @param entity Entity index. - * @param channel Channel number. - * @param name Sound file name relative to the "sounds" folder. + * @param entity Entity index. + * @param channel Channel number. + * @param name Sound file name relative to the "sound" folder. */ native void StopSound(int entity, int channel, const char[] name); /** * Emits a sound to a list of clients. * - * @param clients Array of client indexes. - * @param numClients Number of clients in the array. - * @param sample Sound file name relative to the "sounds" folder. - * @param entity Entity to emit from. - * @param channel Channel to emit with. - * @param level Sound level. - * @param flags Sound flags. - * @param volume Sound volume. - * @param pitch Sound pitch. - * @param speakerentity Unknown. - * @param origin Sound origin. - * @param dir Sound direction. - * @param updatePos Unknown (updates positions?) - * @param soundtime Alternate time to play sound for. - * @param ... Optional list of Float[3] arrays to specify additional origins. - * @error Invalid client index. + * @param clients Array of client indexes. + * @param numClients Number of clients in the array. + * @param sample Sound file name relative to the "sound" folder. + * @param entity Entity to emit from. + * @param channel Channel to emit with. + * @param level Sound level. + * @param flags Sound flags. + * @param volume Sound volume. + * @param pitch Sound pitch. + * @param speakerentity Unknown. + * @param origin Sound origin. + * @param dir Sound direction. + * @param updatePos Unknown (updates positions?) + * @param soundtime Alternate time to play sound for. + * @param ... Optional list of Float[3] arrays to specify additional origins. + * @error Invalid client index. */ native void EmitSound(const int[] clients, int numClients, @@ -220,24 +221,24 @@ native void EmitSound(const int[] clients, * Emits a sound or game sound to a list of clients using the latest version of the engine sound interface. * This native is only available in engines that are greater than or equal to Portal 2. * - * @param clients Array of client indexes. - * @param numClients Number of clients in the array. - * @param soundEntry Sound entry name. - * @param sample Sound file name relative to the "sounds" folder. - * @param entity Entity to emit from. - * @param channel Channel to emit with. - * @param level Sound level. - * @param seed Sound seed. - * @param flags Sound flags. - * @param volume Sound volume. - * @param pitch Sound pitch. - * @param speakerentity Unknown. - * @param origin Sound origin. - * @param dir Sound direction. - * @param updatePos Unknown (updates positions?) - * @param soundtime Alternate time to play sound for. - * @param ... Optional list of Float[3] arrays to specify additional origins. - * @error Invalid client index. + * @param clients Array of client indexes. + * @param numClients Number of clients in the array. + * @param soundEntry Sound entry name. + * @param sample Sound file name relative to the "sound" folder. + * @param entity Entity to emit from. + * @param channel Channel to emit with. + * @param level Sound level. + * @param seed Sound seed. + * @param flags Sound flags. + * @param volume Sound volume. + * @param pitch Sound pitch. + * @param speakerentity Unknown. + * @param origin Sound origin. + * @param dir Sound direction. + * @param updatePos Unknown (updates positions?) + * @param soundtime Alternate time to play sound for. + * @param ... Optional list of Float[3] arrays to specify additional origins. + * @error Invalid client index. */ native void EmitSoundEntry(const int[] clients, int numClients, @@ -260,22 +261,22 @@ native void EmitSoundEntry(const int[] clients, /** * Emits a sentence to a list of clients. * - * @param clients Array of client indexes. - * @param numClients Number of clients in the array. - * @param sentence Sentence index (from PrecacheSentenceFile). - * @param entity Entity to emit from. - * @param channel Channel to emit with. - * @param level Sound level. - * @param flags Sound flags. - * @param volume Sound volume. - * @param pitch Sound pitch. - * @param speakerentity Unknown. - * @param origin Sound origin. - * @param dir Sound direction. - * @param updatePos Unknown (updates positions?) - * @param soundtime Alternate time to play sound for. - * @param ... Optional list of Float[3] arrays to specify additional origins. - * @error Invalid client index. + * @param clients Array of client indexes. + * @param numClients Number of clients in the array. + * @param sentence Sentence index (from PrecacheSentenceFile). + * @param entity Entity to emit from. + * @param channel Channel to emit with. + * @param level Sound level. + * @param flags Sound flags. + * @param volume Sound volume. + * @param pitch Sound pitch. + * @param speakerentity Unknown. + * @param origin Sound origin. + * @param dir Sound direction. + * @param updatePos Unknown (updates positions?) + * @param soundtime Alternate time to play sound for. + * @param ... Optional list of Float[3] arrays to specify additional origins. + * @error Invalid client index. */ native void EmitSentence(const int[] clients, int numClients, @@ -292,13 +293,13 @@ native void EmitSentence(const int[] clients, bool updatePos = true, float soundtime = 0.0, any ...); - + /** * Calculates gain of sound on given distance with given sound level in decibel * - * @param soundlevel decibel of sound, like SNDLEVEL_NORMAL or integer value - * @param distance distance of sound to calculate, not meter or feet, but Source Engine`s normal Coordinate unit - * @return gain of sound. you can multiply this with original sound`s volume to calculate volume on given distance + * @param soundlevel decibel of sound, like SNDLEVEL_NORMAL or integer value + * @param distance distance of sound to calculate, not meter or feet, but Source Engine`s normal Coordinate unit + * @return gain of sound. you can multiply this with original sound`s volume to calculate volume on given distance */ native float GetDistGainFromSoundLevel(int soundlevel, float distance); @@ -307,16 +308,16 @@ native float GetDistGainFromSoundLevel(int soundlevel, float distance); * * NOTICE: all parameters can be overwritten to modify the default behavior. * - * @param sample Sound file name relative to the "sounds" folder. - * @param entity Entity index associated to the sound. - * @param volume Volume (from 0.0 to 1.0). - * @param level Sound level (from 0 to 255). - * @param pitch Pitch (from 0 to 255). - * @param pos Origin of sound. - * @param flags Sound flags. - * @param delay Play delay. - * @return Plugin_Continue to allow the sound to be played, Plugin_Stop to block it, - * Plugin_Changed when any parameter has been modified. + * @param sample Sound file name relative to the "sound" folder. + * @param entity Entity index associated to the sound. + * @param volume Volume (from 0.0 to 1.0). + * @param level Sound level (from 0 to 255). + * @param pitch Pitch (from 0 to 255). + * @param pos Origin of sound. + * @param flags Sound flags. + * @param delay Play delay. + * @return Plugin_Continue to allow the sound to be played, Plugin_Stop to block it, + * Plugin_Changed when any parameter has been modified. */ typedef AmbientSHook = function Action ( char sample[PLATFORM_MAX_PATH], @@ -336,7 +337,7 @@ typeset NormalSHook // // @param clients Array of client indexes. // @param numClients Number of clients in the array (modify this value if you add/remove elements from the client array). - // @param sample Sound file name relative to the "sounds" folder. + // @param sample Sound file name relative to the "sound" folder. // @param entity Entity emitting the sound. // @param channel Channel emitting the sound. // @param volume Sound volume. @@ -345,17 +346,17 @@ typeset NormalSHook // @param flags Sound flags. // @param soundEntry Game sound entry name. (Used in engines newer than Portal 2) // @param seed Sound seed. (Used in engines newer than Portal 2) - // @return Plugin_Continue to allow the sound to be played, Plugin_Stop to block it, + // @return Plugin_Continue to allow the sound to be played, Plugin_Stop to block it, // Plugin_Changed when any parameter has been modified. function Action (int clients[MAXPLAYERS], int &numClients, char sample[PLATFORM_MAX_PATH], int &entity, int &channel, float &volume, int &level, int &pitch, int &flags, char soundEntry[PLATFORM_MAX_PATH], int &seed); - + // Deprecated. Use other prototype. function Action (int clients[64], int &numClients, char sample[PLATFORM_MAX_PATH], int &entity, int &channel, float &volume, int &level, int &pitch, int &flags, char soundEntry[PLATFORM_MAX_PATH], int &seed); - + // Deprecated. Use other prototype. function Action (int clients[64], int &numClients, char sample[PLATFORM_MAX_PATH], int &entity, int &channel, float &volume, int &level, int &pitch, int &flags); @@ -364,52 +365,52 @@ typeset NormalSHook /** * Hooks all played ambient sounds. * - * @param hook Function to use as a hook. - * @error Invalid function hook. + * @param hook Function to use as a hook. + * @error Invalid function hook. */ native void AddAmbientSoundHook(AmbientSHook hook); /** * Hooks all played normal sounds. * - * @param hook Function to use as a hook. - * @error Invalid function hook. + * @param hook Function to use as a hook. + * @error Invalid function hook. */ native void AddNormalSoundHook(NormalSHook hook); /** * Unhooks all played ambient sounds. * - * @param hook Function used for the hook. - * @error Invalid function hook. + * @param hook Function used for the hook. + * @error Invalid function hook. */ native void RemoveAmbientSoundHook(AmbientSHook hook); /** * Unhooks all played normal sounds. * - * @param hook Function used for the hook. - * @error Invalid function hook. + * @param hook Function used for the hook. + * @error Invalid function hook. */ native void RemoveNormalSoundHook(NormalSHook hook); - + /** * Wrapper to emit sound to one client. * - * @param client Client index. - * @param sample Sound file name relative to the "sounds" folder. - * @param entity Entity to emit from. - * @param channel Channel to emit with. - * @param level Sound level. - * @param flags Sound flags. - * @param volume Sound volume. - * @param pitch Sound pitch. - * @param speakerentity Unknown. - * @param origin Sound origin. - * @param dir Sound direction. - * @param updatePos Unknown (updates positions?) - * @param soundtime Alternate time to play sound for. - * @error Invalid client index. + * @param client Client index. + * @param sample Sound file name relative to the "sound" folder. + * @param entity Entity to emit from. + * @param channel Channel to emit with. + * @param level Sound level. + * @param flags Sound flags. + * @param volume Sound volume. + * @param pitch Sound pitch. + * @param speakerentity Unknown. + * @param origin Sound origin. + * @param dir Sound direction. + * @param updatePos Unknown (updates positions?) + * @param soundtime Alternate time to play sound for. + * @error Invalid client index. */ stock void EmitSoundToClient(int client, const char[] sample, @@ -429,7 +430,7 @@ stock void EmitSoundToClient(int client, clients[0] = client; /* Save some work for SDKTools and remove SOUND_FROM_PLAYER references */ entity = (entity == SOUND_FROM_PLAYER) ? client : entity; - EmitSound(clients, 1, sample, entity, channel, + EmitSound(clients, 1, sample, entity, channel, level, flags, volume, pitch, speakerentity, origin, dir, updatePos, soundtime); } @@ -437,19 +438,19 @@ stock void EmitSoundToClient(int client, /** * Wrapper to emit sound to all clients. * - * @param sample Sound file name relative to the "sounds" folder. - * @param entity Entity to emit from. - * @param channel Channel to emit with. - * @param level Sound level. - * @param flags Sound flags. - * @param volume Sound volume. - * @param pitch Sound pitch. - * @param speakerentity Unknown. - * @param origin Sound origin. - * @param dir Sound direction. - * @param updatePos Unknown (updates positions?) - * @param soundtime Alternate time to play sound for. - * @error Invalid client index. + * @param sample Sound file name relative to the "sound" folder. + * @param entity Entity to emit from. + * @param channel Channel to emit with. + * @param level Sound level. + * @param flags Sound flags. + * @param volume Sound volume. + * @param pitch Sound pitch. + * @param speakerentity Unknown. + * @param origin Sound origin. + * @param dir Sound direction. + * @param updatePos Unknown (updates positions?) + * @param soundtime Alternate time to play sound for. + * @error Invalid client index. */ stock void EmitSoundToAll(const char[] sample, int entity = SOUND_FROM_PLAYER, @@ -466,7 +467,7 @@ stock void EmitSoundToAll(const char[] sample, { int[] clients = new int[MaxClients]; int total = 0; - + for (int i=1; i<=MaxClients; i++) { if (IsClientInGame(i)) @@ -474,23 +475,21 @@ stock void EmitSoundToAll(const char[] sample, clients[total++] = i; } } - - if (!total) + + if (total) { - return; + EmitSound(clients, total, sample, entity, channel, + level, flags, volume, pitch, speakerentity, + origin, dir, updatePos, soundtime); } - - EmitSound(clients, total, sample, entity, channel, - level, flags, volume, pitch, speakerentity, - origin, dir, updatePos, soundtime); } /** - * Converts an attenuation value to a sound level. + * Converts an attenuation value to a sound level. * This function is from the HL2SDK. * - * @param attn Attenuation value. - * @return Integer sound level. + * @param attn Attenuation value. + * @return Integer sound level. */ stock int ATTN_TO_SNDLEVEL(float attn) { @@ -510,16 +509,16 @@ stock int ATTN_TO_SNDLEVEL(float attn) * Note that if a game sound has a rndwave section, one of them will be returned * at random. * - * @param gameSound Name of game sound. - * @param channel Channel to emit with. - * @param level Sound level. - * @param volume Sound volume. - * @param pitch Sound pitch. - * @param sample Sound file name relative to the "sounds" folder. - * @param maxlength Maximum length of sample string buffer. - * @param entity Entity the sound is being emitted from. - * @return True if the sound was successfully retrieved, false if it - * was not found + * @param gameSound Name of game sound. + * @param channel Channel to emit with. + * @param level Sound level. + * @param volume Sound volume. + * @param pitch Sound pitch. + * @param sample Sound file name relative to the "sound" folder. + * @param maxlength Maximum length of sample string buffer. + * @param entity Entity the sound is being emitted from. + * @return True if the sound was successfully retrieved, false if it + * was not found */ native bool GetGameSoundParams(const char[] gameSound, int &channel, @@ -539,18 +538,18 @@ native bool GetGameSoundParams(const char[] gameSound, * Note that if a game sound has a rndwave section, one of them will be returned * at random. * - * @param clients Array of client indexes. - * @param numClients Number of clients in the array. - * @param gameSound Name of game sound. - * @param entity Entity to emit from. - * @param flags Sound flags. - * @param speakerentity Unknown. - * @param origin Sound origin. - * @param dir Sound direction. - * @param updatePos Unknown (updates positions?) - * @param soundtime Alternate time to play sound for. - * @return True if the sound was played successfully, false if it failed - * @error Invalid client index. + * @param clients Array of client indexes. + * @param numClients Number of clients in the array. + * @param gameSound Name of game sound. + * @param entity Entity to emit from. + * @param flags Sound flags. + * @param speakerentity Unknown. + * @param origin Sound origin. + * @param dir Sound direction. + * @param updatePos Unknown (updates positions?) + * @param soundtime Alternate time to play sound for. + * @return True if the sound was played successfully, false if it failed + * @error Invalid client index. */ stock bool EmitGameSound(const int[] clients, int numClients, @@ -568,16 +567,14 @@ stock bool EmitGameSound(const int[] clients, float volume; int pitch; char sample[PLATFORM_MAX_PATH]; - + if (GetGameSoundParams(gameSound, channel, level, volume, pitch, sample, sizeof(sample), entity)) { EmitSound(clients, numClients, sample, entity, channel, level, flags, volume, pitch, speakerentity, origin, dir, updatePos, soundtime); return true; } - else - { - return false; - } + + return false; } /** @@ -589,11 +586,11 @@ stock bool EmitGameSound(const int[] clients, * Note that if a game sound has a rndwave section, one of them will be returned * at random. * - * @param gameSound Name of game sound. - * @param pos Origin of sound. - * @param entity Entity index to associate sound with. - * @param flags Sound flags. - * @param delay Play delay. + * @param gameSound Name of game sound. + * @param pos Origin of sound. + * @param entity Entity index to associate sound with. + * @param flags Sound flags. + * @param delay Play delay. */ stock bool EmitAmbientGameSound(const char[] gameSound, const float pos[3], @@ -606,16 +603,14 @@ stock bool EmitAmbientGameSound(const char[] gameSound, float volume; int pitch; char sample[PLATFORM_MAX_PATH]; - + if (GetGameSoundParams(gameSound, channel, level, volume, pitch, sample, sizeof(sample), entity)) { EmitAmbientSound(sample, pos, entity, level, flags, volume, pitch, delay); return true; } - else - { - return false; - } + + return false; } /** @@ -627,16 +622,16 @@ stock bool EmitAmbientGameSound(const char[] gameSound, * Note that if a game sound has a rndwave section, one of them will be returned * at random. * - * @param client Client index. - * @param gameSound Name of game sound. - * @param entity Entity to emit from. - * @param flags Sound flags. - * @param speakerentity Unknown. - * @param origin Sound origin. - * @param dir Sound direction. - * @param updatePos Unknown (updates positions?) - * @param soundtime Alternate time to play sound for. - * @error Invalid client index. + * @param client Client index. + * @param gameSound Name of game sound. + * @param entity Entity to emit from. + * @param flags Sound flags. + * @param speakerentity Unknown. + * @param origin Sound origin. + * @param dir Sound direction. + * @param updatePos Unknown (updates positions?) + * @param soundtime Alternate time to play sound for. + * @error Invalid client index. */ stock bool EmitGameSoundToClient(int client, const char[] gameSound, @@ -665,15 +660,15 @@ stock bool EmitGameSoundToClient(int client, * Note that if a game sound has a rndwave section, one of them will be returned * at random. * - * @param gameSound Name of game sound. - * @param entity Entity to emit from. - * @param flags Sound flags. - * @param speakerentity Unknown. - * @param origin Sound origin. - * @param dir Sound direction. - * @param updatePos Unknown (updates positions?) - * @param soundtime Alternate time to play sound for. - * @error Invalid client index. + * @param gameSound Name of game sound. + * @param entity Entity to emit from. + * @param flags Sound flags. + * @param speakerentity Unknown. + * @param origin Sound origin. + * @param dir Sound direction. + * @param updatePos Unknown (updates positions?) + * @param soundtime Alternate time to play sound for. + * @error Invalid client index. */ stock bool EmitGameSoundToAll(const char[] gameSound, int entity = SOUND_FROM_PLAYER, @@ -686,7 +681,7 @@ stock bool EmitGameSoundToAll(const char[] gameSound, { int[] clients = new int[MaxClients]; int total = 0; - + for (int i=1; i<=MaxClients; i++) { if (IsClientInGame(i)) @@ -694,12 +689,12 @@ stock bool EmitGameSoundToAll(const char[] gameSound, clients[total++] = i; } } - + if (!total) { return false; } - + return EmitGameSound(clients, total, gameSound, entity, flags, speakerentity, origin, dir, updatePos, soundtime); } @@ -710,16 +705,15 @@ stock bool EmitGameSoundToAll(const char[] gameSound, * Most games will precache all game sounds on map start, but this is not guaranteed... * Team Fortress 2 is known to not pre-cache MvM game mode sounds on non-MvM maps. * - * Due to the above, this native should be called before any calls to GetGameSoundParams, + * Due to the above, this native should be called before any calls to GetGameSoundParams, * EmitGameSound*, or EmitAmbientGameSound. * * It should be safe to pass already precached game sounds to this function. - * + * * Note: It precaches all files for a game sound. - * - * @param soundname Game sound to precache - * - * @return True if the game sound was found, false if sound did not exist - * or had no files + * + * @param soundname Game sound to precache + * @return True if the game sound was found, false if sound did not exist + * or had no files */ native bool PrecacheScriptSound(const char[] soundname); diff --git a/addons/sourcemod/scripting/include/sdktools_stocks.inc b/addons/sourcemod/scripting/include/sdktools_stocks.inc index dfc32e0..9417938 100644 --- a/addons/sourcemod/scripting/include/sdktools_stocks.inc +++ b/addons/sourcemod/scripting/include/sdktools_stocks.inc @@ -31,7 +31,7 @@ */ #if defined _sdktools_stocks_included - #endinput + #endinput #endif #define _sdktools_stocks_included @@ -42,10 +42,10 @@ * first N characters of the team names, where N is the number of * characters in the search pattern. * - * @param name Partial or full team name. - * @return A valid team index on success. - * -1 if no team matched. - * -2 if more than one team matched. + * @param name Partial or full team name. + * @return A valid team index on success. + * -1 if no team matched. + * -2 if more than one team matched. */ stock int FindTeamByName(const char[] name) { diff --git a/addons/sourcemod/scripting/include/sdktools_stringtables.inc b/addons/sourcemod/scripting/include/sdktools_stringtables.inc index 9d36c2d..497dd99 100644 --- a/addons/sourcemod/scripting/include/sdktools_stringtables.inc +++ b/addons/sourcemod/scripting/include/sdktools_stringtables.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -31,131 +31,131 @@ */ #if defined _sdktools_stringtables_included - #endinput + #endinput #endif #define _sdktools_stringtables_included -#define INVALID_STRING_TABLE -1 /**< An invalid string table index */ -#define INVALID_STRING_INDEX -1 /**< An invalid string index in a table */ +#define INVALID_STRING_TABLE -1 /**< An invalid string table index */ +#define INVALID_STRING_INDEX -1 /**< An invalid string index in a table */ /** * Searches for a string table. * - * @param name Name of string table to find. - * @return A string table index number if found, INVALID_STRING_TABLE otherwise. + * @param name Name of string table to find. + * @return A string table index number if found, INVALID_STRING_TABLE otherwise. */ native int FindStringTable(const char[] name); /** * Returns the number of string tables that currently exist. * - * @return Number of string tables that currently exist. + * @return Number of string tables that currently exist. */ native int GetNumStringTables(); /** * Returns the number of strings that currently exist in a given string table. * - * @param tableidx A string table index. - * @return Number of strings that currently exist. - * @error Invalid string table index. + * @param tableidx A string table index. + * @return Number of strings that currently exist. + * @error Invalid string table index. */ native int GetStringTableNumStrings(int tableidx); /** * Returns the maximum number of strings that are allowed in a given string table. * - * @param tableidx A string table index. - * @return Maximum number of strings allowed. - * @error Invalid string table index. + * @param tableidx A string table index. + * @return Maximum number of strings allowed. + * @error Invalid string table index. */ native int GetStringTableMaxStrings(int tableidx); /** * Retrieves the name of a string table. * - * @param tableidx A string table index. - * @param name Buffer to store the name of the string table. - * @param maxlength Maximum length of string buffer. - * @return Number of bytes written to the buffer (UTF-8 safe). - * @error Invalid string table index. + * @param tableidx A string table index. + * @param name Buffer to store the name of the string table. + * @param maxlength Maximum length of string buffer. + * @return Number of bytes written to the buffer (UTF-8 safe). + * @error Invalid string table index. */ native int GetStringTableName(int tableidx, char[] name, int maxlength); /** * Searches for the index of a given string in a string table. * - * @param tableidx A string table index. - * @param str String to find. - * @return String index if found, INVALID_STRING_INDEX otherwise. - * @error Invalid string table index. + * @param tableidx A string table index. + * @param str String to find. + * @return String index if found, INVALID_STRING_INDEX otherwise. + * @error Invalid string table index. */ native int FindStringIndex(int tableidx, const char[] str); /** * Retrieves the string at a given index of a string table. * - * @param tableidx A string table index. - * @param stringidx A string index. - * @param str Buffer to store the string value. - * @param maxlength Maximum length of string buffer. - * @return Number of bytes written to the buffer (UTF-8 safe). - * @error Invalid string table index or string index. + * @param tableidx A string table index. + * @param stringidx A string index. + * @param str Buffer to store the string value. + * @param maxlength Maximum length of string buffer. + * @return Number of bytes written to the buffer (UTF-8 safe). + * @error Invalid string table index or string index. */ native int ReadStringTable(int tableidx, int stringidx, char[] str, int maxlength); /** * Returns the length of the user data associated with a given string index. * - * @param tableidx A string table index. - * @param stringidx A string index. - * @return Length of user data. This will be 0 if there is no user data. - * @error Invalid string table index or string index. + * @param tableidx A string table index. + * @param stringidx A string index. + * @return Length of user data. This will be 0 if there is no user data. + * @error Invalid string table index or string index. */ native int GetStringTableDataLength(int tableidx, int stringidx); /** * Retrieves the user data associated with a given string index. * - * @param tableidx A string table index. - * @param stringidx A string index. - * @param userdata Buffer to store the user data. This will be set to "" if there is no user data. - * @param maxlength Maximum length of string buffer. - * @return Number of bytes written to the buffer (UTF-8 safe). - * @error Invalid string table index or string index. + * @param tableidx A string table index. + * @param stringidx A string index. + * @param userdata Buffer to store the user data. This will be set to "" if there is no user data. + * @param maxlength Maximum length of string buffer. + * @return Number of bytes written to the buffer (UTF-8 safe). + * @error Invalid string table index or string index. */ native int GetStringTableData(int tableidx, int stringidx, char[] userdata, int maxlength); /** * Sets the user data associated with a given string index. * - * @param tableidx A string table index. - * @param stringidx A string index. - * @param userdata User data string that will be set. - * @param length Length of user data string. This should include the null terminator. - * @return Number of bytes written to the buffer (UTF-8 safe). - * @error Invalid string table index or string index. + * @param tableidx A string table index. + * @param stringidx A string index. + * @param userdata User data string that will be set. + * @param length Length of user data string. This should include the null terminator. + * @return Number of bytes written to the buffer (UTF-8 safe). + * @error Invalid string table index or string index. */ native int SetStringTableData(int tableidx, int stringidx, const char[] userdata, int length); /** * Adds a string to a given string table. * - * @param tableidx A string table index. - * @param str String to add. - * @param userdata An optional user data string. - * @param length Length of user data string. This should include the null terminator. - * If set to -1, then user data will be not be altered if the specified string - * already exists in the string table. + * @param tableidx A string table index. + * @param str String to add. + * @param userdata An optional user data string. + * @param length Length of user data string. This should include the null terminator. + * If set to -1, then user data will be not be altered if the specified string + * already exists in the string table. */ native void AddToStringTable(int tableidx, const char[] str, const char[] userdata="", int length=-1); /** * Locks or unlocks the network string tables. * - * @param lock Determines whether network string tables should be locked. - * True means the tables should be locked for writing; false means unlocked. - * @return Previous lock state. + * @param lock Determines whether network string tables should be locked. + * True means the tables should be locked for writing; false means unlocked. + * @return Previous lock state. */ native bool LockStringTables(bool lock); @@ -163,17 +163,17 @@ native bool LockStringTables(bool lock); * Adds a file to the downloadables network string table. * This forces a client to download the file if they do not already have it. * - * @param filename File that will be added to downloadables table. + * @param filename File that will be added to downloadables table. */ stock void AddFileToDownloadsTable(const char[] filename) { static int table = INVALID_STRING_TABLE; - + if (table == INVALID_STRING_TABLE) { table = FindStringTable("downloadables"); } - + bool save = LockStringTables(false); AddToStringTable(table, filename); LockStringTables(save); diff --git a/addons/sourcemod/scripting/include/sdktools_tempents.inc b/addons/sourcemod/scripting/include/sdktools_tempents.inc index 252fdd7..cc35c71 100644 --- a/addons/sourcemod/scripting/include/sdktools_tempents.inc +++ b/addons/sourcemod/scripting/include/sdktools_tempents.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -38,128 +38,128 @@ /** * Called when a temp entity is going to be sent. * - * @param te_name TE name. - * @param Players Array containing target player indexes. - * @param numClients Number of players in the array. - * @param delay Delay in seconds to send the TE. - * @return Plugin_Continue to allow the transmission of the TE, Plugin_Stop to block it. + * @param te_name TE name. + * @param Players Array containing target player indexes. + * @param numClients Number of players in the array. + * @param delay Delay in seconds to send the TE. + * @return Plugin_Continue to allow the transmission of the TE, Plugin_Stop to block it. */ typedef TEHook = function Action (const char[] te_name, const int[] Players, int numClients, float delay); /** * Hooks a temp entity. * - * @param te_name TE name to hook. - * @param hook Function to use as a hook. - * @error Temp Entity name not available or invalid function hook. + * @param te_name TE name to hook. + * @param hook Function to use as a hook. + * @error Temp Entity name not available or invalid function hook. */ native void AddTempEntHook(const char[] te_name, TEHook hook); /** * Removes a temp entity hook. * - * @param te_name TE name to unhook. - * @param hook Function used for the hook. - * @error Temp Entity name not available or invalid function hook. + * @param te_name TE name to unhook. + * @param hook Function used for the hook. + * @error Temp Entity name not available or invalid function hook. */ native void RemoveTempEntHook(const char[] te_name, TEHook hook); /** * Starts a temp entity transmission. * - * @param te_name TE name. - * @error Temp Entity name not available. + * @param te_name TE name. + * @error Temp Entity name not available. */ native void TE_Start(const char[] te_name); /** * Checks if a certain TE property exists. * - * @param prop Property to use. - * @return True if the property exists, otherwise false. + * @param prop Property to use. + * @return True if the property exists, otherwise false. */ native bool TE_IsValidProp(const char[] prop); /** * Sets an integer value in the current temp entity. * - * @param prop Property to use. - * @param value Integer value to set. - * @error Property not found. + * @param prop Property to use. + * @param value Integer value to set. + * @error Property not found. */ native void TE_WriteNum(const char[] prop, int value); /** * Reads an integer value in the current temp entity. * - * @param prop Property to use. - * @return Property value. - * @error Property not found. + * @param prop Property to use. + * @return Property value. + * @error Property not found. */ native int TE_ReadNum(const char[] prop); /** * Sets a floating point number in the current temp entity. * - * @param prop Property to use. - * @param value Floating point number to set. - * @error Property not found. + * @param prop Property to use. + * @param value Floating point number to set. + * @error Property not found. */ native void TE_WriteFloat(const char[] prop, float value); /** * Reads a floating point number in the current temp entity. * - * @param prop Property to use. - * @return Property value. - * @error Property not found. + * @param prop Property to use. + * @return Property value. + * @error Property not found. */ native float TE_ReadFloat(const char[] prop); /** * Sets a vector in the current temp entity. * - * @param prop Property to use. - * @param vector Vector to set. - * @error Property not found. + * @param prop Property to use. + * @param vector Vector to set. + * @error Property not found. */ native void TE_WriteVector(const char[] prop, const float vector[3]); /** * Reads a vector in the current temp entity. * - * @param prop Property to use. - * @param vector Vector to read. - * @error Property not found. + * @param prop Property to use. + * @param vector Vector to read. + * @error Property not found. */ native void TE_ReadVector(const char[] prop, float vector[3]); /** * Sets a QAngle in the current temp entity. * - * @param prop Property to use. - * @param angles Angles to set. - * @error Property not found. + * @param prop Property to use. + * @param angles Angles to set. + * @error Property not found. */ native void TE_WriteAngles(const char[] prop, const float angles[3]); /** * Sets an array of floats in the current temp entity. * - * @param prop Property to use. - * @param array Array of values to copy. - * @param arraySize Number of values to copy. - * @error Property not found. + * @param prop Property to use. + * @param array Array of values to copy. + * @param arraySize Number of values to copy. + * @error Property not found. */ native void TE_WriteFloatArray(const char[] prop, const float[] array, int arraySize); /** * Sends the current temp entity to one or more clients. * - * @param clients Array containing player indexes to broadcast to. - * @param numClients Number of players in the array. - * @param delay Delay in seconds to send the TE. - * @error Invalid client index or client not in game. + * @param clients Array containing player indexes to broadcast to. + * @param numClients Number of players in the array. + * @param delay Delay in seconds to send the TE. + * @error Invalid client index or client not in game. */ native void TE_Send(const int[] clients, int numClients, float delay=0.0); @@ -167,9 +167,9 @@ native void TE_Send(const int[] clients, int numClients, float delay=0.0); * Sets an encoded entity index in the current temp entity. * (This is usually used for m_nStartEntity and m_nEndEntity). * - * @param prop Property to use. - * @param value Value to set. - * @error Property not found. + * @param prop Property to use. + * @param value Value to set. + * @error Property not found. */ stock void TE_WriteEncodedEnt(const char[] prop, int value) { @@ -181,7 +181,7 @@ stock void TE_WriteEncodedEnt(const char[] prop, int value) * Broadcasts the current temp entity to all clients. * @note See TE_Start(). * - * @param delay Delay in seconds to send the TE. + * @param delay Delay in seconds to send the TE. */ stock void TE_SendToAll(float delay=0.0) { @@ -201,9 +201,9 @@ stock void TE_SendToAll(float delay=0.0) * Sends the current TE to only a client. * @note See TE_Start(). * - * @param client Client to send to. - * @param delay Delay in seconds to send the TE. - * @error Invalid client index or client not in game. + * @param client Client to send to. + * @param delay Delay in seconds to send the TE. + * @error Invalid client index or client not in game. */ stock void TE_SendToClient(int client, float delay=0.0) { @@ -215,14 +215,14 @@ stock void TE_SendToClient(int client, float delay=0.0) } /** - * Sends the current TE to all clients that are in + * Sends the current TE to all clients that are in * visible or audible range of the origin. * @note See TE_Start(). * @note See GetClientsInRange() * - * @param origin Coordinates from which to test range. - * @param rangeType Range type to use for filtering clients. - * @param delay Delay in seconds to send the TE. + * @param origin Coordinates from which to test range. + * @param rangeType Range type to use for filtering clients. + * @param delay Delay in seconds to send the TE. */ stock void TE_SendToAllInRange(float origin[3], ClientRangeType rangeType, float delay=0.0) { diff --git a/addons/sourcemod/scripting/include/sdktools_tempents_stocks.inc b/addons/sourcemod/scripting/include/sdktools_tempents_stocks.inc index d114ba0..75dfc5e 100644 --- a/addons/sourcemod/scripting/include/sdktools_tempents_stocks.inc +++ b/addons/sourcemod/scripting/include/sdktools_tempents_stocks.inc @@ -38,15 +38,15 @@ /** * @section TE Explosion flags. */ -#define TE_EXPLFLAG_NONE 0x0 /**< all flags clear makes default Half-Life explosion */ -#define TE_EXPLFLAG_NOADDITIVE 0x1 /**< sprite will be drawn opaque (ensure that the sprite you send is a non-additive sprite) */ -#define TE_EXPLFLAG_NODLIGHTS 0x2 /**< do not render dynamic lights */ -#define TE_EXPLFLAG_NOSOUND 0x4 /**< do not play client explosion sound */ -#define TE_EXPLFLAG_NOPARTICLES 0x8 /**< do not draw particles */ -#define TE_EXPLFLAG_DRAWALPHA 0x10 /**< sprite will be drawn alpha */ -#define TE_EXPLFLAG_ROTATE 0x20 /**< rotate the sprite randomly */ -#define TE_EXPLFLAG_NOFIREBALL 0x40 /**< do not draw a fireball */ -#define TE_EXPLFLAG_NOFIREBALLSMOKE 0x80 /**< do not draw smoke with the fireball */ +#define TE_EXPLFLAG_NONE 0x0 /**< all flags clear makes default Half-Life explosion */ +#define TE_EXPLFLAG_NOADDITIVE 0x1 /**< sprite will be drawn opaque (ensure that the sprite you send is a non-additive sprite) */ +#define TE_EXPLFLAG_NODLIGHTS 0x2 /**< do not render dynamic lights */ +#define TE_EXPLFLAG_NOSOUND 0x4 /**< do not play client explosion sound */ +#define TE_EXPLFLAG_NOPARTICLES 0x8 /**< do not draw particles */ +#define TE_EXPLFLAG_DRAWALPHA 0x10 /**< sprite will be drawn alpha */ +#define TE_EXPLFLAG_ROTATE 0x20 /**< rotate the sprite randomly */ +#define TE_EXPLFLAG_NOFIREBALL 0x40 /**< do not draw a fireball */ +#define TE_EXPLFLAG_NOFIREBALLSMOKE 0x80 /**< do not draw smoke with the fireball */ /** * @endsection @@ -55,22 +55,22 @@ /** * @section TE Beam flags. */ -#define FBEAM_STARTENTITY 0x00000001 -#define FBEAM_ENDENTITY 0x00000002 -#define FBEAM_FADEIN 0x00000004 -#define FBEAM_FADEOUT 0x00000008 -#define FBEAM_SINENOISE 0x00000010 -#define FBEAM_SOLID 0x00000020 -#define FBEAM_SHADEIN 0x00000040 -#define FBEAM_SHADEOUT 0x00000080 -#define FBEAM_ONLYNOISEONCE 0x00000100 /**< Only calculate our noise once */ -#define FBEAM_NOTILE 0x00000200 -#define FBEAM_USE_HITBOXES 0x00000400 /**< Attachment indices represent hitbox indices instead when this is set. */ -#define FBEAM_STARTVISIBLE 0x00000800 /**< Has this client actually seen this beam's start entity yet? */ -#define FBEAM_ENDVISIBLE 0x00001000 /**< Has this client actually seen this beam's end entity yet? */ -#define FBEAM_ISACTIVE 0x00002000 -#define FBEAM_FOREVER 0x00004000 -#define FBEAM_HALOBEAM 0x00008000 /**< When drawing a beam with a halo, don't ignore the segments and endwidth */ +#define FBEAM_STARTENTITY 0x00000001 +#define FBEAM_ENDENTITY 0x00000002 +#define FBEAM_FADEIN 0x00000004 +#define FBEAM_FADEOUT 0x00000008 +#define FBEAM_SINENOISE 0x00000010 +#define FBEAM_SOLID 0x00000020 +#define FBEAM_SHADEIN 0x00000040 +#define FBEAM_SHADEOUT 0x00000080 +#define FBEAM_ONLYNOISEONCE 0x00000100 /**< Only calculate our noise once */ +#define FBEAM_NOTILE 0x00000200 +#define FBEAM_USE_HITBOXES 0x00000400 /**< Attachment indices represent hitbox indices instead when this is set. */ +#define FBEAM_STARTVISIBLE 0x00000800 /**< Has this client actually seen this beam's start entity yet? */ +#define FBEAM_ENDVISIBLE 0x00001000 /**< Has this client actually seen this beam's end entity yet? */ +#define FBEAM_ISACTIVE 0x00002000 +#define FBEAM_FOREVER 0x00004000 +#define FBEAM_HALOBEAM 0x00008000 /**< When drawing a beam with a halo, don't ignore the segments and endwidth */ /** * @endsection @@ -79,10 +79,10 @@ /** * Sets up a sparks effect. * - * @param pos Position of the sparks. - * @param dir Direction of the sparks. - * @param Magnitude Sparks size. - * @param TrailLength Trail lenght of the sparks. + * @param pos Position of the sparks. + * @param dir Direction of the sparks. + * @param Magnitude Sparks size. + * @param TrailLength Trail lenght of the sparks. */ stock void TE_SetupSparks(const float pos[3], const float dir[3], int Magnitude, int TrailLength) { @@ -96,10 +96,10 @@ stock void TE_SetupSparks(const float pos[3], const float dir[3], int Magnitude, /** * Sets up a smoke effect. * - * @param pos Position of the smoke. - * @param Model Precached model index. - * @param Scale Scale of the smoke. - * @param FrameRate Frame rate of the smoke. + * @param pos Position of the smoke. + * @param Model Precached model index. + * @param Scale Scale of the smoke. + * @param FrameRate Frame rate of the smoke. */ stock void TE_SetupSmoke(const float pos[3], int Model, float Scale, int FrameRate) { @@ -113,10 +113,10 @@ stock void TE_SetupSmoke(const float pos[3], int Model, float Scale, int FrameRa /** * Sets up a dust cloud effect. * - * @param pos Position of the dust. - * @param dir Direction of the dust. - * @param Size Dust cloud size. - * @param Speed Dust cloud speed. + * @param pos Position of the dust. + * @param dir Direction of the dust. + * @param Size Dust cloud size. + * @param Speed Dust cloud speed. */ stock void TE_SetupDust(const float pos[3], const float dir[3], float Size, float Speed) { @@ -130,10 +130,10 @@ stock void TE_SetupDust(const float pos[3], const float dir[3], float Size, floa /** * Sets up a muzzle flash effect. * - * @param pos Position of the muzzle flash. - * @param angles Rotation angles of the muzzle flash. - * @param Scale Scale of the muzzle flash. - * @param Type Muzzle flash type to render (Mod specific). + * @param pos Position of the muzzle flash. + * @param angles Rotation angles of the muzzle flash. + * @param Scale Scale of the muzzle flash. + * @param Type Muzzle flash type to render (Mod specific). */ stock void TE_SetupMuzzleFlash(const float pos[3], const float angles[3], float Scale, int Type) { @@ -147,8 +147,8 @@ stock void TE_SetupMuzzleFlash(const float pos[3], const float angles[3], float /** * Sets up a metal sparks effect. * - * @param pos Position of the metal sparks. - * @param dir Direction of the metal sparks. + * @param pos Position of the metal sparks. + * @param dir Direction of the metal sparks. */ stock void TE_SetupMetalSparks(const float pos[3], const float dir[3]) { @@ -160,9 +160,9 @@ stock void TE_SetupMetalSparks(const float pos[3], const float dir[3]) /** * Sets up an energy splash effect. * - * @param pos Position of the energy splash. - * @param dir Direction of the energy splash. - * @param Explosive Makes the effect explosive. + * @param pos Position of the energy splash. + * @param dir Direction of the energy splash. + * @param Explosive Makes the effect explosive. */ stock void TE_SetupEnergySplash(const float pos[3], const float dir[3], bool Explosive) { @@ -175,8 +175,8 @@ stock void TE_SetupEnergySplash(const float pos[3], const float dir[3], bool Exp /** * Sets up an armor ricochet effect. * - * @param pos Position of the armor ricochet. - * @param dir Direction of the armor ricochet. + * @param pos Position of the armor ricochet. + * @param dir Direction of the armor ricochet. */ stock void TE_SetupArmorRicochet(const float pos[3], const float dir[3]) { @@ -188,11 +188,11 @@ stock void TE_SetupArmorRicochet(const float pos[3], const float dir[3]) /** * Sets up a glowing sprite effect. * - * @param pos Position of the sprite. - * @param Model Precached model index. - * @param Life Time duration of the sprite. - * @param Size Sprite size. - * @param Brightness Sprite brightness. + * @param pos Position of the sprite. + * @param Model Precached model index. + * @param Life Time duration of the sprite. + * @param Size Sprite size. + * @param Brightness Sprite brightness. */ stock void TE_SetupGlowSprite(const float pos[3], int Model, float Life, float Size, int Brightness) { @@ -207,15 +207,15 @@ stock void TE_SetupGlowSprite(const float pos[3], int Model, float Life, float S /** * Sets up a explosion effect. * - * @param pos Explosion position. - * @param Model Precached model index. - * @param Scale Explosion scale. - * @param Framerate Explosion frame rate. - * @param Flags Explosion flags. - * @param Radius Explosion radius. - * @param Magnitude Explosion size. - * @param normal Normal vector to the explosion. - * @param MaterialType Exploded material type. + * @param pos Explosion position. + * @param Model Precached model index. + * @param Scale Explosion scale. + * @param Framerate Explosion frame rate. + * @param Flags Explosion flags. + * @param Radius Explosion radius. + * @param Magnitude Explosion size. + * @param normal Normal vector to the explosion. + * @param MaterialType Exploded material type. */ stock void TE_SetupExplosion(const float pos[3], int Model, float Scale, int Framerate, int Flags, int Radius, int Magnitude, const float normal[3]={0.0, 0.0, 1.0}, int MaterialType='C') { @@ -234,12 +234,12 @@ stock void TE_SetupExplosion(const float pos[3], int Model, float Scale, int Fra /** * Sets up a blood sprite effect. * - * @param pos Position of the sprite. - * @param dir Sprite direction. - * @param color Color array (r, g, b, a). - * @param Size Sprite size. - * @param SprayModel Precached model index. - * @param BloodDropModel Precached model index. + * @param pos Position of the sprite. + * @param dir Sprite direction. + * @param color Color array (r, g, b, a). + * @param Size Sprite size. + * @param SprayModel Precached model index. + * @param BloodDropModel Precached model index. */ stock void TE_SetupBloodSprite(const float pos[3], const float dir[3], const int color[4], int Size, int SprayModel, int BloodDropModel) { @@ -258,19 +258,19 @@ stock void TE_SetupBloodSprite(const float pos[3], const float dir[3], const int /** * Sets up a beam ring point effect. * - * @param center Center position of the ring. - * @param Start_Radius Initial ring radius. - * @param End_Radius Final ring radius. - * @param ModelIndex Precached model index. - * @param HaloIndex Precached model index. - * @param StartFrame Initial frame to render. - * @param FrameRate Ring frame rate. - * @param Life Time duration of the ring. - * @param Width Beam width. - * @param Amplitude Beam amplitude. - * @param Color Color array (r, g, b, a). - * @param Speed Speed of the beam. - * @param Flags Beam flags. + * @param center Center position of the ring. + * @param Start_Radius Initial ring radius. + * @param End_Radius Final ring radius. + * @param ModelIndex Precached model index. + * @param HaloIndex Precached model index. + * @param StartFrame Initial frame to render. + * @param FrameRate Ring frame rate. + * @param Life Time duration of the ring. + * @param Width Beam width. + * @param Amplitude Beam amplitude. + * @param Color Color array (r, g, b, a). + * @param Speed Speed of the beam. + * @param Flags Beam flags. */ stock void TE_SetupBeamRingPoint(const float center[3], float Start_Radius, float End_Radius, int ModelIndex, int HaloIndex, int StartFrame, int FrameRate, float Life, float Width, float Amplitude, const int Color[4], int Speed, int Flags) @@ -299,19 +299,19 @@ stock void TE_SetupBeamRingPoint(const float center[3], float Start_Radius, floa /** * Sets up a point to point beam effect. * - * @param start Start position of the beam. - * @param end End position of the beam. - * @param ModelIndex Precached model index. - * @param HaloIndex Precached model index. - * @param StartFrame Initial frame to render. - * @param FrameRate Beam frame rate. - * @param Life Time duration of the beam. - * @param Width Initial beam width. - * @param EndWidth Final beam width. - * @param FadeLength Beam fade time duration. - * @param Amplitude Beam amplitude. - * @param Color Color array (r, g, b, a). - * @param Speed Speed of the beam. + * @param start Start position of the beam. + * @param end End position of the beam. + * @param ModelIndex Precached model index. + * @param HaloIndex Precached model index. + * @param StartFrame Initial frame to render. + * @param FrameRate Beam frame rate. + * @param Life Time duration of the beam. + * @param Width Initial beam width. + * @param EndWidth Final beam width. + * @param FadeLength Beam fade time duration. + * @param Amplitude Beam amplitude. + * @param Color Color array (r, g, b, a). + * @param Speed Speed of the beam. */ stock void TE_SetupBeamPoints(const float start[3], const float end[3], int ModelIndex, int HaloIndex, int StartFrame, int FrameRate, float Life, float Width, float EndWidth, int FadeLength, float Amplitude, const int Color[4], int Speed) @@ -338,19 +338,19 @@ stock void TE_SetupBeamPoints(const float start[3], const float end[3], int Mode /** * Sets up an entity to entity laser effect. * - * @param StartEntity Entity index from where the beam starts. - * @param EndEntity Entity index from where the beam ends. - * @param ModelIndex Precached model index. - * @param HaloIndex Precached model index. - * @param StartFrame Initial frame to render. - * @param FrameRate Beam frame rate. - * @param Life Time duration of the beam. - * @param Width Initial beam width. - * @param EndWidth Final beam width. - * @param FadeLength Beam fade time duration. - * @param Amplitude Beam amplitude. - * @param Color Color array (r, g, b, a). - * @param Speed Speed of the beam. + * @param StartEntity Entity index from where the beam starts. + * @param EndEntity Entity index from where the beam ends. + * @param ModelIndex Precached model index. + * @param HaloIndex Precached model index. + * @param StartFrame Initial frame to render. + * @param FrameRate Beam frame rate. + * @param Life Time duration of the beam. + * @param Width Initial beam width. + * @param EndWidth Final beam width. + * @param FadeLength Beam fade time duration. + * @param Amplitude Beam amplitude. + * @param Color Color array (r, g, b, a). + * @param Speed Speed of the beam. */ stock void TE_SetupBeamLaser(int StartEntity, int EndEntity, int ModelIndex, int HaloIndex, int StartFrame, int FrameRate, float Life, float Width, float EndWidth, int FadeLength, float Amplitude, const int Color[4], int Speed) @@ -377,18 +377,18 @@ stock void TE_SetupBeamLaser(int StartEntity, int EndEntity, int ModelIndex, int /** * Sets up a beam ring effect. * - * @param StartEntity Entity index from where the ring starts. - * @param EndEntity Entity index from where the ring ends. - * @param ModelIndex Precached model index. - * @param HaloIndex Precached model index. - * @param StartFrame Initial frame to render. - * @param FrameRate Ring frame rate. - * @param Life Time duration of the ring. - * @param Width Beam width. - * @param Amplitude Beam amplitude. - * @param Color Color array (r, g, b, a). - * @param Speed Speed of the beam. - * @param Flags Beam flags. + * @param StartEntity Entity index from where the ring starts. + * @param EndEntity Entity index from where the ring ends. + * @param ModelIndex Precached model index. + * @param HaloIndex Precached model index. + * @param StartFrame Initial frame to render. + * @param FrameRate Ring frame rate. + * @param Life Time duration of the ring. + * @param Width Beam width. + * @param Amplitude Beam amplitude. + * @param Color Color array (r, g, b, a). + * @param Speed Speed of the beam. + * @param Flags Beam flags. */ stock void TE_SetupBeamRing(int StartEntity, int EndEntity, int ModelIndex, int HaloIndex, int StartFrame, int FrameRate, float Life, float Width, float Amplitude, const int Color[4], int Speed, int Flags) { @@ -415,14 +415,14 @@ stock void TE_SetupBeamRing(int StartEntity, int EndEntity, int ModelIndex, int /** * Sets up a follow beam effect. * - * @param EntIndex Entity index from where the beam starts. - * @param ModelIndex Precached model index. - * @param HaloIndex Precached model index. - * @param Life Time duration of the beam. - * @param Width Initial beam width. - * @param EndWidth Final beam width. - * @param FadeLength Beam fade time duration. - * @param Color Color array (r, g, b, a). + * @param EntIndex Entity index from where the beam starts. + * @param ModelIndex Precached model index. + * @param HaloIndex Precached model index. + * @param Life Time duration of the beam. + * @param Width Initial beam width. + * @param EndWidth Final beam width. + * @param FadeLength Beam fade time duration. + * @param Color Color array (r, g, b, a). */ stock void TE_SetupBeamFollow(int EntIndex, int ModelIndex, int HaloIndex, float Life, float Width, float EndWidth, int FadeLength, const int Color[4]) { diff --git a/addons/sourcemod/scripting/include/sdktools_trace.inc b/addons/sourcemod/scripting/include/sdktools_trace.inc index daf83c7..cf977e1 100644 --- a/addons/sourcemod/scripting/include/sdktools_trace.inc +++ b/addons/sourcemod/scripting/include/sdktools_trace.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -35,70 +35,124 @@ #endif #define _sdktools_trace_included -#define CONTENTS_EMPTY 0 /**< No contents. */ -#define CONTENTS_SOLID 0x1 /**< an eye is never valid in a solid . */ -#define CONTENTS_WINDOW 0x2 /**< translucent, but not watery (glass). */ -#define CONTENTS_AUX 0x4 -#define CONTENTS_GRATE 0x8 /**< alpha-tested "grate" textures. Bullets/sight pass through, but solids don't. */ -#define CONTENTS_SLIME 0x10 -#define CONTENTS_WATER 0x20 -#define CONTENTS_MIST 0x40 -#define CONTENTS_OPAQUE 0x80 /**< things that cannot be seen through (may be non-solid though). */ -#define LAST_VISIBLE_CONTENTS 0x80 -#define ALL_VISIBLE_CONTENTS (LAST_VISIBLE_CONTENTS | (LAST_VISIBLE_CONTENTS-1)) -#define CONTENTS_TESTFOGVOLUME 0x100 -#define CONTENTS_UNUSED5 0x200 -#define CONTENTS_UNUSED6 0x4000 -#define CONTENTS_TEAM1 0x800 /**< per team contents used to differentiate collisions. */ -#define CONTENTS_TEAM2 0x1000 /**< between players and objects on different teams. */ -#define CONTENTS_IGNORE_NODRAW_OPAQUE 0x2000 /**< ignore CONTENTS_OPAQUE on surfaces that have SURF_NODRAW. */ -#define CONTENTS_MOVEABLE 0x4000 /**< hits entities which are MOVETYPE_PUSH (doors, plats, etc) */ -#define CONTENTS_AREAPORTAL 0x8000 /**< remaining contents are non-visible, and don't eat brushes. */ -#define CONTENTS_PLAYERCLIP 0x10000 -#define CONTENTS_MONSTERCLIP 0x20000 +#define CONTENTS_EMPTY 0 /**< No contents. */ +#define CONTENTS_SOLID 0x1 /**< an eye is never valid in a solid . */ +#define CONTENTS_WINDOW 0x2 /**< translucent, but not watery (glass). */ +#define CONTENTS_AUX 0x4 +#define CONTENTS_GRATE 0x8 /**< alpha-tested "grate" textures. Bullets/sight pass through, but solids don't. */ +#define CONTENTS_SLIME 0x10 +#define CONTENTS_WATER 0x20 +#define CONTENTS_MIST 0x40 +#define CONTENTS_OPAQUE 0x80 /**< things that cannot be seen through (may be non-solid though). */ +#define LAST_VISIBLE_CONTENTS 0x80 +#define ALL_VISIBLE_CONTENTS (LAST_VISIBLE_CONTENTS | (LAST_VISIBLE_CONTENTS-1)) +#define CONTENTS_TESTFOGVOLUME 0x100 +#define CONTENTS_UNUSED5 0x200 +#define CONTENTS_UNUSED6 0x4000 +#define CONTENTS_TEAM1 0x800 /**< per team contents used to differentiate collisions. */ +#define CONTENTS_TEAM2 0x1000 /**< between players and objects on different teams. */ +#define CONTENTS_IGNORE_NODRAW_OPAQUE 0x2000 /**< ignore CONTENTS_OPAQUE on surfaces that have SURF_NODRAW. */ +#define CONTENTS_MOVEABLE 0x4000 /**< hits entities which are MOVETYPE_PUSH (doors, plats, etc) */ +#define CONTENTS_AREAPORTAL 0x8000 /**< remaining contents are non-visible, and don't eat brushes. */ +#define CONTENTS_PLAYERCLIP 0x10000 +#define CONTENTS_MONSTERCLIP 0x20000 /** * @section currents can be added to any other contents, and may be mixed */ -#define CONTENTS_CURRENT_0 0x40000 -#define CONTENTS_CURRENT_90 0x80000 -#define CONTENTS_CURRENT_180 0x100000 -#define CONTENTS_CURRENT_270 0x200000 -#define CONTENTS_CURRENT_UP 0x400000 -#define CONTENTS_CURRENT_DOWN 0x800000 +#define CONTENTS_CURRENT_0 0x40000 +#define CONTENTS_CURRENT_90 0x80000 +#define CONTENTS_CURRENT_180 0x100000 +#define CONTENTS_CURRENT_270 0x200000 +#define CONTENTS_CURRENT_UP 0x400000 +#define CONTENTS_CURRENT_DOWN 0x800000 /** * @endsection */ -#define CONTENTS_ORIGIN 0x1000000 /**< removed before bsp-ing an entity. */ -#define CONTENTS_MONSTER 0x2000000 /**< should never be on a brush, only in game. */ -#define CONTENTS_DEBRIS 0x4000000 -#define CONTENTS_DETAIL 0x8000000 /**< brushes to be added after vis leafs. */ -#define CONTENTS_TRANSLUCENT 0x10000000 /**< auto set if any surface has trans. */ -#define CONTENTS_LADDER 0x20000000 -#define CONTENTS_HITBOX 0x40000000 /**< use accurate hitboxes on trace. */ +#define CONTENTS_ORIGIN 0x1000000 /**< removed before bsp-ing an entity. */ +#define CONTENTS_MONSTER 0x2000000 /**< should never be on a brush, only in game. */ +#define CONTENTS_DEBRIS 0x4000000 +#define CONTENTS_DETAIL 0x8000000 /**< brushes to be added after vis leafs. */ +#define CONTENTS_TRANSLUCENT 0x10000000 /**< auto set if any surface has trans. */ +#define CONTENTS_LADDER 0x20000000 +#define CONTENTS_HITBOX 0x40000000 /**< use accurate hitboxes on trace. */ /** * @section Trace masks. */ -#define MASK_ALL (0xFFFFFFFF) -#define MASK_SOLID (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_WINDOW|CONTENTS_MONSTER|CONTENTS_GRATE) /**< everything that is normally solid */ -#define MASK_PLAYERSOLID (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_PLAYERCLIP|CONTENTS_WINDOW|CONTENTS_MONSTER|CONTENTS_GRATE) /**< everything that blocks player movement */ -#define MASK_NPCSOLID (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_MONSTERCLIP|CONTENTS_WINDOW|CONTENTS_MONSTER|CONTENTS_GRATE) /**< blocks npc movement */ -#define MASK_WATER (CONTENTS_WATER|CONTENTS_MOVEABLE|CONTENTS_SLIME) /**< water physics in these contents */ -#define MASK_OPAQUE (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_OPAQUE) /**< everything that blocks line of sight for AI, lighting, etc */ -#define MASK_OPAQUE_AND_NPCS (MASK_OPAQUE|CONTENTS_MONSTER) /**< everything that blocks line of sight for AI, lighting, etc, but with monsters added. */ -#define MASK_VISIBLE (MASK_OPAQUE|CONTENTS_IGNORE_NODRAW_OPAQUE) /**< everything that blocks line of sight for players */ -#define MASK_VISIBLE_AND_NPCS (MASK_OPAQUE_AND_NPCS|CONTENTS_IGNORE_NODRAW_OPAQUE) /**< everything that blocks line of sight for players, but with monsters added. */ -#define MASK_SHOT (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_MONSTER|CONTENTS_WINDOW|CONTENTS_DEBRIS|CONTENTS_HITBOX) /**< bullets see these as solid */ -#define MASK_SHOT_HULL (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_MONSTER|CONTENTS_WINDOW|CONTENTS_DEBRIS|CONTENTS_GRATE) /**< non-raycasted weapons see this as solid (includes grates) */ -#define MASK_SHOT_PORTAL (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_WINDOW) /**< hits solids (not grates) and passes through everything else */ -#define MASK_SOLID_BRUSHONLY (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_WINDOW|CONTENTS_GRATE) /**< everything normally solid, except monsters (world+brush only) */ -#define MASK_PLAYERSOLID_BRUSHONLY (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_WINDOW|CONTENTS_PLAYERCLIP|CONTENTS_GRATE) /**< everything normally solid for player movement, except monsters (world+brush only) */ -#define MASK_NPCSOLID_BRUSHONLY (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_WINDOW|CONTENTS_MONSTERCLIP|CONTENTS_GRATE) /**< everything normally solid for npc movement, except monsters (world+brush only) */ -#define MASK_NPCWORLDSTATIC (CONTENTS_SOLID|CONTENTS_WINDOW|CONTENTS_MONSTERCLIP|CONTENTS_GRATE) /**< just the world, used for route rebuilding */ -#define MASK_SPLITAREAPORTAL (CONTENTS_WATER|CONTENTS_SLIME) /**< These are things that can split areaportals */ +#define MASK_ALL (0xFFFFFFFF) +#define MASK_SOLID (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_WINDOW|CONTENTS_MONSTER|CONTENTS_GRATE) /**< everything that is normally solid */ +#define MASK_PLAYERSOLID (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_PLAYERCLIP|CONTENTS_WINDOW|CONTENTS_MONSTER|CONTENTS_GRATE) /**< everything that blocks player movement */ +#define MASK_NPCSOLID (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_MONSTERCLIP|CONTENTS_WINDOW|CONTENTS_MONSTER|CONTENTS_GRATE) /**< blocks npc movement */ +#define MASK_WATER (CONTENTS_WATER|CONTENTS_MOVEABLE|CONTENTS_SLIME) /**< water physics in these contents */ +#define MASK_OPAQUE (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_OPAQUE) /**< everything that blocks line of sight for AI, lighting, etc */ +#define MASK_OPAQUE_AND_NPCS (MASK_OPAQUE|CONTENTS_MONSTER) /**< everything that blocks line of sight for AI, lighting, etc, but with monsters added. */ +#define MASK_VISIBLE (MASK_OPAQUE|CONTENTS_IGNORE_NODRAW_OPAQUE) /**< everything that blocks line of sight for players */ +#define MASK_VISIBLE_AND_NPCS (MASK_OPAQUE_AND_NPCS|CONTENTS_IGNORE_NODRAW_OPAQUE) /**< everything that blocks line of sight for players, but with monsters added. */ +#define MASK_SHOT (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_MONSTER|CONTENTS_WINDOW|CONTENTS_DEBRIS|CONTENTS_HITBOX) /**< bullets see these as solid */ +#define MASK_SHOT_HULL (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_MONSTER|CONTENTS_WINDOW|CONTENTS_DEBRIS|CONTENTS_GRATE) /**< non-raycasted weapons see this as solid (includes grates) */ +#define MASK_SHOT_PORTAL (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_WINDOW) /**< hits solids (not grates) and passes through everything else */ +#define MASK_SOLID_BRUSHONLY (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_WINDOW|CONTENTS_GRATE) /**< everything normally solid, except monsters (world+brush only) */ +#define MASK_PLAYERSOLID_BRUSHONLY (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_WINDOW|CONTENTS_PLAYERCLIP|CONTENTS_GRATE) /**< everything normally solid for player movement, except monsters (world+brush only) */ +#define MASK_NPCSOLID_BRUSHONLY (CONTENTS_SOLID|CONTENTS_MOVEABLE|CONTENTS_WINDOW|CONTENTS_MONSTERCLIP|CONTENTS_GRATE) /**< everything normally solid for npc movement, except monsters (world+brush only) */ +#define MASK_NPCWORLDSTATIC (CONTENTS_SOLID|CONTENTS_WINDOW|CONTENTS_MONSTERCLIP|CONTENTS_GRATE) /**< just the world, used for route rebuilding */ +#define MASK_SPLITAREAPORTAL (CONTENTS_WATER|CONTENTS_SLIME) /**< These are things that can split areaportals */ + +/** + * @endsection + */ + +/** + * @section Surface flags. + */ + +#define SURF_LIGHT 0x0001 /**< value will hold the light strength */ +#define SURF_SKY2D 0x0002 /**< don't draw, indicates we should skylight + draw 2d sky but not draw the 3D skybox */ +#define SURF_SKY 0x0004 /**< don't draw, but add to skybox */ +#define SURF_WARP 0x0008 /**< turbulent water warp */ +#define SURF_TRANS 0x0010 +#define SURF_NOPORTAL 0x0020 /**< the surface can not have a portal placed on it */ +#define SURF_TRIGGER 0x0040 /**< This is an xbox hack to work around elimination of trigger surfaces, which breaks occluders */ +#define SURF_NODRAW 0x0080 /**< don't bother referencing the texture */ + +#define SURF_HINT 0x0100 /**< make a primary bsp splitter */ + +#define SURF_SKIP 0x0200 /**< completely ignore, allowing non-closed brushes */ +#define SURF_NOLIGHT 0x0400 /**< Don't calculate light */ +#define SURF_BUMPLIGHT 0x0800 /**< calculate three lightmaps for the surface for bumpmapping */ +#define SURF_NOSHADOWS 0x1000 /**< Don't receive shadows */ +#define SURF_NODECALS 0x2000 /**< Don't receive decals */ +#define SURF_NOCHOP 0x4000 /**< Don't subdivide patches on this surface */ +#define SURF_HITBOX 0x8000 /**< surface is part of a hitbox */ + +/** + * @endsection + */ + +/** + * @section Partition masks. + */ + +#define PARTITION_SOLID_EDICTS (1 << 1) /**< every edict_t that isn't SOLID_TRIGGER or SOLID_NOT (and static props) */ +#define PARTITION_TRIGGER_EDICTS (1 << 2) /**< every edict_t that IS SOLID_TRIGGER */ +#define PARTITION_NON_STATIC_EDICTS (1 << 5) /**< everything in solid & trigger except the static props, includes SOLID_NOTs */ +#define PARTITION_STATIC_PROPS (1 << 7) + +/** + * @endsection + */ + +/** + * @section Displacement flags. + */ + +#define DISPSURF_FLAG_SURFACE (1<<0) +#define DISPSURF_FLAG_WALKABLE (1<<1) +#define DISPSURF_FLAG_BUILDABLE (1<<2) +#define DISPSURF_FLAG_SURFPROP1 (1<<3) +#define DISPSURF_FLAG_SURFPROP2 (1<<4) /** * @endsection @@ -106,8 +160,8 @@ enum RayType { - RayType_EndPoint, /**< The trace ray will go from the start position to the end position. */ - RayType_Infinite /**< The trace ray will go from the start position to infinity using a direction vector. */ + RayType_EndPoint, /**< The trace ray will go from the start position to the end position. */ + RayType_Infinite /**< The trace ray will go from the start position to infinity using a direction vector. */ }; typeset TraceEntityFilter @@ -115,254 +169,495 @@ typeset TraceEntityFilter /** * Called on entity filtering. * - * @param entity Entity index. - * @param contentsMask Contents Mask. - * @return True to allow the current entity to be hit, otherwise false. - */ + * @param entity Entity index. + * @param contentsMask Contents Mask. + * @return True to allow the current entity to be hit, otherwise false. + */ function bool (int entity, int contentsMask); - + /** * Called on entity filtering. * - * @param entity Entity index. - * @param contentsMask Contents Mask. - * @param data Data value, if used. - * @return True to allow the current entity to be hit, otherwise false. - */ + * @param entity Entity index. + * @param contentsMask Contents Mask. + * @param data Data value, if used. + * @return True to allow the current entity to be hit, otherwise false. + */ function bool (int entity, int contentsMask, any data); }; +typeset TraceEntityEnumerator +{ + /** + * Called for each entity enumerated with EnumerateEntities*. + * + * @param entity Entity index. + * @return True to continue enumerating, otherwise false. + */ + function bool (int entity); + + /** + * Called for each entity enumerated with EnumerateEntities*. + * + * @param entity Entity index. + * @param data Data value, if used. + * @return True to continue enumerating, otherwise false. */ + function bool (int entity, any data); +} + /** * Get the contents mask and the entity index at the given position. * - * @param pos World position to test. - * @param entindex Entity index found at the given position (by reference). - * @return Contents mask. + * @param pos World position to test. + * @param entindex Entity index found at the given position (by reference). + * @return Contents mask. */ native int TR_GetPointContents(const float pos[3], int &entindex=-1); /** * Get the point contents testing only the given entity index. * - * @param entindex Entity index to test. - * @param pos World position. - * @return Contents mask. + * @param entindex Entity index to test. + * @param pos World position. + * @return Contents mask. */ native int TR_GetPointContentsEnt(int entindex, const float pos[3]); /** * Starts up a new trace ray using a global trace result. * - * @param pos Starting position of the ray. - * @param vec Depending on RayType, it will be used as the - * ending point, or the direction angle. - * @param flags Trace flags. - * @param rtype Method to calculate the ray direction. + * @param pos Starting position of the ray. + * @param vec Depending on RayType, it will be used as the + * ending point, or the direction angle. + * @param flags Trace flags. + * @param rtype Method to calculate the ray direction. */ native void TR_TraceRay(const float pos[3], - const float vec[3], - int flags, - RayType rtype); - + const float vec[3], + int flags, + RayType rtype); + /** * Starts up a new trace hull using a global trace result. * - * @param pos Starting position of the ray. - * @param vec Ending position of the ray. - * @param mins Hull minimum size. - * @param maxs Hull maximum size. - * @param flags Trace flags. + * @param pos Starting position of the ray. + * @param vec Ending position of the ray. + * @param mins Hull minimum size. + * @param maxs Hull maximum size. + * @param flags Trace flags. */ native void TR_TraceHull(const float pos[3], - const float vec[3], - const float mins[3], - const float maxs[3], - int flags); + const float vec[3], + const float mins[3], + const float maxs[3], + int flags); + +/** + * Enumerates over entities along a ray. This may find entities that are + * close to the ray but do not actually intersect it. Use TR_Clip*RayToEntity + * with TR_DidHit to check if the ray actually intersects the entity. + * + * @param pos Starting position of the ray. + * @param vec Depending on RayType, it will be used as the ending + * point, or the direction angle. + * @param mask Mask to use for the trace. See PARTITION_* flags. + * @param rtype Method to calculate the ray direction. + * @param enumerator Function to use as enumerator. For each entity found + * along the ray, this function is called. + * @param data Arbitrary data value to pass through to the enumerator. + */ +native void TR_EnumerateEntities(const float pos[3], + const float vec[3], + int mask, + RayType rtype, + TraceEntityEnumerator enumerator, + any data=0); + +/** + * Enumerates over entities along a ray hull. This may find entities that are + * close to the ray but do not actually intersect it. Use TR_Clip*RayToEntity + * with TR_DidHit to check if the ray actually intersects the entity. + * + * @param pos Starting position of the ray. + * @param vec Ending position of the ray. + * @param mins Hull minimum size. + * @param maxs Hull maximum size. + * @param mask Mask to use for the trace. See PARTITION_* flags. + * @param enumerator Function to use as enumerator. For each entity found + * along the ray, this function is called. + * @param data Arbitrary data value to pass through to the enumerator. + */ +native void TR_EnumerateEntitiesHull(const float pos[3], + const float vec[3], + const float mins[3], + const float maxs[3], + int mask, + TraceEntityEnumerator enumerator, + any data=0); /** - * Starts up a new trace ray using a global trace result and a customized + * Starts up a new trace ray using a global trace result and a customized * trace ray filter. * - * Calling TR_Trace*Filter or TR_Trace*FilterEx from inside a filter + * Calling TR_Trace*Filter or TR_Trace*FilterEx from inside a filter * function is currently not allowed and may not work. * - * @param pos Starting position of the ray. - * @param vec Depending on RayType, it will be used as the ending - * point, or the direction angle. - * @param flags Trace flags. - * @param rtype Method to calculate the ray direction. - * @param filter Function to use as a filter. - * @param data Arbitrary data value to pass through to the filter - * function. + * @param pos Starting position of the ray. + * @param vec Depending on RayType, it will be used as the ending + * point, or the direction angle. + * @param flags Trace flags. + * @param rtype Method to calculate the ray direction. + * @param filter Function to use as a filter. + * @param data Arbitrary data value to pass through to the filter + * function. */ native void TR_TraceRayFilter(const float pos[3], - const float vec[3], - int flags, - RayType rtype, - TraceEntityFilter filter, - any data=0); - -/** - * Starts up a new trace hull using a global trace result and a customized + const float vec[3], + int flags, + RayType rtype, + TraceEntityFilter filter, + any data=0); + +/** + * Starts up a new trace hull using a global trace result and a customized * trace ray filter. * - * Calling TR_Trace*Filter or TR_Trace*FilterEx from inside a filter + * Calling TR_Trace*Filter or TR_Trace*FilterEx from inside a filter * function is currently not allowed and may not work. * - * @param pos Starting position of the ray. - * @param vec Depending on RayType, it will be used as the ending - * point, or the direction angle. - * @param mins Hull minimum size. - * @param maxs Hull maximum size. - * @param flags Trace flags. - * @param filter Function to use as a filter. - * @param data Arbitrary data value to pass through to the filter - * function. + * @param pos Starting position of the ray. + * @param vec Ending position of the ray. + * @param mins Hull minimum size. + * @param maxs Hull maximum size. + * @param flags Trace flags. + * @param filter Function to use as a filter. + * @param data Arbitrary data value to pass through to the filter + * function. */ native void TR_TraceHullFilter(const float pos[3], - const float vec[3], - const float mins[3], - const float maxs[3], - int flags, - TraceEntityFilter filter, - any data=0); + const float vec[3], + const float mins[3], + const float maxs[3], + int flags, + TraceEntityFilter filter, + any data=0); + +/** + * Clips a ray to a particular entity. + * + * @param pos Starting position of the ray. + * @param vec Depending on RayType, it will be used as the ending + * point, or the direction angle. + * @param flags Trace flags. + * @param rtype Method to calculate the ray direction. + * @param entity Entity to clip to. + */ +native void TR_ClipRayToEntity(const float pos[3], + const float vec[3], + int flags, + RayType rtype, + int entity); + +/** + * Clips a ray hull to a particular entity. + * + * @param pos Starting position of the ray. + * @param vec Ending position of the ray. + * @param mins Hull minimum size. + * @param maxs Hull maximum size. + * @param flags Trace flags. + * @param entity Entity to clip to. + */ +native void TR_ClipRayHullToEntity(const float pos[3], + const float vec[3], + const float mins[3], + const float maxs[3], + int flags, + int entity); + +/** + * Clips the current global ray (or hull) to a particular entity. + * + * @param flags Trace flags. + * @param entity Entity to clip to. + */ +native void TR_ClipCurrentRayToEntity(int flags, int entity); /** * Starts up a new trace ray using a new trace result. * - * @param pos Starting position of the ray. - * @param vec Depending on RayType, it will be used as the ending - * point, or the direction angle. - * @param flags Trace flags. - * @param rtype Method to calculate the ray direction. - * @return Ray trace handle, which must be closed via CloseHandle(). + * @param pos Starting position of the ray. + * @param vec Depending on RayType, it will be used as the ending + * point, or the direction angle. + * @param flags Trace flags. + * @param rtype Method to calculate the ray direction. + * @return Ray trace handle, which must be closed via CloseHandle(). */ native Handle TR_TraceRayEx(const float pos[3], - const float vec[3], - int flags, - RayType rtype); - + const float vec[3], + int flags, + RayType rtype); + /** * Starts up a new trace hull using a new trace result. * - * @param pos Starting position of the ray. - * @param vec Ending position of the ray. - * @param mins Hull minimum size. - * @param maxs Hull maximum size. - * @param flags Trace flags. - * @return Ray trace handle, which must be closed via CloseHandle(). + * @param pos Starting position of the ray. + * @param vec Ending position of the ray. + * @param mins Hull minimum size. + * @param maxs Hull maximum size. + * @param flags Trace flags. + * @return Ray trace handle, which must be closed via CloseHandle(). */ native Handle TR_TraceHullEx(const float pos[3], - const float vec[3], - const float mins[3], - const float maxs[3], - int flags); + const float vec[3], + const float mins[3], + const float maxs[3], + int flags); /** - * Starts up a new trace ray using a new trace result and a customized + * Starts up a new trace ray using a new trace result and a customized * trace ray filter. * - * Calling TR_Trace*Filter or TR_TraceRay*Ex from inside a filter + * Calling TR_Trace*Filter or TR_TraceRay*Ex from inside a filter * function is currently not allowed and may not work. * - * @param pos Starting position of the ray. - * @param vec Depending on RayType, it will be used as the ending - * point, or the direction angle. - * @param flags Trace flags. - * @param rtype Method to calculate the ray direction. - * @param filter Function to use as a filter. - * @param data Arbitrary data value to pass through to the filter function. - * @return Ray trace handle, which must be closed via CloseHandle(). - */ -native Handle TR_TraceRayFilterEx(const float pos[3], - const float vec[3], - int flags, - RayType rtype, - TraceEntityFilter filter, - any data=0); - -/** - * Starts up a new trace hull using a new trace result and a customized + * @param pos Starting position of the ray. + * @param vec Depending on RayType, it will be used as the ending + * point, or the direction angle. + * @param flags Trace flags. + * @param rtype Method to calculate the ray direction. + * @param filter Function to use as a filter. + * @param data Arbitrary data value to pass through to the filter function. + * @return Ray trace handle, which must be closed via CloseHandle(). + */ +native Handle TR_TraceRayFilterEx(const float pos[3], + const float vec[3], + int flags, + RayType rtype, + TraceEntityFilter filter, + any data=0); + +/** + * Starts up a new trace hull using a new trace result and a customized * trace ray filter. * - * Calling TR_Trace*Filter or TR_Trace*FilterEx from inside a filter + * Calling TR_Trace*Filter or TR_Trace*FilterEx from inside a filter * function is currently not allowed and may not work. * - * @param pos Starting position of the ray. - * @param vec Ending position of the ray. - * @param mins Hull minimum size. - * @param maxs Hull maximum size. - * @param flags Trace flags. - * @param filter Function to use as a filter. - * @param data Arbitrary data value to pass through to the filter function. - * @return Ray trace handle, which must be closed via CloseHandle(). + * @param pos Starting position of the ray. + * @param vec Ending position of the ray. + * @param mins Hull minimum size. + * @param maxs Hull maximum size. + * @param flags Trace flags. + * @param filter Function to use as a filter. + * @param data Arbitrary data value to pass through to the filter function. + * @return Ray trace handle, which must be closed via CloseHandle(). + */ +native Handle TR_TraceHullFilterEx(const float pos[3], + const float vec[3], + const float mins[3], + const float maxs[3], + int flags, + TraceEntityFilter filter, + any data=0); + +/** + * Clips a ray to a particular entity. + * + * @param pos Starting position of the ray. + * @param vec Depending on RayType, it will be used as the ending + * point, or the direction angle. + * @param flags Trace flags. + * @param rtype Method to calculate the ray direction. + * @param entity Entity to clip to. + * @return Ray trace handle, which must be closed via CloseHandle(). */ -native Handle TR_TraceHullFilterEx(const float pos[3], - const float vec[3], - const float mins[3], - const float maxs[3], - int flags, - TraceEntityFilter filter, - any data=0); +native Handle TR_ClipRayToEntityEx(const float pos[3], + const float vec[3], + int flags, + RayType rtype, + int entity); + +/** + * Clips a ray hull to a particular entity. + * + * @param pos Starting position of the ray. + * @param vec Ending position of the ray. + * @param mins Hull minimum size. + * @param maxs Hull maximum size. + * @param flags Trace flags. + * @param entity Entity to clip to. + * @return Ray trace handle, which must be closed via CloseHandle(). + */ +native Handle TR_ClipRayHullToEntityEx(const float pos[3], + const float vec[3], + const float mins[3], + const float maxs[3], + int flags, + int entity); + +/** + * Clips the current global ray (or hull) to a particular entity. + * + * @param flags Trace flags. + * @param entity Entity to clip to. + * @return Ray trace handle, which must be closed via CloseHandle(). + */ +native Handle TR_ClipCurrentRayToEntityEx(int flags, int entity); /** * Returns the time fraction from a trace result (1.0 means no collision). * - * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. - * @return Time fraction value of the trace. - * @error Invalid Handle. + * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. + * @return Time fraction value of the trace. + * @error Invalid Handle. */ native float TR_GetFraction(Handle hndl=INVALID_HANDLE); +/** + * Returns the time fraction from a trace result when it left a solid. + * Only valid if trace started in solid + * + * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. + * @return Time fraction left solid value of the trace. + * @error Invalid Handle. + */ +native float TR_GetFractionLeftSolid(Handle hndl=INVALID_HANDLE); + +/** + * Returns the starting position of a trace. + * + * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. + * @param pos Vector buffer to store data in. + * @error Invalid Handle. + */ +native void TR_GetStartPosition(Handle hndl, float pos[3]); + /** * Returns the collision position of a trace result. * - * @param pos Vector buffer to store data in. - * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. - * @error Invalid Handle. + * @param pos Vector buffer to store data in. + * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. + * @error Invalid Handle. */ native void TR_GetEndPosition(float pos[3], Handle hndl=INVALID_HANDLE); /** * Returns the entity index that collided with the trace. * - * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. - * @return Entity index or -1 for no collision. - * @error Invalid Handle. + * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. + * @return Entity index or -1 for no collision. + * @error Invalid Handle. */ native int TR_GetEntityIndex(Handle hndl=INVALID_HANDLE); +/** + * Returns the displacement flags for the surface that was hit. See DISPSURF_FLAG_*. + * + * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. + * @return Displacement flags. + * @error Invalid Handle. + */ +native int TR_GetDisplacementFlags(Handle hndl=INVALID_HANDLE); + +/** + * Returns the name of the surface that was hit. + * + * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. + * @param buffer Buffer to store surface name in + * @param maxlen Maximum length of output buffer + * @error Invalid Handle. + */ +native void TR_GetSurfaceName(Handle hndl, char[] buffer, int maxlen); + +/** + * Returns the surface properties index of the surface that was hit. + * + * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. + * @return Surface props. + * @error Invalid Handle. + */ +native int TR_GetSurfaceProps(Handle hndl=INVALID_HANDLE); + +/** + * Returns the surface flags. See SURF_*. + * + * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. + * @return Surface flags. + * @error Invalid Handle. + */ +native int TR_GetSurfaceFlags(Handle hndl=INVALID_HANDLE); + +/** + * Returns the index of the physics bone that was hit. + * + * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. + * @return Physics bone index. + * @error Invalid Handle. + */ +native int TR_GetPhysicsBone(Handle hndl=INVALID_HANDLE); + +/** + * Returns whether the entire trace was in a solid area. + * + * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. + * @return True if entire trace was in a solid area, otherwise false. + * @error Invalid Handle. + */ +native bool TR_AllSolid(Handle hndl=INVALID_HANDLE); + +/** + * Returns whether the initial point was in a solid area. + * + * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. + * @return True if initial point was in a solid area, otherwise false. + * @error Invalid Handle. + */ +native bool TR_StartSolid(Handle hndl=INVALID_HANDLE); + /** * Returns if there was any kind of collision along the trace ray. * - * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. - * @return True if any collision found, otherwise false. - * @error Invalid Handle. + * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. + * @return True if any collision found, otherwise false. + * @error Invalid Handle. */ native bool TR_DidHit(Handle hndl=INVALID_HANDLE); /** * Returns in which body hit group the trace collided if any. * - * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. - * @return Body hit group. - * @error Invalid Handle. + * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. + * @return Body hit group. + * @error Invalid Handle. */ native int TR_GetHitGroup(Handle hndl=INVALID_HANDLE); +/** + * Returns in which hitbox the trace collided if any. + * + * Note: if the entity that collided with the trace is the world entity, + * then this function doesn't return an hitbox index but a static prop index. + * + * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. + * @return Hitbox index (Or static prop index). + * @error Invalid Handle. + */ +native int TR_GetHitBoxIndex(Handle hndl=INVALID_HANDLE); + /** * Find the normal vector to the collision plane of a trace. * - * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. - * @param normal Vector buffer to store the vector normal to the collision plane - * @error Invalid Handle + * @param hndl A trace Handle, or INVALID_HANDLE to use a global trace result. + * @param normal Vector buffer to store the vector normal to the collision plane + * @error Invalid Handle */ native void TR_GetPlaneNormal(Handle hndl, float normal[3]); /** * Tests a point to see if it's outside any playable area * - * @param pos Vector buffer to store data in. - * @return True if outside world, otherwise false. + * @param pos Vector buffer to store data in. + * @return True if outside world, otherwise false. */ native bool TR_PointOutsideWorld(float pos[3]); diff --git a/addons/sourcemod/scripting/include/sdktools_variant_t.inc b/addons/sourcemod/scripting/include/sdktools_variant_t.inc index 9934816..71bfced 100644 --- a/addons/sourcemod/scripting/include/sdktools_variant_t.inc +++ b/addons/sourcemod/scripting/include/sdktools_variant_t.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -31,63 +31,63 @@ */ #if defined _sdktools_variant_t_included - #endinput + #endinput #endif #define _sdktools_variant_t_included /** * Sets a bool value in the global variant object. * - * @param val Input value. + * @param val Input value. */ native void SetVariantBool(bool val); /** * Sets a string in the global variant object. * - * @param str Input string. + * @param str Input string. */ native void SetVariantString(const char[] str); /** * Sets an integer value in the global variant object. * - * @param val Input value. + * @param val Input value. */ native void SetVariantInt(int val); /** * Sets a floating point value in the global variant object. * - * @param val Input value. + * @param val Input value. */ native void SetVariantFloat(float val); /** * Sets a 3D vector in the global variant object. * - * @param vec Input vector. + * @param vec Input vector. */ native void SetVariantVector3D(const float vec[3]); /** * Sets a 3D position vector in the global variant object. * - * @param vec Input position vector. + * @param vec Input position vector. */ native void SetVariantPosVector3D(const float vec[3]); /** * Sets a color in the global variant object. * - * @param color Input color. + * @param color Input color. */ native void SetVariantColor(const int color[4]); /** * Sets an entity in the global variant object. * - * @param entity Entity index. - * @error Invalid entity index. + * @param entity Entity index. + * @error Invalid entity index. */ -native void SetVariantEntity(int entity); \ No newline at end of file +native void SetVariantEntity(int entity); diff --git a/addons/sourcemod/scripting/include/sdktools_voice.inc b/addons/sourcemod/scripting/include/sdktools_voice.inc index 8d84466..2731997 100644 --- a/addons/sourcemod/scripting/include/sdktools_voice.inc +++ b/addons/sourcemod/scripting/include/sdktools_voice.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -31,54 +31,55 @@ */ #if defined _sdktools_voice_included - #endinput + #endinput #endif #define _sdktools_voice_included /** * @section voice flags. */ -#define VOICE_NORMAL 0 /**< Allow the client to listen and speak normally. */ -#define VOICE_MUTED 1 /**< Mutes the client from speaking to everyone. */ -#define VOICE_SPEAKALL 2 /**< Allow the client to speak to everyone. */ -#define VOICE_LISTENALL 4 /**< Allow the client to listen to everyone. */ -#define VOICE_TEAM 8 /**< Allow the client to always speak to team, even when dead. */ -#define VOICE_LISTENTEAM 16 /**< Allow the client to always hear teammates, including dead ones. */ - +#define VOICE_NORMAL 0 /**< Allow the client to listen and speak normally. */ +#define VOICE_MUTED 1 /**< Mutes the client from speaking to everyone. */ +#define VOICE_SPEAKALL 2 /**< Allow the client to speak to everyone. */ +#define VOICE_LISTENALL 4 /**< Allow the client to listen to everyone. */ +#define VOICE_TEAM 8 /**< Allow the client to always speak to team, even when dead. */ +#define VOICE_LISTENTEAM 16 /**< Allow the client to always hear teammates, including dead ones. */ + /** * @endsection */ enum ListenOverride { - Listen_Default = 0, /**< Leave it up to the game */ - Listen_No, /**< Can't hear */ - Listen_Yes, /**< Can hear */ + Listen_Default = 0, /**< Leave it up to the game */ + Listen_No, /**< Can't hear */ + Listen_Yes /**< Can hear */ }; /** * Set the client listening flags. * - * @param client The client index - * @param flags The voice flags + * @param client The client index + * @param flags The voice flags */ native void SetClientListeningFlags(int client, int flags); /** * Retrieve the client current listening flags. * - * @param client The client index - * @return The current voice flags + * @param client The client index + * @return The current voice flags */ native int GetClientListeningFlags(int client); /** * Set the receiver ability to listen to the sender. * - * @param iReceiver The listener index. - * @param iSender The sender index. - * @param bListen True if the receiver can listen to the sender, false otherwise. - * @return True if successful otherwise false. + * @param iReceiver The listener index. + * @param iSender The sender index. + * @param bListen True if the receiver can listen to the sender, false otherwise. + * @return True if successful otherwise false. + * @deprecated Use SetListenOverride() instead. */ #pragma deprecated Use SetListenOverride() instead native bool SetClientListening(int iReceiver, int iSender, bool bListen); @@ -86,9 +87,10 @@ native bool SetClientListening(int iReceiver, int iSender, bool bListen); /** * Retrieves if the receiver can listen to the sender. * - * @param iReceiver The listener index. - * @param iSender The sender index. - * @return True if successful otherwise false. + * @param iReceiver The listener index. + * @param iSender The sender index. + * @return True if successful otherwise false. + * @deprecated GetListenOverride() instead. */ #pragma deprecated GetListenOverride() instead native bool GetClientListening(int iReceiver, int iSender); @@ -96,27 +98,27 @@ native bool GetClientListening(int iReceiver, int iSender); /** * Override the receiver's ability to listen to the sender. * - * @param iReceiver The listener index. - * @param iSender The sender index. - * @param override The override of the receiver's ability to listen to the sender. - * @return True if successful otherwise false. + * @param iReceiver The listener index. + * @param iSender The sender index. + * @param override The override of the receiver's ability to listen to the sender. + * @return True if successful otherwise false. */ native bool SetListenOverride(int iReceiver, int iSender, ListenOverride override); /** * Retrieves the override of the receiver's ability to listen to the sender. * - * @param iReceiver The listener index. - * @param iSender The sender index. - * @return The override value. + * @param iReceiver The listener index. + * @param iSender The sender index. + * @return The override value. */ native ListenOverride GetListenOverride(int iReceiver, int iSender); /** * Retrieves if the muter has muted the mutee. * - * @param iMuter The muter index. - * @param iMutee The mutee index. - * @return True if muter has muted mutee, false otherwise. + * @param iMuter The muter index. + * @param iMutee The mutee index. + * @return True if muter has muted mutee, false otherwise. */ native bool IsClientMuted(int iMuter, int iMutee); diff --git a/addons/sourcemod/scripting/include/smjansson.inc b/addons/sourcemod/scripting/include/smjansson.inc index 4e5ad66..1d34b53 100644 --- a/addons/sourcemod/scripting/include/smjansson.inc +++ b/addons/sourcemod/scripting/include/smjansson.inc @@ -10,8 +10,8 @@ * The JSON specification (RFC 4627) defines the following data types: * object, array, string, number, boolean, and null. * JSON types are used dynamically; arrays and objects can hold any - * other data type, including themselves. For this reason, Jansson�s - * type system is also dynamic in nature. There�s one Handle type to + * other data type, including themselves. For this reason, Jansson’s + * type system is also dynamic in nature. There’s one Handle type to * represent all JSON values, and the referenced structure knows the * type of the JSON value it holds. * @@ -55,16 +55,16 @@ native json_type:json_typeof(Handle:hObj); #define json_is_boolean(%1) ( json_typeof(%1) == JSON_TRUE || json_typeof(%1) == JSON_FALSE ) /** - * Saves json_type as a String in out + * Saves json_type as a String jannson_in out * - * @param in json_type value to convert to string + * @param jannson_in json_type value to convert to string * @param out Buffer to store the json_type value * @param maxlength Maximum length of string buffer. * * @return False if the type does not exist. */ -stock bool:Stringify_json_type(json_type:type, String:out[], maxlength) { - switch(type) { +stock bool:Stringify_json_type(json_type:jannson_in, String:out[], maxlength) { + switch(jannson_in) { case JSON_OBJECT: strcopy(out, maxlength, "Object"); case JSON_ARRAY: strcopy(out, maxlength, "Array"); case JSON_STRING: strcopy(out, maxlength, "String"); @@ -577,7 +577,7 @@ native Handle:json_null(); * Strings * * Jansson uses UTF-8 as the character encoding. All JSON strings must - * be valid UTF-8 (or ASCII, as it�s a subset of UTF-8). Normal null + * be valid UTF-8 (or ASCII, as it’s a subset of UTF-8). Normal null * terminated C strings are used, so JSON strings may not contain * embedded null characters. * @@ -1002,7 +1002,7 @@ stock json_object_get_string(Handle:hObj, const String:sKey[], String:sBuffer[], /** * Pack String Rules * - * Here�s the full list of format characters: + * Here’s the full list of format characters: * n Output a JSON null value. No argument is consumed. * s Output a JSON string, consuming one argument. * b Output a JSON bool value, consuming one argument. diff --git a/addons/sourcemod/scripting/include/smlib/arrays.inc b/addons/sourcemod/scripting/include/smlib/arrays.inc index 1c9863e..87f1733 100644 --- a/addons/sourcemod/scripting/include/smlib/arrays.inc +++ b/addons/sourcemod/scripting/include/smlib/arrays.inc @@ -15,13 +15,13 @@ * @param start Optional: Offset where to start (0 - (size-1)). * @return Array index, or -1 if the value couldn't be found. */ -stock Array_FindValue(any:array[], size, any:value, start=0) +stock int Array_FindValue(const any[] array, int size, any value, int start=0) { if (start < 0) { start = 0; } - for (new i=start; i < size; i++) { + for (int i=start; i < size; i++) { if (array[i] == value) { return i; @@ -41,13 +41,13 @@ stock Array_FindValue(any:array[], size, any:value, start=0) * @param start Optional: Offset where to start(0 - (size-1)). * @return Array index, or -1 if the value couldn't be found. */ -stock Array_FindString(const String:array[][], size, const String:str[], bool:caseSensitive=true, start=0) +stock int Array_FindString(const char[][] array, int size, const char[] str, bool caseSensitive=true, int start=0) { if (start < 0) { start = 0; } - for (new i=start; i < size; i++) { + for (int i=start; i < size; i++) { if (StrEqual(array[i], str, caseSensitive)) { return i; @@ -65,17 +65,17 @@ stock Array_FindString(const String:array[][], size, const String:str[], bool:ca * @param start Optional: Offset where to start (0 - (size-1)). * @return Array index. */ -stock Array_FindLowestValue(any:array[], size, start=0) +stock int Array_FindLowestValue(const any[] array, int size, int start=0) { if (start < 0) { start = 0; } - new any:value = array[start]; - new any:tempValue; - new x = start; + any value = array[start]; + any tempValue; + int x = start; - for (new i=start; i < size; i++) { + for (int i=start; i < size; i++) { tempValue = array[i]; @@ -97,17 +97,17 @@ stock Array_FindLowestValue(any:array[], size, start=0) * @param start Optional: Offset where to start (0 - (size-1)). * @return Array index. */ -stock Array_FindHighestValue(any:array[], size, start=0) +stock int Array_FindHighestValue(const any[] array, int size, int start=0) { if (start < 0) { start = 0; } - new any:value = array[start]; - new any:tempValue; - new x = start; + any value = array[start]; + any tempValue; + int x = start; - for (new i=start; i < size; i++) { + for (int i=start; i < size; i++) { tempValue = array[i]; @@ -129,15 +129,14 @@ stock Array_FindHighestValue(any:array[], size, start=0) * @param size Number of cells to write (eg. the array's size) * @param value Fill value. * @param start Optional: Offset where to start (0 - (size-1)). - * @noreturn */ -stock Array_Fill(any:array[], size, any:value, start=0) +stock void Array_Fill(any[] array, int size, any value, int start=0) { if (start < 0) { start = 0; } - for (new i=start; i < size; i++) { + for (int i=start; i < size; i++) { array[i] = value; } } @@ -150,9 +149,9 @@ stock Array_Fill(any:array[], size, any:value, start=0) * @param size Size of the array (or number of cells to copy) * @noreturn */ -stock Array_Copy(const any:array[], any:newArray[], size) +stock void Array_Copy(const any[] array, any[] newArray, int size) { - for (new i=0; i < size; i++) { + for (int i=0; i < size; i++) { newArray[i] = array[i]; } } diff --git a/addons/sourcemod/scripting/include/smlib/clients.inc b/addons/sourcemod/scripting/include/smlib/clients.inc index 81d3f56..c8b7643 100644 --- a/addons/sourcemod/scripting/include/smlib/clients.inc +++ b/addons/sourcemod/scripting/include/smlib/clients.inc @@ -43,7 +43,7 @@ * @param 1 Name of the client index variable (will be only valid in the loop). * @param 2 CLIENTFILTER_ flags to check. */ -#define LOOP_CLIENTS(%1,%2) for (new %1=Client_GetNext(%2); %1 >= 1 && %1 <= MaxClients; %1=Client_GetNext(%2, ++%1)) +#define LOOP_CLIENTS(%1,%2) for (int %1=Client_GetNext(%2); %1 >= 1 && %1 <= MaxClients; %1=Client_GetNext(%2, ++%1)) /** * Macro for iterating trough all observers of a player. @@ -52,7 +52,7 @@ * @param 2 Name of the observer client index variable (will be only valid in the loop). * @param 3 CLIENTFILTER_ flags to check. */ -#define LOOP_OBSERVERS(%1,%2,%3) for (new %2=Client_GetNextObserver(%1, 1, %3); %2 >= 1 && %2 <= MaxClients; %2=Client_GetNextObserver(%1, ++%2, %3)) +#define LOOP_OBSERVERS(%1,%2,%3) for (int %2=Client_GetNextObserver(%1, 1, %3); %2 >= 1 && %2 <= MaxClients; %2=Client_GetNextObserver(%1, ++%2, %3)) /** * Very useful macro to iterate all weapons of a client. @@ -61,7 +61,7 @@ * @param 2 Name of the weapon index variable (will be only valid in the loop). * @param 3 Name of the client's weapon index variable (will be only valid in the loop). */ -#define LOOP_CLIENTWEAPONS(%1,%2,%3) for (new %3, %2=Client_GetNextWeapon(%1, %3); %2 != -1; %2=Client_GetNextWeapon(%1, %3)) +#define LOOP_CLIENTWEAPONS(%1,%2,%3) for (int %3, %2=Client_GetNextWeapon(%1, %3); %2 != -1; %2=Client_GetNextWeapon(%1, %3)) // Hud Element hiding flags (possibly outdated) #define HIDEHUD_WEAPONSELECTION ( 1<<0 ) // Hide ammo count & weapon selection @@ -82,9 +82,8 @@ * * @param client Client index. * @param flags Flag to set, use one of the HIDEHUD_ hiding constants -* @noreturn */ -stock Client_SetHideHud(client, flags) +stock void Client_SetHideHud(int client, int flags) { SetEntProp(client, Prop_Send, "m_iHideHUD", flags); } @@ -96,7 +95,7 @@ stock Client_SetHideHud(client, flags) * @param checkConnected Set to false to skip the IsClientConnected check * @return Returns true if the specified entity index is a player connected, false otherwise. */ -stock bool:Client_IsValid(client, bool:checkConnected=true) +stock bool Client_IsValid(int client, bool checkConnected=true) { if (client > 4096) { client = EntRefToEntIndex(client); @@ -119,7 +118,7 @@ stock bool:Client_IsValid(client, bool:checkConnected=true) * @param entity An entity index. * @return Returns true if the specified index is a player and ingame, false otherwise. */ -stock bool:Client_IsIngame(client) +stock bool Client_IsIngame(int client) { if (!Client_IsValid(client, false)) { return false; @@ -134,7 +133,7 @@ stock bool:Client_IsIngame(client) * @param entity An entity index. * @return Returns true if the specified index is a player, ingame and authed, false otherwise. */ -stock bool:Client_IsIngameAuthorized(client) +stock bool Client_IsIngameAuthorized(int client) { if (!Client_IsIngame(client)) { return false; @@ -151,10 +150,10 @@ stock bool:Client_IsIngameAuthorized(client) * @param auth SteamID to search for * @return Client Index or -1 */ -stock Client_FindBySteamId(const String:auth[]) +stock int Client_FindBySteamId(const char[] auth) { - new String:clientAuth[MAX_STEAMAUTH_LENGTH]; - for (new client=1; client <= MaxClients; client++) { + char clientAuth[MAX_STEAMAUTH_LENGTH]; + for (int client=1; client <= MaxClients; client++) { if (!IsClientAuthorized(client)) { continue; } @@ -178,10 +177,10 @@ stock Client_FindBySteamId(const String:auth[]) * @param caseSensitive If true, comparison is case sensitive. If false (default), comparison is case insensitive. * @return Client Index or -1 */ -stock Client_FindByName(const String:name[], bool:partOfName=true, bool:caseSensitive=false) +stock int Client_FindByName(const char[] name, bool partOfName=true, bool caseSensitive=false) { - new String:clientName[MAX_NAME_LENGTH]; - for (new client=1; client <= MaxClients; client++) { + char clientName[MAX_NAME_LENGTH]; + for (int client=1; client <= MaxClients; client++) { if (!IsClientAuthorized(client)) { continue; } @@ -231,9 +230,9 @@ enum Obs_Allow * @param client Client Index. * @return The current observer mode (ObsMode). */ -stock Obs_Mode:Client_GetObserverMode(client) +stock Obs_Mode Client_GetObserverMode(int client) { - return Obs_Mode:GetEntProp(client, Prop_Send, "m_iObserverMode"); + return view_as(GetEntProp(client, Prop_Send, "m_iObserverMode")); } @@ -245,21 +244,20 @@ stock Obs_Mode:Client_GetObserverMode(client) * @param client Client Index. * @param mode New Observer mode value (Obs_Mode). * @param updateMoveType Set to true (default) to allow this function updating the movetype, false otherwise. - * @noreturn */ -stock bool:Client_SetObserverMode(client, Obs_Mode:mode, bool:updateMoveType=true) +stock void Client_SetObserverMode(int client, Obs_Mode mode, bool updateMoveType=true) { if (mode < OBS_MODE_NONE || mode >= NUM_OBSERVER_MODES) { - return false; + return; } // check mp_forcecamera settings for dead players if (mode > OBS_MODE_FIXED && GetClientTeam(client) > TEAM_SPECTATOR) { - new Handle:mp_forcecamera = FindConVar("mp_forcecamera"); + ConVar mp_forcecamera = FindConVar("mp_forcecamera"); if (mp_forcecamera != INVALID_HANDLE) { - switch (GetConVarInt(mp_forcecamera)) + switch (mp_forcecamera.IntValue) { case OBS_ALLOW_TEAM: { mode = OBS_MODE_IN_EYE; @@ -271,13 +269,13 @@ stock bool:Client_SetObserverMode(client, Obs_Mode:mode, bool:updateMoveType=tru } } - new Obs_Mode:observerMode = Client_GetObserverMode(client); + Obs_Mode observerMode = Client_GetObserverMode(client); if (observerMode > OBS_MODE_DEATHCAM) { // remember mode if we were really spectating before Client_SetObserverLastMode(client, observerMode); } - SetEntProp(client, Prop_Send, "m_iObserverMode", _:mode); + SetEntProp(client, Prop_Send, "m_iObserverMode", mode); switch (mode) { case OBS_MODE_NONE, OBS_MODE_FIXED, OBS_MODE_DEATHCAM: { @@ -304,8 +302,6 @@ stock bool:Client_SetObserverMode(client, Obs_Mode:mode, bool:updateMoveType=tru } } } - - return true; } /** @@ -314,9 +310,9 @@ stock bool:Client_SetObserverMode(client, Obs_Mode:mode, bool:updateMoveType=tru * @param client Client Index. * @return Last Observer mode */ -stock Obs_Mode:Client_GetObserverLastMode(client) +stock Obs_Mode Client_GetObserverLastMode(int client) { - return Obs_Mode:GetEntProp(client, Prop_Data, "m_iObserverLastMode"); + return view_as(GetEntProp(client, Prop_Data, "m_iObserverLastMode")); } /** @@ -324,11 +320,10 @@ stock Obs_Mode:Client_GetObserverLastMode(client) * * @param client Client Index. * @param mode Last Observer mode - * @noreturn */ -stock Client_SetObserverLastMode(client, Obs_Mode:mode) +stock void Client_SetObserverLastMode(int client, Obs_Mode mode) { - SetEntProp(client, Prop_Data, "m_iObserverLastMode", _:mode); + SetEntProp(client, Prop_Data, "m_iObserverLastMode", mode); } /** @@ -337,9 +332,8 @@ stock Client_SetObserverLastMode(client, Obs_Mode:mode) * * @param client Client Index. * @param vec Vector Buffer. - * @noreturn */ -stock Client_GetViewOffset(client, Float:vec[3]) +stock void Client_GetViewOffset(int client, float vec[3]) { GetEntPropVector(client, Prop_Data, "m_vecViewOffset", vec); } @@ -352,7 +346,7 @@ stock Client_GetViewOffset(client, Float:vec[3]) * @param vec Vector buffer. * @noreturn */ -stock Client_SetViewOffset(client, Float:vec[3]) +stock void Client_SetViewOffset(int client, float vec[3]) { SetEntPropVector(client, Prop_Data, "m_vecViewOffset", vec); } @@ -363,7 +357,7 @@ stock Client_SetViewOffset(client, Float:vec[3]) * @param client Client Index. * @return Observed Entity Index. */ -stock Client_GetObserverTarget(client) +stock int Client_GetObserverTarget(int client) { return GetEntPropEnt(client, Prop_Send, "m_hObserverTarget"); } @@ -374,9 +368,8 @@ stock Client_GetObserverTarget(client) * @param client Client Index. * @param entity Observed Entity Index. * @param resetFOV If to reset the client's field of view. - * @noreturn */ -stock Client_SetObserverTarget(client, entity, bool:resetFOV=true) +stock void Client_SetObserverTarget(int client, int entity, bool resetFOV=true) { SetEntPropEnt(client, Prop_Send, "m_hObserverTarget", entity); @@ -391,7 +384,7 @@ stock Client_SetObserverTarget(client, entity, bool:resetFOV=true) * @param client Client Index. * @return Field Of View */ -stock Client_GetFOV(client) +stock int Client_GetFOV(int client) { return GetEntProp(client, Prop_Send, "m_iFOV"); } @@ -401,9 +394,8 @@ stock Client_GetFOV(client) * * @param client Client Index. * @param value Field Of View - * @noreturn */ -stock Client_SetFOV(client, value) +stock void Client_SetFOV(int client, int value) { SetEntProp(client, Prop_Send, "m_iFOV", value); } @@ -414,9 +406,9 @@ stock Client_SetFOV(client, value) * @param client Client Index. * @return True if the viewmodel is drawn, false otherwise. */ -stock bool:Client_DrawViewModel(client) +stock bool Client_DrawViewModel(int client) { - return bool:GetEntProp(client, Prop_Send, "m_bDrawViewmodel"); + return GetEntProp(client, Prop_Send, "m_bDrawViewmodel") != 0; } /** @@ -424,9 +416,8 @@ stock bool:Client_DrawViewModel(client) * * @param client Client Index. * @param drawViewModel Set to true if to draw, false otherwise. - * @noreturn */ -stock Client_SetDrawViewModel(client, bool:drawViewModel) +stock void Client_SetDrawViewModel(int client, bool drawViewModel) { SetEntProp(client, Prop_Send, "m_bDrawViewmodel", drawViewModel); } @@ -439,9 +430,8 @@ stock Client_SetDrawViewModel(client, bool:drawViewModel) * @param client Client Index. * @param enable If set to true, the client will be put into thirdperson mode, * if false the client will be put in firstperson mode. - * @noreturn */ -stock Client_SetThirdPersonMode(client, enable=true) +stock void Client_SetThirdPersonMode(int client, bool enable=true) { if (enable) { Client_SetObserverTarget(client, 0); @@ -463,9 +453,10 @@ stock Client_SetThirdPersonMode(client, enable=true) * @param client Cient Undex * @return true if the client is currently in thirdperson mode, false otherwise */ -stock Client_IsInThirdPersonMode(client) +stock bool Client_IsInThirdPersonMode(int client) { - return GetEntProp(client, Prop_Data, "m_iObserverMode"); + // FIXME: Is this enough? + return Client_GetObserverMode(client) == OBS_MODE_DEATHCAM; } #define FFADE_IN 0x0001 // Just here so we don't pass 0 into the function @@ -488,9 +479,9 @@ stock Client_IsInThirdPersonMode(client) * @param a transparency * @return True on success, false otherwise */ -stock bool:Client_ScreenFade(client, duration, mode, holdtime=-1, r=0, g=0, b=0, a=255, bool:reliable=true) +stock bool Client_ScreenFade(int client, int duration, int mode, int holdtime=-1, int r=0, int g=0, int b=0, int a=255, bool reliable=true) { - new Handle:userMessage = StartMessageOne("Fade", client, (reliable?USERMSG_RELIABLE:0)); + Handle userMessage = StartMessageOne("Fade", client, (reliable?USERMSG_RELIABLE:0)); if (userMessage == INVALID_HANDLE) { return false; @@ -499,7 +490,7 @@ stock bool:Client_ScreenFade(client, duration, mode, holdtime=-1, r=0, g=0, b=0, if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && GetUserMessageType() == UM_Protobuf) { - new color[4]; + int color[4]; color[0] = r; color[1] = g; color[2] = b; @@ -532,14 +523,14 @@ stock bool:Client_ScreenFade(client, duration, mode, holdtime=-1, r=0, g=0, b=0, * @param closelist An array that holds all clones of a client. * @return Returns how many clones a client has. */ -stock Client_GetClones(client, cloneList[]) +stock int Client_GetClones(int client, int[] cloneList) { - new x=0; - decl String:ip_client[16], String:ip_player[16]; + int x=0; + char ip_client[16], ip_player[16]; GetClientIP(client, ip_client, sizeof(client)); - for (new player=1; player <= MaxClients; player++) { + for (int player=1; player <= MaxClients; player++) { if (IsClientInGame(player)) { GetClientIP(player, ip_player, sizeof(ip_player)); @@ -559,9 +550,9 @@ stock Client_GetClones(client, cloneList[]) * @param client Client index. * @return Returns true if the client is on a ladder other wise false. */ -stock bool:Client_IsOnLadder(client) +stock bool Client_IsOnLadder(int client) { - new MoveType:movetype = GetEntityMoveType(client); + MoveType movetype = GetEntityMoveType(client); if (movetype == MOVETYPE_LADDER) { return true; @@ -571,7 +562,7 @@ stock bool:Client_IsOnLadder(client) } } -enum Water_level +enum Water_Level { WATER_LEVEL_NOT_IN_WATER = 0, WATER_LEVEL_FEET_IN_WATER, @@ -585,9 +576,9 @@ enum Water_level * @param client Client index. * @return Returns 0 if not in water. 1 if feets are in water. 2 if waist is in water. 3 if head is in water. */ -stock Water_Level:Client_GetWaterLevel(client) +stock Water_Level Client_GetWaterLevel(int client) { - return Water_Level:GetEntProp(client, Prop_Send, "m_nWaterLevel"); + return view_as(GetEntProp(client, Prop_Send, "m_nWaterLevel")); } /* @@ -596,7 +587,7 @@ stock Water_Level:Client_GetWaterLevel(client) * @param client Client index. * @return returns the actual power left in percent. */ -stock Float:Client_GetSuitSprintPower(client) +stock float Client_GetSuitSprintPower(int client) { return GetEntPropFloat(client, Prop_Send, "m_flSuitPower"); } @@ -606,9 +597,8 @@ stock Float:Client_GetSuitSprintPower(client) * * @param client Client index. * @param power power (0.0 to 100.0) - * @noreturn */ -stock Client_SetSuitSprintPower(client, Float:power) +stock void Client_SetSuitSprintPower(int client, float power) { SetEntPropFloat(client, Prop_Send, "m_flSuitPower", power); } @@ -620,11 +610,11 @@ stock Client_SetSuitSprintPower(client, Float:power) * @param countBots If true bots will be counted too. * @return Client count in the server. */ -stock Client_GetCount(bool:countInGameOnly=true, bool:countFakeClients=true) +stock int Client_GetCount(bool countInGameOnly=true, bool countFakeClients=true) { - new numClients = 0; + int numClients = 0; - for (new client=1; client <= MaxClients; client++) { + for (int client=1; client <= MaxClients; client++) { if (!IsClientConnected(client)) { continue; @@ -655,21 +645,21 @@ stock Client_GetCount(bool:countInGameOnly=true, bool:countFakeClients=true) * @param goldSource If true, get the ping as displayed in the player's scoreboard, false returns the net_graph variant. * @return Client's fake ping or 0 for fake clients */ -stock Client_GetFakePing(client, bool:goldSource=true) +stock int Client_GetFakePing(int client, bool goldSource=true) { if (IsFakeClient(client)) { return 0; } - new ping; - new Float:latency = GetClientLatency(client, NetFlow_Outgoing); // in seconds + int ping; + float latency = GetClientLatency(client, NetFlow_Outgoing); // in seconds // that should be the correct latency, we assume that cmdrate is higher // then updaterate, what is the case for default settings - decl String:cl_cmdrate[4]; + char cl_cmdrate[4]; GetClientInfo(client, "cl_cmdrate", cl_cmdrate, sizeof(cl_cmdrate)); - new Float:tickRate = GetTickInterval(); + float tickRate = GetTickInterval(); latency -= (0.5 / StringToInt(cl_cmdrate)) + TICKS_TO_TIME(1.0); // correct latency if (goldSource) { @@ -690,7 +680,7 @@ stock Client_GetFakePing(client, bool:goldSource=true) * @param client Client index * @return The closest client or -1 */ -stock Client_GetClosestToClient(client) +stock int Client_GetClosestToClient(int client) { return Edict_GetClosestToEdict(client, true); } @@ -701,9 +691,8 @@ stock Client_GetClosestToClient(client) * @param entity Entity index. * @param buffer String buffer * @param size Size of the String buffer - * @noreturn */ -stock Client_GetLastPlaceName(client, String:buffer[], size) +stock void Client_GetLastPlaceName(int client, char[] buffer, int size) { GetEntPropString(client, Prop_Send, "m_szLastPlaceName", buffer, size); } @@ -714,7 +703,7 @@ stock Client_GetLastPlaceName(client, String:buffer[], size) * @param client Client's index. * @return Score. */ -stock Client_GetScore(client) +stock int Client_GetScore(int client) { return GetClientFrags(client); } @@ -726,7 +715,7 @@ stock Client_GetScore(client) * @param value Score. * @noreturn */ -stock Client_SetScore(client, value) +stock int Client_SetScore(int client, int value) { SetEntProp(client, Prop_Data, "m_iFrags", value); } @@ -737,7 +726,7 @@ stock Client_SetScore(client, value) * @param client Client's index. * @return Death count */ -stock Client_GetDeaths(client) +stock int Client_GetDeaths(int client) { return GetEntProp(client, Prop_Data, "m_iDeaths"); } @@ -747,9 +736,8 @@ stock Client_GetDeaths(client) * * @param client Client's index. * @param value Death count - * @noreturn */ -stock Client_SetDeaths(client, value) +stock void Client_SetDeaths(int client, int value) { SetEntProp(client, Prop_Data, "m_iDeaths", value); } @@ -760,7 +748,7 @@ stock Client_SetDeaths(client, value) * @param client Client's index. * @return Armor value */ -stock Client_GetArmor(client) +stock int Client_GetArmor(int client) { return GetEntProp(client, Prop_Data, "m_ArmorValue"); } @@ -770,9 +758,8 @@ stock Client_GetArmor(client) * * @param client Client's index. * @param value Armor value - * @noreturn */ -stock Client_SetArmor(client, value) +stock void Client_SetArmor(int client, int value) { SetEntProp(client, Prop_Data, "m_ArmorValue", value); } @@ -783,9 +770,9 @@ stock Client_SetArmor(client, value) * @param client Client's index. * @return Suitpower */ -stock Float:Client_GetSuitPower(client) +stock float Client_GetSuitPower(int client) { - return Float:GetEntPropFloat(client, Prop_Data, "m_flSuitPower"); + return GetEntPropFloat(client, Prop_Data, "m_flSuitPower"); } /** @@ -793,9 +780,8 @@ stock Float:Client_GetSuitPower(client) * * @param client Client's index. * @param value Suitpower - * @noreturn */ -stock Client_SetSuitPower(client, Float:value) +stock void Client_SetSuitPower(int client, float value) { SetEntPropFloat(client, Prop_Data, "m_flSuitPower", value); } @@ -814,7 +800,7 @@ stock Client_SetSuitPower(client, Float:value) * @param client Client's index. * @return The active devices (bitwise value) */ -stock Client_GetActiveDevices(client) +stock int Client_GetActiveDevices(int client) { return GetEntProp(client, Prop_Send, "m_bitsActiveDevices"); } @@ -826,7 +812,7 @@ stock Client_GetActiveDevices(client) * @param client Client's index. * @return Next decal time */ -stock Float:Client_GetNextDecalTime(client) +stock float Client_GetNextDecalTime(int client) { return GetEntPropFloat(client, Prop_Data, "m_flNextDecalTime"); } @@ -837,7 +823,7 @@ stock Float:Client_GetNextDecalTime(client) * @param client Client's index. * @return True if he is allowed to spray a decal, false otherwise */ -stock bool:Client_CanSprayDecal(client) +stock bool Client_CanSprayDecal(int client) { return Client_GetNextDecalTime(client) <= GetGameTime(); } @@ -849,9 +835,9 @@ stock bool:Client_CanSprayDecal(client) * @param client Client's index. * @return Vehicle index, -1 if the client isn't in a vehicle. */ -stock Client_GetVehicle(client) +stock int Client_GetVehicle(int client) { - new m_hVehicle = GetEntPropEnt(client, Prop_Send, "m_hVehicle"); + int m_hVehicle = GetEntPropEnt(client, Prop_Send, "m_hVehicle"); return m_hVehicle; } @@ -862,18 +848,17 @@ stock Client_GetVehicle(client) * @param client Client's index. * @return True if he is in a vehicle, false otherwise */ -stock bool:Client_IsInVehicle(client) +stock bool Client_IsInVehicle(int client) { - return !(Client_GetVehicle(client) == -1); + return (Client_GetVehicle(client) != -1); } /** * Removes all decals for a client * * @param client Client's index. - * @noreturn */ -stock Client_RemoveAllDecals(client) +stock void Client_RemoveAllDecals(int client) { ClientCommand(client, "r_cleardecals"); } @@ -884,9 +869,9 @@ stock Client_RemoveAllDecals(client) * @param vehicle Client index. * @return True on success, false otherwise. */ -stock bool:Client_ExitVehicle(client) +stock bool Client_ExitVehicle(int client) { - new vehicle = Client_GetVehicle(client); + int vehicle = Client_GetVehicle(client); if (vehicle == -1) { return false; @@ -907,9 +892,9 @@ stock bool:Client_ExitVehicle(client) * @param pitch The pitch of the audiofile. * @return True on success, false on failure. */ -stock bool:Client_RawAudio(client, const emitter, const String:soundfile[], Float:length = 0.0, pitch = 100) +stock bool Client_RawAudio(int client, int emitter, const char[] soundfile, float length = 0.0, int pitch = 100) { - new Handle:message = StartMessageOne("RawAudio", client); + Handle message = StartMessageOne("RawAudio", client); if (message == INVALID_HANDLE) { return false; @@ -945,9 +930,9 @@ stock bool:Client_RawAudio(client, const emitter, const String:soundfile[], Floa * @param pitch The pitch of the audiofile. * @return True on success, false on failure. */ -stock bool:Client_RawAudioToAll(const emitter, const String:soundfile[], Float:length = 0.0, pitch = 100) +stock bool Client_RawAudioToAll(int emitter, const char[] soundfile, float length = 0.0, int pitch = 100) { - new Handle:message = StartMessageAll("RawAudio"); + Handle message = StartMessageAll("RawAudio"); if (message == INVALID_HANDLE) { return false; @@ -980,7 +965,7 @@ stock bool:Client_RawAudioToAll(const emitter, const String:soundfile[], Float:l * @param value The impulse command value. * @return True on success, false on failure. */ -stock Client_Impulse(client, value) +stock void Client_Impulse(int client, int value) { SetEntProp(client, Prop_Data, "m_nImpulse", value); } @@ -992,9 +977,9 @@ stock Client_Impulse(client, value) * @param client Client Index. * @return Weapon list offset or -1 on failure. */ -stock Client_GetWeaponsOffset(client) +stock int Client_GetWeaponsOffset(int client) { - static offset = -1; + static int offset = -1; if (offset == -1) { offset = FindDataMapInfo(client, "m_hMyWeapons"); @@ -1009,9 +994,9 @@ stock Client_GetWeaponsOffset(client) * @param client Client Index. * @return Weapon Index or INVALID_ENT_REFERENCE if the client has no active weapon. */ -stock Client_GetActiveWeapon(client) +stock int Client_GetActiveWeapon(int client) { - new weapon = GetEntPropEnt(client, Prop_Data, "m_hActiveWeapon"); + int weapon = GetEntPropEnt(client, Prop_Data, "m_hActiveWeapon"); if (!Entity_IsValid(weapon)) { return INVALID_ENT_REFERENCE; @@ -1028,9 +1013,9 @@ stock Client_GetActiveWeapon(client) * @param size Max size of String: buffer. * @return Weapon Entity Index on success or INVALID_ENT_REFERENCE otherwise */ -stock Client_GetActiveWeaponName(client, String:buffer[], size) +stock int Client_GetActiveWeaponName(int client, char[] buffer, int size) { - new weapon = Client_GetActiveWeapon(client); + int weapon = Client_GetActiveWeapon(client); if (weapon == INVALID_ENT_REFERENCE) { buffer[0] = '\0'; @@ -1048,9 +1033,8 @@ stock Client_GetActiveWeaponName(client, String:buffer[], size) * * @param client Client Index. * @param weapon Index of a valid weapon. - * @noreturn */ -stock Client_SetActiveWeapon(client, weapon) +stock void Client_SetActiveWeapon(int client, int weapon) { SetEntPropEnt(client, Prop_Data, "m_hActiveWeapon", weapon); ChangeEdictState(client, FindDataMapInfo(client, "m_hActiveWeapon")); @@ -1064,9 +1048,9 @@ stock Client_SetActiveWeapon(client, weapon) * @param className Weapon Classname. * @return True on success, false on failure. */ -stock bool:Client_ChangeWeapon(client, const String:className[]) +stock bool Client_ChangeWeapon(int client, const char[] className) { - new weapon = Client_GetWeapon(client, className); + int weapon = Client_GetWeapon(client, className); if (weapon == INVALID_ENT_REFERENCE) { return false; @@ -1086,9 +1070,9 @@ stock bool:Client_ChangeWeapon(client, const String:className[]) * @param client Client Index. * @return Entity Index or, INVALID_ENT_REFERENCE. */ -stock Client_ChangeToLastWeapon(client) +stock int Client_ChangeToLastWeapon(int client) { - new weapon = Client_GetLastActiveWeapon(client); + int weapon = Client_GetLastActiveWeapon(client); if (weapon == INVALID_ENT_REFERENCE) { weapon = Client_GetDefaultWeapon(client); @@ -1113,9 +1097,9 @@ stock Client_ChangeToLastWeapon(client) * @param client Client Index. * @return Entity Index of the weapon on success, INVALID_ENT_REFERENCE on failure. */ -stock Client_GetLastActiveWeapon(client) +stock int Client_GetLastActiveWeapon(int client) { - new weapon = GetEntPropEnt(client, Prop_Data, "m_hLastWeapon"); + int weapon = GetEntPropEnt(client, Prop_Data, "m_hLastWeapon"); if (!Entity_IsValid(weapon)) { return INVALID_ENT_REFERENCE; @@ -1130,20 +1114,20 @@ stock Client_GetLastActiveWeapon(client) * @param client Client Index. * @param buffer Buffer to store the weapon classname. * @param size Max size of String: buffer. - * @return True on success, false on failure. + * @return Weapon Entity Index on success or INVALID_ENT_REFERENCE otherwise */ -stock bool:Client_GetLastActiveWeaponName(client, String:buffer[], size) +stock int Client_GetLastActiveWeaponName(int client, char[] buffer, int size) { - new weapon = Client_GetLastActiveWeapon(client); + int weapon = Client_GetLastActiveWeapon(client); if (weapon == INVALID_ENT_REFERENCE) { buffer[0] = '\0'; - return false; + return INVALID_ENT_REFERENCE; } Entity_GetClassName(weapon, buffer, size); - return true; + return weapon; } /** @@ -1153,7 +1137,7 @@ stock bool:Client_GetLastActiveWeaponName(client, String:buffer[], size) * @param weapon Entity Index of a weapon. * @noreturn */ -stock Client_SetLastActiveWeapon(client, weapon) +stock void Client_SetLastActiveWeapon(int client, int weapon) { SetEntPropEnt(client, Prop_Data, "m_hLastWeapon", weapon); ChangeEdictState(client, FindDataMapInfo(client, "m_hLastWeapon")); @@ -1165,9 +1149,8 @@ stock Client_SetLastActiveWeapon(client, weapon) * @param client Client Index. * @param weapon Entity Index of the weapon. * @param switchTo If true, the client will switch to that weapon (make it active). - * @noreturn */ -stock Client_EquipWeapon(client, weapon, bool:switchTo=false) +stock void Client_EquipWeapon(int client, int weapon, bool switchTo=false) { EquipPlayerWeapon(client, weapon); @@ -1184,7 +1167,7 @@ stock Client_EquipWeapon(client, weapon, bool:switchTo=false) * @param weapon Entity Index of the weapon, you'd like to detach. * @return True on success, false otherwise. */ -stock bool:Client_DetachWeapon(client, weapon) +stock bool Client_DetachWeapon(int client, int weapon) { if (!RemovePlayerItem(client, weapon)) { return false; @@ -1205,9 +1188,9 @@ stock bool:Client_DetachWeapon(client, weapon) * @param switchTo If set to true, the client will switch the active weapon to the new weapon. * @return Entity Index of the given weapon on success, INVALID_ENT_REFERENCE on failure. */ -stock Client_GiveWeapon(client, const String:className[], bool:switchTo=true) +stock int Client_GiveWeapon(int client, const char[] className, bool switchTo=true) { - new weapon = Client_GetWeapon(client, className); + int weapon = Client_GetWeapon(client, className); if (weapon == INVALID_ENT_REFERENCE) { weapon = Weapon_CreateForOwner(client, className); @@ -1234,9 +1217,9 @@ stock Client_GiveWeapon(client, const String:className[], bool:switchTo=true) * @param secondaryClip Secondary ammo value in the weapon clip, if -1 the value is untouched. * @return Entity Index of the given weapon on success, INVALID_ENT_REFERENCE on failure. */ -stock Client_GiveWeaponAndAmmo(client, const String:className[], bool:switchTo=true, primaryAmmo=-1, secondaryAmmo=-1, primaryClip=-1, secondaryClip=-1) +stock int Client_GiveWeaponAndAmmo(int client, const char[] className, bool switchTo=true, int primaryAmmo=-1, int secondaryAmmo=-1, int primaryClip=-1, int secondaryClip=-1) { - new weapon = Client_GiveWeapon(client, className, switchTo); + int weapon = Client_GiveWeapon(client, className, switchTo); if (weapon == INVALID_ENT_REFERENCE) { return INVALID_ENT_REFERENCE; @@ -1264,14 +1247,14 @@ stock Client_GiveWeaponAndAmmo(client, const String:className[], bool:switchTo=t * @param clearAmmo If true, the ammo the client carries for that weapon will be set to 0 (primary and secondary). * @return True on success, false otherwise. */ -stock bool:Client_RemoveWeapon(client, const String:className[], bool:firstOnly=true, bool:clearAmmo=false) +stock bool Client_RemoveWeapon(int client, const char[] className, bool firstOnly=true, bool clearAmmo=false) { - new offset = Client_GetWeaponsOffset(client) - 4; + int offset = Client_GetWeaponsOffset(client) - 4; - for (new i=0; i < MAX_WEAPONS; i++) { + for (int i=0; i < MAX_WEAPONS; i++) { offset += 4; - new weapon = GetEntDataEnt2(client, offset); + int weapon = GetEntDataEnt2(client, offset); if (!Weapon_IsValid(weapon)) { continue; @@ -1311,15 +1294,15 @@ stock bool:Client_RemoveWeapon(client, const String:className[], bool:firstOnly= * @param clearAmmo If true, the ammo the player carries for all removed weapons are set to 0 (primary and secondary). * @return Number of removed weapons. */ -stock Client_RemoveAllWeapons(client, const String:exclude[]="", bool:clearAmmo=false) +stock int Client_RemoveAllWeapons(int client, const char[] exclude="", bool clearAmmo=false) { - new offset = Client_GetWeaponsOffset(client) - 4; + int offset = Client_GetWeaponsOffset(client) - 4; - new numWeaponsRemoved = 0; - for (new i=0; i < MAX_WEAPONS; i++) { + int numWeaponsRemoved = 0; + for (int i=0; i < MAX_WEAPONS; i++) { offset += 4; - new weapon = GetEntDataEnt2(client, offset); + int weapon = GetEntDataEnt2(client, offset); if (!Weapon_IsValid(weapon)) { continue; @@ -1351,9 +1334,9 @@ stock Client_RemoveAllWeapons(client, const String:exclude[]="", bool:clearAmmo= * @param className Weapon Classname. * @return True if client has the weapon, otherwise false. */ -stock Client_HasWeapon(client, const String:className[]) +stock bool Client_HasWeapon(int client, const char[] className) { - new weapon = Client_GetWeapon(client, className); + int weapon = Client_GetWeapon(client, className); return (weapon != INVALID_ENT_REFERENCE); } @@ -1365,11 +1348,11 @@ stock Client_HasWeapon(client, const String:className[]) * @param className Classname of the weapon. * @return Entity index on success or INVALID_ENT_REFERENCE. */ -stock Client_GetWeapon(client, const String:className[]) +stock int Client_GetWeapon(int client, const char[] className) { - new offset = Client_GetWeaponsOffset(client) - 4; - new weapon = INVALID_ENT_REFERENCE; - for (new i=0; i < MAX_WEAPONS; i++) { + int offset = Client_GetWeaponsOffset(client) - 4; + int weapon = INVALID_ENT_REFERENCE; + for (int i=0; i < MAX_WEAPONS; i++) { offset += 4; weapon = GetEntDataEnt2(client, offset); @@ -1395,7 +1378,7 @@ stock Client_GetWeapon(client, const String:className[]) * @param slot Slot Index. * @return Entity index on success or INVALID_ENT_REFERENCE. */ -stock Client_GetWeaponBySlot(client, slot) +stock int Client_GetWeaponBySlot(int client, int slot) { return GetPlayerWeaponSlot(client, slot); } @@ -1406,9 +1389,9 @@ stock Client_GetWeaponBySlot(client, slot) * @param client Client Index. * @return Entity Index on success, INVALID_ENT_REFERENCE on failure. */ -stock Client_GetDefaultWeapon(client) +stock int Client_GetDefaultWeapon(int client) { - decl String:weaponName[MAX_WEAPON_STRING]; + char weaponName[MAX_WEAPON_STRING]; if (Client_GetDefaultWeaponName(client, weaponName, sizeof(weaponName))) { return INVALID_ENT_REFERENCE; } @@ -1426,7 +1409,7 @@ stock Client_GetDefaultWeapon(client) * @param size Max size of string: buffer. * @return True on success, false otherwise. */ -stock bool:Client_GetDefaultWeaponName(client, String:buffer[], size) +stock bool Client_GetDefaultWeaponName(int client, char[] buffer, int size) { if (!GetClientInfo(client, "cl_defaultweapon", buffer, size)) { buffer[0] = '\0'; @@ -1443,14 +1426,14 @@ stock bool:Client_GetDefaultWeaponName(client, String:buffer[], size) * @param client Client Index. * @return Entity Index of the weapon or INVALID_ENT_REFERENCE. */ -stock Client_GetFirstWeapon(client) +stock int Client_GetFirstWeapon(int client) { - new offset = Client_GetWeaponsOffset(client) - 4; + int offset = Client_GetWeaponsOffset(client) - 4; - for (new i=0; i < MAX_WEAPONS; i++) { + for (int i=0; i < MAX_WEAPONS; i++) { offset += 4; - new weapon = GetEntDataEnt2(client, offset); + int weapon = GetEntDataEnt2(client, offset); if (!Weapon_IsValid(weapon)) { continue; @@ -1468,16 +1451,16 @@ stock Client_GetFirstWeapon(client) * @param client Client Index. * @return Number of weapons. */ -stock Client_GetWeaponCount(client) +stock int Client_GetWeaponCount(int client) { - new numWeapons = 0; + int numWeapons = 0; - new offset = Client_GetWeaponsOffset(client) - 4; + int offset = Client_GetWeaponsOffset(client) - 4; - for (new i=0; i < MAX_WEAPONS; i++) { + for (int i=0; i < MAX_WEAPONS; i++) { offset += 4; - new weapon = GetEntDataEnt2(client, offset); + int weapon = GetEntDataEnt2(client, offset); if (!Weapon_IsValid(weapon)) { continue; @@ -1495,9 +1478,9 @@ stock Client_GetWeaponCount(client) * @param client Client Index. * @return True if client is reloading, false otherwise. */ -stock bool:Client_IsReloading(client) +stock bool Client_IsReloading(int client) { - new weapon = Client_GetActiveWeapon(client); + int weapon = Client_GetActiveWeapon(client); if (weapon == INVALID_ENT_REFERENCE) { return false; @@ -1515,9 +1498,9 @@ stock bool:Client_IsReloading(client) * @param secondaryClip Secondary ammo value in the weapon clip, if -1 the value is untouched. * @return True on success, false on failure. */ -stock bool:Client_SetWeaponClipAmmo(client, const String:className[], primaryClip=-1, secondoaryClip=-1) +stock bool Client_SetWeaponClipAmmo(int client, const char[] className, int primaryClip=-1, int secondoaryClip=-1) { - new weapon = Client_GetWeapon(client, className); + int weapon = Client_GetWeapon(client, className); if (weapon == INVALID_ENT_REFERENCE) { return false; @@ -1543,23 +1526,23 @@ stock bool:Client_SetWeaponClipAmmo(client, const String:className[], primaryCli * @param secondaryAmmo Secondary ammo stock from the client, if -1 the value is untouched. * @return True on success, false on failure. */ -stock bool:Client_GetWeaponPlayerAmmo(client, const String:className[], &primaryAmmo=-1, &secondaryAmmo=-1) +stock bool Client_GetWeaponPlayerAmmo(int client, const char[] className, int &primaryAmmo=-1, int &secondaryAmmo=-1) { - new weapon = Client_GetWeapon(client, className); + int weapon = Client_GetWeapon(client, className); if (weapon == INVALID_ENT_REFERENCE) { return false; } - new offset_ammo = FindDataMapInfo(client, "m_iAmmo"); + int offset_ammo = FindDataMapInfo(client, "m_iAmmo"); if (primaryAmmo != -1) { - new offset = offset_ammo + (Weapon_GetPrimaryAmmoType(weapon) * 4); + int offset = offset_ammo + (Weapon_GetPrimaryAmmoType(weapon) * 4); primaryAmmo = GetEntData(client, offset); } if (secondaryAmmo != -1) { - new offset = offset_ammo + (Weapon_GetSecondaryAmmoType(weapon) * 4); + int offset = offset_ammo + (Weapon_GetSecondaryAmmoType(weapon) * 4); secondaryAmmo = GetEntData(client, offset); } @@ -1573,19 +1556,18 @@ stock bool:Client_GetWeaponPlayerAmmo(client, const String:className[], &primary * @param weapon Weapon Entity Index. * @param primaryAmmo Primary ammo stock value from the client, if -1 the value is untouched. * @param secondaryAmmo Secondary ammo stock value from the client, if -1 the value is untouched. - * @noreturn */ -stock Client_GetWeaponPlayerAmmoEx(client, weapon, &primaryAmmo=-1, &secondaryAmmo=-1) +stock void Client_GetWeaponPlayerAmmoEx(int client, int weapon, int &primaryAmmo=-1, int &secondaryAmmo=-1) { - new offset_ammo = FindDataMapInfo(client, "m_iAmmo"); + int offset_ammo = FindDataMapInfo(client, "m_iAmmo"); if (primaryAmmo != -1) { - new offset = offset_ammo + (Weapon_GetPrimaryAmmoType(weapon) * 4); + int offset = offset_ammo + (Weapon_GetPrimaryAmmoType(weapon) * 4); primaryAmmo = GetEntData(client, offset); } if (secondaryAmmo != -1) { - new offset = offset_ammo + (Weapon_GetSecondaryAmmoType(weapon) * 4); + int offset = offset_ammo + (Weapon_GetSecondaryAmmoType(weapon) * 4); secondaryAmmo = GetEntData(client, offset); } } @@ -1599,9 +1581,9 @@ stock Client_GetWeaponPlayerAmmoEx(client, weapon, &primaryAmmo=-1, &secondaryAm * @param secondaryAmmo Secondary ammo stock from the client, if -1 the value is untouched. * @return True on success, false on failure. */ -stock bool:Client_SetWeaponPlayerAmmo(client, const String:className[], primaryAmmo=-1, secondaryAmmo=-1) +stock bool Client_SetWeaponPlayerAmmo(int client, const char[] className, int primaryAmmo=-1, int secondaryAmmo=-1) { - new weapon = Client_GetWeapon(client, className); + int weapon = Client_GetWeapon(client, className); if (weapon == INVALID_ENT_REFERENCE) { return false; @@ -1619,19 +1601,18 @@ stock bool:Client_SetWeaponPlayerAmmo(client, const String:className[], primaryA * @param weapon Weapon Entity Index. * @param primaryAmmo Primary ammo stock value from the client, if -1 the value is untouched. * @param secondaryAmmo Secondary ammo stock value from the client, if -1 the value is untouched. - * @noreturn */ -stock Client_SetWeaponPlayerAmmoEx(client, weapon, primaryAmmo=-1, secondaryAmmo=-1) +stock void Client_SetWeaponPlayerAmmoEx(int client, int weapon, int primaryAmmo=-1, int secondaryAmmo=-1) { - new offset_ammo = FindDataMapInfo(client, "m_iAmmo"); + int offset_ammo = FindDataMapInfo(client, "m_iAmmo"); if (primaryAmmo != -1) { - new offset = offset_ammo + (Weapon_GetPrimaryAmmoType(weapon) * 4); + int offset = offset_ammo + (Weapon_GetPrimaryAmmoType(weapon) * 4); SetEntData(client, offset, primaryAmmo, 4, true); } if (secondaryAmmo != -1) { - new offset = offset_ammo + (Weapon_GetSecondaryAmmoType(weapon) * 4); + int offset = offset_ammo + (Weapon_GetSecondaryAmmoType(weapon) * 4); SetEntData(client, offset, secondaryAmmo, 4, true); } } @@ -1645,11 +1626,11 @@ stock Client_SetWeaponPlayerAmmoEx(client, weapon, primaryAmmo=-1, secondaryAmmo * @param secondaryAmmo Secondary ammo stock value from the client, if -1 the value is untouched. * @param primaryClip Primary ammo value in the weapon clip, if -1 the value is untouched. * @param secondaryClip Secondary ammo value in the weapon clip, if -1 the value is untouched. - * @return Entity Index of the given weapon on success, INVALID_ENT_REFERENCE on failure. + * @return True on success, false on failure. */ -stock Client_SetWeaponAmmo(client, const String:className[], primaryAmmo=-1, secondaryAmmo=-1, primaryClip=-1, secondaryClip=-1) +stock bool Client_SetWeaponAmmo(int client, const char[] className, int primaryAmmo=-1, int secondaryAmmo=-1, int primaryClip=-1, int secondaryClip=-1) { - new weapon = Client_GetWeapon(client, className); + int weapon = Client_GetWeapon(client, className); if (weapon == INVALID_ENT_REFERENCE) { return false; @@ -1673,11 +1654,11 @@ stock Client_SetWeaponAmmo(client, const String:className[], primaryAmmo=-1, sec * @param index Reference to an index variable, will contain the index of the next weapon to check. * @return Weapon Index or -1 if no more weapons are found. */ -stock Client_GetNextWeapon(client, &index = 0) +stock int Client_GetNextWeapon(int client, int &index = 0) { - new offset = Client_GetWeaponsOffset(client) + (index * 4); + int offset = Client_GetWeaponsOffset(client) + (index * 4); - new weapon; + int weapon; while (index < MAX_WEAPONS) { index++; @@ -1703,15 +1684,15 @@ stock Client_GetNextWeapon(client, &index = 0) * @param ... Variable number of format parameters. * @return True on success, false if this usermessage doesn't exist. */ -stock bool:Client_PrintHintText(client, const String:format[], any:...) +stock bool Client_PrintHintText(int client, const char[] format, any ...) { - new Handle:userMessage = StartMessageOne("HintText", client); + Handle userMessage = StartMessageOne("HintText", client); if (userMessage == INVALID_HANDLE) { return false; } - decl String:buffer[254]; + char buffer[254]; SetGlobalTransTarget(client); VFormat(buffer, sizeof(buffer), format, 3); @@ -1739,13 +1720,12 @@ stock bool:Client_PrintHintText(client, const String:format[], any:...) * * @param format Formatting rules. * @param ... Variable number of format parameters. - * @noreturn */ -stock Client_PrintHintTextToAll(const String:format[], any:...) +stock void Client_PrintHintTextToAll(const char[] format, any ...) { - decl String:buffer[254]; + char buffer[254]; - for (new client=1; client <= MaxClients; client++) { + for (int client=1; client <= MaxClients; client++) { if (!IsClientInGame(client)) { continue; @@ -1767,15 +1747,15 @@ stock Client_PrintHintTextToAll(const String:format[], any:...) * @param ... Variable number of format parameters. * @return True on success, false if this usermessage doesn't exist. */ -stock bool:Client_PrintKeyHintText(client, const String:format[], any:...) +stock bool Client_PrintKeyHintText(int client, const char[] format, any ...) { - new Handle:userMessage = StartMessageOne("KeyHintText", client); + Handle userMessage = StartMessageOne("KeyHintText", client); if (userMessage == INVALID_HANDLE) { return false; } - decl String:buffer[254]; + char buffer[254]; SetGlobalTransTarget(client); VFormat(buffer, sizeof(buffer), format, 3); @@ -1804,11 +1784,11 @@ stock bool:Client_PrintKeyHintText(client, const String:format[], any:...) * @param ... Variable number of format parameters. * @noreturn */ -stock Client_PrintKeyHintTextToAll(const String:format[], any:...) +stock void Client_PrintKeyHintTextToAll(const char[] format, any ...) { - decl String:buffer[254]; + char buffer[254]; - for (new client=1; client <= MaxClients; client++) { + for (int client=1; client <= MaxClients; client++) { if (!IsClientInGame(client)) { continue; @@ -1828,19 +1808,18 @@ stock Client_PrintKeyHintTextToAll(const String:format[], any:...) * @param message String Message. * @param subject Client Index/Subject (normally used for teamcolors) * @param isChat Tells the game to handle the chat as normal (false) or chat message (true, plays a sound), only works if SayText2 is supported. - * @noreturn */ -stock Client_PrintToChatRaw(client, const String:message[], subject=0, bool:isChat=false) +stock void Client_PrintToChatRaw(int client, const char[] message, int subject=0, bool isChat=false) { if (client == 0) { - decl String:buffer[253]; + char buffer[253]; Color_StripFromChatText(message, buffer, sizeof(buffer)); PrintToServer(buffer); return; } - static sayText2_supported = true; - static sayText2_checked = false; + static bool sayText2_supported = true; + static bool sayText2_checked = false; if (!sayText2_checked) { @@ -1851,7 +1830,7 @@ stock Client_PrintToChatRaw(client, const String:message[], subject=0, bool:isCh sayText2_checked = true; } - new Handle:userMessage = INVALID_HANDLE; + Handle userMessage = INVALID_HANDLE; if (sayText2_supported) { userMessage = StartMessageOne("SayText2", client, USERMSG_RELIABLE); @@ -1907,24 +1886,23 @@ stock Client_PrintToChatRaw(client, const String:message[], subject=0, bool:isCh * @param isChat Tells the game to handle the chat as normal (false) or chat message (true, plays a sound), only works if SayText2 is supported. * @param format Formatting rules String. * @param ... Variable number of format parameters. - * @noreturn */ -stock Client_PrintToChat(client, bool:isChat, const String:format[], any:...) +stock void Client_PrintToChat(int client, bool isChat, const char[] format, any ...) { - decl - String:buffer[512], - String:buffer2[253]; + char + buffer[512], + buffer2[253]; SetGlobalTransTarget(client); VFormat(buffer, sizeof(buffer), format, 4); - new subject = Color_ParseChatText(buffer, buffer2, sizeof(buffer2)); + int subject = Color_ParseChatText(buffer, buffer2, sizeof(buffer2)); Client_PrintToChatRaw(client, buffer2, subject, isChat); Color_ChatClearSubject(); } -static printToChat_excludeclient = -1; +static int printToChat_excludeclient = -1; /** * Exclude a client from the next call to a Client_PrintToChat function. @@ -1932,7 +1910,7 @@ static printToChat_excludeclient = -1; * @param client Client Index. * @noreturn */ -stock Client_PrintToChatExclude(client) +stock void Client_PrintToChatExclude(int client) { printToChat_excludeclient = client; } @@ -1945,19 +1923,18 @@ stock Client_PrintToChatExclude(client) * @param isChat Tells the game to handle the chat as normal (false) or chat message (true, plays a sound), only works if SayText2 is supported. * @param format Formatting rules String. * @param ... Variable number of format parameters. - * @noreturn */ -stock Client_PrintToChatAll(bool:isChat, const String:format[], any:...) +stock void Client_PrintToChatAll(bool isChat, const char[] format, any ...) { - decl - String:buffer[512], - String:buffer2[253]; - new + char + buffer[512], + buffer2[253]; + int subject, language, lastLanguage = -1; - for (new client=1; client <= MaxClients; client++) { + for (int client=1; client <= MaxClients; client++) { if (!IsClientInGame(client)) { continue; @@ -1994,20 +1971,19 @@ stock Client_PrintToChatAll(bool:isChat, const String:format[], any:...) * @param isChat Tells the game to handle the chat as normal (false) or chat message (true, plays a sound), only works if SayText2 is supported. * @param format Formatting rules. * @param ... Variable number of format parameters. - * @noreturn */ -stock Client_PrintToChatEx(clients[], numClients, bool:isChat, const String:format[], any:...) +stock void Client_PrintToChatEx(int[] clients, int numClients, bool isChat, const char[] format, any ...) { - decl - String:buffer[512], - String:buffer2[253]; - new + char + buffer[512], + buffer2[253]; + int client, subject, language, lastLanguage = -1; - for (new i=0; i < numClients; i++) { + for (int i=0; i < numClients; i++) { client = clients[i]; @@ -2052,11 +2028,10 @@ enum ClientHudPrint { * @param clients Client Array. * @param format Formatting rules. * @param ... Variable number of format parameters. - * @noreturn */ -stock Client_PrintToConsole(client, const String:format[], any:...) +stock void Client_PrintToConsole(int client, const char[] format, any ...) { - decl String:buffer[512]; + char buffer[512]; SetGlobalTransTarget(client); VFormat(buffer, sizeof(buffer), format, 3); @@ -2074,23 +2049,22 @@ stock Client_PrintToConsole(client, const String:format[], any:...) * @param destination Destination place (use onf of the ClientHudPrint_) * @param format Formatting rules. * @param ... Variable number of format parameters. - * @noreturn */ -stock Client_Print(client, ClientHudPrint:destination, const String:format[], any:...) +stock void Client_Print(int client, ClientHudPrint destination, const char[] format, any ...) { - decl String:buffer[512], String:buffer2[254]; + char buffer[512], buffer2[254]; SetGlobalTransTarget(client); VFormat(buffer, sizeof(buffer), format, 4); - new subject = Color_ParseChatText(buffer, buffer2, sizeof(buffer2)); + int subject = Color_ParseChatText(buffer, buffer2, sizeof(buffer2)); if (destination == ClientHudPrint_Talk) { Client_PrintToChatRaw(client, buffer2, subject, false); return; } - new EngineVersion:engineVersion = GetEngineVersion(); + EngineVersion engineVersion = GetEngineVersion(); if (client == 0 || destination != ClientHudPrint_Console || (destination == ClientHudPrint_Console @@ -2104,13 +2078,13 @@ stock Client_Print(client, ClientHudPrint:destination, const String:format[], an } } - new Handle:userMessage = INVALID_HANDLE; + Handle userMessage = INVALID_HANDLE; userMessage = StartMessageOne("TextMsg", client, USERMSG_RELIABLE); if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && GetUserMessageType() == UM_Protobuf) { - PbSetInt(userMessage, "msg_dst", _:destination); + PbSetInt(userMessage, "msg_dst", view_as(destination)); PbAddString(userMessage, "params", buffer2); PbAddString(userMessage, "params", ""); PbAddString(userMessage, "params", ""); @@ -2118,7 +2092,7 @@ stock Client_Print(client, ClientHudPrint:destination, const String:format[], an PbAddString(userMessage, "params", ""); } else { - BfWriteByte(userMessage , _:destination); + BfWriteByte(userMessage , view_as(destination)); BfWriteString(userMessage , buffer2); } @@ -2134,11 +2108,10 @@ stock Client_Print(client, ClientHudPrint:destination, const String:format[], an * @param client Client Index. * @param format Formatting rules String. * @param ... Variable number of format parameters. - * @noreturn */ -stock Client_Reply(client, const String:format[], any:...) +stock void Client_Reply(int client, const char[] format, any ...) { - decl String:buffer[255]; + char buffer[255]; SetGlobalTransTarget(client); VFormat(buffer, sizeof(buffer), format, 3); @@ -2169,7 +2142,7 @@ stock Client_Reply(client, const String:format[], any:...) * @param duration Shake lasts this long. * @return True on success, false otherwise. */ -stock bool:Client_Shake(client, command=SHAKE_START, Float:amplitude=50.0, Float:frequency=150.0, Float:duration=3.0) +stock bool Client_Shake(int client, int command=SHAKE_START, float amplitude=50.0, float frequency=150.0, float duration=3.0) { if (command == SHAKE_STOP) { amplitude = 0.0; @@ -2178,7 +2151,7 @@ stock bool:Client_Shake(client, command=SHAKE_START, Float:amplitude=50.0, Float return false; } - new Handle:userMessage = StartMessageOne("Shake", client); + Handle userMessage = StartMessageOne("Shake", client); if (userMessage == INVALID_HANDLE) { return false; @@ -2210,9 +2183,9 @@ stock bool:Client_Shake(client, command=SHAKE_START, Float:amplitude=50.0, Float * @param Client Index. * @return True if the client is a generic admin, false otheriwse. */ -stock bool:Client_IsAdmin(client) +stock bool Client_IsAdmin(int client) { - new AdminId:adminId = GetUserAdmin(client); + AdminId adminId = GetUserAdmin(client); if (adminId == INVALID_ADMIN_ID) { return false; @@ -2227,15 +2200,15 @@ stock bool:Client_IsAdmin(client) * @param Client Index. * @return True if the client has the admin flags, false otherwise. */ -stock bool:Client_HasAdminFlags(client, flags=ADMFLAG_GENERIC) +stock bool Client_HasAdminFlags(int client, int flags=ADMFLAG_GENERIC) { - new AdminId:adminId = GetUserAdmin(client); + AdminId adminId = GetUserAdmin(client); if (adminId == INVALID_ADMIN_ID) { return false; } - return bool:(GetAdminFlags(adminId, Access_Effective) & flags); + return GetAdminFlags(adminId, Access_Effective) & flags == flags; } /** @@ -2246,9 +2219,9 @@ stock bool:Client_HasAdminFlags(client, flags=ADMFLAG_GENERIC) * @param caseSensitive True if the group check has to be case sensitive, false otherwise. * @return True if the client is in the admin group, false otherwise. */ -stock bool:Client_IsInAdminGroup(client, const String:groupName[], bool:caseSensitive=true) +stock bool Client_IsInAdminGroup(int client, const char[] groupName, bool caseSensitive=true) { - new AdminId:adminId = GetUserAdmin(client); + AdminId adminId = GetUserAdmin(client); // Validate id. if (adminId == INVALID_ADMIN_ID) { @@ -2256,17 +2229,17 @@ stock bool:Client_IsInAdminGroup(client, const String:groupName[], bool:caseSens } // Get number of groups. - new count = GetAdminGroupCount(adminId); + int count = GetAdminGroupCount(adminId); // Validate number of groups. if (count == 0) { return false; } - decl String:groupname[64]; + char groupname[64]; // Loop through each group. - for (new i = 0; i < count; i++) { + for (int i = 0; i < count; i++) { // Get group name. GetAdminGroup(adminId, i, groupname, sizeof(groupname)); @@ -2288,26 +2261,26 @@ stock bool:Client_IsInAdminGroup(client, const String:groupName[], bool:caseSens * @param distance Max Distance as Float value. * @return True if he is looking at a wall, false otherwise. */ -stock bool:Client_IsLookingAtWall(client, Float:distance=40.0) { +stock bool Client_IsLookingAtWall(int client, float distance=40.0) { - decl Float:posEye[3], Float:posEyeAngles[3]; - new bool:isClientLookingAtWall = false; + float posEye[3], posEyeAngles[3]; + bool isClientLookingAtWall = false; GetClientEyePosition(client, posEye); GetClientEyeAngles(client, posEyeAngles); posEyeAngles[0] = 0.0; - new Handle:trace = TR_TraceRayFilterEx(posEye, posEyeAngles, CONTENTS_SOLID, RayType_Infinite, _smlib_TraceEntityFilter); + Handle trace = TR_TraceRayFilterEx(posEye, posEyeAngles, CONTENTS_SOLID, RayType_Infinite, _smlib_TraceEntityFilter); if (TR_DidHit(trace)) { if (TR_GetEntityIndex(trace) > 0) { - CloseHandle(trace); + delete trace; return false; } - decl Float:posEnd[3]; + float posEnd[3]; TR_GetEndPosition(posEnd, trace); @@ -2316,12 +2289,12 @@ stock bool:Client_IsLookingAtWall(client, Float:distance=40.0) { } } - CloseHandle(trace); + delete trace; return isClientLookingAtWall; } -public bool:_smlib_TraceEntityFilter(entity, contentsMask) +public bool _smlib_TraceEntityFilter(int entity, int contentsMask) { return entity == 0; } @@ -2334,7 +2307,7 @@ public bool:_smlib_TraceEntityFilter(entity, contentsMask) * @param client Client Index. * @return Class Index. */ -stock Client_GetClass(client) +stock int Client_GetClass(int client) { if (GetEngineVersion() == Engine_DarkMessiah) { return GetEntProp(client, Prop_Send, "m_iPlayerClass"); @@ -2351,9 +2324,8 @@ stock Client_GetClass(client) * @param client Client Index. * @param playerClass The class number to set the player to. Depends on game. * @param persistant If true changes the players desired class so the change stays after death (probably TF2 only). - * @return Class Index. */ -stock Client_SetClass(client, playerClass, bool:persistant=false) +stock void Client_SetClass(int client, int playerClass, bool persistant=false) { if (GetEngineVersion() == Engine_DarkMessiah) { SetEntProp(client, Prop_Send, "m_iPlayerClass", playerClass); @@ -2372,7 +2344,7 @@ stock Client_SetClass(client, playerClass, bool:persistant=false) * @param client Client Index. * @return Buttons as bitflag. */ -stock Client_GetButtons(client) +stock int Client_GetButtons(int client) { return GetClientButtons(client); } @@ -2383,9 +2355,8 @@ stock Client_GetButtons(client) * * @param client Client Index. * @param buttons Buttons as bitflag. - * @noreturn */ -stock Client_SetButtons(client, buttons) +stock void Client_SetButtons(int client, int buttons) { SetEntProp(client, Prop_Data, "m_nButtons", buttons); } @@ -2396,11 +2367,10 @@ stock Client_SetButtons(client, buttons) * * @param client Client Index. * @param buttons Buttons as bitflag. - * @noreturn */ -stock Client_AddButtons(client, buttons) +stock void Client_AddButtons(int client, int buttons) { - new newButtons = Client_GetButtons(client); + int newButtons = Client_GetButtons(client); newButtons |= buttons; Client_SetButtons(client, newButtons); } @@ -2411,11 +2381,10 @@ stock Client_AddButtons(client, buttons) * * @param client Client Index. * @param buttons Buttons as bitflag. - * @noreturn */ -stock Client_RemoveButtons(client, buttons) +stock void Client_RemoveButtons(int client, int buttons) { - new newButtons = Client_GetButtons(client); + int newButtons = Client_GetButtons(client); newButtons &= ~buttons; Client_SetButtons(client, newButtons); } @@ -2425,9 +2394,8 @@ stock Client_RemoveButtons(client, buttons) * Note: This will likely only work OnPreThink (sdkhooks) or OnPlayerRunCmd. * * @param client Client Index. - * @noreturn */ -stock Client_ClearButtons(client) +stock void Client_ClearButtons(int client) { Client_SetButtons(client,0); } @@ -2439,9 +2407,9 @@ stock Client_ClearButtons(client) * @param buttons Buttons as bitflag. * @return True if the buttons are pressed otherwise false. */ -stock bool:Client_HasButtons(client, buttons) +stock bool Client_HasButtons(int client, int buttons) { - return bool:(Client_GetButtons(client) & buttons); + return Client_GetButtons(client) & buttons == buttons; } /** @@ -2452,12 +2420,12 @@ stock bool:Client_HasButtons(client, buttons) * @param buttons Buttons as bitflag. * @return */ -stock Client_GetChangedButtons(client) +stock int Client_GetChangedButtons(int client) { - static oldButtons[MAXPLAYERS+1] = {0,...}; + static int oldButtons[MAXPLAYERS+1] = {0,...}; - new buttons = Client_GetButtons(client); - new changedButtons = buttons ^ oldButtons[client]; + int buttons = Client_GetButtons(client); + int changedButtons = buttons ^ oldButtons[client]; oldButtons[client] = buttons; @@ -2469,9 +2437,8 @@ stock Client_GetChangedButtons(client) * * @param Client Client Index * @param maxspeed the maximum speed the client can move - * @noreturn */ -stock Client_SetMaxSpeed(client, Float:value) +stock void Client_SetMaxSpeed(int client, float value) { Entity_SetMaxSpeed(client, value); } @@ -2486,7 +2453,7 @@ stock Client_SetMaxSpeed(client, Float:value) * @param path Overlay path (based on the game/materials/ folder) or empty String to not show any overlay. * @noreturn */ -stock Client_SetScreenOverlay(client, const String:path[]) +stock void Client_SetScreenOverlay(int client, const char[] path) { ClientCommand(client, "r_screenoverlay \"%s\"", path); } @@ -2501,7 +2468,7 @@ stock Client_SetScreenOverlay(client, const String:path[]) * @param path Overlay path (based on the game/materials/ folder) or empty String to not show any overlay. * @noreturn */ -stock Client_SetScreenOverlayForAll(const String:path[]) +stock void Client_SetScreenOverlayForAll(const char[] path) { LOOP_CLIENTS(client, CLIENTFILTER_INGAME | CLIENTFILTER_NOBOTS) { Client_SetScreenOverlay(client, path); @@ -2514,7 +2481,7 @@ stock Client_SetScreenOverlayForAll(const String:path[]) * @param Client Client Index. * @noreturn */ -stock Client_Mute(client) +stock void Client_Mute(int client) { SetClientListeningFlags(client, VOICE_MUTED); } @@ -2524,11 +2491,10 @@ stock Client_Mute(client) * Code copied from basecomm.sp * * @param Client Client Index. - * @noreturn */ -stock Client_UnMute(client) +stock void Client_UnMute(int client) { - static Handle:cvDeadTalk = INVALID_HANDLE; + static ConVar cvDeadTalk = null; if (cvDeadTalk == INVALID_HANDLE) { cvDeadTalk = FindConVar("sm_deadtalk"); @@ -2538,10 +2504,10 @@ stock Client_UnMute(client) SetClientListeningFlags(client, VOICE_NORMAL); } else { - if (GetConVarInt(cvDeadTalk) == 1 && !IsPlayerAlive(client)) { + if (cvDeadTalk.IntValue == 1 && !IsPlayerAlive(client)) { SetClientListeningFlags(client, VOICE_LISTENALL); } - else if (GetConVarInt(cvDeadTalk) == 2 && !IsPlayerAlive(client)) { + else if (cvDeadTalk.IntValue == 2 && !IsPlayerAlive(client)) { SetClientListeningFlags(client, VOICE_TEAM); } else { @@ -2556,9 +2522,9 @@ stock Client_UnMute(client) * @param Client Client Index. * @return True if the client is muted, false otherwise. */ -stock bool:Client_IsMuted(client) +stock bool Client_IsMuted(int client) { - return bool:(GetClientListeningFlags(client) & VOICE_MUTED); + return GetClientListeningFlags(client) & VOICE_MUTED > 0; } /** @@ -2572,9 +2538,9 @@ stock bool:Client_IsMuted(client) * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). * @return True if the client if the client matches, false otherwise. */ -stock bool:Client_MatchesFilter(client, flags) +stock bool Client_MatchesFilter(int client, int flags) { - new bool:isIngame = false; + bool isIngame = false; if (flags >= CLIENTFILTER_INGAME) { isIngame = IsClientInGame(client); @@ -2669,10 +2635,10 @@ stock bool:Client_MatchesFilter(client, flags) * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). * @return The number of clients stored in the array */ -stock Client_Get(clients[], flags=CLIENTFILTER_ALL) +stock int Client_Get(int[] clients, int flags=CLIENTFILTER_ALL) { - new x=0; - for (new client = 1; client <= MaxClients; client++) { + int x=0; + for (int client = 1; client <= MaxClients; client++) { if (!Client_MatchesFilter(client, flags)) { continue; @@ -2690,10 +2656,10 @@ stock Client_Get(clients[], flags=CLIENTFILTER_ALL) * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). * @return Client Index or -1 if no client was found */ -stock Client_GetRandom(flags=CLIENTFILTER_ALL) +stock int Client_GetRandom(int flags=CLIENTFILTER_ALL) { - decl clients[MaxClients]; - new num = Client_Get(clients, flags); + int[] clients = new int[MaxClients]; + int num = Client_Get(clients, flags); if (num == 0) { return -1; @@ -2702,7 +2668,7 @@ stock Client_GetRandom(flags=CLIENTFILTER_ALL) return clients[0]; } - new random = Math_GetRandomInt(0, num-1); + int random = Math_GetRandomInt(0, num-1); return clients[random]; } @@ -2714,9 +2680,9 @@ stock Client_GetRandom(flags=CLIENTFILTER_ALL) * @param start Start Index. * @return Client Index or -1 if no client was found */ -stock Client_GetNext(flags, start=1) +stock int Client_GetNext(int flags, int start=1) { - for (new client=start; client <= MaxClients; client++) { + for (int client=start; client <= MaxClients; client++) { if (Client_MatchesFilter(client, flags)) { return client; @@ -2732,10 +2698,10 @@ stock Client_GetNext(flags, start=1) * @param client Client Index. * @return Time in seconds as Float */ -stock Float:Client_GetMapTime(client) +stock float Client_GetMapTime(int client) { - new Float:fClientTime = GetClientTime(client); - new Float:fGameTime = GetGameTime(); + float fClientTime = GetClientTime(client); + float fGameTime = GetGameTime(); return (fClientTime < fGameTime) ? fClientTime : fGameTime; } @@ -2746,7 +2712,7 @@ stock Float:Client_GetMapTime(client) * @param client Client Index. * @return Money value from the client. */ -stock Client_GetMoney(client) +stock int Client_GetMoney(int client) { return GetEntProp(client, Prop_Send, "m_iAccount"); } @@ -2756,9 +2722,8 @@ stock Client_GetMoney(client) * * @param client Client Index. * @param value Money value to set. - * @noreturn */ -stock Client_SetMoney(client, value) +stock void Client_SetMoney(int client, int value) { SetEntProp(client, Prop_Send, "m_iAccount", value); } @@ -2771,9 +2736,9 @@ stock Client_SetMoney(client, value) * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). * @return Number of observers found. */ -stock Client_GetObservers(client, observers[], flags=CLIENTFILTER_ALL) +stock int Client_GetObservers(int client, int[] observers, int flags=CLIENTFILTER_ALL) { - new count = 0; + int count = 0; LOOP_CLIENTS(player, CLIENTFILTER_OBSERVERS | flags) { @@ -2785,7 +2750,7 @@ stock Client_GetObservers(client, observers[], flags=CLIENTFILTER_ALL) return count; } -static Float:getPlayersInRadius_distances[MAXPLAYERS+1]; +static float getPlayersInRadius_distances[MAXPLAYERS+1]; /** * Gets all players near a player in a certain radius and @@ -2797,12 +2762,10 @@ static Float:getPlayersInRadius_distances[MAXPLAYERS+1]; * @param orderByDistance Set to true to order the clients by distance, false otherwise. * @return Number of clients found. */ -stock Client_GetPlayersInRadius(client, clients[], Float:radius, bool:orderByDistance=true) +stock int Client_GetPlayersInRadius(int client, int[] clients, float radius, bool orderByDistance=true) { - decl Float:origin_client[3]; - new - Float:distance, - count=0; + float origin_client[3], distance; + int count=0; Entity_GetAbsOrigin(client, origin_client); @@ -2830,7 +2793,7 @@ stock Client_GetPlayersInRadius(client, clients[], Float:radius, bool:orderByDis return count; } -public __smlib_GetPlayersInRadius_Sort(player1, player2, const clients[], Handle:hndl) +public int __smlib_GetPlayersInRadius_Sort(int player1, int player2, const int[] clients, Handle hndl) { return FloatCompare(getPlayersInRadius_distances[player1], getPlayersInRadius_distances[player2]); } @@ -2843,9 +2806,9 @@ public __smlib_GetPlayersInRadius_Sort(player1, player2, const clients[], Handle * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). * @return Client Index or -1 if no client was found */ -stock Client_GetNextObserver(client, start=1, flags=CLIENTFILTER_ALL) +stock int Client_GetNextObserver(int client, int start=1, int flags=CLIENTFILTER_ALL) { - for (new player=start; player <= MaxClients; player++) { + for (int player=start; player <= MaxClients; player++) { if (Client_MatchesFilter(player, CLIENTFILTER_OBSERVERS | flags)) { @@ -2864,9 +2827,9 @@ stock Client_GetNextObserver(client, start=1, flags=CLIENTFILTER_ALL) * * @return player_manager entity or INVALID_ENT_REFERENCE if not found. */ -stock Client_GetPlayerManager() +stock int Client_GetPlayerManager() { - static player_manager = INVALID_ENT_REFERENCE; + static int player_manager = INVALID_ENT_REFERENCE; if (player_manager != INVALID_ENT_REFERENCE) { @@ -2878,9 +2841,9 @@ stock Client_GetPlayerManager() } } - new maxEntities = GetMaxEntities(); + int maxEntities = GetMaxEntities(); - for (new entity=0; entity < maxEntities; entity++) { + for (int entity=MaxClients+1; entity < maxEntities; entity++) { if (!Entity_IsValid(entity)) { continue; @@ -2904,11 +2867,11 @@ stock Client_GetPlayerManager() * @param start New ping value. * @return True on sucess, false otherwise. */ -stock Client_SetPing(client, value) +stock int Client_SetPing(int client, int value) { - new player_manager = Client_GetPlayerManager(); + int player_manager = Client_GetPlayerManager(); - static offset = -1; + static int offset = -1; if (offset== -1) { offset = GetEntSendPropOffs(player_manager, "m_iPing", true); @@ -2923,7 +2886,7 @@ stock Client_SetPing(client, value) return true; } -static printToTop_excludeclient = -1; +static int printToTop_excludeclient = -1; /** * Exclude a client from the next call to a Client_PrintToTop function. @@ -2931,7 +2894,7 @@ static printToTop_excludeclient = -1; * @param client Client Index. * @noreturn */ -stock Client_PrintToTopExclude(client) +stock void Client_PrintToTopExclude(int client) { printToTop_excludeclient = client; } @@ -2950,12 +2913,12 @@ stock Client_PrintToTopExclude(client) * @param text Text to print to. * @return True on success, false if the key value for the dialog couldn't be created or closed. */ -stock bool:Client_PrintToTopRaw(client, r=255, g=255, b=255, a=255, Float:duration=10.0, const String:text[]) +stock bool Client_PrintToTopRaw(int client, int r=255, int g=255, int b=255, int a=255, float duration=10.0, const char[] text) { //message line max 50 //overline: 39*_ //underline: 44*T - new Handle:keyValue = CreateKeyValues("Stuff", "title", text); + KeyValues keyValue = CreateKeyValues("Stuff", "title", text); if (keyValue == INVALID_HANDLE) { return false; @@ -2966,10 +2929,8 @@ stock bool:Client_PrintToTopRaw(client, r=255, g=255, b=255, a=255, Float:durati KvSetNum(keyValue, "time", RoundToFloor(duration)); CreateDialog(client, keyValue, DialogType_Msg); + delete keyValue; - if (!CloseHandle(keyValue)) { - return false; - } return true; } @@ -2988,9 +2949,9 @@ stock bool:Client_PrintToTopRaw(client, r=255, g=255, b=255, a=255, Float:durati * @param ... Variable number of format parameters. * @return True on success, false if the key value for the dialog couldn't be created or closed. */ -stock bool:Client_PrintToTop(client, r=255, g=255, b=255, a=255, Float:duration=10.0, const String:format[], any:...) +stock bool Client_PrintToTop(int client, int r=255, int g=255, int b=255, int a=255, float duration=10.0, const char[] format, any ...) { - new String:buffer[150]; + char buffer[150]; SetGlobalTransTarget(client); VFormat(buffer, sizeof(buffer), format, 8); @@ -3009,17 +2970,15 @@ stock bool:Client_PrintToTop(client, r=255, g=255, b=255, a=255, Float:duration= * @param duration Duration in seconds the text stays (min 10 - max 200 seconds). * @param format Formatting rules. * @param ... Variable number of format parameters. - * @noreturn */ -stock Client_PrintToTopAll(r=255, g=255, b=255, a=255, Float:duration=10.0, const String:format[], any:...) +stock void Client_PrintToTopAll(int r=255, int g=255, int b=255, int a=255, float duration=10.0, const char[] format, any ...) { - decl - String:buffer[150]; - new + char buffer[150]; + int language, lastLanguage = -1; - for (new client=1; client <= MaxClients; client++) { + for (int client=1; client <= MaxClients; client++) { if (!IsClientInGame(client)) { continue; @@ -3057,18 +3016,16 @@ stock Client_PrintToTopAll(r=255, g=255, b=255, a=255, Float:duration=10.0, cons * @param duration Duration in seconds the text stays (min 10 - max 200 seconds). * @param format Formatting rules. * @param ... Variable number of format parameters. - * @noreturn */ -stock Client_PrintToTopEx(clients[], numClients, r=255, g=255, b=255, a=255, Float:duration=10.0, const String:format[], any:...) +stock void Client_PrintToTopEx(int[] clients, int numClients, int r=255, int g=255, int b=255, int a=255, float duration=10.0, const char[] format, any ...) { - decl - String:buffer[150]; - new + char buffer[150]; + int client, language, lastLanguage = -1; - for (new i=0; i < numClients; i++) { + for (int i=0; i < numClients; i++) { client = clients[i]; @@ -3099,11 +3056,10 @@ stock Client_PrintToTopEx(clients[], numClients, r=255, g=255, b=255, a=255, Flo * * @tested csgo * @param client Client index - * @noreturn */ -stock Client_ShowScoreboard(client, flags=USERMSG_RELIABLE | USERMSG_BLOCKHOOKS) +stock void Client_ShowScoreboard(int client, int flags=USERMSG_RELIABLE | USERMSG_BLOCKHOOKS) { - new Handle:handle = StartMessageOne("VGUIMenu", client, flags); + Handle handle = StartMessageOne("VGUIMenu", client, flags); if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && GetUserMessageType() == UM_Protobuf) { diff --git a/addons/sourcemod/scripting/include/smlib/colors.inc b/addons/sourcemod/scripting/include/smlib/colors.inc index ffcdb9e..9872227 100644 --- a/addons/sourcemod/scripting/include/smlib/colors.inc +++ b/addons/sourcemod/scripting/include/smlib/colors.inc @@ -12,22 +12,22 @@ enum ChatColorSubjectType { - ChatColorSubjectType_none = -3, + ChatColorSubjectType_none = -3, // Subject/Team colors - ChatColorSubjectType_player = -2, + ChatColorSubjectType_player = -2, ChatColorSubjectType_undefined = -1, - ChatColorSubjectType_world = 0 + ChatColorSubjectType_world = 0 // Anything higher is a specific team } -enum ChatColorInfo +enum struct ChatColorInfo { - ChatColorInfo_Code, - ChatColorInfo_Alternative, - bool:ChatColorInfo_Supported, - ChatColorSubjectType:ChatColorInfo_SubjectType -}; + int ChatColorInfo_Code; + int ChatColorInfo_Alternative; + bool ChatColorInfo_Supported; + ChatColorSubjectType ChatColorInfo_SubjectType; +} enum ChatColor { @@ -42,69 +42,54 @@ enum ChatColor ChatColor_Gray, ChatColor_Green, ChatColor_Olivegreen, - ChatColor_Black + ChatColor_Black, + ChatColor_MAXCOLORS } -static String:chatColorTags[][] = { - "N", // Normal - "O", // Orange - "R", // Red - "RB", // Red, Blue - "B", // Blue - "BR", // Blue, Red - "T", // Team - "L", // Light green - "GRA", // GRAy - "G", // Green - "OG", // Olive green - "BLA" // BLAck +static char chatColorTags[][] = { + "N", // Normal + "O", // Orange + "R", // Red + "RB", // Red, Blue + "B", // Blue + "BR", // Blue, Red + "T", // Team + "L", // Light green + "GRA", // Gray + "G", // Green + "OG", // Olive green + "BLA" // Black }; -static String:chatColorNames[][] = { - "normal", // Normal - "orange", // Orange - "red", // Red - "redblue", // Red, Blue - "blue", // Blue - "bluered", // Blue, Red - "team", // Team - "lightgreen", // Light green - "gray", // GRAy - "green", // Green - "olivegreen", // Olive green - "black" // BLAck +static char chatColorNames[][] = { + "normal", // Normal + "orange", // Orange + "red", // Red + "redblue", // Red, Blue + "blue", // Blue + "bluered", // Blue, Red + "team", // Team + "lightgreen", // Light green + "gray", // Gray + "green", // Green + "olivegreen", // Olive green + "black" // Black }; -static chatColorInfo[][ChatColorInfo] = -{ - // Code , alternative , Is Supported? Chat color subject type Color name - { '\x01', -1/* None */ , true, ChatColorSubjectType_none, }, // Normal - { '\x01', 0 /* None */ , true, ChatColorSubjectType_none, }, // Orange - { '\x03', 9 /* Green */ , true, ChatColorSubjectType:2 }, // Red - { '\x03', 4 /* Blue */ , true, ChatColorSubjectType:2 }, // Red, Blue - { '\x03', 9 /* Green */ , true, ChatColorSubjectType:3 }, // Blue - { '\x03', 2 /* Red */ , true, ChatColorSubjectType:3 }, // Blue, Red - { '\x03', 9 /* Green */ , true, ChatColorSubjectType_player }, // Team - { '\x03', 9 /* Green */ , true, ChatColorSubjectType_world }, // Light green - { '\x03', 9 /* Green */ , true, ChatColorSubjectType_undefined},// GRAy - { '\x04', 0 /* Normal*/ , true, ChatColorSubjectType_none }, // Green - { '\x05', 9 /* Green */ , true, ChatColorSubjectType_none }, // Olive green - { '\x06', 9 /* Green */ , true, ChatColorSubjectType_none } // BLAck -}; +static ChatColorInfo chatColorInfo[ChatColor_MAXCOLORS]; -static bool:checkTeamPlay = false; -static Handle:mp_teamplay = INVALID_HANDLE; -static bool:isSayText2_supported = true; -static chatSubject = CHATCOLOR_NOSUBJECT; +static bool checkTeamPlay = false; +static ConVar mp_teamplay = null; +static bool isSayText2_supported = true; +static int chatSubject = CHATCOLOR_NOSUBJECT; /** * Sets the subject (a client) for the chat color parser. * Call this before Color_ParseChatText() or Client_PrintToChat(). * * @param client Client Index/Subject - * @noreturn */ -stock Color_ChatSetSubject(client) +stock void Color_ChatSetSubject(int client) { chatSubject = client; } @@ -114,7 +99,7 @@ stock Color_ChatSetSubject(client) * * @return Client Index/Subject, or CHATCOLOR_NOSUBJECT if none */ -stock Color_ChatGetSubject() +stock int Color_ChatGetSubject() { return chatSubject; } @@ -122,10 +107,8 @@ stock Color_ChatGetSubject() /** * Clears the subject used for the chat color parser. * Call this after Color_ParseChatText(). - * - * @noreturn */ -stock Color_ChatClearSubject() +stock void Color_ChatClearSubject() { chatSubject = CHATCOLOR_NOSUBJECT; } @@ -136,22 +119,20 @@ stock Color_ChatClearSubject() * table. The support colors are hardcoded, but can be overriden for each game by * creating the file gamedata/smlib_colors.games.txt. * - * @param str Chat String - * @param subject Output Buffer - * @param size Output Buffer size - * @return Returns a value for the subject + * @param str Chat String + * @param subject Output Buffer + * @param size Output Buffer size + * @return Returns a value for the subject */ -stock Color_ParseChatText(const String:str[], String:buffer[], size) +stock int Color_ParseChatText(const char[] str, char[] buffer, int size) { - new - bool:inBracket = false, - x = 0, x_buf = 0, x_tag = 0, - subject = CHATCOLOR_NOSUBJECT; + bool inBracket = false; + int x, x_buf, x_tag; + int subject = CHATCOLOR_NOSUBJECT; - decl - String:sTag[10] = "", // This should be able to hold "\x08RRGGBBAA"\0 - String:colorCode[10] = "", // This should be able to hold "\x08RRGGBBAA"\0 - String:currentColor[10] = "\x01"; // Initialize with normal color + char sTag[10] = ""; // This should be able to hold "\x08RRGGBBAA"\0 + char colorCode[10] = ""; // This should be able to hold "\x08RRGGBBAA"\0 + char currentColor[10] = "\x01"; // Initialize with normal color size--; @@ -165,7 +146,7 @@ stock Color_ParseChatText(const String:str[], String:buffer[], size) break; } - new character = str[x++]; + char character = str[x++]; if (inBracket) { // We allow up to 9 characters in the tag (#RRGGBBAA) @@ -243,14 +224,13 @@ stock Color_ParseChatText(const String:str[], String:buffer[], size) * @param tag Color Tag String. * @param subject Subject variable to pass * @param result The result as character sequence (string). This will be \0 if the tag is unkown. - * @noreturn */ -stock Color_TagToCode(const String:tag[], &subject=-1, String:result[10]) +stock void Color_TagToCode(const char[] tag, int &subject=-1, char result[10]) { // Check if the tag starts with a '#'. // We will handle it has RGB(A)-color code then. if (tag[0] == '#') { - new length_tag = strlen(tag); + int length_tag = strlen(tag); switch (length_tag - 1) { // #RGB -> \07RRGGBB case 3: { @@ -283,7 +263,7 @@ stock Color_TagToCode(const String:tag[], &subject=-1, String:result[10]) } else { // Try to handle this string as color name - new n = Array_FindString(chatColorTags, sizeof(chatColorTags), tag); + int n = Array_FindString(chatColorTags, sizeof(chatColorTags), tag); // Check if this tag is invalid if (n == -1) { @@ -294,7 +274,7 @@ stock Color_TagToCode(const String:tag[], &subject=-1, String:result[10]) // Check if the color is actually supported 'n stuff. Color_GetChatColorInfo(n, subject); - result[0] = chatColorInfo[n][ChatColorInfo_Code]; + result[0] = chatColorInfo[n].ChatColorInfo_Code; result[1] = '\0'; } @@ -309,18 +289,17 @@ stock Color_TagToCode(const String:tag[], &subject=-1, String:result[10]) * @param input Input String. * @param output Output String. * @param size Max Size of the Output string - * @noreturn */ -stock Color_StripFromChatText(const String:input[], String:output[], size) +stock void Color_StripFromChatText(const char[] input, char[] output, int size) { - new x = 0; - for (new i=0; input[i] != '\0'; i++) { + int x = 0; + for (int i=0; input[i] != '\0'; i++) { if (x+1 == size) { break; } - new character = input[i]; + char character = input[i]; if (character > 0x08) { output[x++] = character; @@ -336,98 +315,168 @@ stock Color_StripFromChatText(const String:input[], String:output[], size) * if a game uses another color code for a specific color. * All those hardcoded default values can be overriden in * smlib's color gamedata file. - * - * @noreturn */ -static stock Color_ChatInitialize() +static stock void Color_ChatInitialize() { - static initialized = false; + static bool initialized = false; if (initialized) { return; } initialized = true; - - decl String:gameFolderName[32]; + + // Normal + chatColorInfo[ChatColor_Normal].ChatColorInfo_Code = '\x01'; + chatColorInfo[ChatColor_Normal].ChatColorInfo_Alternative = -1; /* None */ + chatColorInfo[ChatColor_Normal].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Normal].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + + // Orange + chatColorInfo[ChatColor_Orange].ChatColorInfo_Code = '\x01'; + chatColorInfo[ChatColor_Orange].ChatColorInfo_Alternative = 0; /* None */ + chatColorInfo[ChatColor_Orange].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Orange].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + + // Red + chatColorInfo[ChatColor_Red].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_Red].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Red].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Red].ChatColorInfo_SubjectType = view_as(2); + + // Red, Blue + chatColorInfo[ChatColor_RedBlue].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_RedBlue].ChatColorInfo_Alternative = 4; /* Blue */ + chatColorInfo[ChatColor_RedBlue].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_RedBlue].ChatColorInfo_SubjectType = view_as(2); + + // Blue + chatColorInfo[ChatColor_Blue].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_Blue].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Blue].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Blue].ChatColorInfo_SubjectType = view_as(3); + + // Blue, Red + chatColorInfo[ChatColor_BlueRed].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_BlueRed].ChatColorInfo_Alternative = 2; /* Red */ + chatColorInfo[ChatColor_BlueRed].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_BlueRed].ChatColorInfo_SubjectType = view_as(3); + + // Team + chatColorInfo[ChatColor_Team].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_Team].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Team].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Team].ChatColorInfo_SubjectType = ChatColorSubjectType_player; + + // Light green + chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_SubjectType = ChatColorSubjectType_world; + + // Gray + chatColorInfo[ChatColor_Gray].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_Gray].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Gray].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Gray].ChatColorInfo_SubjectType = ChatColorSubjectType_undefined; + + // Green + chatColorInfo[ChatColor_Green].ChatColorInfo_Code = '\x04'; + chatColorInfo[ChatColor_Green].ChatColorInfo_Alternative = 0; /* Normal*/ + chatColorInfo[ChatColor_Green].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Green].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + + // Olive green + chatColorInfo[ChatColor_Olivegreen].ChatColorInfo_Code = '\x05'; + chatColorInfo[ChatColor_Olivegreen].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Olivegreen].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Olivegreen].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + + // Black + chatColorInfo[ChatColor_Black].ChatColorInfo_Code = '\x06'; + chatColorInfo[ChatColor_Black].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Black].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + + char gameFolderName[PLATFORM_MAX_PATH]; GetGameFolderName(gameFolderName, sizeof(gameFolderName)); - chatColorInfo[ChatColor_Black][ChatColorInfo_Supported] = false; + chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = false; if (strncmp(gameFolderName, "left4dead", 9, false) != 0 && !StrEqual(gameFolderName, "cstrike", false) && !StrEqual(gameFolderName, "tf", false)) { - chatColorInfo[ChatColor_Lightgreen][ChatColorInfo_Supported]= false; - chatColorInfo[ChatColor_Gray][ChatColorInfo_Supported] = false; + chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_Supported = false; + chatColorInfo[ChatColor_Gray].ChatColorInfo_Supported = false; } if (StrEqual(gameFolderName, "tf", false)) { - chatColorInfo[ChatColor_Black][ChatColorInfo_Supported] = true; + chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = true; - chatColorInfo[ChatColor_Gray][ChatColorInfo_Code] = '\x01'; - chatColorInfo[ChatColor_Gray][ChatColorInfo_SubjectType] = ChatColorSubjectType_none; + chatColorInfo[ChatColor_Gray].ChatColorInfo_Code = '\x01'; + chatColorInfo[ChatColor_Gray].ChatColorInfo_SubjectType = ChatColorSubjectType_none; } else if (strncmp(gameFolderName, "left4dead", 9, false) == 0) { - chatColorInfo[ChatColor_Red][ChatColorInfo_SubjectType] = ChatColorSubjectType:3; - chatColorInfo[ChatColor_RedBlue][ChatColorInfo_SubjectType] = ChatColorSubjectType:3; - chatColorInfo[ChatColor_Blue][ChatColorInfo_SubjectType] = ChatColorSubjectType:2; - chatColorInfo[ChatColor_BlueRed][ChatColorInfo_SubjectType] = ChatColorSubjectType:2; + chatColorInfo[ChatColor_Red].ChatColorInfo_SubjectType = view_as(3); + chatColorInfo[ChatColor_RedBlue].ChatColorInfo_SubjectType = view_as(3); + chatColorInfo[ChatColor_Blue].ChatColorInfo_SubjectType = view_as(2); + chatColorInfo[ChatColor_BlueRed].ChatColorInfo_SubjectType = view_as(2); - chatColorInfo[ChatColor_Orange][ChatColorInfo_Code] = '\x04'; - chatColorInfo[ChatColor_Green][ChatColorInfo_Code] = '\x05'; + chatColorInfo[ChatColor_Orange].ChatColorInfo_Code = '\x04'; + chatColorInfo[ChatColor_Green].ChatColorInfo_Code = '\x05'; } else if (StrEqual(gameFolderName, "hl2mp", false)) { - chatColorInfo[ChatColor_Red][ChatColorInfo_SubjectType] = ChatColorSubjectType:3; - chatColorInfo[ChatColor_RedBlue][ChatColorInfo_SubjectType] = ChatColorSubjectType:3; - chatColorInfo[ChatColor_Blue][ChatColorInfo_SubjectType] = ChatColorSubjectType:2; - chatColorInfo[ChatColor_BlueRed][ChatColorInfo_SubjectType] = ChatColorSubjectType:2; - chatColorInfo[ChatColor_Black][ChatColorInfo_Supported] = true; + chatColorInfo[ChatColor_Red].ChatColorInfo_SubjectType = view_as(3); + chatColorInfo[ChatColor_RedBlue].ChatColorInfo_SubjectType = view_as(3); + chatColorInfo[ChatColor_Blue].ChatColorInfo_SubjectType = view_as(2); + chatColorInfo[ChatColor_BlueRed].ChatColorInfo_SubjectType = view_as(2); + chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = true; checkTeamPlay = true; } else if (StrEqual(gameFolderName, "dod", false)) { - chatColorInfo[ChatColor_Gray][ChatColorInfo_Code] = '\x01'; - chatColorInfo[ChatColor_Gray][ChatColorInfo_SubjectType] = ChatColorSubjectType_none; + chatColorInfo[ChatColor_Gray].ChatColorInfo_Code = '\x01'; + chatColorInfo[ChatColor_Gray].ChatColorInfo_SubjectType = ChatColorSubjectType_none; - chatColorInfo[ChatColor_Black][ChatColorInfo_Supported] = true; - chatColorInfo[ChatColor_Orange][ChatColorInfo_Supported] = false; + chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Orange].ChatColorInfo_Supported = false; } if (GetUserMessageId("SayText2") == INVALID_MESSAGE_ID) { isSayText2_supported = false; } - decl String:path_gamedata[PLATFORM_MAX_PATH]; + char path_gamedata[PLATFORM_MAX_PATH]; BuildPath(Path_SM, path_gamedata, sizeof(path_gamedata), "gamedata/%s.txt", SMLIB_COLORS_GAMEDATAFILE); if (FileExists(path_gamedata)) { - new Handle:gamedata = INVALID_HANDLE; + Handle gamedata = INVALID_HANDLE; if ((gamedata = LoadGameConfigFile(SMLIB_COLORS_GAMEDATAFILE)) != INVALID_HANDLE) { - decl String:keyName[32], String:buffer[6]; + char keyName[32], buffer[6]; - for (new i=0; i < sizeof(chatColorNames); i++) { + for (int i=0; i < sizeof(chatColorNames); i++) { Format(keyName, sizeof(keyName), "%s_code", chatColorNames[i]); if (GameConfGetKeyValue(gamedata, keyName, buffer, sizeof(buffer))) { - chatColorInfo[i][ChatColorInfo_Code] = StringToInt(buffer); + chatColorInfo[i].ChatColorInfo_Code = StringToInt(buffer); } Format(keyName, sizeof(keyName), "%s_alternative", chatColorNames[i]); if (GameConfGetKeyValue(gamedata, keyName, buffer, sizeof(buffer))) { - chatColorInfo[i][ChatColorInfo_Alternative] = buffer[0]; + chatColorInfo[i].ChatColorInfo_Alternative = buffer[0]; } Format(keyName, sizeof(keyName), "%s_supported", chatColorNames[i]); if (GameConfGetKeyValue(gamedata, keyName, buffer, sizeof(buffer))) { - chatColorInfo[i][ChatColorInfo_Supported] = StrEqual(buffer, "true"); + chatColorInfo[i].ChatColorInfo_Supported = StrEqual(buffer, "true"); } Format(keyName, sizeof(keyName), "%s_subjecttype", chatColorNames[i]); if (GameConfGetKeyValue(gamedata, keyName, buffer, sizeof(buffer))) { - chatColorInfo[i][ChatColorInfo_SubjectType] = ChatColorSubjectType:StringToInt(buffer); + chatColorInfo[i].ChatColorInfo_SubjectType = view_as(StringToInt(buffer)); } } @@ -449,9 +498,8 @@ static stock Color_ChatInitialize() * * @param index * @param subject A client index or CHATCOLOR_NOSUBJECT - * @noreturn */ -static stock Color_GetChatColorInfo(&index, &subject=CHATCOLOR_NOSUBJECT) +static stock int Color_GetChatColorInfo(int &index, int &subject=CHATCOLOR_NOSUBJECT) { Color_ChatInitialize(); @@ -459,9 +507,9 @@ static stock Color_GetChatColorInfo(&index, &subject=CHATCOLOR_NOSUBJECT) index = 0; } - while (!chatColorInfo[index][ChatColorInfo_Supported]) { + while (!chatColorInfo[index].ChatColorInfo_Supported) { - new alternative = chatColorInfo[index][ChatColorInfo_Alternative]; + int alternative = chatColorInfo[index].ChatColorInfo_Alternative; if (alternative == -1) { index = 0; @@ -475,11 +523,10 @@ static stock Color_GetChatColorInfo(&index, &subject=CHATCOLOR_NOSUBJECT) index = 0; } - new newSubject = CHATCOLOR_NOSUBJECT; - new ChatColorSubjectType:type = chatColorInfo[index][ChatColorInfo_SubjectType]; + int newSubject = CHATCOLOR_NOSUBJECT; + ChatColorSubjectType type = chatColorInfo[index].ChatColorInfo_SubjectType; switch (type) { - case ChatColorSubjectType_none: { } case ChatColorSubjectType_player: { @@ -493,16 +540,16 @@ static stock Color_GetChatColorInfo(&index, &subject=CHATCOLOR_NOSUBJECT) } default: { - if (!checkTeamPlay || GetConVarBool(mp_teamplay)) { + if (!checkTeamPlay || mp_teamplay.BoolValue) { if (subject > 0 && subject <= MaxClients) { - if (GetClientTeam(subject) == _:type) { + if (GetClientTeam(subject) == view_as(type)) { newSubject = subject; } } else if (subject == CHATCOLOR_NOSUBJECT) { - new client = Team_GetAnyClient(_:type); + int client = Team_GetAnyClient(view_as(type)); if (client != -1) { newSubject = client; @@ -515,7 +562,7 @@ static stock Color_GetChatColorInfo(&index, &subject=CHATCOLOR_NOSUBJECT) if (type > ChatColorSubjectType_none && ((subject != CHATCOLOR_NOSUBJECT && subject != newSubject) || newSubject == CHATCOLOR_NOSUBJECT || !isSayText2_supported)) { - index = chatColorInfo[index][ChatColorInfo_Alternative]; + index = chatColorInfo[index].ChatColorInfo_Alternative; newSubject = Color_GetChatColorInfo(index, subject); } diff --git a/addons/sourcemod/scripting/include/smlib/concommands.inc b/addons/sourcemod/scripting/include/smlib/concommands.inc index a90fd1c..2bd708f 100644 --- a/addons/sourcemod/scripting/include/smlib/concommands.inc +++ b/addons/sourcemod/scripting/include/smlib/concommands.inc @@ -13,9 +13,9 @@ * @param flags Flags to check. * @return True if flags are set, false otherwise. */ -stock bool:ConCommand_HasFlags(const String:command[], const flags) +stock bool ConCommand_HasFlags(const char[] command, int flags) { - return bool:(GetCommandFlags(command) & flags); + return GetCommandFlags(command) & flags > 0; } /** @@ -23,11 +23,10 @@ stock bool:ConCommand_HasFlags(const String:command[], const flags) * * @param command ConCommand name. * @param flags Flags to add. - * @noreturn */ -stock ConCommand_AddFlags(const String:command[], const flags) +stock void ConCommand_AddFlags(const char[] command, int flags) { - new newFlags = GetCommandFlags(command); + int newFlags = GetCommandFlags(command); newFlags |= flags; SetCommandFlags(command, newFlags); } @@ -37,11 +36,10 @@ stock ConCommand_AddFlags(const String:command[], const flags) * * @param command ConCommand name. * @param flags Flags to remove - * @noreturn */ -stock ConCommand_RemoveFlags(const String:command[], const flags) +stock void ConCommand_RemoveFlags(const char[] command, int flags) { - new newFlags = GetCommandFlags(command); + int newFlags = GetCommandFlags(command); newFlags &= ~flags; SetCommandFlags(command, newFlags); } diff --git a/addons/sourcemod/scripting/include/smlib/convars.inc b/addons/sourcemod/scripting/include/smlib/convars.inc index 9b9ba4a..b7f4b23 100644 --- a/addons/sourcemod/scripting/include/smlib/convars.inc +++ b/addons/sourcemod/scripting/include/smlib/convars.inc @@ -12,9 +12,9 @@ * @param flags Flags to check. * @return True if flags are set, false otherwise. */ -stock bool:Convar_HasFlags(Handle:convar, flags) +stock bool Convar_HasFlags(ConVar convar, int flags) { - return bool:(GetConVarFlags(convar) & flags); + return convar.Flags & flags > 0; } /** @@ -22,13 +22,12 @@ stock bool:Convar_HasFlags(Handle:convar, flags) * * @param convar ConVar Handle. * @param flags Flags to add. - * @noreturn */ -stock Convar_AddFlags(Handle:convar, flags) +stock void Convar_AddFlags(ConVar convar, int flags) { - new newFlags = GetConVarFlags(convar); + int newFlags = convar.Flags; newFlags |= flags; - SetConVarFlags(convar, newFlags); + convar.Flags = newFlags; } /** @@ -38,11 +37,11 @@ stock Convar_AddFlags(Handle:convar, flags) * @param flags Flags to remove * @noreturn */ -stock Convar_RemoveFlags(Handle:convar, flags) +stock void Convar_RemoveFlags(ConVar convar, int flags) { - new newFlags = GetConVarFlags(convar); + int newFlags = convar.Flags; newFlags &= ~flags; - SetConVarFlags(convar, newFlags); + convar.Flags = newFlags; } /** @@ -52,13 +51,13 @@ stock Convar_RemoveFlags(Handle:convar, flags) * @param name String Name. * @return True if the name specified is a valid ConVar or console command name, false otherwise. */ -stock bool:Convar_IsValidName(const String:name[]) +stock bool Convar_IsValidName(const char[] name) { if (name[0] == '\0') { return false; } - new n=0; + int n=0; while (name[n] != '\0') { if (!IsValidConVarChar(name[n])) { diff --git a/addons/sourcemod/scripting/include/smlib/crypt.inc b/addons/sourcemod/scripting/include/smlib/crypt.inc index 6e5f380..21319aa 100644 --- a/addons/sourcemod/scripting/include/smlib/crypt.inc +++ b/addons/sourcemod/scripting/include/smlib/crypt.inc @@ -14,13 +14,13 @@ ***********************************************************************************/ // The Base64 encoding table -static const String:base64_sTable[] = +static const char base64_sTable[] = // 0000000000111111111122222222223333333333444444444455555555556666 // 0123456789012345678901234567890123456789012345678901234567890123 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // The Base64 decoding table -static const base64_decodeTable[] = { +static const int base64_decodeTable[] = { // 0 1 2 3 4 5 6 7 8 9 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 9 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 10 - 19 @@ -54,11 +54,11 @@ static const base64_decodeTable[] = { * For some reason the standard demands a string in 24-bit (3 character) intervals. * This fill character is used to identify unused bytes at the end of the string. */ -static const base64_cFillChar = '='; +static const char base64_cFillChar = '='; // The conversion characters between the standard and URL-compliance Base64 protocols -static const String:base64_mime_chars[] = "+/="; -static const String:base64_url_chars[] = "-_."; +static const char base64_mime_chars[] = "+/="; +static const char base64_url_chars[] = "-_."; /* * Encodes a string or binary data into Base64 @@ -70,10 +70,10 @@ static const String:base64_url_chars[] = "-_."; * This is not needed for a text string, but is important for binary data since there is no end-of-line character. * @return The length of the written Base64 string, in bytes. */ -stock Crypt_Base64Encode(const String:sString[], String:sResult[], len, sourcelen=0) +stock int Crypt_Base64Encode(const char[] sString, char[] sResult, int len, int sourcelen=0) { - new nLength; // The string length to be read from the input - new resPos; // The string position in the result buffer + int nLength; // The string length to be read from the input + int resPos; // The string position in the result buffer // If the read length was specified, use it; otherwise, pull the string length from the input. if (sourcelen > 0) { @@ -85,8 +85,8 @@ stock Crypt_Base64Encode(const String:sString[], String:sResult[], len, sourcele // Loop through and generate the Base64 encoded string // NOTE: This performs the standard encoding process. Do not manipulate the logic within this loop. - for (new nPos = 0; nPos < nLength; nPos++) { - new cCode; + for (int nPos = 0; nPos < nLength; nPos++) { + int cCode; cCode = (sString[nPos] >> 2) & 0x3f; @@ -132,16 +132,16 @@ stock Crypt_Base64Encode(const String:sString[], String:sResult[], len, sourcele * @param len The maximum length of the storage buffer, in characters/bytes. * @return The length of the decoded data, in bytes. */ -stock Crypt_Base64Decode(const String:sString[], String:sResult[], len) +stock int Crypt_Base64Decode(const char[] sString, char[] sResult, int len) { - new nLength = strlen(sString); // The string length to be read from the input - new resPos; // The string position in the result buffer + int nLength = strlen(sString); // The string length to be read from the input + int resPos; // The string position in the result buffer // Loop through and generate the Base64 encoded string // NOTE: This performs the standard encoding process. Do not manipulate the logic within this loop. - for (new nPos = 0; nPos < nLength; nPos++) { + for (int nPos = 0; nPos < nLength; nPos++) { - new c, c1; + int c, c1; c = base64_decodeTable[sString[nPos++]]; c1 = base64_decodeTable[sString[nPos]]; @@ -190,21 +190,21 @@ stock Crypt_Base64Decode(const String:sString[], String:sResult[], len) * @param len The maximum length of the storage buffer in characters/bytes. * @return Number of cells written. */ -stock Crypt_Base64MimeToUrl(const String:sString[], String:sResult[], len) +stock int Crypt_Base64MimeToUrl(const char[] sString, char[] sResult, int len) { - new chars_len = sizeof(base64_mime_chars); // Length of the two standards vs. URL character lists - new nLength; // The string length to be read from the input - new temp_char; // Buffer character + int chars_len = sizeof(base64_mime_chars); // Length of the two standards vs. URL character lists + int nLength; // The string length to be read from the input + int temp_char; // Buffer character nLength = strlen(sString); - new String:sTemp[nLength+1]; // Buffer string + char[] sTemp = new char[nLength+1]; // Buffer string // Loop through string - for (new i = 0; i < nLength; i++) { + for (int i = 0; i < nLength; i++) { temp_char = sString[i]; - for (new j = 0; j < chars_len; j++) { + for (int j = 0; j < chars_len; j++) { if(temp_char == base64_mime_chars[j]) { temp_char = base64_url_chars[j]; @@ -230,20 +230,20 @@ stock Crypt_Base64MimeToUrl(const String:sString[], String:sResult[], len) * @param len The maximum length of the storage buffer in characters/bytes. * @return Number of cells written. */ -stock Crypt_Base64UrlToMime(const String:sString[], String:sResult[], len) +stock int Crypt_Base64UrlToMime(const char[] sString, char[] sResult, int len) { - new chars_len = sizeof(base64_mime_chars); // Length of the two standards vs. URL character lists - new nLength; // The string length to be read from the input - new temp_char; // Buffer character + int chars_len = sizeof(base64_mime_chars); // Length of the two standards vs. URL character lists + int nLength; // The string length to be read from the input + int temp_char; // Buffer character nLength = strlen(sString); - new String:sTemp[nLength+1]; // Buffer string + char[] sTemp = new char[nLength+1]; // Buffer string // Loop through string - for (new i = 0; i < nLength; i++) { + for (int i = 0; i < nLength; i++) { temp_char = sString[i]; - for (new j = 0; j < chars_len; j++) { + for (int j = 0; j < chars_len; j++) { if (temp_char == base64_url_chars[j]) { temp_char = base64_mime_chars[j]; break; @@ -273,16 +273,15 @@ stock Crypt_Base64UrlToMime(const String:sString[], String:sResult[], len) * @param str Input String * @param output Output String Buffer * @param maxlen Size of the Output String Buffer - * @noreturn */ -stock Crypt_MD5(const String:str[], String:output[], maxlen) +stock void Crypt_MD5(const char[] str, char[] output, int maxlen) { - decl x[2]; - decl buf[4]; - decl input[64]; - new i, ii; + int x[2]; + int buf[4]; + int input[64]; + int i, ii; - new len = strlen(str); + int len = strlen(str); // MD5Init x[0] = x[1] = 0; @@ -292,12 +291,12 @@ stock Crypt_MD5(const String:str[], String:output[], maxlen) buf[3] = 0x10325476; // MD5Update - new update[16]; + int update[16]; update[14] = x[0]; update[15] = x[1]; - new mdi = (x[0] >>> 3) & 0x3F; + int mdi = (x[0] >>> 3) & 0x3F; if ((x[0] + (len << 3)) < x[0]) { x[1] += 1; @@ -306,7 +305,7 @@ stock Crypt_MD5(const String:str[], String:output[], maxlen) x[0] += len << 3; x[1] += len >>> 29; - new c = 0; + int c = 0; while (len--) { input[mdi] = str[c]; mdi += 1; @@ -327,7 +326,7 @@ stock Crypt_MD5(const String:str[], String:output[], maxlen) } // MD5Final - new padding[64] = { + int padding[64] = { 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -338,7 +337,7 @@ stock Crypt_MD5(const String:str[], String:output[], maxlen) 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - new inx[16]; + int inx[16]; inx[14] = x[0]; inx[15] = x[1]; @@ -382,7 +381,7 @@ stock Crypt_MD5(const String:str[], String:output[], maxlen) MD5Transform(buf, inx); - new digest[16]; + int digest[16]; for (i = 0, ii = 0; i < 4; ++i, ii += 4) { digest[ii] = (buf[i]) & 0xFF; digest[ii + 1] = (buf[i] >>> 8) & 0xFF; @@ -395,39 +394,39 @@ stock Crypt_MD5(const String:str[], String:output[], maxlen) digest[8], digest[9], digest[10], digest[11], digest[12], digest[13], digest[14], digest[15]); } -static stock MD5Transform_FF(&a, &b, &c, &d, x, s, ac) - { +static stock void MD5Transform_FF(int &a, int &b, int &c, int &d, int x, int s, int ac) +{ a += (((b) & (c)) | ((~b) & (d))) + x + ac; a = (((a) << (s)) | ((a) >>> (32-(s)))); a += b; } -static stock MD5Transform_GG(&a, &b, &c, &d, x, s, ac) - { +static stock void MD5Transform_GG(int &a, int &b, int &c, int &d, int x, int s, int ac) +{ a += (((b) & (d)) | ((c) & (~d))) + x + ac; a = (((a) << (s)) | ((a) >>> (32-(s)))); a += b; } -static stock MD5Transform_HH(&a, &b, &c, &d, x, s, ac) +static stock void MD5Transform_HH(int &a, int &b, int &c, int &d, int x, int s, int ac) { a += ((b) ^ (c) ^ (d)) + x + ac; a = (((a) << (s)) | ((a) >>> (32-(s)))); a += b; } -static stock MD5Transform_II(&a, &b, &c, &d, x, s, ac) +static stock void MD5Transform_II(int &a, int &b, int &c, int &d, int x, int s, int ac) { a += ((c) ^ ((b) | (~d))) + x + ac; a = (((a) << (s)) | ((a) >>> (32-(s)))); a += b; } -static stock MD5Transform(buf[], input[]){ - new a = buf[0]; - new b = buf[1]; - new c = buf[2]; - new d = buf[3]; +static stock void MD5Transform(int[] buf, int[] input){ + int a = buf[0]; + int b = buf[1]; + int c = buf[2]; + int d = buf[3]; MD5Transform_FF(a, b, c, d, input[0], 7, 0xd76aa478); MD5Transform_FF(d, a, b, c, input[1], 12, 0xe8c7b756); @@ -514,21 +513,19 @@ static stock MD5Transform(buf[], input[]){ /* * Encrypts a text string using RC4. * Note: This function is NOT binary safe. - * Use EncodeRC4Binary to encode binary data. + * Use Crypt_RC4EncodeBinary to encode binary data. * * @param input The source data to be encrypted. * @param pwd The password/key used to encode and decode the data. * @param output The encoded result. * @param maxlen The maximum length of the output buffer. - * - * @noreturn */ -stock Crypt_RC4Encode(const String:input[], const String:pwd[], String:output[], maxlen) +stock void Crypt_RC4Encode(const char[] input, const char[] pwd, char[] output, int maxlen) { - decl pwd_len,str_len,i,j,a,k; - decl key[256]; - decl box[256]; - decl tmp; + int pwd_len,str_len,i,j,a,k; + int key[256]; + int box[256]; + int tmp; pwd_len = strlen(pwd); str_len = strlen(input); @@ -571,14 +568,13 @@ stock Crypt_RC4Encode(const String:input[], const String:pwd[], String:output[], * @param pwd The password/key used to encode and decode the data. * @param output The encoded result. * @param maxlen The maximum length of the output buffer. - * @noreturn */ -stock Crypt_RC4EncodeBinary(const String:input[], str_len, const String:pwd[], String:output[], maxlen) +stock int Crypt_RC4EncodeBinary(const char[] input, int str_len, const char[] pwd, char[] output, int maxlen) { - decl pwd_len,i,j,a,k; - decl key[256]; - decl box[256]; - decl tmp; + int pwd_len,i,j,a,k; + int key[256]; + int box[256]; + int tmp; pwd_len = strlen(pwd); diff --git a/addons/sourcemod/scripting/include/smlib/debug.inc b/addons/sourcemod/scripting/include/smlib/debug.inc index 46275ba..6a416ed 100644 --- a/addons/sourcemod/scripting/include/smlib/debug.inc +++ b/addons/sourcemod/scripting/include/smlib/debug.inc @@ -10,17 +10,15 @@ * * @param array Static Float-Array. * @param size Size of the Array. - * @noreturn */ -stock Debug_FloatArray(const Float:array[], size=3) +stock void Debug_FloatArray(const float[] array, int size=3) { - new String:output[64] = ""; + char output[64] = ""; - for (new i=0; i < size; ++i) { + for (int i=0; i < size; ++i) { if (i > 0 && i < size) { StrCat(output, sizeof(output), ", "); - } Format(output, sizeof(output), "%s%f", output, array[i]); diff --git a/addons/sourcemod/scripting/include/smlib/dynarrays.inc b/addons/sourcemod/scripting/include/smlib/dynarrays.inc index 8a16011..35a8951 100644 --- a/addons/sourcemod/scripting/include/smlib/dynarrays.inc +++ b/addons/sourcemod/scripting/include/smlib/dynarrays.inc @@ -18,7 +18,7 @@ * @return Value read. * @error Invalid Handle, invalid index, or invalid block. */ -stock bool:DynArray_GetBool(Handle:array, index, block=0, bool:asChar=false) +stock bool DynArray_GetBool(ArrayList array, int index, int block=0, bool asChar=false) { - return bool:GetArrayCell(array, index, block, asChar); + return array.Get(index, block, asChar) != 0; } diff --git a/addons/sourcemod/scripting/include/smlib/edicts.inc b/addons/sourcemod/scripting/include/smlib/edicts.inc index 376f975..86f4e2a 100644 --- a/addons/sourcemod/scripting/include/smlib/edicts.inc +++ b/addons/sourcemod/scripting/include/smlib/edicts.inc @@ -13,10 +13,10 @@ * @param name Name of the entity you want so search. * @return Edict Index or INVALID_ENT_REFERENCE if no entity was found. */ -stock Edict_FindByName(const String:name[]) +stock int Edict_FindByName(const char[] name) { - new maxEntities = GetMaxEntities(); - for (new edict=0; edict < maxEntities; edict++) { + int maxEntities = GetMaxEntities(); + for (int edict=0; edict < maxEntities; edict++) { if (!IsValidEdict(edict)) { continue; @@ -39,10 +39,10 @@ stock Edict_FindByName(const String:name[]) * @param hammerId Hammer editor ID * @return Edict Index or INVALID_ENT_REFERENCE if no entity was found. */ -stock Edict_FindByHammerId(hammerId) +stock int Edict_FindByHammerId(int hammerId) { - new maxEntities = GetMaxEntities(); - for (new edict=0; edict < maxEntities; edict++) { + int maxEntities = GetMaxEntities(); + for (int edict=0; edict < maxEntities; edict++) { if (!IsValidEdict(edict)) { continue; @@ -64,13 +64,13 @@ stock Edict_FindByHammerId(hammerId) * @param ignoreEntity Ignore this entity * @return Edict Index or INVALID_ENT_REFERENCE if no entity was found. */ -stock Edict_GetClosest(Float:vecOrigin_center[3], bool:clientsOnly=false, ignoreEntity=-1) +stock int Edict_GetClosest(float vecOrigin_center[3], bool clientsOnly=false, int ignoreEntity=-1) { - decl Float:vecOrigin_edict[3]; - new Float:smallestDistance = 0.0; - new closestEdict = INVALID_ENT_REFERENCE; + float vecOrigin_edict[3]; + float smallestDistance = 0.0; + int closestEdict = INVALID_ENT_REFERENCE; - new maxEntities; + int maxEntities; if (clientsOnly) { maxEntities = MaxClients; @@ -79,7 +79,7 @@ stock Edict_GetClosest(Float:vecOrigin_center[3], bool:clientsOnly=false, ignore maxEntities = GetMaxEntities(); } - for (new edict=1; edict <= maxEntities; edict++) { + for (int edict=1; edict <= maxEntities; edict++) { if (!IsValidEdict(edict)) { continue; @@ -95,7 +95,7 @@ stock Edict_GetClosest(Float:vecOrigin_center[3], bool:clientsOnly=false, ignore Entity_GetAbsOrigin(edict, vecOrigin_edict); - new Float:edict_distance = GetVectorDistance(vecOrigin_center, vecOrigin_edict, true); + float edict_distance = GetVectorDistance(vecOrigin_center, vecOrigin_edict, true); if (edict_distance < smallestDistance || smallestDistance == 0.0) { smallestDistance = edict_distance; @@ -113,11 +113,11 @@ stock Edict_GetClosest(Float:vecOrigin_center[3], bool:clientsOnly=false, ignore * @param clientsOnly True if you only want to search for clients * @return The closest edict or INVALID_ENT_REFERENCE */ -stock Edict_GetClosestToEdict(edict, bool:clientsOnly=false) +stock int Edict_GetClosestToEdict(int edict, bool clientsOnly=false) { - decl Float:vecOrigin[3]; + float vecOrigin[3]; - if (GetEntSendPropOffs(edict, "m_vecOrigin") == -1) { + if (!HasEntProp(edict, Prop_Send, "m_vecOrigin")) { return INVALID_ENT_REFERENCE; } diff --git a/addons/sourcemod/scripting/include/smlib/effects.inc b/addons/sourcemod/scripting/include/smlib/effects.inc index c638fd6..b5e9122 100644 --- a/addons/sourcemod/scripting/include/smlib/effects.inc +++ b/addons/sourcemod/scripting/include/smlib/effects.inc @@ -31,16 +31,16 @@ enum DissolveType * @param magnitude How strongly to push away from the center. * @return True on success, otherwise false. */ -stock bool:Effect_DissolveEntity(entity, DissolveType:dissolveType=DISSOLVE_NORMAL, magnitude=1) +stock bool Effect_DissolveEntity(int entity, DissolveType dissolveType=DISSOLVE_NORMAL, int magnitude=1) { - new env_entity_dissolver = CreateEntityByName("env_entity_dissolver"); + int env_entity_dissolver = CreateEntityByName("env_entity_dissolver"); if (env_entity_dissolver == -1) { return false; } Entity_PointAtTarget(env_entity_dissolver, entity); - SetEntProp(env_entity_dissolver, Prop_Send, "m_nDissolveType", _:dissolveType); + SetEntProp(env_entity_dissolver, Prop_Send, "m_nDissolveType", dissolveType); SetEntProp(env_entity_dissolver, Prop_Send, "m_nMagnitude", magnitude); AcceptEntityInput(env_entity_dissolver, "Dissolve"); Entity_Kill(env_entity_dissolver); @@ -55,9 +55,9 @@ stock bool:Effect_DissolveEntity(entity, DissolveType:dissolveType=DISSOLVE_NORM * @param dissolveType Dissolve Type, use the DissolveType enum. * @return True on success, otherwise false. */ -stock bool:Effect_DissolvePlayerRagDoll(client, DissolveType:dissolveType=DISSOLVE_NORMAL) +stock bool Effect_DissolvePlayerRagDoll(int client, DissolveType dissolveType=DISSOLVE_NORMAL) { - new m_hRagdoll = GetEntPropEnt(client, Prop_Send, "m_hRagdoll"); + int m_hRagdoll = GetEntPropEnt(client, Prop_Send, "m_hRagdoll"); if (m_hRagdoll == -1) { return false; @@ -66,7 +66,7 @@ stock bool:Effect_DissolvePlayerRagDoll(client, DissolveType:dissolveType=DISSOL return Effect_DissolveEntity(m_hRagdoll, dissolveType); } -functag EffectCallback public(entity, any:data); +typedef EffectCallback = function void(int entity, any data); /** * Fades an entity in our out. @@ -82,11 +82,10 @@ functag EffectCallback public(entity, any:data); * @param fast Optional: Fade the entity fast (~0.7 secs) or slow (~3 secs) * @param callback Optional: You can specify a callback Function that will get called when the fade is finished. * @param data Optional: You can pass any data to the callback. - * @return True on success, otherwise false. */ -stock Effect_Fade(entity, fadeOut=true, kill=false, fast=true, EffectCallback:callback=INVALID_FUNCTION, any:data=0) +stock void Effect_Fade(int entity, bool fadeOut=true, bool kill=false, bool fast=true, EffectCallback callback=INVALID_FUNCTION, any data=0) { - new Float:timerTime = 0.0; + float timerTime = 0.0; if (fast) { timerTime = 0.6; @@ -112,16 +111,12 @@ stock Effect_Fade(entity, fadeOut=true, kill=false, fast=true, EffectCallback:ca ChangeEdictState(entity, GetEntSendPropOffs(entity, "m_nRenderFX", true)); if (kill || callback != INVALID_FUNCTION) { - new Handle:dataPack = INVALID_HANDLE; + DataPack dataPack = null; CreateDataTimer(timerTime, _smlib_Timer_Effect_Fade, dataPack, TIMER_FLAG_NO_MAPCHANGE | TIMER_DATA_HNDL_CLOSE); WritePackCell(dataPack, EntIndexToEntRef(entity)); WritePackCell(dataPack, kill); -#if SOURCEMOD_V_MAJOR >= 1 && SOURCEMOD_V_MINOR >= 7 WritePackFunction(dataPack, callback); -#else - WritePackCell(dataPack, _:callback); -#endif WritePackCell(dataPack, data); ResetPack(dataPack); } @@ -135,9 +130,8 @@ stock Effect_Fade(entity, fadeOut=true, kill=false, fast=true, EffectCallback:ca * @param fast Optional: Fade the entity fast (~0.7 secs) or slow (~3 secs) * @param callback Optional: You can specify a callback Function that will get called when the fade is finished. * @param data Optional: You can pass any data to the callback. - * @return True on success, otherwise false. */ -stock Effect_FadeIn(entity, fast=true, EffectCallback:callback=INVALID_FUNCTION, any:data=0) +stock void Effect_FadeIn(int entity, bool fast=true, EffectCallback callback=INVALID_FUNCTION, any data=0) { Effect_Fade(entity, false, false, fast, callback, data); } @@ -152,23 +146,18 @@ stock Effect_FadeIn(entity, fast=true, EffectCallback:callback=INVALID_FUNCTION, * @param fast Optional: Fade the entity fast (~0.7 secs) or slow (~3 secs) * @param callback Optional: You can specify a callback Function that will get called when the fade is finished. * @param data Optional: You can pass any data to the callback. - * @return True on success, otherwise false. */ -stock Effect_FadeOut(entity, kill=false, fast=true, EffectCallback:callback=INVALID_FUNCTION, any:data=0) +stock void Effect_FadeOut(int entity, bool kill=false, bool fast=true, EffectCallback callback=INVALID_FUNCTION, any data=0) { Effect_Fade(entity, true, kill, fast, callback, data); } -public Action:_smlib_Timer_Effect_Fade(Handle:Timer, Handle:dataPack) +public Action _smlib_Timer_Effect_Fade(Handle Timer, DataPack dataPack) { - new entity = ReadPackCell(dataPack); - new kill = ReadPackCell(dataPack); -#if SOURCEMOD_V_MAJOR >= 1 && SOURCEMOD_V_MINOR >= 7 - new Function:callback = ReadPackFunction(dataPack); -#else - new Function:callback = Function:ReadPackCell(dataPack); -#endif - new any:data = any:ReadPackCell(dataPack); + int entity = ReadPackCell(dataPack); + int kill = ReadPackCell(dataPack); + Function callback = ReadPackFunction(dataPack); + any data = ReadPackCell(dataPack); if (callback != INVALID_FUNCTION) { Call_StartFunction(INVALID_HANDLE, callback); @@ -203,25 +192,24 @@ public Action:_smlib_Timer_Effect_Fade(Handle:Timer, Handle:dataPack) * @param amplitude Beam amplitude. * @param color Color array (r, g, b, a). * @param speed Speed of the beam. - * @noreturn */ -stock Effect_DrawBeamBoxToClient( - client, - const Float:bottomCorner[3], - const Float:upperCorner[3], - modelIndex, - haloIndex, - startFrame=0, - frameRate=30, - Float:life=5.0, - Float:width=5.0, - Float:endWidth=5.0, - fadeLength=2, - Float:amplitude=1.0, - const color[4]={ 255, 0, 0, 255 }, - speed=0 +stock void Effect_DrawBeamBoxToClient( + int client, + const float bottomCorner[3], + const float upperCorner[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + const int color[4]={ 255, 0, 0, 255 }, + int speed=0 ) { - new clients[1]; + int clients[1]; clients[0] = client; Effect_DrawBeamBox(clients, 1, bottomCorner, upperCorner, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); } @@ -244,26 +232,25 @@ stock Effect_DrawBeamBoxToClient( * @param amplitude Beam amplitude. * @param color Color array (r, g, b, a). * @param speed Speed of the beam. - * @noreturn */ -stock Effect_DrawBeamBoxToAll( - const Float:bottomCorner[3], - const Float:upperCorner[3], - modelIndex, - haloIndex, - startFrame=0, - frameRate=30, - Float:life=5.0, - Float:width=5.0, - Float:endWidth=5.0, - fadeLength=2, - Float:amplitude=1.0, - const color[4]={ 255, 0, 0, 255 }, - speed=0 +stock void Effect_DrawBeamBoxToAll( + const float bottomCorner[3], + const float upperCorner[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + const int color[4]={ 255, 0, 0, 255 }, + int speed=0 ) { - new clients[MaxClients]; - new numClients = Client_Get(clients, CLIENTFILTER_INGAME); + int[] clients = new int[MaxClients]; + int numClients = Client_Get(clients, CLIENTFILTER_INGAME); Effect_DrawBeamBox(clients, numClients, bottomCorner, upperCorner, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); } @@ -288,29 +275,28 @@ stock Effect_DrawBeamBoxToAll( * @param amplitude Beam amplitude. * @param color Color array (r, g, b, a). * @param speed Speed of the beam. - * @noreturn */ -stock Effect_DrawBeamBox( - clients[], - numClients, - const Float:bottomCorner[3], - const Float:upperCorner[3], - modelIndex, - haloIndex, - startFrame=0, - frameRate=30, - Float:life=5.0, - Float:width=5.0, - Float:endWidth=5.0, - fadeLength=2, - Float:amplitude=1.0, - const color[4]={ 255, 0, 0, 255 }, - speed=0 +stock void Effect_DrawBeamBox( + int[] clients, + int numClients, + const float bottomCorner[3], + const float upperCorner[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + const int color[4]={ 255, 0, 0, 255 }, + int speed=0 ) { // Create the additional corners of the box - decl Float:corners[8][3]; + float corners[8][3]; - for (new i=0; i < 4; i++) { + for (int i=0; i < 4; i++) { Array_Copy(bottomCorner, corners[i], 3); Array_Copy(upperCorner, corners[i+4], 3); } @@ -328,21 +314,21 @@ stock Effect_DrawBeamBox( // Horizontal Lines // Bottom - for (new i=0; i < 4; i++) { - new j = ( i == 3 ? 0 : i+1 ); + for (int i=0; i < 4; i++) { + int j = ( i == 3 ? 0 : i+1 ); TE_SetupBeamPoints(corners[i], corners[j], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); TE_Send(clients, numClients); } // Top - for (new i=4; i < 8; i++) { - new j = ( i == 7 ? 4 : i+1 ); + for (int i=4; i < 8; i++) { + int j = ( i == 7 ? 4 : i+1 ); TE_SetupBeamPoints(corners[i], corners[j], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); TE_Send(clients, numClients); } // All Vertical Lines - for (new i=0; i < 4; i++) { + for (int i=0; i < 4; i++) { TE_SetupBeamPoints(corners[i], corners[i+4], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); TE_Send(clients, numClients); } @@ -370,27 +356,26 @@ stock Effect_DrawBeamBox( * @param amplitude Beam amplitude. * @param color Color array (r, g, b, a). * @param speed Speed of the beam. - * @noreturn */ -stock Effect_DrawBeamBoxRotatableToClient( - client, - const Float:origin[3], - const Float:mins[3], - const Float:maxs[3], - const Float:angles[3], - modelIndex, - haloIndex, - startFrame=0, - frameRate=30, - Float:life=5.0, - Float:width=5.0, - Float:endWidth=5.0, - fadeLength=2, - Float:amplitude=1.0, - const color[4]={ 255, 0, 0, 255 }, - speed=0 +stock void Effect_DrawBeamBoxRotatableToClient( + int client, + const float origin[3], + const float mins[3], + const float maxs[3], + const float angles[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + const int color[4]={ 255, 0, 0, 255 }, + int speed=0 ) { - new clients[1]; + int clients[1]; clients[0] = client; Effect_DrawBeamBoxRotatable(clients, 1, origin, mins, maxs, angles, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); } @@ -417,28 +402,27 @@ stock Effect_DrawBeamBoxRotatableToClient( * @param amplitude Beam amplitude. * @param color Color array (r, g, b, a). * @param speed Speed of the beam. - * @noreturn */ -stock Effect_DrawBeamBoxRotatableToAll( - const Float:origin[3], - const Float:mins[3], - const Float:maxs[3], - const Float:angles[3], - modelIndex, - haloIndex, - startFrame=0, - frameRate=30, - Float:life=5.0, - Float:width=5.0, - Float:endWidth=5.0, - fadeLength=2, - Float:amplitude=1.0, - const color[4]={ 255, 0, 0, 255 }, - speed=0 +stock void Effect_DrawBeamBoxRotatableToAll( + const float origin[3], + const float mins[3], + const float maxs[3], + const float angles[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + const int color[4]={ 255, 0, 0, 255 }, + int speed=0 ) { - new clients[MaxClients]; - new numClients = Client_Get(clients, CLIENTFILTER_INGAME); + int[] clients = new int[MaxClients]; + int numClients = Client_Get(clients, CLIENTFILTER_INGAME); Effect_DrawBeamBoxRotatable(clients, numClients, origin, mins, maxs, angles, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); } @@ -465,29 +449,28 @@ stock Effect_DrawBeamBoxRotatableToAll( * @param amplitude Beam amplitude. * @param color Color array (r, g, b, a). * @param speed Speed of the beam. - * @noreturn */ -stock Effect_DrawBeamBoxRotatable( - clients[], - numClients, - const Float:origin[3], - const Float:mins[3], - const Float:maxs[3], - const Float:angles[3], - modelIndex, - haloIndex, - startFrame=0, - frameRate=30, - Float:life=5.0, - Float:width=5.0, - Float:endWidth=5.0, - fadeLength=2, - Float:amplitude=1.0, - const color[4]={ 255, 0, 0, 255 }, - speed=0 +stock void Effect_DrawBeamBoxRotatable( + int[] clients, + int numClients, + const float origin[3], + const float mins[3], + const float maxs[3], + const float angles[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + const int color[4]={ 255, 0, 0, 255 }, + int speed=0 ) { // Create the additional corners of the box - decl Float:corners[8][3]; + float corners[8][3]; Array_Copy(mins, corners[0], 3); Math_MakeVector(maxs[0], mins[1], mins[2], corners[1]); Math_MakeVector(maxs[0], maxs[1], mins[2], corners[2]); @@ -498,33 +481,33 @@ stock Effect_DrawBeamBoxRotatable( Math_MakeVector(mins[0], maxs[1], maxs[2], corners[7]); // Rotate all edges - for (new i=0; i < sizeof(corners); i++) { + for (int i=0; i < sizeof(corners); i++) { Math_RotateVector(corners[i], angles, corners[i]); } // Apply world offset (after rotation) - for (new i=0; i < sizeof(corners); i++) { + for (int i=0; i < sizeof(corners); i++) { AddVectors(origin, corners[i], corners[i]); } // Draw all the edges // Horizontal Lines // Bottom - for (new i=0; i < 4; i++) { - new j = ( i == 3 ? 0 : i+1 ); + for (int i=0; i < 4; i++) { + int j = ( i == 3 ? 0 : i+1 ); TE_SetupBeamPoints(corners[i], corners[j], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); TE_Send(clients, numClients); } // Top - for (new i=4; i < 8; i++) { - new j = ( i == 7 ? 4 : i+1 ); + for (int i=4; i < 8; i++) { + int j = ( i == 7 ? 4 : i+1 ); TE_SetupBeamPoints(corners[i], corners[j], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); TE_Send(clients, numClients); } // All Vertical Lines - for (new i=0; i < 4; i++) { + for (int i=0; i < 4; i++) { TE_SetupBeamPoints(corners[i], corners[i+4], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); TE_Send(clients, numClients); } @@ -548,25 +531,24 @@ stock Effect_DrawBeamBoxRotatable( * @param amplitude Beam amplitude. * @param color Color array (r, g, b, a). * @param speed Speed of the beam. - * @noreturn */ -stock Effect_DrawAxisOfRotationToClient( - client, - const Float:origin[3], - const Float:angles[3], - const Float:length[3], - modelIndex, - haloIndex, - startFrame=0, - frameRate=30, - Float:life=5.0, - Float:width=5.0, - Float:endWidth=5.0, - fadeLength=2, - Float:amplitude=1.0, - speed=0 +stock void Effect_DrawAxisOfRotationToClient( + int client, + const float origin[3], + const float angles[3], + const float length[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + int speed=0 ) { - new clients[1]; + int clients[1]; clients[0] = client; Effect_DrawAxisOfRotation(clients, 1, origin, angles, length, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, speed); } @@ -588,26 +570,25 @@ stock Effect_DrawAxisOfRotationToClient( * @param amplitude Beam amplitude. * @param color Color array (r, g, b, a). * @param speed Speed of the beam. - * @noreturn */ -stock Effect_DrawAxisOfRotationToAll( - const Float:origin[3], - const Float:angles[3], - const Float:length[3], - modelIndex, - haloIndex, - startFrame=0, - frameRate=30, - Float:life=5.0, - Float:width=5.0, - Float:endWidth=5.0, - fadeLength=2, - Float:amplitude=1.0, - speed=0 +stock void Effect_DrawAxisOfRotationToAll( + const float origin[3], + const float angles[3], + const float length[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + int speed=0 ) { - new clients[MaxClients]; - new numClients = Client_Get(clients, CLIENTFILTER_INGAME); + int[] clients = new int[MaxClients]; + int numClients = Client_Get(clients, CLIENTFILTER_INGAME); Effect_DrawAxisOfRotation(clients, numClients, origin, angles, length, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, speed); } @@ -631,27 +612,26 @@ stock Effect_DrawAxisOfRotationToAll( * @param amplitude Beam amplitude. * @param color Color array (r, g, b, a). * @param speed Speed of the beam. - * @noreturn */ -stock Effect_DrawAxisOfRotation( - clients[], - numClients, - const Float:origin[3], - const Float:angles[3], - const Float:length[3], - modelIndex, - haloIndex, - startFrame=0, - frameRate=30, - Float:life=5.0, - Float:width=5.0, - Float:endWidth=5.0, - fadeLength=2, - Float:amplitude=1.0, - speed=0 +stock void Effect_DrawAxisOfRotation( + int[] clients, + int numClients, + const float origin[3], + const float angles[3], + const float length[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + int speed=0 ) { // Create the additional corners of the box - new Float:xAxis[3], Float:yAxis[3], Float:zAxis[3]; + float xAxis[3], yAxis[3], zAxis[3]; xAxis[0] = length[0]; yAxis[1] = length[1]; zAxis[2] = length[2]; @@ -695,21 +675,21 @@ stock Effect_DrawAxisOfRotation( * @param receiveShadows When false then this prevents the sprite from receiving shadows. * @return Entity Index of the created Sprite. */ -stock Effect_EnvSprite( - const Float:origin[3], - modelIndex, - const color[4]={255, 255, 255, 255}, - Float:scale=0.25, - const String:targetName[MAX_NAME_LENGTH]="", - parent=-1, - RenderMode:renderMode=RENDER_WORLDGLOW, - RenderFx:renderFx=RENDERFX_NONE, - Float:glowProxySize=2.0, - Float:framerate=10.0, - Float:hdrColorScale=1.0, - bool:receiveShadows = true +stock int Effect_EnvSprite( + const float origin[3], + int modelIndex, + const int color[4]={255, 255, 255, 255}, + float scale=0.25, + const char targetName[MAX_NAME_LENGTH]="", + int parent=-1, + RenderMode renderMode=RENDER_WORLDGLOW, + RenderFx renderFx=RENDERFX_NONE, + float glowProxySize=2.0, + float framerate=10.0, + float hdrColorScale=1.0, + bool receiveShadows = true ) { - new entity = Entity_Create("env_sprite"); + int entity = Entity_Create("env_sprite"); if (entity == INVALID_ENT_REFERENCE) { return INVALID_ENT_REFERENCE; diff --git a/addons/sourcemod/scripting/include/smlib/entities.inc b/addons/sourcemod/scripting/include/smlib/entities.inc index 1036dd3..3f71e8f 100644 --- a/addons/sourcemod/scripting/include/smlib/entities.inc +++ b/addons/sourcemod/scripting/include/smlib/entities.inc @@ -13,7 +13,7 @@ * @param 1 Entity Index of the parent. * @param 2 Name of the children entity index variable (will be only valid in the loop). */ -#define LOOP_CHILDREN(%1,%2) for (new %2=Entity_GetNextChild(%1); %2 != INVALID_ENT_REFERENCE; %2=Entity_GetNextChild(%1, ++%2)) +#define LOOP_CHILDREN(%1,%2) for (int %2=Entity_GetNextChild(%1); %2 != INVALID_ENT_REFERENCE; %2=Entity_GetNextChild(%1, ++%2)) /* * Checks if an entity is valid and exists. @@ -21,7 +21,7 @@ * @param entity Entity Index. * @return True if the entity is valid, false otherwise. */ -stock Entity_IsValid(entity) +stock bool Entity_IsValid(int entity) { return IsValidEntity(entity); } @@ -38,12 +38,12 @@ stock Entity_IsValid(entity) * @param className Optional: Classname of the entity * @return Entity index or INVALID_ENT_REFERENCE if not matching entity was found. */ -stock Entity_FindByName(const String:name[], const String:className[]="") +stock int Entity_FindByName(const char[] name, const char[] className="") { if (className[0] == '\0') { // Hack: Double the limit to gets none-networked entities too. - new realMaxEntities = GetMaxEntities() * 2; - for (new entity=0; entity < realMaxEntities; entity++) { + int realMaxEntities = GetMaxEntities() * 2; + for (int entity=0; entity < realMaxEntities; entity++) { if (!IsValidEntity(entity)) { continue; @@ -55,7 +55,7 @@ stock Entity_FindByName(const String:name[], const String:className[]="") } } else { - new entity = INVALID_ENT_REFERENCE; + int entity = INVALID_ENT_REFERENCE; while ((entity = FindEntityByClassname(entity, className)) != INVALID_ENT_REFERENCE) { if (Entity_NameMatches(entity, name)) { @@ -81,12 +81,12 @@ stock Entity_FindByName(const String:name[], const String:className[]="") * @param className Optional: Classname of the entity * @return Edict Index or INVALID_ENT_REFERENCE if no entity was found. */ -stock Entity_FindByHammerId(hammerId, const String:className[]="") +stock int Entity_FindByHammerId(int hammerId, const char[] className="") { if (className[0] == '\0') { // Hack: Double the limit to gets none-networked entities too. - new realMaxEntities = GetMaxEntities() * 2; - for (new entity=0; entity < realMaxEntities; entity++) { + int realMaxEntities = GetMaxEntities() * 2; + for (int entity=0; entity < realMaxEntities; entity++) { if (!IsValidEntity(entity)) { continue; @@ -98,7 +98,7 @@ stock Entity_FindByHammerId(hammerId, const String:className[]="") } } else { - new entity = INVALID_ENT_REFERENCE; + int entity = INVALID_ENT_REFERENCE; while ((entity = FindEntityByClassname(entity, className)) != INVALID_ENT_REFERENCE) { if (Entity_GetHammerId(entity) == hammerId) { @@ -120,7 +120,7 @@ stock Entity_FindByHammerId(hammerId, const String:className[]="") * @return Entity index >= 0 if found, -1 otherwise. */ -stock Entity_FindByClassName(startEntity, const String:className[]) +stock int Entity_FindByClassName(int startEntity, const char[] className) { return FindEntityByClassname(startEntity, className); } @@ -133,9 +133,9 @@ stock Entity_FindByClassName(startEntity, const String:className[]) * @partialMatch If to do a partial classname check. * @return True if the classname matches, false otherwise. */ -stock bool:Entity_ClassNameMatches(entity, const String:className[], partialMatch=false) +stock bool Entity_ClassNameMatches(int entity, const char[] className, bool partialMatch=false) { - decl String:entity_className[64]; + char entity_className[64]; Entity_GetClassName(entity, entity_className, sizeof(entity_className)); if (partialMatch) { @@ -152,9 +152,9 @@ stock bool:Entity_ClassNameMatches(entity, const String:className[], partialMatc * @param class Name String. * @return True if the name matches, false otherwise. */ -stock bool:Entity_NameMatches(entity, const String:name[]) +stock bool Entity_NameMatches(int entity, const char[] name) { - decl String:entity_name[128]; + char entity_name[128]; Entity_GetName(entity, entity_name, sizeof(entity_name)); return StrEqual(name, entity_name); @@ -168,7 +168,7 @@ stock bool:Entity_NameMatches(entity, const String:name[]) * @param size Max size of buffer. * @return Number of non-null bytes written. */ -stock Entity_GetName(entity, String:buffer[], size) +stock int Entity_GetName(int entity, char[] buffer, int size) { return GetEntPropString(entity, Prop_Data, "m_iName", buffer, size); } @@ -180,9 +180,9 @@ stock Entity_GetName(entity, String:buffer[], size) * @param name The name you want to give. * @return True on success, false otherwise. */ -stock Entity_SetName(entity, const String:name[], any:...) +stock bool Entity_SetName(int entity, const char[] name, any ...) { - decl String:format[128]; + char format[128]; VFormat(format, sizeof(format), name, 3); return DispatchKeyValue(entity, "targetname", format); @@ -198,7 +198,7 @@ stock Entity_SetName(entity, const String:name[], any:...) * @param size Max size of buffer. * @return Number of non-null bytes written. */ -stock Entity_GetClassName(entity, String:buffer[], size) +stock int Entity_GetClassName(int entity, char[] buffer, int size) { return GetEntPropString(entity, Prop_Data, "m_iClassname", buffer, size); } @@ -210,7 +210,7 @@ stock Entity_GetClassName(entity, String:buffer[], size) * @param name The name you want to give. * @return True on success, false otherwise. */ -stock Entity_SetClassName(entity, const String:className[]) +stock bool Entity_SetClassName(int entity, const char[] className) { return DispatchKeyValue(entity, "classname", className); } @@ -223,7 +223,7 @@ stock Entity_SetClassName(entity, const String:className[]) * @param size Max size of buffer. * @return Number of non-null bytes written. */ -stock Entity_GetTargetName(entity, String:buffer[], size) +stock int Entity_GetTargetName(int entity, char[] buffer, int size) { return GetEntPropString(entity, Prop_Data, "m_target", buffer, size); } @@ -235,9 +235,9 @@ stock Entity_GetTargetName(entity, String:buffer[], size) * @param name The target name you want to set * @return True on success, false otherwise. */ -stock Entity_SetTargetName(entity, const String:name[], any:...) +stock bool Entity_SetTargetName(int entity, const char[] name, any ...) { - decl String:format[128]; + char format[128]; VFormat(format, sizeof(format), name, 3); return DispatchKeyValue(entity, "target", format); @@ -251,7 +251,7 @@ stock Entity_SetTargetName(entity, const String:name[], any:...) * @param size Max size of buffer. * @return Number of non-null bytes written. */ -stock Entity_GetGlobalName(entity, String:buffer[], size) +stock int Entity_GetGlobalName(int entity, char[] buffer, int size) { return GetEntPropString(entity, Prop_Data, "m_iGlobalname", buffer, size); } @@ -263,9 +263,9 @@ stock Entity_GetGlobalName(entity, String:buffer[], size) * @param name The global name you want to set. * @return True on success, false otherwise. */ -stock Entity_SetGlobalName(entity, const String:name[], any:...) +stock bool Entity_SetGlobalName(int entity, const char[] name, any ...) { - decl String:format[128]; + char format[128]; VFormat(format, sizeof(format), name, 3); return DispatchKeyValue(entity, "globalname", format); @@ -279,7 +279,7 @@ stock Entity_SetGlobalName(entity, const String:name[], any:...) * @param size Max size of buffer. * @return Number of non-null bytes written. */ -stock Entity_GetParentName(entity, String:buffer[], size) +stock int Entity_GetParentName(int entity, char[] buffer, int size) { return GetEntPropString(entity, Prop_Data, "m_iParent", buffer, size); } @@ -291,9 +291,9 @@ stock Entity_GetParentName(entity, String:buffer[], size) * @param name The parent name you want to set. * @return True on success, false otherwise. */ -stock Entity_SetParentName(entity, const String:name[], any:...) +stock bool Entity_SetParentName(int entity, const char[] name, any ...) { - decl String:format[128]; + char format[128]; VFormat(format, sizeof(format), name, 3); return DispatchKeyValue(entity, "parentname", format); @@ -307,7 +307,7 @@ stock Entity_SetParentName(entity, const String:name[], any:...) * @param entity Entity index. * @return Hammer ID. */ -stock Entity_GetHammerId(entity) +stock int Entity_GetHammerId(int entity) { return GetEntProp(entity, Prop_Data, "m_iHammerID"); } @@ -318,7 +318,7 @@ stock Entity_GetHammerId(entity) * @param entity Entity index. * @return Radius */ -stock Float:Entity_GetRadius(entity) +stock float Entity_GetRadius(int entity) { return GetEntPropFloat(entity, Prop_Data, "m_flRadius"); } @@ -328,9 +328,8 @@ stock Float:Entity_GetRadius(entity) * * @param entity Entity index. * @param radius Radius value - * @noreturn */ -stock Entity_SetRadius(entity, Float:radius) +stock void Entity_SetRadius(int entity, float radius) { SetEntPropFloat(entity, Prop_Data, "m_flRadius", radius); } @@ -339,10 +338,9 @@ stock Entity_SetRadius(entity, Float:radius) * Gets the Mins of an entity. * * @param entity Entity index. - * @param vec Vector. - * @noreturn + * @param vec Buffer to hold the vector. */ -stock Entity_GetMinSize(entity, Float:vec[3]) +stock void Entity_GetMinSize(int entity, float vec[3]) { GetEntPropVector(entity, Prop_Send, "m_vecMins", vec); } @@ -352,9 +350,8 @@ stock Entity_GetMinSize(entity, Float:vec[3]) * * @param entity Entity index. * @param vec Vector. - * @noreturn */ -stock Entity_SetMinSize(entity, const Float:vecMins[3]) +stock void Entity_SetMinSize(int entity, const float vecMins[3]) { SetEntPropVector(entity, Prop_Send, "m_vecMins", vecMins); } @@ -364,10 +361,9 @@ stock Entity_SetMinSize(entity, const Float:vecMins[3]) * This functions isn't safe to use, use Entity_SetMinMaxSize() instead. * * @param entity Entity index - * @param vec return vector. - * @noreturn + * @param vec Buffer to hold the vector */ -stock Entity_GetMaxSize(entity, Float:vec[3]) +stock void Entity_GetMaxSize(int entity, float vec[3]) { GetEntPropVector(entity, Prop_Send, "m_vecMaxs", vec); } @@ -377,10 +373,9 @@ stock Entity_GetMaxSize(entity, Float:vec[3]) * This functions isn't safe to use, use Entity_SetMinMaxSize() instead. * * @param entity Entity index. - * @param vec Vector. - * @noreturn + * @param vec Buffer to hold the vector. */ -stock Entity_SetMaxSize(entity, const Float:vecMaxs[3]) +stock void Entity_SetMaxSize(int entity, const float vecMaxs[3]) { SetEntPropVector(entity, Prop_Send, "m_vecMaxs", vecMaxs); } @@ -392,20 +387,19 @@ stock Entity_SetMaxSize(entity, const Float:vecMaxs[3]) * @param entity Entity index. * @param vecMins Min size Vector * @param vecMaxs Max size Vector - * @noreturn */ -stock Entity_SetMinMaxSize(entity, Float:vecMins[3], Float:vecMaxs[3]) +stock void Entity_SetMinMaxSize(int entity, float vecMins[3], float vecMaxs[3]) { // Taken from hl2sdk-ob-valve\game\server\util.cpp SetMinMaxSize() // Todo: Replace this by a SDK call - for (new i=0; i<3; i++) { + for (int i=0; i<3; i++) { if (vecMins[i] > vecMaxs[i]) { ThrowError("Error: mins[%d] > maxs[%d] of entity %d", i, i, EntRefToEntIndex(entity)); } } - decl Float:m_vecMins[3], Float:m_vecMaxs[3]; + float m_vecMins[3], m_vecMaxs[3]; Entity_GetMinSize(entity, m_vecMins); Entity_GetMaxSize(entity, m_vecMaxs); @@ -416,7 +410,7 @@ stock Entity_SetMinMaxSize(entity, Float:vecMins[3], Float:vecMaxs[3]) Entity_SetMinSize(entity, vecMins); Entity_SetMaxSize(entity, vecMaxs); - decl Float:vecSize[3]; + float vecSize[3]; SubtractVectors(vecMaxs, vecMins, vecSize); Entity_SetRadius(entity, GetVectorLength(vecSize) * 0.5); @@ -492,7 +486,7 @@ stock Entity_SetMinMaxSize(entity, Float:vecMins[3], Float:vecMaxs[3]) * @param entity Entity index. * @return Spawnflags value */ -stock Entity_GetSpawnFlags(entity) +stock int Entity_GetSpawnFlags(int entity) { return GetEntProp(entity, Prop_Data, "m_spawnflags"); } @@ -502,9 +496,8 @@ stock Entity_GetSpawnFlags(entity) * * @param entity Entity index. * @param flags Flags value - * @noreturn */ -stock Entity_SetSpawnFlags(entity, flags) +stock void Entity_SetSpawnFlags(int entity, int flags) { SetEntProp(entity, Prop_Data, "m_spawnflags", flags); } @@ -514,11 +507,10 @@ stock Entity_SetSpawnFlags(entity, flags) * * @param entity Entity index. * @param flags Flags value - * @noreturn */ -stock Entity_AddSpawnFlags(entity, flags) +stock void Entity_AddSpawnFlags(int entity, int flags) { - new spawnFlags = Entity_GetSpawnFlags(entity); + int spawnFlags = Entity_GetSpawnFlags(entity); spawnFlags |= flags; Entity_SetSpawnFlags(entity, spawnFlags); } @@ -528,11 +520,10 @@ stock Entity_AddSpawnFlags(entity, flags) * * @param entity Entity index. * @param flags Flags value - * @noreturn */ -stock Entity_RemoveSpawnFlags(entity, flags) +stock void Entity_RemoveSpawnFlags(int entity, int flags) { - new spawnFlags = Entity_GetSpawnFlags(entity); + int spawnFlags = Entity_GetSpawnFlags(entity); spawnFlags &= ~flags; Entity_SetSpawnFlags(entity, spawnFlags); } @@ -541,9 +532,8 @@ stock Entity_RemoveSpawnFlags(entity, flags) * Clears all Spawnflags of an entity. * * @param entity Entity index. - * @noreturn - */ -stock Entity_ClearSpawnFlags(entity) + * @noretur */ +stock void Entity_ClearSpawnFlags(int entity) { Entity_SetSpawnFlags(entity, 0); } @@ -555,9 +545,9 @@ stock Entity_ClearSpawnFlags(entity) * @param flags Flags value. * @return True if the entity has the spawnflags set, false otherwise. */ -stock bool:Entity_HasSpawnFlags(entity, flags) +stock bool Entity_HasSpawnFlags(int entity, int flags) { - return bool:(Entity_GetSpawnFlags(entity) & flags); + return Entity_GetSpawnFlags(entity) & flags == flags; } /* @@ -622,9 +612,9 @@ enum Entity_Flags * @param entity Entity index. * @return Entity flags value */ -stock Entity_Flags:Entity_GetEFlags(entity) +stock Entity_Flags Entity_GetEFlags(int entity) { - return Entity_Flags:GetEntProp(entity, Prop_Data, "m_iEFlags"); + return view_as(GetEntProp(entity, Prop_Data, "m_iEFlags")); } /** @@ -632,9 +622,8 @@ stock Entity_Flags:Entity_GetEFlags(entity) * * @param entity Entity index. * @param flags Flags value - * @noreturn */ -stock Entity_SetEFlags(entity, Entity_Flags:flags) +stock void Entity_SetEFlags(int entity, Entity_Flags flags) { SetEntProp(entity, Prop_Data, "m_iEFlags", flags); } @@ -644,11 +633,10 @@ stock Entity_SetEFlags(entity, Entity_Flags:flags) * * @param entity Entity index. * @param flags Flags value - * @noreturn */ -stock Entity_AddEFlags(entity, Entity_Flags:flags) +stock void Entity_AddEFlags(int entity, Entity_Flags flags) { - new Entity_Flags:setFlags = Entity_GetEFlags(entity); + Entity_Flags setFlags = Entity_GetEFlags(entity); setFlags |= flags; Entity_SetEFlags(entity, setFlags); } @@ -658,11 +646,10 @@ stock Entity_AddEFlags(entity, Entity_Flags:flags) * * @param entity Entity index. * @param flags Flags value - * @noreturn */ -stock Entity_RemoveEFlags(entity, Entity_Flags:flags) +stock void Entity_RemoveEFlags(int entity, Entity_Flags flags) { - new Entity_Flags:setFlags = Entity_GetEFlags(entity); + Entity_Flags setFlags = Entity_GetEFlags(entity); setFlags &= ~flags; Entity_SetEFlags(entity, setFlags); } @@ -674,11 +661,11 @@ stock Entity_RemoveEFlags(entity, Entity_Flags:flags) * @param flags Flags value * @return True if the flags are set, false otherwise. */ -stock bool:Entity_HasEFlags(entity, Entity_Flags:flags) +stock bool Entity_HasEFlags(int entity, Entity_Flags flags) { - new Entity_Flags:currentEFlags = Entity_GetEFlags(entity); + Entity_Flags currentEFlags = Entity_GetEFlags(entity); - return bool:(currentEFlags & flags); + return currentEFlags & flags == flags; } /** @@ -686,9 +673,8 @@ stock bool:Entity_HasEFlags(entity, Entity_Flags:flags) * You normally call this when a collision setting has changed. * * @param entity Entity index. - * @noreturn */ -stock Entity_MarkSurrBoundsDirty(entity) +stock void Entity_MarkSurrBoundsDirty(int entity) { Entity_AddEFlags(entity, EFL_DIRTY_SURR_COLLISION_BOUNDS); } @@ -707,7 +693,7 @@ stock Entity_MarkSurrBoundsDirty(entity) * @param entity Entity Index. * @return Entity Flags. */ -stock Entity_GetFlags(entity) +stock int Entity_GetFlags(int entity) { return GetEntProp(entity, Prop_Data, "m_fFlags"); } @@ -717,9 +703,8 @@ stock Entity_GetFlags(entity) * * @param entity Entity index. * @param flags New Flags value - * @noreturn */ -stock Entity_SetFlags(entity, flags) +stock void Entity_SetFlags(int entity, int flags) { SetEntProp(entity, Prop_Data, "m_fFlags", flags); } @@ -731,9 +716,9 @@ stock Entity_SetFlags(entity, flags) * @param flags Flags to add * @noreturn */ -stock Entity_AddFlags(entity, flags) +stock void Entity_AddFlags(int entity, int flags) { - new setFlags = Entity_GetFlags(entity); + int setFlags = Entity_GetFlags(entity); setFlags |= flags; Entity_SetFlags(entity, flags); } @@ -743,11 +728,10 @@ stock Entity_AddFlags(entity, flags) * * @param entity Entity index. * @param flags Flags to remove - * @noreturn */ -stock Entity_RemoveFlags(entity, flags) +stock void Entity_RemoveFlags(int entity, int flags) { - new setFlags = Entity_GetFlags(entity); + int setFlags = Entity_GetFlags(entity); setFlags &= ~flags; Entity_SetFlags(entity, setFlags); } @@ -759,11 +743,10 @@ stock Entity_RemoveFlags(entity, flags) * * @param entity Entity index. * @param flags Flag to Toggle - * @noreturn */ -stock Entity_ToggleFlag(entity, flag) +stock void Entity_ToggleFlag(int entity, int flag) { - new setFlag = Entity_GetFlags(entity); + int setFlag = Entity_GetFlags(entity); setFlag ^= flag; Entity_SetFlags(entity, setFlag); } @@ -772,9 +755,8 @@ stock Entity_ToggleFlag(entity, flag) * Removes all flags from the entity * * @param entity Entity index. - * @noreturn */ -stock Entity_ClearFlags(entity) +stock void Entity_ClearFlags(int entity) { Entity_SetFlags(entity, 0); } @@ -811,9 +793,9 @@ enum SolidFlags_t * @param entity Entity index. * @return Solid Flags. */ -stock SolidFlags_t:Entity_GetSolidFlags(entity) +stock SolidFlags_t Entity_GetSolidFlags(int entity) { - return SolidFlags_t:GetEntProp(entity, Prop_Data, "m_usSolidFlags", 2); + return view_as(GetEntProp(entity, Prop_Data, "m_usSolidFlags", 2)); } /** @@ -821,12 +803,11 @@ stock SolidFlags_t:Entity_GetSolidFlags(entity) * * @param entity Entity index. * @param flags Solid Flags. - * @noreturn */ -stock Entity_SetSolidFlags(entity, SolidFlags_t:flags) +stock void Entity_SetSolidFlags(int entity, SolidFlags_t flags) { - new SolidFlags_t:oldFlags = Entity_GetSolidFlags(entity); - flags = flags & SolidFlags_t:0xFFFF; + SolidFlags_t oldFlags = Entity_GetSolidFlags(entity); + flags = flags & view_as(0xFFFF); if (oldFlags == flags) { return; @@ -847,11 +828,10 @@ stock Entity_SetSolidFlags(entity, SolidFlags_t:flags) * * @param entity Entity index. * @param flags Solid Flags. - * @noreturn */ -stock Entity_AddSolidFlags(entity, SolidFlags_t:flags) +stock void Entity_AddSolidFlags(int entity, SolidFlags_t flags) { - new SolidFlags_t:newFlags = Entity_GetSolidFlags(entity); + SolidFlags_t newFlags = Entity_GetSolidFlags(entity); newFlags |= flags; Entity_SetSolidFlags(entity, newFlags); } @@ -861,11 +841,10 @@ stock Entity_AddSolidFlags(entity, SolidFlags_t:flags) * * @param entity Entity index. * @param flags Solid Flags. - * @noreturn */ -stock Entity_RemoveSolidFlags(entity, SolidFlags_t:flags) +stock void Entity_RemoveSolidFlags(int entity, SolidFlags_t flags) { - new SolidFlags_t:newFlags = Entity_GetSolidFlags(entity); + SolidFlags_t newFlags = Entity_GetSolidFlags(entity); newFlags &= ~flags; Entity_SetSolidFlags(entity, newFlags); } @@ -874,11 +853,10 @@ stock Entity_RemoveSolidFlags(entity, SolidFlags_t:flags) * Removes all solid flags from the entity. * * @param entity Entity index. - * @noreturn */ -stock Entity_ClearSolidFlags(entity) +stock void Entity_ClearSolidFlags(int entity) { - Entity_SetSolidFlags(entity, SolidFlags_t:0); + Entity_SetSolidFlags(entity, view_as(0)); } /** @@ -888,9 +866,9 @@ stock Entity_ClearSolidFlags(entity) * @param flags Solid Flags. * @return True if the specified flags are set, false otherwise. */ -stock bool:Entity_SolidFlagsSet(entity, SolidFlags_t:flagMask) +stock bool Entity_SolidFlagsSet(int entity, SolidFlags_t flagMask) { - return bool:(Entity_GetSolidFlags(entity) & flagMask); + return Entity_GetSolidFlags(entity) & flagMask == flagMask; } enum SolidType_t @@ -911,9 +889,9 @@ enum SolidType_t * @param entity Entity index. * @return Solid Type */ -stock SolidType_t:Entity_GetSolidType(entity) +stock SolidType_t Entity_GetSolidType(int entity) { - return SolidType_t:GetEntProp(entity, Prop_Data, "m_nSolidType", 1); + return view_as(GetEntProp(entity, Prop_Data, "m_nSolidType", 1)); } /** @@ -921,9 +899,8 @@ stock SolidType_t:Entity_GetSolidType(entity) * * @param entity Entity index. * @param Solid Type value. - * @noreturn */ -stock Entity_SetSolidType(entity, SolidType_t:value) +stock void Entity_SetSolidType(int entity, SolidType_t value) { SetEntProp(entity, Prop_Send, "m_nSolidType", value, 1); Entity_MarkSurrBoundsDirty(entity); @@ -935,7 +912,7 @@ stock Entity_SetSolidType(entity, SolidType_t:value) * @param entity Entity index. * @return True if the entity is solid, false otherwise. */ -stock bool:Entity_IsSolid(entity) +stock bool Entity_IsSolid(int entity) { return (Entity_GetSolidType(entity) != SOLID_NONE && !Entity_SolidFlagsSet(entity, FSOLID_NOT_SOLID)); @@ -950,7 +927,7 @@ stock bool:Entity_IsSolid(entity) * @param size max size of buffer string * @return Number of non-null bytes written. */ -stock Entity_GetModel(entity, String:buffer[], size) +stock int Entity_GetModel(int entity, char[] buffer, int size) { return GetEntPropString(entity, Prop_Data, "m_ModelName", buffer, size); } @@ -962,9 +939,8 @@ stock Entity_GetModel(entity, String:buffer[], size) * * @param entity Entity index * @param model Model name - * @noreturn */ -stock Entity_SetModel(entity, const String:model[]) +stock void Entity_SetModel(int entity, const char[] model) { SetEntityModel(entity, model); } @@ -975,7 +951,7 @@ stock Entity_SetModel(entity, const String:model[]) * @param entity Entity index. * @return The Entity's model index */ -stock Entity_GetModelIndex(entity) +stock int Entity_GetModelIndex(int entity) { return GetEntProp(entity, Prop_Data, "m_nModelIndex", 2); } @@ -985,9 +961,8 @@ stock Entity_GetModelIndex(entity) * * @param entity Entity index. * @param index Model Index. - * @noreturn */ -stock Entity_SetModelIndex(entity, index) +stock void Entity_SetModelIndex(int entity, int index) { SetEntProp(entity, Prop_Data, "m_nModelIndex", index, 2); } @@ -999,7 +974,7 @@ stock Entity_SetModelIndex(entity, index) * @param maxspeed the maximum speed the entity can move * @noreturn */ -stock Entity_SetMaxSpeed(entity, Float:value) +stock void Entity_SetMaxSpeed(int entity, float value) { SetEntPropFloat(entity, Prop_Data, "m_flMaxspeed", value); } @@ -1040,9 +1015,9 @@ enum Collision_Group_t * @param entity entity index * @return Entity collision group. */ -stock Collision_Group_t:Entity_GetCollisionGroup(entity) +stock Collision_Group_t Entity_GetCollisionGroup(int entity) { - return Collision_Group_t:GetEntProp(entity, Prop_Data, "m_CollisionGroup"); + return view_as(GetEntProp(entity, Prop_Data, "m_CollisionGroup")); } /** @@ -1050,9 +1025,8 @@ stock Collision_Group_t:Entity_GetCollisionGroup(entity) * * @param entity entity index * @param value the new collision group. - * @noreturn */ -stock Entity_SetCollisionGroup(entity, Collision_Group_t:value) +stock void Entity_SetCollisionGroup(int entity, Collision_Group_t value) { SetEntProp(entity, Prop_Data, "m_CollisionGroup", value); } @@ -1068,9 +1042,8 @@ stock Entity_SetCollisionGroup(entity, Collision_Group_t:value) * * @param entity Entity index. * @param vec 3 dimensional vector array. - * @noreturn */ -stock Entity_GetAbsOrigin(entity, Float:vec[3]) +stock void Entity_GetAbsOrigin(int entity, float vec[3]) { GetEntPropVector(entity, Prop_Send, "m_vecOrigin", vec); } @@ -1080,9 +1053,8 @@ stock Entity_GetAbsOrigin(entity, Float:vec[3]) * * @param entity Entity index. * @param vec 3 dimensional vector array. - * @noreturn */ -stock Entity_SetAbsOrigin(entity, const Float:vec[3]) +stock void Entity_SetAbsOrigin(int entity, const float vec[3]) { // We use TeleportEntity to set the origin more safely // Todo: Replace this with a call to UTIL_SetOrigin() or CBaseEntity::SetLocalOrigin() @@ -1102,7 +1074,7 @@ stock Entity_SetAbsOrigin(entity, const Float:vec[3]) * @param vec 3 dimensional vector array. * @noreturn */ -stock Entity_GetAbsAngles(entity, Float:vec[3]) +stock void Entity_GetAbsAngles(int entity, float vec[3]) { GetEntPropVector(entity, Prop_Data, "m_angAbsRotation", vec); } @@ -1112,9 +1084,8 @@ stock Entity_GetAbsAngles(entity, Float:vec[3]) * * @param entity Entity index. * @param vec 3 dimensional vector array. - * @noreturn */ -stock Entity_SetAbsAngles(entity, const Float:vec[3]) +stock void Entity_SetAbsAngles(int entity, const float vec[3]) { // We use TeleportEntity to set the angles more safely // Todo: Replace this with a call to CBaseEntity::SetLocalAngles() @@ -1133,9 +1104,8 @@ stock Entity_SetAbsAngles(entity, const Float:vec[3]) * * @param entity Entity index. * @param vel An 3 dim array - * @noreturn */ -stock Entity_GetLocalVelocity(entity, Float:vec[3]) +stock void Entity_GetLocalVelocity(int entity, float vec[3]) { GetEntPropVector(entity, Prop_Data, "m_vecVelocity", vec); } @@ -1148,9 +1118,8 @@ stock Entity_GetLocalVelocity(entity, Float:vec[3]) * * @param entity Entity index. * @param vel An 3 dim array - * @noreturn */ -stock Entity_SetLocalVelocity(entity, const Float:vec[3]) +stock void Entity_SetLocalVelocity(int entity, const float vec[3]) { SetEntPropVector(entity, Prop_Data, "m_vecVelocity", vec); } @@ -1162,9 +1131,8 @@ stock Entity_SetLocalVelocity(entity, const Float:vec[3]) * * @param entity Entity index. * @param vel An 3 dim array - * @noreturn */ -stock Entity_GetBaseVelocity(entity, Float:vec[3]) +stock void Entity_GetBaseVelocity(int entity, float vec[3]) { GetEntPropVector(entity, Prop_Data, "m_vecBaseVelocity", vec); } @@ -1176,9 +1144,8 @@ stock Entity_GetBaseVelocity(entity, Float:vec[3]) * * @param entity Entity index. * @param vel An 3 dim array - * @noreturn */ -stock Entity_SetBaseVelocity(entity, const Float:vec[3]) +stock void Entity_SetBaseVelocity(int entity, const float vec[3]) { SetEntPropVector(entity, Prop_Data, "m_vecBaseVelocity", vec); } @@ -1190,9 +1157,8 @@ stock Entity_SetBaseVelocity(entity, const Float:vec[3]) * * @param entity Entity index. * @param vel An 3 dim array - * @noreturn */ -stock Entity_GetAbsVelocity(entity, Float:vec[3]) +stock void Entity_GetAbsVelocity(int entity, float vec[3]) { GetEntPropVector(entity, Prop_Data, "m_vecAbsVelocity", vec); } @@ -1204,9 +1170,8 @@ stock Entity_GetAbsVelocity(entity, Float:vec[3]) * * @param entity Entity index. * @param vel An 3 dim array - * @noreturn */ -stock Entity_SetAbsVelocity(entity, const Float:vec[3]) +stock void Entity_SetAbsVelocity(int entity, const float vec[3]) { // We use TeleportEntity to set the velocity more safely // Todo: Replace this with a call to CBaseEntity::SetAbsVelocity() @@ -1219,18 +1184,17 @@ stock Entity_SetAbsVelocity(entity, const Float:vec[3]) * @param entity Entity index. * @return True if locked otherwise false. */ -stock bool:Entity_IsLocked(entity) +stock bool Entity_IsLocked(int entity) { - return bool:GetEntProp(entity, Prop_Data, "m_bLocked", 1); + return GetEntProp(entity, Prop_Data, "m_bLocked", 1) != 0; } /** * Locks an entity. * * @param entity Entity index. - * @noreturn */ -stock Entity_Lock(entity) +stock void Entity_Lock(int entity) { SetEntProp(entity, Prop_Data, "m_bLocked", 1, 1); } @@ -1238,9 +1202,8 @@ stock Entity_Lock(entity) * Unlocks an entity. * * @param entity Entity index. - * @noreturn */ -stock Entity_UnLock(entity) +stock void Entity_UnLock(int entity) { SetEntProp(entity, Prop_Data, "m_bLocked", 0, 1); } @@ -1251,7 +1214,7 @@ stock Entity_UnLock(entity) * @param entity entity index. * @return current health points */ -stock Entity_GetHealth(entity) +stock int Entity_GetHealth(int entity) { return GetEntProp(entity, Prop_Data, "m_iHealth"); } @@ -1259,16 +1222,18 @@ stock Entity_GetHealth(entity) /** * Sets the health of an entity. * - * @param entity entity index. - * @param value health to set (anything above 511 will overload) - * @noreturn + * @param entity Entity index. + * @param value Health to set (anything above 511 will overload) + * @param ignoreMax Ignore the entity's maxhealth setting. + * @param kill Kill the entity if health gets to 0. + * @return The health the entity actually got set to. */ -stock Entity_SetHealth(entity, value, ignoreMax=false, kill=true) +stock int Entity_SetHealth(int entity, int value, bool ignoreMax=false, bool kill=true) { - new health = value; + int health = value; if (!ignoreMax) { - new maxHealth = Entity_GetMaxHealth(entity); + int maxHealth = Entity_GetMaxHealth(entity); if (health > maxHealth) { health = maxHealth; @@ -1291,13 +1256,15 @@ stock Entity_SetHealth(entity, value, ignoreMax=false, kill=true) /** * Add health to an entity * - * @param entity entity index - * @param value health to add - * @return returns the new health value set + * @param entity Entity index + * @param value Health to add + * @param ignoreMax Ignore the entity's maxhealth setting. + * @param kill Kill the entity if health gets to 0. + * @return Returns the new health value set */ -stock Entity_AddHealth(entity, value, ignoreMax=false, kill=true) +stock int Entity_AddHealth(int entity, int value, bool ignoreMax=false, bool kill=true) { - new health = Entity_GetHealth(entity); + int health = Entity_GetHealth(entity); health += value; @@ -1311,9 +1278,9 @@ stock Entity_AddHealth(entity, value, ignoreMax=false, kill=true) * @param value health to add * @return returns the new health value set */ -stock Entity_TakeHealth(entity, value, ignoreMax=false, kill=true) +stock int Entity_TakeHealth(int entity, int value, bool ignoreMax=false, bool kill=true) { - new health = Entity_GetHealth(entity); + int health = Entity_GetHealth(entity); health -= value; @@ -1326,7 +1293,7 @@ stock Entity_TakeHealth(entity, value, ignoreMax=false, kill=true) * @param entity Entity Index * @return Max health points */ -stock Entity_GetMaxHealth(entity) +stock int Entity_GetMaxHealth(int entity) { return GetEntProp(entity, Prop_Data, "m_iMaxHealth"); } @@ -1337,12 +1304,10 @@ stock Entity_GetMaxHealth(entity) * * @param entity Entity index * @param value Max health to set (anything above 511 will overload) - * @noreturn */ -stock Entity_SetMaxHealth(entity, value) +stock void Entity_SetMaxHealth(int entity, int value) { SetEntProp(entity, Prop_Data, "m_iMaxHealth", value); - return value; } /** @@ -1353,9 +1318,9 @@ stock Entity_SetMaxHealth(entity, value) * @param target Vector Origin. * @return Distance Float value. */ -stock Float:Entity_GetDistanceOrigin(entity, const Float:vec[3]) +stock float Entity_GetDistanceOrigin(int entity, const float vec[3]) { - new Float:entityVec[3]; + float entityVec[3]; Entity_GetAbsOrigin(entity, entityVec); return GetVectorDistance(entityVec, vec); @@ -1369,9 +1334,9 @@ stock Float:Entity_GetDistanceOrigin(entity, const Float:vec[3]) * @param target Target Entity Index. * @return Distance Float value. */ -stock Float:Entity_GetDistance(entity, target) +stock float Entity_GetDistance(int entity, int target) { - new Float:targetVec[3]; + float targetVec[3]; Entity_GetAbsOrigin(target, targetVec); return Entity_GetDistanceOrigin(entity, targetVec); @@ -1385,7 +1350,7 @@ stock Float:Entity_GetDistance(entity, target) * @param distance Max Float distance. * @return True if the given entities are closer than the given distance value, false otherwise. */ -stock bool:Entity_InRange(entity, target, Float:distance) +stock bool Entity_InRange(int entity, int target, float distance) { if (Entity_GetDistance(entity, target) > distance) { return false; @@ -1400,7 +1365,7 @@ stock bool:Entity_InRange(entity, target, Float:distance) * @param entity Entity index. * @return True on success, false otherwise */ -stock bool:Entity_EnableMotion(entity) +stock bool Entity_EnableMotion(int entity) { return AcceptEntityInput(entity, "enablemotion"); } @@ -1411,7 +1376,7 @@ stock bool:Entity_EnableMotion(entity) * @param entity Entity index. * @return True on success, false otherwise */ -stock bool:Entity_DisableMotion(entity) +stock bool Entity_DisableMotion(int entity) { return AcceptEntityInput(entity, "disablemotion"); } @@ -1420,9 +1385,8 @@ stock bool:Entity_DisableMotion(entity) * Freezes an entity by setting the FL_FROZEN flag. * * @param entity Entity index. - * @return True on success, false otherwise */ -stock Entity_Freeze(entity) +stock void Entity_Freeze(int entity) { Entity_AddFlags(entity, FL_FROZEN); } @@ -1431,9 +1395,8 @@ stock Entity_Freeze(entity) * Unfreezes an entity by removing the FL_FROZEN flag. * * @param entity Entity index. - * @return True on success, false otherwise */ -stock Entity_UnFreeze(entity) +stock void Entity_UnFreeze(int entity) { Entity_RemoveFlags(entity, FL_FROZEN); } @@ -1447,11 +1410,10 @@ stock Entity_UnFreeze(entity) * @param entity Entity index. * @param target Target entity index. * @param Optional: target name - * @noreturn */ -stock Entity_PointAtTarget(entity, target, const String:name[]="") +stock void Entity_PointAtTarget(int entity, int target, const char[] name="") { - decl String:targetName[128]; + char targetName[128]; Entity_GetTargetName(entity, targetName, sizeof(targetName)); if (name[0] == '\0') { @@ -1482,11 +1444,10 @@ stock Entity_PointAtTarget(entity, target, const String:name[]="") * @param entity Entity index. * @param target Target entity index. * @param Optional: target name - * @noreturn */ -stock Entity_PointHurtAtTarget(entity, target, const String:name[]="") +stock void Entity_PointHurtAtTarget(int entity, int target, const char[] name="") { - decl String:targetName[128]; + char targetName[128]; Entity_GetTargetName(entity, targetName, sizeof(targetName)); if (name[0] == '\0') { @@ -1517,7 +1478,7 @@ stock Entity_PointHurtAtTarget(entity, target, const String:name[]="") * @param entity Entity index. * @return True if the entity is a player, false otherwise. */ -stock bool:Entity_IsPlayer(entity) +stock bool Entity_IsPlayer(int entity) { if (entity < 1 || entity > MaxClients) { return false; @@ -1533,7 +1494,7 @@ stock bool:Entity_IsPlayer(entity) * @param ForceEdictIndex Edict Index to use. * @return Entity Index or INVALID_ENT_REFERENCE if the slot is already in use. */ -stock Entity_Create(const String:className[], ForceEdictIndex=-1) +stock int Entity_Create(const char[] className, int ForceEdictIndex=-1) { if (ForceEdictIndex != -1 && Entity_IsValid(ForceEdictIndex)) { return INVALID_ENT_REFERENCE; @@ -1551,7 +1512,7 @@ stock Entity_Create(const String:className[], ForceEdictIndex=-1) * @param killChildren When true, kennys children are killed too. * @return True on success, false otherwise. */ -stock bool:Entity_Kill(kenny, killChildren=false) +stock bool Entity_Kill(int kenny, bool killChildren=false) { if (Entity_IsPlayer(kenny)) { // Oh My God! They Killed Kenny!! @@ -1575,11 +1536,11 @@ stock bool:Entity_Kill(kenny, killChildren=false) * @param className Entity Network Class to search for. * @return Number of entities killed. */ -stock Entity_KillAllByClassName(const String:className[]) +stock int Entity_KillAllByClassName(const char[] className) { - new x = 0; + int x = 0; - new entity = INVALID_ENT_REFERENCE; + int entity = INVALID_ENT_REFERENCE; while ((entity = FindEntityByClassname(entity, className)) != INVALID_ENT_REFERENCE) { AcceptEntityInput(entity, "kill"); x++; @@ -1595,7 +1556,7 @@ stock Entity_KillAllByClassName(const String:className[]) * @param entity Entity index. * @return Ground Entity or -1 */ -stock Entity_GetOwner(entity) +stock int Entity_GetOwner(int entity) { return GetEntPropEnt(entity, Prop_Data, "m_hOwnerEntity"); } @@ -1605,9 +1566,8 @@ stock Entity_GetOwner(entity) * For example the owner of a weapon entity. * * @param entity Entity index. - * @noreturn */ -stock Entity_SetOwner(entity, newOwner) +stock void Entity_SetOwner(int entity, int newOwner) { SetEntPropEnt(entity, Prop_Send, "m_hOwnerEntity", newOwner); } @@ -1618,7 +1578,7 @@ stock Entity_SetOwner(entity, newOwner) * @param entity Entity index. * @return Ground Entity or -1 */ -stock Entity_GetGroundEntity(entity) +stock int Entity_GetGroundEntity(int entity) { return GetEntPropEnt(entity, Prop_Data, "m_hGroundEntity"); } @@ -1690,9 +1650,9 @@ stock Entity_GetGroundEntity(entity) * want a specific weapon to be shown in the HUD kill message. * @return True on success, false otherwise. */ -stock bool:Entity_Hurt(entity, damage, attacker=0, damageType=DMG_GENERIC, const String:fakeClassName[]="") +stock bool Entity_Hurt(int entity, int damage, int attacker=0, int damageType=DMG_GENERIC, const char[] fakeClassName="") { - static point_hurt = INVALID_ENT_REFERENCE; + static int point_hurt = INVALID_ENT_REFERENCE; if (point_hurt == INVALID_ENT_REFERENCE || !IsValidEntity(point_hurt)) { point_hurt = EntIndexToEntRef(Entity_Create("point_hurt")); @@ -1729,7 +1689,7 @@ stock bool:Entity_Hurt(entity, damage, attacker=0, damageType=DMG_GENERIC, const * @param entity Entity Index. * @return Entity Index of the parent. */ -stock Entity_GetParent(entity) +stock int Entity_GetParent(int entity) { return GetEntPropEnt(entity, Prop_Data, "m_pParent"); } @@ -1738,11 +1698,10 @@ stock Entity_GetParent(entity) * Clears the parent of an entity. * * @param entity Entity Index. - * @noreturn */ -stock Entity_ClearParent(entity) +stock void Entity_ClearParent(int entity) { - SetVariantString(""); + //SetVariantString(""); AcceptEntityInput(entity, "ClearParent"); } @@ -1750,12 +1709,11 @@ stock Entity_ClearParent(entity) * Sets the parent entity of an entity. * * @param entity Entity Index. - * @param parentEntity Entity Index of the new parent. - * @noreturn + * @param parent Entity Index of the new parent. */ -stock Entity_SetParent(entity, parent) +stock void Entity_SetParent(int entity, int parent) { - SetVariantString("!activator"); + //SetVariantString("!activator"); AcceptEntityInput(entity, "SetParent", parent); } @@ -1770,7 +1728,7 @@ stock Entity_SetParent(entity, parent) * @param currentCall The current call number (0 is the 1st call at 0.0 seconds, 1 the 2nd call at tick*1 seconds, ...). * @return When true this callback will be called again at the next defined tick, otherwise it won't. */ -functag Entity_ChangeOverTimeCallback bool:public(&entity, &Float:interval, ¤tCall); +typedef Entity_ChangeOverTimeCallback = function bool (int &entity, float &interval, int ¤tCall); /* * Creates a timer and provides a callback to change various things about an entity over time. @@ -1779,37 +1737,29 @@ functag Entity_ChangeOverTimeCallback bool:public(&entity, &Float:interval, &cur * @param interval Interval from the current game time to execute the given function. * @noreturn */ -stock Entity_ChangeOverTime(entity, Float:interval=0.1, Entity_ChangeOverTimeCallback:valueCallback) +stock void Entity_ChangeOverTime(int entity, float interval=0.1, Entity_ChangeOverTimeCallback valueCallback) { - new Handle:dataPack = CreateDataPack(); + DataPack dataPack = CreateDataPack(); WritePackCell(dataPack, EntIndexToEntRef(entity)); WritePackFloat(dataPack, interval); WritePackCell(dataPack, 0); -#if SOURCEMOD_V_MAJOR >= 1 && SOURCEMOD_V_MINOR >= 7 WritePackFunction(dataPack, valueCallback); -#else - WritePackCell(dataPack, _:valueCallback); -#endif ResetPack(dataPack); __smlib_Timer_ChangeOverTime(INVALID_HANDLE,dataPack); } -public Action:__smlib_Timer_ChangeOverTime(Handle:Timer, Handle:dataPack) +public Action __smlib_Timer_ChangeOverTime(Handle Timer, DataPack dataPack) { - new entity = EntRefToEntIndex(ReadPackCell(dataPack)); + int entity = EntRefToEntIndex(ReadPackCell(dataPack)); if(!Entity_IsValid(entity)){ return Plugin_Stop; } - new Float:interval = ReadPackFloat(dataPack); - new currentCall = ReadPackCell(dataPack); -#if SOURCEMOD_V_MAJOR >= 1 && SOURCEMOD_V_MINOR >= 7 - new Function:callback = ReadPackFunction(dataPack); -#else - new Function:callback = Function:ReadPackCell(dataPack); -#endif + float interval = ReadPackFloat(dataPack); + int currentCall = ReadPackCell(dataPack); + Function callback = ReadPackFunction(dataPack); - new any:result; + any result; Call_StartFunction(INVALID_HANDLE, callback); Call_PushCellRef(entity); Call_PushFloatRef(interval); @@ -1824,13 +1774,9 @@ public Action:__smlib_Timer_ChangeOverTime(Handle:Timer, Handle:dataPack) WritePackCell(dataPack, EntIndexToEntRef(entity)); WritePackFloat(dataPack, interval); WritePackCell(dataPack, currentCall+1); -#if SOURCEMOD_V_MAJOR >= 1 && SOURCEMOD_V_MINOR >= 7 WritePackFunction(dataPack, callback); -#else - WritePackCell(dataPack, _:callback); -#endif ResetPack(dataPack); - CreateTimer(interval,__smlib_Timer_ChangeOverTime,dataPack); + CreateTimer(interval, __smlib_Timer_ChangeOverTime, dataPack); return Plugin_Stop; } @@ -1838,13 +1784,14 @@ public Action:__smlib_Timer_ChangeOverTime(Handle:Timer, Handle:dataPack) /** * Gets the next child, entity is parent of. * - * @param client Entity Index (of Parent) + * @param parent Entity Index (of Parent) * @param start Start Index. * @return Entity Index or -1 if no entity was found. */ -stock Entity_GetNextChild(parent, start=0) +stock int Entity_GetNextChild(int parent, int start=0) { - for (new entity=start; entity <= 2048; entity++) { + int maxEntities = GetMaxEntities(); + for (int entity=start; entity < maxEntities; entity++) { if (!Entity_IsValid(entity)) { continue; @@ -1867,9 +1814,8 @@ stock Entity_GetNextChild(parent, start=0) * * @param entity Entity index. * @param vec Vector. - * @noreturn */ -stock Entity_GetMoveDirection(entity, Float:vec[3]) +stock void Entity_GetMoveDirection(int entity, float vec[3]) { GetEntPropVector(entity, Prop_Data, "m_vecMoveDir", vec); } @@ -1879,9 +1825,8 @@ stock Entity_GetMoveDirection(entity, Float:vec[3]) * * @param entity Entity index. * @param vec Vector. - * @noreturn */ -stock Entity_SetMoveDirection(entity, const Float:vec[3]) +stock void Entity_SetMoveDirection(int entity, const float vec[3]) { SetEntPropVector(entity, Prop_Data, "m_vecMoveDir", vec); } @@ -1892,9 +1837,9 @@ stock Entity_SetMoveDirection(entity, const Float:vec[3]) * @param entity Entity index. * @return True if the door will force close, otherwise false. */ -stock bool:Entity_GetForceClose(entity) +stock bool Entity_GetForceClose(int entity) { - return bool:GetEntProp(entity, Prop_Data, "m_bForceClosed"); + return GetEntProp(entity, Prop_Data, "m_bForceClosed") != 0; } /** @@ -1902,9 +1847,8 @@ stock bool:Entity_GetForceClose(entity) * * @param entity Entity index. * @param forceClose If true the door will force close, otherwise it won't. - * @noreturn */ -stock Entity_SetForceClose(entity, bool:forceClose) +stock void Entity_SetForceClose(int entity, bool forceClose) { SetEntProp(entity, Prop_Data, "m_bForceClosed", forceClose); } @@ -1915,7 +1859,7 @@ stock Entity_SetForceClose(entity, bool:forceClose) * @param entity Entity index. * @return Speed of the entity. */ -stock Float:Entity_GetSpeed(entity) +stock float Entity_GetSpeed(int entity) { return GetEntPropFloat(entity, Prop_Data, "m_flSpeed"); } @@ -1925,9 +1869,8 @@ stock Float:Entity_GetSpeed(entity) * * @param entity Entity index. * @param speed The new speed of the entity. - * @noreturn */ -stock Entity_SetSpeed(entity, Float:speed) +stock void Entity_SetSpeed(int entity, float speed) { SetEntPropFloat(entity, Prop_Data, "m_flSpeed", speed); } @@ -1939,7 +1882,7 @@ stock Entity_SetSpeed(entity, Float:speed) * @param entity Entity index. * @return Damage. */ -stock Float:Entity_GetBlockDamage(entity) +stock float Entity_GetBlockDamage(int entity) { return GetEntPropFloat(entity, Prop_Data, "m_flBlockDamage"); } @@ -1950,9 +1893,8 @@ stock Float:Entity_GetBlockDamage(entity) * * @param entity Entity index. * @param damage Damage. - * @noreturn */ -stock Entity_SetBlockDamage(entity, Float:damage) +stock void Entity_SetBlockDamage(int entity, float damage) { SetEntPropFloat(entity, Prop_Data, "m_flBlockDamage", damage); } @@ -1963,9 +1905,9 @@ stock Entity_SetBlockDamage(entity, Float:damage) * @param entity Entity index. * @return True if entity is disabled, otherwise false. */ -stock bool:Entity_IsDisabled(entity) +stock bool Entity_IsDisabled(int entity) { - return bool:GetEntProp(entity, Prop_Data, "m_bDisabled", 1); + return GetEntProp(entity, Prop_Data, "m_bDisabled", 1) != 0; } /** @@ -1974,7 +1916,7 @@ stock bool:Entity_IsDisabled(entity) * @param entity Entity index. * @return True if successful otherwise false. */ -stock Entity_Disable(entity) +stock bool Entity_Disable(int entity) { return AcceptEntityInput(entity, "Disable"); } @@ -1985,7 +1927,7 @@ stock Entity_Disable(entity) * @param entity Entity index. * @return True if successful otherwise false. */ -stock Entity_Enable(entity) +stock bool Entity_Enable(int entity) { return AcceptEntityInput(entity, "Enable"); } @@ -2003,9 +1945,8 @@ stock Entity_Enable(entity) * * @param entity Entity index. * @param value Mode, use DAMAGE_* defines. - * @noreturn */ -stock Entity_SetTakeDamage(entity, value) +stock void Entity_SetTakeDamage(int entity, int value) { SetEntProp(entity, Prop_Data, "m_takedamage", value, 1); } @@ -2017,7 +1958,7 @@ stock Entity_SetTakeDamage(entity, value) * @param entity Entity index. * @return Take damage mode (DAMAGE_*). */ -stock Entity_GetTakeDamage(entity) +stock int Entity_GetTakeDamage(int entity) { return GetEntProp(entity, Prop_Data, "m_takedamage", 1); } @@ -2028,9 +1969,8 @@ stock Entity_GetTakeDamage(entity) * * @param entity Entity index. * @param minDamage Minimum required damage. - * @noreturn */ -stock Entity_SetMinHealthDamage(entity, minDamage) +stock void Entity_SetMinHealthDamage(int entity, int minDamage) { SetEntProp(entity, Prop_Data, "m_iMinHealthDmg", minDamage); } @@ -2042,7 +1982,7 @@ stock Entity_SetMinHealthDamage(entity, minDamage) * @param entity Entity index. * @return Minimum required damage. */ -stock Entity_GetMinHealthDamage(entity) +stock int Entity_GetMinHealthDamage(int entity) { return GetEntProp(entity, Prop_Data, "m_iMinHealthDmg"); } @@ -2052,18 +1992,17 @@ stock Entity_GetMinHealthDamage(entity) * * @param entity Entity index * @param color 4 dimensional array where [r,g,b,a] values are stored - * @noreturn * @error Invalid entity index, or lack of mod compliance. */ -stock Entity_GetRenderColor(entity, color[4]) +stock void Entity_GetRenderColor(int entity, int color[4]) { - static bool:gotconfig = false; - static String:prop[32]; + static bool gotconfig = false; + static char prop[32]; if (!gotconfig) { - new Handle:gc = LoadGameConfigFile("core.games"); - new bool:exists = GameConfGetKeyValue(gc, "m_clrRender", prop, sizeof(prop)); - CloseHandle(gc); + Handle gc = LoadGameConfigFile("core.games"); + bool exists = GameConfGetKeyValue(gc, "m_clrRender", prop, sizeof(prop)); + delete gc; if (!exists) { strcopy(prop, sizeof(prop), "m_clrRender"); @@ -2072,13 +2011,13 @@ stock Entity_GetRenderColor(entity, color[4]) gotconfig = true; } - new offset = GetEntSendPropOffs(entity, prop); + int offset = GetEntSendPropOffs(entity, prop); if (offset <= 0) { ThrowError("SetEntityRenderColor not supported by this mod"); } - for (new i=0; i < 4; i++) { + for (int i=0; i < 4; i++) { color[i] = GetEntData(entity, offset + i + 1, 1); } } @@ -2092,18 +2031,17 @@ stock Entity_GetRenderColor(entity, color[4]) * @param g Amount of green (0-255) * @param b Amount of blue (0-255) * @param a Amount of alpha (0-255) - * @noreturn * @error Invalid entity index, or lack of mod compliance. */ -stock Entity_SetRenderColor(entity, r=-1, g=-1, b=-1, a=-1) +stock void Entity_SetRenderColor(int entity, int r=-1, int g=-1, int b=-1, int a=-1) { - static bool:gotconfig = false; - static String:prop[32]; + static bool gotconfig = false; + static char prop[32]; if (!gotconfig) { - new Handle:gc = LoadGameConfigFile("core.games"); - new bool:exists = GameConfGetKeyValue(gc, "m_clrRender", prop, sizeof(prop)); - CloseHandle(gc); + Handle gc = LoadGameConfigFile("core.games"); + bool exists = GameConfGetKeyValue(gc, "m_clrRender", prop, sizeof(prop)); + delete gc; if (!exists) { strcopy(prop, sizeof(prop), "m_clrRender"); @@ -2112,7 +2050,7 @@ stock Entity_SetRenderColor(entity, r=-1, g=-1, b=-1, a=-1) gotconfig = true; } - new offset = GetEntSendPropOffs(entity, prop); + int offset = GetEntSendPropOffs(entity, prop); if (offset <= 0) { ThrowError("SetEntityRenderColor not supported by this mod"); @@ -2145,8 +2083,8 @@ stock Entity_SetRenderColor(entity, r=-1, g=-1, b=-1, a=-1) * @param outputid Unknown. * @return True if successful, otherwise false. */ -stock bool:Entity_AddOutput(entity, const String:input[], activator=-1, caller=-1, outputid=0) +stock bool Entity_AddOutput(int entity, const char[] input, int activator=-1, int caller=-1, int outputid=0) { - SetVariantString(input); + //SetVariantString(input); return AcceptEntityInput(entity, "addoutput", activator, caller, outputid); } diff --git a/addons/sourcemod/scripting/include/smlib/files.inc b/addons/sourcemod/scripting/include/smlib/files.inc index 2f56ca0..a31d606 100644 --- a/addons/sourcemod/scripting/include/smlib/files.inc +++ b/addons/sourcemod/scripting/include/smlib/files.inc @@ -16,16 +16,15 @@ * @param path File path * @param buffer String buffer array * @param size Size of string buffer - * @noreturn */ -stock bool:File_GetBaseName(const String:path[], String:buffer[], size) +stock void File_GetBaseName(const char[] path, char[] buffer, int size) { if (path[0] == '\0') { buffer[0] = '\0'; return; } - new pos_start = FindCharInString(path, '/', true); + int pos_start = FindCharInString(path, '/', true); if (pos_start == -1) { pos_start = FindCharInString(path, '\\', true); @@ -46,16 +45,15 @@ stock bool:File_GetBaseName(const String:path[], String:buffer[], size) * @param path File path * @param buffer String buffer array * @param size Size of string buffer - * @noreturn */ -stock bool:File_GetDirName(const String:path[], String:buffer[], size) +stock void File_GetDirName(const char[] path, char[] buffer, int size) { if (path[0] == '\0') { buffer[0] = '\0'; return; } - new pos_start = FindCharInString(path, '/', true); + int pos_start = FindCharInString(path, '/', true); if (pos_start == -1) { pos_start = FindCharInString(path, '\\', true); @@ -78,9 +76,8 @@ stock bool:File_GetDirName(const String:path[], String:buffer[], size) * @param path File path * @param buffer String buffer array * @param size Size of string buffer - * @noreturn */ -stock bool:File_GetFileName(const String:path[], String:buffer[], size) +stock void File_GetFileName(const char[] path, char[] buffer, int size) { if (path[0] == '\0') { buffer[0] = '\0'; @@ -89,7 +86,7 @@ stock bool:File_GetFileName(const String:path[], String:buffer[], size) File_GetBaseName(path, buffer, size); - new pos_ext = FindCharInString(buffer, '.', true); + int pos_ext = FindCharInString(buffer, '.', true); if (pos_ext != -1) { buffer[pos_ext] = '\0'; @@ -105,11 +102,10 @@ stock bool:File_GetFileName(const String:path[], String:buffer[], size) * @param path Path String * @param buffer String buffer array * @param size Max length of string buffer - * @noreturn */ -stock File_GetExtension(const String:path[], String:buffer[], size) +stock void File_GetExtension(const char[] path, char[] buffer, int size) { - new extpos = FindCharInString(path, '.', true); + int extpos = FindCharInString(path, '.', true); if (extpos == -1) { buffer[0] = '\0'; @@ -132,12 +128,11 @@ stock File_GetExtension(const String:path[], String:buffer[], size) * @param recursive Whether to do recursion or not. * @param ignoreExts Optional: 2 dimensional String array.You can define it like this: new String:ignore[][] = { ".ext1", ".ext2" }; * @param size This should be set to the number of file extensions in the ignoreExts array (sizeof(ignore) for the example above) - * @noreturn */ // Damn you SourcePawn :( I didn't want to -new String:_smlib_empty_twodimstring_array[][] = { { '\0' } }; -stock File_AddToDownloadsTable(const String:path[], bool:recursive=true, const String:ignoreExts[][]=_smlib_empty_twodimstring_array, size=0) +char _smlib_empty_twodimstring_array[][] = { { '\0' } }; +stock void File_AddToDownloadsTable(const char[] path, bool recursive=true, const char[][] ignoreExts=_smlib_empty_twodimstring_array, int size=0) { if (path[0] == '\0') { return; @@ -145,7 +140,7 @@ stock File_AddToDownloadsTable(const String:path[], bool:recursive=true, const S if (FileExists(path)) { - new String:fileExtension[5]; + char fileExtension[5]; File_GetExtension(path, fileExtension, sizeof(fileExtension)); if (StrEqual(fileExtension, "bz2", false) || StrEqual(fileExtension, "ztmp", false)) { @@ -156,7 +151,7 @@ stock File_AddToDownloadsTable(const String:path[], bool:recursive=true, const S return; } - decl String:path_new[PLATFORM_MAX_PATH]; + char path_new[PLATFORM_MAX_PATH]; strcopy(path_new, sizeof(path_new), path); ReplaceString(path_new, sizeof(path_new), "//", "/"); @@ -164,8 +159,8 @@ stock File_AddToDownloadsTable(const String:path[], bool:recursive=true, const S } else if (recursive && DirExists(path)) { - decl String:dirEntry[PLATFORM_MAX_PATH]; - new Handle:__dir = OpenDirectory(path); + char dirEntry[PLATFORM_MAX_PATH]; + DirectoryListing __dir = OpenDirectory(path); while (ReadDirEntry(__dir, dirEntry, sizeof(dirEntry))) { @@ -177,25 +172,24 @@ stock File_AddToDownloadsTable(const String:path[], bool:recursive=true, const S File_AddToDownloadsTable(dirEntry, recursive, ignoreExts, size); } - CloseHandle(__dir); + delete __dir; } else if (FindCharInString(path, '*', true)) { - new String:fileExtension[4]; + char fileExtension[4]; File_GetExtension(path, fileExtension, sizeof(fileExtension)); if (StrEqual(fileExtension, "*")) { - decl - String:dirName[PLATFORM_MAX_PATH], - String:fileName[PLATFORM_MAX_PATH], - String:dirEntry[PLATFORM_MAX_PATH]; + char dirName[PLATFORM_MAX_PATH], + fileName[PLATFORM_MAX_PATH], + dirEntry[PLATFORM_MAX_PATH]; File_GetDirName(path, dirName, sizeof(dirName)); File_GetFileName(path, fileName, sizeof(fileName)); StrCat(fileName, sizeof(fileName), "."); - new Handle:__dir = OpenDirectory(dirName); + DirectoryListing __dir = OpenDirectory(dirName); while (ReadDirEntry(__dir, dirEntry, sizeof(dirEntry))) { if (StrEqual(dirEntry, ".") || StrEqual(dirEntry, "..")) { @@ -208,11 +202,9 @@ stock File_AddToDownloadsTable(const String:path[], bool:recursive=true, const S } } - CloseHandle(__dir); + delete __dir; } } - - return; } @@ -222,21 +214,20 @@ stock File_AddToDownloadsTable(const String:path[], bool:recursive=true, const S * Comments are allowed ! Supported comment types are ; // # * * @param path Path to the .txt file. - * @noreturn */ -stock File_ReadDownloadList(const String:path[]) +stock void File_ReadDownloadList(const char[] path) { - new Handle:file = OpenFile(path, "r"); + File file = OpenFile(path, "r"); if (file == INVALID_HANDLE) { return; } - new String:buffer[PLATFORM_MAX_PATH]; + char buffer[PLATFORM_MAX_PATH]; while (!IsEndOfFile(file)) { ReadFileLine(file, buffer, sizeof(buffer)); - new pos; + int pos; pos = StrContains(buffer, "//"); if (pos != -1) { buffer[pos] = '\0'; @@ -261,7 +252,7 @@ stock File_ReadDownloadList(const String:path[]) File_AddToDownloadsTable(buffer); } - CloseHandle(file); + delete file; } /* @@ -272,9 +263,9 @@ stock File_ReadDownloadList(const String:path[]) * @param setFailState If true, it sets the failstate if the translations file doesn't exist * @return True on success, false otherwise (only if setFailState is set to false) */ -stock File_LoadTranslations(const String:file[], setFailState=true) +stock bool File_LoadTranslations(const char[] file, bool setFailState=true) { - decl String:path[PLATFORM_MAX_PATH]; + char path[PLATFORM_MAX_PATH]; BuildPath(Path_SM, path, sizeof(path), "translations/%s", file); @@ -307,17 +298,17 @@ stock File_LoadTranslations(const String:file[], setFailState=true) * @param size If -1, reads until a null terminator is encountered in the file. Otherwise, read_count bytes are read into the buffer provided. In this case the buffer is not explicitly null terminated, and the buffer will contain any null terminators read from the file. * @return Number of characters written to the buffer, or -1 if an error was encountered. */ -stock File_ToString(const String:path[], String:buffer[], size) +stock int File_ToString(const char[] path, char[] buffer, int size) { - new Handle:file = OpenFile(path, "rb"); + File file = OpenFile(path, "rb"); if (file == INVALID_HANDLE) { buffer[0] = '\0'; return -1; } - new num_bytes_written = ReadFileString(file, buffer, size); - CloseHandle(file); + int num_bytes_written = ReadFileString(file, buffer, size); + delete file; return num_bytes_written; } @@ -329,16 +320,16 @@ stock File_ToString(const String:path[], String:buffer[], size) * @param str String to write * @return True on success, false otherwise */ -stock bool:File_StringToFile(const String:path[], String:str[]) +stock bool File_StringToFile(const char[] path, char[] str) { - new Handle:file = OpenFile(path, "wb"); + File file = OpenFile(path, "wb"); if (file == INVALID_HANDLE) { return false; } - new bool:success = WriteFileString(file, str, false); - CloseHandle(file); + bool success = WriteFileString(file, str, false); + delete file; return success; } @@ -350,32 +341,33 @@ stock bool:File_StringToFile(const String:path[], String:str[]) * * @param source Input file * @param destination Output file + * @return True on success, false otherwise */ -stock bool:File_Copy(const String:source[], const String:destination[]) +stock bool File_Copy(const char[] source, const char[] destination) { - new Handle:file_source = OpenFile(source, "rb"); + File file_source = OpenFile(source, "rb"); if (file_source == INVALID_HANDLE) { return false; } - new Handle:file_destination = OpenFile(destination, "wb"); + File file_destination = OpenFile(destination, "wb"); if (file_destination == INVALID_HANDLE) { - CloseHandle(file_source); + delete file_source; return false; } - new buffer[32]; - new cache; + int buffer[32]; + int cache; while (!IsEndOfFile(file_source)) { - cache = ReadFile(file_source, buffer, 32, 1); + cache = ReadFile(file_source, buffer, sizeof(buffer), 1); WriteFile(file_destination, buffer, cache, 1); } - CloseHandle(file_source); - CloseHandle(file_destination); + delete file_source; + delete file_destination; return true; } @@ -391,8 +383,9 @@ stock bool:File_Copy(const String:source[], const String:destination[]) * @param destination Destination directory (This can only be a directory) * @param stop_on_error Optional: Set to true to stop on error (ie can't read a file) * @param dirMode Optional: File mode for directories that will be created (Default = 0755), don't forget to convert FROM octal + * @return True on success, false otherwise */ -stock bool:File_CopyRecursive(const String:path[], const String:destination[], bool:stop_on_error=false, dirMode=493) +stock bool File_CopyRecursive(const char[] path, const char[] destination, bool stop_on_error=false, int dirMode=493) { if (FileExists(path)) { return File_Copy(path, destination); @@ -405,7 +398,7 @@ stock bool:File_CopyRecursive(const String:path[], const String:destination[], b } } -static stock bool:Sub_File_CopyRecursive(const String:path[], const String:destination[], bool:stop_on_error=false, FileType:fileType, dirMode) +static stock bool Sub_File_CopyRecursive(const char[] path, const char[] destination, bool stop_on_error=false, FileType fileType, int dirMode) { if (fileType == FileType_File) { return File_Copy(path, destination); @@ -416,16 +409,16 @@ static stock bool:Sub_File_CopyRecursive(const String:path[], const String:desti return false; } - new Handle:directory = OpenDirectory(path); + DirectoryListing directory = OpenDirectory(path); if (directory == INVALID_HANDLE) { return false; } - decl - String:source_buffer[PLATFORM_MAX_PATH], - String:destination_buffer[PLATFORM_MAX_PATH]; - new FileType:type; + char + source_buffer[PLATFORM_MAX_PATH], + destination_buffer[PLATFORM_MAX_PATH]; + FileType type; while (ReadDirEntry(directory, source_buffer, sizeof(source_buffer), type)) { @@ -442,13 +435,13 @@ static stock bool:Sub_File_CopyRecursive(const String:path[], const String:desti else if (type == FileType_Directory) { if (!File_CopyRecursive(source_buffer, destination_buffer, stop_on_error, dirMode) && stop_on_error) { - CloseHandle(directory); + delete directory; return false; } } } - CloseHandle(directory); + delete directory; } else if (fileType == FileType_Unknown) { return false; diff --git a/addons/sourcemod/scripting/include/smlib/game.inc b/addons/sourcemod/scripting/include/smlib/game.inc index 771f780..ee3d145 100644 --- a/addons/sourcemod/scripting/include/smlib/game.inc +++ b/addons/sourcemod/scripting/include/smlib/game.inc @@ -10,12 +10,11 @@ /* * End's the game and displays the scoreboard with intermission time. * - * @noparam * @return True on success, false otherwise */ -stock bool:Game_End() +stock bool Game_End() { - new game_end = FindEntityByClassname(-1, "game_end"); + int game_end = FindEntityByClassname(-1, "game_end"); if (game_end == -1) { game_end = CreateEntityByName("game_end"); @@ -38,9 +37,9 @@ stock bool:Game_End() * @param switchTeams If to switch the teams when the game is going to be reset. * @return True on success, false otherwise */ -stock bool:Game_EndRound(team=0, bool:forceMapReset=false, bool:switchTeams=false) +stock bool Game_EndRound(int team=0, bool forceMapReset=false, bool switchTeams=false) { - new game_round_win = FindEntityByClassname(-1, "game_round_win"); + int game_round_win = FindEntityByClassname(-1, "game_round_win"); if (game_round_win == -1) { game_round_win = CreateEntityByName("game_round_win"); diff --git a/addons/sourcemod/scripting/include/smlib/general.inc b/addons/sourcemod/scripting/include/smlib/general.inc index ef061b6..a7e4d35 100644 --- a/addons/sourcemod/scripting/include/smlib/general.inc +++ b/addons/sourcemod/scripting/include/smlib/general.inc @@ -18,9 +18,9 @@ * @param material Path of the material to precache. * @return Returns the material index, INVALID_STRING_INDEX on error. */ -stock PrecacheMaterial(const String:material[]) +stock int PrecacheMaterial(const char[] material) { - static materialNames = INVALID_STRING_TABLE; + static int materialNames = INVALID_STRING_TABLE; if (materialNames == INVALID_STRING_TABLE) { if ((materialNames = FindStringTable("Materials")) == INVALID_STRING_TABLE) { @@ -28,9 +28,9 @@ stock PrecacheMaterial(const String:material[]) } } - new index = FindStringIndex2(materialNames, material); + int index = FindStringIndex2(materialNames, material); if (index == INVALID_STRING_INDEX) { - new numStrings = GetStringTableNumStrings(materialNames); + int numStrings = GetStringTableNumStrings(materialNames); if (numStrings >= GetStringTableMaxStrings(materialNames)) { return INVALID_STRING_INDEX; } @@ -48,9 +48,9 @@ stock PrecacheMaterial(const String:material[]) * @param material Path of the material. * @return True if it is precached, false otherwise. */ -stock bool:IsMaterialPrecached(const String:material[]) +stock bool IsMaterialPrecached(const char[] material) { - static materialNames = INVALID_STRING_TABLE; + static int materialNames = INVALID_STRING_TABLE; if (materialNames == INVALID_STRING_TABLE) { if ((materialNames = FindStringTable("Materials")) == INVALID_STRING_TABLE) { @@ -69,9 +69,9 @@ stock bool:IsMaterialPrecached(const String:material[]) * @param particleSystem Name of the particle system to precache. * @return Returns the particle system index, INVALID_STRING_INDEX on error. */ -stock PrecacheParticleSystem(const String:particleSystem[]) +stock int PrecacheParticleSystem(const char[] particleSystem) { - static particleEffectNames = INVALID_STRING_TABLE; + static int particleEffectNames = INVALID_STRING_TABLE; if (particleEffectNames == INVALID_STRING_TABLE) { if ((particleEffectNames = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) { @@ -79,9 +79,9 @@ stock PrecacheParticleSystem(const String:particleSystem[]) } } - new index = FindStringIndex2(particleEffectNames, particleSystem); + int index = FindStringIndex2(particleEffectNames, particleSystem); if (index == INVALID_STRING_INDEX) { - new numStrings = GetStringTableNumStrings(particleEffectNames); + int numStrings = GetStringTableNumStrings(particleEffectNames); if (numStrings >= GetStringTableMaxStrings(particleEffectNames)) { return INVALID_STRING_INDEX; } @@ -99,9 +99,9 @@ stock PrecacheParticleSystem(const String:particleSystem[]) * @param material Name of the particle system * @return True if it is precached, false otherwise. */ -stock bool:IsParticleSystemPrecached(const String:particleSystem[]) +stock bool IsParticleSystemPrecached(const char[] particleSystem) { - static particleEffectNames = INVALID_STRING_TABLE; + static int particleEffectNames = INVALID_STRING_TABLE; if (particleEffectNames == INVALID_STRING_TABLE) { if ((particleEffectNames = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) { @@ -119,9 +119,9 @@ stock bool:IsParticleSystemPrecached(const String:particleSystem[]) * @param str String to find. * @return String index if found, INVALID_STRING_INDEX otherwise. */ -stock FindStringIndexByTableName(const String:table[], const String:str[]) +stock int FindStringIndexByTableName(const char[] table, const char[] str) { - new tableIndex = INVALID_STRING_TABLE; + int tableIndex = INVALID_STRING_TABLE; if ((tableIndex = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) { return INVALID_STRING_INDEX; } @@ -138,12 +138,12 @@ stock FindStringIndexByTableName(const String:table[], const String:str[]) * @param str String to find. * @return String index if found, INVALID_STRING_INDEX otherwise. */ -stock FindStringIndex2(tableidx, const String:str[]) +stock int FindStringIndex2(int tableidx, const char[] str) { - decl String:buf[1024]; + char buf[1024]; - new numStrings = GetStringTableNumStrings(tableidx); - for (new i=0; i < numStrings; i++) { + int numStrings = GetStringTableNumStrings(tableidx); + for (int i=0; i < numStrings; i++) { ReadStringTable(tableidx, i, buf, sizeof(buf)); if (StrEqual(buf, str)) { @@ -160,9 +160,8 @@ stock FindStringIndex2(tableidx, const String:str[]) * @param ip IP Long * @param buffer String Buffer (size = 16) * @param size String Buffer size - * @noreturn */ -stock LongToIP(ip, String:buffer[], size) +stock void LongToIP(int ip, char[] buffer, int size) { Format( buffer, size, @@ -180,9 +179,9 @@ stock LongToIP(ip, String:buffer[], size) * @param ip IP String * @return Long IP */ -stock IPToLong(const String:ip[]) +stock int IPToLong(const char[] ip) { - decl String:pieces[4][4]; + char pieces[4][4]; if (ExplodeString(ip, ".", pieces, sizeof(pieces), sizeof(pieces[])) != 4) { return 0; @@ -196,7 +195,7 @@ stock IPToLong(const String:ip[]) ); } -static localIPRanges[] = +static int localIPRanges[] = { 10 << 24, // 10. 127 << 24 | 1 , // 127.0.0.1 @@ -210,16 +209,17 @@ static localIPRanges[] = * @param ip IP Long * @return True if the IP is local, false otherwise. */ -stock bool:IsIPLocal(ip) +stock bool IsIPLocal(int ip) { - new range, bits, move, bool:matches; + int range, bits, move; + bool matches; - for (new i=0; i < sizeof(localIPRanges); i++) { + for (int i=0; i < sizeof(localIPRanges); i++) { range = localIPRanges[i]; matches = true; - for (new j=0; j < 4; j++) { + for (int j=0; j < 4; j++) { move = j * 8; bits = (range >> move) & 0xFF; @@ -238,11 +238,11 @@ stock bool:IsIPLocal(ip) /* * Closes the given hindle and sets it to INVALID_HANDLE. + * Obsolete now. Just use |delete handle|. * * @param handle handle - * @noreturn */ -stock ClearHandle(&Handle:handle) +stock void ClearHandle(Handle &handle) { if (handle != INVALID_HANDLE) { CloseHandle(handle); diff --git a/addons/sourcemod/scripting/include/smlib/math.inc b/addons/sourcemod/scripting/include/smlib/math.inc index 8acca98..2e584fb 100644 --- a/addons/sourcemod/scripting/include/smlib/math.inc +++ b/addons/sourcemod/scripting/include/smlib/math.inc @@ -19,7 +19,7 @@ enum VecAngle ANG_ALPHA, ANG_BETA, ANG_GAMMA -} +}; /** * Makes a negative integer number to a positive integer number. @@ -29,7 +29,7 @@ enum VecAngle * @param number A number that can be positive or negative. * @return Positive number. */ -stock Math_Abs(value) +stock int Math_Abs(int value) { return (value ^ (value >> 31)) - (value >> 31); } @@ -43,9 +43,9 @@ stock Math_Abs(value) * @param tolerance If you want to check that those vectors are somewhat even. 0.0 means they are 100% even if this function returns true. * @return True if vectors are equal, false otherwise. */ -stock bool:Math_VectorsEqual(Float:vec1[3], Float:vec2[3], Float:tolerance=0.0) +stock bool Math_VectorsEqual(float vec1[3], float vec2[3], float tolerance=0.0) { - new Float:distance = GetVectorDistance(vec1, vec2, true); + float distance = GetVectorDistance(vec1, vec2, true); return distance <= (tolerance * tolerance); } @@ -53,12 +53,13 @@ stock bool:Math_VectorsEqual(Float:vec1[3], Float:vec2[3], Float:tolerance=0.0) /** * Sets the given value to min * if the value is smaller than the given. + * Don't use this with float values. * * @param value Value * @param min Min Value used as lower border * @return Correct value not lower than min */ -stock any:Math_Min(any:value, any:min) +stock any Math_Min(any value, any min) { if (value < min) { value = min; @@ -70,12 +71,13 @@ stock any:Math_Min(any:value, any:min) /** * Sets the given value to max * if the value is greater than the given. + * Don't use this with float values. * * @param value Value * @param max Max Value used as upper border * @return Correct value not upper than max */ -stock any:Math_Max(any:value, any:max) +stock any Math_Max(any value, any max) { if (value > max) { value = max; @@ -90,13 +92,14 @@ stock any:Math_Max(any:value, any:max) * If the value is outside the range it is set to either * min or max, if it is inside the range it will just return * the specified value. + * Don't use this with float values. * * @param value Value * @param min Min value used as lower border * @param max Max value used as upper border * @return Correct value not lower than min and not greater than max. */ -stock any:Math_Clamp(any:value, any:min, any:max) +stock any Math_Clamp(any value, any min, any max) { value = Math_Min(value, min); value = Math_Max(value, max); @@ -106,13 +109,14 @@ stock any:Math_Clamp(any:value, any:min, any:max) /* * Checks if the value is within the given bounds (min & max). + * Don't use this with float values. * * @param value The value you want to check. * @param min The lower border. * @param max The upper border. * @return True if the value is within bounds (bigger or equal min / smaller or equal max), false otherwise. */ -stock bool:Math_IsInBounds(any:value, any:min, any:max) +stock bool Math_IsInBounds(any value, any min, any max) { if (value < min || value > max) { return false; @@ -125,13 +129,14 @@ stock bool:Math_IsInBounds(any:value, any:min, any:max) * Let's the specified value "overflow" if it is outside the given limit. * This is like with integers when it reaches a value above the max possible * integer size. + * Don't use this with float values. * * @param value Value * @param min Min value used as lower border * @param max Max value used as upper border * @return Overflowed number */ -stock any:Math_Overflow(any:value, any:min, any:max) +stock any Math_Overflow(any value, any min, any max) { return (value % max) + min; } @@ -146,9 +151,9 @@ stock any:Math_Overflow(any:value, any:min, any:max) * @param max Max value used as upper border * @return Random Integer number between min and max */ -stock Math_GetRandomInt(min, max) +stock int Math_GetRandomInt(int min, int max) { - new random = GetURandomInt(); + int random = GetURandomInt(); if (random == 0) { random++; @@ -166,7 +171,7 @@ stock Math_GetRandomInt(min, max) * @param max Max value used as upper border * @return Random Float number between min and max */ -stock Float:Math_GetRandomFloat(Float:min, Float:max) +stock float Math_GetRandomFloat(float min, float max) { return (GetURandomFloat() * (max - min)) + min; } @@ -180,7 +185,7 @@ stock Float:Math_GetRandomFloat(Float:min, Float:max) * @param all Integer value * @return An Integer value between 0 and 100 (inclusive). */ -stock Math_GetPercentage(value, all) { +stock int Math_GetPercentage(int value, int all) { return RoundToNearest((float(value) / float(all)) * 100.0); } @@ -193,7 +198,7 @@ stock Math_GetPercentage(value, all) { * @param all Float value * @return A Float value between 0.0 and 100.0 (inclusive). */ -stock Float:Math_GetPercentageFloat(Float:value, Float:all) { +stock float Math_GetPercentageFloat(float value, float all) { return (value / all) * 100.0; } @@ -206,9 +211,8 @@ stock Float:Math_GetPercentageFloat(Float:value, Float:all) { * @param end The end vector where the imagined line ends. * @param scale The position on the line 0.0 is the start 1.0 is the end. * @param output Output vector - * @noreturn */ -stock Math_MoveVector(const Float:start[3], const Float:end[3], Float:scale, Float:output[3]) +stock void Math_MoveVector(const float start[3], const float end[3], float scale, float output[3]) { SubtractVectors(end,start,output); ScaleVector(output,scale); @@ -222,9 +226,8 @@ stock Math_MoveVector(const Float:start[3], const Float:end[3], Float:scale, Flo * @param y Float value. * @param z Float value. * @param result Output vector. - * @noreturn */ -stock Math_MakeVector(const Float:x, const Float:y, const Float:z, Float:result[3]) +stock void Math_MakeVector(float x, float y, float z, float result[3]) { result[0] = x; result[1] = y; @@ -242,12 +245,11 @@ stock Math_MakeVector(const Float:x, const Float:y, const Float:z, Float:result[ * @param vec Vector to rotate. * @param angles How to rotate the vector. * @param result Output vector. - * @noreturn */ -stock Math_RotateVector(const Float:vec[3], const Float:angles[3], Float:result[3]) +stock void Math_RotateVector(const float vec[3], const float angles[3], float result[3]) { // First the angle/radiant calculations - decl Float:rad[3]; + float rad[3]; // I don't really know why, but the alpha, beta, gamma order of the angles are messed up... // 2 = xAxis // 0 = yAxis @@ -257,16 +259,16 @@ stock Math_RotateVector(const Float:vec[3], const Float:angles[3], Float:result[ rad[2] = DegToRad(angles[1]); // Pre-calc function calls - new Float:cosAlpha = Cosine(rad[0]); - new Float:sinAlpha = Sine(rad[0]); - new Float:cosBeta = Cosine(rad[1]); - new Float:sinBeta = Sine(rad[1]); - new Float:cosGamma = Cosine(rad[2]); - new Float:sinGamma = Sine(rad[2]); + float cosAlpha = Cosine(rad[0]); + float sinAlpha = Sine(rad[0]); + float cosBeta = Cosine(rad[1]); + float sinBeta = Sine(rad[1]); + float cosGamma = Cosine(rad[2]); + float sinGamma = Sine(rad[2]); // 3D rotation matrix for more information: http://en.wikipedia.org/wiki/Rotation_matrix#In_three_dimensions - new Float:x = vec[0], Float:y = vec[1], Float:z = vec[2]; - new Float:newX, Float:newY, Float:newZ; + float x = vec[0], y = vec[1], z = vec[2]; + float newX, newY, newZ; newY = cosAlpha*y - sinAlpha*z; newZ = cosAlpha*z + sinAlpha*y; y = newY; @@ -294,7 +296,7 @@ stock Math_RotateVector(const Float:vec[3], const Float:angles[3], Float:result[ * @param units Float value * @return Meters as Float value. */ -stock Float:Math_UnitsToMeters(Float:units) +stock float Math_UnitsToMeters(float units) { return (units * GAMEUNITS_TO_METERS); } @@ -305,7 +307,7 @@ stock Float:Math_UnitsToMeters(Float:units) * @param units Float value * @return Feet as Float value. */ -stock Float:Math_UnitsToFeet(Float:units) +stock float Math_UnitsToFeet(float units) { return (Math_UnitsToMeters(units) * METERS_TO_FEET); } @@ -316,7 +318,7 @@ stock Float:Math_UnitsToFeet(Float:units) * @param units Float value * @return Centimeters as Float value. */ -stock Float:Math_UnitsToCentimeters(Float:units) +stock float Math_UnitsToCentimeters(float units) { return (Math_UnitsToMeters(units) * 100.0); } @@ -327,7 +329,7 @@ stock Float:Math_UnitsToCentimeters(Float:units) * @param units Float value * @return Kilometers as Float value. */ -stock Float:Math_UnitsToKilometers(Float:units) +stock float Math_UnitsToKilometers(float units) { return (Math_UnitsToMeters(units) / 1000.0); } @@ -338,7 +340,7 @@ stock Float:Math_UnitsToKilometers(Float:units) * @param units Float value * @return Miles as Float value. */ -stock Float:Math_UnitsToMiles(Float:units) +stock float Math_UnitsToMiles(float units) { return (Math_UnitsToKilometers(units) * KILOMETERS_TO_MILES); } diff --git a/addons/sourcemod/scripting/include/smlib/menus.inc b/addons/sourcemod/scripting/include/smlib/menus.inc index c0c825d..87f253e 100644 --- a/addons/sourcemod/scripting/include/smlib/menus.inc +++ b/addons/sourcemod/scripting/include/smlib/menus.inc @@ -13,13 +13,12 @@ * @param menu Handle to the menu * @param value Integer value for the option * @param display Display text for the menu - * @noreturn */ -stock Menu_AddIntItem(Handle:menu, any:value, String:display[]) +stock void Menu_AddIntItem(Menu menu, any value, char[] display) { - decl String:buffer[INT_MAX_DIGITS + 1]; + char buffer[INT_MAX_DIGITS + 1]; IntToString(value, buffer, sizeof(buffer)); - AddMenuItem(menu, buffer, display); + menu.AddItem(buffer, display); } /** @@ -30,9 +29,9 @@ stock Menu_AddIntItem(Handle:menu, any:value, String:display[]) * @param param2 The item position selected from the menu. * @return Integer choice from the menu, or 0 if the integer could not be parsed. */ -stock any:Menu_GetIntItem(Handle:menu, any:param2) +stock any Menu_GetIntItem(Menu menu, any param2) { - decl String:buffer[INT_MAX_DIGITS + 1]; - GetMenuItem(menu, param2, buffer, sizeof(buffer)); + char buffer[INT_MAX_DIGITS + 1]; + menu.GetItem(param2, buffer, sizeof(buffer)); return StringToInt(buffer); } diff --git a/addons/sourcemod/scripting/include/smlib/server.inc b/addons/sourcemod/scripting/include/smlib/server.inc index cb439e2..ae54cc4 100644 --- a/addons/sourcemod/scripting/include/smlib/server.inc +++ b/addons/sourcemod/scripting/include/smlib/server.inc @@ -17,11 +17,11 @@ * @param public Set to true to retrieve the server's public/external IP, false otherwise. * @return Long IP or 0 if the IP couldn't be retrieved. */ -stock Server_GetIP(bool:public_=true) +stock int Server_GetIP(bool public_=true) { - new ip = 0; + int ip = 0; - static Handle:cvHostip = INVALID_HANDLE; + static ConVar cvHostip = null; if (cvHostip == INVALID_HANDLE) { cvHostip = FindConVar("hostip"); @@ -29,7 +29,7 @@ stock Server_GetIP(bool:public_=true) } if (cvHostip != INVALID_HANDLE) { - ip = GetConVarInt(cvHostip); + ip = cvHostip.IntValue; } if (ip != 0 && IsIPLocal(ip) == public_) { @@ -39,7 +39,7 @@ stock Server_GetIP(bool:public_=true) #if defined _steamtools_included if (ip == 0) { if (CanTestFeatures() && GetFeatureStatus(FeatureType_Native, "Steam_GetPublicIP") == FeatureStatus_Available) { - decl octets[4]; + int octets[4]; Steam_GetPublicIP(octets); ip = @@ -72,9 +72,9 @@ stock Server_GetIP(bool:public_=true) * @param public Set to true to retrieve the server's public/external IP, false otherwise. * @return True on success, false otherwise. */ -stock bool:Server_GetIPString(String:buffer[], size, bool:public_=true) +stock bool Server_GetIPString(char[] buffer, int size, bool public_=true) { - new ip; + int ip; if ((ip = Server_GetIP(public_)) == 0) { buffer[0] = '\0'; @@ -92,9 +92,9 @@ stock bool:Server_GetIPString(String:buffer[], size, bool:public_=true) * @noparam * @return The server's port, 0 if there is no port. */ -stock Server_GetPort() +stock int Server_GetPort() { - static Handle:cvHostport = INVALID_HANDLE; + static ConVar cvHostport = null; if (cvHostport == INVALID_HANDLE) { cvHostport = FindConVar("hostport"); @@ -104,7 +104,7 @@ stock Server_GetPort() return 0; } - new port = GetConVarInt(cvHostport); + int port = cvHostport.IntValue; return port; } @@ -116,9 +116,9 @@ stock Server_GetPort() * @param size String buffer size * @return True on success, false otherwise. */ -stock bool:Server_GetHostName(String:buffer[], size) +stock bool Server_GetHostName(char[] buffer, int size) { - static Handle:cvHostname = INVALID_HANDLE; + static ConVar cvHostname = null; if (cvHostname == INVALID_HANDLE) { cvHostname = FindConVar("hostname"); @@ -129,7 +129,7 @@ stock bool:Server_GetHostName(String:buffer[], size) return false; } - GetConVarString(cvHostname, buffer, size); + cvHostname.GetString(buffer, size); return true; } diff --git a/addons/sourcemod/scripting/include/smlib/sql.inc b/addons/sourcemod/scripting/include/smlib/sql.inc index 1a4f1f1..e291cfa 100644 --- a/addons/sourcemod/scripting/include/smlib/sql.inc +++ b/addons/sourcemod/scripting/include/smlib/sql.inc @@ -17,16 +17,15 @@ * @param format Query string, printf syntax supported * @param priority Priority queue to use * @param ... Variable number of format parameters. - * @noreturn */ -stock SQL_TQueryF(Handle:database, SQLTCallback:callback, any:data, DBPriority:priority=DBPrio_Normal, const String:format[], any:...) { +stock void SQL_TQueryF(Database database, SQLTCallback callback, any data, DBPriority priority=DBPrio_Normal, const char[] format, any ...) { - if (database == INVALID_HANDLE) { + if (!database) { ThrowError("[SMLIB] Error: Invalid database handle."); return; } - decl String:query[16384]; + char query[16384]; VFormat(query, sizeof(query), format, 6); SQL_TQuery(database, callback, query, data, priority); @@ -43,9 +42,9 @@ stock SQL_TQueryF(Handle:database, SQLTCallback:callback, any:data, DBPriority:p * type conversion requested from the database, * or no current result set. */ -stock SQL_FetchIntByName(Handle:query, String:fieldName[], &DBResult:result=DBVal_Error) { +stock int SQL_FetchIntByName(DBResultSet query, const char[] fieldName, DBResult &result=DBVal_Error) { - new fieldNum; + int fieldNum; SQL_FieldNameToNum(query, fieldName, fieldNum); return SQL_FetchInt(query, fieldNum, result); @@ -62,9 +61,9 @@ stock SQL_FetchIntByName(Handle:query, String:fieldName[], &DBResult:result=DBVa * type conversion requested from the database, * or no current result set. */ -stock bool:SQL_FetchBoolByName(Handle:query, String:fieldName[], &DBResult:result=DBVal_Error) { +stock bool SQL_FetchBoolByName(DBResultSet query, const char[] fieldName, DBResult &result=DBVal_Error) { - return bool:SQL_FetchIntByName(query, fieldName, result); + return SQL_FetchIntByName(query, fieldName, result) != 0; } /** @@ -78,9 +77,9 @@ stock bool:SQL_FetchBoolByName(Handle:query, String:fieldName[], &DBResult:resul * type conversion requested from the database, * or no current result set. */ -stock Float:SQL_FetchFloatByName(Handle:query, String:fieldName[], &DBResult:result=DBVal_Error) { +stock float SQL_FetchFloatByName(DBResultSet query, const char[] fieldName, DBResult &result=DBVal_Error) { - new fieldNum; + int fieldNum; SQL_FieldNameToNum(query, fieldName, fieldNum); return SQL_FetchFloat(query, fieldNum, result); @@ -99,9 +98,9 @@ stock Float:SQL_FetchFloatByName(Handle:query, String:fieldName[], &DBResult:res * type conversion requested from the database, * or no current result set. */ -stock SQL_FetchStringByName(Handle:query, String:fieldName[], String:buffer[], maxlength, &DBResult:result=DBVal_Error) { +stock int SQL_FetchStringByName(DBResultSet query, const char[] fieldName, char[] buffer, int maxlength, DBResult &result=DBVal_Error) { - new fieldNum; + int fieldNum; SQL_FieldNameToNum(query, fieldName, fieldNum); return SQL_FetchString(query, fieldNum, buffer, maxlength, result); diff --git a/addons/sourcemod/scripting/include/smlib/strings.inc b/addons/sourcemod/scripting/include/smlib/strings.inc index 96657f9..b7cf9b4 100644 --- a/addons/sourcemod/scripting/include/smlib/strings.inc +++ b/addons/sourcemod/scripting/include/smlib/strings.inc @@ -13,11 +13,11 @@ * @param str String to check. * @return True if the String is numeric, false otherwise.. */ -stock bool:String_IsNumeric(const String:str[]) +stock bool String_IsNumeric(const char[] str) { - new x=0; - new dotsFound=0; - new numbersFound=0; + int x=0; + int dotsFound=0; + int numbersFound=0; if (str[x] == '+' || str[x] == '-') { x++; @@ -58,11 +58,10 @@ stock bool:String_IsNumeric(const String:str[]) * @param output Output String (Can be the as the input). * @param size Size of the output String. * @param chars Characters to remove. - * @noreturn */ -stock String_Trim(const String:str[], String:output[], size, const String:chrs[]=" \t\r\n") +stock void String_Trim(const char[] str, char[] output, int size, const char[] chrs=" \t\r\n") { - new x=0; + int x=0; while (str[x] != '\0' && FindCharInString(chrs, str[x]) != -1) { x++; } @@ -80,15 +79,14 @@ stock String_Trim(const String:str[], String:output[], size, const String:chrs[] /** * Removes a list of strings from a string. * - * @param buffer Input/Ourput buffer. + * @param buffer Input/Output buffer. * @param removeList A list of strings which should be removed from buffer. * @param size Number of Strings in the List. * @param caseSensitive If true, comparison is case sensitive. If false (default), comparison is case insensitive. - * @noreturn */ -stock String_RemoveList(String:buffer[], String:removeList[][], size, bool:caseSensitive=false) +stock void String_RemoveList(char[] buffer, const char[][] removeList, int size, bool caseSensitive=false) { - for (new i=0; i < size; i++) { + for (int i=0; i < size; i++) { ReplaceString(buffer, SIZE_OF_INT, removeList[i], "", caseSensitive); } } @@ -101,13 +99,12 @@ stock String_RemoveList(String:buffer[], String:removeList[][], size, bool:caseS * @param input Input String. * @param output Output String. * @param size Max Size of the Output string - * @noreturn */ -stock String_ToLower(const String:input[], String:output[], size) +stock void String_ToLower(const char[] input, char[] output, int size) { size--; - new x=0; + int x=0; while (input[x] != '\0' && x < size) { output[x] = CharToLower(input[x]); @@ -126,13 +123,12 @@ stock String_ToLower(const String:input[], String:output[], size) * @param input Input String. * @param output Output String. * @param size Max Size of the Output string - * @noreturn */ -stock String_ToUpper(const String:input[], String:output[], size) +stock void String_ToUpper(const char[] input, char[] output, int size) { size--; - new x=0; + int x=0; while (input[x] != '\0' && x < size) { output[x] = CharToUpper(input[x]); @@ -153,18 +149,17 @@ stock String_ToUpper(const String:input[], String:output[], size) * @param chrs String for specifying the characters used for random character generation. * By default it will use all letters of the alphabet (upper and lower) and all numbers. * If you pass an empty String, it will use all readable ASCII characters (33 - 126) - * @noreturn */ -stock String_GetRandom(String:buffer[], size, length=32, const String:chrs[]="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234556789") +stock void String_GetRandom(char[] buffer, int size, int length=32, const char[] chrs="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234556789") { - new random, len; + int random, len; size--; if (chrs[0] != '\0') { len = strlen(chrs) - 1; } - new n = 0; + int n = 0; while (n < length && n < size) { if (chrs[0] == '\0') { @@ -190,9 +185,9 @@ stock String_GetRandom(String:buffer[], size, length=32, const String:chrs[]="ab * @param subString Sub-String to check in str * @return True if str starts with subString, false otherwise. */ -stock bool:String_StartsWith(const String:str[], const String:subString[]) +stock bool String_StartsWith(const char[] str, const char[] subString) { - new n = 0; + int n = 0; while (subString[n] != '\0') { if (str[n] == '\0' || str[n] != subString[n]) { @@ -213,10 +208,10 @@ stock bool:String_StartsWith(const String:str[], const String:subString[]) * @param subString Sub-String to check in str * @return True if str ends with subString, false otherwise. */ -stock bool:String_EndsWith(const String:str[], const String:subString[]) +stock bool String_EndsWith(const char[] str, const char[] subString) { - new n_str = strlen(str) - 1; - new n_subString = strlen(subString) - 1; + int n_str = strlen(str) - 1; + int n_subString = strlen(subString) - 1; if(n_str < n_subString) { return false; diff --git a/addons/sourcemod/scripting/include/smlib/teams.inc b/addons/sourcemod/scripting/include/smlib/teams.inc index 2fd18c8..621c8b1 100644 --- a/addons/sourcemod/scripting/include/smlib/teams.inc +++ b/addons/sourcemod/scripting/include/smlib/teams.inc @@ -25,10 +25,10 @@ * @noparam * @return True if one team is empty, false otherwise. */ -stock bool:Team_HaveAllPlayers(bool:countFakeClients=true) { +stock bool Team_HaveAllPlayers(bool countFakeClients=true) { - new teamCount = GetTeamCount(); - for (new i=2; i < teamCount; i++) { + int teamCount = GetTeamCount(); + for (int i=2; i < teamCount; i++) { if (Team_GetClientCount(i, ((countFakeClients) ? CLIENTFILTER_ALL : CLIENTFILTER_NOBOTS)) == 0) { return false; @@ -45,12 +45,12 @@ stock bool:Team_HaveAllPlayers(bool:countFakeClients=true) { * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). * @return Client count in the server. */ -stock Team_GetClientCount(team, flags=0) +stock int Team_GetClientCount(int team, int flags=0) { flags |= CLIENTFILTER_INGAME; - new numClients = 0; - for (new client=1; client <= MaxClients; client++) { + int numClients = 0; + for (int client=1; client <= MaxClients; client++) { if (!Client_MatchesFilter(client, flags)) { continue; @@ -72,13 +72,12 @@ stock Team_GetClientCount(team, flags=0) * @param team1 Pass an integer variable by reference * @param team2 Pass an integer variable by reference * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). - * @noreturn */ -stock Team_GetClientCounts(&team1=0, &team2=0, flags=0) +stock void Team_GetClientCounts(int &team1=0, int &team2=0, int flags=0) { flags |= CLIENTFILTER_INGAME; - for (new client=1; client <= MaxClients; client++) { + for (int client=1; client <= MaxClients; client++) { if (!Client_MatchesFilter(client, flags)) { continue; @@ -102,9 +101,9 @@ stock Team_GetClientCounts(&team1=0, &team2=0, flags=0) * @param size String Buffer Size * @return True on success, false otherwise */ -stock bool:Team_GetName(index, String:str[], size) +stock bool Team_GetName(int index, char[] str, int size) { - new edict = Team_GetEdict(index); + int edict = Team_GetEdict(index); if (edict == -1) { str[0] = '\0'; @@ -126,9 +125,9 @@ stock bool:Team_GetName(index, String:str[], size) * @param name New Name String * @return True on success, false otherwise */ -stock bool:Team_SetName(index, const String:name[]) +stock bool Team_SetName(int index, const char[] name) { - new edict = Team_GetEdict(index); + int edict = Team_GetEdict(index); if (edict == -1) { return false; @@ -147,9 +146,9 @@ stock bool:Team_SetName(index, const String:name[]) * @param index Team Index. * @return Team Score or -1 if the team is not valid. */ -stock Team_GetScore(index) +stock int Team_GetScore(int index) { - new edict = Team_GetEdict(index); + int edict = Team_GetEdict(index); if (edict == -1) { return -1; @@ -166,9 +165,9 @@ stock Team_GetScore(index) * @param score Score value. * @return True on success, false otherwise */ -stock bool:Team_SetScore(index, score) +stock bool Team_SetScore(int index, int score) { - new edict = Team_GetEdict(index); + int edict = Team_GetEdict(index); if (edict == -1) { return false; @@ -188,7 +187,7 @@ stock bool:Team_SetScore(index, score) * @param edict Edict * @return Team Index */ -stock Team_EdictGetNum(edict) +stock int Team_EdictGetNum(int edict) { return GetEntProp(edict, Prop_Send, "m_iTeamNum"); } @@ -200,7 +199,7 @@ stock Team_EdictGetNum(edict) * @param index Index. * @return True if the Index is a valid team, false otherwise. */ -stock bool:Team_IsValid(index) +stock bool Team_IsValid(int index) { return (Team_GetEdict(index) != -1); } @@ -212,7 +211,7 @@ stock bool:Team_IsValid(index) * @param index Edict * @return Team Index */ -stock Team_EdictIsValid(edict) +stock int Team_EdictIsValid(int edict) { return GetEntProp(edict, Prop_Send, "m_iTeamNum"); } @@ -225,23 +224,23 @@ stock Team_EdictIsValid(edict) * @param index Team Index. * @return Team edict or -1 if not found */ -stock Team_GetEdict(index) +stock int Team_GetEdict(int index) { - static teams[MAX_TEAMS] = { INVALID_ENT_REFERENCE, ... }; + static int teams[MAX_TEAMS] = { INVALID_ENT_REFERENCE, ... }; if (index < 0 || index > MAX_TEAMS) { return -1; } - new edict = teams[index]; + int edict = teams[index]; if (Entity_IsValid(edict)) { return edict; } - new bool:foundTeamManager = false; + bool foundTeamManager = false; - new maxEntities = GetMaxEntities(); - for (new entity=MaxClients+1; entity < maxEntities; entity++) { + int maxEntities = GetMaxEntities(); + for (int entity=MaxClients+1; entity < maxEntities; entity++) { if (!IsValidEntity(entity)) { continue; @@ -258,7 +257,7 @@ stock Team_GetEdict(index) continue; } - new num = Team_EdictGetNum(entity); + int num = Team_EdictGetNum(entity); if (num >= 0 && num <= MAX_TEAMS) { teams[num] = EntIndexToEntRef(entity); @@ -280,10 +279,10 @@ stock Team_GetEdict(index) * @param index Team Index. * @return Client Index or -1 if no client was found in the specified team. */ -stock Team_GetAnyClient(index) +stock int Team_GetAnyClient(int index) { - static client_cache[MAX_TEAMS] = -1; - new client; + static int client_cache[MAX_TEAMS] = {-1, ...}; + int client; if (index > 0) { client = client_cache[index]; diff --git a/addons/sourcemod/scripting/include/smlib/vehicles.inc b/addons/sourcemod/scripting/include/smlib/vehicles.inc index d9fdebd..045875f 100644 --- a/addons/sourcemod/scripting/include/smlib/vehicles.inc +++ b/addons/sourcemod/scripting/include/smlib/vehicles.inc @@ -15,9 +15,9 @@ * @param vehicle Entity index. * @return Client index, or -1 if there is no driver. */ -stock Vehicle_GetDriver(vehicle) +stock int Vehicle_GetDriver(int vehicle) { - new m_hVehicle = GetEntPropEnt(vehicle, Prop_Send, "m_hPlayer"); + int m_hVehicle = GetEntPropEnt(vehicle, Prop_Send, "m_hPlayer"); return m_hVehicle; } @@ -28,9 +28,9 @@ stock Vehicle_GetDriver(vehicle) * @param vehicle Entity index. * @return True if the vehicle has a driver, false otherwise */ -stock bool:Vehicle_HasDriver(vehicle) +stock bool Vehicle_HasDriver(int vehicle) { - return !(Vehicle_GetDriver(vehicle) == -1); + return Vehicle_GetDriver(vehicle) != -1; } /** @@ -39,7 +39,7 @@ stock bool:Vehicle_HasDriver(vehicle) * @param vehicle Entity index. * @return True on success, false otherwise. */ -stock bool:Vehicle_ExitDriver(vehicle) +stock bool Vehicle_ExitDriver(int vehicle) { if (!Vehicle_HasDriver(vehicle)) { return false; @@ -54,9 +54,8 @@ stock bool:Vehicle_ExitDriver(vehicle) * @param vehicle Entity index. * @return True on success, false otherwise. */ -stock bool:Vehicle_TurnOn(vehicle) +stock bool Vehicle_TurnOn(int vehicle) { - return AcceptEntityInput(vehicle, "TurnOn"); } @@ -66,9 +65,8 @@ stock bool:Vehicle_TurnOn(vehicle) * @param vehicle Entity index. * @return True on success, false otherwise. */ -stock bool:Vehicle_TurnOff(vehicle) +stock bool Vehicle_TurnOff(int vehicle) { - return AcceptEntityInput(vehicle, "TurnOff"); } @@ -78,9 +76,8 @@ stock bool:Vehicle_TurnOff(vehicle) * @param vehicle Entity index. * @return True on success, false otherwise. */ -stock bool:Vehicle_Lock(vehicle) +stock bool Vehicle_Lock(int vehicle) { - return AcceptEntityInput(vehicle, "Lock"); } @@ -90,9 +87,8 @@ stock bool:Vehicle_Lock(vehicle) * @param vehicle Entity index. * @return True on success, false otherwise. */ -stock bool:Vehicle_Unlock(vehicle) +stock bool Vehicle_Unlock(int vehicle) { - return AcceptEntityInput(vehicle, "Unlock"); } @@ -102,7 +98,7 @@ stock bool:Vehicle_Unlock(vehicle) * @param vehicle Entity index. * @return True if it is a valid vehicle, false otherwise. */ -stock bool:Vehicle_IsValid(vehicle) +stock bool Vehicle_IsValid(int vehicle) { if (!Entity_IsValid(vehicle)) { return false; @@ -121,7 +117,7 @@ stock bool:Vehicle_IsValid(vehicle) * @param size String Buffer size. * @noreturn */ -stock bool:Vehicle_GetScript(vehicle, String:buffer[], size) +stock bool Vehicle_GetScript(int vehicle, char[] buffer, int size) { GetEntPropString(vehicle, Prop_Data, "m_vehicleScript", buffer, size); } @@ -135,7 +131,7 @@ stock bool:Vehicle_GetScript(vehicle, String:buffer[], size) * @param buffer Vehicle Script path. * @noreturn */ -stock bool:Vehicle_SetScript(vehicle, String:script[]) +stock bool Vehicle_SetScript(int vehicle, char[] script) { DispatchKeyValue(vehicle, "vehiclescript", script); } diff --git a/addons/sourcemod/scripting/include/smlib/weapons.inc b/addons/sourcemod/scripting/include/smlib/weapons.inc index 757119d..2f08d4e 100644 --- a/addons/sourcemod/scripting/include/smlib/weapons.inc +++ b/addons/sourcemod/scripting/include/smlib/weapons.inc @@ -25,7 +25,7 @@ * @param weapon Weapon Entity. * @return Owner of the weapon or INVALID_ENT_REFERENCE if the weapon has no owner. */ -stock Weapon_GetOwner(weapon) +stock int Weapon_GetOwner(int weapon) { return GetEntPropEnt(weapon, Prop_Data, "m_hOwner"); } @@ -37,7 +37,7 @@ stock Weapon_GetOwner(weapon) * @param entity Entity Index. * @noreturn */ -stock Weapon_SetOwner(weapon, entity) +stock int Weapon_SetOwner(int weapon, int entity) { SetEntPropEnt(weapon, Prop_Data, "m_hOwner", entity); } @@ -48,7 +48,7 @@ stock Weapon_SetOwner(weapon, entity) * @param weapon Weapon Entity. * @return True if the entity is a valid weapon, false otherwise. */ -stock Weapon_IsValid(weapon) +stock bool Weapon_IsValid(int weapon) { if (!IsValidEdict(weapon)) { return false; @@ -65,9 +65,9 @@ stock Weapon_IsValid(weapon) * @param absAngles Absolute Angles Vector. * @return Weapon Index of the created weapon or INVALID_ENT_REFERENCE on error. */ -stock Weapon_Create(const String:className[], Float:absOrigin[3], Float:absAngles[3]) +stock int Weapon_Create(const char[] className, float absOrigin[3], float absAngles[3]) { - new weapon = Entity_Create(className); + int weapon = Entity_Create(className); if (weapon == INVALID_ENT_REFERENCE) { return INVALID_ENT_REFERENCE; @@ -89,13 +89,13 @@ stock Weapon_Create(const String:className[], Float:absOrigin[3], Float:absAngle * @param absAngles Absolute Angles Vector. * @return Weapon Index of the created weapon or INVALID_ENT_REFERENCE on error. */ -stock Weapon_CreateForOwner(client, const String:className[]) +stock int Weapon_CreateForOwner(int client, const char[] className) { - decl Float:absOrigin[3], Float:absAngles[3]; + float absOrigin[3], absAngles[3]; Entity_GetAbsOrigin(client, absOrigin); Entity_GetAbsAngles(client, absAngles); - new weapon = Weapon_Create(className, absOrigin, absAngles); + int weapon = Weapon_Create(className, absOrigin, absAngles); if (weapon == INVALID_ENT_REFERENCE) { return INVALID_ENT_REFERENCE; @@ -113,7 +113,7 @@ stock Weapon_CreateForOwner(client, const String:className[]) * @param weapon Weapon Entity. * @return Subtype of the weapon. */ -stock Weapon_GetSubType(weapon) +stock int Weapon_GetSubType(int weapon) { return GetEntProp(weapon, Prop_Data, "m_iSubType"); } @@ -124,9 +124,9 @@ stock Weapon_GetSubType(weapon) * @param weapon Weapon Entity. * @return True if weapon is currently reloading, false if not. */ -stock bool:Weapon_IsReloading(weapon) +stock bool Weapon_IsReloading(int weapon) { - return bool:GetEntProp(weapon, Prop_Data, "m_bInReload"); + return GetEntProp(weapon, Prop_Data, "m_bInReload") != 0; } /* @@ -145,7 +145,7 @@ stock bool:Weapon_IsReloading(weapon) * @param weapon Weapon Entity. * @return Weapon State. */ -stock Weapon_GetState(weapon) +stock int Weapon_GetState(int weapon) { return GetEntProp(weapon, Prop_Data, "m_iState"); } @@ -156,9 +156,9 @@ stock Weapon_GetState(weapon) * @param weapon Weapon Entity. * @return True or False. */ -stock bool:Weapon_FiresUnderWater(weapon) +stock bool Weapon_FiresUnderWater(int weapon) { - return bool:GetEntProp(weapon, Prop_Data, "m_bFiresUnderwater"); + return GetEntProp(weapon, Prop_Data, "m_bFiresUnderwater") != 0; } /* @@ -166,11 +166,10 @@ stock bool:Weapon_FiresUnderWater(weapon) * * @param weapon Weapon Entity. * @param can True or False. - * @noreturn */ -stock Weapon_SetFiresUnderWater(weapon, bool:can=true) +stock void Weapon_SetFiresUnderWater(int weapon, bool can=true) { - SetEntProp(weapon, Prop_Data, "m_bFiresUnderwater", _:can); + SetEntProp(weapon, Prop_Data, "m_bFiresUnderwater", can); } /* @@ -179,9 +178,9 @@ stock Weapon_SetFiresUnderWater(weapon, bool:can=true) * @param weapon Weapon Entity. * @return True or False. */ -stock bool:Weapon_FiresUnderWaterAlt(weapon) +stock bool Weapon_FiresUnderWaterAlt(int weapon) { - return bool:GetEntProp(weapon, Prop_Data, "m_bAltFiresUnderwater"); + return GetEntProp(weapon, Prop_Data, "m_bAltFiresUnderwater") != 0; } /* @@ -189,11 +188,10 @@ stock bool:Weapon_FiresUnderWaterAlt(weapon) * * @param weapon Weapon Entity. * @param can True or False. - * @noreturn */ -stock Weapon_SetFiresUnderWaterAlt(weapon, bool:can=true) +stock void Weapon_SetFiresUnderWaterAlt(int weapon, bool can=true) { - SetEntProp(weapon, Prop_Data, "m_bAltFiresUnderwater", _:can); + SetEntProp(weapon, Prop_Data, "m_bAltFiresUnderwater", can); } /* @@ -202,7 +200,7 @@ stock Weapon_SetFiresUnderWaterAlt(weapon, bool:can=true) * @param weapon Weapon Entity. * @return Primary ammo type value. */ -stock Weapon_GetPrimaryAmmoType(weapon) +stock int Weapon_GetPrimaryAmmoType(int weapon) { return GetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoType"); } @@ -213,7 +211,7 @@ stock Weapon_GetPrimaryAmmoType(weapon) * @param weapon Weapon Entity. * @param type Primary ammo type value. */ -stock Weapon_SetPrimaryAmmoType(weapon,type) +stock void Weapon_SetPrimaryAmmoType(int weapon, int type) { SetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoType", type); } @@ -224,7 +222,7 @@ stock Weapon_SetPrimaryAmmoType(weapon,type) * @param weapon Weapon Entity. * @return Secondary ammo type value. */ -stock Weapon_GetSecondaryAmmoType(weapon) +stock int Weapon_GetSecondaryAmmoType(int weapon) { return GetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoType"); } @@ -235,7 +233,7 @@ stock Weapon_GetSecondaryAmmoType(weapon) * @param weapon Weapon Entity. * @param type Secondary ammo type value. */ -stock Weapon_SetSecondaryAmmoType(weapon,type) +stock void Weapon_SetSecondaryAmmoType(int weapon, int type) { SetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoType", type); } @@ -246,7 +244,7 @@ stock Weapon_SetSecondaryAmmoType(weapon,type) * @param weapon Weapon Entity. * @return Primary Clip count. */ -stock Weapon_GetPrimaryClip(weapon) +stock int Weapon_GetPrimaryClip(int weapon) { return GetEntProp(weapon, Prop_Data, "m_iClip1"); } @@ -257,7 +255,7 @@ stock Weapon_GetPrimaryClip(weapon) * @param weapon Weapon Entity. * @param value Clip Count value. */ -stock Weapon_SetPrimaryClip(weapon, value) +stock void Weapon_SetPrimaryClip(int weapon, int value) { SetEntProp(weapon, Prop_Data, "m_iClip1", value); } @@ -268,7 +266,7 @@ stock Weapon_SetPrimaryClip(weapon, value) * @param weapon Weapon Entity. * @return Secondy Clip count. */ -stock Weapon_GetSecondaryClip(weapon) +stock int Weapon_GetSecondaryClip(int weapon) { return GetEntProp(weapon, Prop_Data, "m_iClip2"); } @@ -279,7 +277,7 @@ stock Weapon_GetSecondaryClip(weapon) * @param weapon Weapon Entity. * @param value Clip Count value. */ -stock Weapon_SetSecondaryClip(weapon, value) +stock void Weapon_SetSecondaryClip(int weapon, int value) { SetEntProp(weapon, Prop_Data, "m_iClip2", value); } @@ -291,7 +289,7 @@ stock Weapon_SetSecondaryClip(weapon, value) * @param primary Primary Clip Count value. * @param secondary Primary Clip Count value. */ -stock Weapon_SetClips(weapon, primary, secondary) +stock void Weapon_SetClips(int weapon, int primary, int secondary) { Weapon_SetPrimaryClip(weapon, primary); Weapon_SetSecondaryClip(weapon, secondary); @@ -306,7 +304,7 @@ stock Weapon_SetClips(weapon, primary, secondary) * @param weapon Weapon Entity. * @return Primary Ammo Count. */ -stock Weapon_GetPrimaryAmmoCount(weapon) +stock int Weapon_GetPrimaryAmmoCount(int weapon) { return GetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoCount"); } @@ -319,9 +317,8 @@ stock Weapon_GetPrimaryAmmoCount(weapon) * * @param weapon Weapon Entity. * @param value Primary Ammo Count. - * @noreturn */ -stock Weapon_SetPrimaryAmmoCount(weapon, value) +stock void Weapon_SetPrimaryAmmoCount(int weapon, int value) { SetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoCount", value); } @@ -335,7 +332,7 @@ stock Weapon_SetPrimaryAmmoCount(weapon, value) * @param weapon Weapon Entity. * @return Secondary Ammo Count. */ -stock Weapon_GetSecondaryAmmoCount(weapon) +stock int Weapon_GetSecondaryAmmoCount(int weapon) { return GetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoCount"); } @@ -348,9 +345,8 @@ stock Weapon_GetSecondaryAmmoCount(weapon) * * @param weapon Weapon Entity. * @param value Secondary Ammo Count. - * @noreturn */ -stock Weapon_SetSecondaryAmmoCount(weapon, value) +stock void Weapon_SetSecondaryAmmoCount(int weapon, int value) { SetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoCount", value); } @@ -364,9 +360,8 @@ stock Weapon_SetSecondaryAmmoCount(weapon, value) * @param weapon Weapon Entity. * @value primary Primary Ammo Count. * @value secondary Secondary Ammo Count. - * @noreturn */ -stock Weapon_SetAmmoCounts(weapon, primary, secondary) +stock void Weapon_SetAmmoCounts(int weapon, int primary, int secondary) { Weapon_SetPrimaryAmmoCount(weapon, primary); Weapon_SetSecondaryAmmoCount(weapon, secondary); @@ -378,7 +373,7 @@ stock Weapon_SetAmmoCounts(weapon, primary, secondary) * @param weapon Weapon Entity. * @return View Model Index. */ -stock Weapon_GetViewModelIndex(weapon) +stock int Weapon_GetViewModelIndex(int weapon) { return GetEntProp(weapon, Prop_Data, "m_nViewModelIndex"); } @@ -391,7 +386,7 @@ stock Weapon_GetViewModelIndex(weapon) * @param index Model Index. * @noreturn */ -stock Weapon_SetViewModelIndex(weapon, index) +stock void Weapon_SetViewModelIndex(int weapon, int index) { SetEntProp(weapon, Prop_Data, "m_nViewModelIndex", index); ChangeEdictState(weapon, FindDataMapInfo(weapon, "m_nViewModelIndex")); diff --git a/addons/sourcemod/scripting/include/smlib/world.inc b/addons/sourcemod/scripting/include/smlib/world.inc index cd14b95..d438b41 100644 --- a/addons/sourcemod/scripting/include/smlib/world.inc +++ b/addons/sourcemod/scripting/include/smlib/world.inc @@ -9,9 +9,8 @@ * Gets the world's max size * * @param vec Vector buffer - * @noreturn */ -stock World_GetMaxs(Float:vec[3]) { +stock void World_GetMaxs(float vec[3]) { GetEntPropVector(0, Prop_Data, "m_WorldMaxs", vec); } diff --git a/addons/sourcemod/scripting/include/socket.inc b/addons/sourcemod/scripting/include/socket.inc new file mode 100644 index 0000000..7bd636a --- /dev/null +++ b/addons/sourcemod/scripting/include/socket.inc @@ -0,0 +1,482 @@ +// socket extension include file + +#if defined _socket_included + #endinput +#endif +#define _socket_included +#include + +enum SocketType { + SOCKET_TCP = 1, + SOCKET_UDP, + SOCKET_RAW +} + +#define EMPTY_HOST 1 +#define NO_HOST 2 +#define CONNECT_ERROR 3 +#define SEND_ERROR 4 +#define BIND_ERROR 5 +#define RECV_ERROR 6 +#define LISTEN_ERROR 7 + + +/*************************************************************************************************/ +/******************************************** options ********************************************/ +/*************************************************************************************************/ + + +/** + * Options available for SocketSetOption() + * + * @note modifying these options is not required for normal operation, you can skip the whole + * section in most cases. + */ +enum SocketOption { +/** + * If this option is set the socket extension will try to concatenate SocketReceive callbacks. + * + * This will possibly lower the amount of callbacks passed to SourceMod plugins and improve the + * performance. The socket extension will preserve the packet order. + * + * @note this doesn't prevent multiple callbacks, it only reduces them for high load. + * @note this will not truncate packets below 4096 bytes, setting it lower will be ignored + * @note set this option if you expect lots of data in a short timeframe + * @note don't forget to set your buffer sizes at least to the value passed to this function, but + * always at least to 4096 + * + * @param cell_t 0(=default) to disable or max. chunk size including \0 terminator in bytes + * @return bool true on success + */ + ConcatenateCallbacks = 1, +/** + * If this option is set the socket extension will enforce a mutex lock in the GameFrame() hook. + * + * This will ensure that callbacks will be processed every gameframe as fast as possible with the + * drawback of potentially creating lag. It's not recommended to set this option for most cases. + * If this option is not set the gameframe will be skipped if quietly obtaining a lock fails. + * + * @note combine this with CallbacksPerFrame for best performance + * @note this option will affect all sockets from all plugins, use it with caution! + * + * @param bool whether to force locking or not + * @return bool true on success + */ + ForceFrameLock, +/** + * This will specify the maximum amount of callbacks processed in every gameframe. + * + * The default value for this option is 1, setting it higher will possibly increase networking + * performance but may cause lag if it's set too high. + * The amount of callbacks actually being processed is limited by not being able to quietly obtain + * a lock (see ForceFrameLock) and the amount of callbacks in the queue. + * + * @note this option will affect all sockets from all plugins, use it with caution! + * + * @param cell_t maximum amount of callbacks per gameframe + * @return bool true on success + */ + CallbacksPerFrame, +/** + * If this option is set the socket will be allowed to send broadcast messages in case the protocol + * supports it. This is a wrapper for setting SO_BROADCAST. + * + * @param bool whether to allow broadcasting or not + * @return bool true on success + */ + SocketBroadcast, +/** + * If this option is set SocketBind() will allow reusing local adresses in case the protocol + * supports it. This is a wrapper for setting SO_REUSEADDR. + * + * @param bool whether to allow broadcasting or not + * @return bool true on success + */ + SocketReuseAddr, +/** + * If this option is set the socket will try to keep the connection alive by periodically sending + * messages if the protocol supports it. This is a wrapper for setting SO_KEEPALIVE. + * + * @param bool whether to allow broadcasting or not + * @return bool true on success + */ + SocketKeepAlive, +/** + * This option specifies how long a socket will wait if it's being closed and its send buffer is + * still filled. This is a wrapper for setting SO_LINGER. + * + * @param cell_t 0 (=default) to disable or time in s + * @return bool true on success + */ + SocketLinger, +/** + * If this option is set out-of-band data will be inlined into the normal receive stream. This is a + * wrapper for setting SO_OOBINLINE. + * + * @param bool whether to inline out-of-band data or not + * @return bool true on success + */ + SocketOOBInline, +/** + * This option specifies how large the send buffer will be. This is a wrapper for setting + * SO_SNDBUF. + * + * @param cell_t size in bytes + * @return bool true on success + */ + SocketSendBuffer, +/** + * This option specifies how large the receive buffer will be. This is a wrapper for setting + * SO_RCVBUF. + * + * @param cell_t size in bytes + * @return bool true on success + */ + SocketReceiveBuffer, +/** + * If this option is set outgoing messages will ignore the default routing facilities if the + * protocol implementation supports it. The remote site should be directly connected to the sender. + * This is a wrapper for setting SO_DONTROUTE. + * + * @param bool whether to skip default routing or not + * @return bool true on success + */ + SocketDontRoute, +/** + * This option specifies the minimum amount of data to receive before processing it. This is a + * wrapper for setting SO_RCVLOWAT. + * + * @note this can probably block the extension, use it with caution! + * + * @param cell_t size in bytes + * @return bool true on success + */ + SocketReceiveLowWatermark, +/** + * This option specifies how long a socket will try to receive data before it times out and + * processes the data. This is a wrapper for setting SO_RCVTIMEO. + * + * @param cell_t 0 (=default) to disable or time in ms + * @return bool true on success + */ + SocketReceiveTimeout, +/** + * This option specifies the minimum amount of data required in the send buffer before starting to + * send it. This is a wrapper for setting SO_SNDLOWAT. + * + * @note this can probably block the extension, use it with caution! + * + * @param cell_t size in bytes + * @return bool true on success + */ + SocketSendLowWatermark, +/** + * This option specifies how long a socket will try to send data before it times out and + * retries it later. This is a wrapper for setting SO_SNDTIMEO. + * + * @param cell_t 0 (=default) to disable or time in ms + * @return bool true on success + */ + SocketSendTimeout, +/** + * If this option is set the socket extension will display debugging messages in the server console/logs. + * + * @param bool whether to enable debugging or not + * @return bool true on success + */ + DebugMode +} + + +/*************************************************************************************************/ +/******************************************* callbacks *******************************************/ +/*************************************************************************************************/ + + +/** + * triggered if a normal sockets finished connecting and is ready to be used + * + * @param socket The socket handle pointing to the calling socket + * @param arg The argument set by SocketSetArg() + * @noreturn + */ +funcenum SocketConnectCB +{ + public(Handle:socket, any:arg) +}; + +/** + * triggered if a listening socket received an incoming connection and is ready to be used + * + * @note The child-socket won't work until receive-, disconnect-, and errorcallback for it are set. + * + * @param Handle socket The socket handle pointing to the calling listen-socket + * @param Handle newSocket The socket handle to the newly spawned child socket + * @param String remoteIP The remote IP + * @param any arg The argument set by SocketSetArg() for the listen-socket + * @noreturn + */ +funcenum SocketIncomingCB +{ + public(Handle:socket, Handle:newSocket, const String:remoteIP[], remotePort, any:arg) +}; + +/** + * triggered if a socket receives data + * + * @note This is binary safe if you always use dataSize for operations on receiveData[] + * @note packets may be split up into multiple chunks -> multiple calls to the receive callback + * @note if not set otherwise by SocketSetOption(..., ConcatenateCallbacks, ...) receiveData will + * never be longer than 4096 characters including \0 terminator + * + * @param Handle socket The socket handle pointing to the calling socket + * @param String receiveData The data which arrived, 0-terminated at receiveData[dataSize] + * @param cell_t dataSize The length of the arrived data excluding the 0-termination + * @param any arg The argument set by SocketSetArg() for the socket + * @noreturn + */ +funcenum SocketReceiveCB +{ + public(Handle:socket, const String:receiveData[], const dataSize, any:arg) +}; + +/** + * called after a socket sent all items in its send queue successfully + * + * @param Handle socket The socket handle pointing to the calling socket + * @param any arg The argument set by SocketSetArg() for the socket + * @noreturn + */ +funcenum SocketSendqueueEmptyCB +{ + public(Handle:socket, any:arg) +}; + +/** + * called if a socket has been properly disconnected by the remote side + * + * @note You should call CloseHandle(socket) or reuse the socket before this function ends + * + * @param Handle socket The socket handle pointing to the calling socket + * @param any arg The argument set by SocketSetArg() for the socket + * @noreturn + */ +funcenum SocketDisconnectCB +{ + public(Handle:socket, any:arg) +}; + +/** + * called if an unrecoverable error occured, close the socket without an additional call to a disconnect callback + * + * @note You should call CloseHandle(socket) or reuse the socket before this function ends + * + * @param Handle socket The socket handle pointing to the calling socket + * @param cell_t errorType The error type, see defines above + * @param cell_t errorNum The errno, see errno.h for details + * @param any arg The argument set by SocketSetArg() for the socket + * @noreturn + */ +funcenum SocketErrorCB +{ + public(Handle:socket, const errorType, const errorNum, any:arg) +}; + + +/*************************************************************************************************/ +/******************************************** natives ********************************************/ +/*************************************************************************************************/ + + +/** + * Returns whether a socket is connected or not. + * + * @param socket Socket handle to check + * @return bool The connection status + */ +native bool:SocketIsConnected(Handle:socket); + + +/** + * Creates a new socket. + * + * @note this function may be relatively expensive, reuse sockets if possible + * + * @param SocketType protocol The protocol to use, SOCKET_TCP is default + * @param SocketErrorCB efunc The error callback + * @return Handle The socket handle. Returns INVALID_HANDLE on failure + */ +native Handle:SocketCreate(SocketType:protocol=SOCKET_TCP, SocketErrorCB:efunc); + +/** + * Binds the socket to a local address + * + * @param Handle socket The handle of the socket to be used. * @param String hostname The hostname (or IP) to bind the socket to. + * @param cell_t port The port to bind the socket to. + * @return bool true on success + */ +native bool:SocketBind(Handle:socket, const String:hostname[], port); + +/** + * Connects a socket + * + * @note this native is threaded, it may be still running after it executed, use the connect callback + * @note invokes the SocketError callback with errorType = CONNECT_ERROR or EMPTY_HOST if it fails + * @note invokes the SocketConnect callback if it succeeds + * + * @param Handle socket The handle of the socket to be used. + * @param SocketConnectCB cfunc The connect callback + * @param SocketReceiveCB rfunc The receive callback + * @param SocketDisconnectCB dfunc The disconnect callback * @param String hostname The hostname (or IP) to connect to. + * @param cell_t port The port to connect to. + * @noreturn + */ +native SocketConnect(Handle:socket, SocketConnectCB:cfunc, SocketReceiveCB:rfunc, SocketDisconnectCB:dfunc, const String:hostname[], port); + +/** + * Disconnects a socket + * + * @note this will not close the handle, the socket will be reset to a state similar to after SocketCreate() + * @note this won't trigger any disconnect/error callbacks + * + * @noreturn + */ +native bool:SocketDisconnect(Handle:socket); + +/** + * Makes a socket listen for incoming connections + * + * @param Handle socket The handle of the socket to be used. + * @param SocketIncomingCB ifunc The callback for incoming connections + * @return bool true on success + */ +native bool:SocketListen(Handle:socket, SocketIncomingCB:ifunc); + +/** + * Sends data through the socket. + * + * @note specify size for binary safe operation + * @note if size is not specified the \0 terminator will not be included + * @note This native is threaded, it may be still running after it executed (not atomic). + * @note Use the SendqueueEmpty callback to determine when all data has been successfully sent. + * @note The socket extension will ensure that the data will be send in the correct order and split + * the data if required. + * + * @param Handle socket The handle of the socket to be used. + * @param String data The data to send. + * @noreturn */ +native SocketSend(Handle:socket, const String:data[], size=-1); + +/** * Sends UDP data through the socket to a specific destination. + * + * @note specify size for binary safe operation + * @note if size is not specified the \0 terminator will not be included + * @note This native is threaded, it may be still running after it executed (not atomic). + * @note Use the SendqueueEmpty callback to determine when all data has been successfully sent. + * @note The socket extension will ensure that the data will be send in the correct order and split + * the data if required. + * + * @param Handle socket The handle of the socket to be used. + * @param String data The data to send. + * @param String hostname The hostname (or IP) to send to. + * @param cell_t port The port to send to. + * @noreturn */ +native SocketSendTo(Handle:socket, const String:data[], size=-1, const String:hostname[], port); + +/** + * Set a socket option. + * + * @param Handle socket The handle of the socket to be used. May be INVALID_HANDLE if not essential. + * @param SocketOption option The option to modify (see enum SocketOption for details). + * @param cellt_ value The value to set the option to. + * @return cell_t 1 on success. */ +native SocketSetOption(Handle:socket, SocketOption:option, value); + + +/** + * Defines the callback function for when the socket receives data + * + * @note this is only useful and required for child-sockets spawned by listen-sockets + * (otherwise you already set it in SocketConnect()) + * + * @param Handle socket The handle of the socket to be used. + * @param SocketReceiveCB rfunc The receive callback + * @noreturn + */ +native SocketSetReceiveCallback(Handle:socket, SocketReceiveCB:rfunc); + +/** + * Defines the callback function for when the socket sent all items in its send queue + * + * @note this must be called AFTER sending (queueing) the data + * @note if no send-data is queued this will fire the callback itself + * @note the callback is guaranteed to fire + * + * @param Handle socket The handle of the socket to be used. + * @param SocketDisconnectCB dfunc The disconnect callback + * @noreturn + */ +native SocketSetSendqueueEmptyCallback(Handle:socket, SocketSendqueueEmptyCB:sfunc); + +/** + * Defines the callback function for when the socket was properly disconnected by the remote side + * + * @note this is only useful and required for child-sockets spawned by listen-sockets + * (otherwise you already set it in SocketConnect()) + * + * @param Handle socket The handle of the socket to be used. + * @param SocketDisconnectCB dfunc The disconnect callback + * @noreturn + */ +native SocketSetDisconnectCallback(Handle:socket, SocketDisconnectCB:dfunc); + +/** + * Defines the callback function for when the socket triggered an error + * + * @note this is only useful and required for child-sockets spawned by listen-sockets + * (otherwise you already set it in SocketCreate()) + * + * @param Handle socket The handle of the socket to be used. + * @param SocketErrorCB efunc The error callback + * @noreturn + */ +native SocketSetErrorCallback(Handle:socket, SocketErrorCB:efunc); + + +/** + * Sets the argument being passed to callbacks + * + * @param Handle socket The handle of the socket to be used. + * @param any arg The argument to set + * @noreturn + */ +native SocketSetArg(Handle:socket, any:arg); + +/** + * Retrieve the local system's hostname as the command "hostname" does. + * + * @param dest Destination string buffer to copy to. + * @param destLen Destination buffer length (includes null terminator). + * + * @return 1 on success + */ +native SocketGetHostName(String:dest[], destLen); + +/** + * _________________Do not edit below this line!_______________________ + */ +public Extension:__ext_smsock = +{ + name = "Socket", + file = "socket.ext", +#if defined AUTOLOAD_EXTENSIONS + autoload = 1, +#else + autoload = 0, +#endif +#if defined REQUIRE_EXTENSIONS + required = 1, +#else + required = 0, +#endif +}; diff --git a/addons/sourcemod/scripting/include/sorting.inc b/addons/sourcemod/scripting/include/sorting.inc index 2478645..5b0c249 100644 --- a/addons/sourcemod/scripting/include/sorting.inc +++ b/addons/sourcemod/scripting/include/sorting.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -32,7 +32,7 @@ #if defined _sorting_included - #endinput + #endinput #endif #define _sorting_included @@ -41,9 +41,9 @@ */ enum SortOrder { - Sort_Ascending = 0, /**< Ascending order */ - Sort_Descending = 1, /**< Descending order */ - Sort_Random = 2 /**< Random order */ + Sort_Ascending = 0, /**< Ascending order */ + Sort_Descending = 1, /**< Descending order */ + Sort_Random = 2 /**< Random order */ }; /** @@ -51,35 +51,35 @@ enum SortOrder */ enum SortType { - Sort_Integer = 0, - Sort_Float, - Sort_String, + Sort_Integer = 0, + Sort_Float, + Sort_String }; /** * Sorts an array of integers. * - * @param array Array of integers to sort in-place. - * @param array_size Size of the array. - * @param order Sorting order to use. + * @param array Array of integers to sort in-place. + * @param array_size Size of the array. + * @param order Sorting order to use. */ native void SortIntegers(int[] array, int array_size, SortOrder order = Sort_Ascending); /** * Sorts an array of float point numbers. * - * @param array Array of floating point numbers to sort in-place. - * @param array_size Size of the array. - * @param order Sorting order to use. + * @param array Array of floating point numbers to sort in-place. + * @param array_size Size of the array. + * @param order Sorting order to use. */ native void SortFloats(float[] array, int array_size, SortOrder order = Sort_Ascending); /** * Sorts an array of strings. * - * @param array Array of strings to sort in-place. - * @param array_size Size of the array. - * @param order Sorting order to use. + * @param array Array of strings to sort in-place. + * @param array_size Size of the array. + * @param order Sorting order to use. */ native void SortStrings(char[][] array, int array_size, SortOrder order = Sort_Ascending); @@ -87,23 +87,23 @@ native void SortStrings(char[][] array, int array_size, SortOrder order = Sort_A * Sort comparison function for 1D array elements. * @note You may need to use explicit tags in order to use data properly. * - * @param elem1 First element to compare. - * @param elem2 Second element to compare. - * @param array Array that is being sorted (order is undefined). - * @param hndl Handle optionally passed in while sorting. - * @return -1 if first should go before second - * 0 if first is equal to second - * 1 if first should go after second + * @param elem1 First element to compare. + * @param elem2 Second element to compare. + * @param array Array that is being sorted (order is undefined). + * @param hndl Handle optionally passed in while sorting. + * @return -1 if first should go before second + * 0 if first is equal to second + * 1 if first should go after second */ typedef SortFunc1D = function int (int elem1, int elem2, const int[] array, Handle hndl); -/** +/** * Sorts a custom 1D array. You must pass in a comparison function. * - * @param array Array to sort. - * @param array_size Size of the array to sort. - * @param sortfunc Sort function. - * @param hndl Optional Handle to pass through the comparison calls. + * @param array Array to sort. + * @param array_size Size of the array to sort. + * @param sortfunc Sort function. + * @param hndl Optional Handle to pass through the comparison calls. */ native void SortCustom1D(int[] array, int array_size, SortFunc1D sortfunc, Handle hndl=INVALID_HANDLE); @@ -111,13 +111,13 @@ native void SortCustom1D(int[] array, int array_size, SortFunc1D sortfunc, Handl * Sort comparison function for 2D array elements (sub-arrays). * @note You may need to use explicit tags in order to use data properly. * - * @param elem1 First array to compare. - * @param elem2 Second array to compare. - * @param array Array that is being sorted (order is undefined). - * @param hndl Handle optionally passed in while sorting. - * @return -1 if first should go before second - * 0 if first is equal to second - * 1 if first should go after second + * @param elem1 First array to compare. + * @param elem2 Second array to compare. + * @param array Array that is being sorted (order is undefined). + * @param hndl Handle optionally passed in while sorting. + * @return -1 if first should go before second + * 0 if first is equal to second + * 1 if first should go after second */ typeset SortFunc2D { @@ -125,22 +125,22 @@ typeset SortFunc2D function int (char[] elem1, char[] elem2, const char[][] array, Handle hndl); }; -/** +/** * Sorts a custom 2D array. You must pass in a comparison function. * - * @param array Array to sort. - * @param array_size Size of the major array to sort (first index, outermost). - * @param sortfunc Sort comparison function to use. - * @param hndl Optional Handle to pass through the comparison calls. + * @param array Array to sort. + * @param array_size Size of the major array to sort (first index, outermost). + * @param sortfunc Sort comparison function to use. + * @param hndl Optional Handle to pass through the comparison calls. */ native void SortCustom2D(any[][] array, int array_size, SortFunc2D sortfunc, Handle hndl=INVALID_HANDLE); /** * Sort an ADT Array. Specify the type as Integer, Float, or String. * - * @param array Array Handle to sort - * @param order Sort order to use, same as other sorts. - * @param type Data type stored in the ADT Array + * @param array Array Handle to sort + * @param order Sort order to use, same as other sorts. + * @param type Data type stored in the ADT Array */ native void SortADTArray(Handle array, SortOrder order, SortType type); @@ -149,21 +149,21 @@ native void SortADTArray(Handle array, SortOrder order, SortType type); * indexes currently being sorted, use ADT Array functions to retrieve the * index values and compare. * - * @param index1 First index to compare. - * @param index2 Second index to compare. - * @param array Array that is being sorted (order is undefined). - * @param hndl Handle optionally passed in while sorting. - * @return -1 if first should go before second - * 0 if first is equal to second - * 1 if first should go after second + * @param index1 First index to compare. + * @param index2 Second index to compare. + * @param array Array that is being sorted (order is undefined). + * @param hndl Handle optionally passed in while sorting. + * @return -1 if first should go before second + * 0 if first is equal to second + * 1 if first should go after second */ typedef SortFuncADTArray = function int (int index1, int index2, Handle array, Handle hndl); /** * Custom sorts an ADT Array. You must pass in a comparison function. * - * @param array Array Handle to sort - * @param sortfunc Sort comparison function to use - * @param hndl Optional Handle to pass through the comparison calls. + * @param array Array Handle to sort + * @param sortfunc Sort comparison function to use + * @param hndl Optional Handle to pass through the comparison calls. */ -native void SortADTArrayCustom(Handle array, SortFuncADTArray sortfunc, Handle hndl=INVALID_HANDLE); +native void SortADTArrayCustom(Handle array, SortFuncADTArray sortfunc, Handle hndl=INVALID_HANDLE); diff --git a/addons/sourcemod/scripting/include/sourcemod.inc b/addons/sourcemod/scripting/include/sourcemod.inc index c8594ed..917f5db 100644 --- a/addons/sourcemod/scripting/include/sourcemod.inc +++ b/addons/sourcemod/scripting/include/sourcemod.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -40,11 +40,11 @@ */ struct Plugin { - public const char[] name; /**< Plugin Name */ - public const char[] description; /**< Plugin Description */ - public const char[] author; /**< Plugin Author */ - public const char[] version; /**< Plugin Version */ - public const char[] url; /**< Plugin URL */ + public const char[] name; /**< Plugin Name */ + public const char[] description; /**< Plugin Description */ + public const char[] author; /**< Plugin Author */ + public const char[] version; /**< Plugin Version */ + public const char[] url; /**< Plugin URL */ }; #include @@ -79,17 +79,48 @@ struct Plugin enum APLRes { - APLRes_Success = 0, /**< Plugin should load */ - APLRes_Failure, /**< Plugin shouldn't load and should display an error */ - APLRes_SilentFailure /**< Plugin shouldn't load but do so silently */ + APLRes_Success = 0, /**< Plugin should load */ + APLRes_Failure, /**< Plugin shouldn't load and should display an error */ + APLRes_SilentFailure /**< Plugin shouldn't load but do so silently */ +}; + +methodmap GameData < Handle +{ + // Loads a game config file. + // + // @param file File to load. The path must be relative to the 'gamedata' folder under the config folder + // and the extension should be omitted. + // @return A handle to the game config file or null on failure. + public native GameData(const char[] file); + + // Returns an offset value. + // + // @param key Key to retrieve from the offset section. + // @return An offset, or -1 on failure. + public native int GetOffset(const char[] key); + + // Gets the value of a key from the "Keys" section. + // + // @param key Key to retrieve from the Keys section. + // @param buffer Destination string buffer. + // @param maxlen Maximum length of output string buffer. + // @return True if key existed, false otherwise. + public native bool GetKeyValue(const char[] key, char[] buffer, int maxlen); + + // Finds an address calculation in a GameConfig file, + // performs LoadFromAddress on it as appropriate, then returns the final address. + // + // @param name Name of the property to find. + // @return An address calculated on success, or 0 on failure. + public native Address GetAddress(const char[] name); }; /** - * Called when the plugin is fully initialized and all known external references - * are resolved. This is only called once in the lifetime of the plugin, and is + * Called when the plugin is fully initialized and all known external references + * are resolved. This is only called once in the lifetime of the plugin, and is * paired with OnPluginEnd(). * - * If any run-time error is thrown during this callback, the plugin will be marked + * If any run-time error is thrown during this callback, the plugin will be marked * as failed. */ forward void OnPluginStart(); @@ -104,30 +135,29 @@ forward bool AskPluginLoad(Handle myself, bool late, char[] error, int err_max); /** * Called before OnPluginStart, in case the plugin wants to check for load failure. - * This is called even if the plugin type is "private." Any natives from modules are - * not available at this point. Thus, this forward should only be used for explicit - * pre-emptive things, such as adding dynamic natives, setting certain types of load + * This is called even if the plugin type is "private." Any natives from modules are + * not available at this point. Thus, this forward should only be used for explicit + * pre-emptive things, such as adding dynamic natives, setting certain types of load * filters (such as not loading the plugin for certain games). - * + * * @note It is not safe to call externally resolved natives until OnPluginStart(). * @note Any sort of RTE in this function will cause the plugin to fail loading. - * @note If you do not return anything, it is treated like returning success. + * @note If you do not return anything, it is treated like returning success. * @note If a plugin has an AskPluginLoad2(), AskPluginLoad() will not be called. * - * - * @param myself Handle to the plugin. - * @param late Whether or not the plugin was loaded "late" (after map load). - * @param error Error message buffer in case load failed. - * @param err_max Maximum number of characters for error message buffer. - * @return APLRes_Success for load success, APLRes_Failure or APLRes_SilentFailure otherwise + * @param myself Handle to the plugin. + * @param late Whether or not the plugin was loaded "late" (after map load). + * @param error Error message buffer in case load failed. + * @param err_max Maximum number of characters for error message buffer. + * @return APLRes_Success for load success, APLRes_Failure or APLRes_SilentFailure otherwise */ forward APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max); /** * Called when the plugin is about to be unloaded. * - * It is not necessary to close any handles or remove hooks in this function. - * SourceMod guarantees that plugin shutdown automatically and correctly releases + * It is not necessary to close any handles or remove hooks in this function. + * SourceMod guarantees that plugin shutdown automatically and correctly releases * all resources. */ forward void OnPluginEnd(); @@ -135,7 +165,7 @@ forward void OnPluginEnd(); /** * Called when the plugin's pause status is changing. * - * @param pause True if the plugin is being paused, false otherwise. + * @param pause True if the plugin is being paused, false otherwise. */ forward void OnPluginPauseChange(bool pause); @@ -149,7 +179,7 @@ forward void OnGameFrame(); * Called when the map is loaded. * * @note This used to be OnServerLoad(), which is now deprecated. - * Plugins still using the old forward will work. + * Plugins still using the old forward will work. */ forward void OnMapStart(); @@ -159,39 +189,39 @@ forward void OnMapStart(); forward void OnMapEnd(); /** - * Called when the map has loaded, servercfgfile (server.cfg) has been + * Called when the map has loaded, servercfgfile (server.cfg) has been * executed, and all plugin configs are done executing. This is the best - * place to initialize plugin functions which are based on cvar data. + * place to initialize plugin functions which are based on cvar data. * - * @note This will always be called once and only once per map. It will be - * called after OnMapStart(). + * @note This will always be called once and only once per map. It will be + * called after OnMapStart(). */ forward void OnConfigsExecuted(); /** - * This is called once, right after OnMapStart() but any time before - * OnConfigsExecuted(). It is called after the "exec sourcemod.cfg" - * command and all AutoExecConfig() exec commands have been added to + * This is called once, right after OnMapStart() but any time before + * OnConfigsExecuted(). It is called after the "exec sourcemod.cfg" + * command and all AutoExecConfig() exec commands have been added to * the ServerCommand() buffer. * - * If you need to load per-map settings that override default values, - * adding commands to the ServerCommand() buffer here will guarantee + * If you need to load per-map settings that override default values, + * adding commands to the ServerCommand() buffer here will guarantee * that they're set before OnConfigsExecuted(). * - * Unlike OnMapStart() and OnConfigsExecuted(), this is not called on + * Unlike OnMapStart() and OnConfigsExecuted(), this is not called on * late loads that occur after OnMapStart(). */ forward void OnAutoConfigsBuffered(); /** - * @deprecated Use OnConfigsExecuted() instead. + * @deprecated Use OnConfigsExecuted() instead. */ #pragma deprecated Use OnConfigsExecuted() instead forward void OnServerCfg(); /** - * Called after all plugins have been loaded. This is called once for - * every plugin. If a plugin late loads, it will be called immediately + * Called after all plugins have been loaded. This is called once for + * every plugin. If a plugin late loads, it will be called immediately * after OnPluginStart(). */ forward void OnAllPluginsLoaded(); @@ -199,87 +229,87 @@ forward void OnAllPluginsLoaded(); /** * Returns the calling plugin's Handle. * - * @return Handle of the calling plugin. + * @return Handle of the calling plugin. */ native Handle GetMyHandle(); /** * Returns an iterator that can be used to search through plugins. * - * @return Handle to iterate with. Must be closed via - * CloseHandle(). - * @error Invalid Handle. + * @return Handle to iterate with. Must be closed via + * CloseHandle(). + * @error Invalid Handle. */ native Handle GetPluginIterator(); /** * Returns whether there are more plugins available in the iterator. * - * @param iter Handle to the plugin iterator. - * @return True on more plugins, false otherwise. - * @error Invalid Handle. + * @param iter Handle to the plugin iterator. + * @return True on more plugins, false otherwise. + * @error Invalid Handle. */ native bool MorePlugins(Handle iter); /** * Returns the current plugin in the iterator and advances the iterator. * - * @param iter Handle to the plugin iterator. - * @return Current plugin the iterator is at, before - * the iterator is advanced. - * @error Invalid Handle. + * @param iter Handle to the plugin iterator. + * @return Current plugin the iterator is at, before + * the iterator is advanced. + * @error Invalid Handle. */ native Handle ReadPlugin(Handle iter); /** * Returns a plugin's status. * - * @param plugin Plugin Handle (INVALID_HANDLE uses the calling plugin). - * @return Status code for the plugin. - * @error Invalid Handle. + * @param plugin Plugin Handle (INVALID_HANDLE uses the calling plugin). + * @return Status code for the plugin. + * @error Invalid Handle. */ native PluginStatus GetPluginStatus(Handle plugin); /** * Retrieves a plugin's file name relative to the plugins folder. * - * @param plugin Plugin Handle (INVALID_HANDLE uses the calling plugin). - * @param buffer Buffer to the store the file name. - * @param maxlength Maximum length of the name buffer. - * @error Invalid Handle. + * @param plugin Plugin Handle (INVALID_HANDLE uses the calling plugin). + * @param buffer Buffer to the store the file name. + * @param maxlength Maximum length of the name buffer. + * @error Invalid Handle. */ native void GetPluginFilename(Handle plugin, char[] buffer, int maxlength); /** * Retrieves whether or not a plugin is being debugged. * - * @param plugin Plugin Handle (INVALID_HANDLE uses the calling plugin). - * @return True if being debugged, false otherwise. - * @error Invalid Handle. + * @param plugin Plugin Handle (INVALID_HANDLE uses the calling plugin). + * @return True if being debugged, false otherwise. + * @error Invalid Handle. */ native bool IsPluginDebugging(Handle plugin); /** * Retrieves a plugin's public info. * - * @param plugin Plugin Handle (INVALID_HANDLE uses the calling plugin). - * @param info Plugin info property to retrieve. - * @param buffer Buffer to store info in. - * @param maxlength Maximum length of buffer. - * @return True on success, false if property is not available. - * @error Invalid Handle. + * @param plugin Plugin Handle (INVALID_HANDLE uses the calling plugin). + * @param info Plugin info property to retrieve. + * @param buffer Buffer to store info in. + * @param maxlength Maximum length of buffer. + * @return True on success, false if property is not available. + * @error Invalid Handle. */ native bool GetPluginInfo(Handle plugin, PluginInfo info, char[] buffer, int maxlength); /** - * Finds a plugin by its order in the list from the "plugins list" server - * "sm" command. You should not use this function to loop through all plugins, - * use the iterator instead. Looping through all plugins using this native + * Finds a plugin by its order in the list from the "plugins list" server + * "sm" command. You should not use this function to loop through all plugins, + * use the iterator instead. Looping through all plugins using this native * is O(n^2), whereas using the iterator is O(n). * - * @param order_num Number of the plugin as it appears in "sm plugins list". - * @return Plugin Handle on success, INVALID_HANDLE if no plugin - * matches the given number. + * @param order_num Number of the plugin as it appears in "sm plugins list". + * @return Plugin Handle on success, INVALID_HANDLE if no plugin + * matches the given number. */ native Handle FindPluginByNumber(int order_num); @@ -287,18 +317,18 @@ native Handle FindPluginByNumber(int order_num); * Causes the plugin to enter a failed state. An error will be thrown and * the plugin will be paused until it is unloaded or reloaded. * - * For backwards compatibility, if no extra arguments are passed, no - * formatting is applied. If one or more additional arguments is passed, - * the string is formatted using Format(). If any errors are encountered - * during formatting, both the format specifier string and an additional + * For backwards compatibility, if no extra arguments are passed, no + * formatting is applied. If one or more additional arguments is passed, + * the string is formatted using Format(). If any errors are encountered + * during formatting, both the format specifier string and an additional * error message are written. * - * This function does not return, and no further code in the plugin is + * This function does not return, and no further code in the plugin is * executed. * - * @param string Format specifier string. - * @param ... Formatting arguments. - * @error Always throws SP_ERROR_ABORT. + * @param string Format specifier string. + * @param ... Formatting arguments. + * @error Always throws SP_ERROR_ABORT. */ native void SetFailState(const char[] string, any ...); @@ -306,60 +336,74 @@ native void SetFailState(const char[] string, any ...); * Aborts the current callback and throws an error. This function * does not return in that no code is executed following it. * - * @param fmt String format. - * @param ... Format arguments. - * @error Always! + * @param fmt String format. + * @param ... Format arguments. + * @error Always! */ native void ThrowError(const char[] fmt, any ...); +/** + * Logs a stack trace from the current function call. Code + * execution continues after the call + * + * @param fmt Format string to send with the stack trace. + * @param ... Format arguments. + * @error Always logs a stack trace. + */ +native void LogStackTrace(const char[] fmt, any ...); + /** * Gets the system time as a unix timestamp. * - * @param bigStamp Optional array to store the 64bit timestamp in. - * @return 32bit timestamp (number of seconds since unix epoch). + * @param bigStamp Optional array to store the 64bit timestamp in. + * @return 32bit timestamp (number of seconds since unix epoch). */ native int GetTime(int bigStamp[2]={0,0}); /** * Produces a date and/or time string value for a timestamp. * - * See this URL for valid parameters: + * See this URL for valid parameters: * http://cplusplus.com/reference/clibrary/ctime/strftime.html * - * @param buffer Destination string buffer. - * @param maxlength Maximum length of output string buffer. - * @param format Formatting rules (passing NULL_STRING will use the rules defined in sm_datetime_format). - * @param stamp Optional time stamp. - * @error Buffer too small or invalid time format. + * Note that available parameters depends on support from your operating system. + * In particular, ones highlighted in yellow on that page are not currently + * available on Windows and should be avoided for portable plugins. + * + * @param buffer Destination string buffer. + * @param maxlength Maximum length of output string buffer. + * @param format Formatting rules (passing NULL_STRING will use the rules defined in sm_datetime_format). + * @param stamp Optional time stamp. + * @error Buffer too small or invalid time format. */ native void FormatTime(char[] buffer, int maxlength, const char[] format, int stamp=-1); /** * Loads a game config file. * - * @param file File to load. The path must be relative to the 'gamedata' folder under the config folder - * and the extension should be omitted. - * @return A handle to the game config file or INVALID_HANDLE in failure. + * @param file File to load. The path must be relative to the 'gamedata' folder under the config folder + * and the extension should be omitted. + * @return A handle to the game config file or INVALID_HANDLE on failure. */ -native Handle LoadGameConfigFile(const char[] file); +native GameData LoadGameConfigFile(const char[] file); /** * Returns an offset value. * - * @param gc Game config handle. - * @param key Key to retrieve from the offset section. - * @return An offset, or -1 on failure. + * @param gc Game config handle. + * @param key Key to retrieve from the offset section. + * @return An offset, or -1 on failure. */ native int GameConfGetOffset(Handle gc, const char[] key); /** * Gets the value of a key from the "Keys" section. * - * @param gc Game config handle. - * @param key Key to retrieve from the Keys section. - * @param buffer Destination string buffer. - * @param maxlen Maximum length of output string buffer. - * @return True if key existed, false otherwise. + * @param gc Game config handle. + * @param key Key to retrieve from the Keys section. + * @param buffer Destination string buffer. + * @param maxlen Maximum length of output string buffer. + * @return True if key existed, false otherwise. */ native bool GameConfGetKeyValue(Handle gc, const char[] key, char[] buffer, int maxlen); @@ -367,174 +411,174 @@ native bool GameConfGetKeyValue(Handle gc, const char[] key, char[] buffer, int * Finds an address calculation in a GameConfig file, * performs LoadFromAddress on it as appropriate, then returns the final address. * - * @param gameconf GameConfig Handle, or INVALID_HANDLE to use sdktools.games.txt. + * @param gameconf Game config handle. * @param name Name of the property to find. * @return An address calculated on success, or 0 on failure. */ native Address GameConfGetAddress(Handle gameconf, const char[] name); /** - * Returns the operating system's "tick count," which is a number of + * Returns the operating system's "tick count," which is a number of * milliseconds since the operating system loaded. This can be used * for basic benchmarks. * - * @return Tick count in milliseconds. + * @return Tick count in milliseconds. */ native int GetSysTickCount(); /** * Specifies that the given config file should be executed after plugin load. - * OnConfigsExecuted() will not be called until the config file has executed, + * OnConfigsExecuted() will not be called until the config file has executed, * but it will be called if the execution fails. * - * @param autoCreate If true, and the config file does not exist, such a config - * file will be automatically created and populated with - * information from the plugin's registered cvars. - * @param name Name of the config file, excluding the .cfg extension. - * If empty, is assumed. - * @param folder Folder under cfg/ to use. By default this is "sourcemod." + * @param autoCreate If true, and the config file does not exist, such a config + * file will be automatically created and populated with + * information from the plugin's registered cvars. + * @param name Name of the config file, excluding the .cfg extension. + * If empty, is assumed. + * @param folder Folder under cfg/ to use. By default this is "sourcemod." */ native void AutoExecConfig(bool autoCreate=true, const char[] name="", const char[] folder="sourcemod"); /** - * Registers a library name for identifying as a dependency to + * Registers a library name for identifying as a dependency to * other plugins. * - * @param name Library name. + * @param name Library name. */ native void RegPluginLibrary(const char[] name); /** - * Returns whether a library exists. This function should be considered - * expensive; it should only be called on plugin to determine availability - * of resources. Use OnLibraryAdded()/OnLibraryRemoved() to detect changes + * Returns whether a library exists. This function should be considered + * expensive; it should only be called on plugin to determine availability + * of resources. Use OnLibraryAdded()/OnLibraryRemoved() to detect changes * in optional resources. * - * @param name Library name of a plugin or extension. - * @return True if exists, false otherwise. + * @param name Library name of a plugin or extension. + * @return True if exists, false otherwise. */ native bool LibraryExists(const char[] name); /** * Returns the status of an extension, by filename. * - * @param name Extension name (like "sdktools.ext"). - * @param error Optional error message buffer. - * @param maxlength Length of optional error message buffer. - * @return -2 if the extension was not found. - * -1 if the extension was found but failed to load. - * 0 if the extension loaded but reported an error. - * 1 if the extension is running without error. + * @param name Extension name (like "sdktools.ext"). + * @param error Optional error message buffer. + * @param maxlength Length of optional error message buffer. + * @return -2 if the extension was not found. + * -1 if the extension was found but failed to load. + * 0 if the extension loaded but reported an error. + * 1 if the extension is running without error. */ native int GetExtensionFileStatus(const char[] name, char[] error="", int maxlength=0); /** - * Called after a library is added that the current plugin references - * optionally. A library is either a plugin name or extension name, as + * Called after a library is added that the current plugin references + * optionally. A library is either a plugin name or extension name, as * exposed via its include file. * - * @param name Library name. + * @param name Library name. */ forward void OnLibraryAdded(const char[] name); /** - * Called right before a library is removed that the current plugin references - * optionally. A library is either a plugin name or extension name, as + * Called right before a library is removed that the current plugin references + * optionally. A library is either a plugin name or extension name, as * exposed via its include file. * - * @param name Library name. + * @param name Library name. */ forward void OnLibraryRemoved(const char[] name); -#define MAPLIST_FLAG_MAPSFOLDER (1<<0) /**< On failure, use all maps in the maps folder. */ -#define MAPLIST_FLAG_CLEARARRAY (1<<1) /**< If an input array is specified, clear it before adding. */ -#define MAPLIST_FLAG_NO_DEFAULT (1<<2) /**< Do not read "default" or "mapcyclefile" on failure. */ +#define MAPLIST_FLAG_MAPSFOLDER (1<<0) /**< On failure, use all maps in the maps folder. */ +#define MAPLIST_FLAG_CLEARARRAY (1<<1) /**< If an input array is specified, clear it before adding. */ +#define MAPLIST_FLAG_NO_DEFAULT (1<<2) /**< Do not read "default" or "mapcyclefile" on failure. */ /** * Loads a map list to an ADT Array. * - * A map list is a list of maps from a file. SourceMod allows easy configuration of - * maplists through addons/sourcemod/configs/maplists.cfg. Each entry is given a - * name and a file (for example, "rtv" => "rtv.cfg"), or a name and a redirection - * (for example, "rtv" => "default"). This native will read a map list entry, - * cache the file, and return the list of maps it holds. + * A map list is a list of maps from a file. SourceMod allows easy configuration of + * maplists through addons/sourcemod/configs/maplists.cfg. Each entry is given a + * name and a file (for example, "rtv" => "rtv.cfg"), or a name and a redirection + * (for example, "rtv" => "default"). This native will read a map list entry, + * cache the file, and return the list of maps it holds. * - * Serial change numbers are used to identify if a map list has changed. Thus, if - * you pass a serial change number and it's equal to what SourceMod currently knows + * Serial change numbers are used to identify if a map list has changed. Thus, if + * you pass a serial change number and it's equal to what SourceMod currently knows * about the map list, then SourceMod won't re-parse the file. * - * If the maps end up being read from the maps folder (MAPLIST_FLAG_MAPSFOLDER), they + * If the maps end up being read from the maps folder (MAPLIST_FLAG_MAPSFOLDER), they * are automatically sorted in alphabetical, ascending order. * * Arrays created by this function are temporary and must be freed via CloseHandle(). - * Modifying arrays created by this function will not affect future return values or + * Modifying arrays created by this function will not affect future return values or * or the contents of arrays returned to other plugins. * - * @param array Array to store the map list. If INVALID_HANDLE, a new blank - * array will be created. The blocksize should be at least 16; - * otherwise results may be truncated. Items are added to the array - * as strings. The array is never checked for duplicates, and it is - * not read beforehand. Only the serial number is used to detect - * changes. - * @param serial Serial number to identify last known map list change. If -1, the - * the value will not be checked. If the map list has since changed, - * the serial is updated (even if -1 was passed). If there is an error - * finding a valid maplist, then the serial is set to -1. - * @param str Config name, or "default" for the default map list. Config names - * should be somewhat descriptive. For example, the admin menu uses - * a config name of "admin menu". The list names can be configured - * by users in addons/sourcemod/configs/maplists.cfg. - * @param flags MAPLIST_FLAG flags. - * @return On failure: - * INVALID_HANDLE is returned, the serial is set to -1, and the input - * array (if any) is left unchanged. - * On no change: - INVALID_HANDLE is returned, the serial is unchanged, and the input - array (if any) is left unchanged. - * On success: - * A valid array Handle is returned, containing at least one map string. - * If an array was passed, the return value is equal to the passed Array - * Handle. If the passed array was not cleared, it will have grown by at - * least one item. The serial number is updated to a positive number. - * @error Invalid array Handle that is not INVALID_HANDLE. + * @param array Array to store the map list. If INVALID_HANDLE, a new blank + * array will be created. The blocksize should be at least 16; + * otherwise results may be truncated. Items are added to the array + * as strings. The array is never checked for duplicates, and it is + * not read beforehand. Only the serial number is used to detect + * changes. + * @param serial Serial number to identify last known map list change. If -1, the + * the value will not be checked. If the map list has since changed, + * the serial is updated (even if -1 was passed). If there is an error + * finding a valid maplist, then the serial is set to -1. + * @param str Config name, or "default" for the default map list. Config names + * should be somewhat descriptive. For example, the admin menu uses + * a config name of "admin menu". The list names can be configured + * by users in addons/sourcemod/configs/maplists.cfg. + * @param flags MAPLIST_FLAG flags. + * @return On failure: + * INVALID_HANDLE is returned, the serial is set to -1, and the input + * array (if any) is left unchanged. + * On no change: + * INVALID_HANDLE is returned, the serial is unchanged, and the input + * array (if any) is left unchanged. + * On success: + * A valid array Handle is returned, containing at least one map string. + * If an array was passed, the return value is equal to the passed Array + * Handle. If the passed array was not cleared, it will have grown by at + * least one item. The serial number is updated to a positive number. + * @error Invalid array Handle that is not INVALID_HANDLE. */ native Handle ReadMapList(Handle array=INVALID_HANDLE, - int &serial=-1, - const char[] str="default", - int flags=MAPLIST_FLAG_CLEARARRAY); - + int &serial=-1, + const char[] str="default", + int flags=MAPLIST_FLAG_CLEARARRAY); + /** - * Makes a compatibility binding for map lists. For example, if a function previously used - * "clam.cfg" for map lists, this function will insert a "fake" binding to "clam.cfg" that + * Makes a compatibility binding for map lists. For example, if a function previously used + * "clam.cfg" for map lists, this function will insert a "fake" binding to "clam.cfg" that * will be overridden if it's in the maplists.cfg file. * - * @param name Configuration name that would be used with ReadMapList(). - * @param file Default file to use. + * @param name Configuration name that would be used with ReadMapList(). + * @param file Default file to use. */ native void SetMapListCompatBind(const char[] name, const char[] file); /** - * Called when a client has sent chat text. This must return either true or + * Called when a client has sent chat text. This must return either true or * false to indicate that a client is or is not spamming the server. * - * The return value is a hint only. Core or another plugin may decide + * The return value is a hint only. Core or another plugin may decide * otherwise. * - * @param client Client index. The server (0) will never be passed. - * @return True if client is spamming the server, false otherwise. + * @param client Client index. The server (0) will never be passed. + * @return True if client is spamming the server, false otherwise. */ forward bool OnClientFloodCheck(int client); /** - * Called after a client's flood check has been computed. This can be used + * Called after a client's flood check has been computed. This can be used * by antiflood algorithms to decay/increase flooding weights. * - * Since the result from "OnClientFloodCheck" isn't guaranteed to be the - * final result, it is generally a good idea to use this to play with other + * Since the result from "OnClientFloodCheck" isn't guaranteed to be the + * final result, it is generally a good idea to use this to play with other * algorithms nicely. * - * @param client Client index. The server (0) will never be passed. - * @param blocked True if client flooded last "say", false otherwise. + * @param client Client index. The server (0) will never be passed. + * @param blocked True if client flooded last "say", false otherwise. */ forward void OnClientFloodResult(int client, bool blocked); @@ -547,7 +591,7 @@ enum FeatureType * A native function call. */ FeatureType_Native, - + /** * A named capability. This is distinctly different from checking for a * native, because the underlying functionality could be enabled on-demand @@ -567,12 +611,12 @@ enum FeatureStatus * Feature is available for use. */ FeatureStatus_Available, - + /** * Feature is not available. */ FeatureStatus_Unavailable, - + /** * Feature is not known at all. */ @@ -624,7 +668,7 @@ enum NumberType enum Address { - Address_Null = 0, // a typical invalid result when an address lookup fails + Address_Null = 0 // a typical invalid result when an address lookup fails }; /** @@ -643,32 +687,32 @@ native int LoadFromAddress(Address addr, NumberType size); * @param data Value to store at the address. * @param size How many bytes should be written. */ -native void StoreToAddress(Address addr, int data, NumberType size); +native void StoreToAddress(Address addr, int data, NumberType size); methodmap FrameIterator < Handle { // Creates a stack frame iterator to build your own stack traces. - // @return New handle to a FrameIterator. + // @return New handle to a FrameIterator. public native FrameIterator(); - + // Advances the iterator to the next stack frame. - // @return True if another frame was fetched and data can be successfully read. - // @error No next element exception. + // @return True if another frame was fetched and data can be successfully read. + // @error No next element exception. public native bool Next(); - + // Resets the iterator back to it's starting position. public native void Reset(); - + // Returns the line number of the current function call. - property bool LineNumber { + property int LineNumber { public native get(); } - + // Gets the name of the current function in the call stack. // // @param buffer Buffer to copy to. // @param maxlen Max size of the buffer. public native void GetFunctionName(char[] buffer, int maxlen); - + // Gets the file path to the current call in the call stack. // // @param buffer Buffer to copy to. diff --git a/addons/sourcemod/scripting/include/string.inc b/addons/sourcemod/scripting/include/string.inc index 2f16ca9..990989f 100644 --- a/addons/sourcemod/scripting/include/string.inc +++ b/addons/sourcemod/scripting/include/string.inc @@ -45,53 +45,53 @@ /** * Calculates the length of a string. * - * @param str String to check. - * @return Number of valid character bytes in the string. + * @param str String to check. + * @return Number of valid character bytes in the string. */ native int strlen(const char[] str); /** * Tests whether a string is found inside another string. * - * @param str String to search in. - * @param substr Substring to find inside the original string. - * @param caseSensitive If true (default), search is case sensitive. - * If false, search is case insensitive. - * @return -1 on failure (no match found). Any other value - * indicates a position in the string where the match starts. + * @param str String to search in. + * @param substr Substring to find inside the original string. + * @param caseSensitive If true (default), search is case sensitive. + * If false, search is case insensitive. + * @return -1 on failure (no match found). Any other value + * indicates a position in the string where the match starts. */ native int StrContains(const char[] str, const char[] substr, bool caseSensitive=true); /** * Compares two strings lexographically. * - * @param str1 First string (left). - * @param str2 Second string (right). - * @param caseSensitive If true (default), comparison is case sensitive. - * If false, comparison is case insensitive. - * @return -1 if str1 < str2 - * 0 if str1 == str2 - * 1 if str1 > str2 + * @param str1 First string (left). + * @param str2 Second string (right). + * @param caseSensitive If true (default), comparison is case sensitive. + * If false, comparison is case insensitive. + * @return -1 if str1 < str2 + * 0 if str1 == str2 + * 1 if str1 > str2 */ native int strcmp(const char[] str1, const char[] str2, bool caseSensitive=true); /** * Compares two strings parts lexographically. * - * @param str1 First string (left). - * @param str2 Second string (right). - * @param num Number of characters to compare. - * @param caseSensitive If true (default), comparison is case sensitive. - * If false, comparison is case insensitive. - * @return -1 if str1 < str2 - * 0 if str1 == str2 - * 1 if str1 > str2 + * @param str1 First string (left). + * @param str2 Second string (right). + * @param num Number of characters to compare. + * @param caseSensitive If true (default), comparison is case sensitive. + * If false, comparison is case insensitive. + * @return -1 if str1 < str2 + * 0 if str1 == str2 + * 1 if str1 > str2 */ native int strncmp(const char[] str1, const char[] str2, int num, bool caseSensitive=true); /** * Backwards compatible stock - StrCompare is now strcmp - * @deprecated Renamed to strcmp + * @deprecated Renamed to strcmp */ #pragma deprecated Use strcmp() instead stock int StrCompare(const char[] str1, const char[] str2, bool caseSensitive=true) @@ -102,11 +102,11 @@ stock int StrCompare(const char[] str1, const char[] str2, bool caseSensitive=tr /** * Returns whether two strings are equal. * - * @param str1 First string (left). - * @param str2 Second string (right). - * @param caseSensitive If true (default), comparison is case sensitive. - * If false, comparison is case insensitive. - * @return True if equal, false otherwise. + * @param str1 First string (left). + * @param str2 Second string (right). + * @param caseSensitive If true (default), comparison is case sensitive. + * If false, comparison is case insensitive. + * @return True if equal, false otherwise. */ stock bool StrEqual(const char[] str1, const char[] str2, bool caseSensitive=true) { @@ -118,16 +118,16 @@ stock bool StrEqual(const char[] str1, const char[] str2, bool caseSensitive=tru * @note If the destination buffer is too small to hold the source string, the * destination will be truncated. * - * @param dest Destination string buffer to copy to. - * @param destLen Destination buffer length (includes null terminator). - * @param source Source string buffer to copy from. - * @return Number of cells written. + * @param dest Destination string buffer to copy to. + * @param destLen Destination buffer length (includes null terminator). + * @param source Source string buffer to copy from. + * @return Number of cells written. */ native int strcopy(char[] dest, int destLen, const char[] source); /** * Backwards compatibility stock - use strcopy - * @deprecated Renamed to strcopy + * @deprecated Renamed to strcopy */ #pragma deprecated Use strcopy() instead stock int StrCopy(char[] dest, int destLen, const char[] source) @@ -138,11 +138,11 @@ stock int StrCopy(char[] dest, int destLen, const char[] source) /** * Formats a string according to the SourceMod format rules (see documentation). * - * @param buffer Destination string buffer. - * @param maxlength Maximum length of output string buffer. - * @param format Formatting rules. - * @param ... Variable number of format parameters. - * @return Number of cells written. + * @param buffer Destination string buffer. + * @param maxlength Maximum length of output string buffer. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @return Number of cells written. */ native int Format(char[] buffer, int maxlength, const char[] format, any ...); @@ -152,11 +152,11 @@ native int Format(char[] buffer, int maxlength, const char[] format, any ...); * overlap the same memory as the output buffer. Since this security * check is removed, it is slightly faster. * - * @param buffer Destination string buffer. - * @param maxlength Maximum length of output string buffer. - * @param format Formatting rules. - * @param ... Variable number of format parameters. - * @return Number of cells written. + * @param buffer Destination string buffer. + * @param maxlength Maximum length of output string buffer. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @return Number of cells written. */ native int FormatEx(char[] buffer, int maxlength, const char[] format, any ...); @@ -166,68 +166,68 @@ native int FormatEx(char[] buffer, int maxlength, const char[] format, any ...); * parent parameter stack, rather than a local. This is useful for * implementing your own variable argument functions. * - * @param buffer Destination string buffer. - * @param maxlength Maximum length of output string buffer. - * @param format Formatting rules. - * @param varpos Argument number which contains the '...' symbol. - * Note: Arguments start at 1. - * @return Number of bytes written. + * @param buffer Destination string buffer. + * @param maxlength Maximum length of output string buffer. + * @param format Formatting rules. + * @param varpos Argument number which contains the '...' symbol. + * Note: Arguments start at 1. + * @return Number of bytes written. */ native int VFormat(char[] buffer, int maxlength, const char[] format, int varpos); /** * Converts a string to an integer. * - * @param str String to convert. - * @param nBase Numerical base to use. 10 is default. - * @return Integer conversion of string, or 0 on failure. + * @param str String to convert. + * @param nBase Numerical base to use. 10 is default. + * @return Integer conversion of string, or 0 on failure. */ native int StringToInt(const char[] str, int nBase=10); /** * Converts a string to an integer with some more options. * - * @param str String to convert. - * @param result Variable to store the result in. - * @param nBase Numerical base to use. 10 is default. - * @return Number of characters consumed. + * @param str String to convert. + * @param result Variable to store the result in. + * @param nBase Numerical base to use. 10 is default. + * @return Number of characters consumed. */ native int StringToIntEx(const char[] str, int &result, int nBase=10); /** * Converts an integer to a string. * - * @param num Integer to convert. - * @param str Buffer to store string in. - * @param maxlength Maximum length of string buffer. - * @return Number of cells written to buffer. + * @param num Integer to convert. + * @param str Buffer to store string in. + * @param maxlength Maximum length of string buffer. + * @return Number of cells written to buffer. */ native int IntToString(int num, char[] str, int maxlength); /** * Converts a string to a floating point number. * - * @param str String to convert to a float. - * @return Floating point result, or 0.0 on error. + * @param str String to convert to a float. + * @return Floating point result, or 0.0 on error. */ native float StringToFloat(const char[] str); /** * Converts a string to a floating point number with some more options. * - * @param str String to convert to a float. - * @param result Variable to store result in. - * @return Number of characters consumed. + * @param str String to convert to a float. + * @param result Variable to store result in. + * @return Number of characters consumed. */ native int StringToFloatEx(const char[] str, float &result); /** * Converts a floating point number to a string. * - * @param num Floating point number to convert. - * @param str Buffer to store string in. - * @param maxlength Maximum length of string buffer. - * @return Number of cells written to buffer. + * @param num Floating point number to convert. + * @param str Buffer to store string in. + * @param maxlength Maximum length of string buffer. + * @return Number of cells written to buffer. */ native int FloatToString(float num, char[] str, int maxlength); @@ -238,16 +238,16 @@ native int FloatToString(float num, char[] str, int maxlength); * of the string is reached. If nothing remains, -1 is returned. * Otherwise, the index to the first character is returned. * - * @param source Source input string. - * @param arg Stores argument read from string. - * @param argLen Maximum length of argument buffer. - * @return Index to next piece of string, or -1 if none. + * @param source Source input string. + * @param arg Stores argument read from string. + * @param argLen Maximum length of argument buffer. + * @return Index to next piece of string, or -1 if none. */ native int BreakString(const char[] source, char[] arg, int argLen); /** * Backwards compatibility stock - use BreakString - * @deprecated Renamed to BreakString. + * @deprecated Renamed to BreakString. */ #pragma deprecated Use BreakString() instead stock int StrBreak(const char[] source, char[] arg, int argLen) @@ -258,21 +258,21 @@ stock int StrBreak(const char[] source, char[] arg, int argLen) /** * Removes whitespace characters from the beginning and end of a string. * - * @param str The string to trim. - * @return Number of bytes written (UTF-8 safe). + * @param str The string to trim. + * @return Number of bytes written (UTF-8 safe). */ native int TrimString(char[] str); /** * Returns text in a string up until a certain character sequence is reached. * - * @param source Source input string. - * @param split A string which specifies a search point to break at. - * @param part Buffer to store string part. - * @param partLen Maximum length of the string part buffer. - * @return -1 if no match was found; otherwise, an index into source - * marking the first index after the searched text. The - * index is always relative to the start of the input string. + * @param source Source input string. + * @param split A string which specifies a search point to break at. + * @param part Buffer to store string part. + * @param partLen Maximum length of the string part buffer. + * @return -1 if no match was found; otherwise, an index into source + * marking the first index after the searched text. The + * index is always relative to the start of the input string. */ native int SplitString(const char[] source, const char[] split, char[] part, int partLen); @@ -280,12 +280,12 @@ native int SplitString(const char[] source, const char[] split, char[] part, int * Given a string, replaces all occurrences of a search string with a * replacement string. * - * @param text String to perform search and replacements on. - * @param maxlength Maximum length of the string buffer. - * @param search String to search for. - * @param replace String to replace the search string with. - * @param caseSensitive If true (default), search is case sensitive. - * @return Number of replacements that were performed. + * @param text String to perform search and replacements on. + * @param maxlength Maximum length of the string buffer. + * @param search String to search for. + * @param replace String to replace the search string with. + * @param caseSensitive If true (default), search is case sensitive. + * @return Number of replacements that were performed. */ native int ReplaceString(char[] text, int maxlength, const char[] search, const char[] replace, bool caseSensitive=true); @@ -293,18 +293,18 @@ native int ReplaceString(char[] text, int maxlength, const char[] search, const * Given a string, replaces the first occurrence of a search string with a * replacement string. * - * @param text String to perform search and replacements on. - * @param maxlength Maximum length of the string buffer. - * @param search String to search for. - * @param replace String to replace the search string with. - * @param searchLen If higher than -1, its value will be used instead of - * a strlen() call on the search parameter. - * @param replaceLen If higher than -1, its value will be used instead of - * a strlen() call on the replace parameter. - * @param caseSensitive If true (default), search is case sensitive. - * @return Index into the buffer (relative to the start) from where - * the last replacement ended, or -1 if no replacements were - * made. + * @param text String to perform search and replacements on. + * @param maxlength Maximum length of the string buffer. + * @param search String to search for. + * @param replace String to replace the search string with. + * @param searchLen If higher than -1, its value will be used instead of + * a strlen() call on the search parameter. + * @param replaceLen If higher than -1, its value will be used instead of + * a strlen() call on the replace parameter. + * @param caseSensitive If true (default), search is case sensitive. + * @return Index into the buffer (relative to the start) from where + * the last replacement ended, or -1 if no replacements were + * made. */ native int ReplaceStringEx(char[] text, int maxlength, const char[] search, const char[] replace, int searchLen=-1, int replaceLen=-1, bool caseSensitive=true); @@ -313,8 +313,8 @@ native int ReplaceStringEx(char[] text, int maxlength, const char[] search, cons * for multi-byte characters (UTF-8). For normal ASCII characters, * this will return 1. * - * @param source Source input string. - * @return Number of bytes the current character uses. + * @param source Source input string. + * @return Number of bytes the current character uses. */ native int GetCharBytes(const char[] source); @@ -323,8 +323,8 @@ native int GetCharBytes(const char[] source); * * @note Multi-byte characters will always return false. * - * @param chr Character to test. - * @return True if character is alphabetical, otherwise false. + * @param chr Character to test. + * @return True if character is alphabetical, otherwise false. */ native bool IsCharAlpha(int chr); @@ -333,8 +333,8 @@ native bool IsCharAlpha(int chr); * * @note Multi-byte characters will always return false. * - * @param chr Character to test. - * @return True if character is numeric, otherwise false. + * @param chr Character to test. + * @return True if character is numeric, otherwise false. */ native bool IsCharNumeric(int chr); @@ -343,17 +343,17 @@ native bool IsCharNumeric(int chr); * * @note Multi-byte characters will always return false. * - * @param chr Character to test. - * @return True if character is whitespace, otherwise false. + * @param chr Character to test. + * @return True if character is whitespace, otherwise false. */ native bool IsCharSpace(int chr); /** * Returns if a character is multi-byte or not. * - * @param chr Character to test. - * @return 0 for a normal 7-bit ASCII character, - * otherwise number of bytes in multi-byte character. + * @param chr Character to test. + * @return 0 for a normal 7-bit ASCII character, + * otherwise number of bytes in multi-byte character. */ native int IsCharMB(int chr); @@ -362,8 +362,8 @@ native int IsCharMB(int chr); * * @note Multi-byte characters will always return false. * - * @param chr Character to test. - * @return True if character is uppercase, otherwise false. + * @param chr Character to test. + * @return True if character is uppercase, otherwise false. */ native bool IsCharUpper(int chr); @@ -372,8 +372,8 @@ native bool IsCharUpper(int chr); * * @note Multi-byte characters will always return false. * - * @param chr Character to test. - * @return True if character is lowercase, otherwise false. + * @param chr Character to test. + * @return True if character is lowercase, otherwise false. */ native bool IsCharLower(int chr); @@ -385,18 +385,18 @@ native bool IsCharLower(int chr); * exist. Otherwise, the string is left unmodified. This function should * be considered O(k) (all characters get shifted down). * - * @param text String to modify (in place). - * @return True if string was modified, false if there was no - * set of quotes. + * @param text String to modify (in place). + * @return True if string was modified, false if there was no + * set of quotes. */ native bool StripQuotes(char[] text); /** - * Returns a lowercase character to an uppercase character. + * Converts a lowercase character to its uppercase counterpart. * - * @param chr Character to convert. - * @return Uppercase character on success, - * no change on failure. + * @param chr Character to convert. + * @return Uppercase character on success, + * no change on failure. */ stock int CharToUpper(int chr) { @@ -404,15 +404,16 @@ stock int CharToUpper(int chr) { return (chr & ~(1<<5)); } + return chr; } /** - * Returns an uppercase character to a lowercase character. + * Converts an uppercase character to its lowercase counterpart. * - * @param chr Character to convert. - * @return Lowercase character on success, - * no change on failure. + * @param chr Character to convert. + * @return Lowercase character on success, + * no change on failure. */ stock int CharToLower(int chr) { @@ -420,32 +421,42 @@ stock int CharToLower(int chr) { return (chr | (1<<5)); } + return chr; } /** * Finds the first occurrence of a character in a string. * - * @param str String. - * @param c Character to search for. - * @param reverse False (default) to search forward, true to search - * backward. - * @return The index of the first occurrence of the character - * in the string, or -1 if the character was not found. + * @param str String. + * @param c Character to search for. + * @param reverse False (default) to search forward, true to search + * backward. + * @return The index of the first occurrence of the character + * in the string, or -1 if the character was not found. */ stock int FindCharInString(const char[] str, char c, bool reverse = false) { int len = strlen(str); - if (!reverse) { - for (int i = 0; i < len; i++) { + if (!reverse) + { + for (int i = 0; i < len; i++) + { if (str[i] == c) + { return i; + } } - } else { - for (int i = len - 1; i >= 0; i--) { + } + else + { + for (int i = len - 1; i >= 0; i--) + { if (str[i] == c) + { return i; + } } } @@ -455,10 +466,10 @@ stock int FindCharInString(const char[] str, char c, bool reverse = false) /** * Concatenates one string onto another. * - * @param buffer String to append to. - * @param maxlength Maximum length of entire buffer. - * @param source Source string to concatenate. - * @return Number of bytes written. + * @param buffer String to append to. + * @param maxlength Maximum length of entire buffer. + * @param source Source string to concatenate. + * @return Number of bytes written. */ stock int StrCat(char[] buffer, int maxlength, const char[] source) { @@ -474,14 +485,14 @@ stock int StrCat(char[] buffer, int maxlength, const char[] source) /** * Breaks a string into pieces and stores each piece into an array of buffers. * - * @param text The string to split. - * @param split The string to use as a split delimiter. - * @param buffers An array of string buffers (2D array). - * @param maxStrings Number of string buffers (first dimension size). - * @param maxStringLength Maximum length of each string buffer. - * @param copyRemainder False (default) discard excess pieces, true to ignore - * delimiters after last piece. - * @return Number of strings retrieved. + * @param text The string to split. + * @param split The string to use as a split delimiter. + * @param buffers An array of string buffers (2D array). + * @param maxStrings Number of string buffers (first dimension size). + * @param maxStringLength Maximum length of each string buffer. + * @param copyRemainder False (default) discard excess pieces, true to ignore + * delimiters after last piece. + * @return Number of strings retrieved. */ stock int ExplodeString(const char[] text, const char[] split, char[][] buffers, int maxStrings, int maxStringLength, bool copyRemainder = false) @@ -515,12 +526,12 @@ stock int ExplodeString(const char[] text, const char[] split, char[][] buffers, * Joins an array of strings into one string, with a "join" string inserted in * between each given string. This function complements ExplodeString. * - * @param strings An array of strings. - * @param numStrings Number of strings in the array. - * @param join The join string to insert between each string. - * @param buffer Output buffer to write the joined string to. - * @param maxLength Maximum length of the output buffer. - * @return Number of bytes written to the output buffer. + * @param strings An array of strings. + * @param numStrings Number of strings in the array. + * @param join The join string to insert between each string. + * @param buffer Output buffer to write the joined string to. + * @param maxLength Maximum length of the output buffer. + * @return Number of bytes written to the output buffer. */ stock int ImplodeStrings(const char[][] strings, int numStrings, const char[] join, char[] buffer, int maxLength) { diff --git a/addons/sourcemod/scripting/include/testing.inc b/addons/sourcemod/scripting/include/testing.inc index 561f068..8673379 100644 --- a/addons/sourcemod/scripting/include/testing.inc +++ b/addons/sourcemod/scripting/include/testing.inc @@ -41,9 +41,12 @@ stock void SetTestContext(const char[] context) stock void AssertEq(const char[] text, int cell1, int cell2) { TestNumber++; - if (cell1 == cell2) { + if (cell1 == cell2) + { PrintToServer("[%d] %s: %s == %d OK", TestNumber, TestContext, text, cell2); - } else { + } + else + { PrintToServer("[%d] %s FAIL: %s should be %d, got %d", TestNumber, TestContext, text, cell2, cell1); ThrowError("test %d (%s in %s) failed", TestNumber, text, TestContext); } @@ -52,9 +55,12 @@ stock void AssertEq(const char[] text, int cell1, int cell2) stock void AssertFalse(const char[] text, bool value) { TestNumber++; - if (!value) { + if (!value) + { PrintToServer("[%d] %s: %s == false OK", TestNumber, TestContext, text, value); - } else { + } + else + { PrintToServer("[%d] %s FAIL: %s should be false, got true", TestNumber, TestContext, text); ThrowError("test %d (%s in %s) failed", TestNumber, text, TestContext); } @@ -63,9 +69,12 @@ stock void AssertFalse(const char[] text, bool value) stock void AssertTrue(const char[] text, bool value) { TestNumber++; - if (value) { + if (value) + { PrintToServer("[%d] %s: %s == true OK", TestNumber, TestContext, text, value); - } else { + } + else + { PrintToServer("[%d] %s FAIL: %s should be true, got false", TestNumber, TestContext, text); ThrowError("test %d (%s in %s) failed", TestNumber, text, TestContext); } diff --git a/addons/sourcemod/scripting/include/textparse.inc b/addons/sourcemod/scripting/include/textparse.inc index d5c59b3..34e99e4 100644 --- a/addons/sourcemod/scripting/include/textparse.inc +++ b/addons/sourcemod/scripting/include/textparse.inc @@ -47,9 +47,9 @@ */ enum SMCResult { - SMCParse_Continue, /**< Continue parsing */ - SMCParse_Halt, /**< Stop parsing here */ - SMCParse_HaltFail /**< Stop parsing and return failure */ + SMCParse_Continue, /**< Continue parsing */ + SMCParse_Halt, /**< Stop parsing here */ + SMCParse_HaltFail /**< Stop parsing and return failure */ }; /** @@ -57,66 +57,77 @@ enum SMCResult */ enum SMCError { - SMCError_Okay = 0, /**< No error */ - SMCError_StreamOpen, /**< Stream failed to open */ - SMCError_StreamError, /**< The stream died... somehow */ - SMCError_Custom, /**< A custom handler threw an error */ - SMCError_InvalidSection1, /**< A section was declared without quotes, and had extra tokens */ - SMCError_InvalidSection2, /**< A section was declared without any header */ - SMCError_InvalidSection3, /**< A section ending was declared with too many unknown tokens */ - SMCError_InvalidSection4, /**< A section ending has no matching beginning */ - SMCError_InvalidSection5, /**< A section beginning has no matching ending */ - SMCError_InvalidTokens, /**< There were too many unidentifiable strings on one line */ - SMCError_TokenOverflow, /**< The token buffer overflowed */ - SMCError_InvalidProperty1, /**< A property was declared outside of any section */ + SMCError_Okay = 0, /**< No error */ + SMCError_StreamOpen, /**< Stream failed to open */ + SMCError_StreamError, /**< The stream died... somehow */ + SMCError_Custom, /**< A custom handler threw an error */ + SMCError_InvalidSection1, /**< A section was declared without quotes, and had extra tokens */ + SMCError_InvalidSection2, /**< A section was declared without any header */ + SMCError_InvalidSection3, /**< A section ending was declared with too many unknown tokens */ + SMCError_InvalidSection4, /**< A section ending has no matching beginning */ + SMCError_InvalidSection5, /**< A section beginning has no matching ending */ + SMCError_InvalidTokens, /**< There were too many unidentifiable strings on one line */ + SMCError_TokenOverflow, /**< The token buffer overflowed */ + SMCError_InvalidProperty1 /**< A property was declared outside of any section */ }; -// Called when parsing is started. -// -// @param smc The SMC Parse Handle. +/** + * Called when parsing is started. + * + * @param smc The SMC Parse Handle. + */ typedef SMC_ParseStart = function void (SMCParser smc); -// Called when the parser is entering a new section or sub-section. -// -// Note: Enclosing quotes are always stripped. -// -// @param smc The SMC Parser. -// @param name String containing section name. -// @param opt_quotes True if the section name was quote-enclosed in the file. -// @return An SMCResult action to take. +/** + * Called when the parser is entering a new section or sub-section. + * + * Note: Enclosing quotes are always stripped. + * + * @param smc The SMC Parser. + * @param name String containing section name. + * @param opt_quotes True if the section name was quote-enclosed in the file. + * @return An SMCResult action to take. + */ typedef SMC_NewSection = function SMCResult (SMCParser smc, const char[] name, bool opt_quotes); -// Called when the parser finds a new key/value pair. -// -// Note: Enclosing quotes are always stripped. -// -// @param smc The SMCParser. -// @param key String containing key name. -// @param value String containing value name. -// @param key_quotes Whether or not the key was enclosed in quotes. -// @param value_quotes Whether or not the value was enclosed in quotes. -// @return An SMCResult action to take. +/** + * Called when the parser finds a new key/value pair. + * + * Note: Enclosing quotes are always stripped. + * + * @param smc The SMCParser. + * @param key String containing key name. + * @param value String containing value name. + * @param key_quotes Whether or not the key was enclosed in quotes. + * @param value_quotes Whether or not the value was enclosed in quotes. + * @return An SMCResult action to take. + */ typedef SMC_KeyValue = function SMCResult (SMCParser smc, const char[] key, const char[] value, bool key_quotes, bool value_quotes); -// Called when the parser finds the end of the current section. -// -// @param smc The SMCParser. -// @return An SMCResult action to take. +/** Called when the parser finds the end of the current section. + * + * @param smc The SMCParser. + * @return An SMCResult action to take. + */ typedef SMC_EndSection = function SMCResult (SMCParser smc); -// Called when parsing is halted. -// -// @param smc The SMCParser. -// @param halted True if abnormally halted, false otherwise. -// @param failed True if parsing failed, false otherwise. +/** + * Called when parsing is halted. + * + * @param smc The SMCParser. + * @param halted True if abnormally halted, false otherwise. + * @param failed True if parsing failed, false otherwise. + */ typedef SMC_ParseEnd = function void (SMCParser smc, bool halted, bool failed); -// Callback for whenever a new line of text is about to be parsed. -// -// @param smc The SMCParser. -// @param line A string containing the raw line from the file. -// @param lineno The line number it occurs on. -// @return An SMCResult action to take. +/** + * Callback for whenever a new line of text is about to be parsed. + * + * @param smc The SMCParser. + * @param line A string containing the raw line from the file. + * @param lineno The line number it occurs on. + * @return An SMCResult action to take. + */ typedef SMC_RawLine = function SMCResult (SMCParser smc, const char[] line, int lineno); // An SMCParser is a callback-driven parser for SourceMod configuration files. @@ -130,10 +141,10 @@ methodmap SMCParser < Handle // Parses an SMC file. // - // @param file A string containing the file path. - // @param line An optional variable to store the last line number read. - // @param col An optional variable to store the last column number read. - // @return An SMCParseError result. + // @param file A string containing the file path. + // @param line An optional variable to store the last line number read. + // @param col An optional variable to store the last column number read. + // @return An SMCParseError result. public native SMCError ParseFile(const char[] file, int &line = 0, int &col = 0); // Sets the callback for receiving SMC_ParseStart events. @@ -168,76 +179,77 @@ methodmap SMCParser < Handle // Gets an error string for an SMCError code. // - // @param error The SMCParseError code. - // @param buffer A string buffer for the error (contents undefined on failure). - // @param buf_max The maximum size of the buffer. - // @return The number of characters written to buffer. + // @param error The SMCParseError code. + // @param buffer A string buffer for the error (contents undefined on failure). + // @param buf_max The maximum size of the buffer. + // @return The number of characters written to buffer. public native void GetErrorString(SMCError error, char[] buffer, int buf_max); }; /** * Creates a new SMC file format parser. This is used to set parse hooks. * - * @return A new Handle to an SMC Parse structure. + * @return A new Handle to an SMC Parse structure. */ native SMCParser SMC_CreateParser(); /** * Parses an SMC file. * - * @param smc A Handle to an SMC Parse structure. - * @param file A string containing the file path. - * @param line An optional by reference cell to store the last line number read. - * @param col An optional by reference cell to store the last column number read. - * @return An SMCParseError result. - * @error Invalid or corrupt Handle. + * @param smc A Handle to an SMC Parse structure. + * @param file A string containing the file path. + * @param line An optional by reference cell to store the last line number read. + * @param col An optional by reference cell to store the last column number read. + * @return An SMCParseError result. + * @error Invalid or corrupt Handle. */ native SMCError SMC_ParseFile(Handle smc, const char[] file, int &line=0, int &col=0); /** * Gets an error string for an SMCError code. + * * @note SMCError_Okay returns false. * @note SMCError_Custom (which is thrown on SMCParse_HaltFail) returns false. * - * @param error The SMCParseError code. - * @param buffer A string buffer for the error (contents undefined on failure). - * @param buf_max The maximum size of the buffer. - * @return True on success, false otherwise. + * @param error The SMCParseError code. + * @param buffer A string buffer for the error (contents undefined on failure). + * @param buf_max The maximum size of the buffer. + * @return True on success, false otherwise. */ native bool SMC_GetErrorString(SMCError error, char[] buffer, int buf_max); /** * Sets the SMC_ParseStart function of a parse Handle. * - * @param smc Handle to an SMC Parse. - * @param func SMC_ParseStart function. - * @error Invalid or corrupt Handle. + * @param smc Handle to an SMC Parse. + * @param func SMC_ParseStart function. + * @error Invalid or corrupt Handle. */ native void SMC_SetParseStart(Handle smc, SMC_ParseStart func); /** * Sets the SMC_ParseEnd of a parse handle. * - * @param smc Handle to an SMC Parse. - * @param func SMC_ParseEnd function. - * @error Invalid or corrupt Handle. + * @param smc Handle to an SMC Parse. + * @param func SMC_ParseEnd function. + * @error Invalid or corrupt Handle. */ native void SMC_SetParseEnd(Handle smc, SMC_ParseEnd func); /** * Sets the three main reader functions. * - * @param smc An SMC parse Handle. - * @param ns An SMC_NewSection function pointer. - * @param kv An SMC_KeyValue function pointer. - * @param es An SMC_EndSection function pointer. + * @param smc An SMC parse Handle. + * @param ns An SMC_NewSection function pointer. + * @param kv An SMC_KeyValue function pointer. + * @param es An SMC_EndSection function pointer. */ native void SMC_SetReaders(Handle smc, SMC_NewSection ns, SMC_KeyValue kv, SMC_EndSection es); /** * Sets a raw line reader on an SMC parser Handle. * - * @param smc Handle to an SMC Parse. - * @param func SMC_RawLine function. + * @param smc Handle to an SMC Parse. + * @param func SMC_RawLine function. */ native void SMC_SetRawLine(Handle smc, SMC_RawLine func); diff --git a/addons/sourcemod/scripting/include/tf2.inc b/addons/sourcemod/scripting/include/tf2.inc index eff91eb..6b8a535 100644 --- a/addons/sourcemod/scripting/include/tf2.inc +++ b/addons/sourcemod/scripting/include/tf2.inc @@ -35,14 +35,14 @@ #endif #define _tf2_included -#define TF_STUNFLAG_SLOWDOWN (1 << 0) /**< activates slowdown modifier */ -#define TF_STUNFLAG_BONKSTUCK (1 << 1) /**< bonk sound, stuck */ -#define TF_STUNFLAG_LIMITMOVEMENT (1 << 2) /**< disable forward/backward movement */ -#define TF_STUNFLAG_CHEERSOUND (1 << 3) /**< cheering sound */ -#define TF_STUNFLAG_NOSOUNDOREFFECT (1 << 5) /**< no sound or particle */ -#define TF_STUNFLAG_THIRDPERSON (1 << 6) /**< panic animation */ -#define TF_STUNFLAG_GHOSTEFFECT (1 << 7) /**< ghost particles */ -#define TF_STUNFLAG_SOUND (1 << 8) /**< sound */ +#define TF_STUNFLAG_SLOWDOWN (1 << 0) /**< activates slowdown modifier */ +#define TF_STUNFLAG_BONKSTUCK (1 << 1) /**< bonk sound, stuck */ +#define TF_STUNFLAG_LIMITMOVEMENT (1 << 2) /**< disable forward/backward movement */ +#define TF_STUNFLAG_CHEERSOUND (1 << 3) /**< cheering sound */ +#define TF_STUNFLAG_NOSOUNDOREFFECT (1 << 5) /**< no sound or particle */ +#define TF_STUNFLAG_THIRDPERSON (1 << 6) /**< panic animation */ +#define TF_STUNFLAG_GHOSTEFFECT (1 << 7) /**< ghost particles */ +#define TF_STUNFLAG_SOUND (1 << 8) /**< sound */ #define TF_STUNFLAGS_LOSERSTATE TF_STUNFLAG_SLOWDOWN|TF_STUNFLAG_NOSOUNDOREFFECT|TF_STUNFLAG_THIRDPERSON #define TF_STUNFLAGS_GHOSTSCARE TF_STUNFLAG_GHOSTEFFECT|TF_STUNFLAG_THIRDPERSON @@ -69,144 +69,144 @@ enum TFTeam TFTeam_Unassigned = 0, TFTeam_Spectator = 1, TFTeam_Red = 2, - TFTeam_Blue = 3 + TFTeam_Blue = 3 }; enum TFCond { - TFCond_Slowed = 0, - TFCond_Zoomed, - TFCond_Disguising, - TFCond_Disguised, - TFCond_Cloaked, - TFCond_Ubercharged, - TFCond_TeleportedGlow, - TFCond_Taunting, - TFCond_UberchargeFading, + TFCond_Slowed = 0, //0: Revving Minigun, Sniper Rifle. Gives zoomed/revved pose + TFCond_Zoomed, //1: Sniper Rifle zooming + TFCond_Disguising, //2: Disguise smoke + TFCond_Disguised, //3: Disguise + TFCond_Cloaked, //4: Cloak effect + TFCond_Ubercharged, //5: Invulnerability, removed when being healed or by another Uber effect + TFCond_TeleportedGlow, //6: Teleport trail effect + TFCond_Taunting, //7: Used for taunting, can remove to stop taunting + TFCond_UberchargeFading, //8: Invulnerability expiration effect TFCond_Unknown1, //9 - TFCond_CloakFlicker = 9, - TFCond_Teleporting, - TFCond_Kritzkrieged, + TFCond_CloakFlicker = 9, //9: Cloak flickering effect + TFCond_Teleporting, //10: Used for teleporting, does nothing applying + TFCond_Kritzkrieged, //11: Crit boost, removed when being healed or another Uber effect TFCond_Unknown2, //12 - TFCond_TmpDamageBonus = 12, - TFCond_DeadRingered, - TFCond_Bonked, - TFCond_Dazed, - TFCond_Buffed, - TFCond_Charging, - TFCond_DemoBuff, - TFCond_CritCola, - TFCond_InHealRadius, - TFCond_Healing, - TFCond_OnFire, - TFCond_Overhealed, - TFCond_Jarated, - TFCond_Bleeding, - TFCond_DefenseBuffed, - TFCond_Milked, - TFCond_MegaHeal, - TFCond_RegenBuffed, - TFCond_MarkedForDeath, - TFCond_NoHealingDamageBuff, - TFCond_SpeedBuffAlly, // 32 - TFCond_HalloweenCritCandy, - TFCond_CritCanteen, - TFCond_CritDemoCharge, - TFCond_CritHype, - TFCond_CritOnFirstBlood, - TFCond_CritOnWin, - TFCond_CritOnFlagCapture, - TFCond_CritOnKill, - TFCond_RestrictToMelee, - TFCond_DefenseBuffNoCritBlock, - TFCond_Reprogrammed, - TFCond_CritMmmph, - TFCond_DefenseBuffMmmph, - TFCond_FocusBuff, - TFCond_DisguiseRemoved, - TFCond_MarkedForDeathSilent, - TFCond_DisguisedAsDispenser, - TFCond_Sapped, - TFCond_UberchargedHidden, - TFCond_UberchargedCanteen, - TFCond_HalloweenBombHead, - TFCond_HalloweenThriller, - TFCond_RadiusHealOnDamage, - TFCond_CritOnDamage, - TFCond_UberchargedOnTakeDamage, - TFCond_UberBulletResist, - TFCond_UberBlastResist, - TFCond_UberFireResist, - TFCond_SmallBulletResist, - TFCond_SmallBlastResist, - TFCond_SmallFireResist, - TFCond_Stealthed, // 64 - TFCond_MedigunDebuff, - TFCond_StealthedUserBuffFade, - TFCond_BulletImmune, - TFCond_BlastImmune, - TFCond_FireImmune, - TFCond_PreventDeath, - TFCond_MVMBotRadiowave, - TFCond_HalloweenSpeedBoost, - TFCond_HalloweenQuickHeal, - TFCond_HalloweenGiant, - TFCond_HalloweenTiny, - TFCond_HalloweenInHell, - TFCond_HalloweenGhostMode, - TFCond_MiniCritOnKill, + TFCond_TmpDamageBonus = 12, //12: Temporary damage buff, something along with attribute 19 + TFCond_DeadRingered, //13: Dead Ringer damage resistance, gives TFCond_Cloaked + TFCond_Bonked, //14: Bonk! Atomic Punch effect + TFCond_Dazed, //15: Slow effect, can remove to remove stun effects + TFCond_Buffed, //16: Buff Banner mini-crits, icon, and glow + TFCond_Charging, //17: Forced forward, charge effect + TFCond_DemoBuff, //18: Eyelander eye glow + TFCond_CritCola, //19: Mini-crit effect + TFCond_InHealRadius, //20: Ring effect, rings disappear after a taunt ends + TFCond_Healing, //21: Used for healing, does nothing applying + TFCond_OnFire, //22: Ignite sound and vocals, can remove to remove afterburn + TFCond_Overhealed, //23: Used for overheal, does nothing applying + TFCond_Jarated, //24: Jarate effect + TFCond_Bleeding, //25: Bleed effect + TFCond_DefenseBuffed, //26: Battalion's Backup's defense, icon, and glow + TFCond_Milked, //27: Mad Milk effect + TFCond_MegaHeal, //28: Quick-Fix Ubercharge's knockback/stun immunity and visual effect + TFCond_RegenBuffed, //29: Concheror's speed boost, heal on hit, icon, and glow + TFCond_MarkedForDeath, //30: Fan o' War marked-for-death effect + TFCond_NoHealingDamageBuff, //31: Mini-crits, blocks healing, glow, no weapon mini-crit effects + TFCond_SpeedBuffAlly, //32: Disciplinary Action speed boost + TFCond_HalloweenCritCandy, //33: Halloween pumpkin crit-boost + TFCond_CritCanteen, //34: Crit-boost and doubles Sentry Gun fire-rate + TFCond_CritDemoCharge, //35: Crit glow, adds TFCond_Charging when charge meter is below 75% + TFCond_CritHype, //36: Soda Popper multi-jump effect + TFCond_CritOnFirstBlood, //37: Arena first blood crit-boost + TFCond_CritOnWin, //38: End-of-round crit-boost (May not remove correctly?) + TFCond_CritOnFlagCapture, //39: Intelligence capture crit-boost + TFCond_CritOnKill, //40: Crit-boost from crit-on-kill weapons + TFCond_RestrictToMelee, //41: Prevents switching once melee is out + TFCond_DefenseBuffNoCritBlock, //42: MvM Bomb Carrier defense buff (TFCond_DefenseBuffed without crit resistance) + TFCond_Reprogrammed, //43: No longer functions + TFCond_CritMmmph, //44: Phlogistinator crit-boost + TFCond_DefenseBuffMmmph, //45: Old Phlogistinator defense buff + TFCond_FocusBuff, //46: Hitman's Heatmaker no-unscope and faster Sniper charge + TFCond_DisguiseRemoved, //47: Enforcer damage bonus removed + TFCond_MarkedForDeathSilent, //48: Marked-for-death without sound effect + TFCond_DisguisedAsDispenser, //49: Dispenser disguise when crouching, max movement speed, sentries ignore player + TFCond_Sapped, //50: Sapper sparkle effect in MvM + TFCond_UberchargedHidden, //51: Out-of-bounds robot invulnerability effect + TFCond_UberchargedCanteen, //52: Invulnerability effect and Sentry Gun damage resistance + TFCond_HalloweenBombHead, //53: Bomb head effect (does not explode) + TFCond_HalloweenThriller, //54: Forced Thriller taunting + TFCond_RadiusHealOnDamage, //55: Radius healing, adds TFCond_InHealRadius, TFCond_Healing. Removed when a taunt ends, but this condition stays but does nothing + TFCond_CritOnDamage, //56: Miscellaneous crit-boost + TFCond_UberchargedOnTakeDamage, //57: Miscellaneous invulnerability + TFCond_UberBulletResist, //58: Vaccinator Uber bullet resistance + TFCond_UberBlastResist, //59: Vaccinator Uber blast resistance + TFCond_UberFireResist, //60: Vaccinator Uber fire resistance + TFCond_SmallBulletResist, //61: Vaccinator healing bullet resistance + TFCond_SmallBlastResist, //62: Vaccinator healing blast resistance + TFCond_SmallFireResist, //63: Vaccinator healing fire resistance + TFCond_Stealthed, //64: Cloaked until next attack + TFCond_MedigunDebuff, //65: Unknown + TFCond_StealthedUserBuffFade, //66: Cloaked, will appear for a few seconds on attack and cloak again + TFCond_BulletImmune, //67: Full bullet immunity + TFCond_BlastImmune, //68: Full blast immunity + TFCond_FireImmune, //69: Full fire immunity + TFCond_PreventDeath, //70: Survive to 1 health, then the condition is removed + TFCond_MVMBotRadiowave, //71: Stuns bots and applies radio effect + TFCond_HalloweenSpeedBoost, //72: Speed boost, non-melee fire rate and reload, infinite air jumps + TFCond_HalloweenQuickHeal, //73: Healing effect, adds TFCond_Healing along with TFCond_MegaHeal temporarily + TFCond_HalloweenGiant, //74: Double size, x10 max health increase, ammo regeneration, and forced thirdperson + TFCond_HalloweenTiny, //75: Half size and increased head size + TFCond_HalloweenInHell, //76: Applies TFCond_HalloweenGhostMode when the player dies + TFCond_HalloweenGhostMode, //77: Becomes a ghost unable to attack but can fly + TFCond_MiniCritOnKill, //78: Mini-crits effect TFCond_DodgeChance, //79 - TFCond_ObscuredSmoke = 79, - TFCond_Parachute, - TFCond_BlastJumping, - TFCond_HalloweenKart, - TFCond_HalloweenKartDash, - TFCond_BalloonHead, - TFCond_MeleeOnly, - TFCond_SwimmingCurse, + TFCond_ObscuredSmoke = 79, //79: 75% chance to dodge an attack + TFCond_Parachute, //80: Parachute effect, removed when touching the ground + TFCond_BlastJumping, //81: Player is blast jumping + TFCond_HalloweenKart, //82: Player forced into a Halloween kart + TFCond_HalloweenKartDash, //83: Forced forward if in TFCond_HalloweenKart, zoom in effect, and dash animations + TFCond_BalloonHead, //84: Big head and lowered gravity + TFCond_MeleeOnly, //85: Forced melee, along with TFCond_SpeedBuffAlly and TFCond_HalloweenTiny + TFCond_SwimmingCurse, //86: Swim in the air with Jarate overlay TFCond_HalloweenKartNoTurn, //87 - TFCond_FreezeInput = 87, - TFCond_HalloweenKartCage, - TFCond_HasRune, - TFCond_RuneStrength, - TFCond_RuneHaste, - TFCond_RuneRegen, - TFCond_RuneResist, - TFCond_RuneVampire, - TFCond_RuneWarlock, - TFCond_RunePrecision, // 96 - TFCond_RuneAgility, - TFCond_GrapplingHook, - TFCond_GrapplingHookSafeFall, - TFCond_GrapplingHookLatched, - TFCond_GrapplingHookBleeding, - TFCond_AfterburnImmune, - TFCond_RuneKnockout, - TFCond_RuneImbalance, - TFCond_CritRuneTemp, - TFCond_PasstimeInterception, - TFCond_SwimmingNoEffects, - TFCond_EyeaductUnderworld, - TFCond_KingRune, - TFCond_PlagueRune, - TFCond_SupernovaRune, - TFCond_Plague, - TFCond_KingAura, - TFCond_SpawnOutline, //114 - TFCond_KnockedIntoAir, - TFCond_CompetitiveWinner, - TFCond_CompetitiveLoser, - TFCond_NoTaunting_DEPRECATED, - TFCond_HealingDebuff = 118, - TFCond_PasstimePenaltyDebuff, - TFCond_GrappledToPlayer, - TFCond_GrappledByPlayer, - TFCond_ParachuteDeployed, - TFCond_Gas, - TFCond_BurningPyro, - TFCond_RocketPack, - TFCond_LostFooting, - TFCond_AirCurrent, + TFCond_FreezeInput = 87, //87: Prevents player from using controls + TFCond_HalloweenKartCage, //88: Puts a cage around the player if in TFCond_HalloweenKart, otherwise crashes + TFCond_HasRune, //89: Has a powerup + TFCond_RuneStrength, //90: Double damage and no damage falloff + TFCond_RuneHaste, //91: Double fire rate, reload speed, clip and ammo size, and 30% faster movement speed + TFCond_RuneRegen, //92: Regen ammo, health, and metal + TFCond_RuneResist, //93: Takes 1/2 damage and critical immunity + TFCond_RuneVampire, //94: Takes 3/4 damage, gain health on damage, and 40% increase in max health + TFCond_RuneWarlock, //95: Attacker takes damage and knockback on hitting the player and 50% increase in max health + TFCond_RunePrecision, //96: Less bullet spread, no damage falloff, 250% faster projectiles, and double damage, faster charge, and faster re-zoom for Sniper Rifles + TFCond_RuneAgility, //97: Increased movement speed, grappling hook speed, jump height, and instant weapon switch + TFCond_GrapplingHook, //98: Used when a player fires their grappling hook, no effect applying or removing + TFCond_GrapplingHookSafeFall, //99: Used when a player is pulled by their grappling hook, no effect applying or removing + TFCond_GrapplingHookLatched, //100: Used when a player latches onto a wall, no effect applying or removing + TFCond_GrapplingHookBleeding, //101: Used when a player is hit by attacker's grappling hook + TFCond_AfterburnImmune, //102: Deadringer afterburn immunity + TFCond_RuneKnockout, //103: Melee and grappling hook only, increased max health, knockback immunity, x4 more damage against buildings, and knockbacks a powerup off a victim on hit + TFCond_RuneImbalance, //104: Prevents gaining a crit-boost or Uber powerups + TFCond_CritRuneTemp, //105: Crit-boost effect + TFCond_PasstimeInterception, //106: Used when a player intercepts the Jack/Ball + TFCond_SwimmingNoEffects, //107: Swimming in the air without animations or overlay + TFCond_EyeaductUnderworld, //108: Refills max health, short Uber, escaped the underworld message on removal + TFCond_KingRune, //109: Increased max health and applies TFCond_KingAura + TFCond_PlagueRune, //110: Radius health kit stealing, increased max health, TFCond_Plague on touching a victim + TFCond_SupernovaRune, //111: Charge meter passively increasing, when charged activiated causes radius Bonk stun + TFCond_Plague, //112: Plague sound effect and message, blocks King powerup health regen + TFCond_KingAura, //113: Increased fire rate, reload speed, and health regen to players in a radius + TFCond_SpawnOutline, //114: Outline and health meter of teammates (and disguised spies) + TFCond_KnockedIntoAir, //115: Used when a player is airblasted + TFCond_CompetitiveWinner, //116: Unknown + TFCond_CompetitiveLoser, //117: Unknown + TFCond_NoTaunting_DEPRECATED, //118 + TFCond_HealingDebuff = 118, //118: Healing debuff from Medics and dispensers + TFCond_PasstimePenaltyDebuff, //119: Marked-for-death effect + TFCond_GrappledToPlayer, //120: Prevents taunting and some Grappling Hook actions + TFCond_GrappledByPlayer, //121: Unknown + TFCond_ParachuteDeployed, //122: Parachute deployed, prevents reopening it + TFCond_Gas, //123: Gas Passer effect + TFCond_BurningPyro, //124: Dragon's Fury afterburn on Pyros + TFCond_RocketPack, //125: Thermal Thruster launched effects, prevents reusing + TFCond_LostFooting, //126: Less ground friction + TFCond_AirCurrent //127: Reduced air control and friction }; const float TFCondDuration_Infinite = -1.0; @@ -245,57 +245,60 @@ enum TFObjectMode }; /** - * Sets a client on fire for 10 seconds. + * Sets a client on fire. * - * @param client Player's index. - * @param attacker Attacker's index. - * @error Invalid client index, client not in game, or no mod support. + * @note Fire duration is capped to 10 seconds. + * + * @param client Player's index. + * @param attacker Attacker's index. + * @param duration Duration of fire (in seconds). + * @error Invalid client index, client not in game, or no mod support. */ -native void TF2_IgnitePlayer(int client, int attacker); +native void TF2_IgnitePlayer(int client, int attacker, float duration=10.0); /** * Respawns a client * - * @param client Player's index. - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @error Invalid client index, client not in game, or no mod support. */ native void TF2_RespawnPlayer(int client); /** * Regenerates a client's health and ammunition * - * @param client Player's index. - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @error Invalid client index, client not in game, or no mod support. */ native void TF2_RegeneratePlayer(int client); /** * Adds a condition to a player * - * @param client Player's index. - * @param condition Integer identifier of condition to apply. - * @param duration Duration of condition (does not apply to all conditions). + * @param client Player's index. + * @param condition Integer identifier of condition to apply. + * @param duration Duration of condition (does not apply to all conditions). * Pass TFCondDuration_Infinite to apply until manually removed. - * @param inflictor Condition inflictor's index (0 for no inflictor). - * @error Invalid client index, client not in game, or no mod support. + * @param inflictor Condition inflictor's index (0 for no inflictor). + * @error Invalid client index, client not in game, or no mod support. */ native void TF2_AddCondition(int client, TFCond condition, float duration=TFCondDuration_Infinite, int inflictor=0); /** * Removes a condition from a player * - * @param client Player's index. - * @param condition Integer identifier of condition to remove. - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @param condition Integer identifier of condition to remove. + * @error Invalid client index, client not in game, or no mod support. */ native void TF2_RemoveCondition(int client, TFCond condition); /** * Enables/disables PowerPlay mode on a player. * - * @param client Player's index. - * @param enabled Whether to enable or disable PowerPlay on player. - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @param enabled Whether to enable or disable PowerPlay on player. + * @error Invalid client index, client not in game, or no mod support. */ native void TF2_SetPlayerPowerPlay(int client, bool enabled); @@ -304,47 +307,48 @@ native void TF2_SetPlayerPowerPlay(int client, bool enabled); * * Note: This only starts the disguise process and a delay occurs before the spy is fully disguised * - * @param client Player's index. - * @param team Team to disguise the player as (only TFTeam_Red and TFTeam_Blue have an effect) - * @param classType TFClassType class to disguise the player as - * @param target Specific target player to disguise as (0 for any) - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @param team Team to disguise the player as (only TFTeam_Red and TFTeam_Blue have an effect) + * @param classType TFClassType class to disguise the player as + * @param target Specific target player to disguise as (0 for any) + * @error Invalid client index, client not in game, or no mod support. */ native void TF2_DisguisePlayer(int client, TFTeam team, TFClassType classType, int target=0); /** * Removes the current disguise from a client. Only has an effect on spies. * - * @param client Player's index. - * @error Invalid client index, client not in game, or no mod support. + * @param client Player's index. + * @error Invalid client index, client not in game, or no mod support. */ native void TF2_RemovePlayerDisguise(int client); /** * Stuns a client * - * @param client Player's index. - * @param duration Duration of stun. - * @param slowdown Slowdown percent (as decimal, 0.00-1.00) - * Ignored if TF_STUNFLAG_SLOWDOWN is not set. - * @param stunflags Stun flags. - * @param attacker Attacker's index (0 is allowed for world). + * @param client Player's index. + * @param duration Duration of stun. + * @param slowdown Slowdown percent (as decimal, 0.00-1.00) + * Ignored if TF_STUNFLAG_SLOWDOWN is not set. + * @param stunflags Stun flags. + * @param attacker Attacker's index (0 is allowed for world). */ native void TF2_StunPlayer(int client, float duration, float slowdown=0.0, int stunflags, int attacker=0); /** * Induces the bleed effect on a client * - * @param client Player's index. - * @param attacker Attacker's index. - * @param duration Duration of bleeding (in seconds). + * @param client Player's index. + * @param attacker Attacker's index. + * @param duration Duration of bleeding (in seconds). */ native void TF2_MakeBleed(int client, int attacker, float duration); /** * Retrieves the entity index of the CPlayerResource entity * - * @return The current resource entity index. + * @return The current resource entity index. + * @deprecated Use GetPlayerResourceEntity instead */ #pragma deprecated Use GetPlayerResourceEntity instead native int TF2_GetResourceEntity(); @@ -352,8 +356,8 @@ native int TF2_GetResourceEntity(); /** * Finds the TFClassType for a given class name. * - * @param classname A classname string such as "sniper" or "demoman" - * @return A TFClassType constant. + * @param classname A classname string such as "sniper" or "demoman" + * @return A TFClassType constant. */ native TFClassType TF2_GetClass(const char[] classname); @@ -363,19 +367,19 @@ native TFClassType TF2_GetClass(const char[] classname); * action to override the decision with the value of 'result' * * @note Since critical shots are also calculated client side any changes made with - * this will not show for the shooter. Projectile weapons such as the rocketlauncher - * and demoman weapons will show a critical bullet but no critical sound effect. - * Bullet hits should appear as expected. + * this will not show for the shooter. Projectile weapons such as the rocketlauncher + * and demoman weapons will show a critical bullet but no critical sound effect. + * Bullet hits should appear as expected. * - * @param client Client Index. - * @param weapon Weapon entity Index. - * @param weaponname Classname of the weapon. - * @param result Buffer param for the result of the decision. + * @param client Client Index. + * @param weapon Weapon entity Index. + * @param weaponname Classname of the weapon. + * @param result Buffer param for the result of the decision. */ forward Action TF2_CalcIsAttackCritical(int client, int weapon, char[] weaponname, bool &result); /** - * @deprecated No longer called. Use TF2_OnIsHolidayActive. + * @deprecated No longer called. Use TF2_OnIsHolidayActive. */ #pragma deprecated No longer called. Use TF2_OnIsHolidayActive. forward Action TF2_OnGetHoliday(TFHoliday &holiday); @@ -385,17 +389,17 @@ forward Action TF2_OnGetHoliday(TFHoliday &holiday); * Return Plugin_Continue to let the original calculation or return a higher * action to override the decision with the value of 'result' * - * @param holiday Holiday being checked. - * @param result Buffer param for the result of the decision. - * @return Plugin_Continue for original calculation, higher value to use 'result'. + * @param holiday Holiday being checked. + * @param result Buffer param for the result of the decision. + * @return Plugin_Continue for original calculation, higher value to use 'result'. */ forward Action TF2_OnIsHolidayActive(TFHoliday holiday, bool &result); /** * Returns whether or not a holiday is active * - * @param holiday Holiday being checked. - * @return Boolean of whether or not the holiday is active. + * @param holiday Holiday being checked. + * @return Boolean of whether or not the holiday is active. */ native bool TF2_IsHolidayActive(TFHoliday holiday); @@ -403,7 +407,7 @@ native bool TF2_IsHolidayActive(TFHoliday holiday); * Returns whether or not a client (Player) is in a duel. * * @param client Client Index. - * @return Boolean of whether or not the client/player is dueling. + * @return Boolean of whether or not the client/player is dueling. */ native bool TF2_IsPlayerInDuel(int client); @@ -411,16 +415,16 @@ native bool TF2_IsPlayerInDuel(int client); * Removes an econ wearable (hat, misc, etc) from a player. * This also deletes the wearable entity. * - * @param client Client index. - * @param wearable Index of the wearable entity. - * @error Invalid client index, client not in game, invalid wearable entity, or no mod support. + * @param client Client index. + * @param wearable Index of the wearable entity. + * @error Invalid client index, client not in game, invalid wearable entity, or no mod support. */ native void TF2_RemoveWearable(int client, int wearable); /** * Called after a condition is added to a player * - * @param client Index of the client to which the condition is being added. + * @param client Index of the client to which the condition is being added. * @param condition Condition that is being added. */ forward void TF2_OnConditionAdded(int client, TFCond condition); @@ -428,8 +432,8 @@ forward void TF2_OnConditionAdded(int client, TFCond condition); /** * Called after a condition is removed from a player * - * @param client Index of the client to which the condition is being removed. - * @param condition Condition that is being removed. + * @param client Index of the client to which the condition is being removed. + * @param condition Condition that is being removed. */ forward void TF2_OnConditionRemoved(int client, TFCond condition); @@ -448,11 +452,11 @@ forward void TF2_OnWaitingForPlayersEnd(); * Return Plugin_Continue to let the original calculation or return a higher * action to override the decision with the value of 'result' * - * @param client Client index. - * @param teleporter Teleporter entity index. - * @param result Buffer param for the result of the decision. - * This is prepopulated with the game's original decision to let a player teleport. - * @return Plugin_Continue for original calculation, higher value to use 'result'. + * @param client Client index. + * @param teleporter Teleporter entity index. + * @param result Buffer param for the result of the decision. + * This is prepopulated with the game's original decision to let a player teleport. + * @return Plugin_Continue for original calculation, higher value to use 'result'. */ forward Action TF2_OnPlayerTeleport(int client, int teleporter, bool &result); diff --git a/addons/sourcemod/scripting/include/tf2_stocks.inc b/addons/sourcemod/scripting/include/tf2_stocks.inc index 53ee4a7..02c0054 100644 --- a/addons/sourcemod/scripting/include/tf2_stocks.inc +++ b/addons/sourcemod/scripting/include/tf2_stocks.inc @@ -166,6 +166,7 @@ enum { TF_CUSTOM_SLAP_KILL, TF_CUSTOM_CROC, TF_CUSTOM_TAUNTATK_GASBLAST, + TF_CUSTOM_AXTINGUISHER_BOOSTED }; // Weapon codes as used in some events, such as player_death @@ -280,7 +281,7 @@ enum { TF_WEAPON_SLAP, TF_WEAPON_JAR_GAS, TF_WEAPON_GRENADE_JAR_GAS, - TF_WEAPON_FLAME_BALL, + TF_WEAPON_FLAME_BALL }; // TF2 Weapon Loadout Slots @@ -352,9 +353,9 @@ static const char TFResourceNames[TFResourceType][] = /** * Gets a client's current team. * - * @param client Client index. - * @return Current TFTeam of client. - * @error Invalid client index. + * @param client Client index. + * @return Current TFTeam of client. + * @error Invalid client index. */ stock TFTeam TF2_GetClientTeam(int client) { @@ -376,9 +377,9 @@ stock void TF2_ChangeClientTeam(int client, TFTeam team) /** * Gets a client's current class. * - * @param client Player's index. - * @return Current TFClassType of player. - * @error Invalid client index. + * @param client Player's index. + * @return Current TFClassType of player. + * @error Invalid client index. */ stock TFClassType TF2_GetPlayerClass(int client) { @@ -390,11 +391,11 @@ stock TFClassType TF2_GetPlayerClass(int client) * * Note: If setting player class in a player spawn hook weapons should be set to false. * - * @param client Player's index. - * @param classType TFClassType class symbol. - * @param weapons This parameter is ignored. - * @param persistent If true, changes the player's desired class so the change stays after death. - * @error Invalid client index. + * @param client Player's index. + * @param classType TFClassType class symbol. + * @param weapons This parameter is ignored. + * @param persistent If true, changes the player's desired class so the change stays after death. + * @error Invalid client index. */ stock void TF2_SetPlayerClass(int client, TFClassType classType, bool weapons=true, bool persistent=true) { @@ -413,6 +414,7 @@ stock void TF2_SetPlayerClass(int client, TFClassType classType, bool weapons=tr * @param type ResourceType constant * @return Value or -1 on failure. * @error Invalid client index, client not in game or failed to find resource entity. + * @deprecated Use GetPlayerResourceEntity and GetEntProp instead. */ #pragma deprecated Use GetPlayerResourceEntity and GetEntProp instead stock int TF2_GetPlayerResourceData(int client, TFResourceType type) @@ -444,11 +446,12 @@ stock int TF2_GetPlayerResourceData(int client, TFResourceType type) * * Note: The game overwrites these values every frame, so changing them will have very little effect. * - * @param client Player's index. - * @param type ResourceType constant - * @param value Value to set. - * @return Value or -1 on failure. - * @error Invalid client index, client not in game or failed to find resource entity. + * @param client Player's index. + * @param type ResourceType constant + * @param value Value to set. + * @return Value or -1 on failure. + * @error Invalid client index, client not in game or failed to find resource entity. + * @deprecated Use GetPlayerResourceEntity and SetEntProp instead. */ #pragma deprecated Use GetPlayerResourceEntity and SetEntProp instead stock bool TF2_SetPlayerResourceData(int client, TFResourceType type, any value) @@ -480,9 +483,9 @@ stock bool TF2_SetPlayerResourceData(int client, TFResourceType type, any value) /** * Removes all weapons from a client's weapon slot * - * @param client Player's index. - * @param slot Slot index (0-5) - * @error Invalid client, invalid slot or lack of mod support + * @param client Player's index. + * @param slot Slot index (0-5) + * @error Invalid client, invalid slot or lack of mod support */ stock void TF2_RemoveWeaponSlot(int client, int slot) { @@ -511,7 +514,7 @@ stock void TF2_RemoveWeaponSlot(int client, int slot) /** * Removes all weapons from a client * - * @param client Player's index. + * @param client Player's index. */ stock void TF2_RemoveAllWeapons(int client) { @@ -524,8 +527,9 @@ stock void TF2_RemoveAllWeapons(int client) /** * Gets a player's condition bits * - * @param client Player's index. - * @return Player's condition bits + * @param client Player's index. + * @return Player's condition bits + * @deprecated Use TF2_IsPlayerInCondition instead. */ #pragma deprecated Use TF2_IsPlayerInCondition instead. stock int TF2_GetPlayerConditionFlags(int client) @@ -536,9 +540,9 @@ stock int TF2_GetPlayerConditionFlags(int client) /** * Check whether or not a condition is set on a player * - * @param client Player's index. - * @param cond TFCond constant - * @return True if set, false otherwise + * @param client Player's index. + * @param cond TFCond constant + * @return True if set, false otherwise */ stock bool TF2_IsPlayerInCondition(int client, TFCond cond) { @@ -546,7 +550,7 @@ stock bool TF2_IsPlayerInCondition(int client, TFCond cond) int iCond = view_as(cond); switch (iCond / 32) { - case 0: + case 0: { int bit = 1 << iCond; if ((GetEntProp(client, Prop_Send, "m_nPlayerCond") & bit) == bit) @@ -559,7 +563,7 @@ stock bool TF2_IsPlayerInCondition(int client, TFCond cond) return true; } } - case 1: + case 1: { int bit = (1 << (iCond - 32)); if ((GetEntProp(client, Prop_Send, "m_nPlayerCondEx") & bit) == bit) @@ -567,7 +571,7 @@ stock bool TF2_IsPlayerInCondition(int client, TFCond cond) return true; } } - case 2: + case 2: { int bit = (1 << (iCond - 64)); if ((GetEntProp(client, Prop_Send, "m_nPlayerCondEx2") & bit) == bit) @@ -575,7 +579,7 @@ stock bool TF2_IsPlayerInCondition(int client, TFCond cond) return true; } } - case 3: + case 3: { int bit = (1 << (iCond - 96)); if ((GetEntProp(client, Prop_Send, "m_nPlayerCondEx3") & bit) == bit) @@ -583,7 +587,7 @@ stock bool TF2_IsPlayerInCondition(int client, TFCond cond) return true; } } - case 4: + case 4: { int bit = (1 << (iCond - 128)); if ((GetEntProp(client, Prop_Send, "m_nPlayerCondEx4") & bit) == bit) @@ -591,8 +595,10 @@ stock bool TF2_IsPlayerInCondition(int client, TFCond cond) return true; } } - default: - ThrowError("Invalid TFCond value %d", iCond); + default: + { + ThrowError("Invalid TFCond value %d", iCond); + } } return false; @@ -601,9 +607,9 @@ stock bool TF2_IsPlayerInCondition(int client, TFCond cond) /** * Gets an entity's object type. * - * @param entity Entity index. - * @return Current TFObjectType of entity. - * @error Invalid entity index. + * @param entity Entity index. + * @return Current TFObjectType of entity. + * @error Invalid entity index. */ stock TFObjectType TF2_GetObjectType(int entity) { @@ -620,9 +626,9 @@ stock TFObjectType TF2_GetObjectType(int entity) /** * Gets an entity's object mode. * - * @param entity Entity index. - * @return Current TFObjectMode of entity. - * @error Invalid entity index. + * @param entity Entity index. + * @return Current TFObjectMode of entity. + * @error Invalid entity index. */ stock TFObjectMode TF2_GetObjectMode(int entity) { diff --git a/addons/sourcemod/scripting/include/timers.inc b/addons/sourcemod/scripting/include/timers.inc index 880bd07..2fb74d9 100644 --- a/addons/sourcemod/scripting/include/timers.inc +++ b/addons/sourcemod/scripting/include/timers.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -37,10 +37,10 @@ #include -#define TIMER_REPEAT (1<<0) /**< Timer will repeat until it returns Plugin_Stop */ -#define TIMER_FLAG_NO_MAPCHANGE (1<<1) /**< Timer will not carry over mapchanges */ -#define TIMER_HNDL_CLOSE (1<<9) /**< Deprecated define, replaced by below */ -#define TIMER_DATA_HNDL_CLOSE (1<<9) /**< Timer will automatically call CloseHandle() on its data when finished */ +#define TIMER_REPEAT (1<<0) /**< Timer will repeat until it returns Plugin_Stop */ +#define TIMER_FLAG_NO_MAPCHANGE (1<<1) /**< Timer will not carry over mapchanges */ +#define TIMER_HNDL_CLOSE (1<<9) /**< Deprecated define, replaced by below */ +#define TIMER_DATA_HNDL_CLOSE (1<<9) /**< Timer will automatically call CloseHandle() on its data when finished */ /** * Any of the following prototypes will work for a timed function. @@ -48,108 +48,108 @@ typeset Timer { /** - * Called when the timer interval has elapsed. - * - * @param timer Handle to the timer object. - * @param hndl Handle passed to CreateTimer() when timer was created. - * @return Plugin_Stop to stop a repeating timer, any other value for - * default behavior. - */ + * Called when the timer interval has elapsed. + * + * @param timer Handle to the timer object. + * @param hndl Handle passed to CreateTimer() when timer was created. + * @return Plugin_Stop to stop a repeating timer, any other value for + * default behavior. + */ function Action(Handle timer, Handle hndl); - + /** - * Called when the timer interval has elapsed. - * - * @param timer Handle to the timer object. - * @param data Data passed to CreateTimer() when timer was created. - * @return Plugin_Stop to stop a repeating timer, any other value for - * default behavior. - */ + * Called when the timer interval has elapsed. + * + * @param timer Handle to the timer object. + * @param data Data passed to CreateTimer() when timer was created. + * @return Plugin_Stop to stop a repeating timer, any other value for + * default behavior. + */ function Action(Handle timer, any data); - + /** - * Called when the timer interval has elapsed. - * - * @param timer Handle to the timer object. - * @return Plugin_Stop to stop a repeating timer, any other value for - * default behavior. - */ + * Called when the timer interval has elapsed. + * + * @param timer Handle to the timer object. + * @return Plugin_Stop to stop a repeating timer, any other value for + * default behavior. + */ function Action(Handle timer); }; /** * Creates a basic timer. Calling CloseHandle() on a timer will end the timer. * - * @param interval Interval from the current game time to execute the given function. - * @param func Function to execute once the given interval has elapsed. - * @param data Handle or value to pass through to the timer callback function. - * @param flags Flags to set (such as repeatability or auto-Handle closing). - * @return Handle to the timer object. You do not need to call CloseHandle(). - * If the timer could not be created, INVALID_HANDLE will be returned. + * @param interval Interval from the current game time to execute the given function. + * @param func Function to execute once the given interval has elapsed. + * @param data Handle or value to pass through to the timer callback function. + * @param flags Flags to set (such as repeatability or auto-Handle closing). + * @return Handle to the timer object. You do not need to call CloseHandle(). + * If the timer could not be created, INVALID_HANDLE will be returned. */ native Handle CreateTimer(float interval, Timer func, any data=INVALID_HANDLE, int flags=0); /** * Kills a timer. Use this instead of CloseHandle() if you need more options. * - * @param timer Timer Handle to kill. - * @param autoClose If autoClose is true, the data that was passed to CreateTimer() will - * be closed as a handle if TIMER_DATA_HNDL_CLOSE was not specified. - * @error Invalid handles will cause a run time error. + * @param timer Timer Handle to kill. + * @param autoClose If autoClose is true, the data that was passed to CreateTimer() will + * be closed as a handle if TIMER_DATA_HNDL_CLOSE was not specified. + * @error Invalid handles will cause a run time error. */ native void KillTimer(Handle timer, bool autoClose=false); /** * Manually triggers a timer so its function will be called. * - * @param timer Timer Handle to trigger. - * @param reset If reset is true, the elapsed time counter is reset - * so the full interval must pass again. + * @param timer Timer Handle to trigger. + * @param reset If reset is true, the elapsed time counter is reset + * so the full interval must pass again. */ native void TriggerTimer(Handle timer, bool reset=false); /** - * Returns the simulated game time. + * Returns the simulated game time. * - * This time is internally maintained by SourceMod and is based on the game - * tick count and tick rate. Unlike GetGameTime(), it will increment past - * map changes and while no players are connected. Unlike GetEngineTime(), - * it will not increment based on the system clock (i.e. it is still bound + * This time is internally maintained by SourceMod and is based on the game + * tick count and tick rate. Unlike GetGameTime(), it will increment past + * map changes and while no players are connected. Unlike GetEngineTime(), + * it will not increment based on the system clock (i.e. it is still bound * to the ticking process). * - * @return Time based on the game tick count. + * @return Time based on the game tick count. */ native float GetTickedTime(); /** - * Returns an estimate of the time left before the map ends. If the server - * has not processed any frames yet (i.e. no players have joined the map yet), + * Returns an estimate of the time left before the map ends. If the server + * has not processed any frames yet (i.e. no players have joined the map yet), * then the time left returned will always be infinite. * - * @param timeleft Variable to store the time, in seconds. If the - * value is less than 0, the time limit is infinite. - * @return True if the operation is supported, false otherwise. + * @param timeleft Variable to store the time, in seconds. If the + * value is less than 0, the time limit is infinite. + * @return True if the operation is supported, false otherwise. */ native bool GetMapTimeLeft(int &timeleft); /** - * Retrieves the current map time limit. If the server has not processed any - * frames yet (i.e. no players have joined the map yet), then the time limit + * Retrieves the current map time limit. If the server has not processed any + * frames yet (i.e. no players have joined the map yet), then the time limit * returned will always be 0. * - * @param time Set to the number of total seconds in the map time - * limit, or 0 if there is no time limit set. - * @return True on success, false if operation is not supported. + * @param time Set to the number of total seconds in the map time + * limit, or 0 if there is no time limit set. + * @return True on success, false if operation is not supported. */ native bool GetMapTimeLimit(int &time); /** * Extends the map time limit in a way that will notify all plugins. * - * @param time Number of seconds to extend map time limit by. - * The number can be negative to decrease the time limit. - * If 0, the map will be set to have no time limit. - * @return True on success, false if operation is not supported. + * @param time Number of seconds to extend map time limit by. + * The number can be negative to decrease the time limit. + * If 0, the map will be set to have no time limit. + * @return True on success, false if operation is not supported. */ native bool ExtendMapTimeLimit(int time); @@ -158,34 +158,34 @@ native bool ExtendMapTimeLimit(int time); * * Note: A tick, in this context, is a frame. * - * @return Number of seconds in between ticks. + * @return Number of seconds in between ticks. */ native float GetTickInterval(); /** - * Notification that the map's time left has changed via a change in the time - * limit or a change in the game rules (such as mp_restartgame). This is useful + * Notification that the map's time left has changed via a change in the time + * limit or a change in the game rules (such as mp_restartgame). This is useful * for plugins trying to create timers based on the time left in the map. * - * Calling ExtendMapTimeLimit() from here, without proper precaution, will + * Calling ExtendMapTimeLimit() from here, without proper precaution, will * cause infinite recursion. * * If the operation is not supported, this will never be called. - * If the server has not yet processed any frames (i.e. no players have joined - * the map yet), then this will be called once the server begins ticking, even + * If the server has not yet processed any frames (i.e. no players have joined + * the map yet), then this will be called once the server begins ticking, even * if there is no time limit set. */ forward void OnMapTimeLeftChanged(); /** - * Returns whether or not the server is processing frames or not. + * Returns whether or not the server is processing frames or not. * - * The server does not process frames until at least one client joins the game. - * Once the first player has in, even if that player, leaves, the server's + * The server does not process frames until at least one client joins the game. + * Once the first player has in, even if that player, leaves, the server's * timers and entities will work. * - * @return True if the server is ticking, false otherwise. + * @return True if the server is ticking, false otherwise. */ native bool IsServerProcessing(); @@ -194,12 +194,12 @@ native bool IsServerProcessing(); * @note The datapack is automatically freed when the timer ends. * @note The position of the datapack is not reset or changed for the timer function. * - * @param interval Interval from the current game time to execute the given function. - * @param func Function to execute once the given interval has elapsed. - * @param datapack The newly created datapack is passed though this by-reference - * parameter to the timer callback function. - * @param flags Timer flags. - * @return Handle to the timer object. You do not need to call CloseHandle(). + * @param interval Interval from the current game time to execute the given function. + * @param func Function to execute once the given interval has elapsed. + * @param datapack The newly created datapack is passed though this by-reference + * parameter to the timer callback function. + * @param flags Timer flags. + * @return Handle to the timer object. You do not need to call CloseHandle(). */ stock Handle CreateDataTimer(float interval, Timer func, Handle &datapack, int flags=0) { diff --git a/addons/sourcemod/scripting/include/topmenus.inc b/addons/sourcemod/scripting/include/topmenus.inc index d29cd78..bd1c6da 100644 --- a/addons/sourcemod/scripting/include/topmenus.inc +++ b/addons/sourcemod/scripting/include/topmenus.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -29,7 +29,7 @@ * * Version: $Id$ */ - + #if defined _topmenus_included #endinput #endif @@ -49,18 +49,18 @@ enum TopMenuAction * OUTPUT: Buffer for rendering, maxlength of buffer. */ TopMenuAction_DisplayOption = 0, - + /** * The title of a menu is being drawn for a given topobj. * - * Note: The Object ID will be INVALID_TOPMENUOBJECT if drawing the + * Note: The Object ID will be INVALID_TOPMENUOBJECT if drawing the * root title. Otherwise, the Object ID is a category. * * INPUT : TopMenu Handle, topobj ID, client index. * OUTPUT: Buffer for rendering, maxlength of buffer. */ TopMenuAction_DisplayTitle = 1, - + /** * A menu option has been selected. * @@ -74,19 +74,19 @@ enum TopMenuAction * A menu option is being drawn and its flags can be overridden. * * INPUT : TopMenu Handle, topobj ID, client index. - * OUTPUT: The first byte of the 'buffer' string should be set - * to the desired flags. By default, it will contain - * ITEMDRAW_DEFAULT. + * OUTPUT: The first byte of the 'buffer' string should be set + * to the desired flags. By default, it will contain + * ITEMDRAW_DEFAULT. */ TopMenuAction_DrawOption = 3, - + /** * Called when an topobj is being removed from the menu. * This can be used to clean up data stored in the info string. * * INPUT : TopMenu Handle, topobj ID. */ - TopMenuAction_RemoveObject = 4, + TopMenuAction_RemoveObject = 4 }; /** @@ -94,8 +94,8 @@ enum TopMenuAction */ enum TopMenuObjectType { - TopMenuObject_Category = 0, /**< Category (sub-menu branching from root) */ - TopMenuObject_Item = 1 /**< Item on a sub-menu */ + TopMenuObject_Category = 0, /**< Category (sub-menu branching from root) */ + TopMenuObject_Item = 1 /**< Item on a sub-menu */ }; /** @@ -103,9 +103,9 @@ enum TopMenuObjectType */ enum TopMenuPosition { - TopMenuPosition_Start = 0, /**< Start/root of the menu */ - TopMenuPosition_LastRoot = 1, /**< Last position in the root menu */ - TopMenuPosition_LastCategory = 3, /**< Last position in their last category */ + TopMenuPosition_Start = 0, /**< Start/root of the menu */ + TopMenuPosition_LastRoot = 1, /**< Last position in the root menu */ + TopMenuPosition_LastCategory = 3 /**< Last position in their last category */ }; /** @@ -113,21 +113,21 @@ enum TopMenuPosition */ enum TopMenuObject { - INVALID_TOPMENUOBJECT = 0, + INVALID_TOPMENUOBJECT = 0 }; /** * TopMenu callback prototype. * - * @param topmenu Handle to the TopMenu. - * @param action TopMenuAction being performed. - * @param topobj_id The topobj ID (if used). - * @param param Extra parameter (if used). - * @param buffer Output buffer (if used). - * @param maxlength Output buffer (if used). + * @param topmenu Handle to the TopMenu. + * @param action TopMenuAction being performed. + * @param topobj_id The topobj ID (if used). + * @param param Extra parameter (if used). + * @param buffer Output buffer (if used). + * @param maxlength Output buffer (if used). */ typedef TopMenuHandler = function void ( - TopMenu topmenu, + TopMenu topmenu, TopMenuAction action, TopMenuObject topobj_id, int param, @@ -152,18 +152,18 @@ methodmap TopMenu < Handle // Re-sorts the items in a TopMenu via a configuration file. // - // The format of the configuration file should be a Valve Key-Values - // formatted file that SourceMod can parse. There should be one root - // section, and one sub-section for each category. Each sub-section's + // The format of the configuration file should be a Valve Key-Values + // formatted file that SourceMod can parse. There should be one root + // section, and one sub-section for each category. Each sub-section's // name should match the category name. // // Each sub-section may only contain key/value pairs in the form of: // key: "item" // value: Name of the item as passed to AddToTopMenu(). // - // The TopMenu will draw items in the order declared in the configuration - // file. If items do not appear in the configuration file, they are sorted - // per-player based on how the handler function renders for that player. + // The TopMenu will draw items in the order declared in the configuration + // file. If items do not appear in the configuration file, they are sorted + // per-player based on how the handler function renders for that player. // These items appear after the configuration sorted items. // // @param topmenu TopMenu Handle. @@ -172,79 +172,79 @@ methodmap TopMenu < Handle // @param maxlength Maximum size of the error buffer. Error buffer // will be filled with a zero-terminated string if // false is returned. - // @return True on success, false on failure. + // @return True on success, false on failure. public native bool LoadConfig(const char[] file, char[] error, int maxlength); // Adds a category to a TopMenu. - // + // // @param name Object name (MUST be unique). // @param handler Handler for topobj. // @param cmdname Command name (for access overrides). // @param flags Default access flags. // @param info_string Arbitrary storage (max 255 bytes). - // @return A new TopMenuObject ID, or INVALID_TOPMENUOBJECT on failure. + // @return A new TopMenuObject ID, or INVALID_TOPMENUOBJECT on failure. public native TopMenuObject AddCategory(const char[] name, TopMenuHandler handler, const char[] cmdname = "", int flags = 0, const char[] info_string = ""); // Adds an item to a TopMenu category. - // + // // @param name Object name (MUST be unique). // @param handler Handler for topobj. // @param category The object of the parent category for the item. // @param cmdname Command name (for access overrides). // @param flags Default access flags. // @param info_string Arbitrary storage (max 255 bytes). - // @return A new TopMenuObject ID, or INVALID_TOPMENUOBJECT on failure. + // @return A new TopMenuObject ID, or INVALID_TOPMENUOBJECT on failure. public native TopMenuObject AddItem(const char[] name, TopMenuHandler handler, TopMenuObject parent, const char[] cmdname = "", int flags = 0, const char[] info_string = ""); // Retrieves the info string of a top menu item. - // + // // @param parent TopMenuObject ID. // @param buffer Buffer to store info string. // @param maxlength Maximum size of info string. - // @return Number of bytes written, not including the null terminator. + // @return Number of bytes written, not including the null terminator. public native int GetInfoString(TopMenuObject parent, char[] buffer, int maxlength); // Retrieves the name string of a top menu item. - // + // // @param topobj TopMenuObject ID. // @param buffer Buffer to store info string. // @param maxlength Maximum size of info string. - // @return Number of bytes written, not including the null terminator. + // @return Number of bytes written, not including the null terminator. public native int GetObjName(TopMenuObject topobj, char[] buffer, int maxlength); // Removes an topobj from a TopMenu. - // - // Plugins' topobjs are automatically removed all TopMenus when the given + // + // Plugins' topobjs are automatically removed all TopMenus when the given // plugin unloads or pauses. In the case of unpausing, all items are restored. - // + // // @param topobj TopMenuObject ID. public native void Remove(TopMenuObject topobj); // Displays a TopMenu to a client. - // + // // @param client Client index. // @param position Position to display from. - // @return True on success, false on failure. + // @return True on success, false on failure. public native bool Display(int client, TopMenuPosition position); // Displays a TopMenu category to a client. - // + // // @param category Category topobj id. // @param client Client index. - // @return True on success, false on failure. + // @return True on success, false on failure. public native bool DisplayCategory(TopMenuObject category, int client); // Finds a category's topobj ID in a TopMenu. - // + // // @param name Object's unique name. - // @return TopMenuObject ID on success, or + // @return TopMenuObject ID on success, or // INVALID_TOPMENUOBJECT on failure. public native TopMenuObject FindCategory(const char[] name); - + // Set the menu title caching behavior of the TopMenu. By default titles // are cached to reduce overhead. If you need dynamic menu titles which // change each time the menu is displayed to a user, set this to false. @@ -256,56 +256,56 @@ methodmap TopMenu < Handle /** * Creates a TopMenu. * - * @param handler Handler to use for drawing the root title. - * @return A new TopMenu Handle, or INVALID_HANDLE on failure. - */ + * @param handler Handler to use for drawing the root title. + * @return A new TopMenu Handle, or INVALID_HANDLE on failure. + */ native TopMenu CreateTopMenu(TopMenuHandler handler); /** * Re-sorts the items in a TopMenu via a configuration file. * - * The format of the configuration file should be a Valve Key-Values - * formatted file that SourceMod can parse. There should be one root - * section, and one sub-section for each category. Each sub-section's + * The format of the configuration file should be a Valve Key-Values + * formatted file that SourceMod can parse. There should be one root + * section, and one sub-section for each category. Each sub-section's * name should match the category name. * * Each sub-section may only contain key/value pairs in the form of: * key: "item" * value: Name of the item as passed to AddToTopMenu(). * - * The TopMenu will draw items in the order declared in the configuration - * file. If items do not appear in the configuration file, they are sorted - * per-player based on how the handler function renders for that player. + * The TopMenu will draw items in the order declared in the configuration + * file. If items do not appear in the configuration file, they are sorted + * per-player based on how the handler function renders for that player. * These items appear after the configuration sorted items. * - * @param topmenu TopMenu Handle. - * @param file File path. - * @param error Error buffer. - * @param maxlength Maximum size of the error buffer. - * Error buffer will be filled with a - * zero-terminated string if false is - * returned. - * @return True on success, false on failure. - * @error Invalid TopMenu Handle. + * @param topmenu TopMenu Handle. + * @param file File path. + * @param error Error buffer. + * @param maxlength Maximum size of the error buffer. + * Error buffer will be filled with a + * zero-terminated string if false is + * returned. + * @return True on success, false on failure. + * @error Invalid TopMenu Handle. */ native bool LoadTopMenuConfig(Handle topmenu, const char[] file, char[] error, int maxlength); /** * Adds an topobj to a TopMenu. * - * @param topmenu TopMenu Handle. - * @param name Object name (MUST be unique). - * @param type Object type. - * @param handler Handler for topobj. - * @param parent Parent topobj ID, or INVALID_TOPMENUOBJECT for none. - * Items must have a category parent. - * Categories must not have a parent. - * @param cmdname Command name (for access overrides). - * @param flags Default access flags. - * @param info_string Arbitrary storage (max 255 bytes). - * @return A new TopMenuObject ID, or INVALID_TOPMENUOBJECT on - * failure. - * @error Invalid TopMenu Handle. + * @param topmenu TopMenu Handle. + * @param name Object name (MUST be unique). + * @param type Object type. + * @param handler Handler for topobj. + * @param parent Parent topobj ID, or INVALID_TOPMENUOBJECT for none. + * Items must have a category parent. + * Categories must not have a parent. + * @param cmdname Command name (for access overrides). + * @param flags Default access flags. + * @param info_string Arbitrary storage (max 255 bytes). + * @return A new TopMenuObject ID, or INVALID_TOPMENUOBJECT on + * failure. + * @error Invalid TopMenu Handle. */ native TopMenuObject AddToTopMenu(Handle topmenu, const char[] name, @@ -315,75 +315,75 @@ native TopMenuObject AddToTopMenu(Handle topmenu, const char[] cmdname="", int flags=0, const char[] info_string=""); - + /** * Retrieves the info string of a top menu item. * - * @param topmenu TopMenu Handle. - * @param parent TopMenuObject ID. - * @param buffer Buffer to store info string. - * @param maxlength Maximum size of info string. - * @return Number of bytes written, not including the - * null terminator. - * @error Invalid TopMenu Handle or TopMenuObject ID. + * @param topmenu TopMenu Handle. + * @param parent TopMenuObject ID. + * @param buffer Buffer to store info string. + * @param maxlength Maximum size of info string. + * @return Number of bytes written, not including the + * null terminator. + * @error Invalid TopMenu Handle or TopMenuObject ID. */ native int GetTopMenuInfoString(Handle topmenu, TopMenuObject parent, char[] buffer, int maxlength); /** * Retrieves the name string of a top menu item. * - * @param topmenu TopMenu Handle. - * @param topobj TopMenuObject ID. - * @param buffer Buffer to store info string. - * @param maxlength Maximum size of info string. - * @return Number of bytes written, not including the - * null terminator. - * @error Invalid TopMenu Handle or TopMenuObject ID. + * @param topmenu TopMenu Handle. + * @param topobj TopMenuObject ID. + * @param buffer Buffer to store info string. + * @param maxlength Maximum size of info string. + * @return Number of bytes written, not including the + * null terminator. + * @error Invalid TopMenu Handle or TopMenuObject ID. */ native int GetTopMenuObjName(Handle topmenu, TopMenuObject topobj, char[] buffer, int maxlength); /** * Removes an topobj from a TopMenu. * - * Plugins' topobjs are automatically removed all TopMenus when the given + * Plugins' topobjs are automatically removed all TopMenus when the given * plugin unloads or pauses. In the case of unpausing, all items are restored. * - * @param topmenu TopMenu Handle. - * @param topobj TopMenuObject ID. - * @error Invalid TopMenu Handle. + * @param topmenu TopMenu Handle. + * @param topobj TopMenuObject ID. + * @error Invalid TopMenu Handle. */ native void RemoveFromTopMenu(Handle topmenu, TopMenuObject topobj); /** * Displays a TopMenu to a client. * - * @param topmenu TopMenu Handle. - * @param client Client index. - * @param position Position to display from. - * @return True on success, false on failure. - * @error Invalid TopMenu Handle or client not in game. + * @param topmenu TopMenu Handle. + * @param client Client index. + * @param position Position to display from. + * @return True on success, false on failure. + * @error Invalid TopMenu Handle or client not in game. */ native bool DisplayTopMenu(Handle topmenu, int client, TopMenuPosition position); /** * Displays a TopMenu category to a client. * - * @param topmenu TopMenu Handle. - * @param category Category topobj id. - * @param client Client index. - * @return True on success, false on failure. - * @error Invalid TopMenu Handle or client not in game. + * @param topmenu TopMenu Handle. + * @param category Category topobj id. + * @param client Client index. + * @return True on success, false on failure. + * @error Invalid TopMenu Handle or client not in game. */ native bool DisplayTopMenuCategory(Handle topmenu, TopMenuObject category, int client); /** * Finds a category's topobj ID in a TopMenu. * - * @param topmenu TopMenu Handle. - * @param name Object's unique name. - * @return TopMenuObject ID on success, or - * INVALID_TOPMENUOBJECT on failure. - * @error Invalid TopMenu Handle. + * @param topmenu TopMenu Handle. + * @param name Object's unique name. + * @return TopMenuObject ID on success, or + * INVALID_TOPMENUOBJECT on failure. + * @error Invalid TopMenu Handle. */ native TopMenuObject FindTopMenuCategory(Handle topmenu, const char[] name); @@ -403,7 +403,7 @@ native void SetTopMenuTitleCaching(Handle topmenu, bool cache_titles); /** * Do not edit below this line! */ -public Extension __ext_topmenus = +public Extension __ext_topmenus = { name = "TopMenus", file = "topmenus.ext", @@ -430,5 +430,17 @@ public void __ext_topmenus_SetNTVOptional() MarkNativeAsOptional("DisplayTopMenuCategory"); MarkNativeAsOptional("FindTopMenuCategory"); MarkNativeAsOptional("SetTopMenuTitleCaching"); + MarkNativeAsOptional("TopMenu.TopMenu"); + MarkNativeAsOptional("TopMenu.FromHandle"); + MarkNativeAsOptional("TopMenu.LoadConfig"); + MarkNativeAsOptional("TopMenu.AddCategory"); + MarkNativeAsOptional("TopMenu.AddItem"); + MarkNativeAsOptional("TopMenu.GetInfoString"); + MarkNativeAsOptional("TopMenu.GetObjName"); + MarkNativeAsOptional("TopMenu.Remove"); + MarkNativeAsOptional("TopMenu.Display"); + MarkNativeAsOptional("TopMenu.DisplayCategory"); + MarkNativeAsOptional("TopMenu.FindCategory"); + MarkNativeAsOptional("TopMenu.CacheTitles.set"); } #endif diff --git a/addons/sourcemod/scripting/include/usermessages.inc b/addons/sourcemod/scripting/include/usermessages.inc index 0d99e7d..0a43f3f 100644 --- a/addons/sourcemod/scripting/include/usermessages.inc +++ b/addons/sourcemod/scripting/include/usermessages.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -29,7 +29,7 @@ * * Version: $Id$ */ - + #if defined _eventsmsgs_included #endinput #endif @@ -40,7 +40,7 @@ */ enum UserMsg { - INVALID_MESSAGE_ID = -1, + INVALID_MESSAGE_ID = -1 }; /** @@ -49,15 +49,15 @@ enum UserMsg enum UserMessageType { UM_BitBuf = 0, - UM_Protobuf, + UM_Protobuf }; /** * @section Message Flags. */ -#define USERMSG_RELIABLE (1<<2) /**< Message will be set on the reliable stream */ -#define USERMSG_INITMSG (1<<3) /**< Message will be considered to be an initmsg */ -#define USERMSG_BLOCKHOOKS (1<<7) /**< Prevents the message from triggering SourceMod and Metamod hooks */ +#define USERMSG_RELIABLE (1<<2) /**< Message will be set on the reliable stream */ +#define USERMSG_INITMSG (1<<3) /**< Message will be considered to be an initmsg */ +#define USERMSG_BLOCKHOOKS (1<<7) /**< Prevents the message from triggering SourceMod and Metamod hooks */ /** * @endsection @@ -66,14 +66,17 @@ enum UserMessageType /** * Returns usermessage serialization type used for the current engine * - * @return The supported usermessage type. + * @return The supported usermessage type. */ native UserMessageType GetUserMessageType(); stock Protobuf UserMessageToProtobuf(Handle msg) { if (GetUserMessageType() != UM_Protobuf) + { return null; + } + return view_as(msg); } @@ -81,7 +84,10 @@ stock Protobuf UserMessageToProtobuf(Handle msg) stock BfWrite UserMessageToBfWrite(Handle msg) { if (GetUserMessageType() == UM_Protobuf) + { return null; + } + return view_as(msg); } @@ -89,57 +95,62 @@ stock BfWrite UserMessageToBfWrite(Handle msg) stock BfRead UserMessageToBfRead(Handle msg) { if (GetUserMessageType() == UM_Protobuf) + { return null; + } + return view_as(msg); } /** * Returns the ID of a given message, or -1 on failure. * - * @param msg String containing message name (case sensitive). - * @return A message index, or INVALID_MESSAGE_ID on failure. + * @param msg String containing message name (case sensitive). + * @return A message index, or INVALID_MESSAGE_ID on failure. */ native UserMsg GetUserMessageId(const char[] msg); /** * Retrieves the name of a message by ID. * - * @param msg_id Message index. - * @param msg Buffer to store the name of the message. - * @param maxlength Maximum length of string buffer. - * @return True if message index is valid, false otherwise. + * @param msg_id Message index. + * @param msg Buffer to store the name of the message. + * @param maxlength Maximum length of string buffer. + * @return True if message index is valid, false otherwise. */ native bool GetUserMessageName(UserMsg msg_id, char[] msg, int maxlength); /** * Starts a usermessage (network message). + * * @note Only one message can be active at a time. * @note It is illegal to send any message while a non-intercept hook is in progress. * - * @param msgname Message name to start. - * @param clients Array containing player indexes to broadcast to. - * @param numClients Number of players in the array. - * @param flags Optional flags to set. - * @return A handle to a bf_write bit packing structure, or - * INVALID_HANDLE on failure. - * @error Invalid message name, unable to start a message, invalid client, - * or client not connected. + * @param msgname Message name to start. + * @param clients Array containing player indexes to broadcast to. + * @param numClients Number of players in the array. + * @param flags Optional flags to set. + * @return A handle to a bf_write bit packing structure, or + * INVALID_HANDLE on failure. + * @error Invalid message name, unable to start a message, invalid client, + * or client not connected. */ native Handle StartMessage(const char[] msgname, const int[] clients, int numClients, int flags=0); /** * Starts a usermessage (network message). + * * @note Only one message can be active at a time. * @note It is illegal to send any message while a non-intercept hook is in progress. * - * @param msg Message index to start. - * @param clients Array containing player indexes to broadcast to. - * @param numClients Number of players in the array. - * @param flags Optional flags to set. - * @return A handle to a bf_write bit packing structure, or - * INVALID_HANDLE on failure. - * @error Invalid message name, unable to start a message, invalid client, - * or client not connected. + * @param msg Message index to start. + * @param clients Array containing player indexes to broadcast to. + * @param numClients Number of players in the array. + * @param flags Optional flags to set. + * @return A handle to a bf_write bit packing structure, or + * INVALID_HANDLE on failure. + * @error Invalid message name, unable to start a message, invalid client, + * or client not connected. */ native Handle StartMessageEx(UserMsg msg, const int[] clients, int numClients, int flags=0); @@ -156,29 +167,29 @@ typeset MsgHook /** * Called when a bit buffer based usermessage is hooked * - * @param msg_id Message index. - * @param msg Handle to the input bit buffer. - * @param players Array containing player indexes. - * @param playersNum Number of players in the array. - * @param reliable True if message is reliable, false otherwise. - * @param init True if message is an initmsg, false otherwise. - * @return Ignored for normal hooks. For intercept hooks, Plugin_Handled - * blocks the message from being sent, and Plugin_Continue - * resumes normal functionality. + * @param msg_id Message index. + * @param msg Handle to the input bit buffer. + * @param players Array containing player indexes. + * @param playersNum Number of players in the array. + * @param reliable True if message is reliable, false otherwise. + * @param init True if message is an initmsg, false otherwise. + * @return Ignored for normal hooks. For intercept hooks, Plugin_Handled + * blocks the message from being sent, and Plugin_Continue + * resumes normal functionality. */ function Action (UserMsg msg_id, BfRead msg, const int[] players, int playersNum, bool reliable, bool init); /** * Called when a protobuf based usermessage is hooked * - * @param msg_id Message index. - * @param msg Handle to the input protobuf. - * @param players Array containing player indexes. - * @param playersNum Number of players in the array. - * @param reliable True if message is reliable, false otherwise. - * @param init True if message is an initmsg, false otherwise. - * @return Ignored for normal hooks. For intercept hooks, Plugin_Handled - * blocks the message from being sent, and Plugin_Continue - * resumes normal functionality. + * @param msg_id Message index. + * @param msg Handle to the input protobuf. + * @param players Array containing player indexes. + * @param playersNum Number of players in the array. + * @param reliable True if message is reliable, false otherwise. + * @param init True if message is an initmsg, false otherwise. + * @return Ignored for normal hooks. For intercept hooks, Plugin_Handled + * blocks the message from being sent, and Plugin_Continue + * resumes normal functionality. */ function Action (UserMsg msg_id, Protobuf msg, const int[] players, int playersNum, bool reliable, bool init); }; @@ -186,72 +197,74 @@ typeset MsgHook /** * Called when a message hook has completed. * - * @param msg_id Message index. - * @param sent True if message was sent, false if blocked. + * @param msg_id Message index. + * @param sent True if message was sent, false if blocked. */ typedef MsgPostHook = function void (UserMsg msg_id, bool sent); /** * Hooks a user message. * - * @param msg_id Message index. - * @param hook Function to use as a hook. - * @param intercept If intercept is true, message will be fully intercepted, - * allowing the user to block the message. Otherwise, - * the hook is normal and ignores the return value. - * @param post Notification function. - * @error Invalid message index. + * @param msg_id Message index. + * @param hook Function to use as a hook. + * @param intercept If intercept is true, message will be fully intercepted, + * allowing the user to block the message. Otherwise, + * the hook is normal and ignores the return value. + * @param post Notification function. + * @error Invalid message index. */ native void HookUserMessage(UserMsg msg_id, MsgHook hook, bool intercept=false, MsgPostHook post=INVALID_FUNCTION); /** * Removes one usermessage hook. * - * @param msg_id Message index. - * @param hook Function used for the hook. - * @param intercept Specifies whether the hook was an intercept hook or not. - * @error Invalid message index. + * @param msg_id Message index. + * @param hook Function used for the hook. + * @param intercept Specifies whether the hook was an intercept hook or not. + * @error Invalid message index. */ native void UnhookUserMessage(UserMsg msg_id, MsgHook hook, bool intercept=false); /** * Starts a usermessage (network message) that broadcasts to all clients. + * * @note See StartMessage or StartMessageEx(). * - * @param msgname Message name to start. - * @param flags Optional flags to set. - * @return A handle to a bf_write bit packing structure, or - * INVALID_HANDLE on failure. + * @param msgname Message name to start. + * @param flags Optional flags to set. + * @return A handle to a bf_write bit packing structure, or + * INVALID_HANDLE on failure. */ stock Handle StartMessageAll(const char[] msgname, int flags=0) { int total = 0; int[] clients = new int[MaxClients]; - for (int i=1; i<=MaxClients; i++) + for (int i = 1; i <= MaxClients; i++) { if (IsClientConnected(i)) { clients[total++] = i; } } + return StartMessage(msgname, clients, total, flags); } /** * Starts a simpler usermessage (network message) for one client. + * * @note See StartMessage or StartMessageEx(). * - * @param msgname Message name to start. - * @param client Client to send to. - * @param flags Optional flags to set. - * @return A handle to a bf_write bit packing structure, or - * INVALID_HANDLE on failure. + * @param msgname Message name to start. + * @param client Client to send to. + * @param flags Optional flags to set. + * @return A handle to a bf_write bit packing structure, or + * INVALID_HANDLE on failure. */ stock Handle StartMessageOne(const char[] msgname, int client, int flags=0) { int players[1]; - players[0] = client; - + return StartMessage(msgname, players, 1, flags); } diff --git a/addons/sourcemod/scripting/include/vector.inc b/addons/sourcemod/scripting/include/vector.inc index 067754c..3cfe21c 100644 --- a/addons/sourcemod/scripting/include/vector.inc +++ b/addons/sourcemod/scripting/include/vector.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -38,84 +38,84 @@ /** * Calculates a vector's length. * - * @param vec Vector. - * @param squared If true, the result will be squared (for optimization). - * @return Vector length (magnitude). + * @param vec Vector. + * @param squared If true, the result will be squared (for optimization). + * @return Vector length (magnitude). */ native float GetVectorLength(const float vec[3], bool squared=false); /** * Calculates the distance between two vectors. * - * @param vec1 First vector. - * @param vec2 Second vector. - * @param squared If true, the result will be squared (for optimization). - * @return Vector distance. + * @param vec1 First vector. + * @param vec2 Second vector. + * @param squared If true, the result will be squared (for optimization). + * @return Vector distance. */ native float GetVectorDistance(const float vec1[3], const float vec2[3], bool squared=false); /** * Calculates the dot product of two vectors. * - * @param vec1 First vector. - * @param vec2 Second vector. - * @return Dot product of the two vectors. + * @param vec1 First vector. + * @param vec2 Second vector. + * @return Dot product of the two vectors. */ native float GetVectorDotProduct(const float vec1[3], const float vec2[3]); /** - * Computes the cross product of two vectors. Any input array can be the same + * Computes the cross product of two vectors. Any input array can be the same * as the output array. * - * @param vec1 First vector. - * @param vec2 Second vector. - * @param result Resultant vector. + * @param vec1 First vector. + * @param vec2 Second vector. + * @param result Resultant vector. */ native void GetVectorCrossProduct(const float vec1[3], const float vec2[3], float result[3]); /** * Normalizes a vector. The input array can be the same as the output array. * - * @param vec Vector. - * @param result Resultant vector. - * @return Vector length. + * @param vec Vector. + * @param result Resultant vector. + * @return Vector length. */ native float NormalizeVector(const float vec[3], float result[3]); /** * Returns vectors in the direction of an angle. * - * @param angle Angle. - * @param fwd Forward vector buffer or NULL_VECTOR. - * @param right Right vector buffer or NULL_VECTOR. - * @param up Up vector buffer or NULL_VECTOR. + * @param angle Angle. + * @param fwd Forward vector buffer or NULL_VECTOR. + * @param right Right vector buffer or NULL_VECTOR. + * @param up Up vector buffer or NULL_VECTOR. */ native void GetAngleVectors(const float angle[3], float fwd[3], float right[3], float up[3]); /** * Returns angles from a vector. * - * @param vec Vector. - * @param angle Angle buffer. + * @param vec Vector. + * @param angle Angle buffer. */ native void GetVectorAngles(const float vec[3], float angle[3]); /** * Returns direction vectors from a vector. * - * @param vec Vector. - * @param right Right vector buffer or NULL_VECTOR. - * @param up Up vector buffer or NULL_VECTOR. + * @param vec Vector. + * @param right Right vector buffer or NULL_VECTOR. + * @param up Up vector buffer or NULL_VECTOR. */ native void GetVectorVectors(const float vec[3], float right[3], float up[3]); /** - * Adds two vectors. It is safe to use either input buffer as an output + * Adds two vectors. It is safe to use either input buffer as an output * buffer. - * - * @param vec1 First vector. - * @param vec2 Second vector. - * @param result Result buffer. + * + * @param vec1 First vector. + * @param vec2 Second vector. + * @param result Result buffer. */ stock void AddVectors(const float vec1[3], const float vec2[3], float result[3]) { @@ -125,12 +125,12 @@ stock void AddVectors(const float vec1[3], const float vec2[3], float result[3]) } /** - * Subtracts a vector from another vector. It is safe to use either input + * Subtracts a vector from another vector. It is safe to use either input * buffer as an output buffer. - * - * @param vec1 First vector. - * @param vec2 Second vector to subtract from first. - * @param result Result buffer. + * + * @param vec1 First vector. + * @param vec2 Second vector to subtract from first. + * @param result Result buffer. */ stock void SubtractVectors(const float vec1[3], const float vec2[3], float result[3]) { @@ -142,8 +142,8 @@ stock void SubtractVectors(const float vec1[3], const float vec2[3], float resul /** * Scales a vector. * - * @param vec Vector. - * @param scale Scale value. + * @param vec Vector. + * @param scale Scale value. */ stock void ScaleVector(float vec[3], float scale) { @@ -155,7 +155,7 @@ stock void ScaleVector(float vec[3], float scale) /** * Negatives a vector. * - * @param vec Vector. + * @param vec Vector. */ stock void NegateVector(float vec[3]) { @@ -167,9 +167,9 @@ stock void NegateVector(float vec[3]) /** * Builds a vector from two points by subtracting the points. * - * @param pt1 First point (to be subtracted from the second). - * @param pt2 Second point. - * @param output Output vector buffer. + * @param pt1 First point (to be subtracted from the second). + * @param pt2 Second point. + * @param output Output vector buffer. */ stock void MakeVectorFromPoints(const float pt1[3], const float pt2[3], float output[3]) { diff --git a/addons/sourcemod/scripting/include/version.inc b/addons/sourcemod/scripting/include/version.inc index c0e4020..a86dfb9 100644 --- a/addons/sourcemod/scripting/include/version.inc +++ b/addons/sourcemod/scripting/include/version.inc @@ -9,7 +9,7 @@ * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more @@ -29,7 +29,7 @@ * * Version: $Id$ */ - + #if defined _version_included #endinput #endif @@ -38,12 +38,12 @@ #tryinclude #if !defined _auto_version_included -#define SOURCEMOD_V_TAG "manual" -#define SOURCEMOD_V_REV 0 -#define SOURCEMOD_V_CSET "0" -#define SOURCEMOD_V_MAJOR 1 /**< SourceMod Major version */ -#define SOURCEMOD_V_MINOR 8 /**< SourceMod Minor version */ -#define SOURCEMOD_V_RELEASE 0 /**< SourceMod Release version */ + #define SOURCEMOD_V_TAG "manual" + #define SOURCEMOD_V_REV 0 + #define SOURCEMOD_V_CSET "0" + #define SOURCEMOD_V_MAJOR 1 /**< SourceMod Major version */ + #define SOURCEMOD_V_MINOR 10 /**< SourceMod Minor version */ + #define SOURCEMOD_V_RELEASE 0 /**< SourceMod Release version */ -#define SOURCEMOD_VERSION "1.8.0-manual" /**< SourceMod version string (major.minor.release-tag) */ + #define SOURCEMOD_VERSION "1.10.0-manual" /**< SourceMod version string (major.minor.release-tag) */ #endif diff --git a/addons/sourcemod/scripting/include/version_auto.inc b/addons/sourcemod/scripting/include/version_auto.inc index c6bc737..c3fe393 100644 --- a/addons/sourcemod/scripting/include/version_auto.inc +++ b/addons/sourcemod/scripting/include/version_auto.inc @@ -5,11 +5,11 @@ #define _auto_version_included #define SOURCEMOD_V_TAG "" -#define SOURCEMOD_V_CSET "07f8043b" +#define SOURCEMOD_V_CSET "a8b9da9a" #define SOURCEMOD_V_MAJOR 1 -#define SOURCEMOD_V_MINOR 9 +#define SOURCEMOD_V_MINOR 10 #define SOURCEMOD_V_RELEASE 0 -#define SOURCEMOD_V_REV 6241 +#define SOURCEMOD_V_REV 6478 -#define SOURCEMOD_VERSION "1.9.0.6241" +#define SOURCEMOD_VERSION "1.10.0.6478" \ No newline at end of file diff --git a/addons/sourcemod/scripting/nextmap.sp b/addons/sourcemod/scripting/nextmap.sp new file mode 100644 index 0000000..123fdd1 --- /dev/null +++ b/addons/sourcemod/scripting/nextmap.sp @@ -0,0 +1,234 @@ +/** + * vim: set ts=4 : + * ============================================================================= + * SourceMod Nextmap Plugin + * Adds sm_nextmap cvar for changing map and nextmap chat trigger. + * + * SourceMod (C)2004-2014 AlliedModders LLC. All rights reserved. + * ============================================================================= + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License, version 3.0, as published by the + * Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program. If not, see . + * + * As a special exception, AlliedModders LLC gives you permission to link the + * code of this program (as well as its derivative works) to "Half-Life 2," the + * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software + * by the Valve Corporation. You must obey the GNU General Public License in + * all respects for all other code used. Additionally, AlliedModders LLC grants + * this exception to all derivative works. AlliedModders LLC defines further + * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), + * or . + * + * Version: $Id$ + */ + +#include +#include "include/nextmap.inc" + +#pragma semicolon 1 +#pragma newdecls required + +public Plugin myinfo = +{ + name = "Nextmap", + author = "AlliedModders LLC", + description = "Provides nextmap and sm_nextmap", + version = SOURCEMOD_VERSION, + url = "http://www.sourcemod.net/" +}; + +int g_MapPos = -1; +ArrayList g_MapList = null; +int g_MapListSerial = -1; + +int g_CurrentMapStartTime; + +public APLRes AskPluginLoad2(Handle myself, bool late, char[] error, int err_max) +{ + char game[128]; + GetGameFolderName(game, sizeof(game)); + + EngineVersion engine = GetEngineVersion(); + + if (StrEqual(game, "left4dead", false) + || StrEqual(game, "dystopia", false) + || StrEqual(game, "synergy", false) + || StrEqual(game, "left4dead2", false) + || StrEqual(game, "garrysmod", false) + || StrEqual(game, "swarm", false) + || StrEqual(game, "bms", false) + || StrEqual(game, "reactivedrop", false) + || engine == Engine_Insurgency + || engine == Engine_DOI) + { + strcopy(error, err_max, "Nextmap is incompatible with this game"); + return APLRes_SilentFailure; + } + + return APLRes_Success; +} + +public void OnPluginStart() +{ + LoadTranslations("common.phrases"); + LoadTranslations("nextmap.phrases"); + + int size = ByteCountToCells(PLATFORM_MAX_PATH); + g_MapList = new ArrayList(size); + + RegAdminCmd("sm_maphistory", Command_MapHistory, ADMFLAG_CHANGEMAP, "Shows the most recent maps played"); + RegConsoleCmd("listmaps", Command_List); + + // Set to the current map so OnMapStart() will know what to do + char currentMap[PLATFORM_MAX_PATH]; + GetCurrentMap(currentMap, sizeof(currentMap)); + SetNextMap(currentMap); +} + +public void OnMapStart() +{ + g_CurrentMapStartTime = GetTime(); +} + +public void OnConfigsExecuted() +{ + char lastMap[PLATFORM_MAX_PATH], currentMap[PLATFORM_MAX_PATH]; + GetNextMap(lastMap, sizeof(lastMap)); + GetCurrentMap(currentMap, sizeof(currentMap)); + + // Why am I doing this? If we switched to a new map, but it wasn't what we expected (Due to sm_map, sm_votemap, or + // some other plugin/command), we don't want to scramble the map cycle. Or for example, admin switches to a custom map + // not in mapcyclefile. So we keep it set to the last expected nextmap. - ferret + if (strcmp(lastMap, currentMap) == 0) + { + FindAndSetNextMap(); + } +} + +public Action Command_List(int client, int args) +{ + PrintToConsole(client, "Map Cycle:"); + + int mapCount = g_MapList.Length; + char mapName[PLATFORM_MAX_PATH]; + for (int i = 0; i < mapCount; i++) + { + g_MapList.GetString(i, mapName, sizeof(mapName)); + PrintToConsole(client, "%s", mapName); + } + + return Plugin_Handled; +} + +void FindAndSetNextMap() +{ + if (ReadMapList(g_MapList, + g_MapListSerial, + "mapcyclefile", + MAPLIST_FLAG_CLEARARRAY|MAPLIST_FLAG_NO_DEFAULT) + == null) + { + if (g_MapListSerial == -1) + { + LogError("FATAL: Cannot load map cycle. Nextmap not loaded."); + SetFailState("Mapcycle Not Found"); + } + } + + int mapCount = g_MapList.Length; + char mapName[PLATFORM_MAX_PATH]; + + if (g_MapPos == -1) + { + char current[PLATFORM_MAX_PATH]; + GetCurrentMap(current, sizeof(current)); + + for (int i = 0; i < mapCount; i++) + { + g_MapList.GetString(i, mapName, sizeof(mapName)); + if (FindMap(mapName, mapName, sizeof(mapName)) != FindMap_NotFound && + strcmp(current, mapName, false) == 0) + { + g_MapPos = i; + break; + } + } + + if (g_MapPos == -1) + g_MapPos = 0; + } + + g_MapPos++; + if (g_MapPos >= mapCount) + g_MapPos = 0; + + g_MapList.GetString(g_MapPos, mapName, sizeof(mapName)); + SetNextMap(mapName); +} + +public Action Command_MapHistory(int client, int args) +{ + int mapCount = GetMapHistorySize(); + + char mapName[PLATFORM_MAX_PATH]; + char changeReason[100]; + char timeString[100]; + char playedTime[100]; + int startTime; + + int lastMapStartTime = g_CurrentMapStartTime; + + PrintToConsole(client, "Map History:\n"); + PrintToConsole(client, "Map : Started : Played Time : Reason for ending"); + + GetCurrentMap(mapName, sizeof(mapName)); + PrintToConsole(client, "%02i. %s (Current Map)", 0, mapName); + + for (int i=0; i 0) + { + return Format(buffer, maxlen, "%id %ih %im", days, hours, (seconds >= 30) ? minutes+1 : minutes); + } + else if (hours > 0) + { + return Format(buffer, maxlen, "%ih %im", hours, (seconds >= 30) ? minutes+1 : minutes); + } + else if (minutes > 0) + { + return Format(buffer, maxlen, "%im", (seconds >= 30) ? minutes+1 : minutes); + } + else + { + return Format(buffer, maxlen, "%is", seconds); + } +} \ No newline at end of file diff --git a/addons/sourcemod/scripting/spcomp.exe b/addons/sourcemod/scripting/spcomp.exe index c9967ff..4358226 100644 Binary files a/addons/sourcemod/scripting/spcomp.exe and b/addons/sourcemod/scripting/spcomp.exe differ diff --git a/addons/sourcemod/scripting/surftimer.smx b/addons/sourcemod/scripting/surftimer.smx deleted file mode 100644 index 8755641..0000000 Binary files a/addons/sourcemod/scripting/surftimer.smx and /dev/null differ diff --git a/addons/sourcemod/scripting/surftimer/buttonpress.sp b/addons/sourcemod/scripting/surftimer/buttonpress.sp index 9e7ac3d..f4fd405 100644 --- a/addons/sourcemod/scripting/surftimer/buttonpress.sp +++ b/addons/sourcemod/scripting/surftimer/buttonpress.sp @@ -453,7 +453,7 @@ public void CL_OnEndTimerPress(int client) { int count = g_StyleMapTimesCount[style]; - for (int i = 1; i <= GetMaxClients(); i++) + for (int i = 1; i <= MaxClients; i++) { if (IsValidClient(i) && !IsFakeClient(i)) { @@ -863,4 +863,4 @@ public void CL_OnEndWrcpTimerPress(int client, float time2) db_selectWrcpRecord(client, style, stage); g_bWrcpTimeractivated[client] = false; } -} +} \ No newline at end of file diff --git a/addons/sourcemod/scripting/surftimer/commands.sp b/addons/sourcemod/scripting/surftimer/commands.sp index e188e3e..44cc24d 100644 --- a/addons/sourcemod/scripting/surftimer/commands.sp +++ b/addons/sourcemod/scripting/surftimer/commands.sp @@ -2403,9 +2403,9 @@ public void GotoMethod(int client, int target) GetClientEyeAngles(target, angles); AddVectors(position, angles, g_fTeleLocation[client]); - g_fTeleLocation[client][0] = FloatDiv(g_fTeleLocation[client][0], 2.0); - g_fTeleLocation[client][1] = FloatDiv(g_fTeleLocation[client][1], 2.0); - g_fTeleLocation[client][2] = FloatDiv(g_fTeleLocation[client][2], 2.0); + g_fTeleLocation[client][0] = g_fTeleLocation[client][0]/ 2.0; + g_fTeleLocation[client][1] = g_fTeleLocation[client][1]/ 2.0; + g_fTeleLocation[client][2] = g_fTeleLocation[client][2]/ 2.0; g_bRespawnPosition[client] = false; g_specToStage[client] = true; diff --git a/addons/sourcemod/scripting/surftimer/cvote.sp b/addons/sourcemod/scripting/surftimer/cvote.sp index 7ec9acf..80e2110 100644 --- a/addons/sourcemod/scripting/surftimer/cvote.sp +++ b/addons/sourcemod/scripting/surftimer/cvote.sp @@ -107,7 +107,7 @@ public int Handle_VoteMenuExtend(Menu menu, MenuAction action, int param1, int p if (strcmp(item, VOTE_NO) == 0 && param1 == 1) votes = totalVotes - votes; - percent = FloatDiv(float(votes),float(totalVotes)); + percent = float(votes) / float(totalVotes); GetCurrentMaptime(); int iTimeLimit = GetConVarInt(mapTime); diff --git a/addons/sourcemod/scripting/surftimer/db/queries.sp b/addons/sourcemod/scripting/surftimer/db/queries.sp index c448062..00755ee 100644 --- a/addons/sourcemod/scripting/surftimer/db/queries.sp +++ b/addons/sourcemod/scripting/surftimer/db/queries.sp @@ -13,7 +13,7 @@ char sql_updateBonus[] = "UPDATE ck_bonus SET runtime = '%f', name = '%s' WHERE char sql_selectBonusCount[] = "SELECT zonegroup, style, count(1) FROM ck_bonus WHERE mapname = '%s' GROUP BY zonegroup, style;"; char sql_selectPersonalBonusRecords[] = "SELECT runtime, zonegroup, style FROM ck_bonus WHERE steamid = '%s' AND mapname = '%s' AND runtime > '0.0'"; char sql_selectPlayerRankBonus[] = "SELECT name FROM ck_bonus WHERE runtime <= (SELECT runtime FROM ck_bonus WHERE steamid = '%s' AND mapname= '%s' AND runtime > 0.0 AND zonegroup = %i AND style = 0) AND mapname = '%s' AND zonegroup = %i AND style = 0;"; -char sql_selectFastestBonus[] = "SELECT name, MIN(runtime), zonegroup, style FROM ck_bonus WHERE mapname = '%s' GROUP BY zonegroup, style;"; +char sql_selectFastestBonus[] = "SELECT name, MIN(runtime), zonegroup, style FROM ck_bonus WHERE mapname = '%s' GROUP BY name, zonegroup, style;"; char sql_deleteBonus[] = "DELETE FROM ck_bonus WHERE mapname = '%s'"; char sql_selectAllBonusTimesinMap[] = "SELECT zonegroup, runtime from ck_bonus WHERE mapname = '%s';"; char sql_selectTopBonusSurfers[] = "SELECT db2.steamid, db1.name, db2.runtime as overall, db1.steamid, db2.mapname FROM ck_bonus as db2 INNER JOIN ck_playerrank as db1 on db2.steamid = db1.steamid WHERE db2.mapname = '%s' AND db2.style = 0 AND db1.style = 0 AND db2.runtime > -1.0 AND zonegroup = %i ORDER BY overall ASC LIMIT 100;"; @@ -24,7 +24,7 @@ char sql_updateCheckpoints[] = "UPDATE ck_checkpoints SET cp1='%f', cp2='%f', cp char sql_insertCheckpoints[] = "INSERT INTO ck_checkpoints VALUES ('%s', '%s', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%f', '%i')"; char sql_selectCheckpoints[] = "SELECT zonegroup, cp1, cp2, cp3, cp4, cp5, cp6, cp7, cp8, cp9, cp10, cp11, cp12, cp13, cp14, cp15, cp16, cp17, cp18, cp19, cp20, cp21, cp22, cp23, cp24, cp25, cp26, cp27, cp28, cp29, cp30, cp31, cp32, cp33, cp34, cp35 FROM ck_checkpoints WHERE mapname='%s' AND steamid = '%s';"; char sql_selectCheckpointsinZoneGroup[] = "SELECT cp1, cp2, cp3, cp4, cp5, cp6, cp7, cp8, cp9, cp10, cp11, cp12, cp13, cp14, cp15, cp16, cp17, cp18, cp19, cp20, cp21, cp22, cp23, cp24, cp25, cp26, cp27, cp28, cp29, cp30, cp31, cp32, cp33, cp34, cp35 FROM ck_checkpoints WHERE mapname='%s' AND steamid = '%s' AND zonegroup = %i;"; -char sql_selectRecordCheckpoints[] = "SELECT zonegroup, cp1, cp2, cp3, cp4, cp5, cp6, cp7, cp8, cp9, cp10, cp11, cp12, cp13, cp14, cp15, cp16, cp17, cp18, cp19, cp20, cp21, cp22, cp23, cp24, cp25, cp26, cp27, cp28, cp29, cp30, cp31, cp32, cp33, cp34, cp35 FROM ck_checkpoints WHERE steamid = '%s' AND mapname='%s' UNION SELECT a.zonegroup, b.cp1, b.cp2, b.cp3, b.cp4, b.cp5, b.cp6, b.cp7, b.cp8, b.cp9, b.cp10, b.cp11, b.cp12, b.cp13, b.cp14, b.cp15, b.cp16, b.cp17, b.cp18, b.cp19, b.cp20, b.cp21, b.cp22, b.cp23, b.cp24, b.cp25, b.cp26, b.cp27, b.cp28, b.cp29, b.cp30, b.cp31, b.cp32, b.cp33, b.cp34, b.cp35 FROM ck_bonus a LEFT JOIN ck_checkpoints b ON a.steamid = b.steamid AND a.zonegroup = b.zonegroup WHERE a.mapname = '%s' GROUP BY a.zonegroup"; +char sql_selectRecordCheckpoints[] = "SELECT zonegroup, cp1, cp2, cp3, cp4, cp5, cp6, cp7, cp8, cp9, cp10, cp11, cp12, cp13, cp14, cp15, cp16, cp17, cp18, cp19, cp20, cp21, cp22, cp23, cp24, cp25, cp26, cp27, cp28, cp29, cp30, cp31, cp32, cp33, cp34, cp35 FROM ck_checkpoints WHERE steamid = '%s' AND mapname='%s' UNION SELECT a.zonegroup, b.cp1, b.cp2, b.cp3, b.cp4, b.cp5, b.cp6, b.cp7, b.cp8, b.cp9, b.cp10, b.cp11, b.cp12, b.cp13, b.cp14, b.cp15, b.cp16, b.cp17, b.cp18, b.cp19, b.cp20, b.cp21, b.cp22, b.cp23, b.cp24, b.cp25, b.cp26, b.cp27, b.cp28, b.cp29, b.cp30, b.cp31, b.cp32, b.cp33, b.cp34, b.cp35 FROM ck_bonus a LEFT JOIN ck_checkpoints b ON a.steamid = b.steamid AND a.zonegroup = b.zonegroup WHERE a.mapname = '%s' GROUP BY a.zonegroup, b.cp1, b.cp2, b.cp3, b.cp4, b.cp5, b.cp6, b.cp7, b.cp8, b.cp9, b.cp10, b.cp11, b.cp12, b.cp13, b.cp14, b.cp15, b.cp16, b.cp17, b.cp18, b.cp19, b.cp20, b.cp21, b.cp22, b.cp23, b.cp24, b.cp25, b.cp26, b.cp27, b.cp28, b.cp29, b.cp30, b.cp31, b.cp32, b.cp33, b.cp34, b.cp35"; char sql_deleteCheckpoints[] = "DELETE FROM ck_checkpoints WHERE mapname = '%s'"; // ck_latestrecords @@ -47,8 +47,8 @@ char sql_updatePlayerOptions[] = "UPDATE ck_playeroptions2 SET timer = %i, hide // ck_playerrank char sql_createPlayerRank[] = "CREATE TABLE IF NOT EXISTS `ck_playerrank` (`steamid` varchar(32) NOT NULL DEFAULT '', `steamid64` varchar(64) DEFAULT NULL, `name` varchar(32) DEFAULT NULL, `country` varchar(32) DEFAULT NULL, `points` int(12) DEFAULT '0', `wrpoints` int(12) NOT NULL DEFAULT '0', `wrbpoints` int(12) NOT NULL DEFAULT '0', `wrcppoints` int(11) NOT NULL DEFAULT '0', `top10points` int(12) NOT NULL DEFAULT '0', `groupspoints` int(12) NOT NULL DEFAULT '0', `mappoints` int(11) NOT NULL DEFAULT '0', `bonuspoints` int(12) NOT NULL DEFAULT '0', `finishedmaps` int(12) DEFAULT '0', `finishedmapspro` int(12) DEFAULT '0', `finishedbonuses` int(12) NOT NULL DEFAULT '0', `finishedstages` int(12) NOT NULL DEFAULT '0', `wrs` int(12) NOT NULL DEFAULT '0', `wrbs` int(12) NOT NULL DEFAULT '0', `wrcps` int(12) NOT NULL DEFAULT '0', `top10s` int(12) NOT NULL DEFAULT '0', `groups` int(12) NOT NULL DEFAULT '0', `lastseen` int(64) DEFAULT NULL, `joined` int(64) NOT NULL, `timealive` int(64) NOT NULL DEFAULT '0', `timespec` int(64) NOT NULL DEFAULT '0', `connections` int(64) NOT NULL DEFAULT '1', `readchangelog` int(11) NOT NULL DEFAULT '0', `style` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`steamid`, `style`)) DEFAULT CHARSET=utf8mb4;"; char sql_insertPlayerRank[] = "INSERT INTO ck_playerrank (steamid, steamid64, name, country, joined, style) VALUES('%s', '%s', '%s', '%s', %i, %i)"; -char sql_updatePlayerRankPoints[] = "UPDATE ck_playerrank SET name ='%s', points ='%i', wrpoints = %i, wrbpoints = %i, wrcppoints = %i, top10points = %i, groupspoints = %i, mappoints = %i, bonuspoints = %i, finishedmapspro='%i', finishedbonuses = %i, finishedstages = %i, wrs = %i, wrbs = %i, wrcps = %i, top10s = %i, groups = %i where steamid='%s' AND style = %i;"; -char sql_updatePlayerRankPoints2[] = "UPDATE ck_playerrank SET name ='%s', points ='%i', wrpoints = %i, wrbpoints = %i, wrcppoints = %i, top10points = %i, groupspoints = %i, mappoints = %i, bonuspoints = %i, finishedmapspro='%i', finishedbonuses = %i, finishedstages = %i, wrs = %i, wrbs = %i, wrcps = %i, top10s = %i, groups = %i, country = '%s' where steamid='%s' AND style = %i;"; +char sql_updatePlayerRankPoints[] = "UPDATE ck_playerrank SET name ='%s', points ='%i', wrpoints = %i, wrbpoints = %i, wrcppoints = %i, top10points = %i, groupspoints = %i, mappoints = %i, bonuspoints = %i, finishedmapspro='%i', finishedbonuses = %i, finishedstages = %i, wrs = %i, wrbs = %i, wrcps = %i, top10s = %i, `groups` = %i where steamid='%s' AND style = %i;"; +char sql_updatePlayerRankPoints2[] = "UPDATE ck_playerrank SET name ='%s', points ='%i', wrpoints = %i, wrbpoints = %i, wrcppoints = %i, top10points = %i, groupspoints = %i, mappoints = %i, bonuspoints = %i, finishedmapspro='%i', finishedbonuses = %i, finishedstages = %i, wrs = %i, wrbs = %i, wrcps = %i, top10s = %i, `groups` = %i, country = '%s' where steamid='%s' AND style = %i;"; char sql_updatePlayerRank[] = "UPDATE ck_playerrank SET finishedmaps ='%i', finishedmapspro='%i' where steamid='%s' AND style = '%i';"; //char sql_selectPlayerRankAll[] = "SELECT name, steamid FROM ck_playerrank where name like '%c%s%c'"; //char sql_selectPlayerRankAll2[] = "SELECT name, steamid FROM ck_playerrank where name = '%s'"; @@ -61,7 +61,7 @@ char sql_selectRankedPlayersRank[] = "SELECT name FROM ck_playerrank WHERE style char sql_selectRankedPlayers[] = "SELECT steamid, name from ck_playerrank where points > 0 AND style = 0 ORDER BY points DESC LIMIT 0, 1067;"; char sql_CountRankedPlayers[] = "SELECT COUNT(steamid) FROM ck_playerrank WHERE style = %i;"; char sql_CountRankedPlayers2[] = "SELECT COUNT(steamid) FROM ck_playerrank where points > 0 AND style = %i;"; -char sql_selectPlayerProfile[] = "SELECT steamid, steamid64, name, country, points, wrpoints, wrbpoints, wrcppoints, top10points, groupspoints, mappoints, bonuspoints, finishedmapspro, finishedbonuses, finishedstages, wrs, wrbs, wrcps, top10s, groups, lastseen FROM ck_playerrank WHERE steamid = '%s' AND style = '%i';"; +char sql_selectPlayerProfile[] = "SELECT steamid, steamid64, name, country, points, wrpoints, wrbpoints, wrcppoints, top10points, groupspoints, mappoints, bonuspoints, finishedmapspro, finishedbonuses, finishedstages, wrs, wrbs, wrcps, top10s, `groups`, lastseen FROM ck_playerrank WHERE steamid = '%s' AND style = '%i';"; // ck_playertemp char sql_createPlayertmp[] = "CREATE TABLE IF NOT EXISTS ck_playertemp (steamid VARCHAR(32), mapname VARCHAR(32), cords1 FLOAT NOT NULL DEFAULT '-1.0', cords2 FLOAT NOT NULL DEFAULT '-1.0', cords3 FLOAT NOT NULL DEFAULT '-1.0', angle1 FLOAT NOT NULL DEFAULT '-1.0',angle2 FLOAT NOT NULL DEFAULT '-1.0',angle3 FLOAT NOT NULL DEFAULT '-1.0', EncTickrate INT(12) DEFAULT '-1.0', runtimeTmp FLOAT NOT NULL DEFAULT '-1.0', Stage INT, zonegroup INT NOT NULL DEFAULT 0, PRIMARY KEY(steamid,mapname)) DEFAULT CHARSET=utf8mb4;"; @@ -77,7 +77,7 @@ char sql_insertPlayer[] = "INSERT INTO ck_playertimes (steamid, mapname, name) V char sql_insertPlayerTime[] = "INSERT INTO ck_playertimes (steamid, mapname, name, runtimepro, style) VALUES('%s', '%s', '%s', '%f', %i);"; char sql_updateRecordPro[] = "UPDATE ck_playertimes SET name = '%s', runtimepro = '%f' WHERE steamid = '%s' AND mapname = '%s' AND style = %i;"; char sql_selectPlayer[] = "SELECT steamid FROM ck_playertimes WHERE steamid = '%s' AND mapname = '%s';"; -char sql_selectMapRecord[] = "SELECT MIN(runtimepro), name, steamid, style FROM ck_playertimes WHERE mapname = '%s' AND runtimepro > -1.0 GROUP BY style;"; +char sql_selectMapRecord[] = "SELECT MIN(runtimepro), name, steamid, style FROM ck_playertimes WHERE mapname = '%s' AND runtimepro > -1.0 GROUP BY name, steamid, style;"; //char sql_selectPersonalRecords[] = "SELECT runtimepro, name FROM ck_playertimes WHERE mapname = '%s' AND steamid = '%s' AND runtimepro > 0.0"; char sql_selectPersonalAllRecords[] = "SELECT db1.name, db2.steamid, db2.mapname, db2.runtimepro as overall, db1.steamid, db3.tier FROM ck_playertimes as db2 INNER JOIN ck_playerrank as db1 on db2.steamid = db1.steamid INNER JOIN ck_maptier AS db3 ON db2.mapname = db3.mapname WHERE db2.steamid = '%s' AND db2.style = %i AND db1.style = %i AND db2.runtimepro > -1.0 ORDER BY mapname ASC;"; //char sql_selectProSurfers[] = "SELECT db1.name, db2.runtimepro, db2.steamid, db1.steamid FROM ck_playertimes as db2 INNER JOIN ck_playerrank as db1 on db2.steamid = db1.steamid WHERE db2.mapname = '%s' AND db2.runtimepro > -1.0 ORDER BY db2.runtimepro ASC LIMIT 20"; diff --git a/addons/sourcemod/scripting/surftimer/misc.sp b/addons/sourcemod/scripting/surftimer/misc.sp index 965319e..e6aea96 100644 --- a/addons/sourcemod/scripting/surftimer/misc.sp +++ b/addons/sourcemod/scripting/surftimer/misc.sp @@ -1257,7 +1257,7 @@ public void LimitSpeedNew(int client) // Derived from Pythagorean theorem, where the hypotenuse represents the magnitude of velocity, // and the two legs represent the x and y velocity components. // As a side effect, velocity component signs are also handled. - float scale = FloatDiv(speedCap, SquareRoot( FloatAdd( Pow(fVel[0], 2.0), Pow(fVel[1], 2.0) ) ) ); + float scale = speedCap / SquareRoot( Pow(fVel[0], 2.0) + Pow(fVel[1], 2.0) ); // A scale < 1 indicates a magnitude > limit if (scale < 1.0) @@ -1271,8 +1271,8 @@ public void LimitSpeedNew(int client) // Reduce each vector by the appropriate amount float speed = SquareRoot(Pow(fVel[0], 2.0) + Pow(fVel[1], 2.0)); - fVel[0] = FloatMul(fVel[0], scale); - fVel[1] = FloatMul(fVel[1], scale); + fVel[0] = fVel[0] * scale; + fVel[1] = fVel[1] * scale; // Impart new velocity onto player if (g_bInBhop[client] || g_bLeftZone[client]) @@ -1549,7 +1549,7 @@ public void PlayRecordSound(int iRecordtype) char buffer[PLATFORM_MAX_PATH]; if (iRecordtype == 1) { - for (int i = 1; i <= GetMaxClients(); i++) + for (int i = 1; i <= MaxClients; i++) { if (IsValidClient(i) && !IsFakeClient(i) && g_bEnableQuakeSounds[i] == true) { @@ -1560,7 +1560,7 @@ public void PlayRecordSound(int iRecordtype) } else if (iRecordtype == 2) { - for (int i = 1; i <= GetMaxClients(); i++) + for (int i = 1; i <= MaxClients; i++) { if (IsValidClient(i) && !IsFakeClient(i) && g_bEnableQuakeSounds[i] == true) { @@ -1571,7 +1571,7 @@ public void PlayRecordSound(int iRecordtype) } else if (iRecordtype == 3) // top10 { - for (int i = 1; i <= GetMaxClients(); i++) + for (int i = 1; i <= MaxClients; i++) { if (IsValidClient(i) && !IsFakeClient(i) && g_bEnableQuakeSounds[i] == true) { @@ -1582,7 +1582,7 @@ public void PlayRecordSound(int iRecordtype) } else if (iRecordtype == 4) // Discotime { - for (int i = 1; i <= GetMaxClients(); i++) + for (int i = 1; i <= MaxClients; i++) { if (IsValidClient(i) && !IsFakeClient(i) && g_bEnableQuakeSounds[i] == true) { @@ -1620,7 +1620,7 @@ public void PlayWRCPRecord(int iRecordtype) char buffer[255]; if (iRecordtype == 1) { - for (int i = 1; i <= GetMaxClients(); i++) + for (int i = 1; i <= MaxClients; i++) { if (IsValidClient(i) && !IsFakeClient(i) && g_bEnableQuakeSounds[i] == true) { @@ -1878,7 +1878,7 @@ stock void MapFinishedMsgs(int client, int rankThisRun = 0) (GetConVarInt(g_hAnnounceRecord) == 2 && g_bMapSRVRecord[client])) && (rankThisRun <= GetConVarInt(g_hAnnounceRank) || GetConVarInt(g_hAnnounceRank) == 0)) { - for (int i = 1; i <= GetMaxClients(); i++) + for (int i = 1; i <= MaxClients; i++) { if (IsValidClient(i) && !IsFakeClient(i)) { @@ -4067,7 +4067,7 @@ stock void StyleFinishedMsgs(int client, int style) if (GetConVarInt(g_hAnnounceRecord) == 0 || GetConVarInt(g_hAnnounceRecord) == 1) { - for (int i = 1; i <= GetMaxClients(); i++) + for (int i = 1; i <= MaxClients; i++) { if (IsValidClient(i) && !IsFakeClient(i)) { @@ -4093,7 +4093,8 @@ stock void StyleFinishedMsgs(int client, int style) } else if (GetConVarInt(g_hAnnounceRecord) == 2) { - for (int i = 1; i <= GetMaxClients(); i++) + for (int i = 1; i <= MaxClients +; i++) { if (g_bStyleMapSRVRecord[style][client]) { @@ -4416,7 +4417,7 @@ public void totalTimeForHumans(int unix, char[] buffer, int size) } } -public void sendDiscordAnnouncement(char szName[32], char szMapName[128], char szTime[32]) +public void sendDiscordAnnouncement(char szName[128], char szMapName[128], char szTime[32]) { char webhook[1024]; GetConVarString(g_hRecordAnnounceDiscord, webhook, 1024); diff --git a/addons/sourcemod/scripting/surftimer/sql.sp b/addons/sourcemod/scripting/surftimer/sql.sp index 0353d76..f4ca925 100644 --- a/addons/sourcemod/scripting/surftimer/sql.sp +++ b/addons/sourcemod/scripting/surftimer/sql.sp @@ -40,8 +40,8 @@ public void db_setupDatabase() // If updating from a previous version SQL_LockDatabase(g_hDb); - SQL_FastQuery(g_hDb, "SET NAMES 'utf8'"); - SQL_FastQuery(g_hDb, "SET name 'utf8'"); + SQL_FastQuery(g_hDb, "SET NAMES 'utf8mb4'"); + SQL_FastQuery(g_hDb, "SET name 'utf8mb4'"); // Check if tables need to be Created or database needs to be upgraded @@ -656,7 +656,7 @@ public void sql_CalcuatePlayerRankCallback(Handle owner, Handle hndl, const char // Next up, calculate bonus points: char szQuery[512]; - Format(szQuery, 512, "SELECT mapname, (SELECT count(1)+1 FROM ck_bonus b WHERE a.mapname=b.mapname AND a.runtime > b.runtime AND a.zonegroup = b.zonegroup AND b.style = %i) AS rank, (SELECT count(1) FROM ck_bonus b WHERE a.mapname = b.mapname AND a.zonegroup = b.zonegroup AND b.style = %i) as total FROM ck_bonus a WHERE steamid = '%s' AND style = %i;", style, style, szSteamId, style); + Format(szQuery, 512, "SELECT mapname, (SELECT count(1)+1 FROM ck_bonus b WHERE a.mapname=b.mapname AND a.runtime > b.runtime AND a.zonegroup = b.zonegroup AND b.style = %i) AS `rank`, (SELECT count(1) FROM ck_bonus b WHERE a.mapname = b.mapname AND a.zonegroup = b.zonegroup AND b.style = %i) as total FROM ck_bonus a WHERE steamid = '%s' AND style = %i;", style, style, szSteamId, style); SQL_TQuery(g_hDb, sql_CountFinishedBonusCallback, szQuery, pack, DBPrio_Low); } else @@ -857,7 +857,7 @@ public void sql_CountFinishedBonusCallback(Handle owner, Handle hndl, const char g_WRs[client][style][1] = wrbs; // Next up: Points from stages char szQuery[512]; - Format(szQuery, 512, "SELECT mapname, stage, (select count(1)+1 from ck_wrcps b where a.mapname=b.mapname and a.runtimepro > b.runtimepro and a.style = b.style and a.stage = b.stage) AS rank FROM ck_wrcps a where steamid = '%s' AND style = %i;", szSteamId, style); + Format(szQuery, 512, "SELECT mapname, stage, (select count(1)+1 from ck_wrcps b where a.mapname=b.mapname and a.runtimepro > b.runtimepro and a.style = b.style and a.stage = b.stage) AS `rank` FROM ck_wrcps a where steamid = '%s' AND style = %i;", szSteamId, style); SQL_TQuery(g_hDb, sql_CountFinishedStagesCallback, szQuery, pack, DBPrio_Low); } @@ -922,7 +922,7 @@ public void sql_CountFinishedStagesCallback(Handle owner, Handle hndl, const cha // Next up: Points from maps char szQuery[512]; - Format(szQuery, 512, "SELECT mapname, (select count(1)+1 from ck_playertimes b where a.mapname=b.mapname and a.runtimepro > b.runtimepro AND b.style = %i) AS rank, (SELECT count(1) FROM ck_playertimes b WHERE a.mapname = b.mapname AND b.style = %i) as total, (SELECT tier FROM `ck_maptier` b WHERE a.mapname = b.mapname) as tier FROM ck_playertimes a where steamid = '%s' AND style = %i;", style, style, szSteamId, style); + Format(szQuery, 512, "SELECT mapname, (select count(1)+1 from ck_playertimes b where a.mapname=b.mapname and a.runtimepro > b.runtimepro AND b.style = %i) AS `rank`, (SELECT count(1) FROM ck_playertimes b WHERE a.mapname = b.mapname AND b.style = %i) as total, (SELECT tier FROM `ck_maptier` b WHERE a.mapname = b.mapname) as tier FROM ck_playertimes a where steamid = '%s' AND style = %i;", style, style, szSteamId, style); SQL_TQuery(g_hDb, sql_CountFinishedMapsCallback, szQuery, pack, DBPrio_Low); } @@ -3762,7 +3762,7 @@ public void SQL_selectBonusTotalCountCallback(Handle owner, Handle hndl, const c return; } -public void db_insertBonus(int client, char szSteamId[32], char szUName[32], float FinalTime, int zoneGrp) +public void db_insertBonus(int client, char szSteamId[32], char szUName[128], float FinalTime, int zoneGrp) { char szQuery[1024]; char szName[MAX_NAME_LENGTH * 2 + 1]; @@ -3792,7 +3792,7 @@ public void SQL_insertBonusCallback(Handle owner, Handle hndl, const char[] erro CalculatePlayerRank(client, 0); } -public void db_updateBonus(int client, char szSteamId[32], char szUName[32], float FinalTime, int zoneGrp) +public void db_updateBonus(int client, char szSteamId[32], char szUName[128], float FinalTime, int zoneGrp) { char szQuery[1024]; char szName[MAX_NAME_LENGTH * 2 + 1]; @@ -4524,9 +4524,9 @@ public void SQL_selectMapZonesCallback(Handle owner, Handle hndl, const char[] e Array_Copy(g_mapZones[g_mapZonesCount][PointA], posA, 3); Array_Copy(g_mapZones[g_mapZonesCount][PointB], posB, 3); AddVectors(posA, posB, result); - g_mapZones[g_mapZonesCount][CenterPoint][0] = FloatDiv(result[0], 2.0); - g_mapZones[g_mapZonesCount][CenterPoint][1] = FloatDiv(result[1], 2.0); - g_mapZones[g_mapZonesCount][CenterPoint][2] = FloatDiv(result[2], 2.0); + g_mapZones[g_mapZonesCount][CenterPoint][0] = result[0]/ 2.0; + g_mapZones[g_mapZonesCount][CenterPoint][1] = result[1]/ 2.0; + g_mapZones[g_mapZonesCount][CenterPoint][2] = result[2]/ 2.0; for (int i = 0; i < 3; i++) { @@ -4813,7 +4813,7 @@ public int LatestRecordsMenuHandler(Handle menu, MenuAction action, int param1, CloseHandle(menu); } -public void db_InsertLatestRecords(char szSteamID[32], char szName[32], float FinalTime) +public void db_InsertLatestRecords(char szSteamID[32], char szName[128], float FinalTime) { char szQuery[512]; Format(szQuery, 512, sql_insertLatestRecords, szSteamID, szName, FinalTime, g_szMapName); @@ -6530,7 +6530,7 @@ public int StageTopMenuHandler(Menu menu, MenuAction action, int client, int ite public void db_viewStageRecords() { char szQuery[512]; - Format(szQuery, 512, "SELECT name, MIN(runtimepro), stage, style FROM ck_wrcps WHERE mapname = '%s' GROUP BY stage, style;", g_szMapName); + Format(szQuery, 512, "SELECT name, MIN(runtimepro), stage, style FROM ck_wrcps WHERE mapname = '%s' GROUP BY name, stage, style;", g_szMapName); SQL_TQuery(g_hDb, sql_viewStageRecordsCallback, szQuery, 0, DBPrio_Low); } @@ -6931,7 +6931,7 @@ public void db_selectStyleMapTopSurfers(int client, char mapname[128], int style } // Styles for bonuses -public void db_insertBonusStyle(int client, char szSteamId[32], char szUName[32], float FinalTime, int zoneGrp, int style) +public void db_insertBonusStyle(int client, char szSteamId[32], char szUName[128], float FinalTime, int zoneGrp, int style) { char szQuery[1024]; char szName[MAX_NAME_LENGTH * 2 + 1]; @@ -7014,7 +7014,7 @@ public void db_viewMapRankBonusStyleCallback(Handle owner, Handle hndl, const ch } } -public void db_updateBonusStyle(int client, char szSteamId[32], char szUName[32], float FinalTime, int zoneGrp, int style) +public void db_updateBonusStyle(int client, char szSteamId[32], char szUName[128], float FinalTime, int zoneGrp, int style) { char szQuery[1024]; char szName[MAX_NAME_LENGTH * 2 + 1]; diff --git a/addons/sourcemod/scripting/surftimer/sql2.sp b/addons/sourcemod/scripting/surftimer/sql2.sp index 6231452..75ef265 100644 --- a/addons/sourcemod/scripting/surftimer/sql2.sp +++ b/addons/sourcemod/scripting/surftimer/sql2.sp @@ -144,7 +144,7 @@ public void SQL_ViewPlayerPrMaptimeCallback(Handle owner, Handle hndl, const cha char szQuery[1024]; - Format(szQuery, 1024, "SELECT db1.steamid, db1.name, db1.mapname, db1.runtimepro, db1.stage, (SELECT count(name) FROM ck_wrcps WHERE style = 0 AND mapname = db1.mapname AND stage = db1.stage AND runtimepro > -1.0 AND runtimepro <= db1.runtimepro) AS rank, (SELECT count(name) FROM ck_wrcps WHERE style = 0 AND mapname = db1.mapname AND stage = db1.stage AND runtimepro > -1.0) AS total FROM ck_wrcps db1 WHERE db1.mapname = '%s' AND db1.steamid = '%s' AND db1.runtimepro > -1.0 AND db1.style = 0 ORDER BY stage ASC", szMapName, szSteamId); + Format(szQuery, 1024, "SELECT db1.steamid, db1.name, db1.mapname, db1.runtimepro, db1.stage, (SELECT count(name) FROM ck_wrcps WHERE style = 0 AND mapname = db1.mapname AND stage = db1.stage AND runtimepro > -1.0 AND runtimepro <= db1.runtimepro) AS `rank`, (SELECT count(name) FROM ck_wrcps WHERE style = 0 AND mapname = db1.mapname AND stage = db1.stage AND runtimepro > -1.0) AS total FROM ck_wrcps db1 WHERE db1.mapname = '%s' AND db1.steamid = '%s' AND db1.runtimepro > -1.0 AND db1.style = 0 ORDER BY stage ASC", szMapName, szSteamId); SQL_TQuery(g_hDb, SQL_ViewPlayerPrMaptimeCallback2, szQuery, pack, DBPrio_Low); } @@ -874,7 +874,7 @@ public void SQL_SelectAnnouncementsCallback(Handle owner, Handle hndl, const cha } } -public void db_insertAnnouncement(char szName[32], char szMapName[128], char szTime[32]) +public void db_insertAnnouncement(char szName[128], char szMapName[128], char szTime[32]) { if (g_iServerID == -1) return; diff --git a/addons/sourcemod/scripting/surftimer/surfzones.sp b/addons/sourcemod/scripting/surftimer/surfzones.sp index 537f850..142424e 100644 --- a/addons/sourcemod/scripting/surftimer/surfzones.sp +++ b/addons/sourcemod/scripting/surftimer/surfzones.sp @@ -1930,9 +1930,9 @@ public int MenuHandler_Editor(Handle tMenu, MenuAction action, int client, int i float ZonePos[3]; surftimer_StopTimer(client); AddVectors(g_Positions[client][0], g_Positions[client][1], ZonePos); - ZonePos[0] = FloatDiv(ZonePos[0], 2.0); - ZonePos[1] = FloatDiv(ZonePos[1], 2.0); - ZonePos[2] = FloatDiv(ZonePos[2], 2.0); + ZonePos[0] = ZonePos[0]/ 2.0; + ZonePos[1] = ZonePos[1]/ 2.0; + ZonePos[2] = ZonePos[2]/ 2.0; TeleportEntity(client, ZonePos, NULL_VECTOR, NULL_VECTOR); EditorMenu(client); @@ -2044,27 +2044,27 @@ public int MenuHandler_Scale(Handle tMenu, MenuAction action, int client, int it } case 1: { - g_Positions[client][g_ClientSelectedPoint[client]][0] = FloatAdd(g_Positions[client][g_ClientSelectedPoint[client]][0], g_AvaliableScales[g_ClientSelectedScale[client]]); + g_Positions[client][g_ClientSelectedPoint[client]][0] = g_Positions[client][g_ClientSelectedPoint[client]][0] + g_AvaliableScales[g_ClientSelectedScale[client]]; } case 2: { - g_Positions[client][g_ClientSelectedPoint[client]][0] = FloatSub(g_Positions[client][g_ClientSelectedPoint[client]][0], g_AvaliableScales[g_ClientSelectedScale[client]]); + g_Positions[client][g_ClientSelectedPoint[client]][0] = g_Positions[client][g_ClientSelectedPoint[client]][0] - g_AvaliableScales[g_ClientSelectedScale[client]]; } case 3: { - g_Positions[client][g_ClientSelectedPoint[client]][1] = FloatAdd(g_Positions[client][g_ClientSelectedPoint[client]][1], g_AvaliableScales[g_ClientSelectedScale[client]]); + g_Positions[client][g_ClientSelectedPoint[client]][1] = g_Positions[client][g_ClientSelectedPoint[client]][1] + g_AvaliableScales[g_ClientSelectedScale[client]]; } case 4: { - g_Positions[client][g_ClientSelectedPoint[client]][1] = FloatSub(g_Positions[client][g_ClientSelectedPoint[client]][1], g_AvaliableScales[g_ClientSelectedScale[client]]); + g_Positions[client][g_ClientSelectedPoint[client]][1] = g_Positions[client][g_ClientSelectedPoint[client]][1] - g_AvaliableScales[g_ClientSelectedScale[client]]; } case 5: { - g_Positions[client][g_ClientSelectedPoint[client]][2] = FloatAdd(g_Positions[client][g_ClientSelectedPoint[client]][2], g_AvaliableScales[g_ClientSelectedScale[client]]); + g_Positions[client][g_ClientSelectedPoint[client]][2] = g_Positions[client][g_ClientSelectedPoint[client]][2] + g_AvaliableScales[g_ClientSelectedScale[client]]; } case 6: { - g_Positions[client][g_ClientSelectedPoint[client]][2] = FloatSub(g_Positions[client][g_ClientSelectedPoint[client]][2], g_AvaliableScales[g_ClientSelectedScale[client]]); + g_Positions[client][g_ClientSelectedPoint[client]][2] = g_Positions[client][g_ClientSelectedPoint[client]][2] - g_AvaliableScales[g_ClientSelectedScale[client]]; } case 7: { diff --git a/addons/sourcemod/scripting/swag.sp b/addons/sourcemod/scripting/swag.sp new file mode 100644 index 0000000..840078c --- /dev/null +++ b/addons/sourcemod/scripting/swag.sp @@ -0,0 +1,112 @@ +/* + This file is part of SourcePawn SteamWorks. + + SourcePawn SteamWorks is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, as per version 3 of the License. + + SourcePawn SteamWorks is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with SourcePawn SteamWorks. If not, see . + + Author: Kyle Sanderson (KyleS). +*/ + +#pragma semicolon 1 +#include +#include + +new Handle:g_hSteamServersConnected = INVALID_HANDLE; +new Handle:g_hSteamServersDisconnected = INVALID_HANDLE; + +public Plugin:myinfo = { + name = "SteamWorks Additive Glider", /* SWAG */ + author = "Kyle Sanderson", + description = "Translates SteamTools calls into SteamWorks calls.", + version = "1.0", + url = "http://AlliedMods.net" +}; + +public APLRes:AskPluginLoad2(Handle:myself, bool:late, String:error[], err_max) +{ + CreateNative("Steam_IsVACEnabled", native_IsVACEnabled); + CreateNative("Steam_GetPublicIP", native_GetPublicIP); + CreateNative("Steam_SetGameDescription", native_SetGameDescription); + CreateNative("Steam_IsConnected", native_IsConnected); + CreateNative("Steam_SetRule", native_SetRule); + CreateNative("Steam_ClearRules", native_ClearRules); + CreateNative("Steam_ForceHeartbeat", native_ForceHeartbeat); + + g_hSteamServersConnected = CreateGlobalForward("Steam_SteamServersConnected", ET_Ignore); + g_hSteamServersDisconnected = CreateGlobalForward("Steam_SteamServersDisconnected", ET_Ignore); + return APLRes_Success; +} + +public native_IsVACEnabled(Handle:plugin, numParams) +{ + return SteamWorks_IsVACEnabled(); +} + +public native_GetPublicIP(Handle:plugin, numParams) +{ + new addr[4]; + SteamWorks_GetPublicIP(addr); + SetNativeArray(1, addr, sizeof(addr)); + return 1; +} + +public native_SetGameDescription(Handle:plugin, numParams) +{ + decl String:sDesc[PLATFORM_MAX_PATH]; + GetNativeString(1, sDesc, sizeof(sDesc)); + return SteamWorks_SetGameDescription(sDesc); +} + +public native_IsConnected(Handle:plugin, numParams) +{ + return SteamWorks_IsConnected(); +} + +public native_SetRule(Handle:plugin, numParams) +{ + decl String:sKey[PLATFORM_MAX_PATH], String:sValue[PLATFORM_MAX_PATH]; + GetNativeString(1, sKey, sizeof(sKey)); + GetNativeString(2, sValue, sizeof(sValue)); + return SteamWorks_SetRule(sKey, sValue); +} + +public native_ClearRules(Handle:plugin, numParams) +{ + return SteamWorks_ClearRules(); +} + +public native_ForceHeartbeat(Handle:plugin, numParams) +{ + return SteamWorks_ForceHeartbeat(); +} + +public SteamWorks_SteamServersConnected() +{ + if (GetForwardFunctionCount(g_hSteamServersConnected) == 0) + { + return; + } + + Call_StartForward(g_hSteamServersConnected); + Call_Finish(); +} + +public SteamWorks_SteamServersDisconnected() +{ + if (GetForwardFunctionCount(g_hSteamServersDisconnected) == 0) + { + return; + } + + Call_StartForward(g_hSteamServersDisconnected); + Call_Finish(); +}