Difference between revisions of "AMX Mod X 1.9 API Changes"

From AlliedModders Wiki
Jump to: navigation, search
m (Added info about get_playersnum_ex)
m (Predefined Constants)
Line 98: Line 98:
 
! style="padding: 0.4em;" | Description
 
! style="padding: 0.4em;" | Description
 
|-
 
|-
| style="padding: 0.4em;" | {{tt|__BINARY_NAME__|bgcolor=white}}
+
| style="padding: 0.4em;" | {{tt|__BINARY__|bgcolor=white}}
 
| style="padding: 0.4em;" | Name of the compiled plugin. Example: {{tt|admin.amxx|bgcolor=none}}
 
| style="padding: 0.4em;" | Name of the compiled plugin. Example: {{tt|admin.amxx|bgcolor=none}}
 
|-
 
|-
| style="padding: 0.4em;" | {{tt|__BINARY_PATH__|bgcolor=white}}
+
| style="padding: 0.4em;" | {{tt|__FILE__|bgcolor=white}}
| style="padding: 0.4em;" | Absolute path to the compiled plugin. Example: {{tt|/home/hlds/cstrike/addons/amxmodx/plugins/admin.amxx|bgcolor=none}}
+
| style="padding: 0.4em;" | Name of the source plugin. Custom includes is supported. Example: {{tt|admin.sma|bgcolor=none}}, {{tt|myinclude/myfile.inc|bgcolor=none}}
 
|-
 
|-
 
| style="padding: 0.4em;" | {{tt|__LINE__|bgcolor=white}}
 
| style="padding: 0.4em;" | {{tt|__LINE__|bgcolor=white}}

Revision as of 15:23, 9 September 2018

Ambox content soft.svg  This version is not yet released. The release notes are not final.


Note:These are just the API changes from AMX Mod X 1.8.2 to AMX Mod X 1.9. Click here for the full AMX Mod X 1.9 Release Notes.
Hint:This page includes hidden examples or API reference that you can toggle with .

Documentation

A large part of the scripting documentation has been improved and an online version with searching capability can be found at https://amxmodx.org/api/.

Gamedata

As stated in the Release Notes, we have now gamedata files to avoid to hard code data related to the game or engine. Such files located in the amxmodx/data/gamedata/ directory.

Gamedata files shipped with AMX Mod X can and will be updated at any time, therefore it is strongly discouraged to edit them manually.
To make custom gamedata changes, please use the custom folder under the gamedata directory. All files under this directory are parsed (in an undefined order) after the main files are loaded. They will never be overwritten.

The files structure is currently arranged this way:

├─ common.games │ ├─ entities.games │ │ └─ $mod │ │ ├─ offsets-$class.txt │ │ ├─ ... │ ├─ gamerules.games │ │ └─ $mod │ │ ├─ offsets-$class.txt │ │ ├─ ... │ ├─ hostages.games │ │ └─ $mod │ │ ├─ offsets-$class.txt │ │ ├─ ... │ ├─ others.games │ │ └─ $mod │ │ ├─ offsets-$class.txt │ │ ├─ ... │ ├─ functions.engine.txt │ ├─ globalvars.engine.txt │ └─ master.games.txt ├─ modules.games │ ├─ master.games.txt │ └─ game.cstrike.txt

The main directories are:

  • common.games contains the shared data.
  • modules.games contains the data per module.

In those directories, you will find:

  • master.games.txt which references all the files to be loaded by the core/modules.

Inside common.games directory:

  • entities.games, entities.games, entities.games and others.games directories contains the $class member's offset per-$mod. Related to gamerules object but also player, hostage, item and weapons entities.
  • functions.engine.txt contains the symbols/signatures of functions in the engine.
  • globalvars.engine.txt contains the symbols/signatures of global variables in the engine.

Inside modules.games directory:

  • game.cstrike.txt contains CS-specific data such as the symbol/signatures of functions and others static datas.
Note:More details about the file format can be found in the Quick Guide in #Game_Config_Parser.

Compiler

Along a bunch of fixed issues, there are some improvements/features worth to be noted.

Emscripten support

The AMX Mod X Compiler can now be compiled with Emscripten allowing it to run inside of a web browser.

A good example is Spider, a web-based, entirely client-side, editor and compiler for [Source]Pawn development (by asherkin).

Increased Limits

Name/function and input line maximum length (in characters) have been increased.

Description Old value New value
Name/Function 31 63
Input Line 511 4095

Predefined Constants

Global Description
__BINARY__ Name of the compiled plugin. Example: admin.amxx
__FILE__ Name of the source plugin. Custom includes is supported. Example: admin.sma, myinclude/myfile.inc
__LINE__ Current line from the plugin's source code.
Note:Values are populated at compile time.

Pragma

A new #pragma deprecated has been added to tell the compiler that this specific native/stock is deprecated.
This will issue a warning upon the compilation.

Example:

String Literal Contatenation

This basically allows you to concatenate literal strings and stringizing a parameter in macro substitution only (so possible breakage is very limited).

Description Symbol
To concatenate +
To Stringize #
Example:

Internal Core Changes

String Buffer

The buffer size AMX Mod X uses internally to retrieve strings has been increased from 3k to 16k.

Note:A MAX_STRING_LENGTH define has been added in amxconst.inc.
Note:By default plugins don't have enough memory available to allocate an array of this size.
You probably should not use this define to actually declare a buffer unless you absolutely have to.
Look at #pragma dynamic to increase a plugins available memory.

New Core APIs

Automatic Config File

This provides a system for plugins to automatically generate config files with plugin's cvars which get executed on load.
This is done via the AutoExecConfig native.

Once all configuration files are executed, OnConfigsExecuted is called. This forward will always be called, even if your plugin had no configs or if it was loaded late.

Native Description
AutoExecConfig  Specifies that the given config file should be executed after plugin load.
Forward Description
OnConfigsExecuted  Called when the map has loaded, and all configs are done executing.
OnAutoConfigsBuffered  Called when the map has loaded, right after plugin_cfg but any time before OnConfigsExecuted.
Example:

DataPack

This offers you a way to dynamically store and move around various types of data.

