plugins/include/sourcemod.inc
author David Anderson <dvander@alliedmods.net>
Fri Aug 15 05:22:26 2008 +0000 (2008-08-15)
changeset 2226 d10b38524be3
parent 2133 cad0a5ea6742
child 2289 44045ead61cd
permissions -rw-r--r--
Landed sourcepawn-1.2. The big changes:

1) JIT compilation/optimization now occurs per-function, and only when functions are first used. We're now officially a whole-method JIT rather than an AOT compiler (albiet, still a simple JIT). This has two implications: Functions are now much better abstracted internally, and loading a plugin is now much less expensive. If a function contains calls to other functions, THOSE functions are only compiled when they're invoked as well.

2) I've removed debug mode. We always show full backtraces now, as there was a very cheap way to implement this which really cleaned up everything. This is great for a number of reasons -- there's less code, the JIT is better designed, we don't need to relocate debug tables, and best of all we no longer have to tell users to enable debug mode at their own expense.
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod (C)2004-2008 AlliedModders LLC.  All rights reserved.
     5  * =============================================================================
     6  *
     7  * This file is part of the SourceMod/SourcePawn SDK.
     8  *
     9  * This program is free software; you can redistribute it and/or modify it under
    10  * the terms of the GNU General Public License, version 3.0, as published by the
    11  * Free Software Foundation.
    12  * 
    13  * This program is distributed in the hope that it will be useful, but WITHOUT
    14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    15  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
    16  * details.
    17  *
    18  * You should have received a copy of the GNU General Public License along with
    19  * this program.  If not, see <http://www.gnu.org/licenses/>.
    20  *
    21  * As a special exception, AlliedModders LLC gives you permission to link the
    22  * code of this program (as well as its derivative works) to "Half-Life 2," the
    23  * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
    24  * by the Valve Corporation.  You must obey the GNU General Public License in
    25  * all respects for all other code used.  Additionally, AlliedModders LLC grants
    26  * this exception to all derivative works.  AlliedModders LLC defines further
    27  * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
    28  * or <http://www.sourcemod.net/license.php>.
    29  *
    30  * Version: $Id$
    31  */
    32 
    33 #if defined _sourcemod_included
    34  #endinput
    35 #endif
    36 #define _sourcemod_included
    37 
    38 /**
    39  * Plugin public information.
    40  */
    41 struct Plugin
    42 {
    43    const String:name[],			/**< Plugin Name */
    44    const String:description[],	/**< Plugin Description */
    45    const String:author[],		/**< Plugin Author */
    46    const String:version[],		/**< Plugin Version */
    47    const String:url[],			/**< Plugin URL */
    48 };
    49 
    50 #include <core>
    51 #include <float>
    52 #include <vector>
    53 #include <string>
    54 #include <handles>
    55 #include <functions>
    56 #include <files>
    57 #include <logging>
    58 #include <timers>
    59 #include <admin>
    60 #include <dbi>
    61 #include <lang>
    62 #include <sorting>
    63 #include <textparse>
    64 #include <clients>
    65 #include <console>
    66 #include <events>
    67 #include <bitbuffer>
    68 #include <usermessages>
    69 #include <keyvalues>
    70 #include <menus>
    71 #include <halflife>
    72 #include <adt>
    73 #include <banning>
    74 #include <commandfilters>
    75 #include <nextmap>
    76 
    77 /**
    78  * Declare this as a struct in your plugin to expose its information.
    79  * Example:
    80  *
    81  * public Plugin:myinfo =
    82  * {
    83  *    name = "My Plugin",
    84  *    //etc
    85  * };
    86  */
    87 public Plugin:myinfo;
    88  
    89 /**
    90  * Called when the plugin is fully initialized and all known external references 
    91  * are resolved. This is only called once in the lifetime of the plugin, and is 
    92  * paired with OnPluginEnd().
    93  *
    94  * If any run-time error is thrown during this callback, the plugin will be marked 
    95  * as failed.
    96  *
    97  * It is not necessary to close any handles or remove hooks in this function.  
    98  * SourceMod guarantees that plugin shutdown automatically and correctly releases 
    99  * all resources.
   100  *
   101  * @noreturn
   102  */
   103 forward OnPluginStart();
   104  
   105 /**
   106  * Called before OnPluginStart, in case the plugin wants to check for load failure.
   107  * This is called even if the plugin type is "private."  Any natives from modules are 
   108  * not available at this point.  Thus, this forward should only be used for explicit 
   109  * pre-emptive things, such as adding dynamic natives, or setting certain types of load filters.
   110  * 
   111  * @note It is not safe to call externally resolved natives until OnPluginStart().
   112  * @note Any sort of RTE in this function will cause the plugin to fail loading.
   113  * @note You MUST remember to return SOMETHING here.  The act of not returning is 
   114  *       equivalent to returning 0 (false).  If you forgot to return, it will 
   115  *       cause your plugin to not load with a very strange error message.
   116  *
   117  * @param myself	Handle to the plugin.
   118  * @param late		Whether or not the plugin was loaded "late" (after map load).
   119  * @param error		Error message buffer in case load failed.
   120  * @param err_max	Maximum number of characters for error message buffer.
   121  * @return			True if load success, false otherwise.
   122  */
   123 forward bool:AskPluginLoad(Handle:myself, bool:late, String:error[], err_max);
   124 
   125 /**
   126  * Called when the plugin is about to be unloaded.
   127  *
   128  * @noreturn
   129  */
   130 forward OnPluginEnd();
   131 
   132 /**
   133  * Called when the plugin's pause status is changing.
   134  *
   135  * @param pause			True if the plugin is being paused, false otherwise.
   136  * @noreturn
   137  */
   138 forward OnPluginPauseChange(bool:pause);
   139 
   140 /**
   141  * Called before every server frame.  Note that you should avoid
   142  * doing expensive computations here, and you should declare large
   143  * local arrays using 'decl' instead of 'new'.
   144  */
   145 forward OnGameFrame();
   146 
   147 /**
   148  * Called when the map is loaded.
   149  *
   150  * @note This used to be OnServerLoad(), which is now deprecated.
   151  * Plugins still using the old forward will work.
   152  */
   153 forward OnMapStart();
   154 
   155 /**
   156  * Called right before a map ends.
   157  */
   158 forward OnMapEnd();
   159 
   160 /**
   161  * Called when the map has loaded, servercfgfile (server.cfg) has been 
   162  * executed, and all plugin configs are done executing.  This is the best
   163  * place to initialize plugin functions which are based on cvar data.  
   164  *
   165  * @note This will always be called once and only once per map.  It will be 
   166  * called after OnMapStart().
   167  *
   168  * @noreturn
   169  */
   170 forward OnConfigsExecuted();
   171 
   172 /**
   173  * This is called once, right after OnMapStart() but any time before 
   174  * OnConfigsExecuted().  It is called after the "exec sourcemod.cfg" 
   175  * command and all AutoExecConfig() exec commands have been added to 
   176  * the ServerCommand() buffer.
   177  *
   178  * If you need to load per-map settings that override default values, 
   179  * adding commands to the ServerCommand() buffer here will guarantee 
   180  * that they're set before OnConfigsExecuted().
   181  *
   182  * Unlike OnMapStart() and OnConfigsExecuted(), this is not called on 
   183  * late loads that occur after OnMapStart().
   184  *
   185  * @noreturn
   186  */
   187 forward OnAutoConfigsBuffered();
   188 
   189 /**
   190  * @deprecated Use OnConfigsExecuted() instead.
   191  */
   192 #pragma deprecated Use OnConfigsExecuted() instead
   193 forward OnServerCfg();
   194 
   195 /**
   196  * Called after all plugins have been loaded.  This is called once for 
   197  * every plugin.  If a plugin late loads, it will be called immediately 
   198  * after OnPluginStart().
   199  */
   200 forward OnAllPluginsLoaded();
   201 
   202 /**
   203  * Returns the calling plugin's Handle.
   204  *
   205  * @return				Handle of the calling plugin.
   206  */
   207 native Handle:GetMyHandle();
   208 
   209 /**
   210  * Returns an iterator that can be used to search through plugins.
   211  *
   212  * @return				Handle to iterate with.  Must be closed via 
   213  * 						CloseHandle().
   214  * @error				Invalid Handle.
   215  */
   216 native Handle:GetPluginIterator();
   217 
   218 /**
   219  * Returns whether there are more plugins available in the iterator.
   220  *
   221  * @param iter			Handle to the plugin iterator.
   222  * @return				True on more plugins, false otherwise.
   223  * @error				Invalid Handle.
   224  */
   225 native bool:MorePlugins(Handle:iter);
   226 
   227 /**
   228  * Returns the current plugin in the iterator and advances the iterator.
   229  *
   230  * @param iter			Handle to the plugin iterator.
   231  * @return				Current plugin the iterator is at, before
   232  *						the iterator is advanced.
   233  * @error				Invalid Handle.
   234  */
   235 native Handle:ReadPlugin(Handle:iter);
   236 
   237 /**
   238  * Returns a plugin's status.
   239  *
   240  * @param plugin		Plugin Handle (INVALID_HANDLE uses the calling plugin).
   241  * @return				Status code for the plugin.
   242  * @error				Invalid Handle.
   243  */
   244 native PluginStatus:GetPluginStatus(Handle:plugin);
   245 
   246 /**
   247  * Retrieves a plugin's file name relative to the plugins folder.
   248  *
   249  * @param plugin		Plugin Handle (INVALID_HANDLE uses the calling plugin).
   250  * @param buffer		Buffer to the store the file name.
   251  * @param maxlength		Maximum length of the name buffer.
   252  * @noreturn
   253  * @error				Invalid Handle.
   254  */
   255 native GetPluginFilename(Handle:plugin, String:buffer[], maxlength);
   256 
   257 /**
   258  * Retrieves whether or not a plugin is being debugged.
   259  *
   260  * @param plugin		Plugin Handle (INVALID_HANDLE uses the calling plugin).
   261  * @return				True if being debugged, false otherwise.
   262  * @error				Invalid Handle.
   263  */
   264 native bool:IsPluginDebugging(Handle:hndl);
   265 
   266 /**
   267  * Retrieves a plugin's public info.
   268  *
   269  * @param plugin		Plugin Handle (INVALID_HANDLE uses the calling plugin).
   270  * @param info			Plugin info property to retrieve.
   271  * @param buffer		Buffer to store info in.
   272  * @param maxlength		Maximum length of buffer.
   273  * @return				True on success, false if property is not available.
   274  * @error				Invalid Handle.
   275  */
   276 native bool:GetPluginInfo(Handle:plugin, PluginInfo:info, String:buffer[], maxlength);
   277 
   278 /**
   279  * Finds a plugin by its order in the list from the "plugins list" server 
   280  * "sm" command.  You should not use this function to loop through all plugins, 
   281  * use the iterator instead.  Looping through all plugins using this native 
   282  * is O(n^2), whereas using the iterator is O(n).
   283  *
   284  * @param order_num		Number of the plugin as it appears in "sm plugins list".
   285  * @return				Plugin Handle on success, INVALID_HANDLE if no plugin 
   286  *						matches the given number.
   287  */
   288 native Handle:FindPluginByNumber(order_num);
   289 
   290 /**
   291  * Causes the plugin to enter a failed state.  An error will be thrown and
   292  * the plugin will be paused until it is unloaded or reloaded.
   293  *
   294  * For backwards compatibility, if no extra arguments are passed, no 
   295  * formatting is applied.  If one or more additional arguments is passed, 
   296  * the string is formatted using Format().  If any errors are encountered 
   297  * during formatting, both the format specifier string and an additional 
   298  * error message are written.
   299  *
   300  * This function does not return, and no further code in the plugin is 
   301  * executed.
   302  *
   303  * @param string		Format specifier string.
   304  * @param ...			Formatting arguments.
   305  * @noreturn
   306  * @error				Always throws SP_ERROR_ABORT.
   307  */
   308 native SetFailState(const String:string[], any:...);
   309 
   310 /**
   311  * Aborts the current callback and throws an error.  This function
   312  * does not return in that no code is executed following it.
   313  *
   314  * @param format		String format.
   315  * @param ...			Format arguments.
   316  * @noreturn
   317  * @error				Always!
   318  */
   319 native ThrowError(const String:fmt[], any:...);
   320 
   321 /**
   322  * Gets the system time as a unix timestamp.
   323  *
   324  * @param bigStamp		Optional array to store the 64bit timestamp in.
   325  * @return				32bit timestamp (number of seconds since unix epoch).
   326  */
   327 native GetTime(bigStamp[2]={0,0});
   328 
   329 /**
   330  * Produces a date and/or time string value for a timestamp.
   331  *
   332  * See this URL for valid parameters: 
   333  * http://cplusplus.com/reference/clibrary/ctime/strftime.html
   334  *
   335  * @param buffer		Destination string buffer.
   336  * @param maxlength		Maximum length of output string buffer.
   337  * @param format		Formatting rules (passing NULL_STRING will use the rules defined in sm_datetime_format).
   338  * @param stamp			Optional time stamp.
   339  * @noreturn
   340  * @error			Buffer too small or invalid time format.
   341  */
   342 native FormatTime(String:buffer[], maxlength, const String:format[], stamp=-1);
   343 
   344 /**
   345  * Loads a game config file.
   346  *
   347  * @param file			File to load.  The path must be relative to the 'gamedata' folder under the config folder 
   348  *					and the extension should be omitted.
   349  * @return			A handle to the game config file or INVALID_HANDLE in failure.
   350  */
   351 native Handle:LoadGameConfigFile(const String:file[]);
   352 
   353 /**
   354  * Returns an offset value.
   355  *
   356  * @param gc			Game config handle.
   357  * @param key			Key to retrieve from the offset section.
   358  * @return			An offset, or -1 on failure.
   359  */
   360 native GameConfGetOffset(Handle:gc, const String:key[]);
   361 
   362 /**
   363  * Gets the value of a key from the "Keys" section.
   364  *
   365  * @param gc			Game config handle.
   366  * @param key			Key to retrieve from the Keys section.
   367  * @param buffer		Destination string buffer.
   368  * @param maxlen		Maximum length of output string buffer.
   369  * @return				True if key existed, false otherwise.
   370  */
   371 native bool:GameConfGetKeyValue(Handle:gc, const String:key[], String:buffer[], maxlen);
   372 
   373 /**
   374  * Returns the operating system's "tick count," which is a number of 
   375  * milliseconds since the operating system loaded.  This can be used
   376  * for basic benchmarks.
   377  *
   378  * @return				Tick count in milliseconds.
   379  */
   380 native GetSysTickCount();
   381 
   382 /**
   383  * Specifies that the given config file should be executed after plugin load.
   384  * OnConfigsExecuted() will not be called until the config file has executed, 
   385  * but it will be called if the execution fails.
   386  *
   387  * @param autoCreate	If true, and the config file does not exist, such a config
   388  *						file will be automatically created and populated with
   389  *						information from the plugin's registered cvars.
   390  * @param name			Name of the config file, excluding the .cfg extension.
   391  *						If empty, <plugin.filename.cfg> is assumed.
   392  * @param folder		Folder under cfg/ to use.  By default this is "sourcemod."
   393  * @noreturn
   394  */
   395 native AutoExecConfig(bool:autoCreate=true, const String:name[]="", const String:folder[]="sourcemod");
   396 
   397 /**
   398  * Sets a native as optional, such that if it is unloaded, removed,
   399  * or otherwise non-existent, the plugin will still work.  Calling
   400  * removed natives results in a run-time error.
   401  *
   402  * @param name			Native name.
   403  * @noreturn
   404  */
   405 native MarkNativeAsOptional(const String:name[]);
   406 
   407 /**
   408  * Registers a library name for identifying as a dependency to 
   409  * other plugins.
   410  *
   411  * @param name			Library name.
   412  * @noreturn
   413  */
   414 native RegPluginLibrary(const String:name[]);
   415 
   416 /**
   417  * Returns whether a library exists.  This function should be considered 
   418  * expensive; it should only be called on plugin to determine availability 
   419  * of resources.  Use OnLibraryAdded()/OnLibraryRemoved() to detect changes 
   420  * in optional resources.
   421  *
   422  * @param name			Library name of a plugin or extension.
   423  * @return				True if exists, false otherwise.
   424  */
   425 native bool:LibraryExists(const String:name[]);
   426 
   427 /**
   428  * Returns the status of an extension, by filename.
   429  *
   430  * @param name			Extension name (like "sdktools.ext").
   431  * @param error			Optional error message buffer.
   432  * @param maxlength		Length of optional error message buffer.
   433  * @return				-2 if the extension was not found.
   434  *						-1 if the extension was found but failed to load.
   435  * 						 0 if the extension loaded but reported an error.
   436  * 						 1 if the extension is running without error.
   437  */
   438 native GetExtensionFileStatus(const String:name[], String:error[]="", maxlength=0);
   439 
   440 /**
   441  * Called after a library is added that the current plugin references 
   442  * optionally. A library is either a plugin name or extension name, as 
   443  * exposed via its include file.
   444  *
   445  * @param name			Library name.
   446  */
   447 forward OnLibraryAdded(const String:name[]);
   448 
   449 /**
   450  * Called right before a library is removed that the current plugin references 
   451  * optionally.  A library is either a plugin name or extension name, as 
   452  * exposed via its include file.
   453  *
   454  * @param name			Library name.
   455  */
   456 forward OnLibraryRemoved(const String:name[]);
   457 
   458 #define MAPLIST_FLAG_MAPSFOLDER		(1<<0)		/**< On failure, use all maps in the maps folder. */
   459 #define MAPLIST_FLAG_CLEARARRAY		(1<<1)		/**< If an input array is specified, clear it before adding. */
   460 #define MAPLIST_FLAG_NO_DEFAULT		(1<<2)		/**< Do not read "default" or "mapcyclefile" on failure. */
   461 
   462 /**
   463  * Loads a map list to an ADT Array.
   464  *
   465  * A map list is a list of maps from a file.  SourceMod allows easy configuration of 
   466  * maplists through addons/sourcemod/configs/maplists.cfg.  Each entry is given a 
   467  * name and a file (for example, "rtv" => "rtv.cfg"), or a name and a redirection 
   468  * (for example, "rtv" => "default").  This native will read a map list entry, 
   469  * cache the file, and return the list of maps it holds.  
   470  *
   471  * Serial change numbers are used to identify if a map list has changed.  Thus, if 
   472  * you pass a serial change number and it's equal to what SourceMod currently knows 
   473  * about the map list, then SourceMod won't reparse the file.
   474  *
   475  * If the maps end up being read from the maps folder (MAPLIST_FLAG_MAPSFOLDER), they 
   476  * are automatically sorted in alphabetical, ascending order.
   477  *
   478  * Arrays created by this function are temporary and must be freed via CloseHandle().
   479  * Modifying arrays created by this function will not affect future return values or 
   480  * or the contents of arrays returned to other plugins.
   481  *
   482  * @param array			Array to store the map list.  If INVALID_HANDLE, a new blank 
   483  *						array will be created.  The blocksize should be at least 16; 
   484  *						otherwise results may be truncated.  Items are added to the array 
   485  *						as strings.  The array is never checked for duplicates, and it is 
   486  *						not read beforehand.  Only the serial number is used to detect 
   487  *						changes.
   488  * @param serial		Serial number to identify last known map list change.  If -1, the 
   489  *						the value will not be checked.  If the map list has since changed, 
   490  *						the serial is updated (even if -1 was passed).  If there is an error 
   491  *						finding a valid maplist, then the serial is set to -1.
   492  * @param str			Config name, or "default" for the default map list.  Config names 
   493  *						should be somewhat descriptive.  For example, the admin menu uses 
   494  *						a config name of "admin menu".  The list names can be configured 
   495  *						by users in addons/sourcemod/configs/maplists.cfg.
   496  * @param flags			MAPLIST_FLAG flags.
   497  * @return				On failure:
   498  *						 INVALID_HANDLE is returned, the serial is set to -1, and the input 
   499  *						 array (if any) is left unchanged.
   500  *						On no change:
   501  						 INVALID_HANDLE is returned, the serial is unchanged, and the input 
   502  						 array (if any) is left unchanged.
   503  *						On success:
   504  *						 A valid array Handle is returned, containing at least one map string.  
   505  *						 If an array was passed, the return value is equal to the passed Array 
   506  *						 Handle.  If the passed array was not cleared, it will have grown by at 
   507  *						 least one item.  The serial number is updated to a positive number.
   508  * @error				Invalid array Handle that is not INVALID_HANDLE.
   509  */
   510 native Handle:ReadMapList(Handle:array=INVALID_HANDLE,
   511 						  &serial=-1,
   512 						  const String:str[]="default",
   513 						  flags=MAPLIST_FLAG_CLEARARRAY);
   514 						  
   515 /**
   516  * Makes a compatibility binding for map lists.  For example, if a function previously used 
   517  * "clam.cfg" for map lists, this function will insert a "fake" binding to "clam.cfg" that 
   518  * will be overridden if it's in the maplists.cfg file.
   519  *
   520  * @param name			Configuration name that would be used with ReadMapList().
   521  * @param file			Default file to use.
   522  * @noreturn
   523  */
   524 native SetMapListCompatBind(const String:name[], const String:file[]);
   525 
   526 /**
   527  * Called when a client has sent chat text.  This must return either true or 
   528  * false to indicate that a client is or is not spamming the server.
   529  *
   530  * The return value is a hint only.  Core or another plugin may decide 
   531  * otherwise.
   532  *
   533  * @param client		Client index.  The server (0) will never be passed.
   534  * @return				True if client is spamming the server, false otherwise.
   535  */
   536 forward bool:OnClientFloodCheck(client);
   537 
   538 /**
   539  * Called after a client's flood check has been computed.  This can be used 
   540  * by antiflood algorithms to decay/increase flooding weights.
   541  *
   542  * Since the result from "OnClientFloodCheck" isn't guaranteed to be the 
   543  * final result, it is generally a good idea to use this to play with other 
   544  * algorithms nicely.
   545  *
   546  * @param client		Client index.  The server (0) will never be passed.
   547  * @param blocked		True if client flooded last "say", false otherwise.
   548  * @noreturn
   549  */
   550 forward OnClientFloodResult(client, bool:blocked);
   551 
   552 #include <helpers>
   553 #include <entity>
   554 #include <entity_prop_stocks>
   555