KBEngine Module
The KBEngine module provides Python script access to entities, especially timer registration/removal and entity creation.
Member Functions
def addWatcher( path, dataType, getFunction ):
def address( ):
def MemoryStream( ):
def charge( ordersID, dbID, byteDatas, pycallback ):
def createEntity( ):
def createEntityAnywhere( entityType, *params, callback ):
def createEntityRemotely( entityType, baseMB, *params, callback ):
def createEntityFromDBID( entityType, dbID, callback, dbInterfaceName ):
def createEntityAnywhereFromDBID( entityType, dbID, callback, dbInterfaceName ):
def createEntityRemotelyFromDBID( entityType, dbID, baseMB, callback, dbInterfaceName ):
def createEntityLocally( entityType, *params ):
def debugTracing( ):
def delWatcher( path ):
def deleteEntityByDBID( entityType, dbID, callback, dbInterfaceName ):
def deregisterReadFileDescriptor( fileDescriptor ):
def deregisterWriteFileDescriptor( fileDescriptor ):
def executeRawDatabaseCommand( command, callback, threadID, dbInterfaceName ):
def genUUID64( ):
def getResFullPath( res ):
def getWatcher( path ):
def getWatcherDir( path ):
def getAppFlags( ):
def hasRes( res ):
def isShuttingDown( ):
def listPathRes( path, extension ):
def lookUpEntityByDBID( entityType, dbID, callback, dbInterfaceName ):
def matchPath( res ):
def open( res, mode, encoding ):
def publish( ):
def quantumPassedPercent( ):
def registerReadFileDescriptor( fileDescriptor, callback ):
def registerWriteFileDescriptor( fileDescriptor, callback ):
def reloadScript( fullReload ):
def scriptLogType( logType ):
def setAppFlags( flags ):
def time( ):
def urlopen( url, callback, postData, headers ):
Callback Functions
def onBaseAppReady( isBootstrap ):
def onBaseAppShutDown( state ):
def onCellAppDeath( addr ):
def onFini( ):
def onBaseAppData( key, value ):
def onBaseAppDataDel( key ):
def onGlobalData( key, value ):
def onGlobalDataDel( key ):
def onInit( isReload ):
def onLoseChargeCB( orderID, dbID, success, datas ):
def onReadyForLogin( isBootstrap ):
def onReadyForShutDown( ):
def onAutoLoadEntityCreate( entityType, dbID ):
Properties
Member Function Documentation
def addWatcher( path, dataType, getFunction ):
Description:
Interacts with the debug watcher system, allowing users to register a watch variable.
Example:
>>> def countPlayers( ):
>>> i = 0
>>> for e in KBEngine.entities.values():
>>> if e.__class__.__name__ == "Avatar":
>>> i += 1
>>> return i
>>>
>>> KBEngine.addWatcher( "players", "UINT32", countPlayers )
This function adds a watcher variable under the "scripts/players" watcher path. The function countPlayers is called when the watcher is accessed.
Parameters:
path
: The path to create the watcher.
dataType
: The value type of the watcher variable. See: Basic Types
getFunction
: This function is called when the watcher is accessed. It takes no arguments and returns the value to watch.
def address( ):
Description:
Returns the address of the internal network interface.
def MemoryStream( ):
Description:
Returns a new MemoryStream object.
The MemoryStream object stores binary information, allowing users to easily serialize and deserialize Python basic types in the same way as KBEngine's underlying serialization rules.
For example, you can use this object to construct a network packet that KBEngine can parse.
Usage:
>>> s = KBEngine.MemoryStream()
>>> s
>>> b''
>>> s.append("UINT32", 1)
>>> s.pop("UINT32")
>>> 1
Currently, MemoryStream only supports basic data types. See: Basic Types
def charge( ordersID, dbID, byteDatas, pycallback ):
Description:
Billing interface.
Parameters:
ordersID
: string, order ID.
dbID
: uint64, the entity's databaseID.
byteDatas
: bytes, attached data, defined and parsed by the developer.
pycallback
: billing callback.
Billing callback prototype:
(When KBEngine.chargeResponse is called in interfaces, if a callback is set for an order, it will be called)
def on**ChargeCB(self, orderID, dbID, success, datas):
ordersID: string, order ID
dbID: uint64, usually the entity's databaseID
success: bool, whether successful
datas: bytes, attached data, defined and parsed by the developer
def createEntity( ):
Description:
Alias for KBEngine.createEntityLocally.
def createEntityAnywhere( entityType, params, callback ):
Description:
Creates a new Entity entity. The server may choose any Baseapp to create the entity.
This method should be preferred over KBEngine.createEntityLocally, so the server can flexibly choose a suitable Baseapp to create the entity.
The function parameters require the entity type and a Python dictionary to initialize the entity's values.
You do not need to provide all properties in the dictionary; missing properties use the default values from the entity definition file ".def".
Example:
params = {
"name" : "kbe", # base, BASE_AND_CLIENT
"HP" : 100, # cell, ALL_CLIENT, in cellData
"tmp" : "tmp" # baseEntity.tmp
}
def onCreateEntityCallback(entity):
print(entity)
createEntityAnywhere("Avatar", params, onCreateEntityAnywhere)
Parameters:
entityType
: string, the type of Entity to create. Valid types are listed in /scripts/entities.xml.
params
: optional, a Python dictionary. If a key matches an Entity property, its value initializes that property. If a key matches a Cell property, it is added to the entity's cellData property, which is a Python dictionary used to initialize cell entity properties.
callback
: optional callback function, called when the entity is created. The callback receives one argument: the entityCall of the entity on success, or None on failure.
Returns:
Returns the entityCall of the entity via callback.
def createEntityRemotely( entityType, baseMB, params, callback ):
Description:
Creates a new Entity entity on a specified baseapp via the baseMB parameter.
KBEngine.createEntityAnywhere should be preferred.
Parameters are the same as createEntityAnywhere.
Example:
params = {
"name" : "kbe", # base, BASE_AND_CLIENT
"HP" : 100, # cell, ALL_CLIENT, in cellData
"tmp" : "tmp" # baseEntity.tmp
}
def onCreateEntityCallback(entity):
print(entity)
createEntityRemotely("Avatar", baseEntityCall, params, onCreateEntityRemotely)
Parameters:
entityType
: string, type of Entity to create. See /scripts/entities.xml.
baseMB
: BaseEntityCall, an EntityCall of an Entity. The entity will be created on the Baseapp process corresponding to this entity.
params
: optional Python dictionary, as above.
callback
: optional callback, as above.
Returns:
Returns the entityCall of the entity via callback.
def createEntityFromDBID( entityType, dbID, callback, dbInterfaceName ):
Description:
Loads data from the database to create an Entity entity. The new entity will be created on the Baseapp that called this function. If the entity is already checked out from the database, a reference to the existing entity is returned.
Parameters:
entityType
: string, type of Entity to load. See /scripts/entities.xml.
dbID
: database ID of the entity to create. Stored in databaseID.
callback
: optional callback, called when the operation completes. The callback receives three arguments: baseRef, databaseID, and wasActive. On success, baseRef is an entityCall or direct reference to the new entity, databaseID is the entity's database ID, and wasActive indicates if the entity was already active. On failure, baseRef is None, databaseID is 0, and wasActive is False.
dbInterfaceName
: string, optional, specifies which database interface to use, default is "default". Database interfaces are defined in kbengine_defaults.xml->dbmgr->databaseInterfaces.
def createEntityAnywhereFromDBID( entityType, dbID, callback , dbInterfaceName ):
Description:
From the database load data to create an Entity entity. The server may choose any Baseapp to create the entity.
Using this function will help balance the load of BaseApps.
If the entity is already checked out from the database, a reference to the existing entity is returned.
Parameters:
entityType
: string, the type of Entity to create. Valid types are listed in /scripts/entities.xml.
dbID
: database ID of the entity to create. Stored in databaseID.
callback
: optional callback, called when the operation completes. The callback receives three arguments: baseRef, databaseID, and wasActive. On success, baseRef is an entityCall or direct reference to the new entity, databaseID is the entity's database ID, and wasActive indicates if the entity was already active. On failure, baseRef is None, databaseID is 0, and wasActive is False.
dbInterfaceName
: string, optional, specifies which database interface to use, default is "default". Database interfaces are defined in kbengine_defaults.xml->dbmgr->databaseInterfaces.
Returns:
Returns the entityCall of the entity via callback.
def createEntityRemotelyFromDBID( entityType, dbID, baseMB, callback, dbInterfaceName ):
Description:
From the database load data and create an Entity entity on a specified baseapp via the baseMB parameter.
If the entity is already checked out from the database, a reference to the existing entity is returned.
Parameters:
entityType
: string, the type of Entity to create. Valid types are listed in /scripts/entities.xml.
dbID
: database ID of the entity to create. Stored in databaseID.
baseMB
: BaseEntityCall, an EntityCall of an Entity. The entity will be created on the Baseapp process corresponding to this entity.
callback
: optional callback, called when the operation completes. The callback receives three arguments: baseRef, databaseID, and wasActive. On success, baseRef is an entityCall or direct reference to the new entity, databaseID is the entity's database ID, and wasActive indicates if the entity was already active. On failure, baseRef is None, databaseID is 0, and wasActive is False.
dbInterfaceName
: string, optional, specifies which database interface to use, default is "default". Database interfaces are defined in kbengine_defaults.xml->dbmgr->databaseInterfaces.
Returns:
Returns the entityCall of the entity via callback.
def createEntityLocally( entityType, params ):
Description:
Creates a new Entity entity.
The function parameters require the entity type and a Python dictionary to initialize the entity's values.
You do not need to provide all properties in the dictionary; missing properties use the default values from the entity definition file ".def".
KBEngine.createEntityAnywhere should be used as the first choice, as the server can flexibly choose a suitable Baseapp to create the entity.
Example:
params = {
"name" : "kbe", # base, BASE_AND_CLIENT
"HP" : 100, # cell, ALL_CLIENT, in cellData
"tmp" : "tmp" # baseEntity.tmp
}
baseEntity = createEntityLocally("Avatar", params)
Parameters:
entityType
: string, the type of Entity to create. Valid types are listed in /scripts/entities.xml.
params
: optional, a Python dictionary. If a key matches an Entity property, its value initializes that property. If a key matches a Cell property, it is added to the entity's cellData property, which is a Python dictionary used to initialize cell entity properties.
Returns:
The newly created Entity (see Entity)
def debugTracing( ):
Description:
Outputs the current KBEngine tracked Python extension object counter.
Extended objects include: fixed dictionaries, fixed arrays, Entities, EntityCalls...
If the server shuts down normally and the counter is not zero, it indicates that a leak exists, and an error message will be output in the log.
ERROR cellapp [0x0000cd64] [2014-11-12 00:38:07,300] - PyGC::debugTracing(): FixedArray : leaked(128)
ERROR cellapp [0x0000cd64] [2014-11-12 00:38:07,300] - PyGC::debugTracing(): EntityCall : leaked(8)
Parameters:
path
: The path of the variable to be deleted.
def delWatcher( path ):
Description:
Interacts with the debug watcher system, allowing users to delete a watched variable in the script.
Parameters:
path
: The path of the variable to be deleted.
def deleteEntityByDBID( entityType, dbID, callback, dbInterfaceName ):
Description:
Deletes the specified entity from the database (including sub-table data generated by attributes). If the entity is not checked out from the database, the deletion succeeds. If the entity is checked out from the database, the deletion fails and the Entity entity's entityCall is returned in the callback.
Parameters:
entityType
: string, the type of Entity to delete. Valid types are listed in /scripts/entities.xml.
dbID
: the database ID of the entity to delete. Stored in databaseID.
callback
: optional callback, with one parameter. If the entity is not checked out from the database, the data is successfully deleted and the parameter is True. If the entity is checked out from the database, the parameter is the Entity entity's entityCall.
dbInterfaceName
: string, optional, specifies which database interface to use, default is "default". Database interfaces are defined in kbengine_defaults.xml->dbmgr->databaseInterfaces.
def deregisterReadFileDescriptor( fileDescriptor ):
Description:
Unregisters the callback registered by KBEngine.registerReadFileDescriptor.
Example:http://www.kbengine.org/assets/other/py/Poller.py
Parameters:
fileDescriptor
: socket descriptor/file descriptor.
def deregisterWriteFileDescriptor( fileDescriptor ):
Description:
Unregisters the callback registered by KBEngine.registerWriteFileDescriptor.
Example:http://www.kbengine.org/assets/other/py/Poller.py
Parameters:
fileDescriptor
: socket descriptor/file descriptor.
def executeRawDatabaseCommand( command, callback, threadID , dbInterfaceName ):
Description:
This script function executes a raw database command on the database, which will be directly parsed by the relevant database.
Note that using this function to modify entity data may not take effect, because if the entity is checked out, the modified entity data will still be overwritten by the entity archive.
It is strongly recommended not to use this function to read or modify entity data.
Parameters:
command
: This database command will vary depending on the database configuration scheme. For MySQL, it is an SQL query statement.
callback
: optional, a callback object with 4 parameters: result set, affected rows, auto-increment value, and error message.
Example Declaration
def sqlcallback(result, rows, insertid, error):
print(result, rows, insertid, error)
The result
parameter corresponds to the "result set", which is a list of rows. Each row is a list of string values for the fields.
If the command does not return a result set (e.g., DELETE command), or if there is an error in the command execution, this result set will be None.
The rows
parameter is the "number of affected rows", an integer indicating how many rows were affected by the command. This parameter is only relevant for commands that do not return a result set (like DELETE).
If a result set is returned or there is an error in the command execution, this parameter will be None.
insertid
corresponds to the "auto-increment value", similar to the entity's databaseID, when data is successfully inserted into a table with an auto-increment field.
More information can be found in the mysql's mysql_insert_id() method. Also, this parameter is only meaningful when the database type is mysql.
error
corresponds to the "error message", when there is an error in the command execution, this parameter is a string describing the error. When the command executes without errors, this parameter is None.
threadID
: int32, optional, specifies a thread to process this command. This parameter allows users to control the execution order of certain commands (dbmgr processes commands in multiple threads), default is not specified. If threadID is the entity's ID, the command will be added to that entity's archive queue and written in order by the thread.
dbInterfaceName
: string, optional, specifies which database interface to use, default is "default". Database interfaces are defined in kbengine_defaults.xml->dbmgr->databaseInterfaces.
def genUUID64( ):
Description:
This function generates a 64-bit unique ID.
Note: This function depends on the Baseapps service process startup parameter gus, please set the startup parameters correctly to maintain uniqueness.
Also, if gus exceeds 65535, this function can only maintain uniqueness on the current process.
Usage:
Generate a unique item ID across multiple service processes that will not conflict during server merging.
Generate a room ID across multiple service processes that does not require uniqueness verification.
Returns:
A 64-bit integer.
def getResFullPath( res ):
Description:
Gets the absolute path of a resource.
Note: The resource must be under KBE_RES_PATH to be accessed.
Parameters:
res
: string, the relative path of the resource.
Returns:
string, the absolute path of the resource if it exists, otherwise returns empty.
def getWatcher( path ):
Description:
Gets the value of a watch variable from the KBEngine debug system.
Example:
In the Python command line of baseapp1:
>>>KBEngine.getWatcher("/root/stats/runningTime")
12673648533
>>>KBEngine.getWatcher("/root/scripts/players")
32133
Parameters:
path
: string, the absolute path of the variable including the variable name (can be viewed in the watcher page of GUIConsole).
Returns:
The value of the variable.
def getWatcherDir( path ):
Description:
Gets the list of elements (directories, variable names) under a watch directory from the KBEngine debug system.
Example:
In the Python command line of baseapp1:
>>> KBEngine.getWatcher("/root")
('stats', 'objectPools', 'network', 'syspaths', 'ThreadPool',
'cprofiles', 'scripts', 'numProxices', 'componentID',
'componentType', 'uid', 'numClients', 'globalOrder',
'username', 'load', 'gametime', 'entitiesSize', 'groupOrder')
Parameters:
path
: string, the absolute path of the variable (can be viewed in the watcher page of GUIConsole).
Returns:
A list of elements (directories, variable names) under the watch directory.
def getAppFlags( ):
Description:
Gets the flags of the current engine APP, See: KBEngine.setAppFlags.
Returns:
KBEngine.APP_FLAGS_*。
def hasRes( res ):
Description:
This interface can be used to determine whether a resource with a relative path exists.
Note: The resource must be under KBE_RES_PATH to be accessed.
Example:
KBEngine.hasRes("scripts/entities.xml")
True
Parameters:
res
: string, the relative path of the resource.
Returns:
BOOL, returns True if exists, otherwise returns False.
def isShuttingDown( ):
Description:
Returns whether the server is shutting down.
This function returns True after the onBaseAppShutDown(state=0) callback function is called.
Returns:
True if the system is shutting down, otherwise False.
def listPathRes( path, extension ):
Description:
Gets the list of resources in a resource directory.
Note: The resource must be under KBE_RES_PATH to be accessed.
Example:
>>> KBEngine.listPathRes("scripts/cell/interfaces")
('/home/kbe/kbengine/demo/res/scripts/cell/interfaces/AI.py',
'/home/kbe/kbengine/demo/res/scripts/cell/interfaces/新建文本文档.txt')
>>> KBEngine.listPathRes("scripts/cell/interfaces", "txt")
('/home/kbe/kbengine/demo/res/scripts/cell/interfaces/新建文本文档.txt')
>>> KBEngine.listPathRes("scripts/cell/interfaces", "txt|py")
('/home/kbe/kbengine/demo/res/scripts/cell/interfaces/AI.py',
'/home/kbe/kbengine/demo/res/scripts/cell/interfaces/新建文本文档.txt')
>>> KBEngine.listPathRes("scripts/cell/interfaces", ("txt","py"))
('/home/kbe/kbengine/demo/res/scripts/cell/interfaces/AI.py',
'/home/kbe/kbengine/demo/res/scripts/cell/interfaces/新建文本文档.txt')
Parameters:
res
: string, the relative path of the resource.
extension
: string, optional, the file extension.
Returns:
Tuple, list of resources.
def lookUpEntityByDBID( entityType, dbID, callback, dbInterfaceName ):
Description:
Checks if an entity is checked out from the database. If the entity is checked out from the database, the KBEngine service system will return the Entity entity's entityCall in the callback.
Parameters:
entityType
: string, the type of Entity to query. Valid types are listed in /scripts/entities.xml.
dbID
: the database ID of the entity to query. Stored in databaseID.
callback
: optional callback, with one parameter. If the entity is not checked out from the database, the parameter is True. If the entity is checked out from the database, the parameter is the Entity entity's entityCall, otherwise False.
dbInterfaceName
: string, optional, specifies which database interface to use, default is "default". Database interfaces are defined in kbengine_defaults.xml->dbmgr->databaseInterfaces.
def matchPath( res ):
Description:
Gets the absolute path of a resource using its relative path.
Note: The resource must be under KBE_RES_PATH to be accessed.
Example:
>>>KBEngine.matchPath("scripts/entities.xml")
'/home/kbe/kbengine/demo/res/scripts/entities.xml'
Parameters:
res
: string, the relative path of the resource (including the resource name).
Returns:
string, the absolute path of the resource.
def open( res, mode, encoding ):
Description:
This interface allows you to open the related resource using a relative path.
Note: The resource must be under KBE_RES_PATH to be accessed.
Parameters:
res
: string, the relative path of the resource.
mode
: string, optional, default is 'r'
File operation modes:
r
open in read-only mode
w
open in write mode
a
open in append mode (create new file if necessary)
r+
open in read/write mode
w+
open in read/write mode (see w)
a+
open in read/write mode (see a)
rb
open in binary read mode
wb
open in binary write mode (see w)
ab
open in binary append mode (see a)
rb+
open in binary read/write mode (see r+)
wb+
open in binary read/write mode (see w+)
ab+
open in binary read/write mode (see a+)
encoding
: string, optional, the name of the encoding to decode or encode the file, default is platform dependent.
def publish( ):
Description:
This interface returns the current server release mode.
Returns:
int8, 0: debug, 1: release, others customizable.
def quantumPassedPercent( ):
Description:
Returns the percentage of the current tick occupying a clock cycle.
Returns:
Returns the percentage of the current tick occupying a clock cycle.
def registerReadFileDescriptor( fileDescriptor, callback ):
Description:
Registers a callback function that is called when the file descriptor is readable.
Example:http://www.kbengine.org/assets/other/py/Poller.py
Parameters:
fileDescriptor
: socket descriptor/file descriptor.
callback
: A callback function, with the socket descriptor/file descriptor as its only parameter.
def registerWriteFileDescriptor( fileDescriptor, callback ):
Description:
Registers a callback function that is called when the socket descriptor/file descriptor is writable.
Example:http://www.kbengine.org/assets/other/py/Poller.py
Parameters:
fileDescriptor
: socket descriptor/file descriptor.
callback
: A callback function, with the socket descriptor/file descriptor as its only parameter.
def reloadScript( fullReload ):
Description:
Reloads the Python modules related to entities and custom data types. The current entity class is set to the newly loaded class. This method should only be used in development mode, and the following points should be noted:
1)Reloading scripts can only be executed on the Baseapp, Users should ensure that all server components are loaded.
2)Custom types should ensure that objects already instantiated in memory are also updated after the script is reloaded. Here is an example:
for e in KBEngine.entities.values():
if type( e ) is Avatar.Avatar:
e.customData.__class__ = CustomClass
When this method is complete, KBEngine.onInit( True ) is called.
Parameters:
fullReload
: optional boolean, specifies whether to reload the entity definition as well. If False, the entity definition will not be reloaded. Default is True.
Returns:
True if reload is successful, otherwise False.
def scriptLogType( logType ):
Description:
Sets the type of information output by Python.print (See: KBEngine.LOG_TYPE_*)。
def setAppFlags( flags ):
Description:
Sets the flags of the current engine APP.
KBEngine.APP_FLAGS_NONE // Default (no flags set)
KBEngine.APP_FLAGS_NOT_PARTCIPATING_LOAD_BALANCING // Not participating in load balancing
// For example:
KBEngine.setAppFlags(KBEngine.APP_FLAGS_NOT_PARTCIPATING_LOAD_BALANCING | KBEngine.APP_FLAGS_*)
def time( ):
Description:
This method returns the current game time (in ticks).
Returns:
uint32, the current game time, in ticks. The tick rate is influenced by the frequency set in the configuration files kbengine.xml or kbengine_defaults.xml->gameUpdateHertz.
def urlopen( url, callback, postData, headers ):
Description:
This script function provides asynchronous HTTP/HTTPS requests.
Parameters:
url
: A valid HTTP/HTTPS URL, string type.
callback
: optional, a callback object with 5 parameters: HTTP response code (e.g., 200), content, HTTP headers, success flag, and requested URL.
Example Declaration:
def onHttpCallback(httpcode, data, headers, success, url):
print(httpcode, data, headers, success, url)
As shown in the above example:
httpcode
: corresponds to the "HTTP response code", an integer value.
data
: corresponds to the "content", a string.
headers
: corresponds to the "HTTP headers returned by the server", like {"Content-Type": "application/x-www-form-urlencoded"}, a dictionary.
success
: indicates "whether the execution was successful", if there was an error during the request, it will be False, and the httpcode can be used to further determine the error information.
url
: is the URL used for the request.
postData
: optional, default is GET request. If a POST request is needed, provide the POST content, and the engine will automatically use POST to request the server, in bytes.
headers
: optional, HTTP headers used in the request, like {"Content-Type": "application/x-www-form-urlencoded"}, a dictionary.
Callback Function Documentation
def onBaseAppReady( isBootstrap ):
Description:
This function is called when the current Baseapp process is ready.
Note: This callback interface must be implemented in the entry module (kbengine_defaults.xml->entryScriptFile) .
Parameters:
isBootstrap
: bool, whether this is the first started Baseapp.
def onBaseAppShutDown( state ):
Description:
This function is called during the shutdown process of the Baseapp.
Note: This callback interface must be implemented in the entry module (kbengine_defaults.xml->entryScriptFile) .
Parameters:
state
: If state is 0, it means before disconnecting all clients. If state is 1, it means before writing all entities to the database. If state is 2, it means after all entities have been written to the database.
def onCellAppDeath( addr ):
Description:
This function is called when a cellapp dies.
Note: This callback interface must be implemented in the entry module (kbengine_defaults.xml->entryScriptFile) .
Parameters:
addr
: the address of the dead cellapp. tuple:(ip, port) network byte order
def onFini( ):
Description:
This function is called after the engine is officially closed.
Note: This callback interface must be implemented in the entry module (kbengine_defaults.xml->entryScriptFile) .
def onBaseAppData( key, value ):
Description:
This function is called when KBEngine.baseAppData is changed.
Note: This callback interface must be implemented in the entry module (kbengine_defaults.xml->entryScriptFile) .
Parameters:
key
: the key of the changed data.
value
: the value of the changed data.
def onBaseAppDataDel( key ):
Description:
This function is called when KBEngine.baseAppData is deleted.
Note: This callback interface must be implemented in the entry module (kbengine_defaults.xml->entryScriptFile) .
Parameters:
key
: the key of the deleted data.
def onGlobalData( key, value ):
Description:
This function is called when KBEngine.globalData is changed.
Note: This callback interface must be implemented in the entry module (kbengine_defaults.xml->entryScriptFile) .
Parameters:
key
: the key of the changed data.
value
: the value of the changed data.
def onGlobalDataDel( key ):
Description:
This function is called when KBEngine.globalData is deleted.
Note: This callback interface must be implemented in the entry module (kbengine_defaults.xml->entryScriptFile) .
Parameters:
key
: the key of the deleted data.
def onInit( isReload ):
Description:
This interface is called after the engine starts and initializes all scripts.
Note: This callback interface must be implemented in the entry module (kbengine_defaults.xml->entryScriptFile) .
Parameters:
isReload
: bool, whether this is triggered by reloading the script.
def onLoseChargeCB( orderID, dbID, success, datas ):
Description:
This callback is received when an order is lost or an unknown order not recorded in interfaces is received after calling KBEngine.chargeResponse in interfaces.
Note: This callback interface must be implemented in the entry module (kbengine_defaults.xml->entryScriptFile) .
Parameters:
ordersID
: string, order ID.
dbID
: uint64, the database ID of the entity, see: Entity.databaseID.
success
: bool, whether successful.
datas
: bytes, attached information.
def onReadyForLogin( isBootstrap ):
Description:
This interface is called repeatedly to ask whether the script layer is ready after the engine starts and initializes. If the script layer is ready, the loginapp allows clients to log in.
Note: This callback interface must be implemented in the entry module (kbengine_defaults.xml->entryScriptFile) .
Parameters:
isBootstrap
: bool, whether this is the first started Baseapp.
Returns:
A value greater than or equal to 1.0 indicates that the script layer is ready, otherwise, a progress value between 0.0~1.0 is returned.
def onReadyForShutDown( ):
Description:
If this function is implemented in the script, it is called when the process is ready to exit.
This callback can control the timing of the process exit.
Note: This callback interface must be implemented in the entry module (kbengine_defaults.xml->entryScriptFile) .
Returns:
bool, if returns True, the process exit process is allowed, otherwise, the process will be asked again after a while.
def onAutoLoadEntityCreate( entityType, dbID ):
Description:
Callback when an auto-loaded entity is created. If this callback is implemented in the script layer, the entity is created by the script layer, otherwise, the engine uses createEntityAnywhereFromDBID by default to create the entity.
This callback is called due to Entity.writeToDB setting the entity to auto-load.
Note: This callback is executed prior to onBaseAppReady, you can check if the entity is loaded in onBaseAppReady.
Parameters:
entityType
: string, the type of Entity to create. Valid types are listed in /scripts/entities.xml.
dbID
: the database ID of the entity to create. Stored in databaseID.
Property Documentation
LOG_ON_ACCEPT
Description:
This constant is returned by Proxy.onLogOnAttempt, meaning a new client is allowed to bind to a Proxy entity.
If the Proxy entity already has a client bound, the previous client will be kicked out.
LOG_ON_REJECT
Description:
This constant is returned by Proxy.onLogOnAttempt, meaning the current client is rejected from binding to the Proxy entity.
LOG_ON_WAIT_FOR_DESTROY
Description:
This constant is returned by Proxy.onLogOnAttempt, meaning the requesting client will wait until the Proxy entity is completely destroyed before the binding process continues.
Before returning this, Proxy.destroy or Proxy.destroyCellEntity should be called.
LOG_TYPE_DBG
Description:
Log output type for debug messages.
Set by scriptLogType.
LOG_TYPE_ERR
Description:
Log output type for error messages.
Set by scriptLogType.
LOG_TYPE_INFO
Description:
Log output type for informational messages.
Set by scriptLogType.
LOG_TYPE_NORMAL
Description:
Log output type for normal messages.
Set by scriptLogType.
LOG_TYPE_WAR
Description:
Log output type for warning messages.
Set by scriptLogType.
NEXT_ONLY
Description:
This constant is used for Entity.shouldAutoBackup and Entity.shouldAutoArchive properties. It means the entity will be automatically backed up the next time it is considered appropriate, and then this property will automatically be set to False (0).
component
Description:
The component currently running in the Python environment. (So far) possible values are 'cellapp', 'baseapp', 'client', 'dbmgr', 'bots', and 'editor'.
entities
Description:
entities is a dictionary object containing all entities on the current process.
To debug leaked entities (entities that have called destroy but have not released memory, usually due to references preventing release):
>>> KBEngine.entities.garbages.items()
[(1025, Avatar object at 0x7f92431ceae8.)]
>>> e = _[0][1]
>>> import gc
>>> gc.get_referents(e)
[{'spacesIsOk': True, 'bootstrapIdx': 1}, ]
To debug leaked Python objects wrapped by KBEngine: KBEngine.debugTracing
Type:
baseAppData
Description:
This property contains a dictionary-like object that is automatically synchronized among all BaseApps. When a value in the dictionary is modified, the change is broadcast to all BaseApps.
Example:
KBEngine.baseAppData[ "hello" ] = "there"
Other BaseApps can access:
print(KBEngine.baseAppData[ "hello" ])
Keys and values can be any type, but must be serializable and deserializable on all target components.
When a value is changed or deleted, a callback function is called on all components. See: KBEngine.onBaseAppData and KBEngine.onDelBaseAppData.
Note: Only top-level values are broadcast. If you have a value (such as a list) and change an internal value (such as just changing a number), this change will not be broadcast.
Do not do the following:
KBEngine.baseAppData[ "list" ] = [1, 2, 3]
KBEngine.baseAppData[ "list" ][1] = 7
Locally, you get [1, 7, 3], but remotely, you get [1, 2, 3].
globalData
Description:
This property contains a dictionary-like object that is automatically synchronized among all BaseApps and CellApps. When a value in the dictionary is modified, the change is broadcast to all BaseApps and CellApps.
Example:
KBEngine.globalData[ "hello" ] = "there"
Other Baseapp or Cellapp can access:
print(KBEngine.globalData[ "hello" ])
Keys and values can be any type, but must be serializable and deserializable on all target components.
When a value is changed or deleted, a callback function is called on all components. See: KBEngine.onGlobalData and KBEngine.onGlobalDataDel.
Note: Only top-level values are broadcast. If you have a value (such as a list) and change an internal value (such as just changing a number), this change will not be broadcast.
Do not do the following:
KBEngine.globalData[ "list" ] = [1, 2, 3]
KBEngine.globalData[ "list" ][1] = 7
Locally, you get [1, 7, 3], but remotely, you get [1, 2, 3].