Datapacks provide a way to store and move around arbitrary amounts (and types) of data in AMX Mox X, available from datapack.inc.
Data is packed into a single cell value - the DataPack handle. This handle can be passed around more easily, can be returned by functions and can simulate advanced concepts like string consummation.

Native Description
Creating & Disposing
CreateDataPack  Creates a new datapack.
DestroyDataPack  Destroys the datapack and frees its memory.
Resetting
ResetPack  Resets the datapack read/write position to the start.
Writing data
WritePackCell  Packs a cell value into a datapack.
WritePackFloat  Packs a float value into a datapack.
WritePackString  Packs a string into a datapack.
Reading data
ReadPackCell  Reads a cell from a Datapack.
ReadPackFloat  Reads a float from a Datapack.
ReadPackString  Reads a string from a Datapack.
Managing position
GetPackPosition  Returns the datapack read/write position.
SetPackPosition  Sets the datapack read/write position.
Example:

Game Config Parser

Now we have gamedata files, we strongly encourage any plugins which hardcode static game datas to use the following API.

Native Description
Loading & Closing file
LoadGameConfigFile  Loads a game config file.
CloseGameConfigFile  Destroys a game config and frees its memory.
Getting value
GameConfGetOffset  Returns an offset value.
GameConfGetClassOffset  Returns an offset value given a classname.
GameConfGetKeyValue  Gets the value of a key from the "Keys" section.
GameConfGetAddress  Finds an address calculation in a GameConfig file.
Quick guide:

Hasher

Supports several new hash types: CRC32, MD5, SHA*, Keccak*.

Note:The following API deprecates md5 and md5_file natives.
Native Description
hash_string  Generates a hash value (message digest).
hash_file  Generates a hash value using the contents of a given file.

The available HashType constants are:

  • Hash_Crc32
  • Hash_Md5
  • Hash_Sha1
  • Hash_Sha256
  • Hash_Sha3_224
  • Hash_Sha3_256
  • Hash_Sha3_384
  • Hash_Sha3_512
  • Hash_Keccak_224
  • Hash_Keccak_256
  • Hash_Keccak_384
  • Hash_Keccak_512
Example:

Stack Structure

A stack is a LIFO (last in, first out) dynamic vector of of items.

Stacks provide only two operations:

  • Push, adding an item to the top.
  • Pop, removing an item from the top, in reverse-push order.
Note:An example is available in the testsuite directory, see stacktest.sma.
Native Description
Creating & Destroying
CreateStack  Creates a stack structure.
DestroyStack  Destroys a stack and frees its memory.
Pushing Data
PushStackCell  Pushes a value onto the end of the stack, adding a new index.
PushStackString  Pushes a string onto the end of a stack, truncating it if it is too long.
PushStackArray  Pushes an array of cells onto the end of a stack.
Poping Data
PopStackCell  Pops a cell value from a stack.
PopStackString  Pops a string value from a stack.
PopStackArray  Pops an array of cells from a stack.
Others
IsStackEmpty  Returns if a stack is empty.
Stock Description
PopStack  Pops a value off a stack, ignoring it completely.

Text Parser INI/SMC

Event-based text parser to read data in an unified way. It supports INI and SMC (similar to VTF) formats.

Note:An example is available in the testsuite directory, see textparse.sma.

SMC Format

Technical format detail:
Native Description
SMC_CreateParser  Creates a new SMC parser.
SMC_DestroyParser  Disposes of an SMC parser.
SMC_ParseFile  Parses a config file.
SMC_SetParseStart  Sets the SMC_ParseStart function of a parse handle.
SMC_SetParseEnd  Sets the SMC_ParseEnd function of a parse handle.
SMC_SetReaders  Sets the three main reader functions.
SMC_SetRawLine  Sets a raw line reader on an text parser handle.
SMC_GetErrorString  Gets an error string for an SMCError code.

INI Format

Technical format detail:
Native Description
INI_CreateParser  Creates a new SMC parser.
INI_DestroyParser  Disposes of an INI parser.
INI_ParseFile  Parses an INI config file.
INI_ParseStart  Sets the INI_ParseStart function of a parse handle.
INI_SetParseEnd  Sets the INI_ParseEnd function of a parse handle.
INI_SetReaders  Sets the two main reader functions.
INI_SetRawLine  Sets a raw line reader on an INI parser handle.

Existing core APIs additions

Client

Behavior changes

  • The following natives can now be used on connecting players: find_player, get_players and engclient_print (console only).
  • set_user_rendering default color and amount are now set to 0 to follow game behavior.

(Dis)connection

Note:The client_disconnect forward is deprecated in favor of client_disconnected.
This will be called in some additional cases that client_disconnect doesn't cover, most notably when a client aborts the connection process.
It is guaranteed to pair with the client_connect forward.
Forward Description
client_connectex  Called when a client is connecting.
client_disconnected  Called when a client is disconnected from the server.
client_remove  Called when a client entity has been removed from the server.

New Natives & Stocks

For the sake of better understanding and readability, find_player and get_players have now their counterparts which use the flags as name constants instead of letter. It is encouraged to use them instead.

Native & Stock Description
find_player_ex  Finds a player given a filter.
get_players_ex  Stores a filtered list of client indexes to an array.
get_playersnum_ex  Returns the number of clients on the server that match the specified flags.
Example:

New params

Native parameter Description
user_silentkill flag  If nonzero, the death will not affect the client's score.
Forward parameter Description
client_authorized authid  Client auth

Command

Callback

Native Description
amxclient_cmd  Executes a command from the client without actually sending it to the client's DLL.
Similar to engclient_cmd with the difference this triggers plugin command hooks.

Arguments conversion

New natives to retrieve a command's argument directly as an integer or float instead of as a string (read_argv()).

Native Description
read_argv_int  Retrieves argument of client command as integer value.
read_argv_float  Retrieves argument of client command as float value.
Example:

Translatable description

In order to encourage the translations of command's description, a new parameter is available.
This is useful for use with the amx_help client command for example.

Native parameter Description
register_clcmd
register_concmd
register_srvcmd
info_ml  If true, the parameter info will be looked up as multilingual key.
Example:

Cvar

In order to manage cvars more easily, several new cvar features have been added.

Note:A cvar managed at least once is now cached internally, for faster lookup, that's it.
Note:The cvar API is now moved to its own cvars.inc include file.

