diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 50f76f0..b9247be 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -55,7 +55,7 @@ further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at Robin.Rott1@web.de. All +reported by contacting the project team on GitHub. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. diff --git a/Compile.bat b/Compile.bat index cbf2b59..8ae41a8 100644 --- a/Compile.bat +++ b/Compile.bat @@ -1,9 +1,9 @@ -copy /v /y ".\scripting\1.10\kigen-ac_redux\" ".\scripting\1.8\kigen-ac_redux\" -copy /v /y ".\scripting\1.10\kigen-ac_redux.sp" ".\scripting\1.8\kigen-ac_redux.sp" +copy /v /y ".\scripting\latest\kigen-ac_redux\" ".\scripting\1.8\kigen-ac_redux\" +copy /v /y ".\scripting\latest\kigen-ac_redux.sp" ".\scripting\1.8\kigen-ac_redux.sp" cd ./scripting/1.8 spcomp.exe kigen-ac_redux.sp -o../../plugins/kigen-ac_redux_legacy.smx -cd ../1.10 +cd ../latest spcomp.exe kigen-ac_redux.sp -o../../plugins/kigen-ac_redux.smx pause \ No newline at end of file diff --git a/Licenses/License_SMLIB.txt b/Licenses/License_SMLIB.txt deleted file mode 100644 index 7d99a20..0000000 --- a/Licenses/License_SMLIB.txt +++ /dev/null @@ -1,16 +0,0 @@ - SMLIB - Copyright (C) SMLIB Contributors - - This program 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, either version 3 of the License, or - (at your option) any later version. - - 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 . - diff --git a/README.md b/README.md index 9e3fbae..0a353c5 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,16 @@ # Kigen Anti Cheat Redux ### Project Status: Maintained, Rolling Release -SMAC and KAC are outdated, VAC dosent do its Job, NoCheatz-4 is discontinued and Community Projects are often small or unstable. -KACR is aimed to be a failsafe universal Security and Anti Cheat Solution for all common Source based Games. + +KACR is aimed to be a failsafe universal security and anti-cheat Solution for all common Source based games. # Requires: -- SourceMod 1.8 or higher (kigen-ac_redux is for 1.10, kigen-ac_redux_legacy for 1.8/1.9) +- SourceMod 1.8 or higher (kigen-ac_redux is for 1.12, kigen-ac_redux_legacy for previous version) Optional: - Sourcebans++ - Sourcebans 2.X (V1 isent supported) -Official supported Games: +Official supported games: - Counter-Strike: Global Offensive - Team Fortress 2 - Counter-Strike: Source @@ -18,10 +18,13 @@ Official supported Games: - Insurgency - Day of Defeat: Source - Half-Life 2: Deathmatch -#### KACR should work on most Source 2007+ Engine Game +#### KACR should work on most games using the Source 2007 engine or newer +#### Source 2 games like Counter-Strike 2 [wont be supported](https://wiki.alliedmods.net/Introduction_to_SourceMod_Plugins#Will_SourceMod_support_Source_2.3F_Will_plugins_for_existing_games_continue_to_work_if_they_are_ported.3F) # -Since i havent implemented an Updater yet, watch this Project on GitHub so you will be informed about Updates. -![How to watch](https://help.github.com/assets/images/help/repository/repo-actions-watch.png) +Since i havent implemented an updater yet, watch this project on GitHub so you will be informed about updates. # -If you want to help you can Contribute to the Project by submitting Code, Bugs, False-Positives, Wiki Entrys and Translations. -Information on how to submit Code, Wiki Entrys and Translations can be found in CONTRIBUTING.md +If you want to help you can contribute to the project by submitting code, bugs, false-positives, wiki entrys and translations. +Information on how to submit code, wiki entrys and translations can be found in the CONTRIBUTING.md file. + +Credits: +-AutoExecConfig from Impact diff --git a/plugins/kigen-ac_redux.smx b/plugins/kigen-ac_redux.smx index 4981a4d..52ed61e 100644 Binary files a/plugins/kigen-ac_redux.smx and b/plugins/kigen-ac_redux.smx differ diff --git a/plugins/kigen-ac_redux_legacy.smx b/plugins/kigen-ac_redux_legacy.smx index b4223f8..20834fa 100644 Binary files a/plugins/kigen-ac_redux_legacy.smx and b/plugins/kigen-ac_redux_legacy.smx differ diff --git a/scripting/#Note - Only Code in 1.10.txt b/scripting/#Note - Only Code in latest.txt similarity index 58% rename from scripting/#Note - Only Code in 1.10.txt rename to scripting/#Note - Only Code in latest.txt index 1fcfd3d..ade571a 100644 --- a/scripting/#Note - Only Code in 1.10.txt +++ b/scripting/#Note - Only Code in latest.txt @@ -1,3 +1,3 @@ -The compiler batch will copy everythin in 1.10 to 1.18 before compiling +The compiler batch will copy everything from the latest folder to 1.18 before compiling There is also the possability to check the modification date but i dont want to have a 50+ line Script just for compiling \ No newline at end of file diff --git a/scripting/1.10/include/geoip.inc b/scripting/1.10/include/geoip.inc deleted file mode 100644 index be6653d..0000000 --- a/scripting/1.10/include/geoip.inc +++ /dev/null @@ -1,102 +0,0 @@ -/** - * vim: set ts=4 : - * ============================================================================= - * SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved. - * ============================================================================= - * - * This file is part of the SourceMod/SourcePawn SDK. - * - * 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$ - */ - -#if defined _geoip_included - #endinput -#endif -#define _geoip_included - -#include - -/** - * @section IP addresses can contain ports, the ports will be stripped out. - */ - -/** - * 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. - */ -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. - */ -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. - */ -native bool GeoipCountry(const char[] ip, char[] name, int maxlength); - -/** - * @endsection - */ - -/** - * Do not edit below this line! - */ -public Extension __ext_geoip = -{ - name = "GeoIP", - file = "geoip.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 void __ext_geoip_SetNTVOptional() -{ - MarkNativeAsOptional("GeoipCode2"); - MarkNativeAsOptional("GeoipCode3"); - MarkNativeAsOptional("GeoipCountry"); -} -#endif diff --git a/scripting/1.10/include/smlib/arrays.inc b/scripting/1.10/include/smlib/arrays.inc deleted file mode 100644 index 1c9863e..0000000 --- a/scripting/1.10/include/smlib/arrays.inc +++ /dev/null @@ -1,158 +0,0 @@ -#if defined _smlib_array_included - #endinput -#endif -#define _smlib_array_included - -#include - -/** - * Returns the index for the first occurance of the given value. - * If the value cannot be found, -1 will be returned. - * - * @param array Static Array. - * @param size Size of the Array. - * @param value Value to search for. - * @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) -{ - if (start < 0) { - start = 0; - } - - for (new i=start; i < size; i++) { - - if (array[i] == value) { - return i; - } - } - - return -1; -} - -/** - * Searchs for the first occurance of a string in the array. - * If the value cannot be located, -1 will be returned. - * - * @param array Static Array. - * @param size Size of the Array. - * @param value String to search for. - * @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) -{ - if (start < 0) { - start = 0; - } - - for (new i=start; i < size; i++) { - - if (StrEqual(array[i], str, caseSensitive)) { - return i; - } - } - - return -1; -} - -/** - * Returns the Index of the Lowest value in the array - * - * @param array Static Array. - * @param size Size of the Array. - * @param start Optional: Offset where to start (0 - (size-1)). - * @return Array index. - */ -stock Array_FindLowestValue(any:array[], size, start=0) -{ - if (start < 0) { - start = 0; - } - - new any:value = array[start]; - new any:tempValue; - new x = start; - - for (new i=start; i < size; i++) { - - tempValue = array[i]; - - if (tempValue < value) { - value = tempValue; - x = i; - } - - } - - return x; -} - -/** - * Returns the Index of the Highest value in the array - * - * @param array Static Array. - * @param size Size of the Array. - * @param start Optional: Offset where to start (0 - (size-1)). - * @return Array index. - */ -stock Array_FindHighestValue(any:array[], size, start=0) -{ - if (start < 0) { - start = 0; - } - - new any:value = array[start]; - new any:tempValue; - new x = start; - - for (new i=start; i < size; i++) { - - tempValue = array[i]; - - if (tempValue > value) { - value = tempValue; - x = i; - } - - } - - return x; -} - -/** - * Fills an array with a given value in a 1 dimensional static array. - * You can specify the amount of cells to be written. - * - * @param array Static Array. - * @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) -{ - if (start < 0) { - start = 0; - } - - for (new i=start; i < size; i++) { - array[i] = value; - } -} - -/** - * Copies a 1 dimensional static array. - * - * @param array Static Array to copy from. - * @param newArray New Array to copy to. - * @param size Size of the array (or number of cells to copy) - * @noreturn - */ -stock Array_Copy(const any:array[], any:newArray[], size) -{ - for (new i=0; i < size; i++) { - newArray[i] = array[i]; - } -} diff --git a/scripting/1.10/include/smlib/clients.inc b/scripting/1.10/include/smlib/clients.inc deleted file mode 100644 index 0fca2bc..0000000 --- a/scripting/1.10/include/smlib/clients.inc +++ /dev/null @@ -1,3121 +0,0 @@ -#if defined _smlib_client_included - #endinput -#endif -#define _smlib_client_included - -// Defined here beacause needed in teams.inc -#define CLIENTFILTER_ALL 0 // No filtering -#define CLIENTFILTER_BOTS ( 1 << 1 ) // Fake clients -#define CLIENTFILTER_NOBOTS ( 1 << 2 ) // No fake clients -#define CLIENTFILTER_AUTHORIZED ( 1 << 3 ) // SteamID validated -#define CLIENTFILTER_NOTAUTHORIZED ( 1 << 4 ) // SteamID not validated (yet) -#define CLIENTFILTER_ADMINS ( 1 << 5 ) // Generic Admins (or higher) -#define CLIENTFILTER_NOADMINS ( 1 << 6 ) // No generic admins -// All flags below require ingame checking (optimization) -#define CLIENTFILTER_INGAME ( 1 << 7 ) // Ingame -#define CLIENTFILTER_INGAMEAUTH ( 1 << 8 ) // Ingame & Authorized -#define CLIENTFILTER_NOTINGAME ( 1 << 9 ) // Not ingame (currently connecting) -#define CLIENTFILTER_ALIVE ( 1 << 10 ) // Alive -#define CLIENTFILTER_DEAD ( 1 << 11 ) // Dead -#define CLIENTFILTER_SPECTATORS ( 1 << 12 ) // Spectators -#define CLIENTFILTER_NOSPECTATORS ( 1 << 13 ) // No Spectators -#define CLIENTFILTER_OBSERVERS ( 1 << 14 ) // Observers -#define CLIENTFILTER_NOOBSERVERS ( 1 << 15 ) // No Observers -#define CLIENTFILTER_TEAMONE ( 1 << 16 ) // First Team (Terrorists, ...) -#define CLIENTFILTER_TEAMTWO ( 1 << 17 ) // Second Team (Counter-Terrorists, ...) - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -/** - * Very useful macro to iterate all clients - * matching the specified flags. - * - * @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)) - -/** - * Macro for iterating trough all observers of a player. - * - * @param 1 Client Index for who to get the observers. - * @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)) - -/** - * Very useful macro to iterate all weapons of a client. - * - * @param 1 Client Index - * @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)) - -// Hud Element hiding flags (possibly outdated) -#define HIDEHUD_WEAPONSELECTION ( 1<<0 ) // Hide ammo count & weapon selection -#define HIDEHUD_FLASHLIGHT ( 1<<1 ) -#define HIDEHUD_ALL ( 1<<2 ) -#define HIDEHUD_HEALTH ( 1<<3 ) // Hide health & armor / suit battery -#define HIDEHUD_PLAYERDEAD ( 1<<4 ) // Hide when local player's dead -#define HIDEHUD_NEEDSUIT ( 1<<5 ) // Hide when the local player doesn't have the HEV suit -#define HIDEHUD_MISCSTATUS ( 1<<6 ) // Hide miscellaneous status elements (trains, pickup history, death notices, etc) -#define HIDEHUD_CHAT ( 1<<7 ) // Hide all communication elements (saytext, voice icon, etc) -#define HIDEHUD_CROSSHAIR ( 1<<8 ) // Hide crosshairs -#define HIDEHUD_VEHICLE_CROSSHAIR ( 1<<9 ) // Hide vehicle crosshair -#define HIDEHUD_INVEHICLE ( 1<<10 ) -#define HIDEHUD_BONUS_PROGRESS ( 1<<11 ) // Hide bonus progress display (for bonus map challenges) - -/** -* Sets the Hide-Hud flags of a client -* -* @param client Client index. -* @param flags Flag to set, use one of the HIDEHUD_ hiding constants -* @noreturn -*/ -stock Client_SetHideHud(client, flags) -{ - SetEntProp(client, Prop_Send, "m_iHideHUD", flags); -} - -/** -* Checks if the specified index is a player and connected. -* -* @param entity An entity index. -* @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) -{ - if (client > 4096) { - client = EntRefToEntIndex(client); - } - - if (client < 1 || client > MaxClients) { - return false; - } - - if (checkConnected && !IsClientConnected(client)) { - return false; - } - - return true; -} - -/** -* Checks if the specified index is a player and ingame. -* -* @param entity An entity index. -* @return Returns true if the specified index is a player and ingame, false otherwise. -*/ -stock bool:Client_IsIngame(client) -{ - if (!Client_IsValid(client, false)) { - return false; - } - - return IsClientInGame(client); -} - -/** -* Checks if the specified index is a player, ingame and authorized. -* -* @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) -{ - if (!Client_IsIngame(client)) { - return false; - } - - return IsClientAuthorized(client); -} - -#define MAX_STEAMAUTH_LENGTH 21 - -/** -* Finds a player by his SteamID -* -* @param auth SteamID to search for -* @return Client Index or -1 -*/ -stock Client_FindBySteamId(const String:auth[]) -{ - new String:clientAuth[MAX_STEAMAUTH_LENGTH]; - for (new client=1; client <= MaxClients; client++) { - if (!IsClientAuthorized(client)) { - continue; - } - - GetClientAuthId(client, AuthId_Steam2, clientAuth, sizeof(clientAuth)); - - if (StrEqual(auth, clientAuth)) { - return client; - } - } - - return -1; -} - -/** -* Finds a player by his name. -* Only returns the first matching player. -* -* @param name Name to search for. -* @param partOfName Whether to search for the part of a name or compare the full name. -* @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) -{ - new String:clientName[MAX_NAME_LENGTH]; - for (new client=1; client <= MaxClients; client++) { - if (!IsClientAuthorized(client)) { - continue; - } - - GetClientName(client, clientName, sizeof(clientName)); - - if (partOfName) { - if (StrContains(clientName, name, caseSensitive) != -1) { - return client; - } - } - else if (StrEqual(name, clientName, caseSensitive)) { - return client; - } - } - - return -1; -} - -// Spectator Movement modes -enum Obs_Mode -{ - OBS_MODE_NONE = 0, // not in spectator mode - OBS_MODE_DEATHCAM, // special mode for death cam animation - OBS_MODE_FREEZECAM, // zooms to a target, and freeze-frames on them - OBS_MODE_FIXED, // view from a fixed camera position - OBS_MODE_IN_EYE, // follow a player in first person view - OBS_MODE_CHASE, // follow a player in third person view - OBS_MODE_ROAMING, // free roaming - - NUM_OBSERVER_MODES -}; - -// Force Camera Restrictions with mp_forcecamera -enum Obs_Allow -{ - OBS_ALLOW_ALL = 0, // allow all modes, all targets - OBS_ALLOW_TEAM, // allow only own team & first person, no PIP - OBS_ALLOW_NONE, // don't allow any spectating after death (fixed & fade to black) - - OBS_ALLOW_NUM_MODES, -}; - -/** - * Gets the client's observer mode (Obs_Mode). - * - * @param client Client Index. - * @return The current observer mode (ObsMode). - */ -stock Obs_Mode:Client_GetObserverMode(client) -{ - return Obs_Mode:GetEntProp(client, Prop_Send, "m_iObserverMode"); -} - - -/** - * Sets the client's observer mode. - * Use a value of the Obs_Mode enum. - * This is a rewrite of CBasePlayer::SetObserverMode(). - * - * @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) -{ - if (mode < OBS_MODE_NONE || mode >= NUM_OBSERVER_MODES) { - return false; - } - - // check mp_forcecamera settings for dead players - if (mode > OBS_MODE_FIXED && GetClientTeam(client) > TEAM_SPECTATOR) - { - new Handle:mp_forcecamera = FindConVar("mp_forcecamera"); - - if (mp_forcecamera != INVALID_HANDLE) { - switch (GetConVarInt(mp_forcecamera)) - { - case OBS_ALLOW_TEAM: { - mode = OBS_MODE_IN_EYE; - } - case OBS_ALLOW_NONE: { - mode = OBS_MODE_FIXED; // don't allow anything - } - } - } - } - - new 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); - - switch (mode) { - case OBS_MODE_NONE, OBS_MODE_FIXED, OBS_MODE_DEATHCAM: { - Client_SetFOV(client, 0); // Reset FOV - - if (updateMoveType) { - SetEntityMoveType(client, MOVETYPE_NONE); - } - } - case OBS_MODE_CHASE, OBS_MODE_IN_EYE: { - // udpate FOV and viewmodels - Client_SetViewOffset(client, NULL_VECTOR); - - if (updateMoveType) { - SetEntityMoveType(client, MOVETYPE_OBSERVER); - } - } - case OBS_MODE_ROAMING: { - Client_SetFOV(client, 0); // Reset FOV - Client_SetViewOffset(client, NULL_VECTOR); - - if (updateMoveType) { - SetEntityMoveType(client, MOVETYPE_OBSERVER); - } - } - } - - return true; -} - -/** - * Gets the client's last oberserver mode - * - * @param client Client Index. - * @return Last Observer mode - */ -stock Obs_Mode:Client_GetObserverLastMode(client) -{ - return Obs_Mode:GetEntProp(client, Prop_Data, "m_iObserverLastMode"); -} - -/** - * Sets the client's last oberserver mode - * - * @param client Client Index. - * @param mode Last Observer mode - * @noreturn - */ -stock Client_SetObserverLastMode(client, Obs_Mode:mode) -{ - SetEntProp(client, Prop_Data, "m_iObserverLastMode", _:mode); -} - -/** - * Gets the client's view offset. - * This is the position relative to the client itself. - * - * @param client Client Index. - * @param vec Vector Buffer. - * @noreturn - */ -stock Client_GetViewOffset(client, Float:vec[3]) -{ - GetEntPropVector(client, Prop_Data, "m_vecViewOffset", vec); -} - -/** - * Sets the client's view offset. - * This is the position relative to the client itself. - * - * @param client Client Index. - * @param vec Vector buffer. - * @noreturn - */ -stock Client_SetViewOffset(client, Float:vec[3]) -{ - SetEntPropVector(client, Prop_Data, "m_vecViewOffset", vec); -} - -/** - * Gets the client's current observer target entity. - * - * @param client Client Index. - * @return Observed Entity Index. - */ -stock Client_GetObserverTarget(client) -{ - return GetEntPropEnt(client, Prop_Send, "m_hObserverTarget"); -} - -/** - * Sets the client's current observer target entity. - * - * @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) -{ - SetEntPropEnt(client, Prop_Send, "m_hObserverTarget", entity); - - if (resetFOV) { - Client_SetFOV(client, 0); - } -} - -/** - * Gets the client's Field Of View. - * - * @param client Client Index. - * @return Field Of View - */ -stock Client_GetFOV(client) -{ - return GetEntProp(client, Prop_Send, "m_iFOV"); -} - -/** - * Sets the client's Field Of View. - * - * @param client Client Index. - * @param value Field Of View - * @noreturn - */ -stock Client_SetFOV(client, value) -{ - SetEntProp(client, Prop_Send, "m_iFOV", value); -} - -/** - * Checks if the client's View Model is drawn for the client. - * - * @param client Client Index. - * @return True if the viewmodel is drawn, false otherwise. - */ -stock bool:Client_DrawViewModel(client) -{ - return bool:GetEntProp(client, Prop_Send, "m_bDrawViewmodel"); -} - -/** - * Sets if to draw the client's view model for the client. - * - * @param client Client Index. - * @param drawViewModel Set to true if to draw, false otherwise. - * @noreturn - */ -stock Client_SetDrawViewModel(client, bool:drawViewModel) -{ - SetEntProp(client, Prop_Send, "m_bDrawViewmodel", drawViewModel); -} - -/** - * Puts the specified client into thirdperson or back to firstperson when false - * This doesn't work correctly in all games, it works in CS:S and DOD:S and some other games. - * Todo: Enhance this - * - * @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) -{ - if (enable) { - Client_SetObserverTarget(client, 0); - Client_SetObserverMode(client, OBS_MODE_DEATHCAM, false); - Client_SetDrawViewModel(client, false); - Client_SetFOV(client, 120); - } - else { - Client_SetObserverTarget(client, -1); - Client_SetObserverMode(client, OBS_MODE_NONE, false); - Client_SetDrawViewModel(client, true); - Client_SetFOV(client, 90); - } -} - -/** - * Checks if the client is in thirdperson mode - * - * @param client Cient Undex - * @return true if the client is currently in thirdperson mode, false otherwise - */ -stock Client_IsInThirdPersonMode(client) -{ - return GetEntProp(client, Prop_Data, "m_iObserverMode"); -} - -#define FFADE_IN 0x0001 // Just here so we don't pass 0 into the function -#define FFADE_OUT 0x0002 // Fade out (not in) -#define FFADE_MODULATE 0x0004 // Modulate (don't blend) -#define FFADE_STAYOUT 0x0008 // ignores the duration, stays faded out until new ScreenFade message received -#define FFADE_PURGE 0x0010 // Purges all other fades, replacing them with this one - -/** - * Fades a client's screen to a specified color - * Your adviced to read the FFADE_ Comments - * - * @param client Player for which to fade the screen - * @param duration duration in seconds the effect stays - * @param mode fade mode, see FFADE_ defines - * @param holdtime holdtime in seconds - * @param r red amount - * @param g green amount - * @param b blue amount - * @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) -{ - new Handle:userMessage = StartMessageOne("Fade", client, (reliable?USERMSG_RELIABLE:0)); - - if (userMessage == INVALID_HANDLE) { - return false; - } - - if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && - GetUserMessageType() == UM_Protobuf) { - - new color[4]; - color[0] = r; - color[1] = g; - color[2] = b; - color[3] = a; - - PbSetInt(userMessage, "duration", duration); - PbSetInt(userMessage, "hold_time", holdtime); - PbSetInt(userMessage, "flags", mode); - PbSetColor(userMessage, "clr", color); - } - else { - BfWriteShort(userMessage, duration); // Fade duration - BfWriteShort(userMessage, holdtime); // Fade hold time - BfWriteShort(userMessage, mode); // What to do - BfWriteByte(userMessage, r); // Color R - BfWriteByte(userMessage, g); // Color G - BfWriteByte(userMessage, b); // Color B - BfWriteByte(userMessage, a); // Color Alpha - } - EndMessage(); - - return true; -} - -/** - * This function retrieves an array that holds all clones of a client by IP check. - * Size of CloneList has to be MaxClients at least, or MAX_PLAYERS - * - * @param client Client index. - * @param closelist An array that holds all clones of a client. - * @return Returns how many clones a client has. - */ -stock Client_GetClones(client, cloneList[]) -{ - new x=0; - decl String:ip_client[16], String:ip_player[16]; - - GetClientIP(client, ip_client, sizeof(client)); - - for (new player=1; player <= MaxClients; player++) { - - if (IsClientInGame(player)) { - GetClientIP(player, ip_player, sizeof(ip_player)); - - if (StrEqual(ip_client, ip_player, false)) { - cloneList[x++] = player; - } - } - } - - return x; -} - -/* - * This function returns true if the client is at a ladder.. - * - * @param client Client index. - * @return Returns true if the client is on a ladder other wise false. - */ -stock bool:Client_IsOnLadder(client) -{ - new MoveType:movetype = GetEntityMoveType(client); - - if (movetype == MOVETYPE_LADDER) { - return true; - } - else{ - return false; - } -} - -enum Water_Level -{ - WATER_LEVEL_NOT_IN_WATER = 0, - WATER_LEVEL_FEET_IN_WATER, - WATER_LEVEL_WAIST_IN_WATER, - WATER_LEVEL_HEAD_IN_WATER -}; - -/* - * This function returns how deep a client is in water. - * - * @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) -{ - return Water_Level:GetEntProp(client, Prop_Send, "m_nWaterLevel"); -} - -/* - * Returns how much suit sprint power a client has left in percent. - * - * @param client Client index. - * @return returns the actual power left in percent. - */ -stock Float:Client_GetSuitSprintPower(client) -{ - return GetEntPropFloat(client, Prop_Send, "m_flSuitPower"); -} - -/* - * Sets a client suit sprint power in percent. - * - * @param client Client index. - * @param power power (0.0 to 100.0) - * @noreturn - */ -stock Client_SetSuitSprintPower(client, Float:power) -{ - SetEntPropFloat(client, Prop_Send, "m_flSuitPower", power); -} - -/* - * Returns the client count put in the server. - * - * @param inGameOnly If false connecting players are also counted. - * @param countBots If true bots will be counted too. - * @return Client count in the server. - */ -stock Client_GetCount(bool:countInGameOnly=true, bool:countFakeClients=true) -{ - new numClients = 0; - - for (new client=1; client <= MaxClients; client++) { - - if (!IsClientConnected(client)) { - continue; - } - - if (countInGameOnly && !IsClientInGame(client)) { - continue; - } - - if (!countFakeClients && IsFakeClient(client)) { - continue; - } - - numClients++; - } - - return numClients; -} - -/* - * Returns the ping of a client like it is displayed in the scoreboard. - * The weird calculation formula is taken from Valve's SDK - * hl2sdk\game\server\util.cpp: UTIL_GetPlayerConnectionInfo() - * The Scoreboard uses the goldSource corrected Ping, the net_graph doesn't - * For Fake Clients 0 is returned. - * - * @param client Client index - * @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) -{ - if (IsFakeClient(client)) { - return 0; - } - - new ping; - new 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]; - GetClientInfo(client, "cl_cmdrate", cl_cmdrate, sizeof(cl_cmdrate)); - - new Float:tickRate = GetTickInterval(); - latency -= (0.5 / StringToInt(cl_cmdrate)) + TICKS_TO_TIME(1.0); // correct latency - - if (goldSource) { - // in GoldSrc we had a different, not fixed tickrate. so we have to adjust - // Source pings by half a tick to match the old GoldSrc pings. - latency -= tickRate * 0.5; - } - - ping = RoundFloat(latency * 1000.0); // as msecs - ping = Math_Clamp(ping, 5, 1000); // set bounds, dont show pings under 5 msecs - - return ping; -} - -/** - * Searches for the closest client in relation to the given client. - * - * @param client Client index - * @return The closest client or -1 - */ -stock Client_GetClosestToClient(client) -{ - return Edict_GetClosestToEdict(client, true); -} - -/** - * Gets the name of the last place (if set by the game) - * - * @param entity Entity index. - * @param buffer String buffer - * @param size Size of the String buffer - * @noreturn - */ -stock Client_GetLastPlaceName(client, String:buffer[], size) -{ - GetEntPropString(client, Prop_Send, "m_szLastPlaceName", buffer, size); -} - -/** - * Returns the client's Score. - * - * @param client Client's index. - * @return Score. - */ -stock Client_GetScore(client) -{ - return GetClientFrags(client); -} - -/** - * Sets the client's Score. - * - * @param client Client's index. - * @param value Score. - * @noreturn - */ -stock Client_SetScore(client, value) -{ - SetEntProp(client, Prop_Data, "m_iFrags", value); -} - -/** - * Returns the client's Death count - * - * @param client Client's index. - * @return Death count - */ -stock Client_GetDeaths(client) -{ - return GetEntProp(client, Prop_Data, "m_iDeaths"); -} - -/** - * Sets the client's Death count. - * - * @param client Client's index. - * @param value Death count - * @noreturn - */ -stock Client_SetDeaths(client, value) -{ - SetEntProp(client, Prop_Data, "m_iDeaths", value); -} - -/** - * Returns the client's Armor - * - * @param client Client's index. - * @return Armor value - */ -stock Client_GetArmor(client) -{ - return GetEntProp(client, Prop_Data, "m_ArmorValue"); -} - -/** - * Sets the client's Armor. - * - * @param client Client's index. - * @param value Armor value - * @noreturn - */ -stock Client_SetArmor(client, value) -{ - SetEntProp(client, Prop_Data, "m_ArmorValue", value); -} - -/** - * Returns the client's Suitpower - * - * @param client Client's index. - * @return Suitpower - */ -stock Float:Client_GetSuitPower(client) -{ - return Float:GetEntPropFloat(client, Prop_Data, "m_flSuitPower"); -} - -/** - * Sets the client's Suitpower - * - * @param client Client's index. - * @param value Suitpower - * @noreturn - */ -stock Client_SetSuitPower(client, Float:value) -{ - SetEntPropFloat(client, Prop_Data, "m_flSuitPower", value); -} - -// suit usage bits -#define bits_SUIT_DEVICE_SPRINT 0x00000001 -#define bits_SUIT_DEVICE_FLASHLIGHT 0x00000002 -#define bits_SUIT_DEVICE_BREATHER 0x00000004 -#define MAX_SUIT_DEVICES 3 - -/** - * Returns the client's active devices (Max MAX_SUIT_DEVICES) - * The return is a bitwise value with bits_SUIT_DEVICE_SPRINT, - * bits_SUIT_DEVICE_FLASHLIGHT and/or bits_SUIT_DEVICE_BREATHER set. - * - * @param client Client's index. - * @return The active devices (bitwise value) - */ -stock Client_GetActiveDevices(client) -{ - return GetEntProp(client, Prop_Send, "m_bitsActiveDevices"); -} - -/** - * Returns the time when the client is allowed to spray - * a decal again. - * - * @param client Client's index. - * @return Next decal time - */ -stock Float:Client_GetNextDecalTime(client) -{ - return GetEntPropFloat(client, Prop_Data, "m_flNextDecalTime"); -} - -/** - * Returns whether the client is allowed to spray a decal or not. - * - * @param client Client's index. - * @return True if he is allowed to spray a decal, false otherwise - */ -stock bool:Client_CanSprayDecal(client) -{ - return Client_GetNextDecalTime(client) <= GetGameTime(); -} - -/** - * Returns the vehicle the client is in, if the client - * isn't in a vehicle, -1 is returned. - * - * @param client Client's index. - * @return Vehicle index, -1 if the client isn't in a vehicle. - */ -stock Client_GetVehicle(client) -{ - new m_hVehicle = GetEntPropEnt(client, Prop_Send, "m_hVehicle"); - - return m_hVehicle; -} - -/** - * Returns whether the client is in a vehicle or not. - * - * @param client Client's index. - * @return True if he is in a vehicle, false otherwise - */ -stock bool:Client_IsInVehicle(client) -{ - return !(Client_GetVehicle(client) == -1); -} - -/** - * Removes all decals for a client - * - * @param client Client's index. - * @noreturn - */ -stock Client_RemoveAllDecals(client) -{ - ClientCommand(client, "r_cleardecals"); -} - -/** - * Let's the client exit the vehicle - * - * @param vehicle Client index. - * @return True on success, false otherwise. - */ -stock bool:Client_ExitVehicle(client) -{ - new vehicle = Client_GetVehicle(client); - - if (vehicle == -1) { - return false; - } - - return AcceptEntityInput(vehicle, "ExitVehicle"); -} - -/** - * Plays a soundfile as if the player is using voicecomm for a single client. - * The voiceindicator is shown on the right, as if the players is talking. - * Thanks to Peace-Maker for the function. - * - * @param client For whom to play the sound. - * @param emitter Player/Entity the voice stream comes from. - * @param soundfile Path to the soundfile relative to the sound folder. - * @param length Length in seconds how long the hud "voiceindicator" is shown. - * @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) -{ - new Handle:message = StartMessageOne("RawAudio", client); - - if (message == INVALID_HANDLE) { - return false; - } - - if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available - && GetUserMessageType() == UM_Protobuf) { - - PbSetInt(message, "pitch", pitch); - PbSetInt(message, "entidx", emitter); - PbSetFloat(message, "duration", length ); - PbSetString(message, "voice_filename", soundfile); - } - else { - BfWriteByte(message, pitch); - BfWriteByte(message, emitter); - BfWriteFloat(message, length); - BfWriteString(message, soundfile); - } - EndMessage(); - - return true; -} - -/** - * Plays a soundfile as if the player is using voicecomm for all players. - * The voiceindicator is shown on the right, as if the players is talking. - * Thanks to Peace-Maker for the function. - * - * @param emitter Player/Entity the voice stream comes from. - * @param soundfile Path to the soundfile relative to the sound folder. - * @param length Length in seconds how long the hud "voiceindicator" is shown. - * @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) -{ - new Handle:message = StartMessageAll("RawAudio"); - - if (message == INVALID_HANDLE) { - return false; - } - - if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available - && GetUserMessageType() == UM_Protobuf) { - - PbSetInt(message, "pitch", pitch); - PbSetInt(message, "entidx", emitter); - PbSetFloat(message, "duration", length); - PbSetString(message, "voice_filename", soundfile); - } - else { - BfWriteByte(message, pitch); - BfWriteByte(message, emitter); - BfWriteFloat(message, length); - BfWriteString(message, soundfile); - } - EndMessage(); - - return true; -} - -/** - * Sets an Impulse value for a client (eg: "impulse 100" for flashlight, value would be 100). - * See: http://developer.valvesoftware.com/wiki/Impulse - * - * @param client Client Index - * @param value The impulse command value. - * @return True on success, false on failure. - */ -stock Client_Impulse(client, value) -{ - SetEntProp(client, Prop_Data, "m_nImpulse", value); -} - -/** - * Gets the offset for a client's weapon list (m_hMyWeapons). - * The offset will saved globally for optimization. - * - * @param client Client Index. - * @return Weapon list offset or -1 on failure. - */ -stock Client_GetWeaponsOffset(client) -{ - static offset = -1; - - if (offset == -1) { - offset = FindDataMapInfo(client, "m_hMyWeapons"); - } - - return offset; -} - -/** - * Gets the current/active weapon of a client - * - * @param client Client Index. - * @return Weapon Index or INVALID_ENT_REFERENCE if the client has no active weapon. - */ -stock Client_GetActiveWeapon(client) -{ - new weapon = GetEntPropEnt(client, Prop_Data, "m_hActiveWeapon"); - - if (!Entity_IsValid(weapon)) { - return INVALID_ENT_REFERENCE; - } - - return weapon; -} - -/** - * Gets the classname and entity index of the current/active weapon of a client. - * - * @param client Client Index. - * @param buffer String Buffer to store the weapon's classname. - * @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) -{ - new weapon = Client_GetActiveWeapon(client); - - if (weapon == INVALID_ENT_REFERENCE) { - buffer[0] = '\0'; - return INVALID_ENT_REFERENCE; - } - - Entity_GetClassName(weapon, buffer, size); - - return weapon; -} - -/** - * Changes the active/current weapon of a player by Index. - * Note: No changing animation will be played ! - * - * @param client Client Index. - * @param weapon Index of a valid weapon. - * @noreturn - */ -stock Client_SetActiveWeapon(client, weapon) -{ - SetEntPropEnt(client, Prop_Data, "m_hActiveWeapon", weapon); - ChangeEdictState(client, FindDataMapInfo(client, "m_hActiveWeapon")); -} - -/** - * Changes the active weapon the client is holding. - * Note: No changing animation will be played ! - * - * @param client Client Index. - * @param className Weapon Classname. - * @return True on success, false on failure. - */ -stock bool:Client_ChangeWeapon(client, const String:className[]) -{ - new weapon = Client_GetWeapon(client, className); - - if (weapon == INVALID_ENT_REFERENCE) { - return false; - } - - Client_SetActiveWeapon(client,weapon); - - return true; -} - -/** - * Changes the active weapon to the last. - * If the last active weapon can't be found, the default weapon is taken. - * If the default weapon can't be found, the first weapon in the list is taken. - * If the first weapon can't be found, INVALID_ENT_REFERENCEE is returned. - * - * @param client Client Index. - * @return Entity Index or, INVALID_ENT_REFERENCE. - */ -stock Client_ChangeToLastWeapon(client) -{ - new weapon = Client_GetLastActiveWeapon(client); - - if (weapon == INVALID_ENT_REFERENCE) { - weapon = Client_GetDefaultWeapon(client); - - if (weapon == INVALID_ENT_REFERENCE) { - weapon = Client_GetFirstWeapon(client); - - if (weapon == INVALID_ENT_REFERENCE) { - return INVALID_ENT_REFERENCE; - } - } - } - - Client_SetActiveWeapon(client, weapon); - - return weapon; -} - -/** - * Gets the last active weapon of a client. - * - * @param client Client Index. - * @return Entity Index of the weapon on success, INVALID_ENT_REFERENCE on failure. - */ -stock Client_GetLastActiveWeapon(client) -{ - new weapon = GetEntPropEnt(client, Prop_Data, "m_hLastWeapon"); - - if (!Entity_IsValid(weapon)) { - return INVALID_ENT_REFERENCE; - } - - return weapon; -} - -/** - * Gets the classname of the last active weapon of a 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. - */ -stock bool:Client_GetLastActiveWeaponName(client, String:buffer[], size) -{ - new weapon = Client_GetLastActiveWeapon(client); - - if (weapon == INVALID_ENT_REFERENCE) { - buffer[0] = '\0'; - return false; - } - - Entity_GetClassName(weapon, buffer, size); - - return true; -} - -/** - * Sets the last active weapon of a client. - * - * @param client Client Index. - * @param weapon Entity Index of a weapon. - * @noreturn - */ -stock Client_SetLastActiveWeapon(client, weapon) -{ - SetEntPropEnt(client, Prop_Data, "m_hLastWeapon", weapon); - ChangeEdictState(client, FindDataMapInfo(client, "m_hLastWeapon")); -} - -/** - * Equips (attaches) a weapon to a client. - * - * @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) -{ - EquipPlayerWeapon(client, weapon); - - if (switchTo) { - Client_SetActiveWeapon(client, weapon); - } -} - -/** - * Savly detaches a clients weapon, to remove it as example. - * The client will select his last weapon when detached. - * - * @param client Client Index. - * @param weapon Entity Index of the weapon, you'd like to detach. - * @return True on success, false otherwise. - */ -stock bool:Client_DetachWeapon(client, weapon) -{ - if (!RemovePlayerItem(client, weapon)) { - return false; - } - - if (Client_GetActiveWeapon(client) == INVALID_ENT_REFERENCE) { - Client_ChangeToLastWeapon(client); - } - - return true; -} - -/** - * Gives a client a weapon. - * - * @param client Client Index. - * @param className Weapon Classname String. - * @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) -{ - new weapon = Client_GetWeapon(client, className); - - if (weapon == INVALID_ENT_REFERENCE) { - weapon = Weapon_CreateForOwner(client, className); - - if (weapon == INVALID_ENT_REFERENCE) { - return INVALID_ENT_REFERENCE; - } - } - - Client_EquipWeapon(client, weapon, switchTo); - - return weapon; -} - -/** - * Gives a client a weapon and ammo for that weapon. - * - * @param client Client Index. - * @param className Weapon Classname String. - * @param switchTo If set to true, the client will switch the active weapon to the new weapon. - * @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. - * @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. - */ -stock Client_GiveWeaponAndAmmo(client, const String:className[], bool:switchTo=true, primaryAmmo=-1, secondaryAmmo=-1, primaryClip=-1, secondaryClip=-1) -{ - new weapon = Client_GiveWeapon(client, className, switchTo); - - if (weapon == INVALID_ENT_REFERENCE) { - return INVALID_ENT_REFERENCE; - } - - if (primaryClip != -1) { - Weapon_SetPrimaryClip(weapon, primaryClip); - } - - if (secondaryClip != -1) { - Weapon_SetSecondaryClip(weapon, secondaryClip); - } - - Client_SetWeaponPlayerAmmoEx(client, weapon, primaryAmmo, secondaryAmmo); - - return weapon; -} - -/** - * Removes a weapon from a client. - * - * @param client Client Index. - * @param className Weapon Classname String. - * @param firstOnly If false it loops trough the whole weapon list and deletes all weapons that match the specified classname. - * @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) -{ - new offset = Client_GetWeaponsOffset(client) - 4; - - for (new i=0; i < MAX_WEAPONS; i++) { - offset += 4; - - new weapon = GetEntDataEnt2(client, offset); - - if (!Weapon_IsValid(weapon)) { - continue; - } - - if (!Entity_ClassNameMatches(weapon, className)) { - continue; - } - - if (clearAmmo) { - Client_SetWeaponPlayerAmmoEx(client, weapon, 0, 0); - } - - if (Client_GetActiveWeapon(client) == weapon) { - Client_ChangeToLastWeapon(client); - } - - if (RemovePlayerItem(client, weapon)) { - Entity_Kill(weapon); - } - - if (firstOnly) { - return true; - } - } - - return false; -} - -/** - * Removes all weapons of a client. - * You can specify a weapon it shouldn't remove and if to - * clear the player's ammo for a weapon when it gets removed. - * - * @param client Client Index. - * @param exclude If not empty, this weapon won't be removed from the client. - * @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) -{ - new offset = Client_GetWeaponsOffset(client) - 4; - - new numWeaponsRemoved = 0; - for (new i=0; i < MAX_WEAPONS; i++) { - offset += 4; - - new weapon = GetEntDataEnt2(client, offset); - - if (!Weapon_IsValid(weapon)) { - continue; - } - - if (exclude[0] != '\0' && Entity_ClassNameMatches(weapon, exclude)) { - Client_SetActiveWeapon(client, weapon); - continue; - } - - if (clearAmmo) { - Client_SetWeaponPlayerAmmoEx(client, weapon, 0, 0); - } - - if (RemovePlayerItem(client, weapon)) { - Entity_Kill(weapon); - } - - numWeaponsRemoved++; - } - - return numWeaponsRemoved; -} - -/** - * Checks if a client has a specific weapon. - * - * @param client Client Index. - * @param className Weapon Classname. - * @return True if client has the weapon, otherwise false. - */ -stock bool:Client_HasWeapon(client, const String:className[]) -{ - new weapon = Client_GetWeapon(client, className); - - return (weapon != INVALID_ENT_REFERENCE); -} - -/** - * Gets the weapon of a client by the weapon's classname. - * - * @param client Client Index. - * @param className Classname of the weapon. - * @return Entity index on success or INVALID_ENT_REFERENCE. - */ -stock Client_GetWeapon(client, const String:className[]) -{ - new offset = Client_GetWeaponsOffset(client) - 4; - new weapon = INVALID_ENT_REFERENCE; - for (new i=0; i < MAX_WEAPONS; i++) { - offset += 4; - - weapon = GetEntDataEnt2(client, offset); - - if (!Weapon_IsValid(weapon)) { - continue; - } - - if (Entity_ClassNameMatches(weapon, className)) { - return weapon; - } - } - - return INVALID_ENT_REFERENCE; -} - -/** - * Gets the weapon of a client by slot number. - * Note: This is incompatible to games that have multiple - * weapons in one slot (eg.: hl2dm). - * - * @param client Client Index. - * @param slot Slot Index. - * @return Entity index on success or INVALID_ENT_REFERENCE. - */ -stock Client_GetWeaponBySlot(client, slot) -{ - return GetPlayerWeaponSlot(client, slot); -} - -/** - * Gets the clients default weapon (Entity Index). - * - * @param client Client Index. - * @return Entity Index on success, INVALID_ENT_REFERENCE on failure. - */ -stock Client_GetDefaultWeapon(client) -{ - decl String:weaponName[MAX_WEAPON_STRING]; - if (Client_GetDefaultWeaponName(client, weaponName, sizeof(weaponName))) { - return INVALID_ENT_REFERENCE; - } - - return Client_GetWeapon(client, weaponName); -} - -/** - * Gets the clients default weapon (classname). - * This function doesn't work in all games (maybe only works in hl2dm). - * It will return an empty string if cl_defaultweapon doesn't exist. - * - * @param client Client Index. - * @param buffer Buffer to store the default weapon's classname. - * @param size Max size of string: buffer. - * @return True on success, false otherwise. - */ -stock bool:Client_GetDefaultWeaponName(client, String:buffer[], size) -{ - if (!GetClientInfo(client, "cl_defaultweapon", buffer, size)) { - buffer[0] = '\0'; - return false; - } - - return true; -} - -/** - * Gets the first weapon of the client's weapon list (m_hMyWeapons). - * Note: This has nothing to do with weapon slots. - * - * @param client Client Index. - * @return Entity Index of the weapon or INVALID_ENT_REFERENCE. - */ -stock Client_GetFirstWeapon(client) -{ - new offset = Client_GetWeaponsOffset(client) - 4; - - for (new i=0; i < MAX_WEAPONS; i++) { - offset += 4; - - new weapon = GetEntDataEnt2(client, offset); - - if (!Weapon_IsValid(weapon)) { - continue; - } - - return weapon; - } - - return INVALID_ENT_REFERENCE; -} - -/** - * Gets the number of weapons a client has. - * - * @param client Client Index. - * @return Number of weapons. - */ -stock Client_GetWeaponCount(client) -{ - new numWeapons = 0; - - new offset = Client_GetWeaponsOffset(client) - 4; - - for (new i=0; i < MAX_WEAPONS; i++) { - offset += 4; - - new weapon = GetEntDataEnt2(client, offset); - - if (!Weapon_IsValid(weapon)) { - continue; - } - - numWeapons++; - } - - return numWeapons; -} - -/** - * Checks whether the client is currently reloading his active weapon. - * - * @param client Client Index. - * @return True if client is reloading, false otherwise. - */ -stock bool:Client_IsReloading(client) -{ - new weapon = Client_GetActiveWeapon(client); - - if (weapon == INVALID_ENT_REFERENCE) { - return false; - } - - return Weapon_IsReloading(weapon); -} - -/** - * Sets the primary and secondary clip value of a weapon. - * - * @param client Client Index. - * @param classname Classname of a weapon. - * @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 True on success, false on failure. - */ -stock bool:Client_SetWeaponClipAmmo(client, const String:className[], primaryClip=-1, secondoaryClip=-1) -{ - new weapon = Client_GetWeapon(client, className); - - if (weapon == INVALID_ENT_REFERENCE) { - return false; - } - - if (primaryClip != -1) { - Weapon_SetPrimaryClip(weapon, primaryClip); - } - - if (secondoaryClip != -1) { - Weapon_SetSecondaryClip(weapon, primaryClip); - } - - return true; -} - -/** - * Gets the primary and secondary ammo the player carries for a specific weapon classname. - * - * @param client Client Index. - * @param classname Classname of a weapon. - * @param primaryAmmo Primary ammo stock from the client, if -1 the value is untouched. - * @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) -{ - new weapon = Client_GetWeapon(client, className); - - if (weapon == INVALID_ENT_REFERENCE) { - return false; - } - - new offset_ammo = FindDataMapInfo(client, "m_iAmmo"); - - if (primaryAmmo != -1) { - new offset = offset_ammo + (Weapon_GetPrimaryAmmoType(weapon) * 4); - primaryAmmo = GetEntData(client, offset); - } - - if (secondaryAmmo != -1) { - new offset = offset_ammo + (Weapon_GetSecondaryAmmoType(weapon) * 4); - secondaryAmmo = GetEntData(client, offset); - } - - return true; -} - -/** - * Gets the primary and secondary ammo the player carries for a specific weapon index. - * - * @param client Client Index. - * @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) -{ - new offset_ammo = FindDataMapInfo(client, "m_iAmmo"); - - if (primaryAmmo != -1) { - new offset = offset_ammo + (Weapon_GetPrimaryAmmoType(weapon) * 4); - primaryAmmo = GetEntData(client, offset); - } - - if (secondaryAmmo != -1) { - new offset = offset_ammo + (Weapon_GetSecondaryAmmoType(weapon) * 4); - secondaryAmmo = GetEntData(client, offset); - } -} - -/** - * Sets the primary and secondary ammo the player carries for a specific weapon classname. - * - * @param client Client Index. - * @param classname Weapon Classname String. - * @param primaryAmmo Primary ammo stock from the client, if -1 the value is untouched. - * @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) -{ - new weapon = Client_GetWeapon(client, className); - - if (weapon == INVALID_ENT_REFERENCE) { - return false; - } - - Client_SetWeaponPlayerAmmoEx(client, weapon, primaryAmmo, secondaryAmmo); - - return true; -} - -/** - * Sets the primary and secondary ammo the player carries for a specific weapon index. - * - * @param client Client Index. - * @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) -{ - new offset_ammo = FindDataMapInfo(client, "m_iAmmo"); - - if (primaryAmmo != -1) { - new offset = offset_ammo + (Weapon_GetPrimaryAmmoType(weapon) * 4); - SetEntData(client, offset, primaryAmmo, 4, true); - } - - if (secondaryAmmo != -1) { - new offset = offset_ammo + (Weapon_GetSecondaryAmmoType(weapon) * 4); - SetEntData(client, offset, secondaryAmmo, 4, true); - } -} - -/** - * Sets the value from primary and secondary ammo stock, of a client. - * - * @param client Client Index. - * @param className Classname of a weapon. - * @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. - * @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. - */ -stock Client_SetWeaponAmmo(client, const String:className[], primaryAmmo=-1, secondaryAmmo=-1, primaryClip=-1, secondaryClip=-1) -{ - new weapon = Client_GetWeapon(client, className); - - if (weapon == INVALID_ENT_REFERENCE) { - return false; - } - - if (primaryClip != -1) { - Weapon_SetPrimaryClip(weapon, primaryClip); - } - if (secondaryClip != -1) { - Weapon_SetSecondaryClip(weapon, secondaryClip); - } - Client_SetWeaponPlayerAmmoEx(client, weapon, primaryAmmo, secondaryAmmo); - - return true; -} - -/** - * Gets the next weapon of a client, starting at start. - * - * @param client Client Index (must be a valid client ingame). - * @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) -{ - new offset = Client_GetWeaponsOffset(client) + (index * 4); - - new weapon; - while (index < MAX_WEAPONS) { - index++; - - weapon = GetEntDataEnt2(client, offset); - - if (Weapon_IsValid(weapon)) { - return weapon; - } - - offset += 4; - } - - return -1; -} - -/** - * Prints white text to the bottom center of the screen - * for one client. Does not work in all games. - * Line Breaks can be done with "\n". - * - * @param client Client Index. - * @param format Formatting rules. - * @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:...) -{ - new Handle:userMessage = StartMessageOne("HintText", client); - - if (userMessage == INVALID_HANDLE) { - return false; - } - - decl String:buffer[254]; - - SetGlobalTransTarget(client); - VFormat(buffer, sizeof(buffer), format, 3); - - - if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available - && GetUserMessageType() == UM_Protobuf) { - - PbSetString(userMessage, "text", buffer); - } - else { - BfWriteByte(userMessage, 1); - BfWriteString(userMessage, buffer); - } - - EndMessage(); - - return true; -} - -/** - * Prints white text to the bottom center of the screen - * for all clients. Does not work in all games. - * Line Breaks can be done with "\n". - * - * @param format Formatting rules. - * @param ... Variable number of format parameters. - * @noreturn - */ -stock Client_PrintHintTextToAll(const String:format[], any:...) -{ - decl String:buffer[254]; - - for (new client=1; client <= MaxClients; client++) { - - if (!IsClientInGame(client)) { - continue; - } - - SetGlobalTransTarget(client); - VFormat(buffer, sizeof(buffer), format, 2); - Client_PrintHintText(client, buffer); - } -} - -/** - * Prints white text to the right-center side of the screen - * for one client. Does not work in all games. - * Line Breaks can be done with "\n". - * - * @param client Client Index. - * @param format Formatting rules. - * @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:...) -{ - new Handle:userMessage = StartMessageOne("KeyHintText", client); - - if (userMessage == INVALID_HANDLE) { - return false; - } - - decl String:buffer[254]; - - SetGlobalTransTarget(client); - VFormat(buffer, sizeof(buffer), format, 3); - - if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available - && GetUserMessageType() == UM_Protobuf) { - - PbAddString(userMessage, "hints", buffer); - } - else { - BfWriteByte(userMessage, 1); - BfWriteString(userMessage, buffer); - } - - EndMessage(); - - return true; -} - -/** - * Prints white text to the right-center side of the screen - * for all clients. Does not work in all games. - * Line Breaks can be done with "\n". - * - * @param format Formatting rules. - * @param ... Variable number of format parameters. - * @noreturn - */ -stock Client_PrintKeyHintTextToAll(const String:format[], any:...) -{ - decl String:buffer[254]; - - for (new client=1; client <= MaxClients; client++) { - - if (!IsClientInGame(client)) { - continue; - } - - SetGlobalTransTarget(client); - VFormat(buffer, sizeof(buffer), format, 2); - Client_PrintKeyHintText(client, buffer); - } -} - -/** - * Prints a reliable raw chat message to a client in the chat area. - * If the client == 0, the message will printed to server console. - * - * @param client Client Index. - * @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) -{ - if (client == 0) { - decl String:buffer[253]; - Color_StripFromChatText(message, buffer, sizeof(buffer)); - PrintToServer(buffer); - return; - } - - static sayText2_supported = true; - static sayText2_checked = false; - - if (!sayText2_checked) { - - if (GetUserMessageId("SayText2") == INVALID_MESSAGE_ID) { - sayText2_supported = false; - } - - sayText2_checked = true; - } - - new Handle:userMessage = INVALID_HANDLE; - - if (sayText2_supported) { - userMessage = StartMessageOne("SayText2", client, USERMSG_RELIABLE); - - if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available - && GetUserMessageType() == UM_Protobuf) { - - PbSetInt(userMessage, "ent_idx", subject); - PbSetBool(userMessage, "chat", isChat); - PbSetString(userMessage, "msg_name", message); - - // psychonic: Furthermore, some usermessages with repeated field, - // such as the commonly-used SayText2, expected an undocumented - // specific number of values added, else the client will crash when receiving. - PbAddString(userMessage, "params", ""); - PbAddString(userMessage, "params", ""); - PbAddString(userMessage, "params", ""); - PbAddString(userMessage, "params", ""); - } - else { - BfWriteByte(userMessage , subject); - BfWriteByte(userMessage , isChat); - BfWriteString(userMessage , message); - } - } - else { - userMessage = StartMessageOne("SayText", client, USERMSG_RELIABLE); - - if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available - && GetUserMessageType() == UM_Protobuf) { - - PbSetInt(userMessage, "ent_idx", subject); - PbSetString(userMessage, "text", message); - PbSetBool(userMessage, "chat", isChat); - } - else { - BfWriteByte(userMessage , subject); - BfWriteString(userMessage , message); - // For DoD:S nickname coloring - BfWriteByte(userMessage , -1); - } - } - - EndMessage(); -} - -/** - * Prints a reliable chat message to one client in the chat area. - * Allows up to 253 Characters (including \0) to be printed. - * Supports chat color tags (see: colors.inc). - * - * @param client Client Index. - * @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:...) -{ - decl - String:buffer[512], - String:buffer2[253]; - - SetGlobalTransTarget(client); - VFormat(buffer, sizeof(buffer), format, 4); - new subject = Color_ParseChatText(buffer, buffer2, sizeof(buffer2)); - - Client_PrintToChatRaw(client, buffer2, subject, isChat); - - Color_ChatClearSubject(); -} - -static printToChat_excludeclient = -1; - -/** - * Exclude a client from the next call to a Client_PrintToChat function. - * - * @param client Client Index. - * @noreturn - */ -stock Client_PrintToChatExclude(client) -{ - printToChat_excludeclient = client; -} - -/** - * Prints a reliable chat message to all clients in the chat area. - * Allows up to 253 Characters (including \0) to be printed. - * Supports chat color tags (see: colors.inc). - * - * @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:...) -{ - decl - String:buffer[512], - String:buffer2[253]; - new - subject, - language, - lastLanguage = -1; - - for (new client=1; client <= MaxClients; client++) { - - if (!IsClientInGame(client)) { - continue; - } - - if (client == printToChat_excludeclient) { - printToChat_excludeclient = -1; - continue; - } - - language = GetClientLanguage(client); - - if (language != lastLanguage) { - SetGlobalTransTarget(client); - VFormat(buffer, sizeof(buffer), format, 3); - subject = Color_ParseChatText(buffer, buffer2, sizeof(buffer2)); - - lastLanguage = language; - } - - Client_PrintToChatRaw(client, buffer2, subject, isChat); - } - - Color_ChatClearSubject(); -} - -/** - * Prints a reliable chat message to the specified clients in the chat area. - * Allows up to 253 Characters (including \0) to be print. - * Supports chat color tags (see: colors.inc). - * - * @param clients Client Array. - * @param numClients Number of clients in the client array. - * @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:...) -{ - decl - String:buffer[512], - String:buffer2[253]; - new - client, - subject, - language, - lastLanguage = -1; - - for (new i=0; i < numClients; i++) { - - client = clients[i]; - - if (!IsClientInGame(client)) { - continue; - } - - if (client == printToChat_excludeclient) { - printToChat_excludeclient = -1; - continue; - } - - language = GetClientLanguage(client); - - if (language != lastLanguage) { - SetGlobalTransTarget(client); - VFormat(buffer, sizeof(buffer), format, 5); - subject = Color_ParseChatText(buffer, buffer2, sizeof(buffer2)); - - lastLanguage = language; - } - - Client_PrintToChatRaw(client, buffer2, subject, isChat); - } - - Color_ChatClearSubject(); -} - -enum ClientHudPrint { - ClientHudPrint_Notify = 1, - ClientHudPrint_Console, - ClientHudPrint_Talk, - Client_HudPrint_Center -}; - -/** - * Prints a relieable message to the client's console. - * Allows up to 254 Characters (including \0) to be print (253 for talk). - * Supports chat color tags (see: colors.inc, only available in Left 4 Dead (2) or higher). - * Chat colors are stripped automatically if not supported. - * - * @param clients Client Array. - * @param format Formatting rules. - * @param ... Variable number of format parameters. - * @noreturn - */ -stock Client_PrintToConsole(client, const String:format[], any:...) -{ - decl String:buffer[512]; - - SetGlobalTransTarget(client); - VFormat(buffer, sizeof(buffer), format, 3); - - Client_Print(client, ClientHudPrint_Console, buffer); -} - -/** - * Prints a relieable message to the client's console. - * Allows up to 254 Characters (including \0) to be print. - * Supports chat color tags in chat & console (see: colors.inc). - * Chat colors are stripped automatically if not supported in the destination. - * - * @param clients Client Array. - * @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:...) -{ - decl String:buffer[512], String:buffer2[254]; - - SetGlobalTransTarget(client); - VFormat(buffer, sizeof(buffer), format, 4); - - new subject = Color_ParseChatText(buffer, buffer2, sizeof(buffer2)); - - if (destination == ClientHudPrint_Talk) { - Client_PrintToChatRaw(client, buffer2, subject, false); - return; - } - - new EngineVersion:engineVersion = GetEngineVersion(); - if (client == 0 || - destination != ClientHudPrint_Console || - (destination == ClientHudPrint_Console - && engineVersion != Engine_Left4Dead && engineVersion != Engine_Left4Dead2)) - { - Color_StripFromChatText(buffer2, buffer2, sizeof(buffer2)); - - if (client == 0) { - PrintToServer(buffer2); - return; - } - } - - new 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); - PbAddString(userMessage, "params", buffer2); - PbAddString(userMessage, "params", ""); - PbAddString(userMessage, "params", ""); - PbAddString(userMessage, "params", ""); - PbAddString(userMessage, "params", ""); - } - else { - BfWriteByte(userMessage , _:destination); - BfWriteString(userMessage , buffer2); - } - - EndMessage(); -} - -/** - * Replies to a message in a command. - * A client index of 0 will use PrintToServer(). - * If the command was from the console, Client_PrintToConsole() is used. - * If the command was from chat, Client_PrintToChat() is used. - * - * @param client Client Index. - * @param format Formatting rules String. - * @param ... Variable number of format parameters. - * @noreturn - */ -stock Client_Reply(client, const String:format[], any:...) -{ - decl String:buffer[255]; - - SetGlobalTransTarget(client); - VFormat(buffer, sizeof(buffer), format, 3); - - if (GetCmdReplySource() == SM_REPLY_TO_CONSOLE) { - Client_PrintToConsole(client, buffer); - } - else { - Client_PrintToChat(client, false, buffer); - } -} - -#define SHAKE_START 0 // Starts the screen shake for all players within the radius. -#define SHAKE_STOP 1 // Stops the screen shake for all players within the radius. -#define SHAKE_AMPLITUDE 2 // Modifies the amplitude of an active screen shake for all players within the radius. -#define SHAKE_FREQUENCY 3 // Modifies the frequency of an active screen shake for all players within the radius. -#define SHAKE_START_RUMBLEONLY 4 // Starts a shake effect that only rumbles the controller, no screen effect. -#define SHAKE_START_NORUMBLE 5 // Starts a shake that does NOT rumble the controller. - -/** - * Shakes a client's screen with the specified amptitude, - * frequency & duration. - * - * @param client Client Index. - * @param command Shake Mode, use one of the SHAKE_ definitions. - * @param amplitude Shake magnitude/amplitude. - * @param frequency Shake noise frequency. - * @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) -{ - if (command == SHAKE_STOP) { - amplitude = 0.0; - } - else if (amplitude <= 0.0) { - return false; - } - - new Handle:userMessage = StartMessageOne("Shake", client); - - if (userMessage == INVALID_HANDLE) { - return false; - } - - if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available - && GetUserMessageType() == UM_Protobuf) { - - PbSetInt(userMessage, "command", command); - PbSetFloat(userMessage, "local_amplitude", amplitude); - PbSetFloat(userMessage, "frequency", frequency); - PbSetFloat(userMessage, "duration", duration); - } - else { - BfWriteByte(userMessage, command); // Shake Command - BfWriteFloat(userMessage, amplitude); // shake magnitude/amplitude - BfWriteFloat(userMessage, frequency); // shake noise frequency - BfWriteFloat(userMessage, duration); // shake lasts this long - } - - EndMessage(); - - return true; -} - -/** - * Checks whether the client is a generic admin. - * - * @param Client Index. - * @return True if the client is a generic admin, false otheriwse. - */ -stock bool:Client_IsAdmin(client) -{ - new AdminId:adminId = GetUserAdmin(client); - - if (adminId == INVALID_ADMIN_ID) { - return false; - } - - return GetAdminFlag(adminId, Admin_Generic); -} - -/** - * Checks whether a client has certain admin flags - * - * @param Client Index. - * @return True if the client has the admin flags, false otherwise. - */ -stock bool:Client_HasAdminFlags(client, flags=ADMFLAG_GENERIC) -{ - new AdminId:adminId = GetUserAdmin(client); - - if (adminId == INVALID_ADMIN_ID) { - return false; - } - - return bool:(GetAdminFlags(adminId, Access_Effective) & flags); -} - -/** - * Returns whether a player is in a specific admin group. - * - * @param client Client Index. - * @param groupName Admin group name to check. - * @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) -{ - new AdminId:adminId = GetUserAdmin(client); - - // Validate id. - if (adminId == INVALID_ADMIN_ID) { - return false; - } - - // Get number of groups. - new count = GetAdminGroupCount(adminId); - - // Validate number of groups. - if (count == 0) { - return false; - } - - decl String:groupname[64]; - - // Loop through each group. - for (new i = 0; i < count; i++) { - // Get group name. - GetAdminGroup(adminId, i, groupname, sizeof(groupname)); - - // Compare names. - if (StrEqual(groupName, groupname, caseSensitive)) { - return true; - } - } - - // No match. - return false; -} - -/** - * Checks if the client is currently looking at the wall in front - * of him with the given distance as max value. - * - * @param client Client Index. - * @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) { - - decl Float:posEye[3], Float:posEyeAngles[3]; - new 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); - - if (TR_DidHit(trace)) { - - if (TR_GetEntityIndex(trace) > 0) { - CloseHandle(trace); - return false; - } - - decl Float:posEnd[3]; - - TR_GetEndPosition(posEnd, trace); - - if (GetVectorDistance(posEye, posEnd, true) <= (distance * distance)) { - isClientLookingAtWall = true; - } - } - - CloseHandle(trace); - - return isClientLookingAtWall; -} - -public bool:_smlib_TraceEntityFilter(entity, contentsMask) -{ - return entity == 0; -} - -/** - * Gets a client's class. - * Currently supported games are: TF2, Dark Messiah. - * Other games maybe work too, but are not tested. - * - * @param client Client Index. - * @return Class Index. - */ -stock Client_GetClass(client) -{ - if (GetEngineVersion() == Engine_DarkMessiah) { - return GetEntProp(client, Prop_Send, "m_iPlayerClass"); - } - - return GetEntProp(client, Prop_Send, "m_iClass"); -} - -/** - * Sets a client's class. - * Currently supported games are: TF2, Dark Messiah. - * Other games maybe work too, but are not tested. - * - * @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) -{ - if (GetEngineVersion() == Engine_DarkMessiah) { - SetEntProp(client, Prop_Send, "m_iPlayerClass", playerClass); - } else { - SetEntProp(client, Prop_Send, "m_iClass", playerClass); - - if (persistant) { - SetEntProp(client, Prop_Send, "m_iDesiredPlayerClass", playerClass); - } - } -} - -/** - * Returns what buttons are currently pressed by the client. - * - * @param client Client Index. - * @return Buttons as bitflag. - */ -stock Client_GetButtons(client) -{ - return GetClientButtons(client); -} - -/** - * Sets the client buttons. - * Note: This will only work OnPreThink (sdkhooks) or OnPlayerRunCmd. - * - * @param client Client Index. - * @param buttons Buttons as bitflag. - * @noreturn - */ -stock Client_SetButtons(client, buttons) -{ - SetEntProp(client, Prop_Data, "m_nButtons", buttons); -} - -/** - * Adds buttons to the already pressed buttons. - * Note: This will likely only work OnPreThink (sdkhooks) or OnPlayerRunCmd. - * - * @param client Client Index. - * @param buttons Buttons as bitflag. - * @noreturn - */ -stock Client_AddButtons(client, buttons) -{ - new newButtons = Client_GetButtons(client); - newButtons |= buttons; - Client_SetButtons(client, newButtons); -} - -/** - * Removes buttons from the already pressed buttons. - * Note: This will only work OnPreThink (sdkhooks) or OnPlayerRunCmd. - * - * @param client Client Index. - * @param buttons Buttons as bitflag. - * @noreturn - */ -stock Client_RemoveButtons(client, buttons) -{ - new newButtons = Client_GetButtons(client); - newButtons &= ~buttons; - Client_SetButtons(client, newButtons); -} - -/** - * Clears all buttons. - * Note: This will likely only work OnPreThink (sdkhooks) or OnPlayerRunCmd. - * - * @param client Client Index. - * @noreturn - */ -stock Client_ClearButtons(client) -{ - Client_SetButtons(client,0); -} - -/** - * Returns if the given buttons are pressed by the client or not. - * - * @param client Client Index. - * @param buttons Buttons as bitflag. - * @return True if the buttons are pressed otherwise false. - */ -stock bool:Client_HasButtons(client, buttons) -{ - return bool:(Client_GetButtons(client) & buttons); -} - -/** - * Returns only the buttons that have changed since the last call of this. - * Example usage: Within OnPlayerRunCmd use this function to call another function only once when a player pressed or released a button. - * - * @param client Client Index. - * @param buttons Buttons as bitflag. - * @return - */ -stock Client_GetChangedButtons(client) -{ - static oldButtons[MAXPLAYERS+1] = {0,...}; - - new buttons = Client_GetButtons(client); - new changedButtons = buttons ^ oldButtons[client]; - - oldButtons[client] = buttons; - - return changedButtons; -} - -/** - * Sets the client's maxspeed to the given value (in units per second) - * - * @param Client Client Index - * @param maxspeed the maximum speed the client can move - * @noreturn - */ -stock Client_SetMaxSpeed(client, Float:value) -{ - Entity_SetMaxSpeed(client, value); -} - -/** - * Shows a screen overlay tp a client. - * There can only be one overlay at a time. - * If you want to clear the overlay, pass - * an empty string to this function. - * - * @param Client Client Index. - * @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[]) -{ - ClientCommand(client, "r_screenoverlay \"%s\"", path); -} - -/** - * Shows a screen overlay to all clients. - * There can only be one overlay at a time. - * If you want to clear the overlay, pass - * an empty string to this function. - * - * @param Client Client Index. - * @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[]) -{ - LOOP_CLIENTS(client, CLIENTFILTER_INGAME | CLIENTFILTER_NOBOTS) { - Client_SetScreenOverlay(client, path); - } -} - -/** - * Mutes a client's voice - * - * @param Client Client Index. - * @noreturn - */ -stock Client_Mute(client) -{ - SetClientListeningFlags(client, VOICE_MUTED); -} - -/** - * UnMutes a client's voice - * Code copied from basecomm.sp - * - * @param Client Client Index. - * @noreturn - */ -stock Client_UnMute(client) -{ - static Handle:cvDeadTalk = INVALID_HANDLE; - - if (cvDeadTalk == INVALID_HANDLE) { - cvDeadTalk = FindConVar("sm_deadtalk"); - } - - if (cvDeadTalk == INVALID_HANDLE) { - SetClientListeningFlags(client, VOICE_NORMAL); - } - else { - if (GetConVarInt(cvDeadTalk) == 1 && !IsPlayerAlive(client)) { - SetClientListeningFlags(client, VOICE_LISTENALL); - } - else if (GetConVarInt(cvDeadTalk) == 2 && !IsPlayerAlive(client)) { - SetClientListeningFlags(client, VOICE_TEAM); - } - else { - SetClientListeningFlags(client, VOICE_NORMAL); - } - } -} - -/** - * Checks if a client's voice is muted - * - * @param Client Client Index. - * @return True if the client is muted, false otherwise. - */ -stock bool:Client_IsMuted(client) -{ - return bool:(GetClientListeningFlags(client) & VOICE_MUTED); -} - -/** - * Checks if a client matches the specified flag filter. - * Use one of the CLIENTFILTER_ constants. - * Note that this already checks if the client is ingame or connected - * so you don't have to do that yourself. - * This function is optimized to make as less native calls as possible :) - * - * @param Client Client Index. - * @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) -{ - new bool:isIngame = false; - - if (flags >= CLIENTFILTER_INGAME) { - isIngame = IsClientInGame(client); - - if (isIngame) { - if (flags & CLIENTFILTER_NOTINGAME) { - return false; - } - } - else { - return false; - } - } - else if (!IsClientConnected(client)) { - return false; - } - - if (!flags) { - return true; - } - - if (flags & CLIENTFILTER_INGAMEAUTH) { - flags |= CLIENTFILTER_INGAME | CLIENTFILTER_AUTHORIZED; - } - - if (flags & CLIENTFILTER_BOTS && !IsFakeClient(client)) { - return false; - } - - if (flags & CLIENTFILTER_NOBOTS && IsFakeClient(client)) { - return false; - } - - if (flags & CLIENTFILTER_ADMINS && !Client_IsAdmin(client)) { - return false; - } - - if (flags & CLIENTFILTER_NOADMINS && Client_IsAdmin(client)) { - return false; - } - - if (flags & CLIENTFILTER_AUTHORIZED && !IsClientAuthorized(client)) { - return false; - } - - if (flags & CLIENTFILTER_NOTAUTHORIZED && IsClientAuthorized(client)) { - return false; - } - - if (isIngame) { - - if (flags & CLIENTFILTER_ALIVE && !IsPlayerAlive(client)) { - return false; - } - - if (flags & CLIENTFILTER_DEAD && IsPlayerAlive(client)) { - return false; - } - - if (flags & CLIENTFILTER_SPECTATORS && GetClientTeam(client) != TEAM_SPECTATOR) { - return false; - } - - if (flags & CLIENTFILTER_NOSPECTATORS && GetClientTeam(client) == TEAM_SPECTATOR) { - return false; - } - - if (flags & CLIENTFILTER_OBSERVERS && !IsClientObserver(client)) { - return false; - } - - if (flags & CLIENTFILTER_NOOBSERVERS && IsClientObserver(client)) { - return false; - } - - if (flags & CLIENTFILTER_TEAMONE && GetClientTeam(client) != TEAM_ONE) { - return false; - } - - if (flags & CLIENTFILTER_TEAMTWO && GetClientTeam(client) != TEAM_TWO) { - return false; - } - } - - return true; -} - -/** - * Gets all clients matching the specified flags filter. - * - * @param client Client Array, size should be MaxClients or MAXPLAYERS - * @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) -{ - new x=0; - for (new client = 1; client <= MaxClients; client++) { - - if (!Client_MatchesFilter(client, flags)) { - continue; - } - - clients[x++] = client; - } - - return x; -} - -/** - * Gets a random client matching the specified flags filter. - * - * @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) -{ - decl clients[MaxClients]; - new num = Client_Get(clients, flags); - - if (num == 0) { - return -1; - } - else if (num == 1) { - return clients[0]; - } - - new random = Math_GetRandomInt(0, num-1); - - return clients[random]; -} - -/** - * Gets a client matching certain flags starting at start. - * - * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). - * @param start Start Index. - * @return Client Index or -1 if no client was found - */ -stock Client_GetNext(flags, start=1) -{ - for (new client=start; client <= MaxClients; client++) { - - if (Client_MatchesFilter(client, flags)) { - return client; - } - } - - return -1; -} - -/** - * Retrieves the time duration a client played on the current map. - * - * @param client Client Index. - * @return Time in seconds as Float - */ -stock Float:Client_GetMapTime(client) -{ - new Float:fClientTime = GetClientTime(client); - new Float:fGameTime = GetGameTime(); - - return (fClientTime < fGameTime) ? fClientTime : fGameTime; -} - -/** - * Gets client money value (for games like Counter-Strike:Source). - * - * @param client Client Index. - * @return Money value from the client. - */ -stock Client_GetMoney(client) -{ - return GetEntProp(client, Prop_Send, "m_iAccount"); -} - -/** - * Sets client money value (for games like Counter-Strike:Source). - * - * @param client Client Index. - * @param value Money value to set. - * @noreturn - */ -stock Client_SetMoney(client, value) -{ - SetEntProp(client, Prop_Send, "m_iAccount", value); -} - -/** - * Gets a client's observers. - * - * @param client Client Index. - * @param observers Array with size of MaxClients or MAXPLAYERS. - * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). - * @return Number of observers found. - */ -stock Client_GetObservers(client, observers[], flags=CLIENTFILTER_ALL) -{ - new count = 0; - - LOOP_CLIENTS(player, CLIENTFILTER_OBSERVERS | flags) { - - if (Client_GetObserverTarget(player) == client) { - observers[count++] = player; - } - } - - return count; -} - -static Float:getPlayersInRadius_distances[MAXPLAYERS+1]; - -/** - * Gets all players near a player in a certain radius and - * orders the players by distance (optional). - * - * @param client Client Index. - * @param clients Array with size of MaxClients or MAXPLAYERS. - * @param radius radius Float (max distance) - * @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) -{ - decl Float:origin_client[3]; - new - Float:distance, - count=0; - - Entity_GetAbsOrigin(client, origin_client); - - LOOP_CLIENTS(player, CLIENTFILTER_INGAME) { - - if (player == client) { - continue; - } - - distance = Entity_GetDistanceOrigin(player, origin_client); - - if (distance <= radius) { - clients[count++] = player; - - if (orderByDistance) { - getPlayersInRadius_distances[player] = distance; - } - } - } - - if (orderByDistance) { - SortCustom1D(clients, count, __smlib_GetPlayersInRadius_Sort); - } - - return count; -} - -public __smlib_GetPlayersInRadius_Sort(player1, player2, const clients[], Handle:hndl) -{ - return FloatCompare(getPlayersInRadius_distances[player1], getPlayersInRadius_distances[player2]); -} - -/** - * Gets the next player observing client starting at start. - * - * @param client Client Index (Observer Target) - * @param start Start Index. - * @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) -{ - for (new player=start; player <= MaxClients; player++) { - - if (Client_MatchesFilter(player, CLIENTFILTER_OBSERVERS | flags)) { - - if (Client_GetObserverTarget(player) == client) { - return player; - } - } - } - - return -1; -} - -/** - * Searchs and returns the game's player_manager entity. - * This should be called on every map start. - * - * @return player_manager entity or INVALID_ENT_REFERENCE if not found. - */ -stock Client_GetPlayerManager() -{ - static player_manager = INVALID_ENT_REFERENCE; - - if (player_manager != INVALID_ENT_REFERENCE) { - - if (Entity_IsValid(player_manager)) { - return player_manager; - } - else { - player_manager = INVALID_ENT_REFERENCE; - } - } - - new maxEntities = GetMaxEntities(); - - for (new entity=0; entity < maxEntities; entity++) { - - if (!Entity_IsValid(entity)) { - continue; - } - - if (Entity_ClassNameMatches(entity, "player_manager", true)) { - player_manager = EntIndexToEntRef(entity); - - return player_manager; - } - } - - return INVALID_ENT_REFERENCE; -} - -/** - * Sets the client's ping as displayed in the scoreboards. - * Should be called OnGameFrame. - * - * @param client Client Index - * @param start New ping value. - * @return True on sucess, false otherwise. - */ -stock Client_SetPing(client, value) -{ - new player_manager = Client_GetPlayerManager(); - - static offset = -1; - - if (offset== -1) { - offset = GetEntSendPropOffs(player_manager, "m_iPing", true); - - if (offset == -1) { - return false; - } - } - - SetEntData(player_manager, offset + (client * 4), value, 4, true); - - return true; -} - -static printToTop_excludeclient = -1; - -/** - * Exclude a client from the next call to a Client_PrintToTop function. - * - * @param client Client Index. - * @noreturn - */ -stock Client_PrintToTopExclude(client) -{ - printToTop_excludeclient = client; -} - -/** - * Prints colored text to the top left of the screen - * for one client. Does not work in all games. - * Line Breaks can't be done. - * - * @param client Client Index. - * @param r Red amount. - * @param g Green amount. - * @param b Blue amount. - * @param a Transparency. - * @param duration Duration in seconds the text stays (min 10 - max 200 seconds). - * @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[]) -{ - //message line max 50 - //overline: 39*_ - //underline: 44*T - new Handle:keyValue = CreateKeyValues("Stuff", "title", text); - - if (keyValue == INVALID_HANDLE) { - return false; - } - - KvSetColor(keyValue, "color", r, g, b, a); - KvSetNum(keyValue, "level", 1); - KvSetNum(keyValue, "time", RoundToFloor(duration)); - - CreateDialog(client, keyValue, DialogType_Msg); - - if (!CloseHandle(keyValue)) { - return false; - } - return true; -} - -/** - * Prints colored text to the top left of the screen - * for one client. Does not work in all games. - * Line Breaks can't be done. - * - * @param client Client Index. - * @param r Red amount. - * @param g Green amount. - * @param b Blue amount. - * @param a Transparency. - * @param duration Duration in seconds the text stays (min 10 - max 200 seconds). - * @param format Formatting rules. - * @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:...) -{ - new String:buffer[150]; - SetGlobalTransTarget(client); - VFormat(buffer, sizeof(buffer), format, 8); - - return Client_PrintToTopRaw(client, r, g, b, a, duration, buffer); -} - -/** - * Prints colored text to the top left of the screen - * to all clients. Does not work in all games. - * Line Breaks can't be done. - * - * @param r Red amount. - * @param g Green amount. - * @param b Blue amount. - * @param a Transparency. - * @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:...) -{ - decl - String:buffer[150]; - new - language, - lastLanguage = -1; - - for (new client=1; client <= MaxClients; client++) { - - if (!IsClientInGame(client)) { - continue; - } - - if (client == printToTop_excludeclient) { - printToTop_excludeclient = -1; - continue; - } - - language = GetClientLanguage(client); - - if (language != lastLanguage) { - SetGlobalTransTarget(client); - VFormat(buffer, sizeof(buffer), format, 7); - - lastLanguage = language; - } - - Client_PrintToTopRaw(client, r, g, b, a, duration, buffer); - } -} - -/** - * Prints colored text to the top left of the screen - * to specified clients. Does not work in all games. - * Line Breaks can't be done. - * - * @param clients Client Array. - * @param numClients Number of clients in the clients array. - * @param r Red amount. - * @param g Green amount. - * @param b Blue amount. - * @param a Transparency. - * @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:...) -{ - decl - String:buffer[150]; - new - client, - language, - lastLanguage = -1; - - for (new i=0; i < numClients; i++) { - - client = clients[i]; - - if (!IsClientInGame(client)) { - continue; - } - - if (client == printToTop_excludeclient) { - printToTop_excludeclient = -1; - continue; - } - - language = GetClientLanguage(client); - - if (language != lastLanguage) { - SetGlobalTransTarget(client); - VFormat(buffer, sizeof(buffer), format, 9); - - lastLanguage = language; - } - - Client_PrintToTopRaw(client, r, g, b, a, duration, buffer); - } -} - -/** - * Opens the scoreboard for a specific client - * - * @tested csgo - * @param client Client index - * @noreturn - */ -stock Client_ShowScoreboard(client, flags=USERMSG_RELIABLE | USERMSG_BLOCKHOOKS) -{ - new Handle:handle = StartMessageOne("VGUIMenu", client, flags); - - if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && - GetUserMessageType() == UM_Protobuf) { - - PbSetString(handle, "name", "scores"); - PbSetBool(handle, "show", true); - } - else { - BfWriteString(handle, "scores"); - BfWriteByte(handle, 1); // Show - BfWriteByte(handle, 0); // subkeys count - } - - EndMessage(); -} diff --git a/scripting/1.10/include/smlib/colors.inc b/scripting/1.10/include/smlib/colors.inc deleted file mode 100644 index ffcdb9e..0000000 --- a/scripting/1.10/include/smlib/colors.inc +++ /dev/null @@ -1,528 +0,0 @@ -#if defined _smlib_colors_included - #endinput -#endif -#define _smlib_colors_included - -#include -#include -#include - -#define CHATCOLOR_NOSUBJECT -2 -#define SMLIB_COLORS_GAMEDATAFILE "smlib_colors.games" - -enum ChatColorSubjectType -{ - ChatColorSubjectType_none = -3, - - // Subject/Team colors - ChatColorSubjectType_player = -2, - ChatColorSubjectType_undefined = -1, - ChatColorSubjectType_world = 0 - // Anything higher is a specific team -} - -enum ChatColorInfo -{ - ChatColorInfo_Code, - ChatColorInfo_Alternative, - bool:ChatColorInfo_Supported, - ChatColorSubjectType:ChatColorInfo_SubjectType -}; - -enum ChatColor -{ - ChatColor_Normal, - ChatColor_Orange, - ChatColor_Red, - ChatColor_RedBlue, - ChatColor_Blue, - ChatColor_BlueRed, - ChatColor_Team, - ChatColor_Lightgreen, - ChatColor_Gray, - ChatColor_Green, - ChatColor_Olivegreen, - ChatColor_Black -} - -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 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 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 bool:checkTeamPlay = false; -static Handle:mp_teamplay = INVALID_HANDLE; -static bool:isSayText2_supported = true; -static 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) -{ - chatSubject = client; -} - -/** - * Gets the subject used for the chat color parser. - * - * @return Client Index/Subject, or CHATCOLOR_NOSUBJECT if none - */ -stock Color_ChatGetSubject() -{ - return chatSubject; -} - -/** - * Clears the subject used for the chat color parser. - * Call this after Color_ParseChatText(). - * - * @noreturn - */ -stock Color_ChatClearSubject() -{ - chatSubject = CHATCOLOR_NOSUBJECT; -} - -/** - * Parses a chat string and converts all color tags to color codes. - * This is a very powerful function that works recursively over the color information - * 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 - */ -stock Color_ParseChatText(const String:str[], String:buffer[], size) -{ - new - bool:inBracket = false, - x = 0, x_buf = 0, x_tag = 0, - 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 - - size--; - - // Every chat message has to start with a - // color code, otherwise it will ignore all colors. - buffer[x_buf++] = '\x01'; - - while (str[x] != '\0') { - - if (size == x_buf) { - break; - } - - new character = str[x++]; - - if (inBracket) { - // We allow up to 9 characters in the tag (#RRGGBBAA) - if (character == '}' || x_tag > 9) { - inBracket = false; - sTag[x_tag] = '\0'; - x_tag = 0; - - if (character == '}') { - Color_TagToCode(sTag, subject, colorCode); - - if (colorCode[0] == '\0') { - // We got an unknown tag, ignore this - // and forward it to the buffer. - - // Terminate buffer with \0 so Format can handle it. - buffer[x_buf] = '\0'; - x_buf = Format(buffer, size, "%s{%s}", buffer, sTag); - - // We 'r done here - continue; - } - else if (!StrEqual(colorCode, currentColor)) { - // If we are already using this color, - // we don't need to set it again. - - // Write the color code to our buffer. - // x_buf will be increased by the number of cells written. - x_buf += strcopy(buffer[x_buf], size - x_buf, colorCode); - - // Remember the current color. - strcopy(currentColor, sizeof(currentColor), colorCode); - } - } - else { - // If the tag character limit exceeds 9, - // we have to do something. - - // Terminate buffer with \0 so Format can handle it. - buffer[x_buf] = '\0'; - x_buf = Format(buffer, size, "%s{%s%c", buffer, sTag, character); - } - } - else if (character == '{' && !x_tag) { - buffer[x_buf++] = '{'; - inBracket = false; - } - else { - sTag[x_tag++] = character; - } - } - else if (character == '{') { - inBracket = true; - } - else { - buffer[x_buf++] = character; - } - } - - // Write remaining text to the buffer, - // if we have been inside brackets. - if (inBracket) { - buffer[x_buf] = '\0'; - x_buf = Format(buffer, size, "%s{%s", buffer, sTag); - } - - buffer[x_buf] = '\0'; - - return subject; -} - -/** - * Converts a chat color tag to its code character. - * - * @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]) -{ - // 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); - switch (length_tag - 1) { - // #RGB -> \07RRGGBB - case 3: { - FormatEx( - result, sizeof(result), "\x07%c%c%c%c%c%c", - tag[1], tag[1], tag[2], tag[2], tag[3], tag[3] - ); - } - // #RGBA -> \08RRGGBBAA - case 4: { - FormatEx( - result, sizeof(result), "\x08%c%c%c%c%c%c%c%c", - tag[1], tag[1], tag[2], tag[2], tag[3], tag[3], tag[4], tag[4] - ); - } - // #RRGGBB -> \07RRGGBB - case 6: { - FormatEx(result, sizeof(result), "\x07%s", tag[1]); - } - // #RRGGBBAA -> \08RRGGBBAA - case 8: { - FormatEx(result, sizeof(result), "\x08%s", tag[1]); - } - default: { - result[0] = '\0'; - } - } - - return; - } - else { - // Try to handle this string as color name - new n = Array_FindString(chatColorTags, sizeof(chatColorTags), tag); - - // Check if this tag is invalid - if (n == -1) { - result[0] = '\0'; - return; - } - - // Check if the color is actually supported 'n stuff. - Color_GetChatColorInfo(n, subject); - - result[0] = chatColorInfo[n][ChatColorInfo_Code]; - result[1] = '\0'; - } - - return; -} - -/** - * Strips all color control characters in a string. - * The Output buffer can be the same as the input buffer. - * Original code by Psychonic, thanks. - * - * @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) -{ - new x = 0; - for (new i=0; input[i] != '\0'; i++) { - - if (x+1 == size) { - break; - } - - new character = input[i]; - - if (character > 0x08) { - output[x++] = character; - } - } - - output[x] = '\0'; -} - -/** - * Checks the gamename and sets default values. - * For example if some colors are supported, or - * 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 initialized = false; - - if (initialized) { - return; - } - - initialized = true; - - decl String:gameFolderName[32]; - GetGameFolderName(gameFolderName, sizeof(gameFolderName)); - - 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; - } - - if (StrEqual(gameFolderName, "tf", false)) { - chatColorInfo[ChatColor_Black][ChatColorInfo_Supported] = true; - - 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_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; - - checkTeamPlay = true; - } - else if (StrEqual(gameFolderName, "dod", false)) { - 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; - } - - if (GetUserMessageId("SayText2") == INVALID_MESSAGE_ID) { - isSayText2_supported = false; - } - - decl String: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; - - if ((gamedata = LoadGameConfigFile(SMLIB_COLORS_GAMEDATAFILE)) != INVALID_HANDLE) { - - decl String:keyName[32], String:buffer[6]; - - for (new 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); - } - - Format(keyName, sizeof(keyName), "%s_alternative", chatColorNames[i]); - if (GameConfGetKeyValue(gamedata, keyName, buffer, sizeof(buffer))) { - 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"); - } - - Format(keyName, sizeof(keyName), "%s_subjecttype", chatColorNames[i]); - if (GameConfGetKeyValue(gamedata, keyName, buffer, sizeof(buffer))) { - chatColorInfo[i][ChatColorInfo_SubjectType] = ChatColorSubjectType:StringToInt(buffer); - } - } - - if (GameConfGetKeyValue(gamedata, "checkteamplay", buffer, sizeof(buffer))) { - checkTeamPlay = StrEqual(buffer, "true"); - } - - CloseHandle(gamedata); - } - } - - mp_teamplay = FindConVar("mp_teamplay"); -} - -/** - * Checks if the passed color index is actually supported - * for the current game. If not, the index will be overwritten - * The color resolving works recursively until a valid color is found. - * - * @param index - * @param subject A client index or CHATCOLOR_NOSUBJECT - * @noreturn - */ -static stock Color_GetChatColorInfo(&index, &subject=CHATCOLOR_NOSUBJECT) -{ - Color_ChatInitialize(); - - if (index == -1) { - index = 0; - } - - while (!chatColorInfo[index][ChatColorInfo_Supported]) { - - new alternative = chatColorInfo[index][ChatColorInfo_Alternative]; - - if (alternative == -1) { - index = 0; - break; - } - - index = alternative; - } - - if (index == -1) { - index = 0; - } - - new newSubject = CHATCOLOR_NOSUBJECT; - new ChatColorSubjectType:type = chatColorInfo[index][ChatColorInfo_SubjectType]; - - switch (type) { - - case ChatColorSubjectType_none: { - } - case ChatColorSubjectType_player: { - newSubject = chatSubject; - } - case ChatColorSubjectType_undefined: { - newSubject = -1; - } - case ChatColorSubjectType_world: { - newSubject = 0; - } - default: { - - if (!checkTeamPlay || GetConVarBool(mp_teamplay)) { - - if (subject > 0 && subject <= MaxClients) { - - if (GetClientTeam(subject) == _:type) { - newSubject = subject; - } - } - else if (subject == CHATCOLOR_NOSUBJECT) { - new client = Team_GetAnyClient(_:type); - - if (client != -1) { - newSubject = client; - } - } - } - } - } - - if (type > ChatColorSubjectType_none && - ((subject != CHATCOLOR_NOSUBJECT && subject != newSubject) || newSubject == CHATCOLOR_NOSUBJECT || !isSayText2_supported)) - { - index = chatColorInfo[index][ChatColorInfo_Alternative]; - newSubject = Color_GetChatColorInfo(index, subject); - } - - // Only set the subject if there is no subject set already. - if (subject == CHATCOLOR_NOSUBJECT) { - subject = newSubject; - } - - return newSubject; -} diff --git a/scripting/1.10/include/smlib/concommands.inc b/scripting/1.10/include/smlib/concommands.inc deleted file mode 100644 index a90fd1c..0000000 --- a/scripting/1.10/include/smlib/concommands.inc +++ /dev/null @@ -1,47 +0,0 @@ -#if defined _smlib_concommands_included - #endinput -#endif -#define _smlib_concommands_included - -#include -#include - -/** - * Checks if a ConCommand has one or more flags set. - * - * @param command ConCommand name. - * @param flags Flags to check. - * @return True if flags are set, false otherwise. - */ -stock bool:ConCommand_HasFlags(const String:command[], const flags) -{ - return bool:(GetCommandFlags(command) & flags); -} - -/** - * Adds one or more flags to a ConCommand. - * - * @param command ConCommand name. - * @param flags Flags to add. - * @noreturn - */ -stock ConCommand_AddFlags(const String:command[], const flags) -{ - new newFlags = GetCommandFlags(command); - newFlags |= flags; - SetCommandFlags(command, newFlags); -} - -/** - * Removes one ore more flags from a ConCommand. - * - * @param command ConCommand name. - * @param flags Flags to remove - * @noreturn - */ -stock ConCommand_RemoveFlags(const String:command[], const flags) -{ - new newFlags = GetCommandFlags(command); - newFlags &= ~flags; - SetCommandFlags(command, newFlags); -} diff --git a/scripting/1.10/include/smlib/convars.inc b/scripting/1.10/include/smlib/convars.inc deleted file mode 100644 index 9b9ba4a..0000000 --- a/scripting/1.10/include/smlib/convars.inc +++ /dev/null @@ -1,72 +0,0 @@ -#if defined _smlib_convars_included - #endinput -#endif -#define _smlib_convars_included - -#include - -/** - * Checks if a ConVar has one or more flags set. - * - * @param convar ConVar Handle. - * @param flags Flags to check. - * @return True if flags are set, false otherwise. - */ -stock bool:Convar_HasFlags(Handle:convar, flags) -{ - return bool:(GetConVarFlags(convar) & flags); -} - -/** - * Adds one or more flags to a ConVar. - * - * @param convar ConVar Handle. - * @param flags Flags to add. - * @noreturn - */ -stock Convar_AddFlags(Handle:convar, flags) -{ - new newFlags = GetConVarFlags(convar); - newFlags |= flags; - SetConVarFlags(convar, newFlags); -} - -/** - * Removes one ore more flags from a ConVar. - * - * @param convar ConVar Handle. - * @param flags Flags to remove - * @noreturn - */ -stock Convar_RemoveFlags(Handle:convar, flags) -{ - new newFlags = GetConVarFlags(convar); - newFlags &= ~flags; - SetConVarFlags(convar, newFlags); -} - -/** - * Checks if a String is a valid ConVar or - * Console Command name. - * - * @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[]) -{ - if (name[0] == '\0') { - return false; - } - - new n=0; - while (name[n] != '\0') { - - if (!IsValidConVarChar(name[n])) { - return false; - } - - n++; - } - - return true; -} diff --git a/scripting/1.10/include/smlib/crypt.inc b/scripting/1.10/include/smlib/crypt.inc deleted file mode 100644 index 6e5f380..0000000 --- a/scripting/1.10/include/smlib/crypt.inc +++ /dev/null @@ -1,629 +0,0 @@ -#if defined _smlib_crypt_included - #endinput -#endif -#define _smlib_crypt_included - -#include - -/********************************************************************************** - * - * Base64 Encoding/Decoding Functions - * All Credits to to SirLamer & ScriptCoderPro - * Taken from http://forums.alliedmods.net/showthread.php?t=101764 - * - ***********************************************************************************/ - -// The Base64 encoding table -static const String:base64_sTable[] = - // 0000000000111111111122222222223333333333444444444455555555556666 - // 0123456789012345678901234567890123456789012345678901234567890123 - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -// The Base64 decoding table -static const 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 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20 - 29 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 30 - 39 - 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, // 40 - 49 - 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, // 50 - 59 - 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, // 60 - 69 - 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 70 - 79 - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 80 - 89 - 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, // 90 - 99 - 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // 100 - 109 - 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, // 110 - 119 - 49, 50, 51, 0, 0, 0, 0, 0, 0, 0, // 120 - 129 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 130 - 139 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 140 - 149 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 150 - 159 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 160 - 169 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 170 - 179 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 180 - 189 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 190 - 199 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 200 - 209 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 210 - 219 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 220 - 229 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 230 - 239 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 240 - 249 - 0, 0, 0, 0, 0, 0 // 250 - 256 -}; - -/* - * 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 = '='; - -// The conversion characters between the standard and URL-compliance Base64 protocols -static const String:base64_mime_chars[] = "+/="; -static const String:base64_url_chars[] = "-_."; - -/* - * Encodes a string or binary data into Base64 - * - * @param sString The input string or binary data to be encoded. - * @param sResult The storage buffer for the Base64-encoded result. - * @param len The maximum length of the storage buffer, in characters/bytes. - * @param sourcelen (optional): The number of characters or length in bytes to be read from the input source. - * 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) -{ - new nLength; // The string length to be read from the input - new 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) { - nLength = sourcelen; - } - else { - nLength = strlen(sString); - } - - // 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; - - cCode = (sString[nPos] >> 2) & 0x3f; - - resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_sTable[cCode]); - - cCode = (sString[nPos] << 4) & 0x3f; - if (++nPos < nLength) { - cCode |= (sString[nPos] >> 4) & 0x0f; - } - resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_sTable[cCode]); - - if ( nPos < nLength ) { - cCode = (sString[nPos] << 2) & 0x3f; - if (++nPos < nLength) { - cCode |= (sString[nPos] >> 6) & 0x03; - } - - resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_sTable[cCode]); - } - else { - nPos++; - resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_cFillChar); - } - - if (nPos < nLength) { - cCode = sString[nPos] & 0x3f; - resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_sTable[cCode]); - } - else { - resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_cFillChar); - } - } - - return resPos; -} - - -/* - * Decodes a Base64 string. - * - * @param sString The input string in compliant Base64 format to be decoded. - * @param sResult The storage buffer for the decoded text strihg or binary data. - * @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) -{ - new nLength = strlen(sString); // The string length to be read from the input - new 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++) { - - new c, c1; - - c = base64_decodeTable[sString[nPos++]]; - c1 = base64_decodeTable[sString[nPos]]; - - c = (c << 2) | ((c1 >> 4) & 0x3); - - resPos += FormatEx(sResult[resPos], len - resPos, "%c", c); - - if (++nPos < nLength) { - - c = sString[nPos]; - - if (c == base64_cFillChar) - break; - - c = base64_decodeTable[sString[nPos]]; - c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf); - - resPos += FormatEx(sResult[resPos], len - resPos, "%c", c1); - } - - if (++nPos < nLength) { - - c1 = sString[nPos]; - - if (c1 == base64_cFillChar) - break; - - c1 = base64_decodeTable[sString[nPos]]; - c = ((c << 6) & 0xc0) | c1; - - resPos += FormatEx(sResult[resPos], len - resPos, "%c", c); - } - } - - return resPos; -} - - -/* - * Converts a standards-compliant Base64 string to the commonly accepted URL-compliant alternative. - * Note: The result will be the same length as the input string as long as the output buffer is large enough. - * - * @param sString The standards-compliant Base64 input string to converted. - * @param sResult The storage buffer for the URL-compliant result. - * @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) -{ - 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 - - nLength = strlen(sString); - - new String:sTemp[nLength+1]; // Buffer string - - // Loop through string - for (new i = 0; i < nLength; i++) { - temp_char = sString[i]; - - for (new j = 0; j < chars_len; j++) { - - if(temp_char == base64_mime_chars[j]) { - temp_char = base64_url_chars[j]; - break; - } - } - - sTemp[i] = temp_char; - } - - sTemp[nLength] = '\0'; - - return strcopy(sResult, len, sTemp); -} - -/* - * Base64UrlToMime(String:sResult[], len, const String:sString[], sourcelen) - * Converts a URL-compliant Base64 string to the standards-compliant version. - * Note: The result will be the same length as the input string as long as the output buffer is large enough. - * - * @param sString The URL-compliant Base64 input string to converted. - * @param sResult The storage buffer for the standards-compliant result. - * @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) -{ - 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 - - nLength = strlen(sString); - - new String:sTemp[nLength+1]; // Buffer string - - // Loop through string - for (new i = 0; i < nLength; i++) { - temp_char = sString[i]; - for (new j = 0; j < chars_len; j++) { - if (temp_char == base64_url_chars[j]) { - temp_char = base64_mime_chars[j]; - break; - } - } - - sTemp[i] = temp_char; - } - - sTemp[nLength] = '\0'; - - return strcopy(sResult, len, sTemp); -} - -/********************************************************************************** - * - * MD5 Encoding Functions - * All Credits go to sslice - * RSA Data Security, Inc. MD5 Message Digest Algorithm - * Taken from http://forums.alliedmods.net/showthread.php?t=67683 - * - ***********************************************************************************/ - -/* - * Calculate the md5 hash of a string. - * - * @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) -{ - decl x[2]; - decl buf[4]; - decl input[64]; - new i, ii; - - new len = strlen(str); - - // MD5Init - x[0] = x[1] = 0; - buf[0] = 0x67452301; - buf[1] = 0xefcdab89; - buf[2] = 0x98badcfe; - buf[3] = 0x10325476; - - // MD5Update - new update[16]; - - update[14] = x[0]; - update[15] = x[1]; - - new mdi = (x[0] >>> 3) & 0x3F; - - if ((x[0] + (len << 3)) < x[0]) { - x[1] += 1; - } - - x[0] += len << 3; - x[1] += len >>> 29; - - new c = 0; - while (len--) { - input[mdi] = str[c]; - mdi += 1; - c += 1; - - if (mdi == 0x40) { - - for (i = 0, ii = 0; i < 16; ++i, ii += 4) - { - update[i] = (input[ii + 3] << 24) | (input[ii + 2] << 16) | (input[ii + 1] << 8) | input[ii]; - } - - // Transform - MD5Transform(buf, update); - - mdi = 0; - } - } - - // MD5Final - new 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, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 - }; - - new inx[16]; - inx[14] = x[0]; - inx[15] = x[1]; - - mdi = (x[0] >>> 3) & 0x3F; - - len = (mdi < 56) ? (56 - mdi) : (120 - mdi); - update[14] = x[0]; - update[15] = x[1]; - - mdi = (x[0] >>> 3) & 0x3F; - - if ((x[0] + (len << 3)) < x[0]) { - x[1] += 1; - } - - x[0] += len << 3; - x[1] += len >>> 29; - - c = 0; - while (len--) { - input[mdi] = padding[c]; - mdi += 1; - c += 1; - - if (mdi == 0x40) { - - for (i = 0, ii = 0; i < 16; ++i, ii += 4) { - update[i] = (input[ii + 3] << 24) | (input[ii + 2] << 16) | (input[ii + 1] << 8) | input[ii]; - } - - // Transform - MD5Transform(buf, update); - - mdi = 0; - } - } - - for (i = 0, ii = 0; i < 14; ++i, ii += 4) { - inx[i] = (input[ii + 3] << 24) | (input[ii + 2] << 16) | (input[ii + 1] << 8) | input[ii]; - } - - MD5Transform(buf, inx); - - new digest[16]; - for (i = 0, ii = 0; i < 4; ++i, ii += 4) { - digest[ii] = (buf[i]) & 0xFF; - digest[ii + 1] = (buf[i] >>> 8) & 0xFF; - digest[ii + 2] = (buf[i] >>> 16) & 0xFF; - digest[ii + 3] = (buf[i] >>> 24) & 0xFF; - } - - FormatEx(output, maxlen, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", - digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7], - 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) - { - 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) - { - 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) - { - 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) -{ - 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]; - - MD5Transform_FF(a, b, c, d, input[0], 7, 0xd76aa478); - MD5Transform_FF(d, a, b, c, input[1], 12, 0xe8c7b756); - MD5Transform_FF(c, d, a, b, input[2], 17, 0x242070db); - MD5Transform_FF(b, c, d, a, input[3], 22, 0xc1bdceee); - MD5Transform_FF(a, b, c, d, input[4], 7, 0xf57c0faf); - MD5Transform_FF(d, a, b, c, input[5], 12, 0x4787c62a); - MD5Transform_FF(c, d, a, b, input[6], 17, 0xa8304613); - MD5Transform_FF(b, c, d, a, input[7], 22, 0xfd469501); - MD5Transform_FF(a, b, c, d, input[8], 7, 0x698098d8); - MD5Transform_FF(d, a, b, c, input[9], 12, 0x8b44f7af); - MD5Transform_FF(c, d, a, b, input[10], 17, 0xffff5bb1); - MD5Transform_FF(b, c, d, a, input[11], 22, 0x895cd7be); - MD5Transform_FF(a, b, c, d, input[12], 7, 0x6b901122); - MD5Transform_FF(d, a, b, c, input[13], 12, 0xfd987193); - MD5Transform_FF(c, d, a, b, input[14], 17, 0xa679438e); - MD5Transform_FF(b, c, d, a, input[15], 22, 0x49b40821); - - MD5Transform_GG(a, b, c, d, input[1], 5, 0xf61e2562); - MD5Transform_GG(d, a, b, c, input[6], 9, 0xc040b340); - MD5Transform_GG(c, d, a, b, input[11], 14, 0x265e5a51); - MD5Transform_GG(b, c, d, a, input[0], 20, 0xe9b6c7aa); - MD5Transform_GG(a, b, c, d, input[5], 5, 0xd62f105d); - MD5Transform_GG(d, a, b, c, input[10], 9, 0x02441453); - MD5Transform_GG(c, d, a, b, input[15], 14, 0xd8a1e681); - MD5Transform_GG(b, c, d, a, input[4], 20, 0xe7d3fbc8); - MD5Transform_GG(a, b, c, d, input[9], 5, 0x21e1cde6); - MD5Transform_GG(d, a, b, c, input[14], 9, 0xc33707d6); - MD5Transform_GG(c, d, a, b, input[3], 14, 0xf4d50d87); - MD5Transform_GG(b, c, d, a, input[8], 20, 0x455a14ed); - MD5Transform_GG(a, b, c, d, input[13], 5, 0xa9e3e905); - MD5Transform_GG(d, a, b, c, input[2], 9, 0xfcefa3f8); - MD5Transform_GG(c, d, a, b, input[7], 14, 0x676f02d9); - MD5Transform_GG(b, c, d, a, input[12], 20, 0x8d2a4c8a); - - MD5Transform_HH(a, b, c, d, input[5], 4, 0xfffa3942); - MD5Transform_HH(d, a, b, c, input[8], 11, 0x8771f681); - MD5Transform_HH(c, d, a, b, input[11], 16, 0x6d9d6122); - MD5Transform_HH(b, c, d, a, input[14], 23, 0xfde5380c); - MD5Transform_HH(a, b, c, d, input[1], 4, 0xa4beea44); - MD5Transform_HH(d, a, b, c, input[4], 11, 0x4bdecfa9); - MD5Transform_HH(c, d, a, b, input[7], 16, 0xf6bb4b60); - MD5Transform_HH(b, c, d, a, input[10], 23, 0xbebfbc70); - MD5Transform_HH(a, b, c, d, input[13], 4, 0x289b7ec6); - MD5Transform_HH(d, a, b, c, input[0], 11, 0xeaa127fa); - MD5Transform_HH(c, d, a, b, input[3], 16, 0xd4ef3085); - MD5Transform_HH(b, c, d, a, input[6], 23, 0x04881d05); - MD5Transform_HH(a, b, c, d, input[9], 4, 0xd9d4d039); - MD5Transform_HH(d, a, b, c, input[12], 11, 0xe6db99e5); - MD5Transform_HH(c, d, a, b, input[15], 16, 0x1fa27cf8); - MD5Transform_HH(b, c, d, a, input[2], 23, 0xc4ac5665); - - MD5Transform_II(a, b, c, d, input[0], 6, 0xf4292244); - MD5Transform_II(d, a, b, c, input[7], 10, 0x432aff97); - MD5Transform_II(c, d, a, b, input[14], 15, 0xab9423a7); - MD5Transform_II(b, c, d, a, input[5], 21, 0xfc93a039); - MD5Transform_II(a, b, c, d, input[12], 6, 0x655b59c3); - MD5Transform_II(d, a, b, c, input[3], 10, 0x8f0ccc92); - MD5Transform_II(c, d, a, b, input[10], 15, 0xffeff47d); - MD5Transform_II(b, c, d, a, input[1], 21, 0x85845dd1); - MD5Transform_II(a, b, c, d, input[8], 6, 0x6fa87e4f); - MD5Transform_II(d, a, b, c, input[15], 10, 0xfe2ce6e0); - MD5Transform_II(c, d, a, b, input[6], 15, 0xa3014314); - MD5Transform_II(b, c, d, a, input[13], 21, 0x4e0811a1); - MD5Transform_II(a, b, c, d, input[4], 6, 0xf7537e82); - MD5Transform_II(d, a, b, c, input[11], 10, 0xbd3af235); - MD5Transform_II(c, d, a, b, input[2], 15, 0x2ad7d2bb); - MD5Transform_II(b, c, d, a, input[9], 21, 0xeb86d391); - - buf[0] += a; - buf[1] += b; - buf[2] += c; - buf[3] += d; -} - -/********************************************************************************** - * - * RC4 Encoding Functions - * All Credits go to SirLamer and Raydan - * Taken from http://forums.alliedmods.net/showthread.php?t=101834 - * - ***********************************************************************************/ - -/* - * Encrypts a text string using RC4. - * Note: This function is NOT binary safe. - * Use EncodeRC4Binary 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) -{ - decl pwd_len,str_len,i,j,a,k; - decl key[256]; - decl box[256]; - decl tmp; - - pwd_len = strlen(pwd); - str_len = strlen(input); - - if (pwd_len > 0 && str_len > 0) { - - for (i=0; i < 256; i++) { - key[i] = pwd[i%pwd_len]; - box[i]=i; - } - - i=0; j=0; - - for (; i < 256; i++) { - j = (j + box[i] + key[i]) % 256; - tmp = box[i]; - box[i] = box[j]; - box[j] = tmp; - } - - i=0; j=0; a=0; - - for (; i < str_len; i++) { - a = (a + 1) % 256; - j = (j + box[a]) % 256; - tmp = box[a]; - box[a] = box[j]; - box[j] = tmp; - k = box[((box[a] + box[j]) % 256)]; - FormatEx(output[2*i], maxlen-2*i, "%02x", input[i] ^ k); - } - } -} - -/* - * Encrypts binary data using RC4. - * - * @param input The source data to be encrypted. - * @param str_len The length of the source data. - * @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) -{ - decl pwd_len,i,j,a,k; - decl key[256]; - decl box[256]; - decl tmp; - - pwd_len = strlen(pwd); - - if (pwd_len > 0 && str_len > 0) { - - for(i=0;i<256;i++) { - key[i] = pwd[i%pwd_len]; - box[i]=i; - } - - i=0; j=0; - - for (; i < 256; i++) { - j = (j + box[i] + key[i]) % 256; - tmp = box[i]; - box[i] = box[j]; - box[j] = tmp; - } - - i=0; j=0; a=0; - - if (str_len+1 > maxlen) { - str_len = maxlen - 1; - } - - for(; i < str_len; i++) { - a = (a + 1) % 256; - j = (j + box[a]) % 256; - tmp = box[a]; - box[a] = box[j]; - box[j] = tmp; - k = box[((box[a] + box[j]) % 256)]; - FormatEx(output[i], maxlen-i, "%c", input[i] ^ k); - } - - /* - * i = number of written bits (remember increment occurs at end of for loop, and THEN it fails the loop condition) - * Since we're working with binary data, the calling function should not depend on the escape - * character, but putting it here prevents crashes in case someone tries to read the data like a string - */ - output[i] = '\0'; - - return i; - } - else { - return -1; - } -} diff --git a/scripting/1.10/include/smlib/debug.inc b/scripting/1.10/include/smlib/debug.inc deleted file mode 100644 index 46275ba..0000000 --- a/scripting/1.10/include/smlib/debug.inc +++ /dev/null @@ -1,30 +0,0 @@ -#if defined _smlib_debug_included - #endinput -#endif -#define _smlib_debug_included - -#include - -/** - * Prints the values of a static Float-Array to the server console. - * - * @param array Static Float-Array. - * @param size Size of the Array. - * @noreturn - */ -stock Debug_FloatArray(const Float:array[], size=3) -{ - new String:output[64] = ""; - - for (new i=0; i < size; ++i) { - - if (i > 0 && i < size) { - StrCat(output, sizeof(output), ", "); - - } - - Format(output, sizeof(output), "%s%f", output, array[i]); - } - - PrintToServer("[DEBUG] Vector[%d] = { %s }", size, output); -} diff --git a/scripting/1.10/include/smlib/dynarrays.inc b/scripting/1.10/include/smlib/dynarrays.inc deleted file mode 100644 index 8a16011..0000000 --- a/scripting/1.10/include/smlib/dynarrays.inc +++ /dev/null @@ -1,24 +0,0 @@ -#if defined _smlib_dynarray_included - #endinput -#endif -#define _smlib_dynarray_included - -#include - -/** - * Retrieves a cell value from an array. - * This is a wrapper around the Sourcemod Function GetArrayCell, - * but it casts the result as bool - * - * @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. - */ -stock bool:DynArray_GetBool(Handle:array, index, block=0, bool:asChar=false) -{ - return bool:GetArrayCell(array, index, block, asChar); -} diff --git a/scripting/1.10/include/smlib/edicts.inc b/scripting/1.10/include/smlib/edicts.inc deleted file mode 100644 index 376f975..0000000 --- a/scripting/1.10/include/smlib/edicts.inc +++ /dev/null @@ -1,127 +0,0 @@ -#if defined _smlib_edicts_included - #endinput -#endif -#define _smlib_edicts_included - -#include -#include - -/* - * Finds an edict by it's name - * It only finds the first occurence. - * - * @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[]) -{ - new maxEntities = GetMaxEntities(); - for (new edict=0; edict < maxEntities; edict++) { - - if (!IsValidEdict(edict)) { - continue; - } - - if (Entity_NameMatches(edict, name)) { - return edict; - } - } - - return INVALID_ENT_REFERENCE; -} - -/* - * Finds an edict by its HammerID. - * The newer version of Valve's Hammer editor - * sets a unique ID for each entity in a map. - * It only finds the first occurence. - * - * @param hammerId Hammer editor ID - * @return Edict Index or INVALID_ENT_REFERENCE if no entity was found. - */ -stock Edict_FindByHammerId(hammerId) -{ - new maxEntities = GetMaxEntities(); - for (new edict=0; edict < maxEntities; edict++) { - - if (!IsValidEdict(edict)) { - continue; - } - - if (Entity_GetHammerId(edict) == hammerId) { - return edict; - } - } - - return INVALID_ENT_REFERENCE; -} - -/** - * Searches for the closest edict in relation to the given origin - * - * @param vecOrigin_center 3 dimensional origin array - * @param clientsOnly True if you only want to search for clients - * @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) -{ - decl Float:vecOrigin_edict[3]; - new Float:smallestDistance = 0.0; - new closestEdict = INVALID_ENT_REFERENCE; - - new maxEntities; - - if (clientsOnly) { - maxEntities = MaxClients; - } - else { - maxEntities = GetMaxEntities(); - } - - for (new edict=1; edict <= maxEntities; edict++) { - - if (!IsValidEdict(edict)) { - continue; - } - - if (ignoreEntity >= 0 && edict == ignoreEntity) { - continue; - } - - if (GetEntSendPropOffs(edict, "m_vecOrigin") == -1) { - continue; - } - - Entity_GetAbsOrigin(edict, vecOrigin_edict); - - new Float:edict_distance = GetVectorDistance(vecOrigin_center, vecOrigin_edict, true); - - if (edict_distance < smallestDistance || smallestDistance == 0.0) { - smallestDistance = edict_distance; - closestEdict = edict; - } - } - - return closestEdict; -} - -/** - * Searches for the closest edict in relation to the given edict. - * - * @param edict Edict index - * @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) -{ - decl Float:vecOrigin[3]; - - if (GetEntSendPropOffs(edict, "m_vecOrigin") == -1) { - return INVALID_ENT_REFERENCE; - } - - Entity_GetAbsOrigin(edict, vecOrigin); - - return Edict_GetClosest(vecOrigin, clientsOnly, edict); -} diff --git a/scripting/1.10/include/smlib/effects.inc b/scripting/1.10/include/smlib/effects.inc deleted file mode 100644 index ed87e58..0000000 --- a/scripting/1.10/include/smlib/effects.inc +++ /dev/null @@ -1,742 +0,0 @@ -#if defined _smlib_effects_included - #endinput -#endif -#define _smlib_effects_included - -#include -#include -#include -#include -#include -#include -#include -#include - - - -// Entity Dissolve types -enum DissolveType -{ - DISSOLVE_NORMAL = 0, - DISSOLVE_ELECTRICAL, - DISSOLVE_ELECTRICAL_LIGHT, - DISSOLVE_CORE -}; - -/** - * Dissolves a player - * - * @param client Client Index. - * @param dissolveType Dissolve Type, use the DissolveType enum. - * @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) -{ - new 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_nMagnitude", magnitude); - AcceptEntityInput(env_entity_dissolver, "Dissolve"); - Entity_Kill(env_entity_dissolver); - - return true; -} - -/** - * Dissolves a player's Ragdoll - * - * @param client Client Index. - * @param dissolveType Dissolve Type, use the DissolveType enum. - * @return True on success, otherwise false. - */ -stock bool:Effect_DissolvePlayerRagDoll(client, DissolveType:dissolveType=DISSOLVE_NORMAL) -{ - new m_hRagdoll = GetEntPropEnt(client, Prop_Send, "m_hRagdoll"); - - if (m_hRagdoll == -1) { - return false; - } - - return Effect_DissolveEntity(m_hRagdoll, dissolveType); -} - -typedef EffectCallback = function Action (int entity, any data); //function EffectCallback public(entity, any:data); - -/** - * Fades an entity in our out. - * You can specifiy a callback function which will get called - * when the fade is finished. - * Important: The callback will be called if it is passed, - * no matter if the entity is still valid or not. That means you - * have to check if the entity is valid yourself. - * - * @param entity Entity Index. - * @param fadeOut Optional: Fade the entity out (true) or in (false). - * @param kill Optional: If to kill the entity when the fade is finished. - * @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) -{ - new Float:timerTime = 0.0; - - if (fast) { - timerTime = 0.6; - - if (fadeOut) { - SetEntityRenderFx(entity, RENDERFX_FADE_FAST); - } - else { - SetEntityRenderFx(entity, RENDERFX_SOLID_FAST); - } - } - else { - timerTime = 3.0; - - if (fadeOut) { - SetEntityRenderFx(entity, RENDERFX_FADE_SLOW); - } - else { - SetEntityRenderFx(entity, RENDERFX_SOLID_SLOW); - } - } - - ChangeEdictState(entity, GetEntSendPropOffs(entity, "m_nRenderFX", true)); - - if (kill || callback != INVALID_FUNCTION) { - new Handle:dataPack = INVALID_HANDLE; - 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); - } -} - -/** - * Fades the entity in. - * A wrapper function around Effect_Fade(). - * - * @param entity Entity Index. - * @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) -{ - Effect_Fade(entity, false, false, fast, callback, data); -} - -/** - * Fades the entity out. - * A wrapper function around Effect_Fade(). - * - * @param entity Entity Index. - * @param fadeOut Optional: Fade the entity out (true) or in (false). - * @param kill Optional: If to kill the entity when the fade is finished. - * @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) -{ - Effect_Fade(entity, true, kill, fast, callback, data); -} - -public Action:_smlib_Timer_Effect_Fade(Handle:Timer, Handle: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); - - if (callback != INVALID_FUNCTION) { - Call_StartFunction(INVALID_HANDLE, callback); - Call_PushCell(entity); - Call_PushCell(data); - Call_Finish(); - } - - if (kill && IsValidEntity(entity)) { - Entity_Kill(entity); - } - - return Plugin_Stop; -} - -/** - * Sends a boxed beam effect to one player. - * - * Ported from eventscripts vecmath library. - * - * @param client The client to show the box to. - * @param bottomCorner One bottom corner of the box. - * @param upperCorner One upper corner of the box. - * @param modelIndex Precached model index. - * @param haloIndex Precached model index. - * @param startFrame Initital 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. - * @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 -) { - new clients[1]; - clients[0] = client; - Effect_DrawBeamBox(clients, 1, bottomCorner, upperCorner, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); -} - -/** - * Sends a boxed beam effect to all players. - * - * Ported from eventscripts vecmath library. - * - * @param bottomCorner One bottom corner of the box. - * @param upperCorner One upper corner of the box. - * @param modelIndex Precached model index. - * @param haloIndex Precached model index. - * @param startFrame Initital 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. - * @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 -) -{ - new clients[MaxClients]; - new numClients = Client_Get(clients, CLIENTFILTER_INGAME); - - Effect_DrawBeamBox(clients, numClients, bottomCorner, upperCorner, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); -} - -/** - * Sends a boxed beam effect to a list of players. - * - * Ported from eventscripts vecmath library. - * - * @param clients An array of clients to show the box to. - * @param numClients Number of players in the array. - * @param bottomCorner One bottom corner of the box. - * @param upperCorner One upper corner of the box. - * @param modelIndex Precached model index. - * @param haloIndex Precached model index. - * @param startFrame Initital 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. - * @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 -) { - // Create the additional corners of the box - decl Float:corners[8][3]; - - for (new i=0; i < 4; i++) { - Array_Copy(bottomCorner, corners[i], 3); - Array_Copy(upperCorner, corners[i+4], 3); - } - - corners[1][0] = upperCorner[0]; - corners[2][0] = upperCorner[0]; - corners[2][1] = upperCorner[1]; - corners[3][1] = upperCorner[1]; - corners[4][0] = bottomCorner[0]; - corners[4][1] = bottomCorner[1]; - corners[5][1] = bottomCorner[1]; - corners[7][0] = bottomCorner[0]; - - // Draw all the edges - - // Horizontal Lines - // Bottom - for (new i=0; i < 4; i++) { - new 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 ); - 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++) { - TE_SetupBeamPoints(corners[i], corners[i+4], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); - TE_Send(clients, numClients); - } -} - - -/** - * Sends a boxed beam effect to one player. - * - * Ported from eventscripts vecmath library. - * - * @param client The client to show the box to. - * @param origin Origin/center of the box. - * @param mins Min size Vector - * @param maxs Max size Vector - * @param angles Angles used to rotate the box. - * @param modelIndex Precached model index. - * @param haloIndex Precached model index. - * @param startFrame Initital 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. - * @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 -) { - new clients[1]; - clients[0] = client; - Effect_DrawBeamBoxRotatable(clients, 1, origin, mins, maxs, angles, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); -} - - - -/** - * Sends a boxed beam effect to all players. - * - * Ported from eventscripts vecmath library. - * - * @param origin Origin/center of the box. - * @param mins Min size Vector - * @param maxs Max size Vector - * @param angles Angles used to rotate the box. - * @param modelIndex Precached model index. - * @param haloIndex Precached model index. - * @param startFrame Initital 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. - * @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 -) -{ - new clients[MaxClients]; - new 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); -} - -/** - * Sends a boxed beam effect to a list of players. - * - * Ported from eventscripts vecmath library. - * - * @param clients An array of clients to show the box to. - * @param numClients Number of players in the array. - * @param origin Origin/center of the box. - * @param mins Min size Vector - * @param maxs Max size Vector - * @param angles Angles used to rotate the box. - * @param modelIndex Precached model index. - * @param haloIndex Precached model index. - * @param startFrame Initital 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. - * @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 -) { - // Create the additional corners of the box - decl 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]); - Math_MakeVector(mins[0], maxs[1], mins[2], corners[3]); - Math_MakeVector(mins[0], mins[1], maxs[2], corners[4]); - Math_MakeVector(maxs[0], mins[1], maxs[2], corners[5]); - Array_Copy(maxs, corners[6], 3); - Math_MakeVector(mins[0], maxs[1], maxs[2], corners[7]); - - // Rotate all edges - for (new 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++) { - 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 ); - 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 ); - 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++) { - TE_SetupBeamPoints(corners[i], corners[i+4], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); - TE_Send(clients, numClients); - } -} - -/** - * Displays the given axis of rotation as beam effect to one player. - * - * @param client The client to show the box to. - * @param origin Origin/center of the box. - * @param angles Angles used to rotate the box. - * @param length The length in each direction. - * @param modelIndex Precached model index. - * @param haloIndex Precached model index. - * @param startFrame Initital 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. - * @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 -) { - new clients[1]; - clients[0] = client; - Effect_DrawAxisOfRotation(clients, 1, origin, angles, length, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, speed); -} - -/** - * Displays the given axis of rotation as beam effect to all players. - * - * @param origin Origin/center of the box. - * @param angles Angles used to rotate the box. - * @param length The length in each direction. - * @param modelIndex Precached model index. - * @param haloIndex Precached model index. - * @param startFrame Initital 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. - * @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 -) -{ - new clients[MaxClients]; - new numClients = Client_Get(clients, CLIENTFILTER_INGAME); - - Effect_DrawAxisOfRotation(clients, numClients, origin, angles, length, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, speed); -} - -/** - * Displays the given axis of rotation as beam effect to a list of players. - * - * @param clients An array of clients to show the box to. - * @param numClients Number of players in the array. - * @param origin Origin/center of the box. - * @param angles Angles used to rotate the box. - * @param length The length in each direction. - * @param modelIndex Precached model index. - * @param haloIndex Precached model index. - * @param startFrame Initital 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. - * @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 -) { - // Create the additional corners of the box - new Float:xAxis[3], Float:yAxis[3], Float:zAxis[3]; - xAxis[0] = length[0]; - yAxis[1] = length[1]; - zAxis[2] = length[2]; - - // Rotate all edges - Math_RotateVector(xAxis, angles, xAxis); - Math_RotateVector(yAxis, angles, yAxis); - Math_RotateVector(zAxis, angles, zAxis); - - // Apply world offset (after rotation) - AddVectors(origin, xAxis, xAxis); - AddVectors(origin, yAxis, yAxis); - AddVectors(origin, zAxis, zAxis); - - // Draw all - TE_SetupBeamPoints(origin, xAxis, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, {255, 0, 0, 255}, speed); - TE_Send(clients, numClients); - - TE_SetupBeamPoints(origin, yAxis, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, {0, 255, 0, 255}, speed); - TE_Send(clients, numClients); - - TE_SetupBeamPoints(origin, zAxis, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, {0, 0, 255, 255}, speed); - TE_Send(clients, numClients); -} - - -/** - * Creates an env_sprite. - * - * @param origin Origin of the Sprite. - * @param modelIndex Precached model index. - * @param color Color array (r, g, b, a). - * @param scale Scale (Note: many materials ignore a lower value than 0.25). - * @param targetName Targetname of the sprite. - * @param parent Entity Index of this sprite's parent in the movement hierarchy. - * @param renderMode Render mode (use the enum). - * @param renderFx Render fx (use the enum). - * @param glowProxySize Radius size of the glow when to be rendered, if inside a geometry. Ex: a block 2x2x2 units big, if the glowProxySize is between 0.0 and 2.0 the sprite will not be rendered, even if the actual size of the sprite is bigger, everything above 2.0 will render the sprite. Using an abnormal high value will render Sprites trough walls. - * @param frameRate Sprite frame rate. - * @param hdrColorScale Float value to multiply sprite color by when running with HDR. - * @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 -) { - new entity = Entity_Create("env_sprite"); - - if (entity == INVALID_ENT_REFERENCE) { - return INVALID_ENT_REFERENCE; - } - - DispatchKeyValue (entity, "disablereceiveshadows", (receiveShadows) ? "0" : "1"); - DispatchKeyValueFloat (entity, "framerate", framerate); - DispatchKeyValueFloat (entity, "GlowProxySize", glowProxySize); - DispatchKeyValue (entity, "spawnflags", "1"); - DispatchKeyValueFloat (entity, "HDRColorScale", hdrColorScale); - DispatchKeyValue (entity, "maxdxlevel", "0"); - DispatchKeyValue (entity, "mindxlevel", "0"); - DispatchKeyValueFloat (entity, "scale", scale); - - DispatchSpawn(entity); - - SetEntityRenderMode(entity, renderMode); - SetEntityRenderColor(entity, color[0], color[1], color[2], color[3]); - SetEntityRenderFx(entity, renderFx); - - Entity_SetName(entity, targetName); - Entity_SetModelIndex(entity, modelIndex); - Entity_SetAbsOrigin(entity, origin); - - if (parent != -1) { - Entity_SetParent(entity, parent); - } - - return entity; -} diff --git a/scripting/1.10/include/smlib/entities.inc b/scripting/1.10/include/smlib/entities.inc deleted file mode 100644 index d90f7a4..0000000 --- a/scripting/1.10/include/smlib/entities.inc +++ /dev/null @@ -1,2152 +0,0 @@ -#if defined _smlib_entities_included - #endinput -#endif -#define _smlib_entities_included - -#include -#include -#include - -/** - * Macro for iterating trough all children (entities it is parent of) of an entity. - * - * @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)) - -/* - * Checks if an entity is valid and exists. - * - * @param entity Entity Index. - * @return True if the entity is valid, false otherwise. - */ -stock Entity_IsValid(entity) -{ - return IsValidEntity(entity); -} - -/** - * Finds an entity by its name. - * You can optionally specify the classname to search for. - * Note: If the classname is specified it uses The Sourcemod native - * function FindEntityByClassname() which uses the engine's - * linked entity list for finding entities. This might be - * cheaper, use this if you call this function very often. - * - * @param name Name of the entity you want so search. - * @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[]="") -{ - 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++) { - - if (!IsValidEntity(entity)) { - continue; - } - - if (Entity_NameMatches(entity, name)) { - return entity; - } - } - } - else { - new entity = INVALID_ENT_REFERENCE; - while ((entity = FindEntityByClassname(entity, className)) != INVALID_ENT_REFERENCE) { - - if (Entity_NameMatches(entity, name)) { - return entity; - } - } - } - - return INVALID_ENT_REFERENCE; -} - -/** - * Finds an entity by its HammerID. - * The newer version of Valve's Hammer editor - * sets a unique ID for each entity in a map. - * It only finds the first occurence. - * Note: If the classname is specified it uses The Sourcemod native - * function FindEntityByClassname() which uses the engine's - * linked entity list for finding entities. This might be - * cheaper, use this if you call this function very often. - * - * @param hammerId Hammer editor ID - * @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[]="") -{ - 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++) { - - if (!IsValidEntity(entity)) { - continue; - } - - if (Entity_GetHammerId(entity) == hammerId) { - return entity; - } - } - } - else { - new entity = INVALID_ENT_REFERENCE; - while ((entity = FindEntityByClassname(entity, className)) != INVALID_ENT_REFERENCE) { - - if (Entity_GetHammerId(entity) == hammerId) { - return entity; - } - } - } - - return INVALID_ENT_REFERENCE; -} - -/** - * Searches for an entity by classname. - * This is a wrapper around FindEntityByClassname - * and has been added for completion. - * - * @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. - */ - -stock Entity_FindByClassName(startEntity, const String:className[]) -{ - return FindEntityByClassname(startEntity, className); -} - -/** - * Checks if an entity (partially) matches a specific entity class. - * - * @param entity Entity Index. - * @param className Classname String. - * @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) -{ - decl String:entity_className[64]; - Entity_GetClassName(entity, entity_className, sizeof(entity_className)); - - if (partialMatch) { - return (StrContains(entity_className, className) != -1); - } - - return StrEqual(entity_className, className); -} - -/** - * Checks if an entity matches a name - * - * @param entity Entity Index. - * @param class Name String. - * @return True if the name matches, false otherwise. - */ -stock bool:Entity_NameMatches(entity, const String:name[]) -{ - decl String:entity_name[128]; - Entity_GetName(entity, entity_name, sizeof(entity_name)); - - return StrEqual(name, entity_name); -} - -/** - * Gets the Name of an entity. - * - * @param entity Entity index. - * @param buffer Return/Output buffer. - * @param size Max size of buffer. - * @return Number of non-null bytes written. - */ -stock Entity_GetName(entity, String:buffer[], size) -{ - return GetEntPropString(entity, Prop_Data, "m_iName", buffer, size); -} - -/** - * Sets the Name of an entity. - * - * @param entity Entity index. - * @param name The name you want to give. - * @return True on success, false otherwise. - */ -stock Entity_SetName(entity, const String:name[], any:...) -{ - decl String:format[128]; - VFormat(format, sizeof(format), name, 3); - - return DispatchKeyValue(entity, "targetname", format); -} - -/** - * Gets the Classname of an entity. - * This is like GetEdictClassname(), except it works for ALL - * entities, not just edicts. - * - * @param entity Entity index. - * @param buffer Return/Output buffer. - * @param size Max size of buffer. - * @return Number of non-null bytes written. - */ -stock Entity_GetClassName(entity, String:buffer[], size) -{ - return GetEntPropString(entity, Prop_Data, "m_iClassname", buffer, size); -} - -/** - * Sets the Classname of an entity. - * - * @param entity Entity index. - * @param name The name you want to give. - * @return True on success, false otherwise. - */ -stock Entity_SetClassName(entity, const String:className[]) -{ - return DispatchKeyValue(entity, "classname", className); -} - -/** - * Gets the Target name of an other entity - * - * @param entity Entity index. - * @param buffer Return/Output buffer. - * @param size Max size of buffer. - * @return Number of non-null bytes written. - */ -stock Entity_GetTargetName(entity, String:buffer[], size) -{ - return GetEntPropString(entity, Prop_Data, "m_target", buffer, size); -} - -/** - * Sets the Target name of an other Entity - * - * @param entity Entity index. - * @param name The target name you want to set - * @return True on success, false otherwise. - */ -stock Entity_SetTargetName(entity, const String:name[], any:...) -{ - decl String:format[128]; - VFormat(format, sizeof(format), name, 3); - - return DispatchKeyValue(entity, "target", format); -} - -/** - * Gets the Global Name of an entity. - * - * @param entity Entity index. - * @param buffer Return/Output buffer. - * @param size Max size of buffer. - * @return Number of non-null bytes written. - */ -stock Entity_GetGlobalName(entity, String:buffer[], size) -{ - return GetEntPropString(entity, Prop_Data, "m_iGlobalname", buffer, size); -} - -/** - * Sets the Global Name of an entity. - * - * @param entity Entity index. - * @param name The global name you want to set. - * @return True on success, false otherwise. - */ -stock Entity_SetGlobalName(entity, const String:name[], any:...) -{ - decl String:format[128]; - VFormat(format, sizeof(format), name, 3); - - return DispatchKeyValue(entity, "globalname", format); -} - -/** - * Gets the Parent name of an entity. - * - * @param entity Entity index. - * @param buffer Return/Output buffer. - * @param size Max size of buffer. - * @return Number of non-null bytes written. - */ -stock Entity_GetParentName(entity, String:buffer[], size) -{ - return GetEntPropString(entity, Prop_Data, "m_iParent", buffer, size); -} - -/** - * Sets the Parent name of an entity. - * - * @param entity Entity index. - * @param name The parent name you want to set. - * @return True on success, false otherwise. - */ -stock Entity_SetParentName(entity, const String:name[], any:...) -{ - decl String:format[128]; - VFormat(format, sizeof(format), name, 3); - - return DispatchKeyValue(entity, "parentname", format); -} - -/** - * Gets the Hammer-ID of an entity. - * The Hammer Editor gives every entity a unique ID. - * Note: Old maps don't have Hammer-ID's set for entities - * - * @param entity Entity index. - * @return Hammer ID. - */ -stock Entity_GetHammerId(entity) -{ - return GetEntProp(entity, Prop_Data, "m_iHammerID"); -} - -/** - * Gets the radius (m_flRadius) of an entity. - * - * @param entity Entity index. - * @return Radius - */ -stock Float:Entity_GetRadius(entity) -{ - return GetEntPropFloat(entity, Prop_Data, "m_flRadius"); -} - -/** - * Sets the radius (m_flRadius) of an entity. - * - * @param entity Entity index. - * @param radius Radius value - * @noreturn - */ -stock Entity_SetRadius(entity, Float:radius) -{ - SetEntPropFloat(entity, Prop_Data, "m_flRadius", radius); -} - -/** - * Gets the Mins of an entity. - * - * @param entity Entity index. - * @param vec Vector. - * @noreturn - */ -stock Entity_GetMinSize(entity, Float:vec[3]) -{ - GetEntPropVector(entity, Prop_Send, "m_vecMins", vec); -} - -/** - * Sets the Mins of an entity. - * - * @param entity Entity index. - * @param vec Vector. - * @noreturn - */ -stock Entity_SetMinSize(entity, const Float:vecMins[3]) -{ - SetEntPropVector(entity, Prop_Send, "m_vecMins", vecMins); -} - -/** - * Gets the Mins of an entity. - * This functions isn't safe to use, use Entity_SetMinMaxSize() instead. - * - * @param entity Entity index - * @param vec return vector. - * @noreturn - */ -stock Entity_GetMaxSize(entity, Float:vec[3]) -{ - GetEntPropVector(entity, Prop_Send, "m_vecMaxs", vec); -} - -/** - * Sets the Maxs of an entity. - * This functions isn't safe to use, use Entity_SetMinMaxSize() instead. - * - * @param entity Entity index. - * @param vec Vector. - * @noreturn - */ -stock Entity_SetMaxSize(entity, const Float:vecMaxs[3]) -{ - SetEntPropVector(entity, Prop_Send, "m_vecMaxs", vecMaxs); -} - -/** - * Sets the Min and Max Size of an entity. - * Code is taken from HL2SDK and rewritten for Sourcemod. - * - * @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]) -{ - // Taken from hl2sdk-ob-valve\game\server\util.cpp SetMinMaxSize() - // Todo: Replace this by a SDK call - for (new 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]; - Entity_GetMinSize(entity, m_vecMins); - Entity_GetMaxSize(entity, m_vecMaxs); - - if (Math_VectorsEqual(m_vecMins, vecMins) && Math_VectorsEqual(m_vecMaxs, vecMaxs)) { - return; - } - - Entity_SetMinSize(entity, vecMins); - Entity_SetMaxSize(entity, vecMaxs); - - decl Float:vecSize[3]; - SubtractVectors(vecMaxs, vecMins, vecSize); - Entity_SetRadius(entity, GetVectorLength(vecSize) * 0.5); - - Entity_MarkSurrBoundsDirty(entity); -} - -/* - * Spawn Flags - * Many entities define their specific spawnflags, check the HL2SDK. - */ - -/* - * Phys prop spawnflags - * Taken from hl2sdk-ob-valve\game\shared\props_shared.h - */ -#define SF_PHYSPROP_START_ASLEEP 0x000001 -#define SF_PHYSPROP_DONT_TAKE_PHYSICS_DAMAGE 0x000002 // this prop can't be damaged by physics collisions -#define SF_PHYSPROP_DEBRIS 0x000004 -#define SF_PHYSPROP_MOTIONDISABLED 0x000008 // motion disabled at startup (flag only valid in spawn - motion can be enabled via input) -#define SF_PHYSPROP_TOUCH 0x000010 // can be 'crashed through' by running player (plate glass) -#define SF_PHYSPROP_PRESSURE 0x000020 // can be broken by a player standing on it -#define SF_PHYSPROP_ENABLE_ON_PHYSCANNON 0x000040 // enable motion only if the player grabs it with the physcannon -#define SF_PHYSPROP_NO_ROTORWASH_PUSH 0x000080 // The rotorwash doesn't push these -#define SF_PHYSPROP_ENABLE_PICKUP_OUTPUT 0x000100 // If set, allow the player to +USE this for the purposes of generating an output -#define SF_PHYSPROP_PREVENT_PICKUP 0x000200 // If set, prevent +USE/Physcannon pickup of this prop -#define SF_PHYSPROP_PREVENT_PLAYER_TOUCH_ENABLE 0x000400 // If set, the player will not cause the object to enable its motion when bumped into -#define SF_PHYSPROP_HAS_ATTACHED_RAGDOLLS 0x000800 // Need to remove attached ragdolls on enable motion/etc -#define SF_PHYSPROP_FORCE_TOUCH_TRIGGERS 0x001000 // Override normal debris behavior and respond to triggers anyway -#define SF_PHYSPROP_FORCE_SERVER_SIDE 0x002000 // Force multiplayer physics object to be serverside -#define SF_PHYSPROP_RADIUS_PICKUP 0x004000 // For Xbox, makes small objects easier to pick up by allowing them to be found -#define SF_PHYSPROP_ALWAYS_PICK_UP 0x100000 // Physcannon can always pick this up, no matter what mass or constraints may apply. -#define SF_PHYSPROP_NO_COLLISIONS 0x200000 // Don't enable collisions on spawn -#define SF_PHYSPROP_IS_GIB 0x400000 // Limit # of active gibs - -/* - * Physbox Spawnflags. Start at 0x01000 to avoid collision with CBreakable's - * Taken from hl2sdk-ob-valve\game\server\physobj.h - */ -#define SF_PHYSBOX_ASLEEP 0x01000 -#define SF_PHYSBOX_IGNOREUSE 0x02000 -#define SF_PHYSBOX_DEBRIS 0x04000 -#define SF_PHYSBOX_MOTIONDISABLED 0x08000 -#define SF_PHYSBOX_USEPREFERRED 0x10000 -#define SF_PHYSBOX_ENABLE_ON_PHYSCANNON 0x20000 -#define SF_PHYSBOX_NO_ROTORWASH_PUSH 0x40000 // The rotorwash doesn't push these -#define SF_PHYSBOX_ENABLE_PICKUP_OUTPUT 0x80000 -#define SF_PHYSBOX_ALWAYS_PICK_UP 0x100000 // Physcannon can always pick this up, no matter what mass or constraints may apply. -#define SF_PHYSBOX_NEVER_PICK_UP 0x200000 // Physcannon will never be able to pick this up. -#define SF_PHYSBOX_NEVER_PUNT 0x400000 // Physcannon will never be able to punt this object. -#define SF_PHYSBOX_PREVENT_PLAYER_TOUCH_ENABLE 0x800000 // If set, the player will not cause the object to enable its motion when bumped into - -/* - * Spawnflags for func breakable - * Taken from hl2sdk-ob-valve\game\server\func_break.h - */ -#define SF_BREAK_TRIGGER_ONLY 0x0001 // may only be broken by trigger -#define SF_BREAK_TOUCH 0x0002 // can be 'crashed through' by running player (plate glass) -#define SF_BREAK_PRESSURE 0x0004 // can be broken by a player standing on it -#define SF_BREAK_PHYSICS_BREAK_IMMEDIATELY 0x0200 // the first physics collision this breakable has will immediately break it -#define SF_BREAK_DONT_TAKE_PHYSICS_DAMAGE 0x0400 // this breakable doesn't take damage from physics collisions -#define SF_BREAK_NO_BULLET_PENETRATION 0x0800 // don't allow bullets to penetrate - -/* - * Spawnflags for func_pushable (it's also func_breakable, so don't collide with those flags) - * Taken from hl2sdk-ob-valve\game\server\func_break.h - */ -#define SF_PUSH_BREAKABLE 0x0080 -#define SF_PUSH_NO_USE 0x0100 // player cannot +use pickup this ent - -/** - * Gets the Spawnflags of an entity. - * - * @param entity Entity index. - * @return Spawnflags value - */ -stock Entity_GetSpawnFlags(entity) -{ - return GetEntProp(entity, Prop_Data, "m_spawnflags"); -} - -/** - * Sets the Spawnflags of an entity. - * - * @param entity Entity index. - * @param flags Flags value - * @noreturn - */ -stock Entity_SetSpawnFlags(entity, flags) -{ - SetEntProp(entity, Prop_Data, "m_spawnflags", flags); -} - -/** - * Adds Spawnflags to an entity. - * - * @param entity Entity index. - * @param flags Flags value - * @noreturn - */ -stock Entity_AddSpawnFlags(entity, flags) -{ - new spawnFlags = Entity_GetSpawnFlags(entity); - spawnFlags |= flags; - Entity_SetSpawnFlags(entity, spawnFlags); -} - -/** - * Removes Spawnflags from an entity. - * - * @param entity Entity index. - * @param flags Flags value - * @noreturn - */ -stock Entity_RemoveSpawnFlags(entity, flags) -{ - new spawnFlags = Entity_GetSpawnFlags(entity); - spawnFlags &= ~flags; - Entity_SetSpawnFlags(entity, spawnFlags); -} - -/** - * Clears all Spawnflags of an entity. - * - * @param entity Entity index. - * @noreturn - */ -stock Entity_ClearSpawnFlags(entity) -{ - Entity_SetSpawnFlags(entity, 0); -} - -/** - * Returns whether the entity has specific Spawnflags. - * - * @param entity Entity index. - * @param flags Flags value. - * @return True if the entity has the spawnflags set, false otherwise. - */ -stock bool:Entity_HasSpawnFlags(entity, flags) -{ - return bool:(Entity_GetSpawnFlags(entity) & flags); -} - -/* - * Entity flags, CBaseEntity::m_iEFlags - * Taken from: hl2sdk-ob-valve\game\shared\shareddefs.h - */ -enum Entity_Flags -{ - EFL_KILLME = (1<<0), // This entity is marked for death -- This allows the game to actually delete ents at a safe time - EFL_DORMANT = (1<<1), // Entity is dormant, no updates to client - EFL_NOCLIP_ACTIVE = (1<<2), // Lets us know when the noclip command is active. - EFL_SETTING_UP_BONES = (1<<3), // Set while a model is setting up its bones. - EFL_KEEP_ON_RECREATE_ENTITIES = (1<<4), // This is a special entity that should not be deleted when we restart entities only - - EFL_HAS_PLAYER_CHILD= (1<<4), // One of the child entities is a player. - - EFL_DIRTY_SHADOWUPDATE = (1<<5), // Client only- need shadow manager to update the shadow... - EFL_NOTIFY = (1<<6), // Another entity is watching events on this entity (used by teleport) - - // The default behavior in ShouldTransmit is to not send an entity if it doesn't - // have a model. Certain entities want to be sent anyway because all the drawing logic - // is in the client DLL. They can set this flag and the engine will transmit them even - // if they don't have a model. - EFL_FORCE_CHECK_TRANSMIT = (1<<7), - - EFL_BOT_FROZEN = (1<<8), // This is set on bots that are frozen. - EFL_SERVER_ONLY = (1<<9), // Non-networked entity. - EFL_NO_AUTO_EDICT_ATTACH = (1<<10), // Don't attach the edict; we're doing it explicitly - - // Some dirty bits with respect to abs computations - EFL_DIRTY_ABSTRANSFORM = (1<<11), - EFL_DIRTY_ABSVELOCITY = (1<<12), - EFL_DIRTY_ABSANGVELOCITY = (1<<13), - EFL_DIRTY_SURR_COLLISION_BOUNDS = (1<<14), - EFL_DIRTY_SPATIAL_PARTITION = (1<<15), -// UNUSED = (1<<16), - - EFL_IN_SKYBOX = (1<<17), // This is set if the entity detects that it's in the skybox. - // This forces it to pass the "in PVS" for transmission. - EFL_USE_PARTITION_WHEN_NOT_SOL = (1<<18), // Entities with this flag set show up in the partition even when not solid - EFL_TOUCHING_FLUID = (1<<19), // Used to determine if an entity is floating - - // FIXME: Not really sure where I should add this... - EFL_IS_BEING_LIFTED_BY_BARNACLE = (1<<20), - EFL_NO_ROTORWASH_PUSH = (1<<21), // I shouldn't be pushed by the rotorwash - EFL_NO_THINK_FUNCTION = (1<<22), - EFL_NO_GAME_PHYSICS_SIMULATION = (1<<23), - - EFL_CHECK_UNTOUCH = (1<<24), - EFL_DONTBLOCKLOS = (1<<25), // I shouldn't block NPC line-of-sight - EFL_DONTWALKON = (1<<26), // NPC;s should not walk on this entity - EFL_NO_DISSOLVE = (1<<27), // These guys shouldn't dissolve - EFL_NO_MEGAPHYSCANNON_RAGDOLL = (1<<28), // Mega physcannon can't ragdoll these guys. - EFL_NO_WATER_VELOCITY_CHANGE = (1<<29), // Don't adjust this entity's velocity when transitioning into water - EFL_NO_PHYSCANNON_INTERACTION = (1<<30), // Physcannon can't pick these up or punt them - EFL_NO_DAMAGE_FORCES = (1<<31), // Doesn't accept forces from physics damage -}; - -/** - * Gets the Entity flags (m_iEFlags) of an entity. - * - * @param entity Entity index. - * @return Entity flags value - */ -stock Entity_Flags:Entity_GetEFlags(entity) -{ - return Entity_Flags:GetEntProp(entity, Prop_Data, "m_iEFlags"); -} - -/** - * Sets the entity's Entity flags (m_iEFlags). - * - * @param entity Entity index. - * @param flags Flags value - * @noreturn - */ -stock Entity_SetEFlags(entity, Entity_Flags:flags) -{ - SetEntProp(entity, Prop_Data, "m_iEFlags", flags); -} - -/** - * Adds Entity flags (m_iEFlags) to an entity. - * - * @param entity Entity index. - * @param flags Flags value - * @noreturn - */ -stock Entity_AddEFlags(entity, Entity_Flags:flags) -{ - new Entity_Flags:setFlags = Entity_GetEFlags(entity); - setFlags |= flags; - Entity_SetEFlags(entity, setFlags); -} - -/** - * Removes Entity flags (m_iEFlags) from an entity. - * - * @param entity Entity index. - * @param flags Flags value - * @noreturn - */ -stock Entity_RemoveEFlags(entity, Entity_Flags:flags) -{ - new Entity_Flags:setFlags = Entity_GetEFlags(entity); - setFlags &= ~flags; - Entity_SetEFlags(entity, setFlags); -} - -/** - * Checks if the entity has specific Entity flags (m_iEFlags) set. - * - * @param entity Entity index. - * @param flags Flags value - * @return True if the flags are set, false otherwise. - */ -stock bool:Entity_HasEFlags(entity, Entity_Flags:flags) -{ - new Entity_Flags:currentEFlags = Entity_GetEFlags(entity); - - return bool:(currentEFlags & flags); -} - -/** - * Marks the surrounding bounds of an entity as outdated. - * You normally call this when a collision setting has changed. - * - * @param entity Entity index. - * @noreturn - */ -stock Entity_MarkSurrBoundsDirty(entity) -{ - Entity_AddEFlags(entity, EFL_DIRTY_SURR_COLLISION_BOUNDS); -} - -/* - * CBaseEntity::m_fFlags Functions - * Use the FL_ Defines (FL_ONGROUND, ...) or - * special entity specific flags. - * Note: The flag FL_AIMTARGET probably doesn't work as - * we have current no way of adding/removing it to the AimTarget List. - */ - -/** - * Gets the Flags of an entity. - * - * @param entity Entity Index. - * @return Entity Flags. - */ -stock Entity_GetFlags(entity) -{ - return GetEntProp(entity, Prop_Data, "m_fFlags"); -} - -/** - * Sets the Flags of an entity. - * - * @param entity Entity index. - * @param flags New Flags value - * @noreturn - */ -stock Entity_SetFlags(entity, flags) -{ - SetEntProp(entity, Prop_Data, "m_fFlags", flags); -} - -/** - * Adds Flags to the entity - * - * @param entity Entity index. - * @param flags Flags to add - * @noreturn - */ -stock Entity_AddFlags(entity, flags) -{ - new setFlags = Entity_GetFlags(entity); - setFlags |= flags; - Entity_SetFlags(entity, flags); -} - -/** - * Removes flags from the entity - * - * @param entity Entity index. - * @param flags Flags to remove - * @noreturn - */ -stock Entity_RemoveFlags(entity, flags) -{ - new setFlags = Entity_GetFlags(entity); - setFlags &= ~flags; - Entity_SetFlags(entity, setFlags); -} - -/** - * Toggles the specified flag on the entity. - * Adds the flag to the entity if it doesn't exists - * or removes it otherwise. - * - * @param entity Entity index. - * @param flags Flag to Toggle - * @noreturn - */ -stock Entity_ToggleFlag(entity, flag) -{ - new setFlag = Entity_GetFlags(entity); - setFlag ^= flag; - Entity_SetFlags(entity, setFlag); -} - -/** - * Removes all flags from the entity - * - * @param entity Entity index. - * @noreturn - */ -stock Entity_ClearFlags(entity) -{ - Entity_SetFlags(entity, 0); -} - -/* edict->solid values - * NOTE: Some movetypes will cause collisions independent of SOLID_NOT/SOLID_TRIGGER when the entity moves - * SOLID only effects OTHER entities colliding with this one when they move - UGH! - * - * Solid type basically describes how the bounding volume of the object is represented - * NOTE: These numerical values are used in the FGD by the prop code (see prop_dynamic) - * Taken from: hl2sdk-ob-valve\public\const.h - */ - -enum SolidFlags_t -{ - FSOLID_CUSTOMRAYTEST = 0x0001, // Ignore solid type + always call into the entity for ray tests - FSOLID_CUSTOMBOXTEST = 0x0002, // Ignore solid type + always call into the entity for swept box tests - FSOLID_NOT_SOLID = 0x0004, // Are we currently not solid? - FSOLID_TRIGGER = 0x0008, // This is something may be collideable but fires touch functions - // even when it's not collideable (when the FSOLID_NOT_SOLID flag is set) - FSOLID_NOT_STANDABLE = 0x0010, // You can't stand on this - FSOLID_VOLUME_CONTENTS = 0x0020, // Contains volumetric contents (like water) - FSOLID_FORCE_WORLD_ALIGNED = 0x0040, // Forces the collision rep to be world-aligned even if it's SOLID_BSP or SOLID_VPHYSICS - FSOLID_USE_TRIGGER_BOUNDS = 0x0080, // Uses a special trigger bounds separate from the normal OBB - FSOLID_ROOT_PARENT_ALIGNED = 0x0100, // Collisions are defined in root parent's local coordinate space - FSOLID_TRIGGER_TOUCH_DEBRIS = 0x0200, // This trigger will touch debris objects - - FSOLID_MAX_BITS = 10 -}; - -/** - * Gets the solid flags of the entity - * - * @param entity Entity index. - * @return Solid Flags. - */ -stock SolidFlags_t:Entity_GetSolidFlags(entity) -{ - return SolidFlags_t:GetEntProp(entity, Prop_Data, "m_usSolidFlags", 2); -} - -/** - * Sets the solid flags of the entity - * - * @param entity Entity index. - * @param flags Solid Flags. - * @noreturn - */ -stock Entity_SetSolidFlags(entity, SolidFlags_t:flags) -{ - new SolidFlags_t:oldFlags = Entity_GetSolidFlags(entity); - flags = flags & SolidFlags_t:0xFFFF; - - if (oldFlags == flags) { - return; - } - - SetEntProp(entity, Prop_Data, "m_usSolidFlags", flags, 2); - - // These two flags, if changed, can produce different surrounding bounds - if ((oldFlags & (FSOLID_FORCE_WORLD_ALIGNED | FSOLID_USE_TRIGGER_BOUNDS)) != - (flags & (FSOLID_FORCE_WORLD_ALIGNED | FSOLID_USE_TRIGGER_BOUNDS))) - { - Entity_MarkSurrBoundsDirty(entity); - } -} - -/** - * Adds solid flags to the entity - * - * @param entity Entity index. - * @param flags Solid Flags. - * @noreturn - */ -stock Entity_AddSolidFlags(entity, SolidFlags_t:flags) -{ - new SolidFlags_t:newFlags = Entity_GetSolidFlags(entity); - newFlags |= flags; - Entity_SetSolidFlags(entity, newFlags); -} - -/** - * Removes solid flags from the entity. - * - * @param entity Entity index. - * @param flags Solid Flags. - * @noreturn - */ -stock Entity_RemoveSolidFlags(entity, SolidFlags_t:flags) -{ - new SolidFlags_t:newFlags = Entity_GetSolidFlags(entity); - newFlags &= ~flags; - Entity_SetSolidFlags(entity, newFlags); -} - -/** - * Removes all solid flags from the entity. - * - * @param entity Entity index. - * @noreturn - */ -stock Entity_ClearSolidFlags(entity) -{ - Entity_SetSolidFlags(entity, SolidFlags_t:0); -} - -/** - * Checks whether certain solid flags are set on the entity. - * - * @param entity Entity index. - * @param flags Solid Flags. - * @return True if the specified flags are set, false otherwise. - */ -stock bool:Entity_SolidFlagsSet(entity, SolidFlags_t:flagMask) -{ - return bool:(Entity_GetSolidFlags(entity) & flagMask); -} - -enum SolidType_t -{ - SOLID_NONE = 0, // no solid model - SOLID_BSP = 1, // a BSP tree - SOLID_BBOX = 2, // an AABB - SOLID_OBB = 3, // an OBB (not implemented yet) - SOLID_OBB_YAW = 4, // an OBB, constrained so that it can only yaw - SOLID_CUSTOM = 5, // Always call into the entity for tests - SOLID_VPHYSICS = 6, // solid vphysics object, get vcollide from the model and collide with that - SOLID_LAST, -}; - -/** - * Gets the solidity type of the entity - * - * @param entity Entity index. - * @return Solid Type - */ -stock SolidType_t:Entity_GetSolidType(entity) -{ - return SolidType_t:GetEntProp(entity, Prop_Data, "m_nSolidType", 1); -} - -/** - * Sets the solidity type of the entity - * - * @param entity Entity index. - * @param Solid Type value. - * @noreturn - */ -stock Entity_SetSolidType(entity, SolidType_t:value) -{ - SetEntProp(entity, Prop_Send, "m_nSolidType", value, 1); - Entity_MarkSurrBoundsDirty(entity); -} - -/** - * Checks whether the entity is solid or not. - * - * @param entity Entity index. - * @return True if the entity is solid, false otherwise. - */ -stock bool:Entity_IsSolid(entity) -{ - return (Entity_GetSolidType(entity) != SOLID_NONE && - !Entity_SolidFlagsSet(entity, FSOLID_NOT_SOLID)); -} - -/** - * Retrieves the model path of a given entity. - * Returns "*num" for Brush entities. - * - * @param entity entity reference or index - * @param model buffer String for the model - * @param size max size of buffer string - * @return Number of non-null bytes written. - */ -stock Entity_GetModel(entity, String:buffer[], size) -{ - return GetEntPropString(entity, Prop_Data, "m_ModelName", buffer, size); -} - -/** - * Sets the model to a given entity. - * Be sure it has been precached. - * This is an alias for SetEntityModel() - * - * @param entity Entity index - * @param model Model name - * @noreturn - */ -stock Entity_SetModel(entity, const String:model[]) -{ - SetEntityModel(entity, model); -} - -/** - * Gets the entity's model index, if it has one set. - * - * @param entity Entity index. - * @return The Entity's model index - */ -stock Entity_GetModelIndex(entity) -{ - return GetEntProp(entity, Prop_Data, "m_nModelIndex", 2); -} - -/** - * Sets the entity's model index (must be precached) - * - * @param entity Entity index. - * @param index Model Index. - * @noreturn - */ -stock Entity_SetModelIndex(entity, index) -{ - SetEntProp(entity, Prop_Data, "m_nModelIndex", index, 2); -} - -/** -* Sets the entity's maxspeed to the given value (in units per second) -* -* @param entity Entity index -* @param maxspeed the maximum speed the entity can move -* @noreturn -*/ -stock Entity_SetMaxSpeed(entity, Float:value) -{ - SetEntPropFloat(entity, Prop_Data, "m_flMaxspeed", value); -} - -/* - * Collision groups - * Taken from hl2sdk-ob-valve/public/const.h - */ -enum Collision_Group_t -{ - COLLISION_GROUP_NONE = 0, - COLLISION_GROUP_DEBRIS, // Collides with nothing but world and static stuff - COLLISION_GROUP_DEBRIS_TRIGGER, // Same as debris, but hits triggers - COLLISION_GROUP_INTERACTIVE_DEB, // Collides with everything except other interactive debris or debris - COLLISION_GROUP_INTERACTIVE, // Collides with everything except interactive debris or debris - COLLISION_GROUP_PLAYER, - COLLISION_GROUP_BREAKABLE_GLASS, - COLLISION_GROUP_VEHICLE, - COLLISION_GROUP_PLAYER_MOVEMENT, // For HL2, same as Collision_Group_Player, for - // TF2, this filters out other players and CBaseObjects - COLLISION_GROUP_NPC, // Generic NPC group - COLLISION_GROUP_IN_VEHICLE, // for any entity inside a vehicle - COLLISION_GROUP_WEAPON, // for any weapons that need collision detection - COLLISION_GROUP_VEHICLE_CLIP, // vehicle clip brush to restrict vehicle movement - COLLISION_GROUP_PROJECTILE, // Projectiles! - COLLISION_GROUP_DOOR_BLOCKER, // Blocks entities not permitted to get near moving doors - COLLISION_GROUP_PASSABLE_DOOR, // Doors that the player shouldn't collide with - COLLISION_GROUP_DISSOLVING, // Things that are dissolving are in this group - COLLISION_GROUP_PUSHAWAY, // Nonsolid on client and server, pushaway in player code - - COLLISION_GROUP_NPC_ACTOR, // Used so NPCs in scripts ignore the player. - COLLISION_GROUP_NPC_SCRIPTED // USed for NPCs in scripts that should not collide with each other -}; - -/** - * Gets the collision group of an entity. - * - * @param entity entity index - * @return Entity collision group. - */ -stock Collision_Group_t:Entity_GetCollisionGroup(entity) -{ - return Collision_Group_t:GetEntProp(entity, Prop_Data, "m_CollisionGroup"); -} - -/** - * Sets the collision group of an entity. - * - * @param entity entity index - * @param value the new collision group. - * @noreturn - */ -stock Entity_SetCollisionGroup(entity, Collision_Group_t:value) -{ - SetEntProp(entity, Prop_Data, "m_CollisionGroup", value); -} - -/** - * Functions for getting / setting the origin (position) of an entity. - * Go to http://developer.valvesoftware.com/wiki/Origin - * if you want to learn more about origins - */ - -/** - * Gets the Absolute Origin (position) of an entity. - * - * @param entity Entity index. - * @param vec 3 dimensional vector array. - * @noreturn - */ -stock Entity_GetAbsOrigin(entity, Float:vec[3]) -{ - GetEntPropVector(entity, Prop_Send, "m_vecOrigin", vec); -} - -/** - * Sets the Absolute Origin (position) of an entity. - * - * @param entity Entity index. - * @param vec 3 dimensional vector array. - * @noreturn - */ -stock Entity_SetAbsOrigin(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() - TeleportEntity(entity, vec, NULL_VECTOR, NULL_VECTOR); -} - -/** - * Functions for getting / setting the angles (rotation) of an entity. - * http://developer.valvesoftware.com/wiki/Angles - * if you want to learn more about angles - */ - -/** - * Gets the Angles of an entity - * - * @param entity Entity index. - * @param vec 3 dimensional vector array. - * @noreturn - */ -stock Entity_GetAbsAngles(entity, Float:vec[3]) -{ - GetEntPropVector(entity, Prop_Data, "m_angAbsRotation", vec); -} - -/** - * Sets the Angles of an entity - * - * @param entity Entity index. - * @param vec 3 dimensional vector array. - * @noreturn - */ -stock Entity_SetAbsAngles(entity, const Float:vec[3]) -{ - // We use TeleportEntity to set the angles more safely - // Todo: Replace this with a call to CBaseEntity::SetLocalAngles() - TeleportEntity(entity, NULL_VECTOR, vec, NULL_VECTOR); -} - -/** - * Functions for getting / setting the velocity of an entity. - * Go to http://developer.valvesoftware.com/wiki/Velocity - * if you want to learn more about the different kind of velocities. - */ - -/** - * Gets the Local velocity of an entity. - * The local velocity is the velocity generated by the entity. - * - * @param entity Entity index. - * @param vel An 3 dim array - * @noreturn - */ -stock Entity_GetLocalVelocity(entity, Float:vec[3]) -{ - GetEntPropVector(entity, Prop_Data, "m_vecVelocity", vec); -} - -/** - * Sets the Local velocity of an entity. - * The local velocity is the velocity generated by the entity. - * Only use this if you know what you are doing, - * the entity can overwrite this value on next frame. - * - * @param entity Entity index. - * @param vel An 3 dim array - * @noreturn - */ -stock Entity_SetLocalVelocity(entity, const Float:vec[3]) -{ - SetEntPropVector(entity, Prop_Data, "m_vecVelocity", vec); -} - -/** - * Gets the Base velocity of an entity. - * The base velocity is the velocity applied - * to the entity from other sources . - * - * @param entity Entity index. - * @param vel An 3 dim array - * @noreturn - */ -stock Entity_GetBaseVelocity(entity, Float:vec[3]) -{ - GetEntPropVector(entity, Prop_Data, "m_vecBaseVelocity", vec); -} - -/** - * Sets the Base velocity of an entity. - * The base velocity is the velocity applied - * to the entity from other sources . - * - * @param entity Entity index. - * @param vel An 3 dim array - * @noreturn - */ -stock Entity_SetBaseVelocity(entity, const Float:vec[3]) -{ - SetEntPropVector(entity, Prop_Data, "m_vecBaseVelocity", vec); -} - -/** - * Gets the Absolute velocity of an entity. - * The absolute velocity is the sum of the local - * and base velocities. It's the actual value used to move. - * - * @param entity Entity index. - * @param vel An 3 dim array - * @noreturn - */ -stock Entity_GetAbsVelocity(entity, Float:vec[3]) -{ - GetEntPropVector(entity, Prop_Data, "m_vecAbsVelocity", vec); -} - -/** - * Sets the Absolute velocity of an entity. - * The absolute velocity is the sum of the local - * and base velocities. It's the actual value used to move. - * - * @param entity Entity index. - * @param vel An 3 dim array - * @noreturn - */ -stock Entity_SetAbsVelocity(entity, const Float:vec[3]) -{ - // We use TeleportEntity to set the velocity more safely - // Todo: Replace this with a call to CBaseEntity::SetAbsVelocity() - TeleportEntity(entity, NULL_VECTOR, NULL_VECTOR, vec); -} - -/** - * Returns true if the entity is locked. - * - * @param entity Entity index. - * @return True if locked otherwise false. - */ -stock bool:Entity_IsLocked(entity) -{ - return bool:GetEntProp(entity, Prop_Data, "m_bLocked", 1); -} - -/** - * Locks an entity. - * - * @param entity Entity index. - * @noreturn - */ -stock Entity_Lock(entity) -{ - SetEntProp(entity, Prop_Data, "m_bLocked", 1, 1); -} -/** - * Unlocks an entity. - * - * @param entity Entity index. - * @noreturn - */ -stock Entity_UnLock(entity) -{ - SetEntProp(entity, Prop_Data, "m_bLocked", 0, 1); -} - -/** - * Gets the health of an entity. - * - * @param entity entity index. - * @return current health points - */ -stock Entity_GetHealth(entity) -{ - return GetEntProp(entity, Prop_Data, "m_iHealth"); -} - -/** - * Sets the health of an entity. - * - * @param entity entity index. - * @param value health to set (anything above 511 will overload) - * @noreturn - */ -stock Entity_SetHealth(entity, value, ignoreMax=false, kill=true) -{ - new health = value; - - if (!ignoreMax) { - new maxHealth = Entity_GetMaxHealth(entity); - - if (health > maxHealth) { - health = maxHealth; - } - } - - if (health < 0) { - health = 0; - } - - SetEntProp(entity, Prop_Data, "m_iHealth", health); - - if (health <= 0) { - Entity_Kill(entity); - } - - return health; -} - -/** - * Add health to an entity - * - * @param entity entity index - * @param value health to add - * @return returns the new health value set - */ -stock Entity_AddHealth(entity, value, ignoreMax=false, kill=true) -{ - new health = Entity_GetHealth(entity); - - health += value; - - return Entity_SetHealth(entity, health, ignoreMax, kill); -} - -/** - * Takes health from an entity - * - * @param entity entity index - * @param value health to add - * @return returns the new health value set - */ -stock Entity_TakeHealth(entity, value, ignoreMax=false, kill=true) -{ - new health = Entity_GetHealth(entity); - - health -= value; - - return Entity_SetHealth(entity, health, ignoreMax, kill); -} - -/** - * Get the max health of an entity - * - * @param entity Entity Index - * @return Max health points - */ -stock Entity_GetMaxHealth(entity) -{ - return GetEntProp(entity, Prop_Data, "m_iMaxHealth"); -} - - -/** - * Set the max health of an entity. - * - * @param entity Entity index - * @param value Max health to set (anything above 511 will overload) - * @noreturn - */ -stock Entity_SetMaxHealth(entity, value) -{ - SetEntProp(entity, Prop_Data, "m_iMaxHealth", value); - return value; -} - -/** - * Returns the Float distance between an entity - * and a vector origin. - * - * @param entity Entity Index. - * @param target Vector Origin. - * @return Distance Float value. - */ -stock Float:Entity_GetDistanceOrigin(entity, const Float:vec[3]) -{ - new Float:entityVec[3]; - Entity_GetAbsOrigin(entity, entityVec); - - return GetVectorDistance(entityVec, vec); -} - -/** - * Returns the Float distance between two entities. - * Both entities must be valid. - * - * @param entity Entity Index. - * @param target Target Entity Index. - * @return Distance Float value. - */ -stock Float:Entity_GetDistance(entity, target) -{ - new Float:targetVec[3]; - Entity_GetAbsOrigin(target, targetVec); - - return Entity_GetDistanceOrigin(entity, targetVec); -} - -/** - * Checks if the given 2 entitys are within a given range. - * - * @param entity Entity Index. - * @param target Target Entity Index. - * @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) -{ - if (Entity_GetDistance(entity, target) > distance) { - return false; - } - - return true; -} - -/** - * Enables the motion of an entity. - * - * @param entity Entity index. - * @return True on success, false otherwise - */ -stock bool:Entity_EnableMotion(entity) -{ - return AcceptEntityInput(entity, "enablemotion"); -} - -/** - * Disables the motion of an entity. - * - * @param entity Entity index. - * @return True on success, false otherwise - */ -stock bool:Entity_DisableMotion(entity) -{ - return AcceptEntityInput(entity, "disablemotion"); -} - -/** - * Freezes an entity by setting the FL_FROZEN flag. - * - * @param entity Entity index. - * @return True on success, false otherwise - */ -stock Entity_Freeze(entity) -{ - Entity_AddFlags(entity, FL_FROZEN); -} - -/** - * Unfreezes an entity by removing the FL_FROZEN flag. - * - * @param entity Entity index. - * @return True on success, false otherwise - */ -stock Entity_UnFreeze(entity) -{ - Entity_RemoveFlags(entity, FL_FROZEN); -} - - -/** - * This function points an entity to another with the targetname - * and name. Useful for allot of entities like trigger_teleport. - * If the name is not specified it will be generated automatically. - * - * @param entity Entity index. - * @param target Target entity index. - * @param Optional: target name - * @noreturn - */ -stock Entity_PointAtTarget(entity, target, const String:name[]="") -{ - decl String:targetName[128]; - Entity_GetTargetName(entity, targetName, sizeof(targetName)); - - if (name[0] == '\0') { - - if (targetName[0] == '\0') { - // Let's generate our own name - Format( - targetName, - sizeof(targetName), - "_smlib_Entity_PointAtTarget:%d", - target - ); - } - } - else { - strcopy(targetName, sizeof(targetName), name); - } - - Entity_SetTargetName(entity, targetName); - Entity_SetName(target, targetName); -} - -/** - * This function points a point_hurt entity to another damage target entity.. - * and name. Useful for allot of entities like trigger_teleport. - * If the name is not specified it will be generated automatically. - * - * @param entity Entity index. - * @param target Target entity index. - * @param Optional: target name - * @noreturn - */ -stock Entity_PointHurtAtTarget(entity, target, const String:name[]="") -{ - decl String:targetName[128]; - Entity_GetTargetName(entity, targetName, sizeof(targetName)); - - if (name[0] == '\0') { - - if (targetName[0] == '\0') { - // Let's generate our own name - Format( - targetName, - sizeof(targetName), - "_smlib_Entity_PointHurtAtTarget:%d", - target - ); - } - } - else { - strcopy(targetName, sizeof(targetName), name); - } - - DispatchKeyValue(entity, "DamageTarget", targetName); - Entity_SetName(target, targetName); -} - -/** - * Checks if an entity is a player or not. - * No checks are done if the entity is actually valid, - * the player is connected or ingame. - * - * @param entity Entity index. - * @return True if the entity is a player, false otherwise. - */ -stock bool:Entity_IsPlayer(entity) -{ - if (entity < 1 || entity > MaxClients) { - return false; - } - - return true; -} - -/** - * Creates an entity by classname. - * - * @param className Classname String. - * @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) -{ - if (ForceEdictIndex != -1 && Entity_IsValid(ForceEdictIndex)) { - return INVALID_ENT_REFERENCE; - } - - return CreateEntityByName(className, ForceEdictIndex); -} - -/** - * Kills an entity on the next frame (delayed). - * It is safe to use with entity loops. - * If the entity is is player ForcePlayerSuicide() is called. - * - * @param kenny Entity index. - * @param killChildren When true, kennys children are killed too. - * @return True on success, false otherwise. - */ -stock bool:Entity_Kill(kenny, killChildren=false) -{ - if (Entity_IsPlayer(kenny)) { - // Oh My God! They Killed Kenny!! - ForcePlayerSuicide(kenny); - return true; - } - - if(killChildren){ - return AcceptEntityInput(kenny, "KillHierarchy"); - } - else { - return AcceptEntityInput(kenny, "Kill"); - } -} - -/** - * Kills all entities with the given networked classname. - * It is safe to use with entity loops. - * If the entity is is player ForcePlayerSuicide() is called. - * - * @param className Entity Network Class to search for. - * @return Number of entities killed. - */ -stock Entity_KillAllByClassName(const String:className[]) -{ - new x = 0; - - new entity = INVALID_ENT_REFERENCE; - while ((entity = FindEntityByClassname(entity, className)) != INVALID_ENT_REFERENCE) { - AcceptEntityInput(entity, "kill"); - x++; - } - - return x; -} - -/** - * Gets the owner of an entity. - * For example the owner of a weapon entity. - * - * @param entity Entity index. - * @return Ground Entity or -1 - */ -stock Entity_GetOwner(entity) -{ - return GetEntPropEnt(entity, Prop_Data, "m_hOwnerEntity"); -} - -/** - * Sets the owner of an entity. - * For example the owner of a weapon entity. - * - * @param entity Entity index. - * @noreturn - */ -stock Entity_SetOwner(entity, newOwner) -{ - SetEntPropEnt(entity, Prop_Send, "m_hOwnerEntity", newOwner); -} - -/** - * Get's the ground entity this entity stands on. - * - * @param entity Entity index. - * @return Ground Entity or -1 - */ -stock Entity_GetGroundEntity(entity) -{ - return GetEntPropEnt(entity, Prop_Data, "m_hGroundEntity"); -} - -/* - * Damage definitions - */ - -#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. - -#endif - -/** - * Does damage to an entity. - * This is a powerful function that allows you to specify - * who the attacker is, the damage type and also what weapon - * should be displayed in the hud kill message. - * Note that for entities that fire another entity (RPG's, Crossbow's, - * you have to pass the bullet's class, not the weapon's class ! - * It hasn't been tested how expensive this function is, as it - * uses the entity point_hurt. - * If you need a cheaper function use Entity_RemoveHealth(). - * - * @param entity Entity index. - * @param damage Amount of damage. - * @param attacker Entity Index of the attacker. - * @param damageType Use the DMG_ definations. - * @param fakeClassName Classname to fake, you can set this if you - * 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[]="") -{ - static point_hurt = INVALID_ENT_REFERENCE; - - if (point_hurt == INVALID_ENT_REFERENCE || !IsValidEntity(point_hurt)) { - point_hurt = EntIndexToEntRef(Entity_Create("point_hurt")); - - if (point_hurt == INVALID_ENT_REFERENCE) { - return false; - } - - DispatchSpawn(point_hurt); - } - - AcceptEntityInput(point_hurt, "TurnOn"); - SetEntProp(point_hurt, Prop_Data, "m_nDamage", damage); - SetEntProp(point_hurt, Prop_Data, "m_bitsDamageType", damageType); - Entity_PointHurtAtTarget(point_hurt, entity); - - if (fakeClassName[0] != '\0') { - Entity_SetClassName(point_hurt, fakeClassName); - } - - AcceptEntityInput(point_hurt, "Hurt", attacker); - AcceptEntityInput(point_hurt, "TurnOff"); - - if (fakeClassName[0] != '\0') { - Entity_SetClassName(point_hurt, "point_hurt"); - } - - return true; -} - -/* - * Gets the parent entity of an entity. - * - * @param entity Entity Index. - * @return Entity Index of the parent. - */ -stock Entity_GetParent(entity) -{ - return GetEntPropEnt(entity, Prop_Data, "m_pParent"); -} - -/* - * Clears the parent of an entity. - * - * @param entity Entity Index. - * @noreturn - */ -stock Entity_ClearParent(entity) -{ - SetVariantString(""); - AcceptEntityInput(entity, "ClearParent"); -} - -/* - * Sets the parent entity of an entity. - * - * @param entity Entity Index. - * @param parentEntity Entity Index of the new parent. - * @noreturn - */ -stock Entity_SetParent(entity, parent) -{ - SetVariantString("!activator"); - AcceptEntityInput(entity, "SetParent", parent); -} - - -/* - * Callback for Change_OverTime. - * Note that every parameter is a reference and can be changed during this callback. - * You can get the elapsed time since start by multiply tick with currentCall. - * - * @param entity Entity Index. - * @param interval The current interval from the current game time to execute the next call of this function. - * @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. - */ -typedef Entity_ChangeOverTimeCallback = function Action (int entity, float interval, int currentCall); //functag Entity_ChangeOverTimeCallback bool:public(&entity, &Float:interval, ¤tCall); - -/* - * Creates a timer and provides a callback to change various things about an entity over time. - * - * @param entity Entity Index. - * @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) -{ - new Handle: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) -{ - new 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 - - new any:result; - Call_StartFunction(INVALID_HANDLE, callback); - Call_PushCellRef(entity); - Call_PushFloatRef(interval); - Call_PushCellRef(currentCall); - Call_Finish(result); - - if(result == false){ - return Plugin_Stop; - } - - ResetPack(dataPack,true); - 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); - return Plugin_Stop; -} - - -/** - * Gets the next child, entity is parent of. - * - * @param client Entity Index (of Parent) - * @param start Start Index. - * @return Entity Index or -1 if no entity was found. - */ -stock Entity_GetNextChild(parent, start=0) -{ - for (new entity=start; entity <= 2048; entity++) { - - if (!Entity_IsValid(entity)) { - continue; - } - - if (entity > 0 && entity <= MaxClients && !IsClientConnected(entity)) { - continue; - } - - if (Entity_GetParent(entity) == parent) { - return entity; - } - } - - return INVALID_ENT_REFERENCE; -} -/** - * Gets the move/open direction of an entity (only available for func_door*, prop_door* and func_movelinear). - * Ex: if vec[2] is 1.0 a func_door moves straight up. - * - * @param entity Entity index. - * @param vec Vector. - * @noreturn - */ -stock Entity_GetMoveDirection(entity, Float:vec[3]) -{ - GetEntPropVector(entity, Prop_Data, "m_vecMoveDir", vec); -} -/** - * Sets the move/open direction of an entity (only available for func_door*, prop_door* and func_movelinear). - * Ex: if vec[2] is 1.0 a func_door moves straight up. - * - * @param entity Entity index. - * @param vec Vector. - * @noreturn - */ -stock Entity_SetMoveDirection(entity, const Float:vec[3]) -{ - SetEntPropVector(entity, Prop_Data, "m_vecMoveDir", vec); -} - -/** - * Returns if the entity will force close (won't be blockable by players and/or objects) or not when triggered to move. - * - * @param entity Entity index. - * @return True if the door will force close, otherwise false. - */ -stock bool:Entity_GetForceClose(entity) -{ - return bool:GetEntProp(entity, Prop_Data, "m_bForceClosed"); -} - -/** - * Sets if the door should force close (souldn't be blockable by players and/or objects) or not when triggered to move. - * - * @param entity Entity index. - * @param forceClose If true the door will force close, otherwise it won't. - * @noreturn - */ -stock Entity_SetForceClose(entity, bool:forceClose) -{ - SetEntProp(entity, Prop_Data, "m_bForceClosed", forceClose); -} - -/** - * Gets the speed of a moving entity (like doors: open close speed). - * - * @param entity Entity index. - * @return Speed of the entity. - */ -stock Float:Entity_GetSpeed(entity) -{ - return GetEntPropFloat(entity, Prop_Data, "m_flSpeed"); -} - -/** - * Sets how fast an entity moves (like doors: open close speed). - * - * @param entity Entity index. - * @param speed The new speed of the entity. - * @noreturn - */ -stock Entity_SetSpeed(entity, Float:speed) -{ - SetEntPropFloat(entity, Prop_Data, "m_flSpeed", speed); -} - -/** - * Gets the damage of a moving entity when blocked (like doors when open or close and players and/or objects are between the entity and something else). - * Note: Negative values add health to the blocking entity. - * - * @param entity Entity index. - * @return Damage. - */ -stock Float:Entity_GetBlockDamage(entity) -{ - return GetEntPropFloat(entity, Prop_Data, "m_flBlockDamage"); -} - -/** - * Sets the damage of a moving entity when blocked (like doors when open or close and players and/or objects are between the entity and something else). - * Note: Negative values add health to the blocking entity. - * - * @param entity Entity index. - * @param damage Damage. - * @noreturn - */ -stock Entity_SetBlockDamage(entity, Float:damage) -{ - SetEntPropFloat(entity, Prop_Data, "m_flBlockDamage", damage); -} - -/** - * Returns if the given entity is disabled or not. - * - * @param entity Entity index. - * @return True if entity is disabled, otherwise false. - */ -stock bool:Entity_IsDisabled(entity) -{ - return bool:GetEntProp(entity, Prop_Data, "m_bDisabled", 1); -} - -/** - * Disables the given entity. - * - * @param entity Entity index. - * @return True if successful otherwise false. - */ -stock Entity_Disable(entity) -{ - return AcceptEntityInput(entity, "Disable"); -} - -/** - * Enables the given entity. - * - * @param entity Entity index. - * @return True if successful otherwise false. - */ -stock Entity_Enable(entity) -{ - return AcceptEntityInput(entity, "Enable"); -} - - -// settings for m_takedamage taken from hl2sdk-ob-valve\game\shared\shareddefs.h -#define DAMAGE_NO 0 -#define DAMAGE_EVENTS_ONLY 1 // Call damage functions, but don't modify health -#define DAMAGE_YES 2 -#define DAMAGE_AIM 3 - -/** - * Sets the mode for an entity to take damage. - * Note: This is used to give a client god mode (DAMAGE_NO). - * - * @param entity Entity index. - * @param value Mode, use DAMAGE_* defines. - * @noreturn - */ -stock Entity_SetTakeDamage(entity, value) -{ - SetEntProp(entity, Prop_Data, "m_takedamage", value, 1); -} - -/** - * Gets the mode for an entity to take damage. - * Note: When the return value is DAMAGE_NO then the client is using godmode. - * - * @param entity Entity index. - * @return Take damage mode (DAMAGE_*). - */ -stock Entity_GetTakeDamage(entity) -{ - return GetEntProp(entity, Prop_Data, "m_takedamage", 1); -} - -/** - * Sets the minimum of damage required to hurt this entity. - * Example: This is used to block any damage done by projectile weapons against a gun ship in Half-Life 2. - * - * @param entity Entity index. - * @param minDamage Minimum required damage. - * @noreturn - */ -stock Entity_SetMinHealthDamage(entity, minDamage) -{ - SetEntProp(entity, Prop_Data, "m_iMinHealthDmg", minDamage); -} - -/** - * Gets the minimum of damage required to hurt this entity. - * Example: This is used to block any damage done by projectile weapons against a gun ship in Half-Life 2. - * - * @param entity Entity index. - * @return Minimum required damage. - */ -stock Entity_GetMinHealthDamage(entity) -{ - return GetEntProp(entity, Prop_Data, "m_iMinHealthDmg"); -} - -/** - * Gets an entity's color. - * - * @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]) -{ - static bool:gotconfig = false; - static String:prop[32]; - - if (!gotconfig) { - new Handle:gc = LoadGameConfigFile("core.games"); - new bool:exists = GameConfGetKeyValue(gc, "m_clrRender", prop, sizeof(prop)); - CloseHandle(gc); - - if (!exists) { - strcopy(prop, sizeof(prop), "m_clrRender"); - } - - gotconfig = true; - } - - new offset = GetEntSendPropOffs(entity, prop); - - if (offset <= 0) { - ThrowError("SetEntityRenderColor not supported by this mod"); - } - - for (new i=0; i < 4; i++) { - color[i] = GetEntData(entity, offset + i + 1, 1); - } -} - -/** - * Sets an entity's color. - * Doesn't change the value, if set to -1. - * - * @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) - * @noreturn - * @error Invalid entity index, or lack of mod compliance. - */ -stock Entity_SetRenderColor(entity, r=-1, g=-1, b=-1, a=-1) -{ - static bool:gotconfig = false; - static String:prop[32]; - - if (!gotconfig) { - new Handle:gc = LoadGameConfigFile("core.games"); - new bool:exists = GameConfGetKeyValue(gc, "m_clrRender", prop, sizeof(prop)); - CloseHandle(gc); - - if (!exists) { - strcopy(prop, sizeof(prop), "m_clrRender"); - } - - gotconfig = true; - } - - new offset = GetEntSendPropOffs(entity, prop); - - if (offset <= 0) { - ThrowError("SetEntityRenderColor not supported by this mod"); - } - - if(r != -1) { - SetEntData(entity, offset, r, 1, true); - } - - if(g != -1) { - SetEntData(entity, offset + 1, g, 1, true); - } - - if(b != -1) { - SetEntData(entity, offset + 2, b, 1, true); - } - - if(a != -1) { - SetEntData(entity, offset + 3, a, 1, true); - } -} - -/** - * Sends the 'addouput' command to an entity. - * - * @param entity Entity Index. - * @param input Input command. - * @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. - */ -stock bool:Entity_AddOutput(entity, const String:input[], activator=-1, caller=-1, outputid=0) -{ - SetVariantString(input); - return AcceptEntityInput(entity, "addoutput", activator, caller, outputid); -} diff --git a/scripting/1.10/include/smlib/files.inc b/scripting/1.10/include/smlib/files.inc deleted file mode 100644 index 2f56ca0..0000000 --- a/scripting/1.10/include/smlib/files.inc +++ /dev/null @@ -1,458 +0,0 @@ -#if defined _smlib_files_included - #endinput -#endif -#define _smlib_files_included - -#include -#include -#include - -/** - * Gets the Base name of a path. - * Examples: - * blub.txt -> "blub.txt" - * /sourcemod/extensions/example.ext.so -> "example.ext.so" - * - * @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) -{ - if (path[0] == '\0') { - buffer[0] = '\0'; - return; - } - - new pos_start = FindCharInString(path, '/', true); - - if (pos_start == -1) { - pos_start = FindCharInString(path, '\\', true); - } - - pos_start++; - - strcopy(buffer, size, path[pos_start]); -} - -/** - * Gets the Directory of a path (without the file name). - * Does not work with "." as the path. - * Examples: - * blub.txt -> "blub.txt" - * /sourcemod/extensions/example.ext.so -> "example.ext.so" - * - * @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) -{ - if (path[0] == '\0') { - buffer[0] = '\0'; - return; - } - - new pos_start = FindCharInString(path, '/', true); - - if (pos_start == -1) { - pos_start = FindCharInString(path, '\\', true); - - if (pos_start == -1) { - buffer[0] = '\0'; - return; - } - } - - strcopy(buffer, size, path); - buffer[pos_start] = '\0'; -} - -/** - * Gets the File name of a path. - * blub.txt -> "blub" - * /sourcemod/extensions/example.ext.so -> "example.ext" - * - * @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) -{ - if (path[0] == '\0') { - buffer[0] = '\0'; - return; - } - - File_GetBaseName(path, buffer, size); - - new pos_ext = FindCharInString(buffer, '.', true); - - if (pos_ext != -1) { - buffer[pos_ext] = '\0'; - } -} - -/** - * Gets the Extension of a file. - * Examples: - * blub.inc.txt -> "txt" - * /sourcemod/extensions/example.ext.so -> "so" - * - * @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) -{ - new extpos = FindCharInString(path, '.', true); - - if (extpos == -1) { - buffer[0] = '\0'; - return; - } - - strcopy(buffer, size, path[++extpos]); -} - -/** - * Adds a path to the downloadables network string table. - * This can be a file or directory and also works recursed. - * You can optionally specify file extensions that should be ignored. - * Bz2 and ztmp are automatically ignored. - * It only adds files that actually exist. - * You can also specify a wildcard * after the ., very useful for models. - * This forces a client to download the file if they do not already have it. - * - * @param path Path String - * @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) -{ - if (path[0] == '\0') { - return; - } - - if (FileExists(path)) { - - new String:fileExtension[5]; - File_GetExtension(path, fileExtension, sizeof(fileExtension)); - - if (StrEqual(fileExtension, "bz2", false) || StrEqual(fileExtension, "ztmp", false)) { - return; - } - - if (Array_FindString(ignoreExts, size, fileExtension) != -1) { - return; - } - - decl String:path_new[PLATFORM_MAX_PATH]; - strcopy(path_new, sizeof(path_new), path); - ReplaceString(path_new, sizeof(path_new), "//", "/"); - - AddFileToDownloadsTable(path_new); - } - else if (recursive && DirExists(path)) { - - decl String:dirEntry[PLATFORM_MAX_PATH]; - new Handle:__dir = OpenDirectory(path); - - while (ReadDirEntry(__dir, dirEntry, sizeof(dirEntry))) { - - if (StrEqual(dirEntry, ".") || StrEqual(dirEntry, "..")) { - continue; - } - - Format(dirEntry, sizeof(dirEntry), "%s/%s", path, dirEntry); - File_AddToDownloadsTable(dirEntry, recursive, ignoreExts, size); - } - - CloseHandle(__dir); - } - else if (FindCharInString(path, '*', true)) { - - new String: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]; - - File_GetDirName(path, dirName, sizeof(dirName)); - File_GetFileName(path, fileName, sizeof(fileName)); - StrCat(fileName, sizeof(fileName), "."); - - new Handle:__dir = OpenDirectory(dirName); - while (ReadDirEntry(__dir, dirEntry, sizeof(dirEntry))) { - - if (StrEqual(dirEntry, ".") || StrEqual(dirEntry, "..")) { - continue; - } - - if (strncmp(dirEntry, fileName, strlen(fileName)) == 0) { - Format(dirEntry, sizeof(dirEntry), "%s/%s", dirName, dirEntry); - File_AddToDownloadsTable(dirEntry, recursive, ignoreExts, size); - } - } - - CloseHandle(__dir); - } - } - - return; -} - - -/* - * Adds all files/paths in the given text file to the download table. - * Recursive mode enabled, see File_AddToDownloadsTable() - * Comments are allowed ! Supported comment types are ; // # - * - * @param path Path to the .txt file. - * @noreturn - */ -stock File_ReadDownloadList(const String:path[]) -{ - new Handle:file = OpenFile(path, "r"); - - if (file == INVALID_HANDLE) { - return; - } - - new String:buffer[PLATFORM_MAX_PATH]; - while (!IsEndOfFile(file)) { - ReadFileLine(file, buffer, sizeof(buffer)); - - new pos; - pos = StrContains(buffer, "//"); - if (pos != -1) { - buffer[pos] = '\0'; - } - - pos = StrContains(buffer, "#"); - if (pos != -1) { - buffer[pos] = '\0'; - } - - pos = StrContains(buffer, ";"); - if (pos != -1) { - buffer[pos] = '\0'; - } - - TrimString(buffer); - - if (buffer[0] == '\0') { - continue; - } - - File_AddToDownloadsTable(buffer); - } - - CloseHandle(file); -} - -/* - * Attempts to load a translation file and optionally unloads the plugin if the file - * doesn't exist (also prints an error message). - * - * @param file Filename of the translations file (eg. .phrases). - * @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) -{ - decl String:path[PLATFORM_MAX_PATH]; - - BuildPath(Path_SM, path, sizeof(path), "translations/%s", file); - - if (FileExists(path)) { - LoadTranslations(file); - return true; - } - - Format(path,sizeof(path), "%s.txt", path); - - if (!FileExists(path)) { - - if (setFailState) { - SetFailState("Unable to locate translation file (%s).", path); - } - - return false; - } - - LoadTranslations(file); - - return true; -} - -/* - * Reads the contents of a given file into a string buffer in binary mode. - * - * @param path Path to the file - * @param buffer String buffer - * @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) -{ - new Handle:file = OpenFile(path, "rb"); - - if (file == INVALID_HANDLE) { - buffer[0] = '\0'; - return -1; - } - - new num_bytes_written = ReadFileString(file, buffer, size); - CloseHandle(file); - - return num_bytes_written; -} - -/* - * Writes a string into a file in binary mode. - * - * @param file Path to the file - * @param str String to write - * @return True on success, false otherwise - */ -stock bool:File_StringToFile(const String:path[], String:str[]) -{ - new Handle:file = OpenFile(path, "wb"); - - if (file == INVALID_HANDLE) { - return false; - } - - new bool:success = WriteFileString(file, str, false); - CloseHandle(file); - - return success; -} - -/* - * Copies file source to destination - * Based on code of javalia: - * http://forums.alliedmods.net/showthread.php?t=159895 - * - * @param source Input file - * @param destination Output file - */ -stock bool:File_Copy(const String:source[], const String:destination[]) -{ - new Handle:file_source = OpenFile(source, "rb"); - - if (file_source == INVALID_HANDLE) { - return false; - } - - new Handle:file_destination = OpenFile(destination, "wb"); - - if (file_destination == INVALID_HANDLE) { - CloseHandle(file_source); - return false; - } - - new buffer[32]; - new cache; - - while (!IsEndOfFile(file_source)) { - cache = ReadFile(file_source, buffer, 32, 1); - WriteFile(file_destination, buffer, cache, 1); - } - - CloseHandle(file_source); - CloseHandle(file_destination); - - return true; -} - -/* - * Recursively copies (the content) of a directory or file specified - * by "path" to "destination". - * Note that because of Sourcemod API limitations this currently does not - * takeover the file permissions (it leaves them default). - * Links will be resolved. - * - * @param path Source path - * @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 - */ -stock bool:File_CopyRecursive(const String:path[], const String:destination[], bool:stop_on_error=false, dirMode=493) -{ - if (FileExists(path)) { - return File_Copy(path, destination); - } - else if (DirExists(path)) { - return Sub_File_CopyRecursive(path, destination, stop_on_error, FileType_Directory, dirMode); - } - else { - return false; - } -} - -static stock bool:Sub_File_CopyRecursive(const String:path[], const String:destination[], bool:stop_on_error=false, FileType:fileType, dirMode) -{ - if (fileType == FileType_File) { - return File_Copy(path, destination); - } - else if (fileType == FileType_Directory) { - - if (!CreateDirectory(destination, dirMode) && stop_on_error) { - return false; - } - - new Handle: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; - - while (ReadDirEntry(directory, source_buffer, sizeof(source_buffer), type)) { - - if (StrEqual(source_buffer, "..") || StrEqual(source_buffer, ".")) { - continue; - } - - Format(destination_buffer, sizeof(destination_buffer), "%s/%s", destination, source_buffer); - Format(source_buffer, sizeof(source_buffer), "%s/%s", path, source_buffer); - - if (type == FileType_File) { - File_Copy(source_buffer, destination_buffer); - } - else if (type == FileType_Directory) { - - if (!File_CopyRecursive(source_buffer, destination_buffer, stop_on_error, dirMode) && stop_on_error) { - CloseHandle(directory); - return false; - } - } - } - - CloseHandle(directory); - } - else if (fileType == FileType_Unknown) { - return false; - } - - return true; -} diff --git a/scripting/1.10/include/smlib/game.inc b/scripting/1.10/include/smlib/game.inc deleted file mode 100644 index 771f780..0000000 --- a/scripting/1.10/include/smlib/game.inc +++ /dev/null @@ -1,58 +0,0 @@ -#if defined _smlib_game_included - #endinput -#endif -#define _smlib_game_included - -#include -#include -#include - -/* - * End's the game and displays the scoreboard with intermission time. - * - * @noparam - * @return True on success, false otherwise - */ -stock bool:Game_End() -{ - new game_end = FindEntityByClassname(-1, "game_end"); - - if (game_end == -1) { - game_end = CreateEntityByName("game_end"); - - if (game_end == -1) { - ThrowError("Unable to find or create entity \"game_end\""); - } - } - - return AcceptEntityInput(game_end, "EndGame"); -} - -/* - * End's the current round, allows specifying the winning - * team and more. - * This function currently works in TF2 only (it uses the game_round_win entity). - * - * @param team The winning Team, pass 0 for Sudden Death mode (no winning team) - * @param forceMapReset If to force the map to reset during the force respawn after the round is over. - * @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) -{ - new game_round_win = FindEntityByClassname(-1, "game_round_win"); - - if (game_round_win == -1) { - game_round_win = CreateEntityByName("game_round_win"); - - if (game_round_win == -1) { - ThrowError("Unable to find or create entity \"game_round_win\""); - } - } - - DispatchKeyValue(game_round_win, "TeamNum" , (team ? "true" : "false")); - DispatchKeyValue(game_round_win, "force_map_reset" , (forceMapReset? "true" : "false")); - DispatchKeyValue(game_round_win, "switch_teams" , (switchTeams ? "true" : "false")); - - return AcceptEntityInput(game_round_win, "RoundWin"); -} diff --git a/scripting/1.10/include/smlib/general.inc b/scripting/1.10/include/smlib/general.inc deleted file mode 100644 index ef061b6..0000000 --- a/scripting/1.10/include/smlib/general.inc +++ /dev/null @@ -1,251 +0,0 @@ -#if defined _smlib_general_included - #endinput -#endif -#define _smlib_general_included - -#include -#include -#include - -#define TIME_TO_TICKS(%1) ( (int)( 0.5 + (float)(%1) / GetTickInterval() ) ) -#define TICKS_TO_TIME(%1) ( GetTickInterval() * %1 ) -#define ROUND_TO_TICKS(%1) ( TICK_INTERVAL * TIME_TO_TICKS( %1 ) ) - -/* - * Precaches the given model. - * It's best to call this OnMapStart(). - * - * @param material Path of the material to precache. - * @return Returns the material index, INVALID_STRING_INDEX on error. - */ -stock PrecacheMaterial(const String:material[]) -{ - static materialNames = INVALID_STRING_TABLE; - - if (materialNames == INVALID_STRING_TABLE) { - if ((materialNames = FindStringTable("Materials")) == INVALID_STRING_TABLE) { - return INVALID_STRING_INDEX; - } - } - - new index = FindStringIndex2(materialNames, material); - if (index == INVALID_STRING_INDEX) { - new numStrings = GetStringTableNumStrings(materialNames); - if (numStrings >= GetStringTableMaxStrings(materialNames)) { - return INVALID_STRING_INDEX; - } - - AddToStringTable(materialNames, material); - index = numStrings; - } - - return index; -} - -/* - * Checks if the material is precached. - * - * @param material Path of the material. - * @return True if it is precached, false otherwise. - */ -stock bool:IsMaterialPrecached(const String:material[]) -{ - static materialNames = INVALID_STRING_TABLE; - - if (materialNames == INVALID_STRING_TABLE) { - if ((materialNames = FindStringTable("Materials")) == INVALID_STRING_TABLE) { - return false; - } - } - - return (FindStringIndex2(materialNames, material) != INVALID_STRING_INDEX); -} - -/* - * Precaches the given particle system. - * It's best to call this OnMapStart(). - * Code based on Rochellecrab's, thanks. - * - * @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[]) -{ - static particleEffectNames = INVALID_STRING_TABLE; - - if (particleEffectNames == INVALID_STRING_TABLE) { - if ((particleEffectNames = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) { - return INVALID_STRING_INDEX; - } - } - - new index = FindStringIndex2(particleEffectNames, particleSystem); - if (index == INVALID_STRING_INDEX) { - new numStrings = GetStringTableNumStrings(particleEffectNames); - if (numStrings >= GetStringTableMaxStrings(particleEffectNames)) { - return INVALID_STRING_INDEX; - } - - AddToStringTable(particleEffectNames, particleSystem); - index = numStrings; - } - - return index; -} - -/* - * Checks if the particle system is precached. - * - * @param material Name of the particle system - * @return True if it is precached, false otherwise. - */ -stock bool:IsParticleSystemPrecached(const String:particleSystem[]) -{ - static particleEffectNames = INVALID_STRING_TABLE; - - if (particleEffectNames == INVALID_STRING_TABLE) { - if ((particleEffectNames = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) { - return false; - } - } - - return (FindStringIndex2(particleEffectNames, particleSystem) != INVALID_STRING_INDEX); -} - -/* - * Searches for the index of a given string in a string table. - * - * @param table String table name. - * @param str String to find. - * @return String index if found, INVALID_STRING_INDEX otherwise. - */ -stock FindStringIndexByTableName(const String:table[], const String:str[]) -{ - new tableIndex = INVALID_STRING_TABLE; - if ((tableIndex = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) { - return INVALID_STRING_INDEX; - } - - return FindStringIndex2(tableIndex, str); -} - -/* - * Rewrite of FindStringIndex, because in my tests - * FindStringIndex failed to work correctly. - * 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. - */ -stock FindStringIndex2(tableidx, const String:str[]) -{ - decl String:buf[1024]; - - new numStrings = GetStringTableNumStrings(tableidx); - for (new i=0; i < numStrings; i++) { - ReadStringTable(tableidx, i, buf, sizeof(buf)); - - if (StrEqual(buf, str)) { - return i; - } - } - - return INVALID_STRING_INDEX; -} - -/* - * Converts a long IP to a dotted format String. - * - * @param ip IP Long - * @param buffer String Buffer (size = 16) - * @param size String Buffer size - * @noreturn - */ -stock LongToIP(ip, String:buffer[], size) -{ - Format( - buffer, size, - "%d.%d.%d.%d", - (ip >> 24) & 0xFF, - (ip >> 16) & 0xFF, - (ip >> 8 ) & 0xFF, - ip & 0xFF - ); -} - -/* - * Converts a dotted format String IP to a long. - * - * @param ip IP String - * @return Long IP - */ -stock IPToLong(const String:ip[]) -{ - decl String:pieces[4][4]; - - if (ExplodeString(ip, ".", pieces, sizeof(pieces), sizeof(pieces[])) != 4) { - return 0; - } - - return ( - StringToInt(pieces[0]) << 24 | - StringToInt(pieces[1]) << 16 | - StringToInt(pieces[2]) << 8 | - StringToInt(pieces[3]) - ); -} - -static localIPRanges[] = -{ - 10 << 24, // 10. - 127 << 24 | 1 , // 127.0.0.1 - 127 << 24 | 16 << 16, // 127.16. - 192 << 24 | 168 << 16, // 192.168. -}; - -/* - * Checks whether an IP is a private/internal IP - * - * @param ip IP Long - * @return True if the IP is local, false otherwise. - */ -stock bool:IsIPLocal(ip) -{ - new range, bits, move, bool:matches; - - for (new i=0; i < sizeof(localIPRanges); i++) { - - range = localIPRanges[i]; - matches = true; - - for (new j=0; j < 4; j++) { - move = j * 8; - bits = (range >> move) & 0xFF; - - if (bits && bits != ((ip >> move) & 0xFF)) { - matches = false; - } - } - - if (matches) { - return true; - } - } - - return false; -} - -/* - * Closes the given hindle and sets it to INVALID_HANDLE. - * - * @param handle handle - * @noreturn - */ -stock ClearHandle(&Handle:handle) -{ - if (handle != INVALID_HANDLE) { - CloseHandle(handle); - handle = INVALID_HANDLE; - } -} diff --git a/scripting/1.10/include/smlib/math.inc b/scripting/1.10/include/smlib/math.inc deleted file mode 100644 index 8acca98..0000000 --- a/scripting/1.10/include/smlib/math.inc +++ /dev/null @@ -1,344 +0,0 @@ -#if defined _smlib_math_included - #endinput -#endif -#define _smlib_math_included - -#include - -#define SIZE_OF_INT 2147483647 // without 0 -#define INT_MAX_DIGITS 10 - -#define GAMEUNITS_TO_METERS 0.01905 -#define METERS_TO_GAMEUNITS 52.49343832020997 -#define METERS_TO_FEET 3.2808399 -#define FEET_TO_METERS 0.3048 -#define KILOMETERS_TO_MILES 0.62137 - -enum VecAngle -{ - ANG_ALPHA, - ANG_BETA, - ANG_GAMMA -} - -/** - * Makes a negative integer number to a positive integer number. - * This is faster than Sourcemod's native FloatAbs() for integers. - * Use FloatAbs() for Float numbers. - * - * @param number A number that can be positive or negative. - * @return Positive number. - */ -stock Math_Abs(value) -{ - return (value ^ (value >> 31)) - (value >> 31); -} - -/** - * Checks if 2 vectors are equal. - * You can specfiy a tolerance, which is the maximum distance at which vectors are considered equals - * - * @param vec1 First vector (3 dim array) - * @param vec2 Second vector (3 dim array) - * @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) -{ - new Float:distance = GetVectorDistance(vec1, vec2, true); - - return distance <= (tolerance * tolerance); -} - -/** - * Sets the given value to min - * if the value is smaller than the given. - * - * @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) -{ - if (value < min) { - value = min; - } - - return value; -} - -/** - * Sets the given value to max - * if the value is greater than the given. - * - * @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) -{ - if (value > max) { - value = max; - } - - return value; -} - -/** - * Makes sure a value is within a certain range and - * returns the value. - * 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. - * - * @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) -{ - value = Math_Min(value, min); - value = Math_Max(value, max); - - return value; -} - -/* - * Checks if the value is within the given bounds (min & max). - * - * @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) -{ - if (value < min || value > max) { - return false; - } - - return true; -} - -/** - * 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. - * - * @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) -{ - return (value % max) + min; -} - -/** - * Returns a random, uniform Integer number in the specified (inclusive) range. - * This is safe to use multiple times in a function. - * The seed is set automatically for each plugin. - * Rewritten by MatthiasVance, thanks. - * - * @param min Min value used as lower border - * @param max Max value used as upper border - * @return Random Integer number between min and max - */ -stock Math_GetRandomInt(min, max) -{ - new random = GetURandomInt(); - - if (random == 0) { - random++; - } - - return RoundToCeil(float(random) / (float(SIZE_OF_INT) / float(max - min + 1))) + min - 1; -} - -/** - * Returns a random, uniform Float number in the specified (inclusive) range. - * This is safe to use multiple times in a function. - * The seed is set automatically for each plugin. - * - * @param min Min value used as lower border - * @param max Max value used as upper border - * @return Random Float number between min and max - */ -stock Float:Math_GetRandomFloat(Float:min, Float:max) -{ - return (GetURandomFloat() * (max - min)) + min; -} - -/** - * Gets the percentage of amount in all as Integer where - * amount and all are numbers and amount usually - * is a subset of all. - * - * @param value Integer value - * @param all Integer value - * @return An Integer value between 0 and 100 (inclusive). - */ -stock Math_GetPercentage(value, all) { - return RoundToNearest((float(value) / float(all)) * 100.0); -} - -/** - * Gets the percentage of amount in all as Float where - * amount and all are numbers and amount usually - * is a subset of all. - * - * @param value Float value - * @param all Float value - * @return A Float value between 0.0 and 100.0 (inclusive). - */ -stock Float:Math_GetPercentageFloat(Float:value, Float:all) { - return (value / all) * 100.0; -} - -/* - * Moves the start vector on a direct line to the end vector by the given scale. - * Note: If scale is 0.0 the output will be the same as the start vector and if scale is 1.0 the output vector will be the same as the end vector. - * Exmaple usage: Move an entity to another entity but only 12 units: Vector_MoveVector(entity1Origin,entity2Origin,(12.0 / GetVectorDistance(entity1Origin,entity2Origin)),newEntity1Origin); now only teleport your entity to newEntity1Origin. - * - * @param start The start vector where the imagined line starts. - * @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]) -{ - SubtractVectors(end,start,output); - ScaleVector(output,scale); - AddVectors(start,output,output); -} - -/** - * Puts x, y and z into a vector. - * - * @param x Float value. - * @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]) -{ - result[0] = x; - result[1] = y; - result[2] = z; -} - -/** - * Rotates a vector around its zero-point. - * Note: As example you can rotate mins and maxs of an entity and then add its origin to mins and maxs to get its bounding box in relation to the world and its rotation. - * When used with players use the following angle input: - * angles[0] = 0.0; - * angles[1] = 0.0; - * angles[2] = playerEyeAngles[1]; - * - * @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]) -{ - // First the angle/radiant calculations - decl 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 - // 1 = zAxis - rad[0] = DegToRad(angles[2]); - rad[1] = DegToRad(angles[0]); - 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]); - - // 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; - newY = cosAlpha*y - sinAlpha*z; - newZ = cosAlpha*z + sinAlpha*y; - y = newY; - z = newZ; - - newX = cosBeta*x + sinBeta*z; - newZ = cosBeta*z - sinBeta*x; - x = newX; - z = newZ; - - newX = cosGamma*x - sinGamma*y; - newY = cosGamma*y + sinGamma*x; - x = newX; - y = newY; - - // Store everything... - result[0] = x; - result[1] = y; - result[2] = z; -} - -/** - * Converts Source Game Units to metric Meters - * - * @param units Float value - * @return Meters as Float value. - */ -stock Float:Math_UnitsToMeters(Float:units) -{ - return (units * GAMEUNITS_TO_METERS); -} - -/** - * Converts Source Game Units to Meters - * - * @param units Float value - * @return Feet as Float value. - */ -stock Float:Math_UnitsToFeet(Float:units) -{ - return (Math_UnitsToMeters(units) * METERS_TO_FEET); -} - -/** - * Converts Source Game Units to Centimeters - * - * @param units Float value - * @return Centimeters as Float value. - */ -stock Float:Math_UnitsToCentimeters(Float:units) -{ - return (Math_UnitsToMeters(units) * 100.0); -} - -/** - * Converts Source Game Units to Kilometers - * - * @param units Float value - * @return Kilometers as Float value. - */ -stock Float:Math_UnitsToKilometers(Float:units) -{ - return (Math_UnitsToMeters(units) / 1000.0); -} - -/** - * Converts Source Game Units to Miles - * - * @param units Float value - * @return Miles as Float value. - */ -stock Float:Math_UnitsToMiles(Float:units) -{ - return (Math_UnitsToKilometers(units) * KILOMETERS_TO_MILES); -} diff --git a/scripting/1.10/include/smlib/menus.inc b/scripting/1.10/include/smlib/menus.inc deleted file mode 100644 index c0c825d..0000000 --- a/scripting/1.10/include/smlib/menus.inc +++ /dev/null @@ -1,38 +0,0 @@ -#if defined _smlib_menus_included - #endinput -#endif -#define _smlib_menus_included - -#include -#include - -/** - * Adds an option to a menu with a String display but an integer - * identifying the option. - * - * @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[]) -{ - decl String:buffer[INT_MAX_DIGITS + 1]; - IntToString(value, buffer, sizeof(buffer)); - AddMenuItem(menu, buffer, display); -} - -/** - * Retrieves an integer-value choice from a menu, where the - * menu's information strings were created as integers. - * - * @param menu Handle to the menu - * @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) -{ - decl String:buffer[INT_MAX_DIGITS + 1]; - GetMenuItem(menu, param2, buffer, sizeof(buffer)); - return StringToInt(buffer); -} diff --git a/scripting/1.10/include/smlib/server.inc b/scripting/1.10/include/smlib/server.inc deleted file mode 100644 index cb439e2..0000000 --- a/scripting/1.10/include/smlib/server.inc +++ /dev/null @@ -1,135 +0,0 @@ -#if defined _smlib_server_included - #endinput -#endif -#define _smlib_server_included - -#include -#include - -/* - * Gets the server's public/external (default) or - * private/local (usually server's behind a NAT) IP. - * If your server is behind a NAT Router, you need the SteamTools - * extension available at http://forums.alliedmods.net/showthread.php?t=129763 - * to get the public IP. has to be included BEFORE . - * If the server is not behind NAT, the public IP is the same as the private IP. - * - * @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) -{ - new ip = 0; - - static Handle:cvHostip = INVALID_HANDLE; - - if (cvHostip == INVALID_HANDLE) { - cvHostip = FindConVar("hostip"); - MarkNativeAsOptional("Steam_GetPublicIP"); - } - - if (cvHostip != INVALID_HANDLE) { - ip = GetConVarInt(cvHostip); - } - - if (ip != 0 && IsIPLocal(ip) == public_) { - ip = 0; - } - -#if defined _steamtools_included - if (ip == 0) { - if (CanTestFeatures() && GetFeatureStatus(FeatureType_Native, "Steam_GetPublicIP") == FeatureStatus_Available) { - decl octets[4]; - Steam_GetPublicIP(octets); - - ip = - octets[0] << 24 | - octets[1] << 16 | - octets[2] << 8 | - octets[3]; - - if (IsIPLocal(ip) == public_) { - ip = 0; - } - } - } -#endif - - return ip; -} - -/* - * Gets the server's public/external (default) or - * private/local (usually server's behind a NAT) as IP String in dotted format. - * If your server is behind a NAT Router, you need the SteamTools - * extension available at http://forums.alliedmods.net/showthread.php?t=129763 - * to get the public IP. has to be included BEFORE . - * If the public IP couldn't be found, an empty String is returned. - * If the server is not behind NAT, the public IP is the same as the private IP. - * - * @param buffer String buffer (size=16) - * @param size String buffer size. - * @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) -{ - new ip; - - if ((ip = Server_GetIP(public_)) == 0) { - buffer[0] = '\0'; - return false; - } - - LongToIP(ip, buffer, size); - - return true; -} - -/* - * Gets the server's local port. - * - * @noparam - * @return The server's port, 0 if there is no port. - */ -stock Server_GetPort() -{ - static Handle:cvHostport = INVALID_HANDLE; - - if (cvHostport == INVALID_HANDLE) { - cvHostport = FindConVar("hostport"); - } - - if (cvHostport == INVALID_HANDLE) { - return 0; - } - - new port = GetConVarInt(cvHostport); - - return port; -} - -/* - * Gets the server's hostname - * - * @param hostname String buffer - * @param size String buffer size - * @return True on success, false otherwise. - */ -stock bool:Server_GetHostName(String:buffer[], size) -{ - static Handle:cvHostname = INVALID_HANDLE; - - if (cvHostname == INVALID_HANDLE) { - cvHostname = FindConVar("hostname"); - } - - if (cvHostname == INVALID_HANDLE) { - buffer[0] = '\0'; - return false; - } - - GetConVarString(cvHostname, buffer, size); - - return true; -} diff --git a/scripting/1.10/include/smlib/sql.inc b/scripting/1.10/include/smlib/sql.inc deleted file mode 100644 index 1a4f1f1..0000000 --- a/scripting/1.10/include/smlib/sql.inc +++ /dev/null @@ -1,108 +0,0 @@ -#if defined _smlib_sql_included - #endinput -#endif -#define _smlib_sql_included - -#include -#include - -/** - * Executes a threaded SQL Query (See: SQL_TQuery) - * This function supports the printf Syntax. - * - * - * @param database A database Handle. - * @param callback Callback; database is in "owner" and the query Handle is passed in "hndl". - * @param data Extra data value to pass to the callback. - * @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:...) { - - if (database == INVALID_HANDLE) { - ThrowError("[SMLIB] Error: Invalid database handle."); - return; - } - - decl String:query[16384]; - VFormat(query, sizeof(query), format, 6); - - SQL_TQuery(database, callback, query, data, priority); -} - -/** - * Fetches an integer from a field in the current row of a result set (See: SQL_FetchInt) - * - * @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. - */ -stock SQL_FetchIntByName(Handle:query, String:fieldName[], &DBResult:result=DBVal_Error) { - - new fieldNum; - SQL_FieldNameToNum(query, fieldName, fieldNum); - - return SQL_FetchInt(query, fieldNum, result); -} - -/** - * Fetches a bool from a field in the current row of a result set (See: SQL_FetchInt) - * - * @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 bool value. - * @error Invalid query Handle or field index, invalid - * type conversion requested from the database, - * or no current result set. - */ -stock bool:SQL_FetchBoolByName(Handle:query, String:fieldName[], &DBResult:result=DBVal_Error) { - - return bool:SQL_FetchIntByName(query, fieldName, result); -} - -/** - * Fetches a float from a field in the current row of a result set. (See: SQL_FetchFloat) - * - * @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. - */ -stock Float:SQL_FetchFloatByName(Handle:query, String:fieldName[], &DBResult:result=DBVal_Error) { - - new fieldNum; - SQL_FieldNameToNum(query, fieldName, fieldNum); - - return SQL_FetchFloat(query, fieldNum, result); -} - -/** - * Fetches a string from a field in the current row of a result set. (See: SQL_FetchString) - * - * @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. - */ -stock SQL_FetchStringByName(Handle:query, String:fieldName[], String:buffer[], maxlength, &DBResult:result=DBVal_Error) { - - new fieldNum; - SQL_FieldNameToNum(query, fieldName, fieldNum); - - return SQL_FetchString(query, fieldNum, buffer, maxlength, result); -} diff --git a/scripting/1.10/include/smlib/strings.inc b/scripting/1.10/include/smlib/strings.inc deleted file mode 100644 index 96657f9..0000000 --- a/scripting/1.10/include/smlib/strings.inc +++ /dev/null @@ -1,233 +0,0 @@ -#if defined _smlib_strings_included - #endinput -#endif -#define _smlib_strings_included - -#include -#include - -/** - * Checks if the string is numeric. - * This correctly handles + - . in the String. - * - * @param str String to check. - * @return True if the String is numeric, false otherwise.. - */ -stock bool:String_IsNumeric(const String:str[]) -{ - new x=0; - new dotsFound=0; - new numbersFound=0; - - if (str[x] == '+' || str[x] == '-') { - x++; - } - - while (str[x] != '\0') { - - if (IsCharNumeric(str[x])) { - numbersFound++; - } - else if (str[x] == '.') { - dotsFound++; - - if (dotsFound > 1) { - return false; - } - } - else { - return false; - } - - x++; - } - - if (!numbersFound) { - return false; - } - - return true; -} - -/** - * Trims a string by removing the specified chars from beginning and ending. - * Removes all ' ', '\t', '\r', '\n' characters by default. - * The Output String can be the same as the Input String. - * - * @param str Input String. - * @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") -{ - new x=0; - while (str[x] != '\0' && FindCharInString(chrs, str[x]) != -1) { - x++; - } - - x = strcopy(output, size, str[x]); - x--; - - while (x >= 0 && FindCharInString(chrs, output[x]) != -1) { - x--; - } - - output[++x] = '\0'; -} - -/** - * Removes a list of strings from a string. - * - * @param buffer Input/Ourput 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) -{ - for (new i=0; i < size; i++) { - ReplaceString(buffer, SIZE_OF_INT, removeList[i], "", caseSensitive); - } -} - -/** - * Converts the whole String to lower case. - * Only works with alphabetical characters (not ÖÄÜ) because Sourcemod suxx ! - * The Output String can be the same as the Input String. - * - * @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) -{ - size--; - - new x=0; - while (input[x] != '\0' && x < size) { - - output[x] = CharToLower(input[x]); - - x++; - } - - output[x] = '\0'; -} - -/** - * Converts the whole String to upper case. - * Only works with alphabetical characters (not öäü) because Sourcemod suxx ! - * The Output String can be the same as the Input String. - * - * @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) -{ - size--; - - new x=0; - while (input[x] != '\0' && x < size) { - - output[x] = CharToUpper(input[x]); - - x++; - } - - output[x] = '\0'; -} - -/** - * Generates a random string. - * - * - * @param buffer String Buffer. - * @param size String Buffer size (must be length+1) - * @param length Number of characters being generated. - * @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") -{ - new random, len; - size--; - - if (chrs[0] != '\0') { - len = strlen(chrs) - 1; - } - - new n = 0; - while (n < length && n < size) { - - if (chrs[0] == '\0') { - random = Math_GetRandomInt(33, 126); - buffer[n] = random; - } - else { - random = Math_GetRandomInt(0, len); - buffer[n] = chrs[random]; - } - - n++; - } - - buffer[length] = '\0'; -} - -/** - * Checks if string str starts with subString. - * - * - * @param str String to check - * @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[]) -{ - new n = 0; - while (subString[n] != '\0') { - - if (str[n] == '\0' || str[n] != subString[n]) { - return false; - } - - n++; - } - - return true; -} - -/** - * Checks if string str ends with subString. - * - * - * @param str String to check - * @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[]) -{ - new n_str = strlen(str) - 1; - new n_subString = strlen(subString) - 1; - - if(n_str < n_subString) { - return false; - } - - while (n_str != 0 && n_subString != 0) { - - if (str[n_str--] != subString[n_subString--]) { - return false; - } - } - - return true; -} diff --git a/scripting/1.10/include/smlib/teams.inc b/scripting/1.10/include/smlib/teams.inc deleted file mode 100644 index 2fd18c8..0000000 --- a/scripting/1.10/include/smlib/teams.inc +++ /dev/null @@ -1,318 +0,0 @@ -#if defined _smlib_teams_included - #endinput -#endif -#define _smlib_teams_included - -#include -#include -#include - -#define MAX_TEAMS 32 // Max number of teams in a game -#define MAX_TEAM_NAME_LENGTH 32 // Max length of a team's name - -// Team Defines -#define TEAM_INVALID -1 -#define TEAM_UNASSIGNED 0 -#define TEAM_SPECTATOR 1 -#define TEAM_ONE 2 -#define TEAM_TWO 3 -#define TEAM_THREE 4 -#define TEAM_FOUR 5 - -/* - * If one team is empty its assumed single team mode is enabled and the game won't start. - * - * @noparam - * @return True if one team is empty, false otherwise. - */ -stock bool:Team_HaveAllPlayers(bool:countFakeClients=true) { - - new teamCount = GetTeamCount(); - for (new i=2; i < teamCount; i++) { - - if (Team_GetClientCount(i, ((countFakeClients) ? CLIENTFILTER_ALL : CLIENTFILTER_NOBOTS)) == 0) { - return false; - } - } - - return true; -} - -/* - * Returns the client count of the players in a team. - * - * @param team Team Index. - * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). - * @return Client count in the server. - */ -stock Team_GetClientCount(team, flags=0) -{ - flags |= CLIENTFILTER_INGAME; - - new numClients = 0; - for (new client=1; client <= MaxClients; client++) { - - if (!Client_MatchesFilter(client, flags)) { - continue; - } - - if (GetClientTeam(client) == team) { - numClients++; - } - } - - return numClients; -} - -/* - * Returns the client counts of the first two teams (eg.: Terrorists - Counter). - * Use this function for optimization if you have to get the counts of both teams, - * otherwise use Team_GetClientCount(). - * - * @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) -{ - flags |= CLIENTFILTER_INGAME; - - for (new client=1; client <= MaxClients; client++) { - - if (!Client_MatchesFilter(client, flags)) { - continue; - } - - if (GetClientTeam(client) == TEAM_ONE) { - team1++; - } - else if (GetClientTeam(client) == TEAM_TWO) { - team2++; - } - } -} - -/* - * Gets the name of a team. - * Don't call this before OnMapStart() - * - * @param index Team Index. - * @param str String buffer - * @param size String Buffer Size - * @return True on success, false otherwise - */ -stock bool:Team_GetName(index, String:str[], size) -{ - new edict = Team_GetEdict(index); - - if (edict == -1) { - str[0] = '\0'; - return false; - } - - GetEntPropString(edict, Prop_Send, "m_szTeamname", str, size); - - return true; -} - -/* - * Changes a team's name. - * Use this carefully ! - * Only set the teamname OnMapStart() or OnEntityCreated() - * when no players are ingame, otherwise it can crash the server. - * - * @param index Team Index. - * @param name New Name String - * @return True on success, false otherwise - */ -stock bool:Team_SetName(index, const String:name[]) -{ - new edict = Team_GetEdict(index); - - if (edict == -1) { - return false; - } - - SetEntPropString(edict, Prop_Send, "m_szTeamname", name); - ChangeEdictState(edict, GetEntSendPropOffs(edict, "m_szTeamname", true)); - - return true; -} - -/* - * Changes a team's score. - * Don't use this before OnMapStart(). - * - * @param index Team Index. - * @return Team Score or -1 if the team is not valid. - */ -stock Team_GetScore(index) -{ - new edict = Team_GetEdict(index); - - if (edict == -1) { - return -1; - } - - return GetEntProp(edict, Prop_Send, "m_iScore"); -} - -/* - * Changes a team's score. - * Don't use this before OnMapStart(). - * - * @param index Team Index. - * @param score Score value. - * @return True on success, false otherwise - */ -stock bool:Team_SetScore(index, score) -{ - new edict = Team_GetEdict(index); - - if (edict == -1) { - return false; - } - - SetEntProp(edict, Prop_Send, "m_iScore", score); - - ChangeEdictState(edict, GetEntSendPropOffs(edict, "m_iScore", true)); - - return true; -} - -/* - * Gets a team's edict (*team_manager) Team Index. - * Don't call this before OnMapStart() - * - * @param edict Edict - * @return Team Index - */ -stock Team_EdictGetNum(edict) -{ - return GetEntProp(edict, Prop_Send, "m_iTeamNum"); -} - -/* - * Check's whether the index is a valid team index or not. - * Don't call this before OnMapStart() - * - * @param index Index. - * @return True if the Index is a valid team, false otherwise. - */ -stock bool:Team_IsValid(index) -{ - return (Team_GetEdict(index) != -1); -} - -/* - * Gets a team's edict (team_manager) Team Index. - * Don't call this before OnMapStart() - * - * @param index Edict - * @return Team Index - */ -stock Team_EdictIsValid(edict) -{ - return GetEntProp(edict, Prop_Send, "m_iTeamNum"); -} - -/* - * Gets a team's edict (team_manager). - * This function caches found team edicts. - * Don't call this before OnMapStart() - * - * @param index Team Index. - * @return Team edict or -1 if not found - */ -stock Team_GetEdict(index) -{ - static teams[MAX_TEAMS] = { INVALID_ENT_REFERENCE, ... }; - - if (index < 0 || index > MAX_TEAMS) { - return -1; - } - - new edict = teams[index]; - if (Entity_IsValid(edict)) { - return edict; - } - - new bool:foundTeamManager = false; - - new maxEntities = GetMaxEntities(); - for (new entity=MaxClients+1; entity < maxEntities; entity++) { - - if (!IsValidEntity(entity)) { - continue; - } - - if (Entity_ClassNameMatches(entity, "team_manager", true)) { - foundTeamManager = true; - } - // Do not continue when no team managers are found anymore (for optimization) - else if (foundTeamManager) { - return -1; - } - else { - continue; - } - - new num = Team_EdictGetNum(entity); - - if (num >= 0 && num <= MAX_TEAMS) { - teams[num] = EntIndexToEntRef(entity); - } - - if (num == index) { - return entity; - } - } - - return -1; -} - -/* - * Trys to find a client in the specified team. - * This function is NOT random, it returns the first - * or the cached player (Use Client_GetRandom() instead). - * - * @param index Team Index. - * @return Client Index or -1 if no client was found in the specified team. - */ -stock Team_GetAnyClient(index) -{ - static client_cache[MAX_TEAMS] = -1; - new client; - - if (index > 0) { - client = client_cache[index]; - - if (client > 0 && client <= MaxClients) { - - if (IsClientInGame(client) && GetClientTeam(client) == index) { - return client; - } - } - else { - client = -1; - } - } - - for (client=1; client <= MaxClients; client++) { - - if (!IsClientInGame(client)) { - continue; - } - - if (GetClientTeam(client) != index) { - continue; - } - - client_cache[index] = client; - - return client; - } - - return -1; -} diff --git a/scripting/1.10/include/smlib/vehicles.inc b/scripting/1.10/include/smlib/vehicles.inc deleted file mode 100644 index d9fdebd..0000000 --- a/scripting/1.10/include/smlib/vehicles.inc +++ /dev/null @@ -1,141 +0,0 @@ -#if defined _smlib_vehicles_included - #endinput -#endif -#define _smlib_vehicles_included - -#include -#include -#include -#include - -/** - * Returns the vehicle's driver. - * If there is no driver in the vehicle, -1 is returned. - * - * @param vehicle Entity index. - * @return Client index, or -1 if there is no driver. - */ -stock Vehicle_GetDriver(vehicle) -{ - new m_hVehicle = GetEntPropEnt(vehicle, Prop_Send, "m_hPlayer"); - - return m_hVehicle; -} - -/** - * Returns whether there is a driver in the vehicle or not. - * - * @param vehicle Entity index. - * @return True if the vehicle has a driver, false otherwise - */ -stock bool:Vehicle_HasDriver(vehicle) -{ - return !(Vehicle_GetDriver(vehicle) == -1); -} - -/** - * Kicks the driver ouf of the vehicle - * - * @param vehicle Entity index. - * @return True on success, false otherwise. - */ -stock bool:Vehicle_ExitDriver(vehicle) -{ - if (!Vehicle_HasDriver(vehicle)) { - return false; - } - - return AcceptEntityInput(vehicle, "ExitVehicle"); -} - -/** - * Start's the vehicle's engine - * - * @param vehicle Entity index. - * @return True on success, false otherwise. - */ -stock bool:Vehicle_TurnOn(vehicle) -{ - - return AcceptEntityInput(vehicle, "TurnOn"); -} - -/** - * Shuts down the vehicle's engine - * - * @param vehicle Entity index. - * @return True on success, false otherwise. - */ -stock bool:Vehicle_TurnOff(vehicle) -{ - - return AcceptEntityInput(vehicle, "TurnOff"); -} - -/** - * Locks the vehicle. - * - * @param vehicle Entity index. - * @return True on success, false otherwise. - */ -stock bool:Vehicle_Lock(vehicle) -{ - - return AcceptEntityInput(vehicle, "Lock"); -} - -/** - * Unlocks the vehicle. - * - * @param vehicle Entity index. - * @return True on success, false otherwise. - */ -stock bool:Vehicle_Unlock(vehicle) -{ - - return AcceptEntityInput(vehicle, "Unlock"); -} - -/** - * Returns wether the entity is a valid vehicle or not. - * - * @param vehicle Entity index. - * @return True if it is a valid vehicle, false otherwise. - */ -stock bool:Vehicle_IsValid(vehicle) -{ - if (!Entity_IsValid(vehicle)) { - return false; - } - - return Entity_ClassNameMatches(vehicle, "prop_vehicle", true); -} - -/** - * Reads the vehicle script from a vehicle. - * This script contains all the vehicle settings like its speed - * and that stuff. - * - * @param vehicle Entity index. - * @param buffer String Buffer. - * @param size String Buffer size. - * @noreturn - */ -stock bool:Vehicle_GetScript(vehicle, String:buffer[], size) -{ - GetEntPropString(vehicle, Prop_Data, "m_vehicleScript", buffer, size); -} - -/** - * Sets the script of a vehicle. - * This script contains all the vehicle settings like its speed - * and that stuff. - * - * @param vehicle Entity index. - * @param buffer Vehicle Script path. - * @noreturn - */ -stock bool:Vehicle_SetScript(vehicle, String:script[]) -{ - DispatchKeyValue(vehicle, "vehiclescript", script); -} diff --git a/scripting/1.10/include/smlib/weapons.inc b/scripting/1.10/include/smlib/weapons.inc deleted file mode 100644 index 757119d..0000000 --- a/scripting/1.10/include/smlib/weapons.inc +++ /dev/null @@ -1,398 +0,0 @@ -#if defined _smlib_weapons_included - #endinput -#endif -#define _smlib_weapons_included - -#include -#include -#include - -#define MAX_WEAPON_OFFSET 64 -#define MAX_WEAPON_SLOTS 6 // hud item selection slots -#define MAX_WEAPON_POSITIONS 20 // max number of items within a slot -#define MAX_WEAPONS 48 // Max number of weapons availabl -#define WEAPON_NOCLIP -1 // clip sizes set to this tell the weapon it doesn't use a clip -#define MAX_AMMO_TYPES 32 -#define MAX_AMMO_SLOTS 32 // not really slots - -#define MAX_WEAPON_STRING 80 -#define MAX_WEAPON_PREFIX 16 -#define MAX_WEAPON_AMMO_NAME 32 - -/* - * Gets the owner (usually a client) of the weapon - * - * @param weapon Weapon Entity. - * @return Owner of the weapon or INVALID_ENT_REFERENCE if the weapon has no owner. - */ -stock Weapon_GetOwner(weapon) -{ - return GetEntPropEnt(weapon, Prop_Data, "m_hOwner"); -} - -/* - * Sets the owner (usually a client) of the weapon - * - * @param weapon Weapon Entity. - * @param entity Entity Index. - * @noreturn - */ -stock Weapon_SetOwner(weapon, entity) -{ - SetEntPropEnt(weapon, Prop_Data, "m_hOwner", entity); -} - -/* - * Checks whether the entity is a valid weapon or not. - * - * @param weapon Weapon Entity. - * @return True if the entity is a valid weapon, false otherwise. - */ -stock Weapon_IsValid(weapon) -{ - if (!IsValidEdict(weapon)) { - return false; - } - - return Entity_ClassNameMatches(weapon, "weapon_", true); -} - -/* - * Create's a weapon and spawns it in the world at the specified location. - * - * @param className Classname String of the weapon to spawn - * @param absOrigin Absolute Origin Vector where to spawn the 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]) -{ - new weapon = Entity_Create(className); - - if (weapon == INVALID_ENT_REFERENCE) { - return INVALID_ENT_REFERENCE; - } - - Entity_SetAbsOrigin(weapon, absOrigin); - Entity_SetAbsAngles(weapon, absAngles); - - DispatchSpawn(weapon); - - return weapon; -} - -/* - * Create's a weapon and spawns it in the world at the specified location. - * - * @param className Classname String of the weapon to spawn - * @param absOrigin Absolute Origin Vector where to spawn the weapon. - * @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[]) -{ - decl Float:absOrigin[3], Float:absAngles[3]; - Entity_GetAbsOrigin(client, absOrigin); - Entity_GetAbsAngles(client, absAngles); - - new weapon = Weapon_Create(className, absOrigin, absAngles); - - if (weapon == INVALID_ENT_REFERENCE) { - return INVALID_ENT_REFERENCE; - } - - Entity_SetOwner(weapon, client); - - return weapon; -} - -/* - * Gets the weapon's subtype. - * The subtype is only used when a player has multiple weapons of the same type. - * - * @param weapon Weapon Entity. - * @return Subtype of the weapon. - */ -stock Weapon_GetSubType(weapon) -{ - return GetEntProp(weapon, Prop_Data, "m_iSubType"); -} - -/* - * Is the weapon currently reloading ? - * - * @param weapon Weapon Entity. - * @return True if weapon is currently reloading, false if not. - */ -stock bool:Weapon_IsReloading(weapon) -{ - return bool:GetEntProp(weapon, Prop_Data, "m_bInReload"); -} - -/* - * Weapon m_iState - */ -#define WEAPON_IS_ONTARGET 0x40 -#define WEAPON_NOT_CARRIED 0 // Weapon is on the ground -#define WEAPON_IS_CARRIED_BY_PLAYER 1 // This client is carrying this weapon. -#define WEAPON_IS_ACTIVE 2 // This client is carrying this weapon and it's the currently held weapon - -/* - * Get's the state of the weapon. - * This returns whether the weapon is currently carried by a client, - * if it is active and if it is on a target. - * - * @param weapon Weapon Entity. - * @return Weapon State. - */ -stock Weapon_GetState(weapon) -{ - return GetEntProp(weapon, Prop_Data, "m_iState"); -} - -/* - * Returns whether the weapon can fire primary ammo under water. - * - * @param weapon Weapon Entity. - * @return True or False. - */ -stock bool:Weapon_FiresUnderWater(weapon) -{ - return bool:GetEntProp(weapon, Prop_Data, "m_bFiresUnderwater"); -} - -/* - * Sets if the weapon can fire primary ammo under water. - * - * @param weapon Weapon Entity. - * @param can True or False. - * @noreturn - */ -stock Weapon_SetFiresUnderWater(weapon, bool:can=true) -{ - SetEntProp(weapon, Prop_Data, "m_bFiresUnderwater", _:can); -} - -/* - * Returns whether the weapon can fire secondary ammo under water. - * - * @param weapon Weapon Entity. - * @return True or False. - */ -stock bool:Weapon_FiresUnderWaterAlt(weapon) -{ - return bool:GetEntProp(weapon, Prop_Data, "m_bAltFiresUnderwater"); -} - -/* - * Sets if the weapon can fire secondary ammo under water. - * - * @param weapon Weapon Entity. - * @param can True or False. - * @noreturn - */ -stock Weapon_SetFiresUnderWaterAlt(weapon, bool:can=true) -{ - SetEntProp(weapon, Prop_Data, "m_bAltFiresUnderwater", _:can); -} - -/* - * Gets the primary ammo Type (int offset) - * - * @param weapon Weapon Entity. - * @return Primary ammo type value. - */ -stock Weapon_GetPrimaryAmmoType(weapon) -{ - return GetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoType"); -} - -/* - * Sets the primary ammo Type (int offset) - * - * @param weapon Weapon Entity. - * @param type Primary ammo type value. - */ -stock Weapon_SetPrimaryAmmoType(weapon,type) -{ - SetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoType", type); -} - -/* - * Gets the secondary ammo Type (int offset) - * - * @param weapon Weapon Entity. - * @return Secondary ammo type value. - */ -stock Weapon_GetSecondaryAmmoType(weapon) -{ - return GetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoType"); -} - -/* - * Sets the secondary ammo Type (int offset) - * - * @param weapon Weapon Entity. - * @param type Secondary ammo type value. - */ -stock Weapon_SetSecondaryAmmoType(weapon,type) -{ - SetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoType", type); -} - -/* - * Gets the primary clip count of a weapon. - * - * @param weapon Weapon Entity. - * @return Primary Clip count. - */ -stock Weapon_GetPrimaryClip(weapon) -{ - return GetEntProp(weapon, Prop_Data, "m_iClip1"); -} - -/* - * Sets the primary clip count of a weapon. - * - * @param weapon Weapon Entity. - * @param value Clip Count value. - */ -stock Weapon_SetPrimaryClip(weapon, value) -{ - SetEntProp(weapon, Prop_Data, "m_iClip1", value); -} - -/* - * Gets the secondary clip count of a weapon. - * - * @param weapon Weapon Entity. - * @return Secondy Clip count. - */ -stock Weapon_GetSecondaryClip(weapon) -{ - return GetEntProp(weapon, Prop_Data, "m_iClip2"); -} - -/* - * Sets the secondary clip count of a weapon. - * - * @param weapon Weapon Entity. - * @param value Clip Count value. - */ -stock Weapon_SetSecondaryClip(weapon, value) -{ - SetEntProp(weapon, Prop_Data, "m_iClip2", value); -} - -/* - * Sets the primary & secondary clip count of a weapon. - * - * @param weapon Weapon Entity. - * @param primary Primary Clip Count value. - * @param secondary Primary Clip Count value. - */ -stock Weapon_SetClips(weapon, primary, secondary) -{ - Weapon_SetPrimaryClip(weapon, primary); - Weapon_SetSecondaryClip(weapon, secondary); -} - -/* - * Gets the primary ammo count of a weapon. - * This is only used when the weapon is not carried - * by a player to give a player ammo when he picks up - * the weapon. - * - * @param weapon Weapon Entity. - * @return Primary Ammo Count. - */ -stock Weapon_GetPrimaryAmmoCount(weapon) -{ - return GetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoCount"); -} - -/* - * Sets the primary ammo count of a weapon. - * This is only used when the weapon is not carried - * by a player to give a player ammo when he picks up - * the weapon. - * - * @param weapon Weapon Entity. - * @param value Primary Ammo Count. - * @noreturn - */ -stock Weapon_SetPrimaryAmmoCount(weapon, value) -{ - SetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoCount", value); -} - -/* - * Gets the secondary ammo count of a weapon. - * This is only used when the weapon is not carried - * by a player to give a player ammo when he picks up - * the weapon. - * - * @param weapon Weapon Entity. - * @return Secondary Ammo Count. - */ -stock Weapon_GetSecondaryAmmoCount(weapon) -{ - return GetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoCount"); -} - -/* - * Sets the secodary ammo count of a weapon. - * This is only used when the weapon is not carried - * by a player to give a player ammo when he picks up - * the weapon. - * - * @param weapon Weapon Entity. - * @param value Secondary Ammo Count. - * @noreturn - */ -stock Weapon_SetSecondaryAmmoCount(weapon, value) -{ - SetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoCount", value); -} - -/* - * Sets both, the primary & the secondary ammo count of a weapon. - * This is only used when the weapon is not carried - * by a player to give a player ammo when he picks up - * the weapon. - * - * @param weapon Weapon Entity. - * @value primary Primary Ammo Count. - * @value secondary Secondary Ammo Count. - * @noreturn - */ -stock Weapon_SetAmmoCounts(weapon, primary, secondary) -{ - Weapon_SetPrimaryAmmoCount(weapon, primary); - Weapon_SetSecondaryAmmoCount(weapon, secondary); -} - -/* - * Gets the Model Index of the weapon's view model. - * - * @param weapon Weapon Entity. - * @return View Model Index. - */ -stock Weapon_GetViewModelIndex(weapon) -{ - return GetEntProp(weapon, Prop_Data, "m_nViewModelIndex"); -} - -/* - * Sets the Model Index of the weapon's view model. - * You can get the Model Index by precaching a model with PrecacheModel(). - * - * @param weapon Weapon Entity. - * @param index Model Index. - * @noreturn - */ -stock Weapon_SetViewModelIndex(weapon, index) -{ - SetEntProp(weapon, Prop_Data, "m_nViewModelIndex", index); - ChangeEdictState(weapon, FindDataMapInfo(weapon, "m_nViewModelIndex")); -} diff --git a/scripting/1.10/include/smlib/world.inc b/scripting/1.10/include/smlib/world.inc deleted file mode 100644 index cd14b95..0000000 --- a/scripting/1.10/include/smlib/world.inc +++ /dev/null @@ -1,17 +0,0 @@ -#if defined _smlib_world_included - #endinput -#endif -#define _smlib_world_included - -#include - -/* - * Gets the world's max size - * - * @param vec Vector buffer - * @noreturn - */ -stock World_GetMaxs(Float:vec[3]) { - - GetEntPropVector(0, Prop_Data, "m_WorldMaxs", vec); -} diff --git a/scripting/1.10/include/smlib_kacr.inc b/scripting/1.10/include/smlib_kacr.inc deleted file mode 100644 index 1d72d22..0000000 --- a/scripting/1.10/include/smlib_kacr.inc +++ /dev/null @@ -1,31 +0,0 @@ -#if defined _smlib_included - #endinput -#endif -#define _smlib_included - -#define SMLIB_VERSION "0.9.7-B" // A slightly customized Version to compile againest SM 1.10 - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include diff --git a/scripting/1.10/spcomp.exe b/scripting/1.10/spcomp.exe deleted file mode 100644 index a270ebd..0000000 Binary files a/scripting/1.10/spcomp.exe and /dev/null differ diff --git a/scripting/1.8/kigen-ac_redux.sp b/scripting/1.8/kigen-ac_redux.sp index 2fd2f6c..b4127fe 100644 --- a/scripting/1.8/kigen-ac_redux.sp +++ b/scripting/1.8/kigen-ac_redux.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -30,7 +29,6 @@ #include #define REQUIRE_EXTENSIONS // #include // Required for the networking Module // Outdated TODO -#include #include @@ -64,7 +62,7 @@ bool g_bSourceBans, g_bSourceBansPP, g_bMapStarted; //- KACR Modules -// Note: The that ordering of these Includes is imporant -#include "kigen-ac_redux/translations.sp" // Translations Module - NEEDED FIRST +#include "kigen-ac_redux/translations.sp" // Translations Module - Needs to be first #include "kigen-ac_redux/client.sp" // Client Module #include "kigen-ac_redux/commands.sp" // Commands Module #include "kigen-ac_redux/cvars.sp" // CVar Module @@ -128,7 +126,7 @@ public void OnPluginStart() f_hTemp = FindConVar("sv_max_usercmd_future_ticks"); if (f_hTemp != INVALID_HANDLE) SetConVarInt(f_hTemp, 1); - + AutoExecConfig_ExecuteFile(); // Execute the Config AutoExecConfig_CleanFile(); // Cleanup the Config (slow process) @@ -210,7 +208,7 @@ public void OnPluginEnd() CloseHandle(g_hClearTimer); } -//- Map Functions -// +//- Map Hooks -// public void OnMapStart() { @@ -227,7 +225,7 @@ public void OnMapEnd() // RCON_OnMap(); // Currently unused } -//- Client Functions -// +//- Client Hooks -// public bool OnClientConnect(client, char[] rejectmsg, size) { @@ -340,10 +338,22 @@ public Action KACR_ValidateTimer(Handle timer, any client) return Plugin_Stop; } -public Action KACR_ClearTimer(Handle timer, any nothing) -{ - g_hDenyArray.Clear(); -} +// Version Checker for Handle Type TODO 1.8 +#if SOURCEMOD_V_MAJOR == 1 + #if SOURCEMOD_V_MINOR >= 10 // 1.10+ + public void KACR_ClearTimer(Handle timer, any nothing) + { + g_hDenyArray.Clear(); + } + + #else // 1.9 and older + public Action KACR_ClearTimer(Handle timer, any nothing) + { + g_hDenyArray.Clear(); + } + + #endif +#endif //- ConVar Hook -// diff --git a/scripting/1.8/kigen-ac_redux/client.sp b/scripting/1.8/kigen-ac_redux/client.sp index 397b9f0..ccac45c 100644 --- a/scripting/1.8/kigen-ac_redux/client.sp +++ b/scripting/1.8/kigen-ac_redux/client.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -51,7 +50,7 @@ Client_OnPluginStart() HookEvent("player_spawn", Client_PlayerSpawn); HookEvent("player_death", Client_PlayerDeath); HookEvent("round_start", Client_RoundStart); - HookEvent("round_end", Client_CleanEvent); + HookEvent("round_end", Client_RoundEnd); RegConsoleCmd("joinclass", Client_JoinClass); } @@ -159,7 +158,7 @@ public Action Client_Autobuy(client, args) } -//- Map -// +//- Map Hooks -// /*Client_OnMapStart() // Currently unused { @@ -173,27 +172,27 @@ Client_OnMapEnd() strcopy(g_sClientConnections[i], 64, ""); if (hGame == Engine_CSS || hGame == Engine_CSGO) - Client_CleanEvent(INVALID_HANDLE, "", false); + Client_CleanEvent(); } //- Timers -// -public Action Client_AntiSpamConnectTimer(Handle timer, any i) +public Action Client_AntiSpamConnectTimer(Handle hTimer, any iClient) { - strcopy(g_sClientConnections[i], 64, ""); + strcopy(g_sClientConnections[iClient], 64, ""); return Plugin_Stop; } //- Hooks -// -public Action Client_PlayerSpawn(Handle event, const char[] name, bool dontBroadcast) +public Action Client_PlayerSpawn(Event hEvent, const char[] cName, bool bDontBroadcast) { if (!g_bClientEnable || !g_bClientAntiRespawn) return Plugin_Continue; - int client = GetClientOfUserId(GetEventInt(event, "userid")); + int client = GetClientOfUserId(hEvent.GetInt("userid")); char f_sAuthID[64]; if (client <= 0 || GetClientTeam(client) < 2 || !GetClientAuthId(client, AuthId_Steam2, f_sAuthID, sizeof(f_sAuthID))) return Plugin_Continue; @@ -203,12 +202,12 @@ public Action Client_PlayerSpawn(Handle event, const char[] name, bool dontBroad return Plugin_Continue } -public Action Client_PlayerDeath(Handle event, const char[] name, bool dontBroadcast) +public Action Client_PlayerDeath(Event hEvent, const char[] cName, bool bDontBroadcast) { if (!g_bClientEnable || !g_bClientAntiRespawn) return Plugin_Continue; - int client = GetClientOfUserId(GetEventInt(event, "userid")); + int client = GetClientOfUserId(hEvent.GetInt("userid")); char f_sAuthID[64]; if (client <= 0 || !GetClientAuthId(client, AuthId_Steam2, f_sAuthID, sizeof(f_sAuthID))) return Plugin_Continue; @@ -218,24 +217,14 @@ public Action Client_PlayerDeath(Handle event, const char[] name, bool dontBroad return Plugin_Continue } -public Action Client_RoundStart(Handle event, const char[] name, bool dontBroadcast) +public void Client_RoundStart(Event hEvent, const char[] cName, bool bDontBroadcast) { g_bClientMapStarted = true; } -public Action Client_CleanEvent(Handle event, const char[] name, bool dontBroadcast) +public void Client_RoundEnd(Handle hEvent, const char[] cName, bool bDontBroadcast) { - CloseHandle(g_hClientSpawned); // Really needed? We could just clear it? - g_hClientSpawned = new StringMap(); - - for (int i = 1; i <= MaxClients; i++) - { - if (g_bInGame[i] && g_iClientClass[i] != -1) - { - FakeClientCommandEx(i, "joinclass %d", g_iClientClass[i]); - g_iClientClass[i] = -1; - } - } + Client_CleanEvent(); } bool Client_OnClientConnect(iClient, char[] rejectmsg, size) @@ -440,4 +429,22 @@ public void Client_NameProtectChange(Handle convar, const char[] oldValue, const public void Client_AntiSpamConnectChange(Handle convar, const char[] oldValue, const char[] newValue) { g_fClientAntiSpamConnect = GetConVarFloat(convar); -} \ No newline at end of file +} + + +//- Functions -// + +public void Client_CleanEvent() +{ + CloseHandle(g_hClientSpawned); // Really needed? We could just clear it? + g_hClientSpawned = new StringMap(); + + for (int i = 1; i <= MaxClients; i++) + { + if (g_bInGame[i] && g_iClientClass[i] != -1) + { + FakeClientCommandEx(i, "joinclass %d", g_iClientClass[i]); + g_iClientClass[i] = -1; + } + } +} \ No newline at end of file diff --git a/scripting/1.8/kigen-ac_redux/commands.sp b/scripting/1.8/kigen-ac_redux/commands.sp index dbf207b..450bfec 100644 --- a/scripting/1.8/kigen-ac_redux/commands.sp +++ b/scripting/1.8/kigen-ac_redux/commands.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/scripting/1.8/kigen-ac_redux/cvars.sp b/scripting/1.8/kigen-ac_redux/cvars.sp index a083a2a..dcca3e3 100644 --- a/scripting/1.8/kigen-ac_redux/cvars.sp +++ b/scripting/1.8/kigen-ac_redux/cvars.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -956,7 +955,7 @@ public void CVars_EnableChange(Handle convar, const char[] oldValue, const char[ * @param iImportance Priority (PRIORITY_...) * @param cAlternative URL to show to the Player */ -bool CVars_AddCVar(char[] cConVar, f_iComparisonType, f_iAction, const char[] f_sValue, float f_fValue2, f_iImportance, const char f_sAlternative[] = "") +bool CVars_AddCVar(char[] cConVar, f_iComparisonType, f_iAction, const char[] f_sValue, float f_fValue2, f_iImportance, const char[] f_sAlternative = "") { Handle f_hConVar = INVALID_HANDLE, f_hArray; diff --git a/scripting/1.8/kigen-ac_redux/eyetest.sp b/scripting/1.8/kigen-ac_redux/eyetest.sp index 2689629..f3a2560 100644 --- a/scripting/1.8/kigen-ac_redux/eyetest.sp +++ b/scripting/1.8/kigen-ac_redux/eyetest.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -194,8 +193,8 @@ public void Eyetest_AntiWallChange(Handle convar, const char[] oldValue, const c } for (int i = 1; i <= MaxClients; i++) - if (Client_IsValid(i, true)) - if (IsPlayerAlive(i) && !g_bHooked[i]) // We do not use the Arrays here since its OnPluginStart and the Players may havent been checked TODO: is that correct? + if (IsClientInGame(i) && !IsFakeClient(i)) // g_bInGame[i] && !g_bIsFake[i]) - We do not use the Arrays here since its OnPluginStart and the Players may havent been checked. This can be fixed by populating the arrays OnPluginLoad TODO + if (IsPlayerAlive(i) && !g_bHooked[i]) Eyetest_Hook(i); Status_Report(g_iAntiWHStatus, KACR_ON); @@ -213,27 +212,27 @@ public void Eyetest_AntiWallChange(Handle convar, const char[] oldValue, const c g_bAntiWall = f_bEnabled; } -public Action Eyetest_PlayerSpawn(Handle event, const char[] name, bool dontBroadcast) +public void Eyetest_PlayerSpawn(Event hEvent, const char[] cName, bool bDontBroadcast) { - int client = GetClientOfUserId(GetEventInt(event, "userid")); - if (client && GetClientTeam(client) > 1) + int iClient = GetClientOfUserId(hEvent.GetInt("userid")); + if (iClient && GetClientTeam(iClient) > 1) { - if (!IsFakeClient(client)) - g_bShouldProcess[client] = true; + if (!IsFakeClient(iClient)) + g_bShouldProcess[iClient] = true; - if (g_bAntiWall && !g_bHooked[client]) - Eyetest_Hook(client); + if (g_bAntiWall && !g_bHooked[iClient]) + Eyetest_Hook(iClient); } } -public Action Eyetest_PlayerDeath(Handle event, const char[] name, bool dontBroadcast) +public void Eyetest_PlayerDeath(Event hEvent, const char[] cName, bool bDontBroadcast) { - int client = GetClientOfUserId(GetEventInt(event, "userid")); - if (client) + int iClient = GetClientOfUserId(hEvent.GetInt("userid")); + if (iClient) { - g_bShouldProcess[client] = false; - if (g_bAntiWall && g_bHooked[client]) - Eyetest_Unhook(client); + g_bShouldProcess[iClient] = false; + if (g_bAntiWall && g_bHooked[iClient]) + Eyetest_Unhook(iClient); } } @@ -259,21 +258,21 @@ public Action Eyetest_WeaponTransmit(entity, client) return Plugin_Stop; } -public Action Eyetest_Equip(client, weapon) // The Player Picked up a Weapon? Lets bind the Entity ID to the Player ID +public void Eyetest_Equip(iClient, iWeapon) // The Player Picked up a Weapon? Lets bind the Entity ID to the Player ID { - if (g_iWeaponOwner[weapon] == 0) // The Weapon has no owner yet? + if (g_iWeaponOwner[iWeapon] == 0) // The Weapon has no owner yet? { - g_iWeaponOwner[weapon] = client; - SDKHook(weapon, SDKHook_SetTransmit, Eyetest_WeaponTransmit); + g_iWeaponOwner[iWeapon] = iClient; + SDKHook(iWeapon, SDKHook_SetTransmit, Eyetest_WeaponTransmit); } } -public Action Eyetest_Drop(client, weapon) +public void Eyetest_Drop(iClient, iWeapon) { - if (weapon > 0 && g_iWeaponOwner[weapon] > 0) // Is a Player linked to the Entity? Else we do not Care // Check if the Weapon exists first, it may got deleted in the same Frame, Bugfix for #37 + if (iWeapon > 0 && g_iWeaponOwner[iWeapon] > 0) // Is a Player linked to the Entity? Else we do not Care // Check if the Weapon exists first, it may got deleted in the same Frame, Bugfix for #37 { - g_iWeaponOwner[weapon] = 0; - SDKUnhook(weapon, SDKHook_SetTransmit, Eyetest_WeaponTransmit); + g_iWeaponOwner[iWeapon] = 0; + SDKUnhook(iWeapon, SDKHook_SetTransmit, Eyetest_WeaponTransmit); } } diff --git a/scripting/1.8/kigen-ac_redux/network #Unused.sp b/scripting/1.8/kigen-ac_redux/network #Unused.sp index cd826a6..4fe8ae2 100644 --- a/scripting/1.8/kigen-ac_redux/network #Unused.sp +++ b/scripting/1.8/kigen-ac_redux/network #Unused.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/scripting/1.8/kigen-ac_redux/rcon.sp b/scripting/1.8/kigen-ac_redux/rcon.sp index 342443b..d1a4ed6 100644 --- a/scripting/1.8/kigen-ac_redux/rcon.sp +++ b/scripting/1.8/kigen-ac_redux/rcon.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/scripting/1.8/kigen-ac_redux/status.sp b/scripting/1.8/kigen-ac_redux/status.sp index 58186cd..257aa74 100644 --- a/scripting/1.8/kigen-ac_redux/status.sp +++ b/scripting/1.8/kigen-ac_redux/status.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/scripting/1.8/kigen-ac_redux/stocks.sp b/scripting/1.8/kigen-ac_redux/stocks.sp index 6fdf2de..28bdb22 100644 --- a/scripting/1.8/kigen-ac_redux/stocks.sp +++ b/scripting/1.8/kigen-ac_redux/stocks.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/scripting/1.8/kigen-ac_redux/translations.sp b/scripting/1.8/kigen-ac_redux/translations.sp index da15f7c..a185920 100644 --- a/scripting/1.8/kigen-ac_redux/translations.sp +++ b/scripting/1.8/kigen-ac_redux/translations.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/scripting/1.10/include/admin.inc b/scripting/latest/include/admin.inc similarity index 94% rename from scripting/1.10/include/admin.inc rename to scripting/latest/include/admin.inc index d365dd2..3fbf886 100644 --- a/scripting/1.10/include/admin.inc +++ b/scripting/latest/include/admin.inc @@ -191,6 +191,20 @@ methodmap AdminId { // @param enabled True to enable, false to disable. public native void SetFlag(AdminFlag flag, bool enabled); + // Sets multiple bitwise flags to be enabled/disabled on an admin. + // + // @param flags Bitwise admin flags (ADMFLAG_*). + // @param enabled True to set the flag, false to unset/disable. + public void SetBitFlags(int flags, bool enabled) + { + AdminFlag flagArray[AdminFlags_TOTAL]; + int num = FlagBitsToArray(flags, flagArray, sizeof(flagArray)); + for (int i = 0; i < num; i++) + { + this.SetFlag(flagArray[i], enabled); + } + } + // Returns whether or not a flag is enabled on an admin. // // @param flag Admin flag to use. @@ -278,6 +292,20 @@ methodmap GroupId { // @param enabled True to set the flag, false to unset/disable. public native void SetFlag(AdminFlag flag, bool enabled); + // Adds or removes multiple bitwise flags from a group's flag set. + // + // @param flags Bitwise admin flags (ADMFLAG_*). + // @param enabled True to set the flag, false to unset/disable. + public void SetBitFlags(int flags, bool enabled) + { + AdminFlag flagArray[AdminFlags_TOTAL]; + int num = FlagBitsToArray(flags, flagArray, sizeof(flagArray)); + for (int i = 0; i < num; i++) + { + this.SetFlag(flagArray[i], enabled); + } + } + // Returns the flag set that is added to users from this group. // // @return Bitstring containing the flags enabled. @@ -773,3 +801,32 @@ stock bool BitToFlag(int bit, AdminFlag &flag) return false; } + +/** + * Converts a bit string to a string of flag characters. + * + * @param bits Bit string containing the flags. + * @param flags Output array to write a string of flag characters. + * @param maxSize Maximum size of the string array. + * @return Number of flag characters written. + */ +stock int FlagBitsToString(const int bits, char[] flags, const int maxSize) +{ + AdminFlag array[AdminFlags_TOTAL]; + int numFlags = FlagBitsToArray(bits, array, AdminFlags_TOTAL); + if (numFlags > maxSize) + { + numFlags = maxSize; + } + int i, c, numId = 0; + for (i = 0; i < numFlags; ++i) + { + if(FindFlagChar(array[i], c)) + { + flags[numId++] = c; + } + } + flags[numId] = '\0'; + + return numId; +} diff --git a/scripting/1.10/include/adminmenu.inc b/scripting/latest/include/adminmenu.inc similarity index 100% rename from scripting/1.10/include/adminmenu.inc rename to scripting/latest/include/adminmenu.inc diff --git a/scripting/1.10/include/adt.inc b/scripting/latest/include/adt.inc similarity index 100% rename from scripting/1.10/include/adt.inc rename to scripting/latest/include/adt.inc diff --git a/scripting/1.10/include/adt_array.inc b/scripting/latest/include/adt_array.inc similarity index 90% rename from scripting/1.10/include/adt_array.inc rename to scripting/latest/include/adt_array.inc index c8fd919..ad9e252 100644 --- a/scripting/1.10/include/adt_array.inc +++ b/scripting/latest/include/adt_array.inc @@ -74,7 +74,7 @@ methodmap ArrayList < Handle { // Clones an array, returning a new handle with the same size and data. // This should NOT be confused with CloneHandle. This is a completely new - // handle with the same data but no relation to the original. It should + // handle with the same data but no relation to the original. It should be // closed when no longer needed. // // @return New handle to the cloned array object @@ -129,9 +129,11 @@ methodmap ArrayList < Handle { // @param index Index in the array. // @param buffer Buffer to copy to. // @param maxlength Maximum size of the buffer. + // @param block Optionally specify which block to read from + // (useful if the blocksize > 0). // @return Number of characters copied. // @error Invalid index. - public native int GetString(int index, char[] buffer, int maxlength); + public native int GetString(int index, char[] buffer, int maxlength, int block=0); // Retrieves an array of cells from an array. // @@ -139,9 +141,11 @@ methodmap ArrayList < 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. + // @param block Optionally specify which block to read from + // (useful if the blocksize > 0). // @return Number of cells copied. // @error Invalid index. - public native int GetArray(int index, any[] buffer, int size=-1); + public native int GetArray(int index, any[] buffer, int size=-1, int block=0); // Sets a cell value in an array. // @@ -157,9 +161,13 @@ methodmap ArrayList < Handle { // // @param index Index in the array. // @param value String value to set. + // @param size If not set, assumes the buffer size is equal to the + // blocksize. Otherwise, the size passed is used. + // @param block Optionally specify which block to write to + // (useful if the blocksize > 0). // @return Number of characters copied. // @error Invalid index. - public native void SetString(int index, const char[] value); + public native int SetString(int index, const char[] value, int size=-1, int block=0); // Sets an array of cells in an array. // @@ -167,9 +175,11 @@ methodmap ArrayList < Handle { // @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. + // @param block Optionally specify which block to write to + // (useful if the blocksize > 0). // @return Number of cells copied. // @error Invalid index. - public native void SetArray(int index, const any[] values, int size=-1); + public native int SetArray(int index, const any[] values, int size=-1, int block=0); // Shifts an array up. All array contents after and including the given // index are shifted up by one, and the given index is then "free." @@ -198,8 +208,9 @@ methodmap ArrayList < Handle { // the string cannot be located, -1 will be returned. // // @param item String to search for + // @param block Optionally which block to search in // @return Array index, or -1 on failure - public native int FindString(const char[] item); + public native int FindString(const char[] item, int block=0); // Returns the index for the first occurrence of the provided value. If the // value cannot be located, -1 will be returned. @@ -349,10 +360,12 @@ native any GetArrayCell(Handle array, int index, int block=0, bool asChar=false) * @param index Index in the array. * @param buffer Buffer to copy to. * @param maxlength Maximum size of the buffer. + * @param block Optionally specify which block to read from + * (useful if the blocksize > 0). * @return Number of characters copied. * @error Invalid Handle or invalid index. */ -native int GetArrayString(Handle array, int index, char[] buffer, int maxlength); +native int GetArrayString(Handle array, int index, char[] buffer, int maxlength, int block=0); /** * Retrieves an array of cells from an array. @@ -362,10 +375,12 @@ native int GetArrayString(Handle array, int index, char[] buffer, int maxlength) * @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. + * @param block Optionally specify which block to read from + * (useful if the blocksize > 0). * @return Number of cells copied. * @error Invalid Handle or invalid index. */ -native int GetArrayArray(Handle array, int index, any[] buffer, int size=-1); +native int GetArrayArray(Handle array, int index, any[] buffer, int size=-1, int block=0); /** * Sets a cell value in an array. @@ -386,10 +401,14 @@ native void SetArrayCell(Handle array, int index, any value, int block=0, bool a * @param array Array Handle. * @param index Index in the array. * @param value String value to set. + * @param size If not set, assumes the buffer size is equal to the + * blocksize. Otherwise, the size passed is used. + * @param block Optionally specify which block to write to + * (useful if the blocksize > 0). * @return Number of characters copied. * @error Invalid Handle or invalid index. */ -native int SetArrayString(Handle array, int index, const char[] value); +native int SetArrayString(Handle array, int index, const char[] value, int size=-1, int block=0); /** * Sets an array of cells in an array. @@ -399,10 +418,12 @@ native int SetArrayString(Handle array, int index, const char[] value); * @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. + * @param block Optionally specify which block to write to + * (useful if the blocksize > 0). * @return Number of cells copied. * @error Invalid Handle or invalid index. */ -native int SetArrayArray(Handle array, int index, const any[] values, int size=-1); +native int SetArrayArray(Handle array, int index, const any[] values, int size=-1, int block=0); /** * Shifts an array up. All array contents after and including the given @@ -442,10 +463,11 @@ native void SwapArrayItems(Handle array, int index1, int index2); * * @param array Array Handle. * @param item String to search for + * @param block Optionally which block to search in * @return Array index, or -1 on failure * @error Invalid Handle */ -native int FindStringInArray(Handle array, const char[] item); +native int FindStringInArray(Handle array, const char[] item, int block=0); /** * Returns the index for the first occurrence of the provided value. If the value diff --git a/scripting/1.10/include/adt_stack.inc b/scripting/latest/include/adt_stack.inc similarity index 83% rename from scripting/1.10/include/adt_stack.inc rename to scripting/latest/include/adt_stack.inc index 9be8857..c1cd914 100644 --- a/scripting/1.10/include/adt_stack.inc +++ b/scripting/latest/include/adt_stack.inc @@ -54,6 +54,17 @@ methodmap ArrayStack < Handle // new Array[X][32] public native ArrayStack(int blocksize=1); + // Clears a stack of all entries. + public native void Clear(); + + // Clones an stack, returning a new handle with the same size and data. + // This should NOT be confused with CloneHandle. This is a completely new + // handle with the same data but no relation to the original. It should + // closed when no longer needed. + // + // @return New handle to the cloned stack object + public native ArrayStack Clone(); + // Pushes a value onto the end of the stack, adding a new index. // // This may safely be used even if the stack has a blocksize @@ -84,19 +95,37 @@ methodmap ArrayStack < Handle // @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. + // @return Value popped from the stack. // @error The stack is empty. public native any Pop(int block=0, bool asChar=false); + // Reads a cell value from a stack without removing it. + // + // @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 from the stack. + // @error The stack is empty. + public native any Top(int block=0, bool asChar=false); + // Pops a string value from a stack. // // @param buffer Buffer to store string. // @param maxlength Maximum size of the buffer. - // @oaram written Number of characters written to buffer, not including + // @param written Number of characters written to buffer, not including // the null terminator. // @error The stack is empty. public native void PopString(char[] buffer, int maxlength, int &written = 0); + // Reads a string value from a stack without removing it. + // + // @param buffer Buffer to store string. + // @param maxlength Maximum size of the buffer. + // @param written Number of characters written to buffer, not including + // the null terminator. + // @error The stack is empty. + public native void TopString(char[] buffer, int maxlength, int &written = 0); + // Pops an array of cells from a stack. // // @param buffer Buffer to store the array in. @@ -105,6 +134,14 @@ methodmap ArrayStack < Handle // @error The stack is empty. public native void PopArray(any[] buffer, int size=-1); + // Reads an array of cells from a stack without removing it. + // + // @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. + // @error The stack is empty. + public native void TopArray(any[] buffer, int size=-1); + // Returns true if the stack is empty, false otherwise. property bool Empty { public native get(); @@ -114,6 +151,10 @@ methodmap ArrayStack < Handle property int BlockSize { public native get(); } + + property int Length { + public native get(); + } }; /** diff --git a/scripting/1.10/include/adt_trie.inc b/scripting/latest/include/adt_trie.inc similarity index 95% rename from scripting/1.10/include/adt_trie.inc rename to scripting/latest/include/adt_trie.inc index 2d262c4..9e9eb34 100644 --- a/scripting/1.10/include/adt_trie.inc +++ b/scripting/latest/include/adt_trie.inc @@ -52,6 +52,14 @@ methodmap StringMap < Handle // The StringMap must be freed via delete or CloseHandle(). public native StringMap(); + // Clones a string map, returning a new handle with the same size and data. + // This should NOT be confused with CloneHandle. This is a completely new + // handle with the same data but no relation to the original. It should be + // closed when no longer needed with delete or CloseHandle(). + // + // @return New handle to the cloned string map + public native StringMap Clone(); + // Sets a value in a hash map, either inserting a new entry or replacing an old one. // // @param key Key string. @@ -87,7 +95,6 @@ methodmap StringMap < Handle // 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. @@ -106,6 +113,12 @@ methodmap StringMap < Handle // as a value or array (not a string). public native bool GetString(const char[] key, char[] value, int max_size, int &size=0); + // Checks whether a key is present in a Map. + // + // @param key Key string. + // @return True if the key has been found, else false. + public native bool ContainsKey(const char[] key); + // Removes a key entry from a Map. // // @param key Key string. diff --git a/scripting/1.10/include/autoexecconfig_kacr.inc b/scripting/latest/include/autoexecconfig_kacr.inc similarity index 98% rename from scripting/1.10/include/autoexecconfig_kacr.inc rename to scripting/latest/include/autoexecconfig_kacr.inc index 99333e6..9caa758 100644 --- a/scripting/1.10/include/autoexecconfig_kacr.inc +++ b/scripting/latest/include/autoexecconfig_kacr.inc @@ -1,6 +1,6 @@ /** * AutoExecConfig for Kigen AC Redux - * (A slightly modified Version to fit our Needs) + * (A slightly modified version to fit our needs) * * Copyright (C) 2013-2017 Impact * @@ -217,7 +217,7 @@ stock ConVar AutoExecConfig_CreateConVar(const char[] name, const char[] default // We only add this convar if it doesn't exist, or the file doesn't exist and it should be auto-generated if(g_iLastFindResult == AUTOEXEC_FIND_NOT_FOUND || (g_iLastFindResult == AUTOEXEC_FIND_FILE_NOT_FOUND && g_bCreateFile)) - g_iLastAppendResult = AutoExecConfig_AppendValue(name, defaultValue, description, flags, hasMin, min, hasMax, max); + g_iLastAppendResult = AutoExecConfig_AppendValue(name, defaultValue, description, hasMin, min, hasMax, max); } // Create the convar @@ -286,14 +286,13 @@ stock static int AutoExecConfig_FormatFileName(char[] buffer, int size, char[] f * @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 Returns one of the AUTOEXEC_APPEND values */ -stock int AutoExecConfig_AppendValue(const char[] name, const char[] defaultValue, const char[] description, int flags, bool hasMin, float min, bool hasMax, float max) +stock int AutoExecConfig_AppendValue(const char[] name, const char[] defaultValue, const char[] description, bool hasMin, float min, bool hasMax, float max) { if(strlen(g_sConfigFile) < 1) // No config set return AUTOEXEC_NO_CONFIG; diff --git a/scripting/1.10/include/banning.inc b/scripting/latest/include/banning.inc similarity index 100% rename from scripting/1.10/include/banning.inc rename to scripting/latest/include/banning.inc diff --git a/scripting/1.10/include/basecomm.inc b/scripting/latest/include/basecomm.inc similarity index 100% rename from scripting/1.10/include/basecomm.inc rename to scripting/latest/include/basecomm.inc diff --git a/scripting/1.10/include/bitbuffer.inc b/scripting/latest/include/bitbuffer.inc similarity index 100% rename from scripting/1.10/include/bitbuffer.inc rename to scripting/latest/include/bitbuffer.inc diff --git a/scripting/1.10/include/clientprefs.inc b/scripting/latest/include/clientprefs.inc similarity index 84% rename from scripting/1.10/include/clientprefs.inc rename to scripting/latest/include/clientprefs.inc index 218d033..538145e 100644 --- a/scripting/1.10/include/clientprefs.inc +++ b/scripting/latest/include/clientprefs.inc @@ -74,6 +74,9 @@ enum CookieMenuAction CookieMenuAction_SelectOption = 1 }; +#define COOKIE_MAX_NAME_LENGTH 30 /**< Maximum Cookie name length. */ +#define COOKIE_MAX_DESCRIPTION_LENGTH 255 /**< Maximum Cookie description length. */ + /** * Cookie Menu Callback prototype * @@ -119,7 +122,8 @@ methodmap Cookie < Handle { // no longer needed. // // @param name Name of cookie to find. - // @return A handle to the cookie if it is found. INVALID_HANDLE otherwise. + // @return A handle to the cookie if it is found, null otherwise. + public static native Cookie Find(const char[] name); // Set the value of a Client preference cookie. @@ -128,6 +132,31 @@ methodmap Cookie < Handle { // @param value String value to set. // @error Invalid cookie handle or invalid client index. public native void Set(int client, const char[] value); + + // Set the integer value of a Client preference cookie. + // + // @param client Client index. + // @param value Integer value to set. + // @error Invalid cookie handle or invalid client index. + public void SetInt(int client, int value) { + char sValue[12]; + IntToString(value, sValue, sizeof(sValue)); + + this.Set(client, sValue); + } + + // Set the float value of a Client preference cookie. + // + // @param client Client index. + // @param value Float value to set. + // @error Invalid cookie handle or invalid client index. + public void SetFloat(int client, float value) { + char sValue[32]; + FloatToString(value, sValue, sizeof(sValue)); + + this.Set(client, sValue); + } + // Retrieve the value of a Client preference cookie. // @@ -137,7 +166,43 @@ methodmap Cookie < Handle { // @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. + // Retrieve the integer value of a Client preference cookie. + // + // @param client Client index. + // @return Integer value of cookie + // @error Invalid cookie handle or invalid client index. + public int GetInt(int client, int defaultValue = 0) + { + char buffer[12]; + this.Get(client, buffer, sizeof(buffer)); + + int value; + if (!StringToIntEx(buffer, value)) + { + value = defaultValue; + } + return value; + } + + // Retrieve the float value of a Client preference cookie. + // + // @param client Client index. + // @return Float value of cookie + // @error Invalid cookie handle or invalid client index. + public float GetFloat(int client, float defaultValue = 0.0) + { + char buffer[32]; + this.Get(client, buffer, sizeof(buffer)); + + float value; + if (!StringToFloatEx(buffer, value)) + { + value = defaultValue; + } + return value; + } + + // Set 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. @@ -183,7 +248,7 @@ methodmap Cookie < Handle { * exists, a handle to it will still be returned. * @error Cookie name is blank. */ -native Handle RegClientCookie(const char[] name, const char[] description, CookieAccess access); +native Cookie RegClientCookie(const char[] name, const char[] description, CookieAccess access); /** * Searches for a Client preference cookie. @@ -192,9 +257,10 @@ native Handle RegClientCookie(const char[] name, const char[] description, Cooki * no longer needed. * * @param name Name of cookie to find. - * @return A handle to the cookie if it is found. INVALID_HANDLE otherwise. + * @return A handle to the cookie if it is found, null otherwise. + */ -native Handle FindClientCookie(const char[] name); +native Cookie FindClientCookie(const char[] name); /** * Set the value of a Client preference cookie. @@ -326,7 +392,11 @@ public Extension __ext_cprefs = { name = "Client Preferences", file = "clientprefs.ext", +#if defined AUTOLOAD_EXTENSIONS autoload = 1, +#else + autoload = 0, +#endif #if defined REQUIRE_EXTENSIONS required = 1, #else diff --git a/scripting/1.10/include/clients.inc b/scripting/latest/include/clients.inc similarity index 95% rename from scripting/1.10/include/clients.inc rename to scripting/latest/include/clients.inc index 9a2946a..02ccba8 100644 --- a/scripting/1.10/include/clients.inc +++ b/scripting/latest/include/clients.inc @@ -69,8 +69,9 @@ 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 MAXPLAYERS 101 /**< Maximum number of players SourceMod supports */ #define MAX_NAME_LENGTH 128 /**< Maximum buffer required to store a client name */ +#define MAX_AUTHID_LENGTH 64 /**< Maximum buffer required to store any AuthID type */ public const int MaxClients; /**< Maximum number of players the server supports (dynamic) */ @@ -214,6 +215,18 @@ forward Action OnClientPreAdminCheck(int client); */ forward void OnClientPostAdminFilter(int client); +/** + * Called directly before the server enters hibernation. + * This is your last chance to do anything in the plugin before + * hibernation occurs, as SV_Frame will no longer be called. + */ +forward void OnServerEnterHibernation(); + +/** + * Called directly before the server leaves hibernation. + */ +forward void OnServerExitHibernation(); + /** * Called once a client is authorized and fully in-game, and * after all post-connection authorizations have been performed. @@ -225,6 +238,14 @@ forward void OnClientPostAdminFilter(int client); */ forward void OnClientPostAdminCheck(int client); +/** + * Called when the language was received from the player. + * + * @param client Client index. + * @param language Language number. + */ +forward void OnClientLanguageChanged(int client, int language); + /** * This function is deprecated. Use the MaxClients variable instead. * @@ -347,6 +368,7 @@ native int GetClientUserId(int client); * * @param client Player index. * @return True if player is connected to the server, false otherwise. + * @error Invalid client index. */ native bool IsClientConnected(int client); @@ -384,6 +406,7 @@ stock bool IsPlayerInGame(int client) * * @param client Player index. * @return True if player has been authenticated, false otherwise. + * @error Invalid client index. */ native bool IsClientAuthorized(int client); @@ -392,6 +415,7 @@ native bool IsClientAuthorized(int client); * * @param client Player index. * @return True if player is a fake client, false otherwise. + * @error Invalid client index, or client not connected. */ native bool IsFakeClient(int client); @@ -400,6 +424,7 @@ native bool IsFakeClient(int client); * * @param client Player index. * @return True if player is the SourceTV bot, false otherwise. + * @error Invalid client index, or client not connected. */ native bool IsClientSourceTV(int client); @@ -408,6 +433,7 @@ native bool IsClientSourceTV(int client); * * @param client Player index. * @return True if player is the Replay bot, false otherwise. + * @error Invalid client index, or client not connected. */ native bool IsClientReplay(int client); @@ -416,6 +442,7 @@ native bool IsClientReplay(int client); * * @param client Player index. * @return True if player is an observer, false otherwise. + * @error Invalid client index, client not in game, or no mod support. */ native bool IsClientObserver(int client); @@ -496,6 +523,7 @@ native void RemoveUserFlags(int client, AdminFlag ...); * * @param client Player's index. * @param flags Bitstring of flags to set on client. + * @error Invalid client index, or client not connected. */ native void SetUserFlagBits(int client, int flags); @@ -548,6 +576,7 @@ native void NotifyPostAdminCheck(int client); * * @param name Name to use. * @return Client index on success, 0 otherwise. + * @error No map is active. */ native int CreateFakeClient(const char[] name); @@ -791,7 +820,7 @@ native void KickClientEx(int client, const char[] format="", any ...); * * @param client Client index. * @param team Mod-specific team index. - * @error Invalid client index, client not connected, or lack of + * @error Invalid client index, client not in game, or lack of * mod support. */ native void ChangeClientTeam(int client, int team); diff --git a/scripting/1.10/include/commandfilters.inc b/scripting/latest/include/commandfilters.inc similarity index 94% rename from scripting/1.10/include/commandfilters.inc rename to scripting/latest/include/commandfilters.inc index 714502b..de8ebb1 100644 --- a/scripting/1.10/include/commandfilters.inc +++ b/scripting/latest/include/commandfilters.inc @@ -132,16 +132,23 @@ stock void ReplyToTargetError(int client, int reason) } } +#define FEATURECAP_MULTITARGETFILTER_CLIENTPARAM "SourceMod MultiTargetFilter ClientParam" + /** * Adds clients to a multi-target filter. * * @param pattern Pattern name. * @param clients Array to fill with unique, valid client indexes. + * @param client Client that triggered this filter. * @return True if pattern was recognized, false otherwise. + * + * @note To see if the client param is available, use FeatureType_Capability and FEATURECAP_MULTITARGETFILTER_CLIENTPARAM. */ typeset MultiTargetFilter { function bool (const char[] pattern, Handle clients); function bool (const char[] pattern, ArrayList clients); + function bool (const char[] pattern, Handle clients, int client); + function bool (const char[] pattern, ArrayList clients, int client); } /** diff --git a/scripting/1.10/include/commandline.inc b/scripting/latest/include/commandline.inc similarity index 100% rename from scripting/1.10/include/commandline.inc rename to scripting/latest/include/commandline.inc diff --git a/scripting/1.10/include/console.inc b/scripting/latest/include/console.inc similarity index 90% rename from scripting/1.10/include/console.inc rename to scripting/latest/include/console.inc index 3b0693c..80e9086 100644 --- a/scripting/1.10/include/console.inc +++ b/scripting/latest/include/console.inc @@ -273,6 +273,24 @@ native ReplySource SetCmdReplySource(ReplySource source); */ native bool IsChatTrigger(); +/** + * Get the list of characters used for public chat triggers. + * + * @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 GetPublicChatTriggers(char[] buffer, int maxlength); + +/** + * Get the list of characters used for silent chat triggers. + * + * @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 GetSilentChatTriggers(char[] buffer, int maxlength); + /** * Displays usage of an admin command to users depending on the * setting of the sm_show_activity cvar. All users receive a message @@ -423,6 +441,72 @@ native int GetCmdArgs(); */ native int GetCmdArg(int argnum, char[] buffer, int maxlength); +/** + * Retrieves a numeric command argument given its index, from the current + * console or server command. Will return 0 if the argument can not be + * parsed as a number. Use GetCmdArgIntEx to handle that explicitly. + * + * @param argnum Argument number to retrieve. + * @return Value of the command argument. + */ +stock int GetCmdArgInt(int argnum) +{ + char str[12]; + GetCmdArg(argnum, str, sizeof(str)); + + return StringToInt(str); +} + +/** + * Retrieves a numeric command argument given its index, from the current + * console or server command. Returns false if the argument can not be + * completely parsed as an integer. + * + * @param argnum Argument number to retrieve. + * @param value Populated with the value of the command argument. + * @return Whether the argument was entirely a numeric value. + */ +stock bool GetCmdArgIntEx(int argnum, int &value) +{ + char str[12]; + int len = GetCmdArg(argnum, str, sizeof(str)); + + return StringToIntEx(str, value) == len && len > 0; +} + +/** + * Retrieves a float command argument given its index, from the current + * console or server command. Will return 0.0 if the argument can not be + * parsed as a number. Use GetCmdArgFloatEx to handle that explicitly. + * + * @param argnum Argument number to retrieve. + * @return Value of the command argument. + */ +stock float GetCmdArgFloat(int argnum) +{ + char str[18]; + GetCmdArg(argnum, str, sizeof(str)); + + return StringToFloat(str); +} + +/** + * Retrieves a float command argument given its index, from the current + * console or server command. Returns false if the argument can not be + * completely parsed as a floating point. + * + * @param argnum Argument number to retrieve. + * @param value Populated with the value of the command argument. + * @return Whether the argument was entirely a floating point value. + */ +stock bool GetCmdArgFloatEx(int argnum, float &value) +{ + char str[18]; + int len = GetCmdArg(argnum, str, sizeof(str)); + + return StringToFloatEx(str, value) == len && len > 0; +} + /** * Retrieves the entire command argument string in one lump from the current * console or server command. @@ -471,12 +555,29 @@ methodmap CommandIterator < Handle { public native get(); } - // Retrieves the command's default flags + // This property is deprecated. Use .AdminFlags instead. + // Retrieves the command's effective admin flags. // // @error Invalid iterator position. + // @deprecated Use .AdminFlags instead. + #pragma deprecated Use .AdminFlags instead. property int Flags { public native get(); } + + // Retrieves the command's effective admin flags. + // + // @error Invalid iterator position. + property int AdminFlags { + public native get(); + } + + // Retrieves the command's convar flags. + // + // @error Invalid iterator position. + property int ConVarFlags { + public native get(); + } } /** diff --git a/scripting/1.10/include/convars.inc b/scripting/latest/include/convars.inc similarity index 98% rename from scripting/1.10/include/convars.inc rename to scripting/latest/include/convars.inc index 7bc9f77..907ed4d 100644 --- a/scripting/1.10/include/convars.inc +++ b/scripting/latest/include/convars.inc @@ -49,6 +49,7 @@ enum ConVarBounds */ enum ConVarQueryResult { + ConVarQuery_Cancelled = -1, //< Client disconnected during query */ 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. */ @@ -121,6 +122,11 @@ methodmap ConVar < Handle public native set(int flags); } + // Retrieves the plugin handle of the convar's creator + property Handle Plugin { + public native get(); + } + // Sets the boolean value of a console variable. // // Note: The replicate and notify params are only relevant for the @@ -165,7 +171,6 @@ methodmap ConVar < Handle // 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. public native void GetString(char[] value, int maxlength); @@ -224,6 +229,12 @@ methodmap ConVar < Handle // @param maxlength Maximum length of string buffer. public native void GetName(char[] name, int maxlength); + // Retrieves the description of a console variable. + // + // @param buffer Buffer to store the description of the convar. + // @param maxlength Maximum length of string buffer. + public native void GetDescription(char[] buffer, int maxlength); + // Replicates a convar value to a specific client. This does not change the actual convar value. // // @param client Client index @@ -239,7 +250,6 @@ methodmap ConVar < Handle // 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 No active hook on convar. public native void RemoveChangeHook(ConVarChanged callback); diff --git a/scripting/1.10/include/core.inc b/scripting/latest/include/core.inc similarity index 99% rename from scripting/1.10/include/core.inc rename to scripting/latest/include/core.inc index 8fed55c..382ead0 100644 --- a/scripting/1.10/include/core.inc +++ b/scripting/latest/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 7 struct PlVers { diff --git a/scripting/1.10/include/cstrike.inc b/scripting/latest/include/cstrike.inc similarity index 94% rename from scripting/1.10/include/cstrike.inc rename to scripting/latest/include/cstrike.inc index 4894840..c3b5358 100644 --- a/scripting/1.10/include/cstrike.inc +++ b/scripting/latest/include/cstrike.inc @@ -45,6 +45,8 @@ #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_BOOST 11 /**< Slot for healthshot and shield (will only return one weapon/item). */ +#define CS_SLOT_UTILITY 12 /**< Slot for tablet. */ #define CS_DMG_HEADSHOT (1 << 30) /**< Headshot */ @@ -156,6 +158,7 @@ enum CSWeaponID 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_CLASSIC = 503, CSWeapon_KNIFE_FLIP = 505, CSWeapon_KNIFE_GUT = 506, CSWeapon_KNIFE_KARAMBIT = 507, @@ -193,8 +196,10 @@ forward Action CS_OnBuyCommand(int client, const char[] weapon); * * @param client Client index * @param weaponIndex Weapon index + * @param donated Was weapon donated (Bought from a buy menu while ctrl was pressed) + * (Note: This param is for CS:GO only, will be false on other games) */ -forward Action CS_OnCSWeaponDrop(int client, int weaponIndex); +forward Action CS_OnCSWeaponDrop(int client, int weaponIndex, bool donated); /** * Called when game retrieves a weapon's price for a player. @@ -435,10 +440,19 @@ native CSWeaponID CS_ItemDefIndexToID(int iDefIndex); * @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. + * @note In most cases the item definition index will be the id. Works for CS:GO ONLY. */ native int CS_WeaponIDToItemDefIndex(CSWeaponID id); +/** + * Returns the loadout slot based on the CSWeaponID. (CS:GO only) + * + * @param id CSWeaponID to get the loadout slot for. + * @return Returns loadout slot value for the weapon id. + * @error Invalid weapon id. + */ +native int CS_WeaponIDToLoadoutSlot(CSWeaponID id); + /** * Do not edit below this line! */ @@ -479,5 +493,6 @@ public void __ext_cstrike_SetNTVOptional() MarkNativeAsOptional("CS_UpdateClientModel"); MarkNativeAsOptional("CS_ItemDefIndexToID"); MarkNativeAsOptional("CS_WeaponIDToItemDefIndex"); + MarkNativeAsOptional("CS_WeaponIDToLoadoutSlot"); } #endif diff --git a/scripting/1.10/include/datapack.inc b/scripting/latest/include/datapack.inc similarity index 87% rename from scripting/1.10/include/datapack.inc rename to scripting/latest/include/datapack.inc index b3d4e89..ae8b4d9 100644 --- a/scripting/1.10/include/datapack.inc +++ b/scripting/latest/include/datapack.inc @@ -71,6 +71,20 @@ methodmap DataPack < Handle // @param insert Determines whether mid-pack writes will insert instead of overwrite. public native void WriteFunction(Function fktptr, bool insert = false); + // Packs an array of cells into a data pack. + // + // @param array Array to add. + // @param count Number of elements + // @param insert Determines whether mid-pack writes will insert instead of overwrite. + public native void WriteCellArray(const any[] array, int count, bool insert = false); + + // Packs an array of floats into a data pack. + // + // @param array Array to add. + // @param count Number of elements + // @param insert Determines whether mid-pack writes will insert instead of overwrite. + public native void WriteFloatArray(const float[] array, int count, bool insert = false); + // Reads a cell from a data pack. // // @return A cell at this position @@ -92,6 +106,18 @@ methodmap DataPack < Handle // @return Function pointer. public native Function ReadFunction(); + // Reads an array of cells a data pack. + // + // @param buffer Destination buffer. + // @param count Maximum length of output buffer. + public native void ReadCellArray(any[] buffer, int count); + + // Reads an array of floats from a data pack. + // + // @param buffer Destination buffer. + // @param count Maximum length of output buffer. + public native void ReadFloatArray(float[] buffer, int count); + // Resets the position in a data pack. // // @param clear If true, clears the contained data. diff --git a/scripting/1.10/include/dbi.inc b/scripting/latest/include/dbi.inc similarity index 97% rename from scripting/1.10/include/dbi.inc rename to scripting/latest/include/dbi.inc index e43a23c..c03f737 100644 --- a/scripting/1.10/include/dbi.inc +++ b/scripting/latest/include/dbi.inc @@ -162,7 +162,7 @@ methodmap DBResultSet < Handle // Fetches a row from the current result set. This must be // successfully called before any results are fetched. // - // If this function fails, _MoreResults can be used to + // If this function fails, MoreRows can be used to // tell if there was an error or the result set is finished. // // @return True if a row was fetched, false otherwise. @@ -360,7 +360,7 @@ methodmap Database < Handle // // Example: "utf8", "latin1" // - // @param characterset The character set string to change to. + // @param charset The character set string to change to. // @return True, if character set was changed, false otherwise. public native bool SetCharset(const char[] charset); @@ -374,8 +374,8 @@ methodmap Database < Handle // the database's character set. // // NOTE: SourceMod only guarantees properly escaped strings when the query - // encloses the string in ''. While drivers tend to allow " instead, the string - // may be not be escaped (for example, on SQLite)! + // encloses the string in single quotes. While drivers tend to allow double + // quotes (") 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. @@ -393,7 +393,7 @@ methodmap Database < Handle // @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 ...); + public native int Format(char[] buffer, int maxlength, const char[] format, any ...); // Returns whether a database is the same connection as another database. public native bool IsSameConnection(Database other); @@ -547,7 +547,7 @@ native bool SQL_CheckConfig(const char[] name); * string to return the default driver. * @return Driver Handle, or INVALID_HANDLE on failure. */ -native Handle SQL_GetDriver(const char[] name=""); +native DBDriver SQL_GetDriver(const char[] name=""); /** * Reads the driver of an opened database. @@ -557,7 +557,7 @@ native Handle SQL_GetDriver(const char[] name=""); * @param ident_length Maximum length of the buffer. * @return Driver Handle. */ -native Handle SQL_ReadDriver(Handle database, char[] ident="", int ident_length=0); +native DBDriver SQL_ReadDriver(Handle database, char[] ident="", int ident_length=0); /** * Retrieves a driver's identification string. @@ -590,7 +590,7 @@ native void SQL_GetDriverProduct(Handle driver, char[] product, int maxlength); * Example: "utf8", "latin1" * * @param database Database Handle. - * @param characterset The character set string to change to. + * @param charset The character set string to change to. * @return True, if character set was changed, false otherwise. */ native bool SQL_SetCharset(Handle database, const char[] charset); @@ -635,8 +635,8 @@ native bool SQL_GetError(Handle hndl, char[] error, int maxlength); * the database's character set. * * NOTE: SourceMod only guarantees properly escaped strings when the query - * encloses the string in ''. While drivers tend to allow " instead, the string - * may be not be escaped (for example, on SQLite)! + * encloses the string in single quotes. While drivers tend to allow double + * quotes (") instead, the string may be not be escaped (for example, on SQLite)! * * @param database A database Handle. * @param string String to quote. @@ -664,7 +664,7 @@ native bool SQL_EscapeString(Handle database, * @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 ...); +native int SQL_FormatQuery(Handle database, char[] buffer, int maxlength, const char[] format, any ...); /** * This function is deprecated. Use SQL_EscapeString instead. @@ -797,7 +797,7 @@ native bool SQL_FieldNameToNum(Handle query, const char[] name, int &field); * Fetches a row from the current result set. This must be * successfully called before any results are fetched. * - * If this function fails, SQL_MoreResults() can be used to + * If this function fails, SQL_MoreRows() can be used to * tell if there was an error or the result set is finished. * * @param query A query (or statement) Handle. @@ -959,6 +959,10 @@ native bool SQL_Execute(Handle statement); * If the lock cannot be acquired, the main thread will pause until the * threaded operation has concluded. * + * Care should be taken to not lock an already-locked database. Internally, + * lock calls are nested recursively and must be paired with an equal amount + * of unlocks to be undone. This behaviour should not be relied on. + * * @param database A database Handle. * @error Invalid database Handle. */ diff --git a/scripting/latest/include/dhooks.inc b/scripting/latest/include/dhooks.inc new file mode 100644 index 0000000..99f17e7 --- /dev/null +++ b/scripting/latest/include/dhooks.inc @@ -0,0 +1,1100 @@ +/** + * vim: set ts=4 sw=4 tw=99 noet : + * ============================================================================= + * SourceMod (C)2021 AlliedModders LLC. All rights reserved. + * ============================================================================= + * + * This file is part of the SourceMod/SourcePawn SDK. + * + * 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$ + */ + +#if defined _dhooks_included +#endinput +#endif +#define _dhooks_included + +// Needed for the SDKFuncConfSource enum. +#include + +#define INVALID_HOOK_ID 0 + +enum ObjectValueType +{ + ObjectValueType_Int = 0, + ObjectValueType_Bool, + ObjectValueType_Ehandle, + ObjectValueType_Float, + ObjectValueType_CBaseEntityPtr, + ObjectValueType_IntPtr, + ObjectValueType_BoolPtr, + ObjectValueType_EhandlePtr, + ObjectValueType_FloatPtr, + ObjectValueType_Vector, + ObjectValueType_VectorPtr, + ObjectValueType_CharPtr, + ObjectValueType_String +}; + +enum ListenType +{ + ListenType_Created, + ListenType_Deleted +}; + +enum ReturnType +{ + ReturnType_Unknown, + ReturnType_Void, + ReturnType_Int, + ReturnType_Bool, + ReturnType_Float, + ReturnType_String, // Note this is a string_t + ReturnType_StringPtr, // Note this is a string_t * + ReturnType_CharPtr, + ReturnType_Vector, + ReturnType_VectorPtr, + ReturnType_CBaseEntity, + ReturnType_Edict +}; + +enum HookParamType +{ + HookParamType_Unknown, + HookParamType_Int, + HookParamType_Bool, + HookParamType_Float, + HookParamType_String, // Note this is a string_t + HookParamType_StringPtr, // Note this is a string_t * + HookParamType_CharPtr, + HookParamType_VectorPtr, + HookParamType_CBaseEntity, + HookParamType_ObjectPtr, + HookParamType_Edict, + HookParamType_Object +}; + +enum ThisPointerType +{ + ThisPointer_Ignore, + ThisPointer_CBaseEntity, + ThisPointer_Address +}; + +enum HookType +{ + HookType_Entity, + HookType_GameRules, + HookType_Raw +}; + +enum CallingConvention +{ + CallConv_CDECL, + CallConv_THISCALL, + CallConv_STDCALL, + CallConv_FASTCALL, +}; + +enum HookMode +{ + Hook_Pre, /**< Callback will be executed BEFORE the original function. */ + Hook_Post /**< Callback will be executed AFTER the original function. */ +}; + +enum MRESReturn +{ + MRES_ChangedHandled = -2, /**< Use changed values and return MRES_Handled */ + MRES_ChangedOverride, /**< Use changed values and return MRES_Override */ + MRES_Ignored, /**< plugin didn't take any action */ + MRES_Handled, /**< plugin did something, but real function should still be called */ + MRES_Override, /**< call real function, but use my return value */ + MRES_Supercede /**< skip real function; use my return value */ +}; + +enum DHookPassFlag +{ + DHookPass_ByVal = (1<<0), /**< Passing by value */ + DHookPass_ByRef = (1<<1), /**< Passing by reference */ + DHookPass_ODTOR = (1<<2), /**< Object has a destructor */ + DHookPass_OCTOR = (1<<3), /**< Object has a constructor */ + 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); +}; + +typeset DHookRemovalCB +{ + function void (int hookid); +}; + +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 (DHookParam hParams); + + // Function Example: void Ham::Test(int cake) with this pointer passed + function MRESReturn (int pThis, DHookParam hParams); + + // Function Example: int Ham::Test() with this pointer ignore + function MRESReturn (DHookReturn hReturn); + + // Function Example: int Ham::Test() with this pointer passed + function MRESReturn (int pThis, DHookReturn hReturn); + + // Function Example: int Ham::Test(int cake) with this pointer ignore + function MRESReturn (DHookReturn hReturn, DHookParam hParams); + + // Function Example: int Ham::Test(int cake) with this pointer passed + function MRESReturn (int pThis, DHookReturn hReturn, DHookParam 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, DHookParam hParams); + + // Function Example: int Ham::Test() with this pointer passed + function MRESReturn (Address pThis, DHookReturn hReturn); + + // Function Example: int Ham::Test(int cake) with this pointer passed + function MRESReturn (Address pThis, DHookReturn hReturn, DHookParam hParams); + +}; + +// Represents the parameters of the hooked function. +methodmap DHookParam < Handle +{ + // Get the value of a parameter. + // Use only for: int, entity, edict, bool or float parameter types. + // + // @param num Parameter number to get, starting at 1. Parameter number 0 returns + // the number of parameters. + // + // @return Value if num greater than 0. If 0 returns parameter count. + // If CBaseEntity returns entity index. + // @error Invalid handle, invalid param number or invalid param type. + public native any Get(int num); + + // Get the value of a vector parameter. + // Use only for: vector or vectorptr parameter types. + // + // @param num Parameter number to get, starting at 1. + // @param vec Vector buffer to store result. + // + // @error Invalid handle, invalid param number or invalid param type. + public native void GetVector(int num, float vec[3]); + + // Get the value of a string parameter. + // Use only for: string, stringptr or charptr parameter types. + // + // @param num Parameter number to get, starting at 1. + // @param buffer String buffer to store result. + // @param size Buffer size. + // + // @error Invalid handle, invalid param number or invalid param type. + public native void GetString(int num, char[] buffer, int size); + + // Set the value of a parameter. + // Use only for: int, entity, edict, bool or float parameter types. + // + // An entity parameter type can be set to NULL using INVALID_ENT_REFERENCE (-1). + // + // The changes are only applied when MRES_ChangedHandled or MRES_ChangedOverride + // is returned in the callback. + // + // @param num Parameter number to set starting at 1. + // @param value Value to set it as (only pass int, bool, float or entity index). + // + // @error Invalid handle, invalid param number or invalid param type. + public native void Set(int num, any value); + + // Set the value of a vector parameter. + // Use only for: vector or vectorptr parameter types. + // + // The changes are only applied when MRES_ChangedHandled or MRES_ChangedOverride + // is returned in the callback. + // + // @param num Parameter number to set, starting at 1. + // @param vec Value to set vector as. + // + // @error Invalid handle, invalid param number or invalid param type. + public native void SetVector(int num, const float vec[3]); + + // Set the value of a string parameter. + // Use only for: string, stringptr or charptr parameter types. + // + // The changes are only applied when MRES_ChangedHandled or MRES_ChangedOverride + // is returned in the callback. + // + // @param num Parameter number to set, starting at 1. + // @param value Value to set string as. + // + // @error Invalid handle, invalid param number or invalid param type. + public native void SetString(int num, const char[] value); + + // Gets an object's variable value. + // + // @param num Parameter number to get, starting at 1. + // @param offset Byte offset within the object to the var to get. + // @param type Type of var it is. + // + // @return Value of the objects var. If EHANDLE type or entity returns entity index. + // @error Invalid handle, invalid param number, invalid param type or invalid Object type. + public native any GetObjectVar(int num, int offset, ObjectValueType type); + + // Gets an object's vector variable value. + // + // @param num Parameter number to get, starting at 1. + // @param offset Byte offset within the object to the var to get. + // @param type Type of var it is. + // @param vec Buffer to store the result vector. + // + // @error Invalid handle, invalid param number, invalid param type or invalid Object type. + public native void GetObjectVarVector(int num, int offset, ObjectValueType type, float vec[3]); + + // Gets an object's string variable value. + // + // @param num Parameter number to get, starting at 1. + // @param offset Byte offset within the object to the var to get. + // @param type Type of var it is. + // @param buffer Buffer to store the result string. + // @param size Size of the buffer. + // + // @error Invalid handle, invalid param number, invalid param type or invalid Object type. + public native void GetObjectVarString(int num, int offset, ObjectValueType type, char[] buffer, int size); + + // Sets an object's variable value. + // + // The changes are only applied when MRES_ChangedHandled or MRES_ChangedOverride + // is returned in the callback. + // + // @param num Parameter number to set, starting at 1. + // @param offset Byte offset within the object to the var to set. + // @param type Type of var it is. + // @param value The value to set the var to. + // + // @error Invalid handle, invalid param number, invalid param type or invalid Object type. + public native void SetObjectVar(int num, int offset, ObjectValueType type, any value); + + // Sets an object's vector variable value. + // + // The changes are only applied when MRES_ChangedHandled or MRES_ChangedOverride + // is returned in the callback. + // + // @param num Parameter number to set, starting at 1. + // @param offset Byte offset within the object to the var to set. + // @param type Type of var it is. + // @param vec The value to set the vector var to. + // + // @error Invalid handle, invalid param number, invalid param type or invalid Object type. + public native void SetObjectVarVector(int num, int offset, ObjectValueType type, const float vec[3]); + + // No setter for object strings yet. Open an issue if you really need it. + + // Checks if a pointer parameter is null. + // + // @param num Parameter number to check, starting at 1. + // + // @return true if null, false otherwise. + // @error Non-pointer parameter. + public native bool IsNull(int num); + + // Get param address (Use only for ptr param types) + // + // @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.) + // + // @return Address of the parameter. + // @error Invalid handle. Invalid param number. Invalid param type. + public native Address GetAddress(int num); +}; + + +// Represents the return value of the hooked function. +methodmap DHookReturn < Handle +{ + // Retrieves or sets the return value. + // Use only for: int, entity, edict, bool or float return types. + // + // An entity return type can be set to NULL using INVALID_ENT_REFERENCE (-1). + // + // The return value is only readable in a post hook. + // The value is only applied when MRES_Override or MRES_Supercede is returned + // in the callback. + property any Value { + public native get(); + public native set(any value); + } + + // Get return vector value. + // Use only for: vector or vectorptr return types. + // + // Only useful in post hooks. + // + // @param vec Vector buffer to store result in. + // + // @error Invalid Handle or invalid type. + public native void GetVector(float vec[3]); + + // Get return string value. + // Use only for: string, stringptr or charptr return types. + // + // Only useful in post hooks. + // + // @param buffer String buffer to store result in. + // @param size String buffer size. + // + // @error Invalid Handle or invalid type. + public native void GetString(char[] buffer, int size); + + // Set return vector value. + // Use only for: vector or vectorptr return types. + // + // The value is only applied when MRES_Override or MRES_Supercede is returned + // in the callback. + // + // @param vec Value to set return vector to. + // + // @error Invalid Handle or invalid type. + public native void SetVector(const float vec[3]); + + // Set return string value. + // Use only for: string, stringptr or charptr return types. + // + // The value is only applied when MRES_Override or MRES_Supercede is returned + // in the callback. + // + // @param buffer Value to set return string to. + // + // @error Invalid Handle or invalid type. + public native void SetString(const char[] buffer); +}; + +// Base method map for common functions between virtual hooks and detours. +methodmap DHookSetup < Handle +{ + // Load address or offset for a vtable hook or detour from a gamedata file. + // + // @param gameconf GameData handle. + // @param source Whether to look in Offsets, Signatures, or Addresses. + // @param name Name of the property to find. + // + // @return true on success, false if nothing was found. + // @error Invalid setup or gamedata handle. + public native bool SetFromConf(Handle gameconf, SDKFuncConfSource source, const char[] name); + + // Adds a parameter to a hook setup. + // + // @param type Parameter type. + // @param size Used for Objects (not Object ptr) to define the size of the object. + // @param flag Used to change the pass type (ignored by detours). + // @param custom_register The register this argument is passed in instead of the stack (ignored by vhooks). + // + // @error Invalid setup handle or too many params added (request upping the max in thread). + public native void AddParam(HookParamType type, int size=-1, DHookPassFlag flag=DHookPass_ByVal, DHookRegister custom_register=DHookRegister_Default); +}; + +// A DynamicHook allows to hook a virtual function on any C++ object. +// Currently CBaseEntity and CGameRules have a convenience API for easy entity hooking, +// but it's possible to provide a raw this-pointer to hook any object in memory too. +// +// Internally this intercepts function calls by replacing the function pointer +// in the virtual table of the object with our own function. +methodmap DynamicHook < DHookSetup +{ + // Creates a vtable hook. + // + // @param offset Virtual table offset of function to hook. + // @param hooktype Type of hook. + // @param returntype Type of return value. + // @param thistype Type of this pointer or ignore (ignore can be used if not needed). + // + // @error Failed to create hook setup handle or invalid callback function. + public native DynamicHook(int offset, HookType hooktype, ReturnType returntype, ThisPointerType thistype); + + // Setup a vtable hook for a function as described in a "Functions" section in gamedata. + // The "Functions" section is parsed once the gamedata file is loaded and cached globally. + // + // @param gameconf GameData handle to use for address lookup. + // Doesn't have to be the same as the one with the "Functions" section. + // @param name Name of the function in a "Functions" section to load. + // + // @return Setup handle for the detour or null if offset wasn't found. + // @error Failed to create detour setup handle, invalid gamedata handle, + // invalid callback function or failed to find function in cached "Functions" sections. + public static native DynamicHook FromConf(Handle gameconf, const char[] name); + + // Hook an entity. + // + // Entity hooks are auto-removed when the entity is destroyed. + // If you need to read the return value of the function, choose a post hook. + // + // @param mode The desired hook mode - pre or post. + // A pre hook calls your callback BEFORE the original function is called. + // You can access the parameters, set the return value, and skip the original function. + // A post hook calls your callback AFTER the original function executed. + // You can access the parameters and get/set the return value. + // @param entity Entity index to hook on. + // @param callback Callback function. + // @param removalcb Optional callback for when the hook is removed. + // + // @return A hookid on success, INVALID_HOOK_ID otherwise. + // @error Invalid setup handle, invalid address, invalid hook type or invalid callback. + public native int HookEntity(HookMode mode, int entity, DHookCallback callback, DHookRemovalCB removalcb=INVALID_FUNCTION); + + // Hook gamerules object. + // + // Game rules hooks are auto-removed on map end. + // If you need to read the return value of the function, choose a post hook. + // + // @param mode The desired hook mode - pre or post. + // A pre hook calls your callback BEFORE the original function is called. + // You can access the parameters, set the return value, and skip the original function. + // A post hook calls your callback AFTER the original function executed. + // You can access the parameters and get/set the return value. + // @param callback Callback function. + // @param removalcb Optional callback for when the hook is removed. + // + // @return A hookid on success, INVALID_HOOK_ID otherwise. + // @error Invalid setup handle, invalid address, invalid hook type or invalid callback. + public native int HookGamerules(HookMode mode, DHookCallback callback, DHookRemovalCB removalcb=INVALID_FUNCTION); + + // Hook a raw this-pointer. + // If you need to read the return value of the function, choose a post hook. + // + // @param mode The desired hook mode - pre or post. + // A pre hook calls your callback BEFORE the original function is called. + // You can access the parameters, set the return value, and skip the original function. + // A post hook calls your callback AFTER the original function executed. + // You can access the parameters and get/set the return value. + // @param addr This pointer address. + // @param callback Callback function. + // + // @return A hookid on success, INVALID_HOOK_ID otherwise. + // @error Invalid setup handle, invalid address, invalid hook type or invalid callback. + public native int HookRaw(HookMode mode, Address addr, DHookCallback callback); + + // Remove hook by hook id. + // + // @param hookid Hook id to remove. + // + // @return true on success, false otherwise + public static native bool RemoveHook(int hookid); +}; + +// A DynamicDetour is a way to hook and block any function in memory. +// Given the address of a function, it can call a callback in your script whenever +// the function gets called. The callback has access to all parameters of the function +// as well as the return value. +// +// Internally this works by replacing the first instructions of the function +// with a jump to our own code. This means that the signature used to find +// the function address in the first place might not match anymore after a detour. +// If you need to detour the same function in different plugins make sure to +// wildcard \x2a the first 6 bytes of the signature to accommodate for the patched +// jump introduced by the detour. +methodmap DynamicDetour < DHookSetup +{ + // 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). + // Only used for thiscall detours. + // + // @error Failed to create detour setup handle. + public native DynamicDetour(Address funcaddr, CallingConvention callConv, ReturnType returntype, ThisPointerType thisType=ThisPointer_Ignore); + + // Setup a detour for a function as described in a "Functions" section in gamedata. + // The "Functions" section is parsed once the gamedata file is loaded and cached globally. + // + // @param gameconf GameData handle to use for address lookup. + // Doesn't have to be the same as the one with the "Functions" section. + // @param name Name of the function in a "Functions" section to load. + // + // @return Setup handle for the detour or null if offset wasn't found. + // @error Failed to create detour setup handle, invalid gamedata handle, + // invalid callback function or failed to find function in cached "Functions" sections. + public static native DynamicDetour FromConf(Handle gameconf, const char[] name); + + // Enable the detour of the function described in this detour setup. + // If you need to read the return value of the function, choose a post hook. + // + // @param mode The desired hook mode - pre or post. + // A pre hook calls your callback BEFORE the original function is called. + // You can access the parameters, set the return value, and skip the original function. + // A post hook calls your callback AFTER the original function executed. + // You can access the parameters and get/set the return value. + // @param callback Callback function. + // + // @return true if detour was enabled, false otherwise. + // @error Hook handle is not setup for a detour. + public native bool Enable(HookMode mode, DHookCallback callback); + + // Disable the detour of the function described in this detour setup. + // + // @param mode The hook mode to disable - pre or post. + // @param callback Callback function. + // + // @return true if detour was disabled, false otherwise. + // @error Hook handle is not setup for a detour or function is not detoured. + public native bool Disable(HookMode mode, DHookCallback callback); +}; + +/** + * Adds an entity listener hook + * + * @param type Type of listener to add + * @param callback Callback to use + */ +native void DHookAddEntityListener(ListenType type, ListenCB callback); + +/** + * Removes an entity listener hook + * + * @param type Type of listener to remove + * @param callback Callback this listener was using + * + * @return true if one was removed, false otherwise + */ +native bool DHookRemoveEntityListener(ListenType type, ListenCB callback); + +/** + * Creates a hook + * + * @param offset vtable offset of function to hook + * @param hooktype Type of hook + * @param returntype Type of return value + * @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 DynamicHook 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 DynamicDetour 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 DHookSetup 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 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 callback Callback function + * + * @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); + +/** + * 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 + * + * @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) + */ +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 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) + * @param callback Optional callback function, if not set here must be set when creating the hook. + * + * @return INVALID_HOOK_ID on fail a hookid on success + * @error Invalid setup handle, invalid address, invalid hook type or invalid callback. + */ +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 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) + * @param callback Optional callback function, if not set here must be set when creating the hook. + * + * @return INVALID_HOOK_ID on fail a hookid on success + * @error Invalid setup handle, invalid address, invalid hook type or invalid callback. + */ +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 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) + * @param callback Optional callback function, if not set here must be set when creating the hook. + * + * @return INVALID_HOOK_ID on fail a hookid on success + * @error Invalid setup handle, invalid address, invalid hook type or invalid callback. + */ +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 + */ +native bool DHookRemoveHookID(int hookid); + +/** + * Get param value (Use only for: int, entity, edict, 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) + * + * @return value if num greater than 0. If 0 returns paramcount. + * @error Invalid handle. Invalid param number. Invalid param type. + */ +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. + */ +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. + */ +native void DHookGetParamString(Handle hParams, int num, char[] buffer, int size); + +/** + * Set param value (Use only for: int, entity, edict, bool or float param types) + * + * An entity param type can be set to NULL using INVALID_ENT_REFERENCE (-1). + * + * @param hParams Handle to params structure + * @param 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. + */ +native void DHookSetParam(Handle hParams, int num, any value); + +/** + * Set vector param value + * + * @param hParams Handle to params structure + * @param 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. + */ +native void DHookSetParamVector(Handle hParams, int num, float vec[3]); + +/** + * Set string param value + * + * @param hParams Handle to params structure + * @param 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. + */ +native void DHookSetParamString(Handle hParams, int num, char[] value); + +/** + * Get return value (Use only 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. + */ +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. + */ +native void DHookGetReturnString(Handle hReturn, char[] buffer, int size); + +/** + * Set return value (Use only for: int, entity, bool or float return types) + * + * An entity return type can be set to NULL using INVALID_ENT_REFERENCE (-1). + * + * @param hReturn Handle to return structure + * @param value Value to set return as + * + * @error Invalid Handle, invalid type. + */ +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. + */ +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. + */ +native void DHookSetReturnString(Handle hReturn, char[] value); + +//WE SHOULD WRAP THESE AROUND STOCKS FOR NON PTR AS WE SUPPORT BOTH WITH THESE NATIVE'S + +/** + * Gets an objects variable value + * + * @param hParams Handle to params structure + * @param num Param number to get. + * @param offset Offset within the object to the var to get. + * @param type Type of var it is + * + * @error Invalid handle. Invalid param number. Invalid param type. Invalid Object type. + * @return Value of the objects var. If EHANDLE type or entity returns entity index. + */ +native any DHookGetParamObjectPtrVar(Handle hParams, int num, int offset, ObjectValueType type); + +/** + * Sets an objects variable value + * + * @param hParams Handle to params structure + * @param num Param number to set. + * @param offset Offset within the object to the var to set. + * @param type Type of var it is + * @param value The value to set the var to. + * + * @error Invalid handle. Invalid param number. Invalid param type. Invalid Object type. + */ +native void DHookSetParamObjectPtrVar(Handle hParams, int num, int offset, ObjectValueType type, any value); + +/** + * Gets an objects vector variable value + * + * @param hParams Handle to params structure + * @param num Param number to get. + * @param offset Offset within the object to the var to get. + * @param type Type of var it is + * @param buffer Buffer to store the result vector + * + * @error Invalid handle. Invalid param number. Invalid param type. Invalid Object type. + */ +native void DHookGetParamObjectPtrVarVector(Handle hParams, int num, int offset, ObjectValueType type, float buffer[3]); + +/** + * Sets an objects vector variable value + * + * @param hParams Handle to params structure + * @param num Param number to set. + * @param offset Offset within the object to the var to set. + * @param type Type of var it is + * @param value The value to set the vector var to. + * + * @error Invalid handle. Invalid param number. Invalid param type. Invalid Object type. + */ +native void DHookSetParamObjectPtrVarVector(Handle hParams, int num, int offset, ObjectValueType type, float value[3]); + +/** + * Gets an objects string variable value + * + * @param hParams Handle to params structure + * @param num Param number to get. + * @param offset Offset within the object to the var to get. + * @param type Type of var it is + * @param buffer Buffer to store the result vector + * @param size Size of the buffer + * + * @error Invalid handle. Invalid param number. Invalid param type. Invalid Object type. + */ +native void DHookGetParamObjectPtrString(Handle hParams, int num, int offset, ObjectValueType type, char[] buffer, int size); + +/** + * Checks if a pointer param is null + * + * @param hParams Handle to params structure + * @param num Param number to check. + * + * @return true if null, false otherwise. + * @error Non pointer param + */ +native bool DHookIsNullParam(Handle hParams, int num); + +/** + * Get param address (Use only for ptr 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.) + * + * @return Address of the parameter. + * @error Invalid handle. Invalid param number. Invalid param type. + */ +native Address DHookGetParamAddress(Handle hParams, int num); + +public Extension __ext_dhooks = +{ + name = "dhooks", + file = "dhooks.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_dhooks_SetNTVOptional() +{ + MarkNativeAsOptional("DHookAddEntityListener"); + MarkNativeAsOptional("DHookRemoveEntityListener"); + MarkNativeAsOptional("DHookCreate"); + MarkNativeAsOptional("DHookCreateDetour"); + MarkNativeAsOptional("DHookCreateFromConf"); + MarkNativeAsOptional("DHookSetFromConf"); + MarkNativeAsOptional("DHookEnableDetour"); + MarkNativeAsOptional("DHookDisableDetour"); + MarkNativeAsOptional("DHookAddParam"); + MarkNativeAsOptional("DHookEntity"); + MarkNativeAsOptional("DHookGamerules"); + MarkNativeAsOptional("DHookRaw"); + MarkNativeAsOptional("DHookRemoveHookID"); + MarkNativeAsOptional("DHookGetParam"); + MarkNativeAsOptional("DHookGetParamVector"); + MarkNativeAsOptional("DHookGetParamString"); + MarkNativeAsOptional("DHookSetParam"); + MarkNativeAsOptional("DHookSetParamVector"); + MarkNativeAsOptional("DHookSetParamString"); + MarkNativeAsOptional("DHookGetReturn"); + MarkNativeAsOptional("DHookGetReturnVector"); + MarkNativeAsOptional("DHookGetReturnString"); + MarkNativeAsOptional("DHookSetReturn"); + MarkNativeAsOptional("DHookSetReturnVector"); + MarkNativeAsOptional("DHookSetReturnString"); + MarkNativeAsOptional("DHookGetParamObjectPtrVar"); + MarkNativeAsOptional("DHookSetParamObjectPtrVar"); + MarkNativeAsOptional("DHookGetParamObjectPtrVarVector"); + MarkNativeAsOptional("DHookSetParamObjectPtrVarVector"); + MarkNativeAsOptional("DHookIsNullParam"); + MarkNativeAsOptional("DHookGetParamObjectPtrString"); + MarkNativeAsOptional("DHookGetParamAddress"); + + MarkNativeAsOptional("DHookParam.IsNull"); + MarkNativeAsOptional("DHookParam.Get"); + MarkNativeAsOptional("DHookParam.GetVector"); + MarkNativeAsOptional("DHookParam.GetString"); + MarkNativeAsOptional("DHookParam.Set"); + MarkNativeAsOptional("DHookParam.SetVector"); + MarkNativeAsOptional("DHookParam.SetString"); + MarkNativeAsOptional("DHookParam.GetObjectVar"); + MarkNativeAsOptional("DHookParam.GetObjectVarVector"); + MarkNativeAsOptional("DHookParam.GetObjectVarString"); + MarkNativeAsOptional("DHookParam.SetObjectVar"); + MarkNativeAsOptional("DHookParam.SetObjectVarVector"); + MarkNativeAsOptional("DHookParam.GetAddress"); + MarkNativeAsOptional("DHookReturn.Value.get"); + MarkNativeAsOptional("DHookReturn.Value.set"); + MarkNativeAsOptional("DHookReturn.GetVector"); + MarkNativeAsOptional("DHookReturn.GetString"); + MarkNativeAsOptional("DHookReturn.SetVector"); + MarkNativeAsOptional("DHookReturn.SetString"); + MarkNativeAsOptional("DHookSetup.SetFromConf"); + MarkNativeAsOptional("DHookSetup.AddParam"); + MarkNativeAsOptional("DynamicHook.DynamicHook"); + MarkNativeAsOptional("DynamicHook.FromConf"); + MarkNativeAsOptional("DynamicHook.HookEntity"); + MarkNativeAsOptional("DynamicHook.HookGamerules"); + MarkNativeAsOptional("DynamicHook.HookRaw"); + MarkNativeAsOptional("DynamicHook.RemoveHook"); + MarkNativeAsOptional("DynamicDetour.DynamicDetour"); + MarkNativeAsOptional("DynamicDetour.FromConf"); + MarkNativeAsOptional("DynamicDetour.Enable"); + MarkNativeAsOptional("DynamicDetour.Disable"); +} +#endif diff --git a/scripting/1.10/include/entity.inc b/scripting/latest/include/entity.inc similarity index 96% rename from scripting/1.10/include/entity.inc rename to scripting/latest/include/entity.inc index a0f9116..2c9e4de 100644 --- a/scripting/1.10/include/entity.inc +++ b/scripting/latest/include/entity.inc @@ -428,6 +428,7 @@ native int FindSendPropOffs(const char[] cls, const char[] prop); * for strings. * @param local_offset Optional parameter to store the local offset, as * FindSendPropOffs() would return. + * @param array_size Optional parameter to store array size, 0 if not an array. * @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. @@ -436,7 +437,8 @@ native int FindSendPropInfo(const char[] cls, const char[] prop, PropFieldType &type=view_as(0), int &num_bits=0, - int &local_offset=0); + int &local_offset=0, + int &array_size=0); /** * Given an entity, finds a datamap property offset. @@ -700,7 +702,7 @@ native int SetEntPropString(int entity, PropType type, const char[] prop, const * @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. + * @return Size of array (in elements) or 0 if property is not an array. * @error Invalid entity or property not found. */ native int GetEntPropArraySize(int entity, PropType type, const char[] prop); @@ -715,7 +717,7 @@ native int GetEntPropArraySize(int entity, PropType type, const char[] prop); * @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) +stock void GetEntDataArray(int entity, int offset, any[] array, int arraySize, int dataSize=4) { for (int i = 0; i < arraySize; i++) { @@ -734,7 +736,7 @@ stock void GetEntDataArray(int entity, int offset, int[] array, int arraySize, i * @param changeState True to set the network state as changed; false otherwise. * @error Invalid entity or offset out of reasonable bounds. */ -stock void SetEntDataArray(int entity, int offset, const int[] array, int arraySize, int dataSize=4, bool changeState=false) +stock void SetEntDataArray(int entity, int offset, const any[] array, int arraySize, int dataSize=4, bool changeState=false) { for (int i = 0; i < arraySize; i++) { @@ -765,3 +767,19 @@ stock bool GetEntityClassname(int entity, char[] clsname, int maxlength) { return !!GetEntPropString(entity, Prop_Data, "m_iClassname", clsname, maxlength); } + +/** + * Interprets the address as an entity handle and returns the associated entity. + * + * @param addr Address to a memory location. + * @return Entity index at the given location. If there is no entity, or the stored entity is invalid, then -1 is returned. + */ +native int LoadEntityFromHandleAddress(Address addr); + +/** + * Interprets the address as an entity handle and sets the entity. + * + * @param addr Address to a memory location. + * @param entity Entity index to set, or -1 to clear. + */ +native void StoreEntityToHandleAddress(Address addr, int entity); diff --git a/scripting/1.10/include/entity_prop_stocks.inc b/scripting/latest/include/entity_prop_stocks.inc similarity index 98% rename from scripting/1.10/include/entity_prop_stocks.inc rename to scripting/latest/include/entity_prop_stocks.inc index c0bc6ff..4dd4060 100644 --- a/scripting/1.10/include/entity_prop_stocks.inc +++ b/scripting/latest/include/entity_prop_stocks.inc @@ -534,19 +534,10 @@ stock void SetEntityHealth(int entity, int amount) 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) + if ((offset = FindDataMapInfo(entity, prop, type)) == -1) { ThrowError("SetEntityHealth not supported by this mod"); return; @@ -559,7 +550,12 @@ stock void SetEntityHealth(int entity, int amount) } else { - SetEntProp(entity, Prop_Send, prop, amount); + SetEntData(entity, offset, amount); + } + + if (IsValidEdict(entity)) + { + ChangeEdictState(entity); } } diff --git a/scripting/latest/include/entitylump.inc b/scripting/latest/include/entitylump.inc new file mode 100644 index 0000000..9d269e6 --- /dev/null +++ b/scripting/latest/include/entitylump.inc @@ -0,0 +1,157 @@ +#if defined _entitylump_included + #endinput +#endif + +#define _entitylump_included + +/** + * An ordered list of key / value pairs for a map entity. + * If the entry in the EntityLump is removed, the handle will error on all operations. + * (The handle will remain valid on the scripting side, and will still need to be deleted.) + * + * Write operations (update, insert, erase, append) are only allowed during OnMapInit. + */ +methodmap EntityLumpEntry < Handle { + /** + * Copies the key / value at the given index into buffers. + * + * @param index Position, starting from 0. + * @param keybuf Key name buffer. + * @param keylen Maximum length of the key name buffer. + * @param valbuf Value buffer. + * @param vallen Maximum length of the value buffer. + * @error Index is out of bounds. + */ + public native void Get(int index, char[] keybuf = "", int keylen = 0, char[] valbuf = "", int vallen = 0); + + /** + * Updates the key / value pair at the given index. + * + * @param index Position, starting from 0. + * @param key New key name, or NULL_STRING to preserve the existing key name. + * @param value New value, or NULL_STRING to preserve the existing value. + * @error Index is out of bounds or entity lump is read-only. + */ + public native void Update(int index, const char[] key = NULL_STRING, const char[] value = NULL_STRING); + + /** + * Inserts a new key / value pair at the given index, shifting the pair at that index and beyond up. + * If EntityLumpEntry.Length is passed in, this is an append operation. + * + * @param index Position, starting from 0. + * @param key New key name. + * @param value New value. + * @error Index is out of bounds or entity lump is read-only. + */ + public native void Insert(int index, const char[] key, const char[] value); + + /** + * Removes the key / value pair at the given index, shifting all entries past it down. + * + * @param index Position, starting from 0. + * @error Index is out of bounds or entity lump is read-only. + */ + public native void Erase(int index); + + /** + * Inserts a new key / value pair at the end of the entry's list. + * + * @param key New key name. + * @param value New value. + * @error Index is out of bounds or entity lump is read-only. + */ + public native void Append(const char[] key, const char[] value); + + /** + * Searches the entry list for an index matching a key starting from a position. + * + * @param key Key name to search. + * @param start A position after which to begin searching from. Use -1 to start from the + * first entry. + * @return Position after start with an entry matching the given key, or -1 if no + * match was found. + * @error Invalid start position; must be a value between -1 and one less than the + * length of the entry. + */ + public native int FindKey(const char[] key, int start = -1); + + /** + * Searches the entry list for an index matching a key starting from a position. + * This also copies the value from that index into the given buffer. + * + * This can be used to find the first / only value matching a key, or to iterate over all + * the values that match said key. + * + * @param key Key name to search. + * @param buffer Value buffer. This will contain the result of the next match, or empty + * if no match was found. + * @param maxlen Maximum length of the value buffer. + * @param start An index after which to begin searching from. Use -1 to start from the + * first entry. + * @return Position after start with an entry matching the given key, or -1 if no + * match was found. + * @error Invalid start position; must be a value between -1 and one less than the + * length of the entry. + */ + public int GetNextKey(const char[] key, char[] buffer, int maxlen, int start = -1) { + int result = this.FindKey(key, start); + if (result != -1) { + this.Get(result, .valbuf = buffer, .vallen = maxlen); + } else { + buffer[0] = '\0'; + } + return result; + } + + /** + * Retrieves the number of key / value pairs in the entry. + */ + property int Length { + public native get(); + } +}; + +/** + * A group of natives for a singleton entity lump, representing all the entities defined in the map. + * + * Write operations (insert, erase, append) are only allowed during OnMapInit. + */ +methodmap EntityLump { + /** + * Returns the EntityLumpEntry at the given index. + * This handle should be freed by the calling plugin. + * + * @param index Position, starting from 0. + * @error Index is out of bounds. + */ + public static native EntityLumpEntry Get(int index); + + /** + * Erases an EntityLumpEntry at the given index, shifting all entries past it down. + * Any handles referencing the erased EntityLumpEntry will throw on any operations aside from delete. + * + * @param index Position, starting from 0. + * @error Index is out of bounds or entity lump is read-only. + */ + public static native void Erase(int index); + + /** + * Inserts an empty EntityLumpEntry at the given index, shifting the existing entry and ones past it up. + * + * @param index Position, starting from 0. + * @error Index is out of bounds or entity lump is read-only. + */ + public static native void Insert(int index); + + /** + * Creates an empty EntityLumpEntry, returning its index. + * + * @error Entity lump is read-only. + */ + public static native int Append(); + + /** + * Returns the number of entities currently in the lump. + */ + public static native int Length(); +}; diff --git a/scripting/1.10/include/events.inc b/scripting/latest/include/events.inc similarity index 100% rename from scripting/1.10/include/events.inc rename to scripting/latest/include/events.inc diff --git a/scripting/1.10/include/files.inc b/scripting/latest/include/files.inc similarity index 95% rename from scripting/1.10/include/files.inc rename to scripting/latest/include/files.inc index fd292ba..0eacc99 100644 --- a/scripting/1.10/include/files.inc +++ b/scripting/latest/include/files.inc @@ -112,6 +112,11 @@ methodmap File < Handle CloseHandle(this); } + // Get the file size in bytes. + // + // @return File size in bytes, -1 on error. + public native int Size(); + // Reads a line of text from a file. // // @param buffer String buffer to hold the line. @@ -126,7 +131,7 @@ methodmap File < Handle // @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. - public native int Read(int[] items, int num_items, int size); + public native int Read(any[] items, int num_items, int size); // Reads a UTF8 or ANSI string from a file. // @@ -152,7 +157,7 @@ methodmap File < Handle // @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); + public native bool Write(const any[] items, int num_items, int size); // Writes a binary string to a file. // @@ -314,7 +319,7 @@ native bool ReadDirEntry(Handle dir, char[] buffer, int maxlength, FileType &typ * Mac, this has no distinction from binary mode. On Windows, it causes the '\n' * character (0xA) to be written as "\r\n" (0xD, 0xA). * - * Example: "rb" opens a binary file for writing; "at" opens a text file for + * Example: "rb" opens a binary file for reading; "at" opens a text file for * appending. * * @param file File to open. @@ -361,7 +366,7 @@ native bool ReadFileLine(Handle hndl, char[] buffer, int maxlength); * 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); +native int ReadFile(Handle hndl, any[] items, int num_items, int size); /** * Reads a UTF8 or ANSI string from a file. @@ -394,7 +399,7 @@ native int ReadFileString(Handle hndl, char[] buffer, int max_size, int read_cou * @return True on success, false on error. * @error Invalid Handle. */ -native bool WriteFile(Handle hndl, const int[] items, int num_items, int size); +native bool WriteFile(Handle hndl, const any[] items, int num_items, int size); /** * Writes a binary string to a file. @@ -575,7 +580,7 @@ native bool RemoveDir(const char[] path); /** * Creates a directory. * - * @param path Path to create. + * @param path Path to create. Note that directories are not created recursively unless use_valve_fs is used. * @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. @@ -585,7 +590,7 @@ native bool RemoveDir(const char[] path); * 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"); +native bool CreateDirectory(const char[] path, int mode=FPERM_O_READ|FPERM_O_EXEC|FPERM_G_READ|FPERM_G_EXEC|FPERM_U_READ|FPERM_U_WRITE|FPERM_U_EXEC, bool use_valve_fs=false, const char[] valve_path_id="DEFAULT_WRITE_PATH"); /** * Changes a file or directories permissions. @@ -596,6 +601,15 @@ native bool CreateDirectory(const char[] path, int mode, bool use_valve_fs=false */ native bool SetFilePermissions(const char[] path, int mode); +/** + * Retrieves a file or directories permissions. + * + * @param path Path to the file. + * @param mode Variable to store the permissions in. + * @return True on success, false otherwise. + */ +native bool GetFilePermissions(const char[] path, int &mode); + /** * Returns a file timestamp as a unix timestamp. * diff --git a/scripting/1.10/include/float.inc b/scripting/latest/include/float.inc similarity index 85% rename from scripting/1.10/include/float.inc rename to scripting/latest/include/float.inc index 8005e05..65e2b87 100644 --- a/scripting/1.10/include/float.inc +++ b/scripting/latest/include/float.inc @@ -97,6 +97,19 @@ native float FloatAdd(float oper1, float oper2); #pragma deprecated This native is internal implementation. For subtraction use the '-' operator. native float FloatSub(float oper1, float oper2); +/** + * Returns the modulus of oper1 and oper2. + * + * Note: This native is internal implementation. For modulo use the '%' operator. + * + * @param oper1 First value. + * @param oper2 Second value. + * @return oper1%oper2. + * @deprecated This native is internal implementation. For modulo use the '%' operator. + */ +#pragma deprecated This native is internal implementation. For modulo use the '%' operator. +native float FloatMod(float oper1, float oper2); + /** * Returns the decimal part of a float. * @@ -262,13 +275,13 @@ stock int RoundFloat(float value) * User defined operators. */ #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; +// Internal aliases for backwards compatibility. +native float __FLOAT_MUL__(float a, float b); +native float __FLOAT_DIV__(float a, float b); +native float __FLOAT_ADD__(float a, float b); +native float __FLOAT_SUB__(float a, float b); +native float __FLOAT_MOD__(float a, float b); native bool __FLOAT_GT__(float a, float b); native bool __FLOAT_GE__(float a, float b); @@ -278,17 +291,18 @@ native bool __FLOAT_EQ__(float a, float b); native bool __FLOAT_NE__(float a, float b); native bool __FLOAT_NOT__(float a); -native float operator*(float oper1, float oper2) = FloatMul; -native float operator/(float oper1, float oper2) = FloatDiv; -native float operator+(float oper1, float oper2) = FloatAdd; -native float operator-(float oper1, float oper2) = FloatSub; -native bool operator!(float oper1) = __FLOAT_NOT__; -native bool operator>(float oper1, float oper2) = __FLOAT_GT__; -native bool operator>=(float oper1, float oper2) = __FLOAT_GE__; -native bool operator<(float oper1, float oper2) = __FLOAT_LT__; -native bool operator<=(float oper1, float oper2) = __FLOAT_LE__; -native bool operator!=(float oper1, float oper2) = __FLOAT_NE__; -native bool operator==(float oper1, float oper2) = __FLOAT_EQ__; +stock float operator*(float oper1, float oper2) { return __FLOAT_MUL__(oper1, oper2); } +stock float operator/(float oper1, float oper2) { return __FLOAT_DIV__(oper1, oper2); } +stock float operator+(float oper1, float oper2) { return __FLOAT_ADD__(oper1, oper2); } +stock float operator-(float oper1, float oper2) { return __FLOAT_SUB__(oper1, oper2); } +stock float operator%(float oper1, float oper2) { return __FLOAT_MOD__(oper1, oper2); } +stock bool operator!(float oper1) { return __FLOAT_NOT__(oper1); } +stock bool operator>(float oper1, float oper2) { return __FLOAT_GT__(oper1, oper2); } +stock bool operator>=(float oper1, float oper2) { return __FLOAT_GE__(oper1, oper2); } +stock bool operator<(float oper1, float oper2) { return __FLOAT_LT__(oper1, oper2); } +stock bool operator<=(float oper1, float oper2) { return __FLOAT_LE__(oper1, oper2); } +stock bool operator!=(float oper1, float oper2) { return __FLOAT_NE__(oper1, oper2); } +stock bool operator==(float oper1, float oper2) { return __FLOAT_EQ__(oper1, oper2); } stock float operator++(float oper) { @@ -387,12 +401,15 @@ stock bool operator<=(int oper1, float oper2) return __FLOAT_LE__(float(oper1), oper2); } -/** - * Forbidden operators. - */ -forward operator%(float oper1, float oper2); -forward operator%(float oper1, int oper2); -forward operator%(int oper1, float oper2); +stock float operator%(float oper1, int oper2) +{ + return __FLOAT_MOD__(oper1, float(oper2)); +} + +stock float operator%(int oper1, float oper2) +{ + return __FLOAT_MOD__(float(oper1), oper2); +} #endif // __sourcepawn2__ #define FLOAT_PI 3.1415926535897932384626433832795 diff --git a/scripting/1.10/include/functions.inc b/scripting/latest/include/functions.inc similarity index 97% rename from scripting/1.10/include/functions.inc rename to scripting/latest/include/functions.inc index 490012b..8ce0ea0 100644 --- a/scripting/1.10/include/functions.inc +++ b/scripting/latest/include/functions.inc @@ -123,7 +123,7 @@ methodmap GlobalForward < Handle { // @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. + // @error More than 32 parameter 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. @@ -142,7 +142,7 @@ methodmap PrivateForward < GlobalForward { // @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. + // @error More than 32 parameter types passed. public native PrivateForward(ExecType type, ParamType ...); // Adds a function to a private forward's call list. @@ -202,7 +202,7 @@ native Function GetFunctionByName(Handle plugin, const char[] name); * @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. + * @error More than 32 parameter types passed. */ native GlobalForward CreateGlobalForward(const char[] name, ExecType type, ParamType ...); @@ -216,7 +216,7 @@ native GlobalForward CreateGlobalForward(const char[] name, ExecType type, Param * @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. + * @error More than 32 parameter types passed. */ native PrivateForward CreateForward(ExecType type, ParamType ...); @@ -353,7 +353,7 @@ native void Call_PushArray(const any[] value, int size); * @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. + * See SM_PARAM_* constants for details. * @error Called before a call has been started. */ native void Call_PushArrayEx(any[] value, int size, int cpflags); @@ -448,6 +448,16 @@ typeset NativeCall * @return Value for the native call to return. */ function any (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. + */ + function void (Handle plugin, int numParams); } /** @@ -466,6 +476,8 @@ native void CreateNative(const char[] name, NativeCall func); * @param error Error code to use. * @param fmt Error message format. * @param ... Format arguments. + * @noreturn + * @error Always! */ native int ThrowNativeError(int error, const char[] fmt, any ...); diff --git a/scripting/latest/include/geoip.inc b/scripting/latest/include/geoip.inc new file mode 100644 index 0000000..0676f75 --- /dev/null +++ b/scripting/latest/include/geoip.inc @@ -0,0 +1,241 @@ +/** + * vim: set ts=4 : + * ============================================================================= + * SourceMod (C)2004-2008 AlliedModders LLC. All rights reserved. + * ============================================================================= + * + * This file is part of the SourceMod/SourcePawn SDK. + * + * 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$ + */ + +#if defined _geoip_included + #endinput +#endif +#define _geoip_included + +enum Continent +{ + CONTINENT_UNKNOWN = 0, + CONTINENT_AFRICA, + CONTINENT_ANTARCTICA, + CONTINENT_ASIA, + CONTINENT_EUROPE, + CONTINENT_NORTH_AMERICA, + CONTINENT_OCEANIA, + CONTINENT_SOUTH_AMERICA, +}; + +// The system of measurement for calculate the distance between geographical coordinates +#define SYSTEM_METRIC 0 // kilometers +#define SYSTEM_IMPERIAL 1 // statute miles + +#include + +/** + * @section IP addresses can contain ports, the ports will be stripped out. + */ + +/** + * 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 otherwise. + */ +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 otherwise. + */ +native bool GeoipCode3(const char[] ip, char ccode[4]); + +/** + * Gets the region code with country code from an IP address. (US-IL, CH-CHE, etc) + * + * @param ip Ip to determine the region code. + * @param ccode Destination string buffer to store the code. + * @return True on success, false otherwise. + */ +native bool GeoipRegionCode(const char[] ip, char ccode[12]); + +/** + * Gets the two character continent code from an IP address. (EU, AS, etc) + * + * @param ip Ip to determine the continent code. + * @param ccode Destination string buffer to store the code. + * @return The continent id on success, 0 otherwise. + */ +native Continent GeoipContinentCode(const char[] ip, char ccode[3]); + +/** + * Gets the full country name. + * + * @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 otherwise. + */ +native bool GeoipCountry(const char[] ip, char[] name, int maxlength); + +/** + * Gets the full country name. + * + * @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. + * @param client Client index in order to return the result in the player's language + * -1: the default language, which is english. + * 0: the server language. You can use LANG_SERVER define. + * >=1: the player's language. + * @return True on success, false otherwise. + */ +native bool GeoipCountryEx(const char[] ip, char[] name, int maxlength, int client = -1); + +/** + * Gets the full continent name. + * + * @param ip Ip to determine the continent code. + * @param name Destination string buffer to store the continent name. + * @param maxlength Maximum length of output string buffer. + * @param client Client index in order to return the result in the player's language + * -1: the default language, which is english. + * 0: the server language. You can use LANG_SERVER define. + * >=1: the player's language. + * @return True on success, false otherwise. + */ +native bool GeoipContinent(const char[] ip, char[] name, int maxlength, int client = -1); + +/** + * Gets the full region name. + * + * @param ip Ip to determine the region code. + * @param name Destination string buffer to store the region name. + * @param maxlength Maximum length of output string buffer. + * @param client Client index in order to return the result in the player's language + * -1: the default language, which is english. + * 0: the server language. You can use LANG_SERVER define. + * >=1: the player's language. + * @return True on success, false otherwise. + */ +native bool GeoipRegion(const char[] ip, char[] name, int maxlength, int client = -1); + +/** + * Gets the city name. + * + * @param ip Ip to determine the city code. + * @param name Destination string buffer to store the city name. + * @param maxlength Maximum length of output string buffer. + * @param client Client index in order to return the result in the player's language + * -1: the default language, which is english. + * 0: the server language. You can use LANG_SERVER define. + * >=1: the player's language. + * @return True on success, false otherwise. + */ +native bool GeoipCity(const char[] ip, char[] name, int maxlength, int client = -1); + +/** + * Gets the timezone. + * + * @param ip Ip to determine the timezone. + * @param name Destination string buffer to store the timezone. + * @param maxlength Maximum length of output string buffer. + * @return True on success, false otherwise. + */ +native bool GeoipTimezone(const char[] ip, char[] name, int maxlength); + +/** + * Gets the city's latitude + * + * @param ip Ip to determine the city latitude. + * @return The result of the latitude, 0 if latitude is not found + */ +native float GeoipLatitude(const char[] ip); + +/** + * Gets the city's longitude + * + * @param ip Ip to determine the city longitude. + * @return The result of the longitude, 0 if longitude is not found + */ +native float GeoipLongitude(const char[] ip); + +/* + * Calculate the distance between geographical coordinates, latitude and longitude. + * + * @param lat1 The first IP latitude. + * @param lon1 The first IP longitude. + * @param lat2 The second IP latitude. + * @param lon2 The second IP longitude. + * @param system The system of measurement, 0 = Metric(kilometers) or 1 = English(miles). + * + * @return The distance as result in specified system of measurement. + */ +native float GeoipDistance(float lat1, float lon1, float lat2, float lon2, int system = SYSTEM_METRIC); + +/** + * @endsection + */ + +/** + * Do not edit below this line! + */ +public Extension __ext_geoip = +{ + name = "GeoIP", + file = "geoip.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 void __ext_geoip_SetNTVOptional() +{ + MarkNativeAsOptional("GeoipCode2"); + MarkNativeAsOptional("GeoipCode3"); + MarkNativeAsOptional("GeoipRegionCode"); + MarkNativeAsOptional("GeoipContinentCode"); + MarkNativeAsOptional("GeoipCountry"); + MarkNativeAsOptional("GeoipCountryEx"); + MarkNativeAsOptional("GeoipContinent"); + MarkNativeAsOptional("GeoipRegion"); + MarkNativeAsOptional("GeoipCity"); + MarkNativeAsOptional("GeoipTimezone"); + MarkNativeAsOptional("GeoipLatitude"); + MarkNativeAsOptional("GeoipLongitude"); + MarkNativeAsOptional("GeoipDistance"); +} +#endif diff --git a/scripting/1.10/include/halflife.inc b/scripting/latest/include/halflife.inc similarity index 92% rename from scripting/1.10/include/halflife.inc rename to scripting/latest/include/halflife.inc index c9c9912..4a1b6a4 100644 --- a/scripting/1.10/include/halflife.inc +++ b/scripting/latest/include/halflife.inc @@ -89,7 +89,9 @@ enum EngineVersion Engine_Insurgency, /**< Insurgency (2013 Retail version)*/ Engine_Contagion, /**< Contagion */ Engine_BlackMesa, /**< Black Mesa Multiplayer */ - Engine_DOI /**< Day of Infamy */ + Engine_DOI, /**< Day of Infamy */ + Engine_PVKII = 26, /**< Pirates, Vikings, and Knights II */ + Engine_MCV, /**< Military Conflict: Vietnam */ }; enum FindMapResult @@ -330,10 +332,14 @@ native bool IsSoundPrecached(const char[] sound); /** * Creates different types of ingame messages. * + * Note: On many newer games (Left 4 Dead/2008+), the display of this to clients is broken. + * Additionally, as of 2018, some games also require the client to have cl_showpluginmessages + * set to 1, a non-default value, for this to function. + * * @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. + * @error Invalid client index, or client not in game. */ native void CreateDialog(int client, Handle kv, DialogType type); @@ -366,7 +372,7 @@ native EngineVersion GetEngineVersion(); * @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. + * @error Invalid client index, or client not in game. */ native void PrintToChat(int client, const char[] format, any ...); @@ -397,7 +403,7 @@ stock void PrintToChatAll(const char[] format, any ...) * @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. + * @error Invalid client index, or client not in game. */ native void PrintCenterText(int client, const char[] format, any ...); @@ -428,7 +434,7 @@ stock void PrintCenterTextAll(const char[] format, any ...) * @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. + * @error Invalid client index, or client not in game. */ native void PrintHintText(int client, const char[] format, any ...); @@ -462,7 +468,7 @@ stock void PrintHintTextToAll(const char[] format, any ...) * @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. + * @error Invalid client index, or client not in game. */ native void ShowVGUIPanel(int client, const char[] name, Handle Kv=INVALID_HANDLE, bool show=true); @@ -561,7 +567,7 @@ native void SetHudTextParamsEx(float x, float y, float holdTime, int color1[4], * @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. + * @error Invalid client index, client not in game, or sync object not valid. */ native int ShowSyncHudText(int client, Handle sync, const char[] message, any ...); @@ -579,14 +585,14 @@ native int ShowSyncHudText(int client, Handle sync, const char[] message, any .. * * @param client Client index to send the message to. * @param sync Synchronization object. - * @error Client not in-game, or sync object not valid. + * @error Invalid client index, client not in game, or sync object not valid. */ 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. + * Note: while many games support HUD Text, not all do. * * @param client Client index to send the message to. * @param channel A channel number. @@ -599,6 +605,7 @@ native void ClearSyncHud(int client, Handle sync); * @return -1 on failure (lack of mod support). * Any other return value is the channel number that was * used to render the text. + * @error Invalid client index, or client not in game. */ native int ShowHudText(int client, int channel, const char[] message, any ...); @@ -610,7 +617,7 @@ native int ShowHudText(int client, int channel, const char[] message, any ...); * @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. + * @error Invalid client index, or client not in game. */ stock void ShowMOTDPanel(int client, const char[] title, const char[] msg, int type=MOTDPANEL_TYPE_INDEX) { @@ -627,11 +634,16 @@ 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. + * + * Note: On many newer games (Left 4 Dead/2008+), the display of this to clients is broken. + * Additionally, as of 2018, some games also require the client to have cl_showpluginmessages + * set to 1, a non-default value, for this to function. * * @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. + * @error Invalid client index, or client not in game. */ stock void DisplayAskConnectBox(int client, float time, const char[] ip, const char[] password = "") { @@ -649,15 +661,17 @@ 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. + * @return Entity reference or -1 on invalid entity. + * @error Entity index >= GetMaxEntities() or < 0 */ native int EntIndexToEntRef(int entity); /** - * Retrieves the entity index from a reference. + * Retrieves the entity index from a reference or validates an entity index. + * The input ref is checked that it is still valid and refers to the same entity. * - * @param ref Entity reference. - * @return Entity index. + * @param ref Entity reference or index. + * @return Entity index or returns INVALID_ENT_REFERENCE if ref is invalid. */ native int EntRefToEntIndex(int ref); @@ -684,7 +698,7 @@ enum ClientRangeType * @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); +native int GetClientsInRange(const float origin[3], ClientRangeType rangeType, int[] clients, int size); /** * Retrieves the server's authentication string (SteamID). diff --git a/scripting/1.10/include/handles.inc b/scripting/latest/include/handles.inc similarity index 71% rename from scripting/1.10/include/handles.inc rename to scripting/latest/include/handles.inc index a6f7ebe..362ab37 100644 --- a/scripting/1.10/include/handles.inc +++ b/scripting/latest/include/handles.inc @@ -75,7 +75,38 @@ native void CloseHandle(Handle hndl); */ native Handle CloneHandle(Handle hndl, Handle plugin=INVALID_HANDLE); -using __intrinsics__.Handle; +methodmap Handle __nullable__ { + public native ~Handle(); + + /** + * 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. + * + * @error Invalid handles will cause a run time error. + */ + public native void Close(); + + /** + * 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. + * + * @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. + */ + public native Handle Clone(Handle plugin=INVALID_HANDLE); +}; /** * Do not use this function. Returns if a Handle and its contents diff --git a/scripting/1.10/include/helpers.inc b/scripting/latest/include/helpers.inc similarity index 100% rename from scripting/1.10/include/helpers.inc rename to scripting/latest/include/helpers.inc diff --git a/scripting/1.10/include/keyvalues.inc b/scripting/latest/include/keyvalues.inc similarity index 95% rename from scripting/1.10/include/keyvalues.inc rename to scripting/latest/include/keyvalues.inc index 7318507..2291ba9 100644 --- a/scripting/1.10/include/keyvalues.inc +++ b/scripting/latest/include/keyvalues.inc @@ -241,12 +241,13 @@ methodmap KeyValues < Handle // have the previous key saved for backwards traversal. // // @param kv KeyValues Handle. - public native void SavePosition(); + // @return True on success, false if there is no higher node. + public native bool SavePosition(); // Jumps back to the previous position. Returns false if there are no - // previous positions (i.e., at the root node). This should be called - // once for each successful Jump call, in order to return to the top node. - // This function pops one node off the internal traversal stack. + // previous positions (i.e., at the root node with an empty traversal stack). + // This should be called once for each successful Jump call, in order to return + // to the top node. This function pops one node off the internal traversal stack. // // @return True on success, false if there is no higher node. public native bool GoBack(); @@ -271,12 +272,14 @@ 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 - // traversal history. This can be used instead of looping KvGoBack() - // if recursive iteration is not important. + // Sets the position back to the top node and clears the entire + // node traversal history (by default). This can be used instead of looping + // KvGoBack() if recursive iteration is not important. // // @param kv KeyValues Handle. - public native void Rewind(); + // @param clearHistory If true, the entire node traversal stack is cleared. + // If false, this will add to the traversal stack. + public native void Rewind(bool clearHistory=true); // Retrieves the current section name. // @@ -305,7 +308,7 @@ methodmap KeyValues < Handle // 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. + // and the traversal stack is empty, 0 is returned. // // @return Number of non-root nodes in the jump stack. public native int NodesInStack(); @@ -523,9 +526,10 @@ native bool KvGotoNextKey(Handle kv, bool keyOnly=true); * have the previous key saved for backwards traversal. * * @param kv KeyValues Handle. + * @return True on success, false if there is no higher node. * @error Invalid Handle. */ -native void KvSavePosition(Handle kv); +native bool KvSavePosition(Handle kv); /** * Removes the given key from the current position. @@ -556,9 +560,9 @@ native int KvDeleteThis(Handle kv); /** * Jumps back to the previous position. Returns false if there are no - * previous positions (i.e., at the root node). This should be called - * once for each successful Jump call, in order to return to the top node. - * This function pops one node off the internal traversal stack. + * previous positions (i.e., at the root node with an empty traversal stack). + * This should be called 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. diff --git a/scripting/1.10/include/lang.inc b/scripting/latest/include/lang.inc similarity index 93% rename from scripting/1.10/include/lang.inc rename to scripting/latest/include/lang.inc index 440b795..3b66905 100644 --- a/scripting/1.10/include/lang.inc +++ b/scripting/latest/include/lang.inc @@ -99,6 +99,15 @@ native void GetLanguageInfo(int language, char[] code="", int codeLen=0, char[] */ native void SetClientLanguage(int client, int language); +/** + * Retrieves the language number a client had when they connected. + * + * @param client Client index. + * @return Language number client originally had. + * @error Invalid client index or client not connected. + */ +native int GetClientOriginalLanguage(int client); + /** * Retrieves the language number from a language code. * diff --git a/scripting/1.10/include/logging.inc b/scripting/latest/include/logging.inc similarity index 100% rename from scripting/1.10/include/logging.inc rename to scripting/latest/include/logging.inc diff --git a/scripting/1.10/include/mapchooser.inc b/scripting/latest/include/mapchooser.inc similarity index 98% rename from scripting/1.10/include/mapchooser.inc rename to scripting/latest/include/mapchooser.inc index 89d73c7..f95e464 100644 --- a/scripting/1.10/include/mapchooser.inc +++ b/scripting/latest/include/mapchooser.inc @@ -135,6 +135,8 @@ forward void OnNominationRemoved(const char[] map, int owner); */ forward void OnMapVoteStarted(); +/* DO NOT EDIT BELOW THIS LINE */ + public SharedPlugin __pl_mapchooser = { name = "mapchooser", @@ -146,6 +148,7 @@ public SharedPlugin __pl_mapchooser = #endif }; +#if !defined REQUIRE_PLUGIN public void __pl_mapchooser_SetNTVOptional() { MarkNativeAsOptional("NominateMap"); @@ -158,3 +161,4 @@ public void __pl_mapchooser_SetNTVOptional() MarkNativeAsOptional("HasEndOfMapVoteFinished"); MarkNativeAsOptional("EndOfMapVoteEnabled"); } +#endif diff --git a/scripting/1.10/include/menus.inc b/scripting/latest/include/menus.inc similarity index 95% rename from scripting/1.10/include/menus.inc rename to scripting/latest/include/menus.inc index 5cdfb7a..866a312 100644 --- a/scripting/1.10/include/menus.inc +++ b/scripting/latest/include/menus.inc @@ -148,8 +148,15 @@ enum MenuSource * @param action The action of the menu. * @param param1 First action parameter (usually the client). * @param param2 Second action parameter (usually the item). + * + * Use void-typed prototype if you don't plan to handle MenuAction_DrawItem + * and MenuAction_DisplayItem actions. */ -typedef MenuHandler = function int (Menu menu, MenuAction action, int param1, int param2); +typeset MenuHandler +{ + function int (Menu menu, MenuAction action, int param1, int param2); + function void (Menu menu, MenuAction action, int param1, int param2); +}; // Panels are used for drawing raw menus without any extra helper functions. // Handles must be closed via delete or CloseHandle(). @@ -307,9 +314,23 @@ methodmap Menu < Handle // @param style By-reference variable to store drawing flags. // @param dispBuf Display buffer. // @param dispBufLen Maximum length of the display buffer. + // @param client Client index. Must be specified if menu is per-client random shuffled, -1 to ignore. // @return True on success, false if position is invalid. public native bool GetItem(int position, char[] infoBuf, int infoBufLen, - int &style=0, char[] dispBuf="", int dispBufLen=0); + int &style=0, char[] dispBuf="", int dispBufLen=0, int client=0); + + // Generates a per-client random mapping for the current vote options. + // + // @param start Menu item index to start randomizing from. + // @param stop Menu item index to stop randomizing at. -1 = infinite + public native void ShufflePerClient(int start=0, int stop=-1); + + // Fills the client vote option mapping with user supplied values. + // + // @param client Client index. + // @param array Integer array with mapping. + // @param length Length of array. + public native void SetClientMapping(int client, int[] array, int length); // Sets the menu's default title/instruction message. // @@ -504,7 +525,7 @@ native bool AddMenuItem(Handle menu, * @error Invalid Handle or menu position. */ native bool InsertMenuItem(Handle menu, - position, + int position, const char[] info, const char[] display, int style=ITEMDRAW_DEFAULT); @@ -537,6 +558,7 @@ native void RemoveAllMenuItems(Handle menu); * @param style By-reference variable to store drawing flags. * @param dispBuf Display buffer. * @param dispBufLen Maximum length of the display buffer. + * @param client Client index. Must be specified if menu is per-client random shuffled, -1 to ignore. * @return True on success, false if position is invalid. * @error Invalid Handle. */ @@ -546,7 +568,27 @@ native bool GetMenuItem(Handle menu, int infoBufLen, int &style=0, char[] dispBuf="", - int dispBufLen=0); + int dispBufLen=0, + int client=0); + +/** + * Generates a per-client random mapping for the current vote options. + * + * @param menu Menu Handle. + * @param start Menu item index to start randomizing from. + * @param stop Menu item index to stop randomizing at. -1 = infinite + */ +native void MenuShufflePerClient(Handle menu, int start=0, int stop=-1); + +/* + * Fills the client vote option mapping with user supplied values. + * + * @param menu Menu Handle. + * @param client Client index. + * @param array Integer array with mapping. + * @param length Length of array. + */ +native void MenuSetClientMapping(Handle menu, int client, int[] array, int length); /** * Returns the first item on the page of a currently selected menu. diff --git a/scripting/1.10/include/nextmap.inc b/scripting/latest/include/nextmap.inc similarity index 100% rename from scripting/1.10/include/nextmap.inc rename to scripting/latest/include/nextmap.inc diff --git a/scripting/1.10/include/profiler.inc b/scripting/latest/include/profiler.inc similarity index 100% rename from scripting/1.10/include/profiler.inc rename to scripting/latest/include/profiler.inc diff --git a/scripting/1.10/include/protobuf.inc b/scripting/latest/include/protobuf.inc similarity index 100% rename from scripting/1.10/include/protobuf.inc rename to scripting/latest/include/protobuf.inc diff --git a/scripting/1.10/include/regex.inc b/scripting/latest/include/regex.inc similarity index 99% rename from scripting/1.10/include/regex.inc rename to scripting/latest/include/regex.inc index 88ae11e..97fcc18 100644 --- a/scripting/1.10/include/regex.inc +++ b/scripting/latest/include/regex.inc @@ -199,12 +199,13 @@ native Regex CompileRegex(const char[] pattern, int flags = 0, char[] error="", * @param regex Regex Handle from CompileRegex() * @param str The string to check. * @param ret Error code, if applicable. + * @param offset Offset in the string to start searching from. * @return Number of captures found or -1 on failure. * * @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); +native int MatchRegex(Handle regex, const char[] str, RegexError &ret = REGEX_ERROR_NONE, int offset = 0); /** * Returns a matched substring from a regex handle. diff --git a/scripting/1.10/include/sdkhooks.inc b/scripting/latest/include/sdkhooks.inc similarity index 95% rename from scripting/1.10/include/sdkhooks.inc rename to scripting/latest/include/sdkhooks.inc index 0c8ba4e..b6f73c1 100644 --- a/scripting/1.10/include/sdkhooks.inc +++ b/scripting/latest/include/sdkhooks.inc @@ -237,11 +237,12 @@ typeset SDKHookCB function void (int client); // Spawn + // Think function Action (int entity); // GroundEntChanged // SpawnPost - // Think/Post + // ThinkPost // VPhysicsUpdate/Post function void (int entity); @@ -350,7 +351,7 @@ forward void OnEntityCreated(int entity, const char[] classname); /** * When an entity is destroyed * - * @param entity Entity index + * @param entity Entity index or edict reference. */ forward void OnEntityDestroyed(int entity); @@ -368,14 +369,17 @@ forward Action OnGetGameDescription(char gameDesc[64]); * 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 mapEntities Unused, always empty + * @return Unused, return value is ignored */ +#pragma deprecated Use OnMapInit() instead forward Action OnLevelInit(const char[] mapName, char mapEntities[2097152]); /** * Hooks an entity * + * Unhooked automatically upon destruction/removal of the entity + * * @param entity Entity index * @param type Type of function to hook * @param callback Function to call when hook is called @@ -385,6 +389,8 @@ native void SDKHook(int entity, SDKHookType type, SDKHookCB callback); /** * Hooks an entity * + * Unhooked automatically upon destruction/removal of the entity + * * @param entity Entity index * @param type Type of function to hook * @param callback Function to call when hook is called @@ -414,10 +420,13 @@ native void SDKUnhook(int entity, SDKHookType type, SDKHookCB callback); * @param weapon Weapon index (orangebox and later) or -1 for unspecified * @param damageForce Velocity of damage force * @param damagePosition Origin of damage + * @param bypassHooks If true, bypass SDK hooks on OnTakeDamage + * @error Invalid entity, attacker, inflictor, or weapon entity. */ 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); + const float damageForce[3]=NULL_VECTOR, const float damagePosition[3]=NULL_VECTOR, + bool bypassHooks = true); /** * Forces a client to drop the specified weapon @@ -426,10 +435,11 @@ native void SDKHooks_TakeDamage(int entity, int inflictor, int attacker, * @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. + * @param bypassHooks If true, bypass SDK hooks on Weapon Drop * @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); + const float vecVelocity[3]=NULL_VECTOR, bool bypassHooks = true); /** * Do not edit below this line! diff --git a/scripting/1.10/include/sdktools.inc b/scripting/latest/include/sdktools.inc similarity index 95% rename from scripting/1.10/include/sdktools.inc rename to scripting/latest/include/sdktools.inc index e5dffba..6687e64 100644 --- a/scripting/1.10/include/sdktools.inc +++ b/scripting/latest/include/sdktools.inc @@ -60,7 +60,9 @@ enum SDKCallType SDKCall_Player, /**< CBasePlayer call */ SDKCall_GameRules, /**< CGameRules call */ SDKCall_EntityList, /**< CGlobalEntityList call */ - SDKCall_Raw /**< |this| pointer with an arbitrary address */ + SDKCall_Raw, /**< |this| pointer with an arbitrary address */ + SDKCall_Server, /**< CBaseServer call */ + SDKCall_Engine /**< CVEngineServer call */ }; enum SDKLibrary @@ -146,6 +148,7 @@ native bool PrepSDKCall_SetAddress(Address addr); * @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 game config Handle. */ native bool PrepSDKCall_SetFromConf(Handle gameconf, SDKFuncConfSource source, const char[] name); @@ -168,6 +171,7 @@ native void PrepSDKCall_SetReturnInfo(SDKType type, SDKPassMethod pass, int decf * @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. + * @error Parameter limit for SDK calls reached. */ native void PrepSDKCall_AddParameter(SDKType type, SDKPassMethod pass, int decflags=0, int encflags=0); @@ -190,6 +194,7 @@ native Handle EndPrepSDKCall(); * 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 string, the value returned by the function will be the number of bytes written, or -1 for NULL. * If the return value is a CBaseEntity, CBasePlayer, or edict, the return value will * always be the entity index, or -1 for NULL. * diff --git a/scripting/1.10/include/sdktools_client.inc b/scripting/latest/include/sdktools_client.inc similarity index 95% rename from scripting/1.10/include/sdktools_client.inc rename to scripting/latest/include/sdktools_client.inc index 23da412..885f563 100644 --- a/scripting/1.10/include/sdktools_client.inc +++ b/scripting/latest/include/sdktools_client.inc @@ -39,6 +39,7 @@ * Sets the client to an inactive state waiting for a new map * * @param client The client index + * @error Invalid client index. */ native void InactivateClient(int client); @@ -46,5 +47,6 @@ native void InactivateClient(int client); * Reconnect a client without dropping the netchannel * * @param client The client index + * @error Invalid client index. */ native void ReconnectClient(int client); diff --git a/scripting/1.10/include/sdktools_engine.inc b/scripting/latest/include/sdktools_engine.inc similarity index 100% rename from scripting/1.10/include/sdktools_engine.inc rename to scripting/latest/include/sdktools_engine.inc diff --git a/scripting/1.10/include/sdktools_entinput.inc b/scripting/latest/include/sdktools_entinput.inc similarity index 100% rename from scripting/1.10/include/sdktools_entinput.inc rename to scripting/latest/include/sdktools_entinput.inc diff --git a/scripting/1.10/include/sdktools_entoutput.inc b/scripting/latest/include/sdktools_entoutput.inc similarity index 100% rename from scripting/1.10/include/sdktools_entoutput.inc rename to scripting/latest/include/sdktools_entoutput.inc diff --git a/scripting/1.10/include/sdktools_functions.inc b/scripting/latest/include/sdktools_functions.inc similarity index 77% rename from scripting/1.10/include/sdktools_functions.inc rename to scripting/latest/include/sdktools_functions.inc index 3be387e..e1beca0 100644 --- a/scripting/1.10/include/sdktools_functions.inc +++ b/scripting/latest/include/sdktools_functions.inc @@ -96,15 +96,16 @@ native void ExtinguishEntity(int entity); * @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]); +native void TeleportEntity(int entity, const float origin[3] = NULL_VECTOR, const float angles[3] = NULL_VECTOR, const float velocity[3] = NULL_VECTOR); /** * Forces a player to commit suicide. * * @param client Client index. + * @param explode If true, explode the player. * @error Invalid client or client not in game, or lack of mod support. */ -native void ForcePlayerSuicide(int client); +native void ForcePlayerSuicide(int client, bool explode = false); /** * Slaps a player in a random direction. @@ -119,11 +120,11 @@ 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. + * @param startEnt A valid entity's 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. + * @error Invalid start entity or lack of mod support. */ native int FindEntityByClassname(int startEnt, const char[] classname); @@ -133,7 +134,7 @@ native int FindEntityByClassname(int startEnt, const char[] classname); * @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. + * @error Invalid client index, client not in game, or lack of mod support. */ native bool GetClientEyeAngles(int client, float ang[3]); @@ -145,7 +146,7 @@ native bool GetClientEyeAngles(int client, float ang[3]); * @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. + * @error Invalid edict index, no map is running, or lack of mod support. */ native int CreateEntityByName(const char[] classname, int ForceEdictIndex=-1); @@ -154,7 +155,7 @@ native int CreateEntityByName(const char[] classname, int ForceEdictIndex=-1); * * @param entity Entity index of the created entity. * @return True on success, false otherwise. - * @error Invalid entity index, or no mod support. + * @error Invalid entity index or lack of mod support. */ native bool DispatchSpawn(int entity); @@ -165,10 +166,27 @@ native bool DispatchSpawn(int entity); * @param keyName Name of the key. * @param value String value. * @return True on success, false otherwise. - * @error Invalid entity index, or no mod support. + * @error Invalid entity index or lack of mod support. */ native bool DispatchKeyValue(int entity, const char[] keyName, const char[] value); +/** + * Dispatches a KeyValue into given entity using an integer value. + * + * @param entity Destination entity index. + * @param keyName Name of the key. + * @param value Integer value. + * @return True on success, false otherwise. + * @error Invalid entity index or lack of mod support. + */ +stock bool DispatchKeyValueInt(int entity, const char[] keyName, int value) +{ + char str[12]; + FormatEx(str, sizeof(str), "%d", value); + + return DispatchKeyValue(entity, keyName, str); +} + /** * Dispatches a KeyValue into given entity using a floating point value. * @@ -176,7 +194,7 @@ native bool DispatchKeyValue(int entity, const char[] keyName, const char[] valu * @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. + * @error Invalid entity index or lack of mod support. */ native bool DispatchKeyValueFloat(int entity, const char[] keyName, float value); @@ -187,7 +205,7 @@ native bool DispatchKeyValueFloat(int entity, const char[] keyName, float value) * @param keyName Name of the key. * @param vec Vector value. * @return True on success, false otherwise. - * @error Invalid entity index, or no mod support. + * @error Invalid entity index or lack of mod support. */ native bool DispatchKeyValueVector(int entity, const char[] keyName, const float vec[3]); @@ -266,7 +284,7 @@ native int GetTeamEntity(int teamIndex); * * @param entity Entity index. * @param model Model name. - * @error Invalid entity index, or no mod support. + * @error Invalid entity index or lack of mod support. */ native void SetEntityModel(int entity, const char[] model); @@ -297,6 +315,7 @@ native bool GetPlayerJingleFile(int client, char[] hex, int maxlength); * * @param in Buffer to store the input traffic velocity. * @param out Buffer to store the output traffic velocity. + * @error Lack of mod support. */ native void GetServerNetStats(float &inAmount, float &outAmout); @@ -325,7 +344,7 @@ native void ActivateEntity(int entity); * @param client Player's index. * @param key Key string. * @param value Value string. - * @error Invalid client index, or client not connected. + * @error Invalid client index, client not connected, or lack of mod support. */ native void SetClientInfo(int client, const char[] key, const char[] value); @@ -334,7 +353,7 @@ native void SetClientInfo(int client, const char[] key, const char[] value); * * @param client Player's index. * @param name New name. - * @error Invalid client index, or client not connected. + * @error Invalid client index, client not connected, or lack of mod support. */ native void SetClientName(int client, const char[] name); @@ -347,5 +366,54 @@ native void SetClientName(int client, const char[] name); * @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. + * @error Lack of mod support. */ native int GivePlayerAmmo(int client, int amount, int ammotype, bool suppressSound=false); + +/** + * Changes an entity's collision group (CBaseEntity::SetCollisionGroup). + * + * @param entity The entity index. + * @param collisionGroup Collision group to use. + * @error Invalid entity or lack of mod support. + */ +native void SetEntityCollisionGroup(int entity, int collisionGroup); + +/** + * Recaculates entity collision rules (CBaseEntity::CollisionRulesChanged). + * + * @param entity The entity index. + * @error Invalid entity or lack of mod support. + */ +native void EntityCollisionRulesChanged(int entity); + +/** + * Sets an entity's owner (CBaseEntity::SetEntityOwner). + * + * @param entity The entity index. + * @param owner The owner entity index, can be invalid. + * @error Invalid entity or lack of mod support. + */ +native void SetEntityOwner(int entity, int owner=INVALID_ENT_REFERENCE); + +/** + * Returns the index number of a given named attachment. + * + * @param entity The entity index. + * @param name The attachment name. + * @return An attachment index, or 0 if the attachment name is invalid or unused. + * @error Invalid entity or lack of mod support. + */ +native int LookupEntityAttachment(int entity, const char[] name); + +/** + * Returns the world location and world angles of an attachment. + * + * @param entity The entity index. + * @param attachment The attachment index. + * @param origin Destination vector to store the attachment's origin vector. + * @param angles Destination vector to store the attachment's position angle. + * @return True on success, otherwise false. + * @error Invalid entity or lack of mod support. + */ +native bool GetEntityAttachment(int entity, int attachment, float origin[3], float angles[3]); diff --git a/scripting/1.10/include/sdktools_gamerules.inc b/scripting/latest/include/sdktools_gamerules.inc similarity index 87% rename from scripting/1.10/include/sdktools_gamerules.inc rename to scripting/latest/include/sdktools_gamerules.inc index dc69355..6d07166 100644 --- a/scripting/1.10/include/sdktools_gamerules.inc +++ b/scripting/latest/include/sdktools_gamerules.inc @@ -80,7 +80,7 @@ enum RoundState { * 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. + * @error Prop type is not an integer, or lack of mod support. */ native int GameRules_GetProp(const char[] prop, int size=4, int element=0); @@ -94,7 +94,7 @@ native int GameRules_GetProp(const char[] prop, int size=4, int element=0); * 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. + * @error Prop type is not an integer, or lack of mod support. */ native void GameRules_SetProp(const char[] prop, any value, int size=4, int element=0, bool changeState=false); @@ -104,7 +104,7 @@ native void GameRules_SetProp(const char[] prop, any value, int size=4, int elem * @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. + * @error Prop type is not a float, or lack of mod support. */ native float GameRules_GetPropFloat(const char[] prop, int element=0); @@ -115,7 +115,7 @@ native float GameRules_GetPropFloat(const char[] prop, int element=0); * @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. + * @error Prop type is not a float, or lack of mod support. */ native void GameRules_SetPropFloat(const char[] prop, float value, int element=0, bool changeState=false); @@ -127,7 +127,7 @@ native void GameRules_SetPropFloat(const char[] prop, float value, int element=0 * @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. + * @error Prop type is not an entity, or lack of mod support. */ native int GameRules_GetPropEnt(const char[] prop, int element=0); @@ -138,7 +138,7 @@ native int GameRules_GetPropEnt(const char[] prop, int element=0); * @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. + * @error Prop type is not an entity, invalid entity, or lack of mod support. */ native void GameRules_SetPropEnt(const char[] prop, int other, int element=0, bool changeState=false); @@ -148,7 +148,7 @@ native void GameRules_SetPropEnt(const char[] prop, int other, int element=0, bo * @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. + * @error Prop type is not a vector, or lack of mod support. */ native void GameRules_GetPropVector(const char[] prop, float vec[3], int element=0); @@ -159,7 +159,7 @@ native void GameRules_GetPropVector(const char[] prop, float vec[3], int element * @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. + * @error Prop type is not a vector, or lack of mod support. */ native void GameRules_SetPropVector(const char[] prop, const float vec[3], int element=0, bool changeState=false); @@ -169,10 +169,11 @@ native void GameRules_SetPropVector(const char[] prop, const float vec[3], int e * @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 Not supported. + * @error Prop type is not a string, or lack of mod support. */ -native int GameRules_GetPropString(const char[] prop, char[] buffer, int maxlen); +native int GameRules_GetPropString(const char[] prop, char[] buffer, int maxlen, int element=0); /** * Sets a gamerules property as a string. @@ -180,10 +181,11 @@ native int GameRules_GetPropString(const char[] prop, char[] buffer, int maxlen) * @param prop Property to use. * @param buffer String to set. * @param changeState This parameter is ignored. + * @param element Element # (starting from 0) if property is an array. * @return Number of non-null bytes written. - * @error Not supported. + * @error Prop type is not a string, or lack of mod support. */ -native int GameRules_SetPropString(const char[] prop, const char[] buffer, bool changeState=false); +native int GameRules_SetPropString(const char[] prop, const char[] buffer, bool changeState=false, int element=0); /** * Gets the current round state. diff --git a/scripting/1.10/include/sdktools_hooks.inc b/scripting/latest/include/sdktools_hooks.inc similarity index 81% rename from scripting/1.10/include/sdktools_hooks.inc rename to scripting/latest/include/sdktools_hooks.inc index aa20e3b..9c92772 100644 --- a/scripting/1.10/include/sdktools_hooks.inc +++ b/scripting/latest/include/sdktools_hooks.inc @@ -37,6 +37,23 @@ #define FEATURECAP_PLAYERRUNCMD_11PARAMS "SDKTools PlayerRunCmd 11Params" +/** + * Called when a clients movement buttons are being processed (Read Only) + * + * @param client Index of the client. + * @param buttons Current commands (as bitflags - see entity_prop_stocks.inc). + * @param impulse 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 OnPlayerRunCmdPre(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]); + /** * Called when a clients movement buttons are being processed * diff --git a/scripting/1.10/include/sdktools_sound.inc b/scripting/latest/include/sdktools_sound.inc similarity index 93% rename from scripting/1.10/include/sdktools_sound.inc rename to scripting/latest/include/sdktools_sound.inc index 41c87de..247971e 100644 --- a/scripting/1.10/include/sdktools_sound.inc +++ b/scripting/latest/include/sdktools_sound.inc @@ -72,15 +72,18 @@ 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 << 0), /** Change sound volume */ + SND_CHANGEPITCH = (1 << 1), /** Change sound pitch */ + SND_STOP = (1 << 2), /** Stop the sound */ + SND_SPAWNING = (1 << 3), /** Used in some cases for ambients */ + SND_DELAY = (1 << 4), /** Sound has an initial delay */ + SND_STOPLOOPING = (1 << 5), /** Stop looping all sounds on the entity */ + SND_SPEAKER = (1 << 6), /** Being played by a mic through a speaker */ + SND_SHOULDPAUSE = (1 << 7), /** Pause if game is paused */ + SND_IGNORE_PHONEMES = (1 << 8), /** Prevents flex animation from being driven by this sound */ + SND_IGNORE_NAME = (1 << 9), /** Changes all sounds emitted on the entity, regardless of actual name */ + SND_DO_NOT_OVERWRITE_EXISTING_ON_CHANNEL = (1 << 10) /** If an existing sound is found on the channel, the sound will not play instead of overwriting it */ }; /** @@ -199,7 +202,7 @@ native void StopSound(int entity, int channel, const char[] name); * @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. + * @error Invalid client index or client not in game. */ native void EmitSound(const int[] clients, int numClients, @@ -238,7 +241,7 @@ native void EmitSound(const int[] clients, * @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. + * @error Invalid client index, client not in game, or lack of mod support. */ native void EmitSoundEntry(const int[] clients, int numClients, @@ -276,7 +279,7 @@ native void EmitSoundEntry(const int[] clients, * @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. + * @error Invalid client index or client not in game. */ native void EmitSentence(const int[] clients, int numClients, @@ -410,7 +413,7 @@ native void RemoveNormalSoundHook(NormalSHook hook); * @param dir Sound direction. * @param updatePos Unknown (updates positions?) * @param soundtime Alternate time to play sound for. - * @error Invalid client index. + * @error Invalid client index or client not in game. */ stock void EmitSoundToClient(int client, const char[] sample, @@ -549,7 +552,7 @@ native bool GetGameSoundParams(const char[] gameSound, * @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. + * @error Invalid client index or client not in game. */ stock bool EmitGameSound(const int[] clients, int numClients, @@ -631,7 +634,7 @@ stock bool EmitAmbientGameSound(const char[] gameSound, * @param dir Sound direction. * @param updatePos Unknown (updates positions?) * @param soundtime Alternate time to play sound for. - * @error Invalid client index. + * @error Invalid client index or client not in game. */ stock bool EmitGameSoundToClient(int client, const char[] gameSound, diff --git a/scripting/1.10/include/sdktools_stocks.inc b/scripting/latest/include/sdktools_stocks.inc similarity index 100% rename from scripting/1.10/include/sdktools_stocks.inc rename to scripting/latest/include/sdktools_stocks.inc diff --git a/scripting/1.10/include/sdktools_stringtables.inc b/scripting/latest/include/sdktools_stringtables.inc similarity index 95% rename from scripting/1.10/include/sdktools_stringtables.inc rename to scripting/latest/include/sdktools_stringtables.inc index 497dd99..346fb33 100644 --- a/scripting/1.10/include/sdktools_stringtables.inc +++ b/scripting/latest/include/sdktools_stringtables.inc @@ -119,9 +119,9 @@ native int GetStringTableDataLength(int tableidx, int stringidx); * * @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 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). + * @return Number of bytes written to the buffer (binary safe, includes the null terminator). * @error Invalid string table index or string index. */ native int GetStringTableData(int tableidx, int stringidx, char[] userdata, int maxlength); @@ -133,10 +133,9 @@ native int GetStringTableData(int tableidx, int stringidx, char[] userdata, int * @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); +native void SetStringTableData(int tableidx, int stringidx, const char[] userdata, int length); /** * Adds a string to a given string table. @@ -147,6 +146,7 @@ native int SetStringTableData(int tableidx, int stringidx, const char[] userdata * @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. + * @error Invalid string table index. */ native void AddToStringTable(int tableidx, const char[] str, const char[] userdata="", int length=-1); diff --git a/scripting/1.10/include/sdktools_tempents.inc b/scripting/latest/include/sdktools_tempents.inc similarity index 91% rename from scripting/1.10/include/sdktools_tempents.inc rename to scripting/latest/include/sdktools_tempents.inc index cc35c71..7364395 100644 --- a/scripting/1.10/include/sdktools_tempents.inc +++ b/scripting/latest/include/sdktools_tempents.inc @@ -98,6 +98,24 @@ native void TE_WriteNum(const char[] prop, int value); */ native int TE_ReadNum(const char[] prop); +/** + * Sets an entity value in the current temp entity. + * + * @param prop Property to use. + * @param value Entity reference or index value to set. + * @error Property not found. + */ +native void TE_WriteEnt(const char[] prop, int value); + +/** + * Reads an entity value in the current temp entity. + * + * @param prop Property to use. + * @return Property value as backwards compatible entity reference. + * @error Property not found. + */ +native int TE_ReadEnt(const char[] prop); + /** * Sets a floating point number in the current temp entity. * @@ -224,7 +242,7 @@ stock void TE_SendToClient(int client, float delay=0.0) * @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) +stock void TE_SendToAllInRange(const float origin[3], ClientRangeType rangeType, float delay=0.0) { int[] clients = new int[MaxClients]; int total = GetClientsInRange(origin, rangeType, clients, MaxClients); diff --git a/scripting/1.10/include/sdktools_tempents_stocks.inc b/scripting/latest/include/sdktools_tempents_stocks.inc similarity index 100% rename from scripting/1.10/include/sdktools_tempents_stocks.inc rename to scripting/latest/include/sdktools_tempents_stocks.inc diff --git a/scripting/1.10/include/sdktools_trace.inc b/scripting/latest/include/sdktools_trace.inc similarity index 89% rename from scripting/1.10/include/sdktools_trace.inc rename to scripting/latest/include/sdktools_trace.inc index cf977e1..e5cce27 100644 --- a/scripting/1.10/include/sdktools_trace.inc +++ b/scripting/latest/include/sdktools_trace.inc @@ -164,6 +164,14 @@ enum RayType RayType_Infinite /**< The trace ray will go from the start position to infinity using a direction vector. */ }; +enum TraceType +{ + TRACE_EVERYTHING = 0, + TRACE_WORLD_ONLY, /**< NOTE: This does *not* test static props!!! */ + TRACE_ENTITIES_ONLY, /**< NOTE: This version will *not* test static props */ + TRACE_EVERYTHING_FILTER_PROPS /**< NOTE: This version will pass the IHandleEntity for props through the filter, unlike all other filters */ +}; + typeset TraceEntityFilter { /** @@ -220,6 +228,7 @@ native int TR_GetPointContents(const float pos[3], int &entindex=-1); * @param entindex Entity index to test. * @param pos World position. * @return Contents mask. + * @error Invalid entity. */ native int TR_GetPointContentsEnt(int entindex, const float pos[3]); @@ -295,6 +304,52 @@ native void TR_EnumerateEntitiesHull(const float pos[3], TraceEntityEnumerator enumerator, any data=0); +/** + * Enumerates over entities in a sphere. + * + * @param pos Starting position of the ray. + * @param radius Radius of the ray. + * @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_EnumerateEntitiesSphere(const float pos[3], + float radius, + int mask, + TraceEntityEnumerator enumerator, + any data=0); + +/** + * Enumerates over entities in a box. + * + * @param mins Box minimum size. + * @param maxs Box 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 box, this function is called. + * @param data Arbitrary data value to pass through to the enumerator. + */ +native void TR_EnumerateEntitiesBox(const float mins[3], + const float maxs[3], + int mask, + TraceEntityEnumerator enumerator, + any data=0); + +/** + * Enumerates over entities at point. + * + * @param pos Position of the point. + * @param mask Mask to use for the trace. See PARTITION_* flags. + * @param enumerator Function to use as enumerator. For each entity found + * along the point, this function is called. + * @param data Arbitrary data value to pass through to the enumerator. + */ +native void TR_EnumerateEntitiesPoint(const float pos[3], + int mask, + TraceEntityEnumerator enumerator, + any data=0); + /** * Starts up a new trace ray using a global trace result and a customized * trace ray filter. @@ -310,13 +365,15 @@ native void TR_EnumerateEntitiesHull(const float pos[3], * @param filter Function to use as a filter. * @param data Arbitrary data value to pass through to the filter * function. + * @param traceType Trace type. */ native void TR_TraceRayFilter(const float pos[3], const float vec[3], int flags, RayType rtype, TraceEntityFilter filter, - any data=0); + any data=0, + TraceType traceType=TRACE_EVERYTHING); /** * Starts up a new trace hull using a global trace result and a customized @@ -333,6 +390,7 @@ native void TR_TraceRayFilter(const float pos[3], * @param filter Function to use as a filter. * @param data Arbitrary data value to pass through to the filter * function. + * @param traceType Trace type. */ native void TR_TraceHullFilter(const float pos[3], const float vec[3], @@ -340,7 +398,8 @@ native void TR_TraceHullFilter(const float pos[3], const float maxs[3], int flags, TraceEntityFilter filter, - any data=0); + any data=0, + TraceType traceType=TRACE_EVERYTHING); /** * Clips a ray to a particular entity. @@ -351,6 +410,7 @@ native void TR_TraceHullFilter(const float pos[3], * @param flags Trace flags. * @param rtype Method to calculate the ray direction. * @param entity Entity to clip to. + * @error Invalid entity. */ native void TR_ClipRayToEntity(const float pos[3], const float vec[3], @@ -367,6 +427,7 @@ native void TR_ClipRayToEntity(const float pos[3], * @param maxs Hull maximum size. * @param flags Trace flags. * @param entity Entity to clip to. + * @error Invalid entity. */ native void TR_ClipRayHullToEntity(const float pos[3], const float vec[3], @@ -380,6 +441,7 @@ native void TR_ClipRayHullToEntity(const float pos[3], * * @param flags Trace flags. * @param entity Entity to clip to. + * @error Invalid entity. */ native void TR_ClipCurrentRayToEntity(int flags, int entity); @@ -428,6 +490,7 @@ native Handle TR_TraceHullEx(const float pos[3], * @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 traceType Trace type. * @return Ray trace handle, which must be closed via CloseHandle(). */ native Handle TR_TraceRayFilterEx(const float pos[3], @@ -435,7 +498,8 @@ native Handle TR_TraceRayFilterEx(const float pos[3], int flags, RayType rtype, TraceEntityFilter filter, - any data=0); + any data=0, + TraceType traceType=TRACE_EVERYTHING); /** * Starts up a new trace hull using a new trace result and a customized @@ -451,6 +515,7 @@ native Handle TR_TraceRayFilterEx(const float pos[3], * @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 traceType Trace type. * @return Ray trace handle, which must be closed via CloseHandle(). */ native Handle TR_TraceHullFilterEx(const float pos[3], @@ -459,7 +524,8 @@ native Handle TR_TraceHullFilterEx(const float pos[3], const float maxs[3], int flags, TraceEntityFilter filter, - any data=0); + any data=0, + TraceType traceType=TRACE_EVERYTHING); /** * Clips a ray to a particular entity. @@ -471,6 +537,7 @@ native Handle TR_TraceHullFilterEx(const float pos[3], * @param rtype Method to calculate the ray direction. * @param entity Entity to clip to. * @return Ray trace handle, which must be closed via CloseHandle(). + * @error Invalid entity. */ native Handle TR_ClipRayToEntityEx(const float pos[3], const float vec[3], @@ -488,6 +555,7 @@ native Handle TR_ClipRayToEntityEx(const float pos[3], * @param flags Trace flags. * @param entity Entity to clip to. * @return Ray trace handle, which must be closed via CloseHandle(). + * @error Invalid entity. */ native Handle TR_ClipRayHullToEntityEx(const float pos[3], const float vec[3], @@ -502,6 +570,7 @@ native Handle TR_ClipRayHullToEntityEx(const float pos[3], * @param flags Trace flags. * @param entity Entity to clip to. * @return Ray trace handle, which must be closed via CloseHandle(). + * @error Invalid entity. */ native Handle TR_ClipCurrentRayToEntityEx(int flags, int entity); diff --git a/scripting/1.10/include/sdktools_variant_t.inc b/scripting/latest/include/sdktools_variant_t.inc similarity index 100% rename from scripting/1.10/include/sdktools_variant_t.inc rename to scripting/latest/include/sdktools_variant_t.inc diff --git a/scripting/1.10/include/sdktools_voice.inc b/scripting/latest/include/sdktools_voice.inc similarity index 87% rename from scripting/1.10/include/sdktools_voice.inc rename to scripting/latest/include/sdktools_voice.inc index 2731997..6bcaf3d 100644 --- a/scripting/1.10/include/sdktools_voice.inc +++ b/scripting/latest/include/sdktools_voice.inc @@ -56,11 +56,26 @@ enum ListenOverride Listen_Yes /**< Can hear */ }; +/** + * Called when a client is speaking. + * + * @param client The client index + */ +forward void OnClientSpeaking(int client); + +/** + * Called once a client speaking end. + * + * @param client The client index + */ +forward void OnClientSpeakingEnd(int client); + /** * Set the client listening flags. * * @param client The client index * @param flags The voice flags + * @error Invalid client index or client not connected. */ native void SetClientListeningFlags(int client, int flags); @@ -69,6 +84,7 @@ native void SetClientListeningFlags(int client, int flags); * * @param client The client index * @return The current voice flags + * @error Invalid client index or client not connected. */ native int GetClientListeningFlags(int client); @@ -102,6 +118,7 @@ native bool GetClientListening(int iReceiver, int iSender); * @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. + * @error Listener or sender client index is invalid or not connected. */ native bool SetListenOverride(int iReceiver, int iSender, ListenOverride override); @@ -111,6 +128,7 @@ native bool SetListenOverride(int iReceiver, int iSender, ListenOverride overrid * @param iReceiver The listener index. * @param iSender The sender index. * @return The override value. + * @error Listener or sender client index is invalid or not connected. */ native ListenOverride GetListenOverride(int iReceiver, int iSender); @@ -120,5 +138,6 @@ native ListenOverride GetListenOverride(int iReceiver, int iSender); * @param iMuter The muter index. * @param iMutee The mutee index. * @return True if muter has muted mutee, false otherwise. + * @error Muter or mutee client index is invalid or not connected. */ native bool IsClientMuted(int iMuter, int iMutee); diff --git a/scripting/1.10/include/socket.inc b/scripting/latest/include/socket.inc similarity index 100% rename from scripting/1.10/include/socket.inc rename to scripting/latest/include/socket.inc diff --git a/scripting/1.10/include/sorting.inc b/scripting/latest/include/sorting.inc similarity index 100% rename from scripting/1.10/include/sorting.inc rename to scripting/latest/include/sorting.inc diff --git a/scripting/1.10/include/sourcemod.inc b/scripting/latest/include/sourcemod.inc similarity index 89% rename from scripting/1.10/include/sourcemod.inc rename to scripting/latest/include/sourcemod.inc index 917f5db..853898f 100644 --- a/scripting/1.10/include/sourcemod.inc +++ b/scripting/latest/include/sourcemod.inc @@ -76,6 +76,7 @@ struct Plugin #include #include #include +#include enum APLRes { @@ -113,6 +114,12 @@ methodmap GameData < Handle // @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); + + // Returns a function address calculated from a signature. + // + // @param name Name of the property to find. + // @return An address calculated on success, or 0 on failure. + public native Address GetMemSig(const char[] name); }; /** @@ -176,10 +183,14 @@ forward void OnPluginPauseChange(bool pause); forward void OnGameFrame(); /** - * Called when the map is loaded. + * Called when the map starts loading. * - * @note This used to be OnServerLoad(), which is now deprecated. - * Plugins still using the old forward will work. + * @param mapName Name of the map + */ +forward void OnMapInit(const char[] mapName); + +/** + * Called when the map is loaded. */ forward void OnMapStart(); @@ -233,6 +244,28 @@ forward void OnAllPluginsLoaded(); */ native Handle GetMyHandle(); +methodmap PluginIterator < Handle +{ + // Returns an iterator that can be used to search through plugins. + // + // @return A new Handle to a PluginIterator. + public native PluginIterator(); + + // Advances the iterator. Returns whether there are more plugins available in the iterator. + // + // @return True on more plugins, false otherwise. + // @error Invalid Handle. + public native bool Next(); + + // Returns the current plugin in the iterator. + // + // @return Current plugin the iterator is at + // @error Invalid Handle. + property Handle Plugin { + public native get(); + } +} + /** * Returns an iterator that can be used to search through plugins. * @@ -338,6 +371,7 @@ native void SetFailState(const char[] string, any ...); * * @param fmt String format. * @param ... Format arguments. + * @noreturn * @error Always! */ native void ThrowError(const char[] fmt, any ...); @@ -364,7 +398,7 @@ 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: - * http://cplusplus.com/reference/clibrary/ctime/strftime.html + * https://cplusplus.com/reference/ctime/strftime/ * * Note that available parameters depends on support from your operating system. * In particular, ones highlighted in yellow on that page are not currently @@ -378,6 +412,24 @@ native int GetTime(int bigStamp[2]={0,0}); */ native void FormatTime(char[] buffer, int maxlength, const char[] format, int stamp=-1); +/** + * Parses a string representing a date and/or time into a unix timestamp. + * The timezone is always interpreted as UTC/GMT. + * + * See this URL for valid parameters: + * https://en.cppreference.com/w/cpp/io/manip/get_time + * + * 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 dateTime Date and/or time string. + * @param format Formatting rules (passing NULL_STRING will use the rules defined in sm_datetime_format). + * @return 32bit timestamp (number of seconds since unix epoch). + * @error Invalid date/time string or time format. + */ +native int ParseTime(const char[] dateTime, const char[] format); + /** * Loads a game config file. * @@ -452,7 +504,7 @@ 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 - * in optional resources. + * in libraries. * * @param name Library name of a plugin or extension. * @return True if exists, false otherwise. @@ -473,8 +525,8 @@ native bool LibraryExists(const char[] name); 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. + * A library is either a plugin name or extension name, as * exposed via its include file. * * @param name Library name. @@ -482,14 +534,21 @@ native int GetExtensionFileStatus(const char[] name, char[] error="", int maxlen 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. + * A library is either a plugin name or extension name, as * exposed via its include file. * * @param name Library name. */ forward void OnLibraryRemoved(const char[] name); +/** + * Called when a plugin unloaded. + * + * @param plugin Plugin Handle who unloaded. + */ +forward void OnNotifyPluginUnloaded(Handle plugin); + #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. */ @@ -676,18 +735,24 @@ enum Address * * @param addr Address to a memory location. * @param size How many bytes should be read. + * If loading a floating-point value, use NumberType_Int32. * @return The value that is stored at that address. + * @error Address is null or pointing to reserved memory. */ -native int LoadFromAddress(Address addr, NumberType size); +native any LoadFromAddress(Address addr, NumberType size); /** * Store up to 4 bytes to a memory address. * - * @param addr Address to a memory location. - * @param data Value to store at the address. - * @param size How many bytes should be written. + * @param addr Address to a memory location. + * @param data Value to store at the address. + * @param size How many bytes should be written. + * If storing a floating-point value, use NumberType_Int32. + * @param updateMemAccess If true, SourceMod will set read / write / exec permissions + * on the memory page being written to. + * @error Address is null or pointing to reserved memory. */ -native void StoreToAddress(Address addr, int data, NumberType size); +native void StoreToAddress(Address addr, any data, NumberType size, bool updateMemAccess = true); methodmap FrameIterator < Handle { // Creates a stack frame iterator to build your own stack traces. diff --git a/scripting/1.10/include/string.inc b/scripting/latest/include/string.inc similarity index 90% rename from scripting/1.10/include/string.inc rename to scripting/latest/include/string.inc index 990989f..7044bad 100644 --- a/scripting/1.10/include/string.inc +++ b/scripting/latest/include/string.inc @@ -121,7 +121,8 @@ stock bool StrEqual(const char[] str1, const char[] str2, bool caseSensitive=tru * @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. + * @return Number of characters written to the buffer, + * not including the null terminator. */ native int strcopy(char[] dest, int destLen, const char[] source); @@ -139,10 +140,12 @@ 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 maxlength Maximum length of output string buffer, + * including the null terminator. * @param format Formatting rules. * @param ... Variable number of format parameters. - * @return Number of cells written. + * @return Number of characters written to the buffer, + * not including the null terminator. */ native int Format(char[] buffer, int maxlength, const char[] format, any ...); @@ -153,10 +156,12 @@ native int Format(char[] buffer, int maxlength, const char[] format, any ...); * check is removed, it is slightly faster. * * @param buffer Destination string buffer. - * @param maxlength Maximum length of output string buffer. + * @param maxlength Maximum length of output string buffer, + * including the null terminator. * @param format Formatting rules. * @param ... Variable number of format parameters. - * @return Number of cells written. + * @return Number of characters written to the buffer, + * not including the null terminator. */ native int FormatEx(char[] buffer, int maxlength, const char[] format, any ...); @@ -167,11 +172,13 @@ native int FormatEx(char[] buffer, int maxlength, const char[] format, any ...); * implementing your own variable argument functions. * * @param buffer Destination string buffer. - * @param maxlength Maximum length of output string buffer. + * @param maxlength Maximum length of output string buffer, + * including the null terminator. * @param format Formatting rules. * @param varpos Argument number which contains the '...' symbol. * Note: Arguments start at 1. * @return Number of bytes written. + * @error Invalid argument index. */ native int VFormat(char[] buffer, int maxlength, const char[] format, int varpos); @@ -194,16 +201,40 @@ native int StringToInt(const char[] str, int nBase=10); */ native int StringToIntEx(const char[] str, int &result, int nBase=10); +/** + * Converts a string to a 64-bit integer. + * + * @param str String to convert. + * @param result Array to store the upper and lower + * 32-bits of the 64-bit integer. + * @param nBase Numerical base to use. 10 is default. + * @return Number of characters consumed. + */ +native int StringToInt64(const char[] str, int result[2], 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. + * @return Number of characters written to the buffer, + * not including the null terminator. */ native int IntToString(int num, char[] str, int maxlength); +/** + * Converts a 64-bit integer to a string. + * + * @param num Array containing the upper and lower + * 32-bits of a 64-bit integer. + * @param str Buffer to store string in. + * @param maxlength Maximum length of string buffer. + * @return Number of characters written to the buffer, + * not including the null terminator. + */ +native int Int64ToString(const int num[2], char[] str, int maxlength); + /** * Converts a string to a floating point number. * @@ -227,7 +258,8 @@ native int StringToFloatEx(const char[] str, float &result); * @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. + * @return Number of characters written to the buffer, + * not including the null terminator. */ native int FloatToString(float num, char[] str, int maxlength); @@ -286,6 +318,7 @@ native int SplitString(const char[] source, const char[] split, char[] part, int * @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. + * @error 'search' parameter is empty. */ native int ReplaceString(char[] text, int maxlength, const char[] search, const char[] replace, bool caseSensitive=true); @@ -305,6 +338,7 @@ native int ReplaceString(char[] text, int maxlength, const char[] search, const * @return Index into the buffer (relative to the start) from where * the last replacement ended, or -1 if no replacements were * made. + * @error 'search' parameter is empty. */ native int ReplaceStringEx(char[] text, int maxlength, const char[] search, const char[] replace, int searchLen=-1, int replaceLen=-1, bool caseSensitive=true); diff --git a/scripting/1.10/include/testing.inc b/scripting/latest/include/testing.inc similarity index 56% rename from scripting/1.10/include/testing.inc rename to scripting/latest/include/testing.inc index 8673379..6ff6d73 100644 --- a/scripting/1.10/include/testing.inc +++ b/scripting/latest/include/testing.inc @@ -38,7 +38,7 @@ stock void SetTestContext(const char[] context) strcopy(TestContext, sizeof(TestContext), context); } -stock void AssertEq(const char[] text, int cell1, int cell2) +stock void AssertEq(const char[] text, any cell1, any cell2) { TestNumber++; if (cell1 == cell2) @@ -52,6 +52,39 @@ stock void AssertEq(const char[] text, int cell1, int cell2) } } +stock void AssertArrayEq(const char[] text, const any[] value, const any[] expected, int len) +{ + TestNumber++; + for (int i = 0; i < len; ++i) + { + if (value[i] != expected[i]) + { + PrintToServer("[%d] %s FAIL: %s should be %d at index %d, got %d", TestNumber, TestContext, text, expected[i], i, value[i]); + ThrowError("test %d (%s in %s) failed", TestNumber, text, TestContext); + break; + } + } + PrintToServer("[%d] %s: '%s' arrays are equal OK", TestNumber, TestContext, text); +} + +stock void AssertArray2DEq(const char[] text, const any[][] value, const any[][] expected, int len, int innerlen) +{ + TestNumber++; + for (int i=0; i < len; ++i) + { + for (int j=0; j < innerlen; ++j) + { + if (value[i][j] != expected[i][j]) + { + PrintToServer("[%d] %s FAIL: %s should be %d at index [%d][%d], got %d", TestNumber, TestContext, text, expected[i][j], i, j, value[i][j]); + ThrowError("test %d (%s in %s) failed", TestNumber, text, TestContext); + break; + } + } + } + PrintToServer("[%d] %s: '%s' 2D arrays are equal OK", TestNumber, TestContext, text); +} + stock void AssertFalse(const char[] text, bool value) { TestNumber++; @@ -79,3 +112,32 @@ stock void AssertTrue(const char[] text, bool value) ThrowError("test %d (%s in %s) failed", TestNumber, text, TestContext); } } + +stock void AssertStrEq(const char[] text, const char[] value, const char[] expected) +{ + TestNumber++; + if (StrEqual(value, expected)) + { + PrintToServer("[%d] %s: '%s' == '%s' OK", TestNumber, TestContext, text, expected); + } + else + { + PrintToServer("[%d] %s FAIL: %s should be '%s', got '%s'", TestNumber, TestContext, text, expected, value); + ThrowError("test %d (%s in %s) failed", TestNumber, text, TestContext); + } +} + +stock void AssertStrArrayEq(const char[] text, const char[][] value, const char[][] expected, int len) +{ + TestNumber++; + for (int i = 0; i < len; ++i) + { + if (!StrEqual(value[i], expected[i])) + { + PrintToServer("[%d] %s FAIL: %s should be '%s' at index %d, got '%s'", TestNumber, TestContext, text, expected[i], i, value[i]); + ThrowError("test %d (%s in %s) failed", TestNumber, text, TestContext); + break; + } + } + PrintToServer("[%d] %s: '%s' arrays are equal OK", TestNumber, TestContext, text); +} diff --git a/scripting/1.10/include/textparse.inc b/scripting/latest/include/textparse.inc similarity index 95% rename from scripting/1.10/include/textparse.inc rename to scripting/latest/include/textparse.inc index 34e99e4..e76fc4d 100644 --- a/scripting/1.10/include/textparse.inc +++ b/scripting/latest/include/textparse.inc @@ -147,6 +147,14 @@ methodmap SMCParser < Handle // @return An SMCParseError result. public native SMCError ParseFile(const char[] file, int &line = 0, int &col = 0); + // Parses raw UTF-8 text as an SMC file. + // + // @param string A string containing an SMC file. + // @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 ParseString(const char[] string, int &line = 0, int &col = 0); + // Sets the callback for receiving SMC_ParseStart events. property SMC_ParseStart OnStart { public native set(SMC_ParseStart func); diff --git a/scripting/1.10/include/tf2.inc b/scripting/latest/include/tf2.inc similarity index 98% rename from scripting/1.10/include/tf2.inc rename to scripting/latest/include/tf2.inc index 6b8a535..8be97de 100644 --- a/scripting/1.10/include/tf2.inc +++ b/scripting/latest/include/tf2.inc @@ -206,7 +206,10 @@ enum TFCond 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 + TFCond_AirCurrent, //127: Reduced air control and friction + TFCond_HalloweenHellHeal, // 128: Used when a player gets teleported to hell + TFCond_PowerupModeDominant, // 129: Reduces effects of certain powerups + TFCond_ImmuneToPushback // 130: Player is immune to pushback effects }; const float TFCondDuration_Infinite = -1.0; @@ -227,6 +230,7 @@ public const TFHoliday TFHoliday_FullMoon; public const TFHoliday TFHoliday_HalloweenOrFullMoon; public const TFHoliday TFHoliday_HalloweenOrFullMoonOrValentines; public const TFHoliday TFHoliday_AprilFools; +public const TFHoliday TFHoliday_Soldier; enum TFObjectType { diff --git a/scripting/1.10/include/tf2_stocks.inc b/scripting/latest/include/tf2_stocks.inc similarity index 99% rename from scripting/1.10/include/tf2_stocks.inc rename to scripting/latest/include/tf2_stocks.inc index 02c0054..f978284 100644 --- a/scripting/1.10/include/tf2_stocks.inc +++ b/scripting/latest/include/tf2_stocks.inc @@ -328,7 +328,7 @@ enum TFResourceType TFResource_PlayerClass }; -static const char TFResourceNames[TFResourceType][] = +static const char TFResourceNames[][] = { "m_iPing", "m_iScore", @@ -399,6 +399,7 @@ stock TFClassType TF2_GetPlayerClass(int client) */ stock void TF2_SetPlayerClass(int client, TFClassType classType, bool weapons=true, bool persistent=true) { + #pragma unused weapons SetEntProp(client, Prop_Send, "m_iClass", view_as(classType)); if (persistent) @@ -431,7 +432,7 @@ stock int TF2_GetPlayerResourceData(int client, TFResourceType type) return -1; } - int entity = TF2_GetResourceEntity(); + int entity = GetPlayerResourceEntity(); if (entity == -1) { @@ -468,7 +469,7 @@ stock bool TF2_SetPlayerResourceData(int client, TFResourceType type, any value) return false; } - int entity = TF2_GetResourceEntity(); + int entity = GetPlayerResourceEntity(); if (entity == -1) { diff --git a/scripting/1.10/include/timers.inc b/scripting/latest/include/timers.inc similarity index 89% rename from scripting/1.10/include/timers.inc rename to scripting/latest/include/timers.inc index 2fb74d9..7a5edf5 100644 --- a/scripting/1.10/include/timers.inc +++ b/scripting/latest/include/timers.inc @@ -51,21 +51,21 @@ 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. + * @param data Handle or value passed to CreateTimer() when timer was created. * @return Plugin_Stop to stop a repeating timer, any other value for * default behavior. + * Ignored for non-repeating timers (use void return type). */ - function Action(Handle timer, Handle hndl); + function Action(Handle timer, any data); /** * Called when the timer interval has elapsed. + * For repeating timers, use the callback with return value. * * @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. + * @param data Handle or value passed to CreateTimer() when timer was created. */ - function Action(Handle timer, any data); + function void(Handle timer, any data); /** * Called when the timer interval has elapsed. @@ -73,8 +73,17 @@ typeset Timer * @param timer Handle to the timer object. * @return Plugin_Stop to stop a repeating timer, any other value for * default behavior. + * Ignored for non-repeating timers (use void return type). */ function Action(Handle timer); + + /** + * Called when the timer interval has elapsed. + * For repeating timers, use the callback with return value. + * + * @param timer Handle to the timer object. + */ + function void(Handle timer); }; /** @@ -87,7 +96,7 @@ typeset Timer * @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); +native Handle CreateTimer(float interval, Timer func, any data=0, int flags=0); /** * Kills a timer. Use this instead of CloseHandle() if you need more options. @@ -95,7 +104,7 @@ native Handle CreateTimer(float interval, Timer func, any data=INVALID_HANDLE, i * @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. + * @error Invalid timer handle. */ native void KillTimer(Handle timer, bool autoClose=false); @@ -105,6 +114,7 @@ native void KillTimer(Handle timer, bool autoClose=false); * @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. + * @error Invalid timer handle. */ native void TriggerTimer(Handle timer, bool reset=false); @@ -182,8 +192,8 @@ forward void OnMapTimeLeftChanged(); * 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 - * timers and entities will work. + * If server hibernation is disabled, once the first player has joined, even if that player + * leaves, the server's timers and entities will continue to work. * * @return True if the server is ticking, false otherwise. */ diff --git a/scripting/1.10/include/topmenus.inc b/scripting/latest/include/topmenus.inc similarity index 98% rename from scripting/1.10/include/topmenus.inc rename to scripting/latest/include/topmenus.inc index bd1c6da..800610c 100644 --- a/scripting/1.10/include/topmenus.inc +++ b/scripting/latest/include/topmenus.inc @@ -361,7 +361,7 @@ native void RemoveFromTopMenu(Handle topmenu, TopMenuObject topobj); * @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. + * @error Invalid TopMenu Handle, invalid client index, or client not in game. */ native bool DisplayTopMenu(Handle topmenu, int client, TopMenuPosition position); @@ -372,7 +372,7 @@ native bool DisplayTopMenu(Handle topmenu, int client, TopMenuPosition position) * @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. + * @error Invalid TopMenu Handle, invalid client index, or client not in game. */ native bool DisplayTopMenuCategory(Handle topmenu, TopMenuObject category, int client); diff --git a/scripting/1.10/include/usermessages.inc b/scripting/latest/include/usermessages.inc similarity index 100% rename from scripting/1.10/include/usermessages.inc rename to scripting/latest/include/usermessages.inc diff --git a/scripting/1.10/include/vector.inc b/scripting/latest/include/vector.inc similarity index 100% rename from scripting/1.10/include/vector.inc rename to scripting/latest/include/vector.inc diff --git a/scripting/1.10/include/version.inc b/scripting/latest/include/version.inc similarity index 94% rename from scripting/1.10/include/version.inc rename to scripting/latest/include/version.inc index a86dfb9..8005d8e 100644 --- a/scripting/1.10/include/version.inc +++ b/scripting/latest/include/version.inc @@ -42,8 +42,8 @@ #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_MINOR 12 /**< SourceMod Minor version */ #define SOURCEMOD_V_RELEASE 0 /**< SourceMod Release version */ - #define SOURCEMOD_VERSION "1.10.0-manual" /**< SourceMod version string (major.minor.release-tag) */ + #define SOURCEMOD_VERSION "1.12.0-manual" /**< SourceMod version string (major.minor.release-tag) */ #endif diff --git a/scripting/1.10/include/version_auto.inc b/scripting/latest/include/version_auto.inc similarity index 56% rename from scripting/1.10/include/version_auto.inc rename to scripting/latest/include/version_auto.inc index 9cb19b0..6d92ef0 100644 --- a/scripting/1.10/include/version_auto.inc +++ b/scripting/latest/include/version_auto.inc @@ -5,11 +5,11 @@ #define _auto_version_included #define SOURCEMOD_V_TAG "" -#define SOURCEMOD_V_CSET "ac29ac06" +#define SOURCEMOD_V_CSET "9e51736f" #define SOURCEMOD_V_MAJOR 1 -#define SOURCEMOD_V_MINOR 10 +#define SOURCEMOD_V_MINOR 12 #define SOURCEMOD_V_RELEASE 0 -#define SOURCEMOD_V_REV 6490 +#define SOURCEMOD_V_REV 7176 -#define SOURCEMOD_VERSION "1.10.0.6490" +#define SOURCEMOD_VERSION "1.12.0.7176" \ No newline at end of file diff --git a/scripting/1.10/kigen-ac_redux.sp b/scripting/latest/kigen-ac_redux.sp similarity index 95% rename from scripting/1.10/kigen-ac_redux.sp rename to scripting/latest/kigen-ac_redux.sp index 2fd2f6c..b4127fe 100644 --- a/scripting/1.10/kigen-ac_redux.sp +++ b/scripting/latest/kigen-ac_redux.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -30,7 +29,6 @@ #include #define REQUIRE_EXTENSIONS // #include // Required for the networking Module // Outdated TODO -#include #include @@ -64,7 +62,7 @@ bool g_bSourceBans, g_bSourceBansPP, g_bMapStarted; //- KACR Modules -// Note: The that ordering of these Includes is imporant -#include "kigen-ac_redux/translations.sp" // Translations Module - NEEDED FIRST +#include "kigen-ac_redux/translations.sp" // Translations Module - Needs to be first #include "kigen-ac_redux/client.sp" // Client Module #include "kigen-ac_redux/commands.sp" // Commands Module #include "kigen-ac_redux/cvars.sp" // CVar Module @@ -128,7 +126,7 @@ public void OnPluginStart() f_hTemp = FindConVar("sv_max_usercmd_future_ticks"); if (f_hTemp != INVALID_HANDLE) SetConVarInt(f_hTemp, 1); - + AutoExecConfig_ExecuteFile(); // Execute the Config AutoExecConfig_CleanFile(); // Cleanup the Config (slow process) @@ -210,7 +208,7 @@ public void OnPluginEnd() CloseHandle(g_hClearTimer); } -//- Map Functions -// +//- Map Hooks -// public void OnMapStart() { @@ -227,7 +225,7 @@ public void OnMapEnd() // RCON_OnMap(); // Currently unused } -//- Client Functions -// +//- Client Hooks -// public bool OnClientConnect(client, char[] rejectmsg, size) { @@ -340,10 +338,22 @@ public Action KACR_ValidateTimer(Handle timer, any client) return Plugin_Stop; } -public Action KACR_ClearTimer(Handle timer, any nothing) -{ - g_hDenyArray.Clear(); -} +// Version Checker for Handle Type TODO 1.8 +#if SOURCEMOD_V_MAJOR == 1 + #if SOURCEMOD_V_MINOR >= 10 // 1.10+ + public void KACR_ClearTimer(Handle timer, any nothing) + { + g_hDenyArray.Clear(); + } + + #else // 1.9 and older + public Action KACR_ClearTimer(Handle timer, any nothing) + { + g_hDenyArray.Clear(); + } + + #endif +#endif //- ConVar Hook -// diff --git a/scripting/1.10/kigen-ac_redux/client.sp b/scripting/latest/kigen-ac_redux/client.sp similarity index 93% rename from scripting/1.10/kigen-ac_redux/client.sp rename to scripting/latest/kigen-ac_redux/client.sp index 397b9f0..ccac45c 100644 --- a/scripting/1.10/kigen-ac_redux/client.sp +++ b/scripting/latest/kigen-ac_redux/client.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -51,7 +50,7 @@ Client_OnPluginStart() HookEvent("player_spawn", Client_PlayerSpawn); HookEvent("player_death", Client_PlayerDeath); HookEvent("round_start", Client_RoundStart); - HookEvent("round_end", Client_CleanEvent); + HookEvent("round_end", Client_RoundEnd); RegConsoleCmd("joinclass", Client_JoinClass); } @@ -159,7 +158,7 @@ public Action Client_Autobuy(client, args) } -//- Map -// +//- Map Hooks -// /*Client_OnMapStart() // Currently unused { @@ -173,27 +172,27 @@ Client_OnMapEnd() strcopy(g_sClientConnections[i], 64, ""); if (hGame == Engine_CSS || hGame == Engine_CSGO) - Client_CleanEvent(INVALID_HANDLE, "", false); + Client_CleanEvent(); } //- Timers -// -public Action Client_AntiSpamConnectTimer(Handle timer, any i) +public Action Client_AntiSpamConnectTimer(Handle hTimer, any iClient) { - strcopy(g_sClientConnections[i], 64, ""); + strcopy(g_sClientConnections[iClient], 64, ""); return Plugin_Stop; } //- Hooks -// -public Action Client_PlayerSpawn(Handle event, const char[] name, bool dontBroadcast) +public Action Client_PlayerSpawn(Event hEvent, const char[] cName, bool bDontBroadcast) { if (!g_bClientEnable || !g_bClientAntiRespawn) return Plugin_Continue; - int client = GetClientOfUserId(GetEventInt(event, "userid")); + int client = GetClientOfUserId(hEvent.GetInt("userid")); char f_sAuthID[64]; if (client <= 0 || GetClientTeam(client) < 2 || !GetClientAuthId(client, AuthId_Steam2, f_sAuthID, sizeof(f_sAuthID))) return Plugin_Continue; @@ -203,12 +202,12 @@ public Action Client_PlayerSpawn(Handle event, const char[] name, bool dontBroad return Plugin_Continue } -public Action Client_PlayerDeath(Handle event, const char[] name, bool dontBroadcast) +public Action Client_PlayerDeath(Event hEvent, const char[] cName, bool bDontBroadcast) { if (!g_bClientEnable || !g_bClientAntiRespawn) return Plugin_Continue; - int client = GetClientOfUserId(GetEventInt(event, "userid")); + int client = GetClientOfUserId(hEvent.GetInt("userid")); char f_sAuthID[64]; if (client <= 0 || !GetClientAuthId(client, AuthId_Steam2, f_sAuthID, sizeof(f_sAuthID))) return Plugin_Continue; @@ -218,24 +217,14 @@ public Action Client_PlayerDeath(Handle event, const char[] name, bool dontBroad return Plugin_Continue } -public Action Client_RoundStart(Handle event, const char[] name, bool dontBroadcast) +public void Client_RoundStart(Event hEvent, const char[] cName, bool bDontBroadcast) { g_bClientMapStarted = true; } -public Action Client_CleanEvent(Handle event, const char[] name, bool dontBroadcast) +public void Client_RoundEnd(Handle hEvent, const char[] cName, bool bDontBroadcast) { - CloseHandle(g_hClientSpawned); // Really needed? We could just clear it? - g_hClientSpawned = new StringMap(); - - for (int i = 1; i <= MaxClients; i++) - { - if (g_bInGame[i] && g_iClientClass[i] != -1) - { - FakeClientCommandEx(i, "joinclass %d", g_iClientClass[i]); - g_iClientClass[i] = -1; - } - } + Client_CleanEvent(); } bool Client_OnClientConnect(iClient, char[] rejectmsg, size) @@ -440,4 +429,22 @@ public void Client_NameProtectChange(Handle convar, const char[] oldValue, const public void Client_AntiSpamConnectChange(Handle convar, const char[] oldValue, const char[] newValue) { g_fClientAntiSpamConnect = GetConVarFloat(convar); -} \ No newline at end of file +} + + +//- Functions -// + +public void Client_CleanEvent() +{ + CloseHandle(g_hClientSpawned); // Really needed? We could just clear it? + g_hClientSpawned = new StringMap(); + + for (int i = 1; i <= MaxClients; i++) + { + if (g_bInGame[i] && g_iClientClass[i] != -1) + { + FakeClientCommandEx(i, "joinclass %d", g_iClientClass[i]); + g_iClientClass[i] = -1; + } + } +} \ No newline at end of file diff --git a/scripting/1.10/kigen-ac_redux/commands.sp b/scripting/latest/kigen-ac_redux/commands.sp similarity index 99% rename from scripting/1.10/kigen-ac_redux/commands.sp rename to scripting/latest/kigen-ac_redux/commands.sp index dbf207b..450bfec 100644 --- a/scripting/1.10/kigen-ac_redux/commands.sp +++ b/scripting/latest/kigen-ac_redux/commands.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/scripting/1.10/kigen-ac_redux/cvars.sp b/scripting/latest/kigen-ac_redux/cvars.sp similarity index 99% rename from scripting/1.10/kigen-ac_redux/cvars.sp rename to scripting/latest/kigen-ac_redux/cvars.sp index a083a2a..dcca3e3 100644 --- a/scripting/1.10/kigen-ac_redux/cvars.sp +++ b/scripting/latest/kigen-ac_redux/cvars.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -956,7 +955,7 @@ public void CVars_EnableChange(Handle convar, const char[] oldValue, const char[ * @param iImportance Priority (PRIORITY_...) * @param cAlternative URL to show to the Player */ -bool CVars_AddCVar(char[] cConVar, f_iComparisonType, f_iAction, const char[] f_sValue, float f_fValue2, f_iImportance, const char f_sAlternative[] = "") +bool CVars_AddCVar(char[] cConVar, f_iComparisonType, f_iAction, const char[] f_sValue, float f_fValue2, f_iImportance, const char[] f_sAlternative = "") { Handle f_hConVar = INVALID_HANDLE, f_hArray; diff --git a/scripting/1.10/kigen-ac_redux/eyetest.sp b/scripting/latest/kigen-ac_redux/eyetest.sp similarity index 88% rename from scripting/1.10/kigen-ac_redux/eyetest.sp rename to scripting/latest/kigen-ac_redux/eyetest.sp index 2689629..f3a2560 100644 --- a/scripting/1.10/kigen-ac_redux/eyetest.sp +++ b/scripting/latest/kigen-ac_redux/eyetest.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -194,8 +193,8 @@ public void Eyetest_AntiWallChange(Handle convar, const char[] oldValue, const c } for (int i = 1; i <= MaxClients; i++) - if (Client_IsValid(i, true)) - if (IsPlayerAlive(i) && !g_bHooked[i]) // We do not use the Arrays here since its OnPluginStart and the Players may havent been checked TODO: is that correct? + if (IsClientInGame(i) && !IsFakeClient(i)) // g_bInGame[i] && !g_bIsFake[i]) - We do not use the Arrays here since its OnPluginStart and the Players may havent been checked. This can be fixed by populating the arrays OnPluginLoad TODO + if (IsPlayerAlive(i) && !g_bHooked[i]) Eyetest_Hook(i); Status_Report(g_iAntiWHStatus, KACR_ON); @@ -213,27 +212,27 @@ public void Eyetest_AntiWallChange(Handle convar, const char[] oldValue, const c g_bAntiWall = f_bEnabled; } -public Action Eyetest_PlayerSpawn(Handle event, const char[] name, bool dontBroadcast) +public void Eyetest_PlayerSpawn(Event hEvent, const char[] cName, bool bDontBroadcast) { - int client = GetClientOfUserId(GetEventInt(event, "userid")); - if (client && GetClientTeam(client) > 1) + int iClient = GetClientOfUserId(hEvent.GetInt("userid")); + if (iClient && GetClientTeam(iClient) > 1) { - if (!IsFakeClient(client)) - g_bShouldProcess[client] = true; + if (!IsFakeClient(iClient)) + g_bShouldProcess[iClient] = true; - if (g_bAntiWall && !g_bHooked[client]) - Eyetest_Hook(client); + if (g_bAntiWall && !g_bHooked[iClient]) + Eyetest_Hook(iClient); } } -public Action Eyetest_PlayerDeath(Handle event, const char[] name, bool dontBroadcast) +public void Eyetest_PlayerDeath(Event hEvent, const char[] cName, bool bDontBroadcast) { - int client = GetClientOfUserId(GetEventInt(event, "userid")); - if (client) + int iClient = GetClientOfUserId(hEvent.GetInt("userid")); + if (iClient) { - g_bShouldProcess[client] = false; - if (g_bAntiWall && g_bHooked[client]) - Eyetest_Unhook(client); + g_bShouldProcess[iClient] = false; + if (g_bAntiWall && g_bHooked[iClient]) + Eyetest_Unhook(iClient); } } @@ -259,21 +258,21 @@ public Action Eyetest_WeaponTransmit(entity, client) return Plugin_Stop; } -public Action Eyetest_Equip(client, weapon) // The Player Picked up a Weapon? Lets bind the Entity ID to the Player ID +public void Eyetest_Equip(iClient, iWeapon) // The Player Picked up a Weapon? Lets bind the Entity ID to the Player ID { - if (g_iWeaponOwner[weapon] == 0) // The Weapon has no owner yet? + if (g_iWeaponOwner[iWeapon] == 0) // The Weapon has no owner yet? { - g_iWeaponOwner[weapon] = client; - SDKHook(weapon, SDKHook_SetTransmit, Eyetest_WeaponTransmit); + g_iWeaponOwner[iWeapon] = iClient; + SDKHook(iWeapon, SDKHook_SetTransmit, Eyetest_WeaponTransmit); } } -public Action Eyetest_Drop(client, weapon) +public void Eyetest_Drop(iClient, iWeapon) { - if (weapon > 0 && g_iWeaponOwner[weapon] > 0) // Is a Player linked to the Entity? Else we do not Care // Check if the Weapon exists first, it may got deleted in the same Frame, Bugfix for #37 + if (iWeapon > 0 && g_iWeaponOwner[iWeapon] > 0) // Is a Player linked to the Entity? Else we do not Care // Check if the Weapon exists first, it may got deleted in the same Frame, Bugfix for #37 { - g_iWeaponOwner[weapon] = 0; - SDKUnhook(weapon, SDKHook_SetTransmit, Eyetest_WeaponTransmit); + g_iWeaponOwner[iWeapon] = 0; + SDKUnhook(iWeapon, SDKHook_SetTransmit, Eyetest_WeaponTransmit); } } diff --git a/scripting/1.10/kigen-ac_redux/network #Unused.sp b/scripting/latest/kigen-ac_redux/network #Unused.sp similarity index 99% rename from scripting/1.10/kigen-ac_redux/network #Unused.sp rename to scripting/latest/kigen-ac_redux/network #Unused.sp index cd826a6..4fe8ae2 100644 --- a/scripting/1.10/kigen-ac_redux/network #Unused.sp +++ b/scripting/latest/kigen-ac_redux/network #Unused.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/scripting/1.10/kigen-ac_redux/rcon.sp b/scripting/latest/kigen-ac_redux/rcon.sp similarity index 98% rename from scripting/1.10/kigen-ac_redux/rcon.sp rename to scripting/latest/kigen-ac_redux/rcon.sp index 342443b..d1a4ed6 100644 --- a/scripting/1.10/kigen-ac_redux/rcon.sp +++ b/scripting/latest/kigen-ac_redux/rcon.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/scripting/1.10/kigen-ac_redux/status.sp b/scripting/latest/kigen-ac_redux/status.sp similarity index 97% rename from scripting/1.10/kigen-ac_redux/status.sp rename to scripting/latest/kigen-ac_redux/status.sp index 58186cd..257aa74 100644 --- a/scripting/1.10/kigen-ac_redux/status.sp +++ b/scripting/latest/kigen-ac_redux/status.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/scripting/1.10/kigen-ac_redux/stocks.sp b/scripting/latest/kigen-ac_redux/stocks.sp similarity index 98% rename from scripting/1.10/kigen-ac_redux/stocks.sp rename to scripting/latest/kigen-ac_redux/stocks.sp index 6fdf2de..28bdb22 100644 --- a/scripting/1.10/kigen-ac_redux/stocks.sp +++ b/scripting/latest/kigen-ac_redux/stocks.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/scripting/1.10/kigen-ac_redux/translations.sp b/scripting/latest/kigen-ac_redux/translations.sp similarity index 99% rename from scripting/1.10/kigen-ac_redux/translations.sp rename to scripting/latest/kigen-ac_redux/translations.sp index da15f7c..a185920 100644 --- a/scripting/1.10/kigen-ac_redux/translations.sp +++ b/scripting/latest/kigen-ac_redux/translations.sp @@ -1,7 +1,6 @@ /* - Kigen's Anti-Cheat + Based on Kigen's Anti-Cheat Copyright (C) 2007-2011 CodingDirect LLC - No Copyright (i guess) 2018-2019 FunForBattle This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by diff --git a/scripting/latest/spcomp.exe b/scripting/latest/spcomp.exe new file mode 100644 index 0000000..2c4cdb7 Binary files /dev/null and b/scripting/latest/spcomp.exe differ