Hooking

You can now hook when a cvar value has changed. This allows plugins to react to cases where other plugins or clients change a cvar's value.

Native Description
hook_cvar_change  To create a hook
disable_cvar_hook  To disable a hook
enable_cvar_hook  To enable a hook
Example:

Binding

There are situations where you don't need to hook/manage a cvar value and you would wish to not deal with cvar pointers.
You can now bind a cvar's value to a global variable. This means that variable value will be always up to date.

Native Description
bind_pcvar_num  To bind an integer
bind_pcvar_float  To bind a float
bind_pcvar_string  To bind a string
Example:

Boundary

Having a better control over a cvar's value, we can enforce the value to be in a defined boundary.

Description Native
get_pcvar_bounds  To get a boundary
set_pcvar_bounds  To set a boundary
Note:CvarBounds has the following values:
  • CvarBound_Upper
  • CvarBound_Lower
Example:

Constant

A missing FCVAR_NOEXTRAWHITEPACE flag has been added.
It automatically strips trailing/leading white space from the string value.

Creating

A new create_cvar native has been added, similar to register_cvar but with two new features:

Description Similar to command, you can explain shorlty what does the cvar. The message can be retrieved with get_plugins_cvar and can be read from amxx cvars detailed output.
The description is used with AutoExecConfig for example.
Boudary You can set directly a boudary, either a minimum value, a maximum value or both.
Example:

Command

The amxx cvars shows now more informations about a cvar state. Here an example of output:

Managed cvars:
       NAME                     VALUE                    PLUGIN             HOOKED   MIN     MAX
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 [  1] amx_mode                 1                        admin.amxx         no       -       -
 [  2] amx_password_field       _pw                      admin.amxx         no       -       -
 [  3] amx_default_access       z                        admin.amxx         no       -       -
 [  4] amx_vote_ratio           0.02                     admin.amxx         no       -       -
 [  5] amx_something            something                test-hook.amxx     yes      -       -
 [  6] amx_leet                 42                       test-bounds.amxx   no       0.00    42.00
 ...

It can show further details if you specify a cvar or index from the table: amxx cvars <index or cvar name>

amxx cvars 6
 
Cvar details :
 
 Cvar name   : amx_leet
 Value       : 42
 Def. value  : 1337
 Description :
 Flags       : FCVAR_EXTDLL
 
 STATUS        PLUGIN                     INFOS
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 Registered    test-bounds.amxx           -
 Min value     test-bounds.amxx           0.000000
 Max value     test-bounds.amxx           42.000000

Others

Native Description
get_pcvar_bool  Returns an boolean value from a cvar via direct pointer access.
set_pcvar_bool  Sets a boolean value to a cvar via direct pointer access.

CellArray

A bunch of natives have been added to complete the existing API. You are now able to:

  • Clone an array
  • Resize an array
  • Find a value or string inside an array
  • Control more precisely how the data is retrieved/saved
Note:Arrays are heterogeneous. This means you can save different data types into a list.
A good example is the Stack Structure API which is actually based on Array (internal library, that's it).
Note:Initially the reserved parameter in ArrayCreate was intended to create blank entries that would immediately be usable with ArrayGet/Set functions.
This functionality was never working as intended, and can now be achieved using ArrayResize.


Cloning

Native Description
ArrayClone  Clones an array.
Example:

Resizing

Native Description
ArrayResize  Resizes an array.
Example:

Finding a value

Native Description
ArrayFindValue  Searches through the array and returns the index of the first occurence of the specified value.
ArrayFindString  Searches through the array and returns the index of the first occurence of the specified string.
Example:


Sorting

Along two new ArraySort and SortADTArray natives, there is also a new Sort_Random method.

Native Description
ArraySortEx  A faster version of ArraySort.
SortADTArray  To sort directly with a sort method.

New params

Native parameter Description
ArrayGetArray
ArraySetArray
ArrayPushArray
size  Controls the number of elements to use.
ArrayGetCell
ArraySetCell
achar
block
 Specifies which block and retrieves a value as byte.

CellTrie

The word "Trie" in this API is historical. As of AMX Mod X 1.9, tries have been internally replaced with hash tables, which have O(1) insertion time instead of O(n).
As consequence, the API has been completed and you can now:

  • Get a trie size
  • Control more precisely the data on insertion/retrieval
  • Iterate over a trie
Note:Tries are heterogeneous. This means you can save different data types into a list.

Getting size

Native Description
TrieGetSize  Returns the number of entries in a hash map.

Iterating

There are two ways to iterate over a trie:

  • Snapshots
As the name suggested, it will duplicate the whole set of keys (only) into a separate list. Any changes to the original list will not affect the snapshot.
It's an expensive operation, but can be stored.
Native Description
TrieSnapshotCreate  Creates a snapshot of all keys in a hash map.
TrieSnapshotLength  Returns the number of keys in a map snapshot.
TrieSnapshotGetKey  Retrieves the key string of a given key in a map snapshot.
TrieSnapshotDestroy  Retrieves the key string of a given key in a map snapshot.
Note:The keys are not sorted.
Example:
  • Iterator
A contrario, Iterators are designed to be short-lived and not stored, and creating them is very cheap.
Reading data from an iterator is just as fast as reading directly from the map.
This is useful if you just need to iterate (or eventually updating values of existing keys, which is allowed)
Native Description
TrieIterCreate  Creates an iterator for a map.
TrieIterEnded  Returns if the iterator has reached its end and no more data can be read.
TrieIterNext  Advances the iterator to the next key/value pair if one is available.
TrieIterGetKey  Retrieves the key the iterator currently points to.
TrieIterGetSize  Retrieves the number of elements in the underlying map.
TrieIterGetCell  Retrieves a value at the current position of the iterator.
TrieIterGetString  Retrieves a string at the current position of the iterator.
TrieIterGetArray  Retrieves an array at the current position of the iterator.
TrieIterDestroy  Destroys an iterator handle.
Note:The keys are not sorted.
Example:

New params

Native parameter Description
TrieSetString
TrieSetArray
replace  Makes operation fail if key already set.
TrieGetString
TrieGetArray
size  Returns the number of bytes written in the buffer.

Event

New natives

Native Description
register_event_ex  Registers a function to be called on a given game event.
A wrapper of register_event using flags as strings.
enable_event
disable_event
 Enables a function hook of a game event which has been previously registered with register_event or register_event_ex.
 Disables a function hook of a game event which has been previously registered with register_event or register_event_ex.
enable_logevent
disable_logevent
 Enables a function hook of a game log event which has been previously registered with register_logevent.
 Disables a function hook of a game log event which has been previously registered with register_logevent.

New flags

Native flags Description
register_event "f"
"g"
 Call only if sent to human client ("b" flag required)
Call only if sent to bot ("b" flag required).


File

Valve FileSystems

Thanks to the IFileSystem interface from HLSDK, we are now able to make more operations possible with files via Valve File System through Valve search paths (example: download directory).
This is handy when you want to deal with files which are not necessary existing directly in the game directory.

Not all natives are concerned. This features some new natives and enhanced others existing ones with small quality of life changes.

Valve Paths

Path ID Description
GAME All paths related to current mod, including fallback. Depending settings, it includes: <gamedir>_lv/_addon/_language/_hd and <gamedir> itself.
GAMECONFIG The default writable directory: <gamedir>.
GAMEDOWNLOAD The download directory: <gamedir>_download.
GAME_FALLBACK All paths related to fallback game, same as GAME (example: czero has cstrike as fallback. Others mods have usually the default game valve, including cstrike).
DEFAULTGAME All paths related to the default game which is valve, same as GAME.
BASE The base path where server is installed.

Native Support

Some natives supports partially Valve FS, where a path ID can't be provided and this will search in all paths instead.

Native parameter Description
delete_file unlink
file_exists partially
dir_exists partially
file_size
fopen
mkdir
open_dir
use_valve_fs
valve_path_id
 Uses the Valve file system via a search path from gameinfo.

Some natives are not adjusted because not exposed by Valve FS:

  • rename_file
  • rmdir

New Natives

Native Description
FileReadInt8
FileReadUint8
FileReadInt16
FileReadUint16
FileReadInt32
 Reads a single value from a file.
More sane and better designed natives to read a single value (proper type, unsigned byte/short support and returns 1 or 0).
FileWriteInt8
FileWriteInt16
FileWriteInt32
 Writes a single value from a file.
More sane and better designed natives to write a single value (proper type, unsigned byte/short support and returns 1 or 0).
GetFileTime  Returns a file timestamp as a unix timestamp.
SetFilePermissions  Changes a file or directories permissions.

New params

Native parameter Description
fputs null_term  True to append NULL terminator, false otherwise.
mkdir 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.
open_dir
next_file
type  Optional variable to store the file type.

Others

There are as well some minor additions or changes:

  • Added a new define PLATFORM_MAX_PATH to represent a maximum path length.
  • Added any: tag to some natives.
  • read_dir: outlen parameter is now optional.
  • read_file: txtlen parameter is now optional. Adjusted as well buffer to 2048 to match buffer size in write_file.
  • file_size: Fixed potential issue with old compiled plugin which doesn't have the flag parameter. Added FSOPT_* constants as well for use with this flag parameter.


General

Constant

  • DMG_GRENADE (Counter-Strike only)
  • Three missing SVC_ messages (PR 223)
    • SVC_RESOURCELOCATION
    • SVC_SENDCVARVALUE
    • SVC_SENDCVARVALUE2
  • Client statistics:
    • STATSX_KILLS
    • STATSX_DEATHS
    • STATSX_HEADSHOTS
    • STATSX_TEAMKILLS
    • STATSX_SHOTS
    • STATSX_HITS
    • STATSX_DAMAGE
    • STATSX_RANK
    • STATSX_MAX_STATS
  • Objective based statistics for CS only:
    • STATSX_TOTAL_DEFUSIONS
    • STATSX_BOMBS_DEFUSED
    • STATSX_BOMBS_PLANTED
    • STATSX_BOMB_EXPLOSIONS
    • STATSX_MAX_OBJECTIVE
  • Client statistics for DoD only:
    • DODX_KILLS
    • DODX_DEATHS
    • DODX_HEADSHOTS
    • DODX_TEAMKILLS
    • DODX_SHOTS
    • DODX_HITS
    • DODX_DAMAGE
    • DODX_POINTS
    • DODX_RANK
    • DODX_MAX_STATS

Forward

  • Added FP_VAL_BYREF to pass values by reference in forwards.
  • ExecuteForward can now be called without the need to create variable for returned value.

Others

Native Description
has_map_ent_class  Returns if a map contains at least one entity with the provided class name.
engine_changelevel  Changes the map.
Note:This has the same behavior as using the "changelevel" server command, but will also trigger the server_changelevel forward in AMXX plugins.
It will also notify any Metamod plugins that are hooking the pfnChangeLevel function.
RequestFrame  Creates a single use hook for the next frame.
Stock Description
set_task_ex  Calls a function after a specified time has elapsed.
Note:Similar to set_task but it allows you to use named constants for flags instead of letters.

XS

Stock Description
xs_vec_len_2d  Computes the length of a 2D vector.
xs_vec_distance  Computes the distance between two vectors (points).
xs_vec_distance_2d  Computes the distance between two 2D vectors (points).
xs_vec_add_scaled  Adds the second vector scaled by a scalar to the first.
xs_vec_sub_scaled  Subtracts the second vector scaled by a scalar from the first one.

Menu

Timeout

Timeout is now added to newmenus, working similar to those of show_menu.

When a menu is acted upon after the specified timeout has run out it will pass a new MENU_TIMEOUT status code into the menu handler.
Actions are:

  • player disconnect
  • selecting an item,
  • cancelling/destroying the menu in the plugin,
  • sending a different menu or using get_user_menu on a player with an open menu.

Just like with the old menus timeouts are not actively polled, and MENU_TIMEOUT is not guaranteed to fire directly after the time has run out.
Also get_user_menu will detect timeouts and reset the menu flags, which is why it also has to trigger the callback.

Note:An example is available at PR 21.
Native parameter Description
menu_display time  If >=0 menu will timeout after this many seconds.

New native & stock

Native Description
menu_addblank2  Adds a blank line to a menu, always shifting the numbering down.
Note:This fixes an unexpected behavior with the original ones when slot param is set to 1
Stock Description
reset_menu  Resets the client's menu.

New properties

Property Description
MEXIT_FORCE Forces a proper exit button on unpaginated menus
MPROP_SHOWPAGE Whether to show the page number in menu title
MEXIT_FORCE Function to be called on Back and Next

Prototype of callback:

Called when parsing is halted.
 
@param id        Playeer's index
@param status    Either MENU_BACK or MENU_MORE
 
public function(id, status);
Note:An example is available in the testsuite directory, see menu_page_callback_test.sma.

Others

  • menu_item_getinfo's arguments are now optional
  • show_menu] native is allowed to send empty text


Message

New natives

The float version of message_begin, write_angle, write_coord_f, emessage_begin, ewrite_coord and ewrite_angle:

Native Description
message_begin_f
write_angle_f
write_coord_f
 Marks the beginning of a client message.
 Writes an angle entry to a message using a float value.
 Writes a coordinate entry to a message using a float value.
zmessage_begin_f
ewrite_coord_f
ewrite_angle_f
 Marks the beginning of a client message.
 Writes a coordinate entry to a message using a float value.
 Writes an angle entry to a message using a float value.
Native Description
client_print_color  Sends colored chat messages to clients.
Note:Counter-strike only.
set_dhudmessage
show_dhudmessage
 Sets display parameters for director hudmessages.
 Displays a director message on the client HUD.
elog_message  Logs a message hookable by plugins to the current server log file.
Stock Description
client_printex  Sends a predefined text message to player.

Others

  • Added MSG_INIT support in message_begin native
  • Set set_hudmessage default channel to -1 to reflect auto-channeling support

String

  • Constants and stocks from string.inc have been moved in their own files string_const.inc and string_stocks.inc.
  • strlen has been moved from core.inc to string.inc.
  • strbreak is now replaced by a backwards compatibility stock.

Conversion

Native Description
strtol  Parses the string interpreting its content as an integral number of the specified base, which is returned as integer value.
The function also sets the value of endPos to point to the position of the first character after the number.
strtof  Parses the string interpreting its content as an floating point number and returns its value as a float.
The function also sets the value of endPos to point to the position of the first character after the number.

Format specifier

Specifier Description
%b Binary digits in the value
%n Requires a client index. Expands to a string containing the player's name.
If the client index is 0, the string will be: Console
%N Requires a client index. Expands to 1<2><3><4> where 1 is the player's name, 2 is the player's userid, 3 is the player's SteamID, and 4 the player's team name.
If the client index is 0, the string will be: Console<0><Console><Console>
%l Translates a phrase from a key. Similar to %L with the difference it will use the client's index set internally by the function.
This is only allowed in functions which act directly on one or more clients.
Note:To complement this, a new SetGlobalTransTarget native to set the current index has been added.
This is useful to be used before with natives which are not player-oriented", like a bunch of formatex.
Example:

Formatting

  • set_fail_state has now the ability to format a text.
  • A new native for simple inline formatting:
Native Description
fmt  Formats and returns a string according to the AMX Mod X format rules.
Note:This should only be used for simple inline formatting like in the above example.
Avoid using this function to store strings into variables as an additional copying step is required.
Note:The buffer size is defined by MAX_FMT_LENGTH.
Example:

Others

Native Description
strtok2  Breaks a string in two by token.
Note:This function has been added due to strtok being buggy in some situations.
Stock Description
explode_string  Breaks a string into pieces and stores each piece into an array of buffers.
implode_strings  Joins an array of strings into one string, with a join string inserted in between each given string.
This function complements explode_string.

UTF-8

An effort has been made to provide UTF-8 safety for formatting-capable functions. This includes precision with %s e.g. %.12s.

Few specific functions have been updated as well:

  • console_print
  • client_print, client_print_color
  • get_user_name
  • get_concmd, get_clcmd, get_srvcmd
  • get_cvar_string, get_pcvar_string
  • format_time
  • read_data
  • get_localinfo
  • read_argv, read_args
  • read_logdata, read_logargv
  • get_module
  • read_file
  • fgets
  • ReadPackString
  • ArrayGetString
  • TrieGetString
  • strtok, strtok2
  • strbreak
  • isdigit, isalnum, isspace, isalpha

UTF-8 support has been added in the following functions:

  • containi
  • strfind (with ignorecase set)
  • strcmp (with ignorecase set)
  • strncmp (with ignorecase set)
  • equali
  • replace_string (with ignorecase set)
  • replace_stringex (with ignorecase set)
  • get_players (with name and ignorecase flags set)
  • find_player (with name and ignorecase flags set)

New natives have been added:

Native Description
is_char_upper
is_char_lower
is_char_mb
 Returns whether an alphabetic character is uppercase.
 Returns whether an alphabetic character is lowercase.
 Returns if a character is multi-byte or not.
is_string_category  Checks if the input string conforms to the category specified by the flags.
get_char_bytes  Returns the number of bytes a character is using.
mb_strotolower
mb_strtoupper
mb_ucfirst
mb_strtotitle
 Performs a multi-byte safe (UTF-8) conversion of all chars in string to lower case.
 Performs a multi-byte safe (UTF-8) conversion of all chars in string to upper case.
 Performs a multi-byte safe (UTF-8) conversion of a string's first character to upper case.
 Performs a multi-byte safe (UTF-8) conversion of all chars in string to title case.
replace_string
replace_stringex
 Given a string, replaces all occurrences of a search string with a replacement string.
Note:Similar to replace_all stock, but implemented as native and with different algorithm.
This native doesn't error on bad buffer size and will smartly cut off the string in a way that pushes old data out.

 Given a string, replaces the first occurrence of a search string with a replacement string.

Note:Similar to replace native, but implemented as native and with different algorithm.
This native doesn't error on bad buffer size and will smartly cut off the string in a way that pushes old data out.
strncmp  Compares two strings parts lexographically.

New stocks:

Stock Description
char_to_upper  Returns an uppercase character to a lowercase character.
char_to_lower  Returns a lowercase character to an uppercase character.

Existing module APIs additions

AMXX SDK

the following functions have been added:

Function Description
MF_SetAmxStringUTF8Char Sets UTF-8 string from char* input
MF_SetAmxStringUTF8Cell Sets UTF-8 string from cell* input
MF_GetAmxStringNull Gets string with NULL_STRING support
MF_GetAmxVectorNull Gets a vector with NULL_VECTOR support
MF_GetConfigManager Gets the config manager for use with gamedata files
MF_LoadAmxScriptEx Saner version of MF_LoadAmxScript which explicits error max length

CStrike

All hardcoded game datas are now moved to its own gamedata file located in data/gamedata/modules.games/game.cstrike.txt.
See AMX_Mod_X_1.9_Release_Notes#Gamedata for more information.

Constant

Numerous constants from the game have added. See the cstrike_const.inc.

Additionally for two natives:

  • CS_NORESET constant for use with cs_set_user_team for skipping the model reset
  • TRAIN_* constants for use with cs_get_user_driving


Entity

Native Description
cs_create_entity  Creates an entity using Counter-Strike's custom CreateNamedEntity wrapper.
Note:Unlike other mods CS keeps track of entities using a custom hashtable.

This function adds entities to this hashtable, providing benefits over the default CreateNamedEntity (used by create_entity for example):

  • Storing entities in a hashtable allows CS to improve classname lookup performance compared to functions like FindEntityByString (used by find_ent_by_class for example) that usually have to loop through all entities incrementally.
  • As CS exclusively uses the hashtable for classname lookup, entities created using the default engine functions will not be found by the game.
    For example "weaponbox" entities are supposed to be automatically cleaned up on round restart but are not considered if they have not been added to the hashtable.
cs_find_ent_by_class
cs_find_ent_by_owner
 Finds an entity in the world using Counter-Strike's custom FindEntityByString wrapper.
 Finds an entity in the world using Counter-Strike's custom FindEntityByString wrapper, matching by owner.
Note:Those functions utilize the hasthable and allows for considerably faster classname lookup compared to the default FindEntityByString (used by find_ent_by_class for example).
This exclusively considers entities in the hashtable, created by the game itself, using cs_create_entity, or added via cs_set_ent_class).
cs_set_ent_class  Sets a custom classname of an entity.
Note:This function adds or updates the classname in the hasthable as well.
This is useful for use with cs_find_ent_by_class and cs_find_ent_by_owner.

Buying

You can now easily detect when an item is being purchased.

Forward Description
CS_OnBuyAttempt  Called when a client attempts to purchase an item.
Note:This is called immediately when the client issues a buy command.
The game has not yet checked if the client can actually buy the weapon.
CS_OnBuy  Called when a client purchases an item.
Note:This is called right before the user receives the item and before the money is deducted from their cash reserves.
Note:For a list of possible item ids see the CSI_* constants
Example:

Items info

Native Description
cs_get_user_weapon_entity  Returns active weapon entity.
cs_get_user_weapon  Returns weapon index of the active weapon.
Note:More reliable than get_user_weapon.
cs_get_item_id  Returns the item id associated with an item name and its aliases.
Note:The item name is case sensitive an can be with or without weapon_ and item_ prefixes. This can be a command alias as well.
Values examples: ak47, weapon_ak47, kevlar, item_kevlar, vest, bullpup, ...
cs_get_translated_item_alias  Returns an item name associated with a command alias.
Note:The alias is case sensitive.
Note:If not an alias to a weapon, buffer will be set with the original alias.
cs_get_item_alias  Returns the alias name associated with an item index.
cs_get_weapon_info  Returns some information about a weapon.
Note:The alias is case sensitive.
Note:If not an alias to a weapon, buffer will be set with the original alias.
Stock Description
cs_get_weapon_class  Returns a weapon class id associated with a weapon id.
cs_is_valid_itemid  Checks whether an item id is not out of bounds.

New params

Forward Parameter Description
cs_set_user_deaths scoreboard  If true the scoreboard will be updated to reflect the new value.
cs_get_armoury_type
cs_set_armoury_type
count  Optional variable to store in the number of times that an item can be retrieved from the same entity before being hidden.
cs_set_user_model update_index  If true, the modelindex is updated as well.
Note:Updating modelindex is useful for custom models which don't have the same structure as the default ones (hitbox, etc..).
Model must be precached before

Others

  • Hostage natives will work now with monster_scientist entity (alias of hostage_entity)
  • cs_get_user_armor Template:Armortype parameter is now optional
  • cs_set_weapon_silen Template:Draw animation has a new value of 2 which follows game behavior to properly draw the animation


Engine

Entity

Native Description
entity_intersects  Returns if two entities bounding boxes intersect by comparing their absolute minimum and maximum origins.
set_ent_rendering  Sets rendering options of an entity.


Hook

You can now unregister hooks from: register_impulse, register_think and register_touch.

Forward Description
unregister_impulse  Removes a previously registered impulse hook.
unregister_think  Removes a previously registered think hook.
unregister_touch  Removes a previously registered touch hook.


Miscellaneous

  • is_visible is now working on player.
  • set_ent_rendering is new working on non-players entities.
  • get_info_keybuffer can now retrieve local key buffer (i.e. using -1).
  • trace_hull gets a new end destination parameter to make it useful.


Safer Natives

Safer natives which returns -1 if not entity found instead of 00 which is a valid value (worldspawn).

Native Description
get_global_edict2  Safe version of get_global_edict.
Returns a edict type value from the server globals.
entity_get_edict2  Safe version of entity_get_edict.
Returns an edict type value from an entities entvar struct.


Usercmd

  • get_usercmd and set_usercmd are now working and can be used in client_cmdStart forward.
Forward Description
client_cmdStart  Called for CmdStart() on a client.


Fakemeta

KVD

This allows the creation of new KVD structures that can be used with Hamsandwich (Ham_Keyvalue).

Native Description
create_kvd
free_kvd
 Creates a KeyValueData handle.
 Frees a KeyValueData handle.


Entity's Private Data (gamedata)

This is now possible to manage value from an entity's private data based off a class and member name.
The related gamedata files are located in data/gamedata/common.games/entities.games directory.

Example:
Native Description
get_ent_data
set_ent_data
 Retrieves an integer value from an entity's private data based off a class and member name.
 Sets an integer value to an entity's private data based off a class and member name.
get_ent_data_float
set_ent_data_float
 Retrieves an float value from an entity's private data based off a class and member name.
 Sets an float value to an entity's private data based off a class and member name.
get_ent_data_vector
set_ent_data_vector
 Retrieves a vector from an entity's private data based off a class and member name.
 Sets a vector to an entity's private data based off a class and member name.
get_ent_data_entity
set_ent_data_entity
 Retrieves an entity index from an entity's private data based off a class and member name.
 Sets an entity index to an entity's private data based off a class and member name.
get_ent_data_string
set_ent_data_string
 Retrieves a string from an entity's private data based off a class and member name.
 Sets a string to an entity's private data based off a class and member name.
get_ent_data_size  Retrieves the size of array of n entity class member.
find_ent_data_info  Finds a offset based off an entity class and member name.


Entity's Private Data

While it's encouraged to use the new natives based off gamedata, this completes the list with new data types supported: edict, bool, byte, short and ehandle.

Native Description
get_pdata_ent
set_pdata_ent
 Tries to retrieve an edict pointer from an entity's private data.
 Sets an edict pointer to an entity's private data.
get_pdata_bool
set_pdata_bool
 Returns a boolean from an entity's private data.
 Sets a boolean to an entity's private data.
get_pdata_byte
set_pdata_byte
 Returns a byte value from an entity's private data.
 Sets a byte value to an entity's private data.
get_pdata_short
set_pdata_short
 Returns a short value from an entity's private data.
 Sets a short value to an entity's private data.
get_pdata_vector
set_pdata_vector
 Returns a vector from an entity's private data.
 Sets a vector to an entity's private data.
get_pdata_ehandle
set_pdata_ehandle
 Tries to retrieve an edict (entity encapsulation) pointer from an entity's private data.
 Sets an edict (entity encapsulation) pointer to an entity's private data.


Gamerules

You have now the ability to manage a value using the gamerules object based off a class and member name.
The gamedata files are located in /data/gamedata/common.games/gamerules.games directory.

Example:
Native Description
get_gamerules_int
set_gamerules_int
 Retrieves an integer value from the gamerules object based off a class and member name.
 Sets an integer value to the gamerules objecta based off a class and member name.
get_gamerules_float
set_gamerules_float
 Retrieves a float value from the gamerules object based off a class and member name.
 Sets an float value to the gamerules objecta based off a class and member name.
get_gamerules_vector
set_gamerules_vector
 Retrieves a vector from the gamerules object based off a class and member name.
 Sets a vector to the gamerules objecta based off a class and member name.
get_gamerules_entity
set_gamerules_entity
 Retrieves an entity index from the gamerules object based off a class and member name.
 Sets an entity index to the gamerules objecta based off a class and member name.
get_gamerules_string
set_gamerules_string
 Retrieves a string from the gamerules object based off a class and member name.
 Sets a string to the gamerules objecta based off a class and member name.
get_gamerules_size  Retrieves the size of array of a gamerules class member.
find_gamerules_info  Finds a gamerules offset based off a class and member name.
Stock Description
get_field_basetype  Returns the data field base type based off a specific field type.


Miscellaneous

  • get/set_pdata_cbase can now be used at map end whereas player's private datas are still valid.
  • EngFunc_PlayBackEvent can now receive a null invoker.
  • KeyValueData usage is now compatible with Hamsandwich module.


GeoIP

Library

The module uses the new MaxMind GeoIP2 API. The relevant advantages are:

  • Should be more precise
  • Data is localized (current supported languages: de, en, es, fr, ja, ru, pt-BR, zh-CN)

If you want further information, see What’s New in GeoIP2.

Note:GeoIP.dat is replaced with GeoLite2-Country.mmdb (default, downloadable) or GeoLite2-City.mmdb (downloadable).

Command

A geoip command is available for troubleshooting: geoip <command> [argument]

Command Description
version  Displays the geoip database metadata such as the current loaded database and its version.
dump <ip> [output file]  Dumps all data from an IP address formatted in a JSON-ish fashion.
An output file is mod-based and if not provided, it will print in the console.

Deprecated natives

geoip_country has been marked as deprecated in favor of geoip_country_ex.
Hardcoding the maximum buffer length and returning "error" if nothing is found, were not quite the good idea.

New natives

The natives which can output localized data, have a new id parameter in order to retrieve data into the player's language.

Native Database Localized Description
geoip_country_ex Country / City Looks up the full country name.
geoip_city City Returns the (localized) city name.
geoip_continent_code City Returns the continent code. Example: EU (Europe)
geoip_continent_name City Returns the (localized) continent name. Example: Europe
geoip_region_code City Returns a region code.
geoip_region_name City Returns a (localized) region name.
geoip_latitude City Returns a city's latitude.
geoip_longitude City Returns a city's longitude.
geoip_distance City Calculates the distance between geographical coordinates.
geoip_timezone City Returns a full time zone. Example: Europe/Paris


Hamsandwich

Games support

The following games are now supported:

  • Deathmatch Classic
  • Adrenaline Gamer
  • Opposing Forces

The following games have been updated to their latest version:

  • Sven Coop v5.13

ItemInfo structure

A new set of functions have added to manage the {ItemInfo structure.

Native Description
CreateHamItemInfo  Creates an ItemInfo handle.
The handle can be used in GetHamItemInfo and SetHamItemInfo.
FreeHamItemInfo  Frees an ItemIndo handle created with CreateHamItemInfo.
GetHamItemInfo
SetHamItemInfo
 Gets a parameter on the fly of the current hook.
 Sets a parameter on the fly of the current hook.
SetHamParamItemInfo  Sets a parameter on the fly of the current hook. This has no effect in post hooks.

Miscellaneous

Native Description
SetParamEntity2  Sets a parameter on the fly of the current hook. This has no effect in post hooks
Note: Same as SetHamParamEntity except the changes made by this native are reflected in the corresponding post forward.
.

Special bot

RegisterHam has now the ability to register a bot without player classname.

Native Parameter Description
RegisterHam specialbot  Whether or not to enable support for bot without "player" classname.

For convenience a stock to make more intuitive registering a function on "player":

Stock Description
RegisterHamPlayer  Hooks the virtual table for the player class.

Virtual function

A lot of missing virtual functions have been added for all games.
Some of the existing common functions have been renamed because they are mod-dependent.

Short overview:

  • Common
  • Common (not supported by Counter-Strike, The Specialists and Natural Selection mods)
  • Specific to Counter-Strike
  • Specific to Day Of Defeat
  • Specific to Earth's Special Forces
  • Specific to Natural Selection
  • Specific to Sven Coop
  • Specific to Opposing Force
  • Specific to Team Fortress Classic
  • Specific to The Specialists

See ham_const.inc for a full list (it starts from line 1182).


MySQL

Connectivity

To improve the connectivity, few features have been added.

Feature Description
Reconnection This has MySQL automatically reconnects if times out or loses connection through MYSQL_OPT_RECONNECT option.
This should prevent "MySQL server has gone away" errors after a while.
Timeout This establishes a default read/write timeout for MySQL connectivity through MYSQL_OPT_CONNECT_TIMEOUT option.
A new option to set globally the timeout (60s by default) can be found in core.ini and a new amx_sql_timeout cvar in sql.cfg .

Miscellaneous

  • Module threading has been updated to be more responsive. This should help in reducing potential hang up in situations such as on change map or lost connection.

Character Set

Stock Description
MySQL_SetCharset  Sets the character set of the current connection.


RegEx

Library

The internal PCRE library version has been updated from 6.4 to 8.35 and has been compiled with UTF-8 support.
If you are interested, see the changelog.

Miscellaneous

  • regex_subtr: The internal static buffer has been increased to match the same size as core and has been made UTF-8 safe.
  • The maximum number of sub-patterns has been increased from 30 to 150.

New Natives & Stocks

Native Description
regex_compile_ex  Precompiles a regular expression.
Note:Similar as regex_compile/_c but with the differences that you can use directly PCRE_* flags and the error parameter is an integer associated to REGEX_ERROR_* flags.
regex_match_all
regex_match_all_c
 Matches a string against a regular (compiled) expression pattern, matching all occurrences of the pattern inside the string.
Note:This is similar to using the g flag in perl regex.
Stock Description
regex_match_simple  Matches a string against a regular expression pattern. Useful if you need to use the pattern one time.}


Socket

  • WinSock is now update from version 1.1 to 2.2
  • Natives won't be registered if WinSock can't be started

Improvements

Native Parameter Description
socket_open _flags

The following flags are additive:

  • SOCK_NON_BLOCKING: if set, the socket will be on nonblocking mode
  • SOCK_LIBC_ERRORS: f set, the new libc errors will be seen on _error
Note:An example is available at PR 301

New natives

Native Description
socket_is_writable  Checks if a socket is marked as writable.
socket_is_readable  Checks if a socket is marked as readable.
Note:This function is an alias of socket_change which is now deprecated.


SQLite

Library

The SQLite library version has been updated from 3.3.13 to 3.24.0.
If you are interested, see the changelog.

Character Set

Stock Description
SQL_SetCharset  Sets the character set of the current connection.

Miscellaneous

  • The queuetime value is now properly passed to the SQL_ThreadQuery callback.

New module

JSON

A JSON module is now part of the official AMX Mod X package.

Essentially:

  • Supports decoding and encoding (also with pretty format)
  • Relies on Parson, which is lighweight and simple JSON library written in C
  • Supports dot notation (Values can be accessed by typing objectA.objectB.value)
  • Allows us to iterate through arrays and objects
Note:Examples are available on Github an in the testsuite directory, see textparse.sma.
Native Description
General
json_parse  Parses JSON string or a file that contains JSON.
json_equals  Checks if the first value is the same as the second one.
json_validate  Validates json by checking if object have identically named fields with matching types.
json_get_parent  Gets value's parent handle.
json_get_type  Gets JSON type of passed value.
json_init_object
json_init_array
json_init_string
json_init_number
json_init_real
json_init_bool
 Inits an empty object.
 Inits an empty array.
 Inits string data.
 Inits a number.
 Inits a real number.
 Inits a boolean value.
json_init_null  Inits a null.
json_deep_copy  Creates deep copy of passed value.
json_free  Frees handle.
json_get_string
json_get_number
json_get_real
json_get_bool
 Gets string data.
 Gets a number.
 Gets a real number.
 Gets a boolean value.
Array
json_array_get_value
json_array_get_string
json_array_get_number
json_array_get_real
json_array_get_bool
json_array_get_count
 Gets a value from the array.
 Gets string data from the array.
 Gets a number from the array.
 Gets a real number from the array.
 Gets a boolean value from the array.
 Gets count of the elements in the array.
json_array_replace_value
json_array_replace_string
json_array_replace_number
json_array_replace_real
json_array_replace_bool
json_array_replace_null
 Replaces an element in the array with value.
 Replaces an element in the array with string data.
 Replaces an element in the array with number.
 Replaces an element in the array with real number.
 Replaces an element in the array with boolean value.
 Replaces an element in the array with null.
json_array_append_value
json_array_append_string
json_array_append_number
json_array_append_real
json_array_append_bool
json_array_append_null
 Appends a value in the array.
 Appends string data in the array.
 Appends a number in the array.
 Appends a real number in the array.
 Appends a boolean value in the array.
 Appends a null in the array.
json_array_remove  Removes an element from the array.
json_array_clear  Removes all elements from the array.
Object
json_object_get_value
json_object_get_string
json_object_get_number
json_object_get_real
json_object_get_bool
 Gets a value from the object.
 Gets string data from the object.
 Gets a number from the object.
 Gets a real number from the object.
 Gets a boolean value from the object.
json_object_get_count
json_object_get_name
 Gets count of the keys in the object.
 Gets name of the object's key.
json_object_get_value_at  Gets a value at the specified position from the object.
json_object_has_value  Checks if the object has a value with a specific name and type.
json_object_set_value
json_object_set_string
json_object_set_number
json_object_set_real
json_object_set_bool
json_object_set_null
 Sets a value in the object.
 Sets string data in the object.
 Sets a number in the object.
 Sets a real number in the object.
 Sets a boolean value in the object.
 Sets a null in the object.
json_object_remove  Removes a key and its value in the object.
json_object_clear  Removes all keys and their values in the object.
Serialization
json_serial_size  Gets size of serialization.
json_serial_to_string  Copies serialized string to the buffer.
json_serial_to_file  Copies serialized string to the file.
Constants & Macros: