ParaScripting

namespace ParaScripting

for luabind, The main drawback of this approach is that the compilation time will increase for the file that does the registration, it is therefore recommended that you register everything in the same cpp-file.

ParaScripting contains all classes and functions used for communication between the game engine and scripts.

Typedefs

typedef pair<const char *, ParaObjectNode> ParaObject_Pair

Functions

int NPL_dummy(lua_State *L)

split registration to save compiling time. void register_part1(class_<X>& x){ x.def(...); } void register_part2(class_<X>& x){ x.def(...); } void register_(lua_State* L){ class_<X> x(“x”); register_part1(x); register_part2(x); module(L) [ x ]; }this function does nothing but count as one instruction in preemptive function.

static void lua_register_funcs_totable(lua_State *L, lua_func_entry entries[])

for registering functions

static void lua_register_values_totable(lua_State *L, lua_vale_entry entries[])

for registering values

static int NPL_Print(lua_State *L)

e.g. print(“Hello ParaEngine %d”, 10); Receives any number of arguments, and prints their values in stdout, using the tostring function to convert them to strings. This function is not intended for formatted output, but only as a quick way to show a value, typically for debugging. For formatted output, use string.format

static int NPL_Format(lua_State *L)

this function is the same as string.format, except that it only support d, and s, and f (always printed as %.2f) We do not use sprintf internally, so it runs much faster than string.format which uses sprintf. e.g. a = format(“%s hello %d, %f”, “Hello ParaEngine”,10, 10.1234);

static int luaopen_luaxml(lua_State *L)

the luaxml api will be returned in a table, usually we can assign this table like this ParaXML = luaopen_luaxml();

template <typename T>
T *get_pointer(StackObjectPtr<T> const &pointer)
template <typename T>
T *get_pointer(T const &pointer)

this defines a rule, so that every object defined in ParaScripting namespace will be treated as StackObject by luabind. i.e. all objects such as ParaObject, ParaUIObject, etc are passed by value on the stack, instead of using std::auto_ptr( new ParaObject(p)). if one wants to pass by reference, overwrite this method.

See
: see make_pointee_instance in luabind/policy.hpp and object_rep.hpp.

string FileTimeToDateString(const FILETIME *pTime)
template <class T>
void traverse(const Json::Value &var, const object &outTable, const T &sKey, bool bFirstTable = false)
OBJECT_FILTER_CALLBACK GetFilterFuncByName(const char *sFilterFunc)
DWORD GetPhysicsGroupMaskByName(const char *sFilterFunc)

get the physics group mask by filter name

Variables

lua_func_entry luaxml_api_entries[] = { { "LuaXML_ParseFile", ParaXML::LuaXML_ParseFile }, { "LuaXML_ParseString", ParaXML::LuaXML_ParseString }, { 0, 0 } }
CParaFile g_currentIOfile

the current IO file.

bool s_bIsWhiteSpaceCollapsed = true
class CAssetScriptCallbackData

terrain mask file callback data

class CNPL
#include <ParaScriptingNPL.h>

Neural Parallel Language functions are in this namespace.

Public Static Functions

int activate(const object &sNPLFilename, const object &sCode)

activate the specified file. It can either be local or remote file.

the following is a list of all valid file name combinations: “user001@paraengine.com:script/hello.lua” a file of user001 in its default gaming thread “(world1)server001@paraengine.com:script/hello.lua” a file of server001 in its thread world1 “(worker1)script/hello.lua” a local file in the thread worker1 “(gl)script/hello.lua” a glia (local) file in the current runtime state’s thread “script/hello.lua” a file in the current thread. For a single threaded application, this is usually enough. “(worker1)NPLRouter.dll” activate a C++ or C# dll. Please note that, in windows, it looks for NPLRonter.dll; in linux, it looks for ./libNPLRouter.so “plugin/libNPLRouter.dll” almost same as above, it is recommented to remove the heading ‘lib’ when loading. In windows, it looks for plugin/NPLRonter.dll; in linux, it looks for ./plugin/libNPLRouter.so

Parameters
  • pState: the source runtime state that initiated this activation. If pState is NULL, the main runtime state is used.
  • sNPLFileName: a globally unique name of a NPL file name instance. The string format of an NPL file name is like below. [(sRuntimeStateName|gl)][sNID:]sRelativePath[]

Note
: pure data table is defined as table consisting of only string, number and other table of the above type. NPL.activate function also accepts ParaFileObject typed message data type. ParaFileObject will be converted to base64 string upon transmission. There are size limit though of 10MB. one can also programmatically check whether a script object is pure date by calling NPL.SerializeToSCode() function. Please note that data types that is not pure data in sCode will be ignored instead of reporting an error.
Return
: NPLReturnCode. 0 means succeed.
Parameters
  • code: it is a chunk of pure data table init code that would be transmitted to the destination file.
  • nLength: the code length. if this is 0, length is determined from code by finding ‘\0’, but, it must not exceed 4096 bytes. If length is explicitly specified, there is no such a limit.
  • channel:On: which channel to send the package. It can be a number in [0,15]. In case it is nil, the default channel (0) is used.
  • priority: From high to low.If this is nil, medium priority(0) is used. following enumerations are used to describe when packets are delivered. enum PacketPriority { SYSTEM_PRIORITY, /// internally Used to send above-high priority messages. HIGH_PRIORITY, /// High priority messages are send before medium priority messages. MEDIUM_PRIORITY, /// Medium priority messages are send before low priority messages. LOW_PRIORITY, /// Low priority messages are only sent when no other messages are waiting. };
  • reliability:From: unreliable to reliable sequenced. 0 stands for unreliable. If this is nil, RELIABLE_ORDERED(3) is used. following enumerations are used to describe how packets are delivered. enum PacketReliability { UNRELIABLE, /// Same as regular UDP, except that it will also discard duplicate datagrams. It adds (6 to 17) + 21 bits of overhead, 16 of which is used to detect duplicate packets and 6 to 17 of which is used for message length. UNRELIABLE_SEQUENCED, /// Regular UDP with a sequence counter. Out of order messages will be discarded. This adds an additional 13 bits on top what is used for UNRELIABLE. RELIABLE, /// The message is sent reliably, but not necessarily in any order. Same overhead as UNRELIABLE. RELIABLE_ORDERED, /// This message is reliable and will arrive in the order you sent it. Messages will be delayed while waiting for out of order messages. Same overhead as UNRELIABLE_SEQUENCED. RELIABLE_SEQUENCED /// This message is reliable and will arrive in the sequence you sent it. Out or order messages will be dropped. Same overhead as UNRELIABLE_SEQUENCED. };

int activate2_(const char *sNPLFilename, const char *sCode)

this function is only called by .Net API.

int activate_(const char *sNPLFilename, const char *sCode, int channel, int priority, int reliability)

this function is only called by .Net API.

void call(const object &sNPLFilename, const object &sCode)

This function is used to activate a local file synchronously in the current runtime state. Use activate() if you need an asynchronous activation. for more information, please see activate();

void call_(const char *sNPLFilename, const char *sCode)

this function is only called by .Net API.

const char *GetFileName()

return the NPL file name that is being loaded. Only call this function when the file is being initialized. i.e. at the root level. Note: calling this function inside other functions will lead to unexpected result.

void this_(const object &funcActivate)

NOTE: the function name is “this” in NPL, not “this_”. associate a user defined function as the activation function of this file. add the current file name to the __act table. create the activate table, if it does not exist.

Parameters
  • funcActivate: the function pointer to the activation function. It can either be local or global.
  • params: nil or a table {[PreemptiveCount=number,] [MsgQueueSize=number,] [filename|name=string,]}
    • PreemptiveCount: if PreemptiveCount is omitted (default), the activate function will run non-preemptive (it is the programmer’s job to let the function finish in short time). If PreemptiveCount > 0, the activate function will be preemptive (yield) after this number of virtual instructions. which allows us to run tens of thousands of jobs concurrently. Each job has its own stack and but the programmer should pay attention when making changes to shared data.
    • MsgQueueSize: Max message queue size of this file, if not specified it is same as the NPL thread’s message queue size.
    • filename|name: virtual filename, if not specified, the current file being loaded is used.
    • clear: clear all memory used by the file, including its message queue. Normally one never needs to clear. A neuron file without messages takes less than 100 bytes of memory (mostly depending on the length’s of its filename)

ParaAttributeObject GetAttributeObject()

get the attribute object. This function return a clone of this object.

void load(const object &filePath, bool bReload)

load a new file (in the current runtime state) without activating it. If the file is already loaded, it will not be loaded again unless bReload is true. IMPORTANT: this function is synchronous; unlike the asynchronous activation function. LoadFile is more like “include in C++”.When the function returns, contents in the file is loaded to memory.

Note
: in NPL/lua, function is first class object, so loading a file means executing the code chunk in protected mode with pcall, in most cases, this means injecting new code to the global table. Since there may be recursions (such as A load B, while B also load A), your loading code should not reply on the loading order to work. You need to follow basic code injection principles. For example, commonlib.gettable(“”) is the the commended way to inject new code to the current thread’s global table. Be careful not to pollute the global table too much, use nested table/namespace. Different NPL applications may have their own sandbox environments, which have their own dedicated global tables, for example all *.page files use a separate global table per URL request in NPL Web Server App.
Note
: when loading an NPL file, we will first find if there is an up to date compiled version in the bin directory. if there is, we will load the compiled version, otherwise we will use the text version. use bin version, if source version does not exist; use bin version, if source and bin versions are both on disk (instead of zip) and that bin version is newer than the source version. e.g. we can compile source to bin directory with file extension ”.o”, e.g. “script/abc.lua” can be compiled to “bin/script/abc.o”, The latter will be used if available and up-to-date.
Remark
: one should be very careful when calling with bReload set to true, since this may lead to recursive reloading of the same file. If this occurs, it will generate C Stack overflow error message.
Parameters
  • filePath: the local relative file path. If the file extension is ”.dll”, it will be treated as a plug-in. Examples: “NPLRouter.dll” load a C++ or C# dll. Please note that, in windows, it looks for NPLRonter.dll; in linux, it looks for ./libNPLRouter.so “plugin/libNPLRouter.dll” almost same as above, it is reformatted to remove the heading ‘lib’ when loading. In windows, it looks for plugin/NPLRonter.dll; in linux, it looks for ./plugin/libNPLRouter.so
  • bReload: if true, the file will be reloaded even if it is already loaded. otherwise, the file will only be loaded if it is not loaded yet.

void load_(const char *filePath, bool bReload)

for NPL managed only.

void load1(const object &filePath)

same as NPL.load(filepath, false);

void DoString(const object &sCode)

execute a given string immediately in protected mode.

Remark
:caution: there may be a security issue.
Parameters
  • sCode: : the code to run. the code can not be longer than some internally defined value.

void DoString2(const object &sCode, const char *sFilename)

execute a given string immediately in protected mode.

Remark
:caution: there may be a security issue.
Parameters
  • sCode: : the code to run. the code can not be longer than some internally defined value.
  • sFilename: can be nil, a filename to be associated with the chunk of code for debuggin purposes.

void DoString_(const char *sCode)

only for NPL managed only

void test(const object &input)

this function should be removed in release build. it just run NPL C++ test cases

Parameters
  • input: which test case to run.

bool SetTimer(const object &nIDEvent, float fElapse, const object &sNeuronFile)

creates a timer with the specified time-out value

Return
: true if succeeds.An application can pass the value of the nIDEvent parameter to the NPL.KillTimer function to destroy the timer.
Parameters
  • nIDEvent: Specifies a positive timer identifier. For nIDEvent<=0, they are reserved for internal uses. If the NPL runtime already has a timer with the value nIDEvent, then the existing timer is replaced by the new timer. When SetTimer replaces a timer, the timer is reset.
  • fElapse: Specifies the time-out value, in seconds. Please note that a timer will not be repeatedly activated if its timeout is shorter than the frame rate of the NPL simulation pipeline .
  • sNeuronFile: The NPL file to be activated when the time-out value elapses. it can also carry sCode. e.g. “script/hello.lua;funcABC();”, ”;funcABC();”, “(gl)script/hello.lua”;

bool KillTimer(const object &nIDEvent)

Destroys the specified timer

Return
: If the function succeeds, the return value is true
Parameters
  • nIDEvent: Specifies the timer to be destroyed.For nIDEvent<=0, they are reserved for internal uses can not be killed by this function. This value must be the same as the nIDEvent value passed to the SetTimer function that created the timer.

bool ChangeTimer(const object &nIDEvent, int dueTime, int period)

Changes the start time and the interval between method invocations for a timer, using 32-bit signed integers to measure time intervals.

Return
: If the function succeeds, the return value is true
Parameters
  • nIDEvent: Specifies the timer to be destroyed.For nIDEvent<=0, they are reserved for internal uses can not be killed by this function. This value must be the same as the nIDEvent value passed to the SetTimer function that created the timer.
  • dueTime: The amount of time to delay before the invoking the callback method specified when the Timer was constructed, in milliseconds. Specify zero (0) to restart the timer immediately. however, the current implementation does not accept dueTime that is larger than MAX_TIMER_DUE_TIME 10000000, which is 10000 seconds.
  • period:The: time interval between invocations of the callback method specified when the Timer was constructed, in milliseconds.

const string &SerializeToSCode(const char *sStorageVar, const object &input)

serialize a luabind object into sCode. The object could be a value, string or a table of the above type. input also accepts ParaFileObject typed data. ParaFileObject will be converted to base64 string internally.There are size limit though of 10MB.

Return
sCode the output scode
Parameters
  • sStorageVar: if this is “”, the scode contains only the object. otherwise an assignment is made, by prefixing the scode with “[sStorageVar = ”.
  • input: input luabind object

bool IsSCodePureData(const char *sCode)

verify the script code. it returns true if the script code contains pure msg data or table. this function is used to verify scode received from the network. So that the execution of a pure data in the local runtime is harmless.

bool IsPureData(const char *sCode)

it will return true if input string is “false”, “true”, NUMBER, STRING, and {table}

bool IsPureTable(const char *sCode)

it will return true if input string is a {table} containing only “false”, “true”, NUMBER, STRING, and other such {table}

luabind::object LoadTableFromString(const object &input)

load a table from string.

luabind::object LoadObjectFromString(const object &input)

load a table,string, anything from string.

void StartNetServer(const object &server, const object &port)

start the NPL net server’s io_service loop. This function returns immediately. it will spawn the accept and dispatcher thread. call this function only once per process.

Parameters
  • server: if nil, it defaults to “127.0.0.1”
  • port: if nil, it defaults to “60001”; if “0”, we will not listen or accept incoming connections. This is usually the setting for pure client application.

void StopNetServer()

stop the net server

void AddPublicFile(const string &filename, int nID)

add a nID, filename pair to the public file list. we only allow remote NPL runtime to activate files in the public file list. Each public file has a user defined ID. The NPL network layer always try to use its ID for transmission to minimize bandwidth. There are some negotiations between sender and receiver to sync the string to ID map before they use it. [thread safe]

Parameters
  • nID: the integer to encode the string. it is usually small and positive number.
  • sString: the string for the id. if input is empty, it means removing the mapping of nID.

void RegisterEvent(int nType, const char *sID, const char *sScript)

register a network event handler

Parameters
  • nType: reserved, this is always 0.
  • sID: a string identifier of the network event handler.
  • sScript: the script to be executed when the event is triggered.This is usually a function call in NPL. sScript should be in the following format “{NPL filename};{sCode};”. this is the same format in the UI event handler. Please note, it is slightly faster when there is no sCode, and we can register the callback script to be in a different NPL state(thread), such as “(gateway)script/apps/GameServer/GSL_NPLEvent.lua”.

void UnregisterEvent(int nType, const char *sID)

unregister a network event handler

Parameters
  • nType: reserved, this is always 0.

luabind::object GetStats(const object &inout)

get statistics about this runtime environment. e.g. local stats = NPL.GetStats({connection_count = true, nids_str=true, nids = true});

Return
{connection_count = 10, nids_str=”101,102,”}
Parameters
  • input: this should be a table containing mapping from string to true. function will return a new table by replacing true with the actual data. such as {[“connection_count”] = true, [“nids_str”] = true }, supported fields are “connection_count” : total connection. “nids_str”: commar separated list of nids. “nids”: a table array of nids

void ClearPublicFiles()

clear all public files, so that the NPL server will be completely private. [thread safe]

bool AddNPLRuntimeAddress(const object &npl_address)

add a given NPL runtime address to the fully trusted server addresses list. whenever an address is added, one can activate any public files in that runtime. Please note that connection is only established on first activation. In most cases, one should add all trusted servers at start up time.

Return
: true if successfully added.
Parameters
  • npl_address: this should be a table of { host = “127.0.0.1”, port = “60001”, nid = “MyServer”, } [thread safe]

string GetIP(const char *nid)

get the ip address of given NPL connection. this function is usually called by the server for connected clients.

Return
: the ip address in dot format. empty string is returned if connection can not be found.
Parameters
  • nid: nid or tid.

void accept(const object &tid, const object &nid)

accept a given connection. The connection will be regarded as authenticated once accepted. [thread safe]

Parameters
  • tid: the temporary id or NID of the connection to be accepted. usually it is from msg.tid or msg.nid.
  • nid: if this is not nil, tid will be renamed to nid after accepted.

void accept_(const char *tid, const char *nid)

this function is used by C++ API interface.

void reject(const object &nid)

reject and close a given connection. The connection will be closed once rejected. [thread safe]

Parameters
  • nid: the temporary id or NID of the connection to be rejected. usually it is from msg.tid or msg.nid. it can also be {nid=number|string, reason=0|1|-1} reason:
    • 0 or positive value is forcibly reset/disconnect (it will abort pending read/write immediately).
    • 1 is another user with same nid is authenticated. The server should send a message to tell the client about this.
    • -1 or negative value means gracefully close the connection when all pending data has been sent.

void reject_(const char *nid, int nReason = 0)

this function is used by C++ API interface.

void SetUseCompression(bool bCompressIncoming, bool bCompressOutgoing)

whether to use compression on transport layer for incoming and outgoing connections

Parameters
  • bCompressIncoming: if true, compression is used for all incoming connections. default to false.
  • bCompressIncoming: if true, compression is used for all outgoing connections. default to false.

void SetCompressionKey(const object &input)

set the compression method of incoming the outgoing messages. If this is not called, the default internal key is used for message encoding. [Not Thread Safe]: one must call this function before sending or receiving any encoded messages. so it is usually called when the game engine starts.

Parameters
  • input: a table, such as { key = “”, size = 100, UsePlainTextEncoding = 1}, or {UsePlainTextEncoding = 1} input.key: the byte array of key. the generic key that is used for encoding/decoding input.size: size in bytes of the sKey. default is 64 bytes input.UsePlainTextEncoding: default to 0. if 0, the key is used as it is. if 1, the input key will be modified so that the encoded message looks like plain text(this can be useful to pass some firewalls). if -1, the input key will be modified so that the encoded message is binary.

const char *GetSourceName()

get the current activation’s source name. Each NPL activation has a source name which started the activation. This is usually “” for local activation and some kind of “name@server” for network activation.

void SetSourceName(const char *sName)

Set the current activation’s source name. Each NPL activation has a source name which started the activation. This function is called automatically when a new activation occurs.So only call this function if one wants to override the old one for special code logics.

Parameters
  • sName: This is usually “” for local activation and some kind of “name@server” for network activation.

void EnableNetwork(bool bEnable, const char *CenterName, const char *password)

Enable the network, by default the network layer is disabled. calling this function multiple time with different CenterName will restart the network layer with a different center name.

Return
true if succeeded.
Parameters
  • bEnable: true to enable, false to disable.If this is false, the CenterName and Password are ignored.
  • CenterName: the local nerve center name. it is also the user name which local receptor will use in the credentials to login in other NPL runtime.
  • Password:

void AddDNSRecord(const char *sDNSName, const char *sAddress)

add a DNS server record to the current NPL runtime. DNS server record is a mapping from name to (IP:port) if one maps several IP:port to the same name, the former ones will be overridden.

Parameters
  • sDNSName: the DNS server name. the DNS name “_world” is used for the current world DNS server. It is commonly used as a DNS reference to the current world that the user is exploring.
  • sAddress: “IP:port”. e.g. “192.168.1.10:4000”

void SetDefaultChannel(int channel_ID)

Set the default channel ID, default value is 0. Default channel is used when NPL.activate() calls does not contain the channel property.

Parameters
  • channel_ID: It can be a number in [0,15].default is 0

int GetDefaultChannel()

Get the default channel ID, default value is 0. Default channel is used when NPL.activate() calls does not contain the channel property.

Return
channel_ID It can be a number in [0,15].default is 0

void SetChannelProperty(int channel_ID, int priority, int reliability)

Messages can be sent via predefined channels. There are 16 channels from 0 to 15 to be used. 0 is the default channel. This method sets the channel property for a given channel. The default channel property is given in table. The following table shows the default NPL channel properties. It is advised for users to stick to this default mapping when developing their own applications. Table 1. Default NPL channel properties channel_ID Priority Reliability Usage 0 med RELIABLE_ORDERED System message 1 med UNRELIABLE_SEQUENCED Character positions 2 med RELIABLE_ORDERED Large Simulation Object transmission, such as terrain height field. 4 med RELIABLE_ORDERED Chat message 14 med RELIABLE files transmission and advertisement 15 med RELIABLE_SEQUENCED Voice transmission 11-15 med RELIABLE_ORDERED

Parameters
  • channel_ID:
  • priority:
  • reliability:

void ResetChannelProperties()

reset all 16 predefined channel properties. according to table1. Default NPL channel properties. see also NPL_SetChannelProperty The following table shows the default NPL channel properties. It is advised for users to stick to this default mapping when developing their own applications. Table 1. Default NPL channel properties channel_ID Priority Reliability Usage 0 med RELIABLE_ORDERED System message 1 med UNRELIABLE_SEQUENCED Character positions 2 med RELIABLE_ORDERED Large Simulation Object transmission, such as terrain height field. 4 med RELIABLE_ORDERED Chat message 14 med RELIABLE files transmission and advertisement 15 med RELIABLE_SEQUENCED Voice transmission 11-15 med RELIABLE_ORDERED

void GetChannelProperty(int channel_ID, int *priority, int *reliability)

see also NPL_SetChannelProperty

Parameters
  • channel_ID:
  • priority: [out]
  • reliability: [out]

void RegisterWSCallBack(const char *sWebServiceFile, const char *sCode)

this method will associate a web service (method) with either a sCode, which will be called when the web service returned. The returned message, if any, will be passed via a global parameter called msg. If msg == nil, it always means that there is an error during processing, such as HTTP 404 not found. the error code either string or number will be returned in a global variable called msgerror. For example: function callbackFunc1() if(msg~=nil) then log(msg.username); error code in msgerror else log(tostring(msgerror)); error code in msgerror end end NPL.RegisterWSCallBack(“http://paraengine.com/login.aspx”,callbackFunc1); NPL.activate(“http://paraengine.com/login.aspx”, {username=lxz});

Parameters
  • sWebServiceFile: URL of the web service
  • sCode: code to be executed when the web service is called. When a two-way web service call is invoked; it internally will create a thread for the returning message. Please refer to .Net 3.0 network communication architecture.

void UnregisterWSCallBack(const char *sWebServiceFile)

unregister web service call back for a given file.

Parameters
  • sWebServiceFile: if this is nil or “”, all call backs will be unregistered.

void AsyncDownload(const char *url, const char *destFolder, const char *callbackScript, const char *DownloaderName)

Asynchronously download a file or an HTTP web page from the url.

Parameters
  • destFolder:folder: path or file path. if the destFolder contains a file extension, we will save the downloaded file as the destFolder otherwise, we will save the file as the combination of the destFolder and the filename returned from the remote target.
  • callbackScript: script code to be called, a global variable called msg is assigned, as below if url is a file: msg = {DownloadState=”“|”complete”|”terminated”, totalFileSize=number, currentFileSize=number, PercentDone=number} if url is a web page: msg = {DownloadState=”“|”complete”|”terminated”, ContentType=string that contains “text/html”, Headers=string of {name:value }, StatusCode=int, StatusDescription=string, ResponseUri=string of actual url that is responding. totalFileSize=number, currentFileSize=number, PercentDone=number}

void CancelDownload(const char *DownloaderName)

cancel all asynchronous downloads that matches a certain downloader name pattern

Parameters
  • DownloaderName:regular: expression. such as “proc1”, “proc1.*”, ”.*”

int Download(const char *url, const char *destFolder, const char *callbackScript, const char *DownloaderName)

Synchronous call of the function AsyncDownload(). This function will not return until download is complete or an error occurs. this function is rarely used. AsyncDownload() is used.

Return
:1 if succeed, 0 if fail

ParaScripting::ParaNPLRuntimeState CreateRuntimeState(const string &name, int type_)

create a new runtime state. this function is thread safe

Return
the newly created state is returned. If an runtime state with the same non-empty name already exist, the old one is returned.
Parameters
  • name: if “”, it is an anonymous runtime state. otherwise it should be a unique name.
  • type_: NPLRuntimeStateType, the runtime state type. enum NPLRuntimeStateType { / the default NPL runtime state, with all NPL and ParaEngine functions loaded. it will consume about 1MB memory at start up. NPLRuntimeStateType_NPL = 0, / the light-weighter NPL runtime state, with only NPL and very limited functions loaded. NPLRuntimeStateType_NPL_LITE, / it consumes nothing. and is usually used with DLL plugins. NPLRuntimeStateType_DLL, };

ParaScripting::ParaNPLRuntimeState GetRuntimeState(const string &name)

get a runtime state with an explicit name. this function is thread safe

ParaScripting::ParaNPLRuntimeState CreateGetRuntimeState(const string &name, int type_)

it get runtime state first, if none exist, it will create one and add it to the main threaded state

bool DeleteRuntimeState(ParaNPLRuntimeState runtime_state)

create a given runtime state. this function is thread safe

void Compile(const char *arguments)

compile source The main advantages of precompiling chunks are: faster loading, protecting source code from accidental user changes, and off-line syntax checking. Precompiling does not imply faster execution because in npl chunks are always compiled into bytecodes before being executed. compiling simply allows those bytecodes to be saved in a file for later execution. compiling can produce a single output file containing the bytecodes for all source files given. By default, the output file is named luac.out, but you can change this with the -o option. e.g. NPL.Compile(“-p -o bin/script/config.o script/config.lua”);

Parameters
  • arguments: “%s [options] [filenames]” “Available options are:\n” ” - process stdin\n” ” -l list\n” ” -o name output to file ” LUA_QL(“name”) ” (default is \”s”) ” ” -p parse only ” ” -s strip debug information ” ” -v show version information ” ” – stop handling options ”,

bool AppendURLRequest1(const object &url, const char *sCallback, const object &sForm, const char *sPoolName)

Append URL request to a pool.

Parameters
  • pUrlTask: must be new CURLRequestTask(), the ownership of the task is transfered to the manager. so the caller should never delete the pointer.
  • sPoolName: the request pool name. If the pool does not exist, it will be created. If null, the default pool is used. Append URL request to a pool. HTTP Get: NPL.AppendURLRequest(“paraengine.com”, “callbackFunc()”, {“name1”, “value1”, “name2”, “value2”, }, “r”) HTTP Post: NPL.AppendURLRequest(“paraengine.com”, “callbackFunc()”, {name1=”value1”, name2=”value2”}, “r”)
  • url: usually a rest url.
  • sCallback: a string callback function. it may begin with (runtime_state_name) such as “(main)my_function()”, if no runtime state is provided, it is the main state(Not the calling thread). This prevents the user to use multiple threads to download to the same file location by mistake. the callback function to be called. a global msg={data, header, code, rcode} contains the result. the msg.data contains the response data, and msg.header contains the http header, and msg.code contains the return code from libcurl, msg.rcode contains HTTP/FTP status code(200 if succeed)
  • sForm: if it contains name value pairs, HTTP POST is used, otherwise HTTP GET is used. note that if it contains an array of name, value, name, value, ..., they will be regarded as url parameters can inserted to url automatically. This applies regardless of whether http get or post is used. one can also post a file, like belows {name = {file=”/tmp/test.txt”, type=”text/plain”}} {name = {file=”dummy.html”, data=”<html><bold>bold</bold></html>, type=”text/html”}} some predefined field name in sForm is request_timeout: milliseconds of request timeout e.g. {request_timeout=50000,}
  • sPoolName: the request pool name. If the pool does not exist, it will be created. If null, the default pool is used. there are some reserved pool names used by ParaEngine. They are:
    • “d”: download pool. default size is 2, for downloading files.
    • “r”: rest pool. default size is 5, for REST like HTTP get/post calls.
    • “w”: web pool. default size is 5, for web based requests.

string EncodeURLQuery(const char *baseUrl, const object &sParams)

build a use query using base url plus additional query parameters. NPL.BuildURLQuery(“paraengine.com”, {“name1”, “value1”, “name2”, “value2”, }) [thread safe]

Return
: result is like “paraengine.com?name1=value1&name2=value2”, they already in encoded form.
Parameters
  • sParams;: an array table, where odd index is name, even index is value.

std::string GetExternalIP()

get extern IP address of this computer.

bool ChangeRequestPoolSize(const char *sPoolName, int nCount)

There is generally no limit to the number of requests sent. However, each pool has a specified maximum number of concurrent worker slots. the default number is 1. One can change this number with this function.

bool FromJson(const char *sJson, const object &output)

convert json string to NPL object. Internally TinyJson is used.

Return
true if succeed. false if parsing failed.
Parameters
  • sJson: the json code to parse. the first level must be array or table. otherwise, false is returned.
  • output: [in|out] it must be a table. and usually empty table. the output is written to this table.

const string &ToJson(const object &output)

convert from NPL/lua table object to json string. /uXXXX encoding is recognized in string.

bool Compress(const object &output)

compress using zlib/gzip, etc

Return
return true if success.
Parameters
  • output: {method=”zlib|gzip”, content=string, [level=number, windowBits=number,] result=string}

bool Decompress(const object &output)

compress using zlib/gzip, etc

Parameters
  • output: {method=”zlib|gzip”, content=string, [level=number, windowBits=number,] result=string}

class CParaEngine
#include <ParaScriptingMisc.h>

global game engine related functions, such as ParaEngineCore interface, copy right information, simple water marking

Public Static Functions

ParaAttributeObject GetAttributeObject()

get the attribute object of ParaEngine settings

void GetAttributeObject_(ParaAttributeObject &output)

for API exportation.

string GetVersion()

get ParaEngine version

ParaScripting::ParaAttributeObject GetViewportAttributeObject(int nViewportIndex)

get attribute object

bool ForceRender()

render the current frame and does not return until everything is presented to screen. this function is usually used to draw the animated loading screen.

bool Sleep(float fSeconds)

cause the main thread to sleep for the specified seconds.

bool SaveParaXMesh(const char *filename, ParaAssetObject &xmesh, bool bBinaryEncoding)

save an existing mesh to file.

Return
: return true if succeeds.
Parameters
  • filename: file to be saved to. if this is “”, the xmesh entity’s file name will be used and appended with ”.x”
  • xmesh: ParaX mesh object to export.
  • bBinaryEncoding: true to use binary encoding.

ParaAssetObject GetRenderTarget()

return the current render target. calling this function a second time will make the returned object from the previous call invalid.

bool SetRenderTarget(ParaAssetObject &pRenderTarget)

set the render target of the object.

bool StretchRect(ParaAssetObject &pSrcRenderTarget, ParaAssetObject &pDestRenderTarget)

Copy render target content from one surface to another. they may be of different resolution

bool DrawQuad()

draw a full screen quad.

Note
: one need to set the vertex declaration to be S0_POS_TEX0 prior to calling this function

bool SetVertexDeclaration(int nIndex)

Set declaration by id enum VERTEX_DECLARATION { S0_POS_TEX0, // all data in stream 0: position and tex0 S0_POS_NORM_TEX0, // all data in stream 0: position, normal and tex0 S0_POS_NORM_TEX0_INSTANCED, // all data in stream 0: position, normal and tex0, stream1:instanced data S0_POS_TEX0_COLOR, // all data in stream 0: position, tex0 and color S0_S1_S2_OCEAN_FFT, // for FFT ocean S0_S1_S2_S3_OCEAN_FFT, // for FFT ocean with terrain height field S0_POS_NORM_TEX0_TEX1, // all data in stream 0: position, normal tex0 and tex1 MAX_DECLARATIONS_NUM, };

See
VERTEX_DECLARATION
Return
: return true if successful.
Parameters
  • nIndex: value is in

struct FileSystemWatcher_NPLCallback

callback to npl runtime

struct lua_func_entry

for registering functions

struct NPL_GetNidsArray_Iterator

Inherits from NPLConnectionCallBack

struct NPL_GetNidsStr_Iterator

Inherits from NPLConnectionCallBack

class ParaAsset
#include <ParaScriptingCommon.h>

ParaAsset namespace contains a list of HAPI functions to manage resources(asset) used in game world composing, such as 3d models, textures, animations, sound, etc. Resources are used to create scene objects. assets of the same type must have different names. Assets must be initialized before they can be used, and this should be manually done in scripts by calling Init().

Public Static Functions

bool OpenArchive(const char *strFileName)

open the archive file(zip or pkg file) for further resource file searching. If any file can not be located on the disk file system, it will go on searching for it in the archive file. files in the archive file will be relative to the ParaEngine SDK root directory.

Parameters
  • strFileName: the package file path name

bool GeneratePkgFile(const char *srcZip, const char *destPkg)

Generate a pkg file which is equivalent to the specified zip file. This function can only be called, when a zip file can be successfully loaded.

Return
true if successful. It will overwrite existing file. Output file is at the save directory and filename but with pkg file extension.
Parameters
  • srcZip: the zip file name from which to generate.
  • destPkg: : destination file. if nil, it just rename the srcZip

bool OpenArchive2(const char *strFileName, bool bUseRelativePath)

open the archive file(zip or pkg file) for further resource file searching. If any file can not be located on the disk file system, it will go on searching for it in the archive file.

Parameters
  • strFileName: the package file path name
  • bUseRelativePath: if this is true, files in the archive file will be relative to the parent directory of archive path.

bool OpenArchiveEx(const char *strFileName, const char *sRootDir)

add archive to manager

Parameters
  • strFileName: path of the zip or pkg file.
  • sRootDir: files in the archive will be regarded as relative to this this root directory. If this is “”, there is no root directory set. such as “model/”, “script/”, characters after the last slash is always stripped off.

void CloseArchive(const string &path)

close an archive. When done with an archive, one should always close it. Too many opened archives will compromise the IO performances.

const char *GetAssetServerUrl()

when an asset is not found, we will try to find it via this url. e.g. if asset is “model/test.dds”, and asset url is “http://asset.paraengine.com/”, then we will fetch the asset via “http://asset.paraengine.com/model/test.dds” if the asset path is “”, asset server will be disabled.

void SetAssetServerUrl(const char *path)

when an asset is not found, we will try to find it via this url. e.g. if asset is “model/test.dds”, and asset url is “http://asset.paraengine.com/”, then we will fetch the asset via “http://asset.paraengine.com/model/test.dds” if the asset path is “”, asset server will be disabled.

Parameters
  • path:if: the asset path is “”, asset server will be disabled.

void GarbageCollect()

Garbage Collect all assets according to reference count. If the reference count is not maintained well by the user, this function is not effective as UnloadAll().

See
UnloadAll().

void Unload(const char *assettype)

Unload an asset by its type name. once an unloaded asset is used again, its device resource will be reinitialized.

See
UnloadAll()
  • “ParaX”: Unload all ParaX models
  • “StaticMesh”: Unload all StaticMesh models
  • “Texture”: Unload all Texture
  • “Sound”: Unload all Sound
  • “Font”: Unload all Font TODO: currently only “*” is supported.
Parameters
  • strAssetName: value and meaning are listed below
    • “*”: Unload all assets.

void UnloadAll()

unload all assets. once an unloaded asset is used again, its device resource will be reinitialized.

See
Unload()

void UnloadDatabase()

unload all databases.

void Init()

initialize all objects that have not been created yet NOTE: always call this function at least once when finished creating a batch of assets assets created using any of the functions in this namespace can not be used until this function is called.

ParaScripting::ParaAssetObject LoadEffectFile(const char *strAssetName, const char *strFilePath)

Load effect file from a text or compiled HLSL file. It will return the old effect if effect is already loaded before.

ParaScripting::ParaAssetObject GetEffectFile(const char *strAssetName)

load an effect file by its name. it will return an invalid effect if the effect is not found.

ParaAssetObject LoadParaX(const char *strAssetName, const char *strFilePath)

Load ParaX model asset, ParaX model file contains mesh, skeletal animation, etc. Currently ParaX and mdx file format is supported, please refer to ParaX file document for creating ParaX file based multianimation asset.

ParaScripting::ParaAssetObject LoadDatabase(const char *strAssetName, const char *strFilePath)

Load Database asset. it must be sqlite database at the moment.

ParaAssetObject LoadStaticMesh(const char *strAssetName, const char *strFilePath)

Load a X file based static mesh object. If any side of the mesh’s bounding box is longer than 50 meters(units) and that the triangle count is over 1500, Octree will be used to sort its triangle lists, otherwise no culling optimization will be used when rendering the mesh. Static mesh is suitable for rendering small repeated object such as stones, trees, or large object such as level mesh. another usage is that it can be used as physical data to be fed to the physics engine, in which case simple and convex geometry should be used as much as possible.

ParaAssetObject LoadTexture(const char *strAssetName, const char *strFilePath, int nSurfaceType)

Note
: we treat png file as DXT3 by default. if the texture filename ends with “_32bits.png”, we will load with D3DFMT_A8R8G8B8 instead of DXT3. If one wants to ensure high resolution texture, use TGA format instead. All dds textures are loaded with full mipmapping default.
Return
Parameters
  • strAssetName:
  • strFilePath: if the file name ends with _a{0-9}{0-9}{0-9}.xxx, it will be regarded as a texture sequence. and the nSurfaceType will be ignored and forced to TextureSequence
  • nSurfaceType: enum _SurfaceType { / render target, call SetTextureInfo() to specify size. if SetTextureInfo() / is never called, the back buffer size is used. RenderTarget = 0, / normal managed texture, with all mip-mapping level created StaticTexture = 1, / a group of textures, such as xxx_a001.jpg, ..., xxx_a009.jpg TextureSequence = 2, / texture in memory SysMemoryTexture, / BLP textures BlpTexture, / detailed terrain texture TerrainHighResTexture, / cube texture for environment mapping, etc. CubeTexture, }

ParaAssetObject LoadSpriteFrame(const char *strAssetName, int nFrames, int nRow, int nCol)

A sprite object must be created from Sprite frame and a texture. This is to create the sprite frame, which tells the engine how the sprite is loaded in the texture.

Parameters
  • nFrames: how many frames the sprite has
  • nRow: number of rows in the texture
  • nCol: number of columns in the texture

ParaAssetObject LoadFont(const char *strAssetName, const char *FontName, int nFontSize)

load a system font, such as arial, times new man, etc.

Parameters
  • nFontSize: in pixels

ParaAssetObject LoadImageFont(const char *strAssetName, const char *TextureName, int nSize, int nTxtColumns)

load an image based font, not tested.

ParaAssetObject LoadSound(const char *strAssetName, const char *strFilePath, bool bInit)

load a sound or music. The sound is not initialized until it is played for the first time.

Parameters
  • bInit: whether to initialize the file

void AddFontName(const string &sLocalName, const string &sTypeFaceName)

give an alias name to a given font name. The most common use of this function is to replace the “System” font with a custom game font installed at “fonts/” folder.

Parameters
  • sLocalName: a local file name like “System”, “Default”
  • sTypeFaceName: the real type face name to use when creating the font. please note that, the engine will search for the file “fonts/[sTypeFaceName].ttf”, if this file exists, it will use that it, instead of the system installed font if any. Note: game custom font files under “fonts/” must be named by their true font name (i.e. type face name), otherwise they will not be loaded properly.

int GetBoneAnimProviderIDByName(const char *sName)

Get provider id by name. Name is used when creating the provider instance. It is usually the same as the file path from which animation data is loaded. return -1 if not found

const char *GetBoneAnimProviderFileNameByID(int nAnimID)

get the file name of a given animID. It may return NULL, if animID is invalid or is an internal animation id.

int CreateBoneAnimProvider(int nAnimID, const char *name, const char *filename, bool bOverwrite)

Create an animation provider from file.

Return
: return the nAnimID, in case nAnim is set to -1. -1 is returned, if failed.
Parameters
  • nAnimID: -1 if one wants it to be automatically assigned. otherwise one can manually specify one. Please note, if there is already a provider with the same ID, the old one is automatically released and replaced with the new one.
  • name: optional key. Allowing user to query by a user friendly name. This can be NULL.
  • filename: from which file the animation data is loaded. It can be a ParaX animation file or BVH file.
  • bOverwrite: whether to overwrite existing with the same nAnimID or name

bool DeleteBoneAnimProvider(int nAnimID)

delete a provider by ID.

Return
: return true if succeed.

int PrintToFile(const char *strFileName, DWORD dwSelection)

print all asset file to a given file. Each asset is on a single line, in the following format: [AssetFileName]

Return
: the number of results printed are returned.
Parameters
  • strFileName: to which file the result is written to. if NULL or “”, it is “temp/assets.txt”
  • dwSelection: bitwise on which assets to export, 1 is for texture, 2 is for Mesh, 4 is for ParaXEntity. Default to 0xffffffff

bool Refresh(const char *filename)

refresh asset if it is already loaded. it will search for all refreshable asset type, such as textures and mesh, etc. if found, it will call the Refresh() method on the asset entity and return true, or return false.

class ParaAssetObject
#include <ParaScriptingCommon.h>

it represents an asset entity.

Public Functions

bool IsValid()

check if the object is valid

bool IsLoaded()

most assets are loaded asynchronously. This allows us to check if an asset is loaded. For example, we can LoadAsset() for a number of assets that need preloading. and then use a timer to check if they are initialized and remove from the uninialized list.

bool equals(const ParaAssetObject obj) const

whether the two objects are equal

bool Reload()

reload the asset from file. Please note that for scene nodes which are currently using the asset entities, they are not automatically updated. For example, the physics which depends on a mesh entity, will not be automatically updated, once the mesh entity is reloaded. This function is almost solely used for debugging.

Return
: return true if the mesh is updated.

void UnloadAsset()

unload the asset from video and system memory. This is usually used for animated or one time texture entity. Please note, asset is unloaded, but can still be used by other scene objects.The use of an unloaded object will cause the object to be loaded again.

void LoadAsset()

Preload the asset to video and system memory, even though there is no scene object using the object in the previous frames.

void Refresh()

currently, this function only takes effects on texture entity refresh this entity with a local file.

Parameters
  • sFilename: if NULL or empty, the old file will be used.

void Release()

call this function to safely release this asset. If there is no further reference to this object, it will actually delete itself (with “delete this”). So never keep a pointer to this class after you have released it. A macro like SAFE_RELEASE() is advised to be used.

int GetRefCount()

get the reference count

void GarbageCollectMe()

if its reference count is zero, unload this asset object. any reference holder of this object can call this function to free its resources, if they believe that it will not be needed for quite some time in future.

string GetKeyName()

get the key name. this is usually the file name of the entity. return “” if it is not valid.

const char *GetKeyName_()

this function shall never be called from the scripting interface. Solely used for managed exporting.

string GetFileName()

get the file name. this is always the file name of the entity. return “” if it is not valid.

const char *GetFileName_()

this function shall never be called from the scripting interface. Solely used for managed exporting.

int GetType()

get the asset type: enum AssetType { base=0, texture=1, mesh=2, multianimation=3, spritevertex, font, sound, mdx, parax, database, effectfile, dllplugin, };

Return
-1 is returned, if the asset is invalid.

int SetHandle(int nHandle)

set an integer handle to this asset. This is usually used by effect file asset. We can later assign mesh’s primary technique handler using this value. please note that handles are not automatically created for most custom asset, one needs to manually create one. call this function multiple times with different handle, will associate the same asset with multiple handles.

Return
: handle of this asset after successful set.
Parameters
  • nHandle: TODO: if nHandle is -1, the system will automatically allocate a free handle for it and returned.

int GetHandle()

Get the integer handle to this asset. if there are multiple handles, the first (smallest) handle is returned. if handle is not available. it will return -1 (INVALID handle).

ParaScripting::ParaAttributeObject GetAttributeObject()

get the attribute object associated with the current asset object, such as getting the poly count, etc

ParaScripting::ParaParamBlock GetParamBlock()

get the parameter block. currently only effect and mesh entity file asset has effect param block. Currently the effect parameters can be set via ParaParamBlock interface from the scripting interface. we offer three levels of effect parameters: per effect file, per asset file, per mesh object. Effect parameters are also applied in that order. e.g. per effect file affects all object rendering with the effect file; per asset file affects all objects that use the mesh asset file; per mesh object affects only the mesh object.

bool Begin()

only applies to effect entity: begin effect

bool BeginPass(int nPass)

only applies to effect entity: begin effect pass

void SetTexture(int nIndex, const char *filename)

only used for effect file asset.

Parameters
  • nIndex: texture stage
  • filename: if “”, it will set to NULL

bool EndPass()

only applies to effect entity: end effect pass

bool End()

only applies to effect entity: end effect

bool CommitChanges()

this apply to changes.

void SetTextureFPS(float FPS)

For animated textures. set the FPS for animation textures. this provides a short cut to animated textures

Parameters
  • nFPS: frames per seconds. default value is 15 FPS

void EnableTextureAutoAnimation(bool bEnable)

For animated textures. whether to enable texture animation. this provides a short cut to animated textures

Parameters
  • bEnable: default value is true. Set this to false, if one wants to manually animate the texture, such as controlling from the scripting interface.

void SetCurrentFrameNumber(int nFrame)

For animated textures. set the current frame number. this provides a short cut to animated textures

Parameters
  • nFrame:

int GetCurrentFrameNumber()

For animated textures. Get the current frame number. this provides a short cut to animated textures

Return
frame number is returned

int GetFrameCount()

For animated textures. Get the total frames in the animated texture. this provides a short cut to animated textures

Return
frame number is returned

int GetWidth()

get the texture width

Return

int GetHeight()

get the texture height

Return

void SetSize(int nWidth, int nHeight)

set the texture info (size) of the asset

object GetBoundingBox(const object &box)

get the bounding box (AABB) of the mesh or parax entity in object space. This function returns nothing if asset is not mesh or character entity.

Parameters
  • box: [in|out] a script table to receive the output. in the format: {min_x, min_y, min_z, max_x, max_y, max_z}

int GetNumReplaceableTextures()

get the total number of replaceable textures, which is the largest replaceable texture ID. but it does not mean that all ID contains valid replaceable textures. This function can be used to quickly decide whether the model contains replaceable textures. Generally we allow 32 replaceable textures per model.

Return
0 may be returned if no replaceable texture is used by the model.

ParaAssetObject GetDefaultReplaceableTexture(int ReplaceableTextureID)

get the default replaceable texture by its ID. The default replaceable texture is the main texture exported from the 3dsmax exporter.

Return
this may return invalid asset, if replaceable texture is not set before or ID is invalid.
Parameters
  • ReplaceableTextureID: usually [0-32) generally speaking, replaceable ID 0 is used for general purpose replaceable texture, ID 1 is for user defined. ID 2 is for custom skins.

Public Static Functions

TextureEntity *GetTexture(const object &texture)

static helper functions:

Parameters

class ParaAttributeObject
#include <ParaScriptingGlobal.h>

it represents an attribute object associated with an object. Call ParaObject::GetAttributeObject() or ParaObject::GetAttributeObject() to get an instance of this object. e.g. In NPL, one can write local att = player:GetAttributeObject(); local bGloble = att:GetField(“global”, true); local facing = att:GetField(“facing”, 0); att:SetField(“facing”, facing+3.14); local pos = att:GetField(“position”, {0,0,0}); pos[1] = pos[1]+100;pos[2] = 0;pos[3] = 10; att:SetField(“position”, pos); att:PrintObject(“test.txt”);

the following shows objects and their supported attributes.









Public Functions

ParaAttributeObject GetAttributeObject()

get the attribute object. This function return a clone of this object.

bool equals(const ParaAttributeObject &obj) const

return true, if this object is the same as the given object.

ParaScripting::ParaAttributeObject GetChild(const std::string &sName)

get child attribute object. this can be regarded as an intrusive data model of a given object. once you get an attribute object, you can use this model class to access all data in the hierarchy.

int GetColumnCount()

we support multi-dimensional child object. by default objects have only one column.

bool AddChild(ParaAttributeObject &obj)

add a child object

const ParaObject &QueryObject()

query object

bool IsValid() const

check if the object is valid

int GetClassID() const

class ID

const char *GetClassName() const

class name

const char *GetClassDescription() const

class description

void SetOrder(int order)

Set which order fields are saved. enum Field_Order { Sort_ByName, Sort_ByCategory, Sort_ByInstallOrder, };

int GetOrder()

get which order fields are saved.

int GetFieldNum()

get the total number of field.

const char *GetFieldName(int nIndex)

get field at the specified index. “” will be returned if index is out of range.

int GetFieldIndex(const char *sFieldname)

get field index of a given field name. -1 will be returned if name not found.

Return
Parameters
  • sFieldname:

const char *GetFieldType(int nIndex)

get the field type as string

Return
one of the following type may be returned “void” “bool” “string” “int” “float” “float_float” “float_float_float” “double” “vector2” “vector3” “vector4” “enum” “deprecated” “”
Parameters
  • nIndex: : index of the field

bool IsFieldReadOnly(int nIndex)

whether the field is read only. a field is ready only if and only if it has only a get method.

Return
true if it is ready only or field does not exist
Parameters
  • nIndex: : index of the field

const char *GetFieldSchematics(int nIndex)

Get Field Schematics string

Return
“” will be returned if index is out of range
Parameters
  • nIndex: index of the field

const char *GetSchematicsType(int nIndex)

parse the schema type from the schema string.

Return
: simple schema type. it may be any of the following value. unspecified: “” color3 ”:rgb” file ”:file” script ”:script” integer ”:int”

void GetSchematicsMinMax(int nIndex, float fMinIn, float fMaxIn, float &fMin, float &fMax)

parse the schema min max value from the schema string.

Return
true if found min max.
Parameters
  • nIndex: index of the field
  • fMin: : [in|out] default value
  • fMax: : [in|out] default value

object GetField(const char *sFieldname, const object &output)

get field by name. e.g. suppose att is the attribute object. local bGloble = att:GetField(“global”, true); local facing = att:GetField(“facing”, 0); local pos = att:GetField(“position”, {0,0,0}); pos[1] = pos[1]+100;pos[2] = 0;pos[3] = 10;

Return
: return the field result. If field not found, output will be returned. if field type is vectorN, return a table with N items.Please note table index start from 1
Parameters
  • sFieldname: field name
  • output: default value. if field type is vectorN, output is a table with N items.

const char *GetStringField(const char *sFieldname)

similar to GetField(). except that the output is a string. Used for API exporting. not thread safe.

double GetValueField(const char *sFieldname, int nIndex = 0)

similar to GetField(). except that the output is a value. Used for API exporting. not thread safe.

Parameters
  • nIndex: if the value has multiple component, such as a vector3. this is the index of the componet.

void SetField(const char *sFieldname, const object &input)

set field by name e.g. suppose att is the attribute object. att:SetField(“facing”, 3.14); att:SetField(“position”, {100,0,0});

Parameters
  • sFieldname: field name
  • input: input value. if field type is vectorN, input is a table with N items.

void SetStringField(const char *sFieldname, const char *input)

similar to SetField(). except that the input is a string. Used for API exporting. not thread safe.

void SetValueField(const char *sFieldname, int nIndex, double value)

similar to SetField(). except that the input is a string. Used for API exporting. not thread safe.

Parameters
  • nIndex: if the value has multiple component, such as a vector3. this is the index of the component.

void CallField(const char *sFieldname)

call field by name. This function is only valid when The field type is void. It simply calls the function associated with the field name.

void PrintObject(const char *file)

print attribute to file

Parameters
  • file: file name to save the manual to.

bool ResetField(int nFieldID)

Reset the field to its initial or default value.

Return
true if value is set; false if value not set.
Parameters
  • nFieldID: : field ID

bool InvokeEditor(int nFieldID, const char *sParameters)

Invoke an (external) editor for a given field. This is usually for NPL script field

Return
true if editor is invoked, false if failed or field has no editor.
Parameters
  • nFieldID: : field ID
  • sParameters: : the parameter passed to the editor

object GetDynamicField(const char *sFieldname, const object &output)

get field by name. e.g. suppose att is the attribute object. local bGloble = att:GetField(“URL”, nil); local facing = att:GetField(“Title”, “default one”);

Return
: return the field result. If field not found, output will be returned. if field type is vectorN, return a table with N items.Please note table index start from 1
Parameters
  • sFieldname: field name
  • output: default value. if field type is vectorN, output is a table with N items.

object GetDynamicField_(int nIndex, const object &output)

Get a dynamic field with a given index.

const char *GetDynamicFieldNameByIndex(int nIndex)

get field name by index

int GetDynamicFieldCount()

how many dynamic field this object currently have.

int SetDynamicField(const char *sFieldname, const object &input)

set field by name e.g. suppose att is the attribute object. att:SetDynamicField(“URL”, 3.14); att:SetDynamicField(“Title”, {100,0,0});

Return
: -1 failed, if 0 means modified, if 1 means a new key is added, if 2 means a key is removed.
Parameters
  • sFieldname: field name
  • input: input value. can be value or string type

void RemoveAllDynamicFields()

remove all dynamic fields

int AddDynamicField(const std::string &sName, int dwType)

add dynamic field and return field index

Parameters
  • dwType: type of ATTRIBUTE_FIELDTYPE

class ParaAudio
#include <ParaScriptingAudio.h>

Audio Engine functions

Public Static Functions

bool IsAudioEngineEnabled()

————- Audio Engine Functions ————- get is audio engine enabled

void EnableAudioEngine(bool bEnable)

enable Audio Engine

void SetVolume(float fVolume)

Set the volume of all categories and all currently playing wave files.

Parameters
  • fVolume: usually between [0,1], where 0 is silent and 1 is full. value larger than 1 is also possible.

float GetVolume()

Get the volume of average if all categories

Return
usually between [0,1], where 0 is silent and 1 is full. value larger than 1 is also possible.

ParaAudioSource Create(const char *sName, const char *sWavePath, bool bStream)

create a given audio source by name. If no audio source with the name is loaded before, we will create one new; otherwise we will overwrite the previous one.

Return
CAudioSource2_ptr object returned. It may be null if failed.
Parameters
  • sName: the audio source name. Usually same as the audio file path, however it can be any string.
  • sWavePath: if NULL, it will defaults to sName. Please note, in order to play the same music at the same time, they must be created with different names.
  • bStream: whether to stream the music once created.

ParaAudioSource Get(const char *sName)

get audio source by name. The source should be created by Create() function.

ParaAudioSource CreateGet(const char *sName, const char *sWavePath, bool bStream)

get a given audio source by name. If no audio source with the name is loaded before, we will create one.

Return
CAudioSource2_ptr object returned. It may be null if failed.
Parameters
  • sName: the audio source name. Usually same as the audio file path, however it can be any string.
  • sWavePath: if NULL, it will defaults to sName. Please note, in order to play the same music at the same time, they must be created with different names.
  • bStream: whether to stream the music once created.

void SetDistanceModel(int eDistModel)

set the audio distance model. see: http://connect.creativelabs.com/openal/Documentation/OpenAL%201.1%20Specification.htm

Parameters
  • eDistModel: int of following. enum ParaAudioDistanceModelEnum { Audio_DistModel_NONE = 0, Audio_DistModel_INVERSE_DISTANCE, Audio_DistModel_INVERSE_DISTANCE_CLAMPED, Audio_DistModel_LINEAR_DISTANCE, Audio_DistModel_LINEAR_DISTANCE_CLAMPED, Audio_DistModel_EXPONENT_DISTANCE, Audio_DistModel_EXPONENT_DISTANCE_CLAMPED, };

bool PlayWaveFile(const char *szWavePath, int nLoop)

Prepare and play a wave object from a standard wave file (wav, mp3, ogg/vorbis). If a wave file is already prepared before. It will be reused.

Parameters
  • szWavePath: Path to the wave file. It can be from asset_manifest or relative to current directory path.
  • nLoop: 0 means non-looping. 1 means looping.

int PlayMidiMsg(DWORD dwMsg)

more information, please see: midiOutShortMsg

Parameters
  • dwMsg: MIDI message. The message is packed into a DWORD value with the first byte of the message in the low-order byte. The message is packed into this parameter as follows.

bool StopWaveFile(const char *szWavePath, bool bImmediateStop)

stop a wave file

Parameters
  • szWavePath: Path to the wave file.
  • bImmediateStop: if false, it plays the wave to completion, then stops. For looping waves, this flag plays the current iteration to completion, then stops (ignoring any subsequent iterations). In either case, any release (or tail) is played. To stop the wave immediately, use true.

bool ReleaseWaveFile(const char *szWavePath)

release a wave file

Parameters
  • szWavePath: Path to the wave file.

class ParaAudioSource
#include <ParaScriptingAudio.h>

It represents a 2D or 3D audio source object.

Public Functions

bool IsValid() const

true if valid

void release()

stop and unload this audio source from memory. It will make the sound source invalid after calling this function. it is good practice to unload unused sound.

bool play()

Plays the source with the last set parameters.

Return
True if the source is playing, false if not.

const char *GetName()

get the source name. (this may not be the file name)

bool play2d(bool toLoop)

Plays the source in 2D mode. No automatic attenuation or panning will take place in this mode, but using setPosition will allow you to manually pan mono audio streams.

Return
True if the source is playing, false if not.
Parameters
  • toLoop: Whether to loop (restart) the audio when the end is reached.

bool play3d(float x, float y, float z, float soundstr, bool toLoop)

Plays the source in 3D mode.

Return
True if the source is playing, false if not.
Parameters
  • position: Position to start the sound off at.
  • soundstr: Affects how the source attenuates due to distance. Higher values cause the source to stand out more over distance.
  • toLoop: Whether to loop (restart) the audio when the end is reached.

void pause()

Pauses playback of the sound source.

void stop()

Stops playback of the sound source.

void loop(bool toLoop)

Controls whether the source should loop or not.

Parameters
  • toLoop: Whether to loop (restart) the audio when the end is reached.

bool seek(float seconds, bool relative)

Seeks through the audio stream to a specific spot. Note: May not be supported by all codecs.

Return
True on success, False if the codec does not support seeking.
Parameters
  • seconds: Number of seconds to seek.
  • relative: Whether to seek from the current position or the start of the stream.

float getTotalAudioTime()

Return
the total amount of time in the audio stream. See IAudioDecoder for details.

int getTotalAudioSize()

Return
the total decoded size of the audio stream. See IAudioDecoder for details.

float getCurrentAudioTime()

Return
the current position in the audio stream in seconds. See IAudioDecoder for details.

int getCurrentAudioPosition()

Return
the current position in the decoded audio stream in bytes. See IAudioDecoder for details.

bool isValid() const

Return
if the source is ready to be used.

bool isPlaying() const

Return
if the source is playing.

bool isPaused() const

Return
if the source is paused.

bool isStopped() const

Return
if the source is stopped.

bool isLooping() const

Return
if the source is looping.

void setPosition(float x, float y, float z)

Sets the position of the source in 3D space.

Parameters
  • position: A 3D vector giving the new location to put this source.

void setVelocity(float x, float y, float z)

Sets the current velocity of the source for doppler effects.

Parameters
  • velocity: A 3D vector giving the speed and direction that the source is moving.

void setDirection(float x, float y, float z)

Sets the direction the source is facing.

Parameters
  • direction: A 3D vector giving the direction that the source is aiming.

void setRolloffFactor(float rolloff)

Sets the factor used in attenuating the source over distance. Larger values make it attenuate faster, smaller values make the source carry better. Range: 0.0f to +inf (Default: 1.0f).

Parameters
  • rolloff: The rolloff factor to apply to the attenuation calculation.

void setStrength(float soundstrength)

Sets how well the source carries over distance.

Same as setRolloffFactor(1.0f/soundstrength). Range: 0.0f to +inf (Default: 1.0f).

Parameters
  • soundstrength: How well the sound carries over distance.

void setMinDistance(float minDistance)

Sets the distance from the source where attenuation will begin. Range: 0.0f to +inf

Parameters
  • minDistance: Distance from the source where attenuation begins.

void setMaxDistance(float maxDistance)

Sets the distance from the source where attenuation will stop. Range: 0.0f to +inf

Parameters
  • maxDistance: Distance where attenuation will cease. Normally the farthest range you can hear the source.

void setPitch(float pitch)

Sets the pitch of the source. Range: 0.0f to +inf (Default: 1.0f)

Parameters
  • pitch: New pitch level. Note that higher values will speed up the playback of the sound.

void setVolume(float volume)

Sets the source volume before attenuation and other effects. Range: 0.0f to +inf (Default: 1.0f).

Parameters
  • volume: New volume of the source.

void setMinVolume(float minVolume)

Sets the minimum volume that the source can be attenuated to. Range: 0.0f to +inf (Default: 0.0f).

Parameters
  • minVolume: New minimum volume of the source.

void setMaxVolume(float maxVolume)

Sets the maximum volume that the source can achieve. Range: 0.0f to +inf (Default: 1.0f).

Parameters
  • maxVolume: New maximum volume of the source.

void setInnerConeAngle(float innerAngle)

Sets the angle of the inner sound cone of the source. The cone opens up in the direction of the source as set by setDirection(). Note: This causes the sound to be loudest only if the listener is inside this cone. Range: 0.0f to 360.0f (Default: 360.0f).

Parameters
  • innerAngle: Inside angle of the cone.

void setOuterConeAngle(float outerAngle)

Sets the angle of the outer sound cone of the source. The cone opens up in the direction of the source as set by setDirection(). Note: If the listener is outside of this cone, the sound cannot be heard. Between the inner cone angle and this angle, the sound volume will fall off. Range: 0.0f to 360.0f (Default: 360.0f).

Parameters
  • outerAngle: Outside angle of the cone.

void setOuterConeVolume(float outerVolume)

Sets how much the volume of the source is scaled in the outer cone. Range: 0.0f to +inf (Default: 0.0f).

Parameters
  • outerVolume: Volume of the source in the outside cone.

void move(float x, float y, float z)

Convenience function to automatically set the velocity and position for you in a single call. Velocity will be set to new position - last position.

Parameters
  • position: Position to move the source to.

void getPosition(float &x, float &y, float &z) const

Return
the audio objects position

void getVelocity(float &x, float &y, float &z) const

Return
the audio objects velocity

void getDirection(float &x, float &y, float &z) const

Return
the audio objects direction

float getRolloffFactor() const

Return
the factor used in attenuating the source over distance

float getStrength() const

Return
the strength of the source

float getMinDistance() const

Return
the distance from the source where attenuation will begin

float getMaxDistance() const

Return
the distance from the source where attenuation will stop

float getPitch() const

Return
the pitch of the source

float getVolume() const

Return
the source volume before attenuation and other effects

float getMinVolume() const

Return
the minimum volume that the source can be attenuated to

float getMaxVolume() const

Return
the maximum volume that the source can achieve

float getInnerConeAngle() const

Return
the angle of the inner sound cone of the source

float getOuterConeAngle() const

Return
the angle of the outer sound cone of the source

float getOuterConeVolume() const

Return
how much the volume of the source is scaled in the outer cone

class ParaBlockWorld
#include <ParaScriptingBlockWorld.h>

Wrapper of internal CBlockWorld. may have multiple instance of the block world.

Public Static Functions

luabind::object GetWorld(const object &sWorldName)

static function to create get a world instance

int GetVersion(const object &pWorld)

get version

ParaScripting::ParaAttributeObject GetBlockAttributeObject(const object &pWorld)

get block terrain manager’s attribute object.

bool RegisterBlockTemplate(const object &pWorld, uint16_t templateId, const object &params)

register blocks with given parameters

Parameters
  • params: it can be attFlag of int type. or it can be a table containing additional format such as {attFlag=number, modelName=string, etc. }

void SetBlockWorldYOffset(const object &pWorld, float offset)

set Block world’s y offset in real world coordinate.

void EnterWorld(const object &pWorld, const char *sWorldDir)

call this function after all block templates has been registered to initialize the world note this function can be called multiple times to load different world with the same block templates. call LeaveWorld() before EnterWorld again.

Parameters
  • sWorldDir: world directory or world config file.

void LeaveWorld(const object &pWorld)

call this function when leave the block world

void LoadRegion(const object &pWorld, uint16_t x, uint16_t y, uint16_t z)

load region at the given position. current implementation will load entire region rather than just chunk. one need to call load chunk before SetBlock/GetBlock api can be called in the region.

void UnloadRegion(const object &pWorld, uint16_t x, uint16_t y, uint16_t z)

unload data for a given region from memory

void SetBlockId(const object &pWorld, uint16_t x, uint16_t y, uint16_t z, uint32_t templateId)

set block id set the given position.

Parameters
  • xyz: should be positive value
  • templateId: template id. specify 0 to delete a block.

uint32_t GetBlockId(const object &pWorld, uint16_t x, uint16_t y, uint16_t z)

get block id at the given block position.

void SetBlockData(const object &pWorld, uint16_t x, uint16_t y, uint16_t z, uint32_t data)

set per block user data

uint32_t GetBlockData(const object &pWorld, uint16_t x, uint16_t y, uint16_t z)

get per block user data

luabind::object GetBlocksInRegion(const object &pWorld, int32_t startChunkX, int32_t startChunkY, int32_t startChunkZ, int32_t endChunkX, int32_t endChunkY, int32_t endChunkZ, uint32_t matchType, const object &result)

get block in [startChunk,endChunk]

Return
{count,x{},y{},z{},tempId{}}
Parameters
  • result: in/out containing the result.
  • startChunkYendChunkY: if negative, and startChunkY == endChunkY, -startChunkY will be used as verticalSectionFilter (a bitwise filter).

void SetBlockWorldSunIntensity(const object &pWorld, float value)

set current sun intensity in [0,1] range

int FindFirstBlock(const object &pWorld, uint16_t x, uint16_t y, uint16_t z, uint16_t nSide = 4, uint32_t max_dist = 32, uint32_t attrFilter = 0xffffffff, int nCategoryID = -1)

find a block in the side direction that matched filter from block(x,y,z) this function can be used to check for free space upward or download

Return
-1 if not found. otherwise distance to the first block that match in the side direction is returned.
Parameters
  • side: 4 is top. 5 is bottom.
  • attrFilter: attribute to match. 0 means air. default to any block
  • nCategoryID: -1 means any category_id. default to -1

int GetFirstBlock(const object &pWorld, uint16_t x, uint16_t y, uint16_t z, int nBlockId, uint16_t nSide = 4, uint32_t max_dist = 32)

get the y pos of the first block of nBlockID, start searching from x, y, z in the side direction

void SetTemplateTexture(const object &pWorld, uint16_t templateId, const char *fileName)

set the template texture. only used on client side This function is deprecated. use RegisterBlockTemplate instead.

luabind::object GetVisibleChunkRegion(const object &pWorld, const object &result)

get visible chunk region only used on client side

Return
: world space chunk id {minX,minY,minZ,maxX,maxY,maxZ}

luabind::object Pick(const object &pWorld, float rayX, float rayY, float rayZ, float dirX, float dirY, float dirZ, float fMaxDistance, const object &result, uint32_t filter = 0xffffffff)

ray origin should be positive value, ray direction should be normalized value function is only used on client world

Return
: result[“x”] = pickResult.X; result[“y”] = pickResult.Y; result[“z”] = pickResult.Z; result[“blockX”] = pickResult.BlockX; result[“blockY”] = pickResult.BlockY; result[“blockZ”] = pickResult.BlockZ; result[“side”] = pickResult.Side; result[“length”] = pickResult.Distance; side value : 0 negativeX,1 positiveX,2 NZ,3 PZ,4 NY, 5PY length > fMaxDistance when no collision detected

luabind::object MousePick(const object &pWorld, float fMaxDistance, const object &result, uint32_t filter = 0xffffffff)

picking by current mouse position. only used on client world

void SelectBlock(const object &pWorld, uint16_t x, uint16_t y, uint16_t z, bool isSelect)

add/remove block to/from highlight block list only used on client side

Parameters
  • xyz: world space block id;
  • isSelect: : true to select block, false to de-select block
  • nGroupID: group id. 0 for highlight 1 for wireframe.

void DeselectAllBlock1(const object &pWorld, int nGroupID)

Parameters
  • nGroupID: 0 for animated selection, 1 for wire frame selection. -1 for all

void SetDamagedBlock(const object &pWorld, uint16_t x, uint16_t y, uint16_t z)

set damage block id only used on client side

Parameters
  • xyz: :world space block id;

void SetDamageDegree(const object &pWorld, float damagedDegree)

set damage block degree

Parameters
  • damageDegree: [0,1] 0 means undamaged block,1 full damaged block

class ParaBootStrapper
#include <ParaScriptingGlobal.h>

ParaGlobal namespace contains a list of HAPI functions to access the boot strapper functionality.

Bootstrapper file is a xml file to be executed at the very beginning of the game engine. Its main function is to specify the main game loop file to be activated. When the ParaIDE set a solution to be active, it actually modifies the bootstrapper file to load the main file of that application solution.

Public Static Functions

bool LoadFromFile(const char *sXMLfile)

load from a given XML file.

Return
true if success
Parameters
  • sXMLfile: the path of the file, if this is “”, the config/bootstrapper.xml will be used.

bool SaveToFile(const char *sXMLfile)

save to a given XML file.

Return
true if success
Parameters
  • sXMLfile: the path of the file, if this is “”, the config/bootstrapper.xml will be used.

void LoadDefault()

load the default setting. this function is called at the constructor.

const char *GetMainLoopFile()

get the game loop file. the game loop file provides the heart beat of the application. It is also the very first(entry) script to be activated when the application starts up. The default game loop is ./script/gameinterface.lua

void SetMainLoopFile(const char *sMainFile)

Set the game loop file. the game loop file provides the heart beat of the application. It is also the very first(entry) script to be activated when the application starts up. The default game loop is ./script/gameinterface.lua

class ParaBrowserManager
#include <ParaScriptingBrowserManager.h>

managing HTML browsers

Public Static Functions

static ParaHTMLBrowser GetBrowserWindow(const char *sFileName)

get ParaHTMLBrowser by name. this function does not create any player if there is no browser with the given name.

static ParaHTMLBrowser GetBrowserWindow1(int nWindowID)

get ParaHTMLBrowser by nWindowID. this function does not create any player if there is no browser at the given index.

static ParaHTMLBrowser createBrowserWindow(const char *sFileName, int browserWindowWidth, int browserWindowHeight)

create a new browser window with the given name and dimension in pixels.

static void onPageChanged(const object &strScriptName)

set event handler. the scripting interface will receive a msg table for the following type msg={windowid=number, value=[ValueInt|ValueString|nil]} where value is nil

Parameters
  • strScriptName: format is “[neuronfile];sCode”;

static void onNavigateBegin(const object &strScriptName)

set event handler. the scripting interface will receive a msg table for the following type msg={windowid=number, value=[ValueInt|ValueString|nil]} where value is a string

Parameters
  • strScriptName: format is “[neuronfile];sCode”;

static void onNavigateComplete(const object &strScriptName)

set event handler. the scripting interface will receive a msg table for the following type msg={windowid=number, value=[ValueInt|ValueString|nil]} where value is a string

Parameters
  • strScriptName: format is “[neuronfile];sCode”;

static void onUpdateProgress(const object &strScriptName)

set event handler. the scripting interface will receive a msg table for the following type msg={windowid=number, value=[ValueInt|ValueString|nil]} where value is a int of [0-100]

Parameters
  • strScriptName: format is “[neuronfile];sCode”;

static void onStatusTextChange(const object &strScriptName)

set event handler. the scripting interface will receive a msg table for the following type msg={windowid=number, value=[ValueInt|ValueString|nil]} where value is a string of status text

Parameters
  • strScriptName: format is “[neuronfile];sCode”;

static void onLocationChange(const object &strScriptName)

set event handler. the scripting interface will receive a msg table for the following type msg={windowid=number, value=[ValueInt|ValueString|nil]} where value is a string

Parameters
  • strScriptName: format is “[neuronfile];sCode”;

static void onClickLinkHref(const object &strScriptName)

set event handler. the scripting interface will receive a msg table for the following type msg={windowid=number, value=[ValueInt|ValueString|nil]} where value is a string of HRef

Parameters
  • strScriptName: format is “[neuronfile];sCode”;

class ParaCamera
#include <ParaScriptingScene.h>

The camera controller. First call FollowObject() method to set the character to follow. set call any of the camera transition functions to set the camera follow mode

Public Static Functions

void FollowObject(ParaObject obj)

set the character to follow. the object is also set as the current player

Parameters

void FollowObject(const char *strObjectName)

set the character to follow. the object must be global in order to be found by its name. It is also set as the current player currently,

Parameters
  • strObjectName: the name of the object to follow

void FirstPerson(int nTransitionMode, float fHeight, float fAngle)

Set the current camera to follow a certain object, using first person view of the object.

Parameters
  • nTransitionMode: 1 (default) smooth move or 0 immediate move
  • fRadius: the distance from the person to the camera
  • fAngle: camera lift up angle, this is usually Pi/4: 45 degrees

void ThirdPerson(int nTransitionMode, float fHeight, float fFacing, float fAngle)

Set the current camera to follow a certain object, using Third Person view of the object, where character is always centered while allowing rotation around it from 360 degree angles,

Parameters
  • nTransitionMode: 1 (default) smooth move or 0 immediate move
  • fRadius: the distance from the person to the camera
  • fFacing: camera facing, around the y axis, which is the world height axis.
  • fAngle: camera lift up angle, this is usually Pi/4: 45 degrees

void Default(int nTransitionMode, float fHeight, float fAngle)

: Set the current camera to follow a certain object, using the default view of the object. character restricted to move within a rectangular region, while camera is facing a fixed direction.

Parameters
  • nTransitionMode: 1 (default) smooth move or 0 immediate move
  • fHeight: relative camera height above the object.
  • fAngle: camera lift up angle, this is usually Pi/4: 45 degrees

void Fixed(int nTransitionMode, float fX, float fY, float fZ)

Set the current camera to look at a certain object, from a fixed camera location while allowing rotation around it from 360 degree angles,

Parameters
  • nTransitionMode: 1 (default) smooth move or 0 immediate move
  • fX: camera location: x
  • fY: camera location: y
  • fZ: camera location: z

void GetPosition(float *x, float *y, float *z)

get the world position of the camera eye. This function takes no parameters. x,y,z are not input, but pure output. In the script, we can call it as below x,y,z = ParaCamera.GetPosition(); get the camera’s eye position in Luabind, it is defined as .def(“GetPosition”, &ParaCamera::GetPosition, pure_out_value(_1) + pure_out_value(_2) + pure_out_value(_3)) please note, y is the absolute position in world coordinate

See
SetPosition(float x, float y, float z)

void GetLookAtPosition(float *x, float *y, float *z)

get the position that the camera is currently looking at.

void SetKeyMap(int key, int scancode)

we can alter key map at runtime

Parameters
  • key: CharacterAndCameraKeys . [0-10]
  • scancode: DIK_A, DIK_D,DIK_W,DIK_S,DIK_Q,DIK_E,DIK_SPACE,0,0,DIK_INSERT,DIK_DELETE

int GetKeyMap(int key)

get scancode from key id

ParaAttributeObject GetAttributeObject()

get the attribute object associated with the current camera object.

void GetAttributeObject_(ParaAttributeObject &output)

used for API exportation.

class ParaCharacter
#include <ParaScriptingCharacter.h>

ParaObject class: it is used to control game scene objects from scripts.

Public Functions

bool IsValid()

check if the object is valid

void SetSpeedScale(float fSpeedScale)

the default value of speed scale is 1.0f, which will use the character’s default speed.

void FallDown()

if the biped is in air, it will fall down. In case a biped is put to stop and the terrain below it changes. one should manually call this function to let the biped fall down. Internally it just set the vertical speed to a small value

void SetSizeScale(float fScale)

the default value of size scale is 1.0f, which will use the character’s default size. increasing this value will enlarge the character as well as its physical radius.

void SetFocus()

ask the camera to follow this character.The camera will be immediately focused on this character without translation.

void AddAction2(int nAction, const object &param)

add an action symbol, and let the character state manager determine which states it should go to. this function will not perform any concrete actions on the biped objects.

Parameters
  • nAction: please see script/ide/action_table.lua for a list of valid values.
  • param: the param specifying more details about the action. This value default to nil if nAct is S_ACTIONKEY, then this is const ActionKey* if nAct is S_WALK_POINT, then this is nil or 1, specifying whether to use angle.

bool WalkingOrRunning()

return true if character uses walk as the default moving animation.otherwise it uses running.

bool HasAnimation(int nAnimID)

whether an animation id exist. this function may have different return value when asset is async loaded.

Parameters
  • nAnimID: predefined id.

bool IsCustomModel()

check whether this character is customizable.

void ResetBaseModel(ParaAssetObject assetCharBaseModel)

Reset base model. Base model is the frame model, to which other sub-models like weapons and clothing are attached. NOTE: the current version will delete the entire model instance, so that any sub-models attached to this model will be deleted and that the default appearance of the base model will show up, if one does not update its equipment after this call.

Parameters
  • assetCharBaseModel: It is the new base model asset;it should be a valid ParaX model asset.

void SetSkin(int nIndex)

set the replaceable skin according to the skin database. this only applies to non-customizable characters.if the index exceeds, it will use the default one. the default skin is at index 0.

Parameters
  • nIndex: the skin index.

int GetSkin()

return the current skin index. the default skin is at index 0.

void LoadStoredModel(int nModelSetID)

Load a stored model in data base by the model set ID. A stored model usually contain the attachments and equipments, but not the base model. This function is only valid when the base model has already been set.

Parameters
  • nModelSetID: the ID of the model set in the database. Some ID may be reserved for user-specified model

void PlayAnimation(const object &anims)

play a specified animation.

Parameters
  • anims:
    • it can be int of animation ID(external animation id is supported) see local nAnimID = ParaAsset.CreateBoneAnimProvider(-1, filename, filename, false);
    • it can also be string of animation file name
    • it can also be a table of {animID, animID}: currently only two are supported. The first one is usually a non-loop, and second one can be loop or non-loop.

int GetAnimID()

get the current animation ID of the character. Usually 0-46 is for normal animation like idle and walking; 0-1000 are reserved for internally animation. 1000-2000 are game specific; 2000 plus are automatically generated. One should call GetAnimFileName() for id above 2000.

Return
: it may return -1 if invalid.

const char *GetAnimFileName()

get the current animation’s filename. If it is an internal animation, it will return nil. If it is from bone animation provider, it returns the file name from which the animation is loaded.

void EnableAnimIDMap(bool bEnable)

set whether the m_mapAnimIDs will be used. Disabled by default

bool IsAnimIDMapEnabled()

get whether the m_mapAnimIDs will be used.Disabled by default

bool AddAnimIDMap(int nFromID, int nToID)

get whether the m_mapAnimIDs will be used.Disabled by default animation ID mapping is a mapping from one animation ID to another ID. This mapping is usually not used (empty). However, it is used when we can want to secretly replace animation used by this animation instance, by adding a ID to ID map. e.g. we can replace female walk animation ID with an external female walk animation ID.

Note
: remember to EnableAnimIDMap() in order for the mapping to take effect.
Parameters
  • nFromID:
  • nToID: if it is negative, the mapping nFromID is removed.

void ClearAllAnimIDMap()

remove all mapping.

bool HasMountPoint(int nMountPointID)

whether the character has a mount point at the given ID. Such characters are usually cars, horses, planes, etc.

Parameters
  • nMountPointID: this is usually 0.

bool IsMounted()

whether the object is mounted on another object.

void MountOn_(const char *sTarget)

mount the current object on another object.

Parameters
  • sTarget: the name of the global target object on which the current character is mounted on.

void MountOn(ParaObject &target)

the target must contain at least one mount point. if there are multiple mount point, it will mount to the closet one.

Parameters
  • target: the name of the target object on which the current character is mounted on.

void MountOn2(ParaObject &target, int nMountID)

the target must contain at least one mount point. if there are multiple mount point, it will mount to the closet one.

Parameters
  • target: the name of the target object on which the current character is mounted on.
  • nMountID: the attachment ID of the model. if -1 (default), we will attach to the nearest mount position.

void UnMount()

this will force unmount the characer. However, it is usually not natural to do this explicitly, since we do not know how the character should behave after mount. Instead, one can call player_obj:ToCharacter():AddAction(action_table.ActionSymbols.S_JUMP_START) to unmount by jumping off.

void SetBodyParams(int skinColor, int faceType, int hairColor, int hairStyle, int facialHair)

Set the character body parameters. Need to call RefreshModel() after finished with the settings. All body parameters are integer ranging from 0 to maxType, where maxType is the maximum number of types of of a certain body parameter. For each body parameter, one can specify -1 to retain its current value. This is useful, when the caller only wants to change one or several of the body parameters. The default body parameters is (0,0,0,0,0).

int GetBodyParams(int type)

Get the character body parameters. @ param type: the body parameter type of the character BP_SKINCOLOR =0, BP_FACETYPE = 1, BP_HAIRCOLOR = 2, BP_HAIRSTYLE = 3, BP_FACIALHAIR = 4

void SetDisplayOptions(int bShowUnderwear, int bShowEars, int bShowHair)

Set the display options for the character. in case of boolean input: 1 stands for true; 0 stands for false, -1 stands for retaining its current value. Need to call RefreshModel() after finished with the settings.

bool GetDisplayOptions(int type)

Get the display option parameters. @ param type: the display option parameter of the character DO_SHOWUNDERWEAR =0, DO_SHOWEARS = 1, DO_SHOWHAIR = 2

void SetCharacterSlot(int nSlotID, int nItemID)

set the model ID of a specified character slot. Need to call RefreshModel() after finished with the settings.

Parameters
  • nSlotID: the ID of the slot to be set for the character. Normally there are 16 slots on the character. CS_HEAD =0, CS_NECK = 1, CS_SHOULDER = 2, CS_BOOTS = 3, CS_BELT = 4, CS_SHIRT = 5, CS_PANTS = 6, CS_CHEST = 7, CS_BRACERS = 8, CS_GLOVES = 9, CS_HAND_RIGHT = 10, CS_HAND_LEFT = 11, CS_CAPE = 12, CS_TABARD = 13, CS_FACE_ADDON = 14, // newly added by andy 2009.5.10, Item type: IT_MASK 26 CS_WINGS = 15, // newly added by andy 2009.5.11, Item type: IT_WINGS 27 CS_ARIES_CHAR_SHIRT = 16, // newly added by andy 2009.6.16, Item type: IT_WINGS 28 CS_ARIES_CHAR_PANT = 17, CS_ARIES_CHAR_HAND = 18, CS_ARIES_CHAR_FOOT = 19, CS_ARIES_CHAR_GLASS = 20, CS_ARIES_CHAR_WING = 21, CS_ARIES_PET_HEAD = 22, CS_ARIES_PET_BODY = 23, CS_ARIES_PET_TAIL = 24, CS_ARIES_PET_WING = 25, CS_ARIES_CHAR_SHIRT_TEEN = 28, // newly added by andy 2011.8.13, Item type: IT_ARIES_CHAR_SHIRT_TEEN 40
  • nItemID: the ID of the item to be put into the character slot. The default value for all slots is 0. One may empty a certain slots by setting its nItemID to 0.

int GetCharacterSlotItemID(int nSlotID)

Get the model ID of a specified character slot.

Return
: the item ID on the given slot. 0 stands for empty. -1 if invalid slot ID
Parameters
  • nSlotID: the ID of the slot to be set for the character. Normally there are 16 slots on the character.

void LoadFromFile(const char *filename)

load all settings of the model to file. Need to call RefreshModel() after loading.

void SaveToFile(const char *filename)

save all settings of the model to file.

void RefreshModel()

update the entire model from its characters settings, such as body parameters and equipments. This will rebuild the composed character texture.

void UseAIModule(const char *sAIType)

use a specified AI object.

Parameters
  • sAIType: valid AI object is: “NPC”|”“|”NULL” “” is the same as “NPC” “NULL” means no AI module.

void AssignAIController(const char *sAICtrlerName, const char *sParam1)

assign a new controller to the current AI object. if there is no AI object, we will create a default one to use. sAICtrlerName = “face”: Face tracking controller: sParam1 = “true”|”false”: “true” to enable face tracking. e.g. Char:AssignAIController(“face”, true);

Parameters
  • sAICtrlerName:valid: AI controller name is: “sequence”|”movie”|”face”|”follow”|”avoid”
  • sParam1: this format of this parameter is dependent on the sAICtrlerName. see below:

sAICtrlerName = “follow”: follow another named biped: sParam1 = “” | “sName” | “sName radius angle” : “” to disable following, or follow a biped called sName.

  • sName: the name of the biped to follow,
  • radius: [optional, default to 2.5f] it is the default radius around the target biped. it will control the biped to try it best to stand on this circle.
  • angle: [optional, default to Pi] it will control the biped to stand beside the target with the target facing shifted by this value. note that +-Pi means behind the biped;0 means in front of the character. e.g. “playername”, “playername 2.5 3.14”, “playername 3.0 0”, “playername 3.0 1.57”, “playername 3.0 -1.57” e.g. Char:AssignAIController(“follow”, “player1”); e.g. Char:AssignAIController(“follow”, “player1 2.5 3.14”);

sAICtrlerName = “movie”: enable a movie controller. sParam1 = “”|”true”|”false”: “” or “true” to enable a movie, or “false” to disable it. e.g. Char:AssignAIController(“movie”, “true”);Char:AssignAIController(“movie”, “false”); use GetMovieController() to get the controller

sAICtrlerName = “sequence”: enable a sequence controller. sParam1 = “”|”true”|”false”: “” or “true” to enable a sequence, or “false” to disable it. e.g. Char:AssignAIController(“sequence”, “true”);Char:AssignAIController(“sequence”, “false”); use GetSeqController() to get the controller

See
: UseAIModule()

bool IsAIControllerEnabled(const char *sAICtrlerName)

whether a certain controller is enabled.

Parameters
  • sAICtrlerName: “sequence”|”movie”|”face”|”follow”|”avoid” see also AssignAIController();

ParaMovieCtrler GetMovieController()

get the movie controller. the movie controller will be created if it does not exist.

ParaSeqCtrler GetSeqController()

get the sequence controller. the sequence controller will be created if it does not exist.

ParaFaceTrackingCtrler GetFaceTrackingController()

get the face tracking controller. the sequence controller will be created if it does not exist.

void CastEffect(int nEffectID)

cast a magic effect by the effect ID.

Parameters
  • nEffectID: effect ID in the effect database if effect id is negative, the effect will be removed from the object.

void CastEffect2(int nEffectID, const char *sTarget)

cast a magic effect by the effect ID.

Parameters
  • nEffectID: effect ID in the effect database if effect id is negative, the effect will be removed from the object.
  • sTarget: target of the effect, if there is any. it can either to the name of the target object, or an attachment ID on the current character. in case it is an attachment ID. It should be in the following format. <d> d is the attachment ID. For customizable characters, some IDs are: 0 ATT_ID_SHIELD, 1 ATT_ID_HAND_RIGHT, 2 ATT_ID_HAND_LEFT, default value 5 ATT_ID_SHOULDER_RIGHT, 6 ATT_ID_SHOULDER_LEFT, 11 ATT_ID_HEAD, e.g. char:CastEffect(1, “NPC0”); fire missile 1 at NPC0. char:CastEffect(2, “<2>”); attach the effect 2 to the current character’s hand.

void AddAttachment(ParaAssetObject ModelAsset, int nAttachmentID)

Parameters
  • ModelAsset: the model to be attached. This can be both ParaX model or static mesh model.
  • nAttachmentID: to which part of the character, the effect model is attached. ATT_ID_SHIELD = 0, ATT_ID_HAND_RIGHT = 1, ATT_ID_HAND_LEFT = 2, ATT_ID_TEXT = 3, ATT_ID_GROUND = 4, ATT_ID_SHOULDER_RIGHT = 5, ATT_ID_SHOULDER_LEFT = 6, ATT_ID_HEAD = 11, ATT_ID_FACE_ADDON = 12, ATT_ID_EAR_LEFT_ADDON = 13, ATT_ID_EAR_RIGHT_ADDON = 14, ATT_ID_BACK_ADDON = 15, ATT_ID_WAIST = 16, ATT_ID_NECK = 17, ATT_ID_BOOTS = 18, ATT_ID_MOUTH = 19, ATT_ID_MOUNT1 = 20,
  • nSlotID: the slot id of the effect. default value is -1. if there is already an effect with the same ID it will be replaced with this new one.
  • scaling: scaling of the texture
  • ReplaceableTexture: replace the texture.

ParaScripting::ParaAttributeObject GetAttachmentAttObj(int nAttachmentID)

get the attachment object’s attribute field.

void RemoveAttachment(int nAttachmentID)

the model to be detached.

See
AddAttachment();
Parameters
  • nAttachmentID: this value is reserved and can be any value.
  • nSlotID: the slot id of the effect. default value is -1. all attachments with the SlotID will be removed.

void Stop()

stop the biped if it is moving.

void MoveTo(double x, double y, double z)

move (using the current style i.e. walk or run) to a position relative to the current position.

void MoveAndTurn(double x, double y, double z, float facing)

move (using the current style i.e. walk or run) to a position relative to the current position and turn.

double GetCartoonFaceComponent(int nComponentID, int SubType)

get the cartoon face associated with this object. CFS_TOTAL_NUM, }; SubType:

  • 0: style: int [0,00]
  • 1: color: 32bits ARGB
  • 2: scale: float in [-1,1]
  • 3: rotation: float in (-3.14,3.14]
  • 4: x: (-128,128]
  • 5: y: (-128,128]
    Note
    : check IsSupportCartoonFace() before using this function
Parameters
  • nComponentID: one of the following value. cartoon face slots on the face of the character enum CartoonFaceSlots { CFS_FACE = 0, CFS_WRINKLE = 1, CFS_EYE = 2, CFS_EYEBROW = 3, CFS_MOUTH = 4, CFS_NOSE = 5, CFS_MARKS = 6,

string GetCartoonFaceComponentCode(int nComponentID, int SubType)

same as GetCartoonFaceComponent, except that the returned value is a string code.

Parameters
  • nComponentID: enum CartoonFaceSlots, in most cases, this is CFS_FACE(0). SubType:
    • 0: style: int [0,00]: code is the string presentation of int.
    • 1: color: 32bits ARGB: code is hex presentation of RGB of the value, such as “ffffff”
    • 2: scale: float in [-1,1]: code is one hex number, where “0” is 0, “9” is 9/9, “a” is -1/7, “f” is -7/7.
    • 3: rotation: float in (-3.14,3.14]: code is at most 2 hex number, where “0” is 0.
    • 4: x: (-128,128]: code is at most 2 hex number, where “0” is 0.
    • 5: y: (-128,128]: code is at most 2 hex number, where “0” is 0. return the code usually hex format, such as “ffffff”

void SetCartoonFaceComponent(int nComponentID, int SubType, double value)

see GetCartoonFaceComponent()

Note
: check IsSupportCartoonFace() before using this function

void SetCartoonFaceComponentCode(int nComponentID, int SubType, const char *color)

see GetCartoonFaceComponentCode()

Note
: check IsSupportCartoonFace() before using this function

bool IsSupportCartoonFace()

check whether the associated cartoon model supports cartoon face.

void SetSkinColorMask(const char *strColor)

the color mask to be applied to cartoon face and ccs base layer. It can be used to fine tune skin color on top of exiting base skin and face textures. Default value is “ffffff”. setting this to a different value will degrade the performance a little.

Parameters
  • strColor: the hex string of RGB, such as “RGB”.

string GetSkinColorMask()

the color mask to be applied to cartoon face and ccs base layer. It can be used to fine tune skin color on top of exiting base skin and face textures. Default value is “ffffff”. setting this to a different value will degrade the performance a little.

Return
the hex string of RGB, such as “fffff”

int GetGender()

get the character gender.

Return
: 0 if male, 1 if female, -1 if error

int GetRaceID()

get the character race ID according to CharRacesDB table

Return
: race ID, -1 if error

class ParaDataProvider
#include <ParaScriptingWorld.h>

Wrapper of internal ParaWorld data provider

Public Functions

bool IsValid()

check if the object is valid

bool InsertPuzzleRecordFromString(const char *strRecord)

Insert the new puzzle record to Puzzle_DB

Return
true if the record is inserted in database
Parameters
  • record: ID of record will be ignored and filled with actual ID if inserted successfully

bool DeletePuzzleRecordByID(int ID)

delete the existing puzzle record from Puzzle_DB

Return
true if the record is deleted in database
Parameters
  • ID: ID of target record

int GetNPCIDByName(const char *name)

get NPC ID by name

Return
id is returned if found in database; otherwise non-positive value(-1) is returned.
Parameters
  • name: name of character

int GetNPCCount()

the total number of NPC in the database. There is no statement cached for this call.

Return

bool DoesAttributeExists(const char *sName)

whether a given attribute exists. This function is usually used internally. One common use of this function is to test if a field exists, so that we know if a object has been saved before or not.

Return
Parameters
  • sName: : name of the attribute field

object GetAttribute(const char *sName, const object &sOut)

get the attribute of the current attribute instance in the current table e.g. suppose db is a ParaDataProvider object. local x = db:GetAttribute(“PlayerX”, 0); local name = db:GetAttribute(“PlayerName”, “no_name”);

Return
the object is returned. Currently it may be a string, boolean or a number.
Parameters
  • sName: : name of the attribute field
  • sOut: : [in|out] default value of the field. Currently it may be a string or a number

bool UpdateAttribute(const char *sName, const object &sIn)

update the attribute of the current attribute instance in the current table insert the attribute if it is not created before.

Return
true if succeed.
Parameters
  • sName: : name of the attribute field
  • sIn: value of the attribute field. Currently it may be a string, boolean or a number.

bool InsertAttribute(const char *sName, const object &sIn)

insert by simple name value pair

Return
true if succeed.
Parameters
  • sName: : name of the attribute field
  • sIn: value of the attribute field. Currently it may be a string, boolean or a number.

bool DeleteAttribute(const char *sName)

delete the attribute of the current attribute instance in the current table

Return
true if succeed.
Parameters
  • sName: : name of the attribute field

bool ExecSQL(const char *sCmd)

run a given sql command, commonly used commands are “BEGIN”, “END”, when we are batch saving attributes.

void SetTableName(const char *sName)

set current attribute table name, the table will be created if not exists.

Parameters
  • sName: table name

const char *GetTableName()

get the current attribute table name

Return
current attribute table name

class ParaFaceTrackingCtrler
#include <ParaScriptingCharacter.h>

ParaFaceTrackingCtrler object: it will allow the biped to always face to a given target or another biped.

Public Functions

bool IsValid()

check if the object is valid

void FaceTarget(float x, float y, float z, float fDuration)

instruct a character to face a target for a certain duration. It will smoothly rotate the character neck to face it

Parameters
  • xyz: which point in world space to face to
  • fDuration: how many seconds the character should keeps facing the target. Set zero or a negative value to cancel facing previous point.

class ParaFileObject
#include <ParaScriptingIO.h>

file object. Always call close() when finished with the file.

Public Functions

bool IsValid()

whether file is valid

void close()

Close the current file.

int SetSegment(int nFromByte, int nByteCount)

by setting the segment, we can inform NPL that we only transmit the file content in the segment to a remote place. it also affects the returned result of the GetBase64String.

Return
: return the number of bytes in the segment. it is usually the same as nByteCount, unless nBytesCount exceeds the file length.
Parameters
  • nFromByte: from which byte
  • nByteCount: number of bytes of the segment. if -1, it is end of file.

const char *GetBase64StringEx(int *pnStrLength = 0)

get base 64 string of the binary data in the current file segment. to change segment, use SetSegment.

Return
pOutString: a static global buffer containing the string. it ends with ‘\0’. it is NULL, if file is invalid.
Parameters
  • pnStrLength: [out] length of the returned string.

void seek(int offset)

always call seek(0) if one opens a old file for overwritten

int getpos()

get current reader or writer cursor position offset in bytes

void SetFilePointer(int lDistanceToMove, int dwMoveMethod)

The SetFilePointer function moves the file pointer of an open file. this function only works when the ParaFile object is an actual windows file, instead of a virtual file. for virtual file, use the seek and seekRelative function.

Parameters
  • lDistanceToMove:
  • dwMoveMethod: 0: FILE_BEGIN The starting point is 0 (zero) or the beginning of the file. 1: FILE_CURRENT The starting point is the current value of the file pointer. 2: FILE_END The starting point is the current end-of-file position.

bool SetEndOfFile()

The SetEndOfFile function moves the end-of-file (EOF) position for the specified file to the current position of the file pointer.This function can be used to truncate or extend a file. If the file is extended, the contents of the file between the old EOF position and the new position are not defined.

Return

const char *readline()

read line as a string. The string is guaranteed to be ended with ‘\0’. if end of file is reached, it will return NULL. which is nil in the script. if a line begins with “–”, it is automatically recognized as a comment line and will be skipped. a blank line will also be skipped.

const char *GetText()

get the content of the file as text. Text encoding is escaped. If you want to get the raw file text with the heading BOM, such as utf8 (EE BB BF), use GetText2(0,-1)

const std::string &GetText2(int fromPos, int nCount)

get the content of the file as text between two positions.

Parameters
  • fromPos: position in bytes.
  • nCount: nCount in bytes. if -1, it defaults to end of file.

const std::string &ReadString(int nCount)

read a binary string of length nCount from current position.

Parameters
  • nCount: nCount in bytes. if -1, it defaults to end of file.

void WriteString(const char *str)

write a string to the current file.

void WriteString2(const char *buffer, int nSize)

write a buffer to the current file.

void write(const char *buffer, int nSize)

write a buffer to the current file.

int WriteBytes(int nSize, const object &input)

write bytes to file; e.g. local nBytes = file:WriteBytes(3, {[1]=255, [2]=0, [3]=128});

Return
: number of bytes written
Parameters
  • nSize: number of bytes to write
  • input: array of integers, each represents a byte

object ReadBytes(int nSize, const object &output)

read bytes from file. e.g. local data={};local nBytes = file:ReadBytes(3, data); data[1], data[2], data[3]

Return
string or a table array
Parameters
  • nSize: number of bytes to read. if negative, it will be total file size
  • output: in/out, it should be an empty table. When the function returns, it will contain an array of integers, each represents a byte if output is nil or “”, the returned value will also be a string(may contain \0) of the content read

void WriteFloat(float value)

float is 32 bits

void WriteWord(int value)

integer is converted 16 bits unsigned word

void WriteInt(int value)

integer is 32 bits

void WriteShort(int value)

integer is 16 bits signed int

void WriteUInt(unsigned int value)

integer is 32 bits unsigned

int GetFileSize()

get the file size in bytes.

class ParaFileSystemWatcher
#include <ParaScriptingIO.h>

file system watcher to monitor file changes in one or several directories .NET also provides a class similar to this one, called FileSystemWatcher.

Public Functions

void AddDirectory(const char *filename)

add a directory to monitor

void RemoveDirectory(const char *filename)

remove a directory from monitor

void AddCallback(const char *sCallbackScript)

the call back script will be invoked with a global msg msg = {type=[0,5], dirname=string, filename=string}, where type can be { null = 0, added = 1, removed = 2, modified = 3, renamed_old_name = 4, renamed_new_name = 5 };

class ParaGlobal
#include <ParaScriptingGlobal.h>

ParaGlobal namespace contains a list of HAPI functions to globally control the engine

Public Static Functions

void ExitApp()

exit the applications.

void Exit(int nReturnCode)

This is same as ExitApp, except that it supports a return code. this is the recommended way of exiting application. this is mainly used for writing test cases. Where a return value of 0 means success, any other value means failure.

void WriteToConsole(const char *strMessage)

write const char* to console, usually for debugging purposes.

void WriteToLogFile(const char *strMessage)

write const char* to log file, usually for debugging purposes.

int GetLogPos()

get the current log file position. it is equivalent to the log file size in bytes. one can later get log text between two Log positions.

const char *GetLog(int fromPos, int nCount)

get log text between two Log positions.

Return
string returned.
Parameters
  • fromPos: position in bytes. if nil, it defaults to 0
  • nCount: count in bytes. if nil, it defaults to end of log file.

ParaScripting::ParaServiceLogger GetLogger(const object &name)

Get a service logger. Please see util/LogService.h for more information.

bool WriteToFile(const char *filename, const char *strMessage)

write const char* to specific file. obsolete

void SetGameStatus(const char *strState)

set the game status

Parameters
  • strState:
    • “disable” disable the game
    • “enable” enable the game
    • “pause” pause the game
    • “resume” resume the game

double GetGameTime()

Return
return the current game time in milliseconds.When game is paused, game time is also paused. this is usually used for cinematic movies

std::string GetDateFormat(const object &sFormat)

get the date in string [thread safe]

Parameters
  • sFormat: can be NULL to use default.e.g. “ddd’,’ MMM dd yy”
    • d Day of month as digits with no leading zero for single-digit days.
    • dd Day of month as digits with leading zero for single-digit days.
    • ddd Day of week as a three-letter abbreviation. The function uses the LOCALE_SABBREVDAYNAME value associated with the specified locale.
    • dddd Day of week as its full name. The function uses the LOCALE_SDAYNAME value associated with the specified locale.
    • M Month as digits with no leading zero for single-digit months.
    • MM Month as digits with leading zero for single-digit months.
    • MMM Month as a three-letter abbreviation. The function uses the LOCALE_SABBREVMONTHNAME value associated with the specified locale.
    • MMMM Month as its full name. The function uses the LOCALE_SMONTHNAME value associated with the specified locale.
    • y Year as last two digits, but with no leading zero for years less than 10.
    • yy Year as last two digits, but with leading zero for years less than 10.
    • yyyy Year represented by full four digits.
    • gg Period/era string. The function uses the CAL_SERASTRING value associated with the specified locale. This element is ignored if the date to be formatted does not have an associated era or period string.

std::string GetTimeFormat(const object &sFormat)

get the time in string [thread safe]

Parameters
  • sFormat: can be NULL to use default. e.g. “hh’:’mm’:’ss tt”
    • h Hours with no leading zero for single-digit hours; 12-hour clock.
    • hh Hours with leading zero for single-digit hours; 12-hour clock.
    • H Hours with no leading zero for single-digit hours; 24-hour clock.
    • HH Hours with leading zero for single-digit hours; 24-hour clock.
    • m Minutes with no leading zero for single-digit minutes.
    • mm Minutes with leading zero for single-digit minutes.
    • s Seconds with no leading zero for single-digit seconds.
    • ss Seconds with leading zero for single-digit seconds.
    • t One character time-marker string, such as A or P.
    • tt Multicharacter time-marker string, such as AM or PM.

DWORD timeGetTime()

The timeGetTime function retrieves the system time, in milliseconds. The system time is the time elapsed since Windows was started. Note that the value returned by the timeGetTime function is a DWORD value. The return value wraps around to 0 every 2^32 milliseconds, which is about 49.71 days. This can cause problems in code that directly uses the timeGetTime return value in computations, particularly where the value is used to control code execution. You should always use the difference between two timeGetTime return values in computations.

double getAccurateTime()

get the elapsed time using high-resolution timing function in seconds. this function is mostly used for profiling on the NPL

double random()

the random seed is set at application start

Return
generate a random number between [0,1]

double GetSysDateTime()

Get the system date and time in seconds. The system time is expressed in Coordinated Universal Time (UTC). Note: there is some trick to make the returned value a valid number in NPL. Only compare time with time returned by the same function. TODO: in the long run, a true unsigned int64 should be returned. [thread safe]

std::string GenerateUniqueID()

generate a unique ID as a string. This is usually a string. [thread safe]

Return

void SaveObject(const char *strObjectName, const object &objObject)

global object dictionary functions: this is a way for different script runtime to share some global information. Currently only value and const char* object can be saved. one can save nil to a object name to delete the object.

Parameters
  • objObject: object to save

object LoadObject(const object &strObjectName)

global object dictionary functions: this is a way for different script runtime to share some global information. Currently only value and const char* object can be saved. return nil, if object is not found

Parameters
  • strObjectName: the object name

void SetGameLoop(const char *scriptName)

reset the game loop script. the game loop script will be activated every 0.5 seconds see SetGameLoopInterval() to change the default interval Please keep the game loop concise. The default game loop is ./script/gameinterface.lua

void SetGameLoopInterval(float fInterval)

set the game loop activation interval. The default value is 0.5 seconds.

bool CreateProcess(const char *lpApplicationName, const char *lpCommandLine, bool bWaitOnReturn)

run an external application. creates a new process and its primary thread. The new process runs the specified executable file in the security context of the calling process.

Remark
: One can also use ParaEngine C++ or .Net API to write application plug-ins for the game engine, which can be loaded like any other script files. e.g. To open a file in an external notepad editor use ParaGlobal.CreateProcess(“c:\\notepad.exe”, “\”c:\notepad.exe” c:\test.txt”, true);
Return
true if opened.
Parameters
  • lpApplicationName:Pointer: to a null-terminated string that specifies the module to execute. The specified module can be a Windows-based application. The string can specify the full path and file name of the module to execute or it can specify a partial name. In the case of a partial name, the function uses the current drive and current directory to complete the specification. The function will not use the search path. If the file name does not contain an extension, .exe is assumed. If the executable module is a 16-bit application, lpApplicationName should be NULL, and the string pointed to by lpCommandLine should specify the executable module as well as its arguments.
  • lpCommandLine:Pointer: to a null-terminated string that specifies the command line to execute.
  • bWaitOnReturn: if false, the function returns immediately; otherwise it will wait for the editor to return. if this is true, the Child Process will have Redirected Input and Output to current log file.

bool ShellExecute(const char *lpOperation, const char *lpFile, const char *lpParameters, const char *lpDirectory, int nShowCmd)

Performs an operation on a specified file. e.g. ParaGlobal.ShellExecute(“open”, “iexplore.exe”, “http://www.paraengine.com”, nil, 1);

Parameters
  • lpOperation:[in]: Pointer to a null-terminated string,
    • “wait” this is a special one that uses ShellExecuteEx to wait on the process to terminate before return
    • “edit” Launches an editor and opens the document for editing. If lpFile is not a document file, the function will fail.
    • “explore” Explores the folder specified by lpFile.
    • “find” Initiates a search starting from the specified directory.
    • “open” Opens the file specified by the lpFile parameter. The file can be an executable file, a document file, or a folder.
    • “print” Prints the document file specified by lpFile. If lpFile is not a document file, the function will fail.
    • NULL For systems prior to Microsoft Windows 2000, the default verb is used if it is valid and available in the registry. If not, the “open” verb is used.
  • lpFile: [in] Pointer to a null-terminated string that specifies the file or object on which to execute the specified verb. To specify a Shell namespace object, pass the fully qualified parse name. Note that not all verbs are supported on all objects. For example, not all document types support the “print” verb.
  • lpParameters[in]: If the lpFile parameter specifies an executable file, lpParameters is a pointer to a null-terminated string that specifies the parameters to be passed to the application. The format of this string is determined by the verb that is to be invoked. If lpFile specifies a document file, lpParameters should be NULL.
  • lpDirectory: [in] Pointer to a null-terminated string that specifies the default directory.
  • nShowCmd: [in] Flags that specify how an application is to be displayed when it is opened. If lpFile specifies a document file, the flag is simply passed to the associated application. It is up to the application to decide how to handle it.
    • #define SW_HIDE 0
    • #define SW_NORMAL 1
    • #define SW_MAXIMIZE 3
    • #define SW_SHOW 5
    • #define SW_MINIMIZE 6
    • #define SW_RESTORE 9

bool OpenFileDialog(const object &inout)

create a open file dialog. This function does not return until the user selects a dialog.

Return
: true if user clicks ok. and the inout.filename contains the result.
Parameters
  • inout: input table:{filter=”All Files (*.*);*.*;”, filterindex, initialdir, flags, } t.filter=”All Files (*.*)\0*.*\0” output : {filename, result=true} t.filename: the full path and file name specified by the user t.result: boolean if user clicks the OK button

bool WriteRegStr(const string &root_key, const string &sSubKey, const string &name, const string &value)

Write a string to the registry. e.g. WriteRegStr(“HKLM”, “Software\My Company\My Software”, “string Value”, “string Name”);

Parameters
  • root_key: must be HKCR or HKEY_CLASSES_ROOT HKLM or HKEY_LOCAL_MACHINE HKCU or HKEY_CURRENT_USER HKU or HKEY_USERS

const char *ReadRegStr(const string &root_key, const string &sSubKey, const string &name)

Read string from the registry. Valid values for root_key are listed under WriteRegStr. NULL will be returned if the string is not present. If the value is present, but is of type REG_DWORD, it will be read and converted to a string.

Parameters
  • root_key: must be HKCR or HKEY_CLASSES_ROOT HKLM or HKEY_LOCAL_MACHINE HKCU or HKEY_CURRENT_USER HKU or HKEY_USERS

bool WriteRegDWORD(const string &root_key, const string &sSubKey, const string &name, DWORD value)

Write a DWORD to the registry. see WriteRegStr() for more info

Parameters
  • root_key: must be HKCR or HKEY_CLASSES_ROOT HKLM or HKEY_LOCAL_MACHINE HKCU or HKEY_CURRENT_USER HKU or HKEY_USERS

DWORD ReadRegDWORD(const string &root_key, const string &sSubKey, const string &name)

Read DWORD from the registry. Valid values for root_key are listed under WriteRegStr. NULL will be returned if the DWORD is not present or type is a string.

Parameters
  • root_key: must be HKCR or HKEY_CLASSES_ROOT HKLM or HKEY_LOCAL_MACHINE HKCU or HKEY_CURRENT_USER HKU or HKEY_USERS

class ParaHTMLBrowser
#include <ParaScriptingHTMLBrowser.h>

a HTML browser control and texture

Public Functions

bool IsValid()

check if the object is valid

const char *GetName()

get the window name.

const char *GetLastNavURL()

the last url when navigateTo() is called. default is “”

void Release()

something like delete this

class ParaIO
#include <ParaScriptingIO.h>

ParaIO class: IO functions ported to the scripting system

Public Static Functions

const char *DecodePath(const char *input)

replace variables in input path and return the result path. see AddPathVariable

Return
the resulting path. Please note that the return value is the input itself if nothing is replaced. otherwise, it is a static string reference containing the result. therefore the result is NOT thread safe.
Parameters
  • input: a path with or without replaceable. make sure you have called ToCanonicalFilePath() to canonicalize the input before calling this function

const char *EncodePath(const char *input)

this does reverse of DecodePath. see AddPathVariable

Parameters
  • input: a path with or without replaceable. make sure you have called ToCanonicalFilePath() to canonicalize the input before calling this function

const char *EncodePath2(const char *input, const char *varNames)

same as EncodePath, except that it will only replace variables who name appears in varNames. varNames is a comma separated list of variable names.

Parameters
  • varNames: a comma separated list of variable names. like “WORLD,USERID”, etc.

bool AddPathVariable(const char *sVarName, const char *sVarValue)

add a new variable to the replaceable pool

Return
: true if succeed. it may return false, if a protected variable with the same name already exist but it not editable via scripting interface.
Parameters
  • sVarName: the variable name without enclosing %%, such as “WORLD”, “USERID”, usually uppercase.
  • sVarValue: the path that the variable expands to. If nil, it will remove the variable.

bool AddSearchPath(const char *sFile)

add a search path to the search path pool. It will internally normalize the path and check for duplicates note: this function shall not be called by an untrusted client, since it will secretly swap files. : shall we support remote http zip file as a valid search path?

bool RemoveSearchPath(const char *sFile)

remove a search path from the search path pool.

std::string GetWritablePath()

get writable path

bool ClearAllSearchPath()

clear all search paths.

unsigned long CRC32(const char *filename)

Get the CRC 32 code of a given file.

Return
: return 0 if not succeed, otherwise the CRC32 code is returned.

void UpdateMirrorFiles(const char *dirName, bool bOverwrite)

this function is equivalent to calling the following functions. LoadLogFromFile(“InstallFiles.txt”); LoadLogFromFile(“temp/filelog.txt”); MirrorFiles(dirName, bOverwrite);

e.g. UpdateMirrorFiles(“_InstallFiles/”, true);

Parameters
  • dirName: such as “_InstallFiles/”
  • bOverwrite: if this is true, existing files will be overridden.

ParaScripting::ParaZipWriter CreateZip(const char *fn, const char *password)

call this to start the creation of a zip file.

int DeleteFile(const char *sFilePattern)

delete a given file. It will reject any system files outside the application directory. after all, this function is of high security level.

Return
: the number of files deleted.
Parameters
  • sFilePattern: such as “*.dds”, “temp.txt”, etc

bool MoveFile(const char *src, const char *dest)

The MoveFile function will move (rename) either a file or a directory (including its children) either in the same directory or across directories.

Return
true if succeeds
Parameters
  • src: specifies the name of an existing file
  • dest: specifies the name of the new file

bool CopyFile(const char *src, const char *dest, bool bOverride)

The CopyFile function copies an existing file to a new file

Return
true if succeeds
Parameters
  • src: specifies the name of an existing file
  • dest: specifies the name of the new file
  • bOverride: [in] If this parameter is false and the new file specified by src already exists, the function fails. If this parameter is true and the new file already exists, the function overwrites the existing file and succeeds.

bool CreateNewFile(const char *filename)

create a new file for writing. it will make all necessary directories in order to create the file.

bool OpenFileWrite(const char *filename)

open a new file for write-only access. If the file does not exist, it will be created. if the file exists, the file pointer is at the end of file.

bool OpenFile(const char *filename)

Open a file for read-only access.

ParaFileObject OpenAssetFile(const char *filename)

This is rather similar to OpenFile() method, except that it will first look in the AssetManifest to see if the file exit. If the file does appear in manifest list, we will download the latest version from the current asset server, if not done before. the download process is SYNCHRONOUS. If the file does not appear in AssetManifest list, this function is equivalent to OpenFile()

Return
: 1 if succeed. 0, if file is not downloaded successfully.
Parameters
  • filename: the asset file key to open. The actual file opened may from the temp/cache/ folder.
  • bDownloadIfNotUpToDate: default to true. if true, we will download the latest version from the current asset server. the download process is synchronous. If false, the function will return 0 immediately, when the caller may consider download the file asynchronously, and then open the file again.

bool DoesAssetFileExist(const char *filename)

check to see whether we have a up to date version of an asset file. if the asset file does not appear in asset manifest list, it will return the result of DoesFileExist() instead.

bool DoesAssetFileExist2(const char *filename, bool bSearchZipFile)

same as DoesAssetFileExist, except that if bSearchZipFile == false, it is equivalent to DoesFileExist().

int SyncAssetFile_Async(const char *filename, const char *sCallBackScript)

similar to SyncFile(), except that this function will return immediately and does not redownload or call AddDownloadCount. And use callback.

Return
: 0 if download has begun, 1 if file is already downloaded, -1 if failed, -2 if input is not an asset file.
Parameters
  • sCallBackScript: the callback script code to be executed when the download is complete. it must begin with ”;”, such as ”;log([[download is complete]]);” the global “msg.res” table contains the error code in case an error is met. msg.res == 0 if succeed, otherwise -1.

int CheckAssetFile(const char *filename)

check to see whether an asset file is already downloaded to local disk. generally return value is larger than 1 if succeed.

Return
: 1 if already downloaded; 0 if asset has not been downloaded; -1 if we are unable to download the asset file after trying serveral times; -3 if asset is being downloaded but is not completed; -4 if input file is not an asset file.

ParaFileObject open(const char *filename, const char *mode)

Open or create a file e.g. ParaIO.open(“temp/test.txt”, “w”);

Return
file object is returned.
Parameters
  • filename: the file name to open. if it is “<memory>” and mode is “w”. it is a memory buffer.
  • mode: : access mode
    • “r” Opens for reading. If the file does not exist or cannot be found, the call fails.
    • “w” Opens an empty file for writing. If the given file exists, its contents are destroyed.If not, file will be created.
    • “a” append to the end of an existing file. if file does not exist, a new one is created.

ParaScripting::ParaFileObject openimage(const char *filename, const char *mode)

open an image file. The r,g,b can then be retrieved as bytes arrays using ReadBytes() function.

Parameters
  • filename: such as BMP, DDS, JPG, etc. It must be a square image. The size of the image can thus be calculated by file size.
  • mode: : access mode
    • “r8g8b8”: each pixel is a three bytes of R,G,B
    • “a8r8g8b8”: each pixel is a four bytes of A,R,G,B
    • “float32”: each pixel is a four bytes of float. [Not supported yet]

bool CreateDirectory(const char *filename)

make directory

Return
: true if the directory is made or already exists
Parameters
  • filename: director path. file portion will be automatically striped off. So it is ok to pass in file name, instead of directory name.

void CloseFile()

Close the current file.

void WriteString(const char *str)

write a string to the current file.

const char *readline()

read line as a string. The string is guaranteed to be ended with ‘\0’. if end of file is reached, it will return NULL. which is nil in the script. if a line begins with “–”, it is automatically recognized as a comment line and will be skipped. a blank line will also be skipped.

void write(const char *buffer, int nSize)

write a buffer to the current file.

bool DoesFileExist(const char *filename, bool bSearchZipFiles)

Check whether a given file exists on disk.

Parameters
  • filename: file name to check
  • bSearchZipFiles: if false, not disk file is searched. If true, both the disk file and zip file will be searched. currently bSearchZipFiles can only be false. Because it is not efficient to check existence of ZIPPED files. Use OpenFile() and check for return value instead.

bool DoesFileExist_(const char *filename)

see DoesFileExist(). This version is same as DoesFileExist(filename, false);

bool BackupFile(const char *filename)

backup a specified file, if the file exists. A new file with an extension ”.bak” appended to the end of the original file will be created, whose content is identical to the original file.

Return
: return true if the file is backed up. return false, if the file does not exist or some error occurs during backup.
Parameters
  • filename: file name to back up

ParaSearchResult SearchFiles(const char *sRootPath, const char *sFilePattern, const char *sZipArchive, int nSubLevel, int nMaxFilesNum, int nFrom)

search files at once.

See
CSearchResult the current version of this function can support only one query at a time. The search result is invalid if called intermitantly
Return
: one should manually release the search result.
Parameters
  • sRootPath: the root path. for example: “”, “xmodel/”,”xmodel/models/”. Other format is not acceptable
  • sFilePattern: file pattern, e.g. “*.x” (all files with x extension), “*” (any files), “*.”(directories only) if sZipArchive is non-empty, sFilePattern support both regular expression and wild card search. it performs wild cards search by default, where “/\\” matches to directory. “* “matches to anything except “/\\.”, and ”.” matches to ”.” itself. e.g.. “*.*”, “*.”, “worlds/ *.abc”, “*abc/ *.jpg”, etc it sFilePattern begins with ”:”, things after ”:” is treated like a regular expression. It has the same syntax with the perl regular expression and uses full match. e.g.. ”:.*\\.jpg”, etc.
  • sZipArchive: it can be “” or a zip archive file name. . if it is not, only that archive files are saved.
    • “”: only disk files are searched
    • “*.zip”: currently opened zip files are searched
    • “*.*”: search disk file followed by all zip files.
  • nSubLevel: how many sub folders of sRootPath to look into. default value is 0, which only searches the sRootPath folder.
  • nMaxFilesNum: one can limit the total number of files in the search result. Default value is 50. the search will stop at this value even there are more matching files.
  • nFrom: only contains results from nFrom to (nFrom+nMaxFilesNum)

string GetCurDirectory(DWORD dwDirectoryType)

get the current directory of the application. it allows querying a number of standard directories. please note that all directory are returned as absolute path with slash “/” between two level of directories. and that it always ends with “\”. e.g. “c:/lxzsrc/paraengineSDK/” or “c:/lxzsrc/paraengineSDK/script/”

Return
: the directory is returned.
Parameters
  • dwDirectoryType: it can be one of the PARAENGINE_DIRECTORY enumeration type enum PARAENGINE_DIRECTORY{ APP_ROOT_DIR=0, APP_SCRIPT_DIR=1, APP_ARCHIVE_DIR=2, // xmodels APP_MODEL_DIR=3, APP_SHADER_DIR=4, APP_DATABASE_DIR=5, APP_TEMP_DIR=6, APP_USER_DIR=7, APP_BACKUP_DIR=8, APP_SCREENSHOT_DIR=9, APP_PLUGIN_DIR=10, };

const char *GetCurDirectory_(DWORD dwDirectoryType)

this should never be called from the scripting interface. it is only for API exportation. it uses a static string for the output. so it is not thread-safe.

string GetParentDirectoryFromPath(const char *sfilename, int nParentCounts)

trim the sFile by nParentCounts number of parent directories.

Return
: return “” if the input directory does not have that many parent directories. e.g. “C:/abc/” = GetDirectoryFromPath(“C:/abc/aaa”,0); “C:/” = GetDirectoryFromPath(“C:/abc/”,1);
Parameters
  • nParentCounts: number of parent directory to remove

const char *GetParentDirectoryFromPath_(const char *sfilename, int nParentCounts)

this should never be called from the scripting interface. it is only for API exportation. it uses a static string for the output. so it is not thread-safe.

string AutoFindParaEngineRootPath(const char *sFile)

This will find the root path from a given directory path using the following rule: find a file called “ParaEngine.sig” in the parent directories of sFile, from near to far. e.g. if sFile is “c:/a/b/c/xxx.x”, then it will search for “c:/a/b/c/”,”c:/a/b/”,”c:/a/” and “c:/”. the function will return the first parent directory that contains the file, otherwise “” is returned.

const char *AutoFindParaEngineRootPath_(const char *sFile)

this should never be called from the scripting interface. it is only for API exportation. it uses a static string for the output. so it is not thread-safe.

string ChangeFileExtension(const char *sFile, const string &sExt)

change the file extension.

Return
: return the file with the changed extension. the input file does not contain a valid file extension, the returned string will be identical to the input file.
Parameters
  • sFile: the file whose extension to change.
  • sExt: the file extension to change to. such as “dds”,”x”

const char *ChangeFileExtension_(const char *sFile, const string &sExt)

this should never be called from the scripting interface. it is only for API exportation. it uses a static string for the output. so it is not thread-safe.

string GetFileExtension(const char *sFile)

get the file extension. this function may return “” if no file extension is found

const char *GetFileExtension_(const char *sFile)

this should never be called from the scripting interface. it is only for API exportation. it uses a static string for the output. so it is not thread-safe.

string GetRelativePath(const char *sAbsolutePath, const char *sRootPath)

Get the relative file path by stripping the root path from the beginning. please note that all paths should uses slash “/”, instead of backslash “\”, in the path name.letter case is ignored

Return
: the relative path is returned. If the absolute path does not math the root path, the absolute path is returned unchanged. the relative path does not begin with “/” e.g. “a/b.x” = GetRelativePath(“c:/lxzsrc/a/b.x”, “c:/lxzsrc/”); “c:/lxzsrc/a/b.x” = GetRelativePath(“c:/lxzsrc/a/b.x”, “c:/srclxz/”); // not match
Parameters
  • sAbsolutePath: the absolute path from which to obtain the relative path.
  • sRootPath: the parent root path, which will be removed from the absolute path. It should end with “/”

const char *GetRelativePath_(const char *sAbsolutePath, const char *sRootPath)

this should never be called from the scripting interface. it is only for API exportation. it uses a static string for the output. so it is not thread-safe.

string GetAbsolutePath(const char *sRelativePath, const char *sRootPath)

Get the absolute file path by appending the root path before the relative path. please note that all paths should uses slash “/”, instead of backslash “\”, in the path name. letter case is ignored

Return
: the relative path is returned. If the absolute path does not math the root path, the absolute path is returned unchanged. e.g. “c:/lxzsrc/a/b.x” = GetAbsolutePath(“a/b.x”, “c:/lxzsrc/”);
Parameters
  • sRelativePath: the absolute path from which to obtain the relative path. It should not begin with “/”
  • sRootPath: the parent root path, which will be removed from the absolute path. It should end with “/”

const char *GetAbsolutePath_(const char *sRelativePath, const char *sRootPath)

this should never be called from the scripting interface. it is only for API exportation. it uses a static string for the output. so it is not thread-safe.

string GetFileName(const char *sFilePath)

get only the file name from the file path. “a.x” = GetFileName(“c:/lxzsrc/a.x”);

const char *GetFileName_(const char *sFilePath)

this should never be called from the scripting interface. it is only for API exportation. it uses a static string for the output. so it is not thread-safe.

int GetFileSize(const char *sFilePath)

The GetFileSize function retrieves the size of the specified file. The file size that can be reported by this function is limited to a DWORD value

Return
: size of the file. If the file does not exist or the file size is 0, the return value is 0.
Note
: only disk file is searched.files inside zip file are ignored.

bool GetFileInfo(const char *sFilePath, const object &inout)

get file info

Parameters
  • inout: {modification, attr, access, create, size, mode=”file|directoy|fileinzip|”, fullpath=string}

string ToCanonicalFilePath(const char *sfilename, bool bBackSlash)

convert a file name to canonical file path

Return
: the canonical file path name returned.
Parameters
  • sfilename: it is assumed that strlen(filename) <= MAX_PATH
  • bBackSlash: if true, the file will use ‘\’; otherwise use ‘/’. ‘\’ is win32 compatible. ‘/’ is more user friendly.

const char *ToCanonicalFilePath__(const char *sfilename, bool bBackSlash)

this should never be called from the scripting interface. it is only for API exportation. it uses a static string for the output. so it is not thread-safe.

void SetDiskFilePriority(int nPriority)

set the disk file priority. it affects whether the disk will be searched first or the one in the archive files. default disk file will be searched first.

Parameters
  • nPriority: 0 is the same priority as the disk file. so 0 or above will cause the disk file to be searched before archive files. below 0, such as -1 will cause the archive files go first.

int GetDiskFilePriority()

set the disk file priority. it affects whether the disk will be searched first or the one in the archive files. default disk file will be searched first.

Return
: 0 is the same priority as the disk file. so 0 or above will cause the disk file to be searched before archive files. below 0, such as -1 will cause the archive files go first.

ParaScripting::ParaFileSystemWatcher GetFileSystemWatcher(const char *filename)

create and get a file system watcher object. always use local to retrieve the object to ensure that the object is properly released when out of scope.

void DeleteFileSystemWatcher(const char *name)

delete a watcher, it will no longer receive callbacks. note that if someone else still keeps a pointer to the directory watcher, it will not be deleted.

class ParaMiniSceneGraph
#include <ParaScriptingScene.h>

ParaMiniSceneGraph class:

Public Functions

const char *GetName()

get name

void SetName(const char *sName)

set the object name. this function can be used to rename this object

bool IsValid() const

check if the object is valid

ParaAttributeObject GetAttributeObject()

get the attribute object associated with the global scene.

ParaScripting::ParaAttributeObject GetAttributeObject1(const char *name)

get the attribute object associated with the global scene.

Parameters
  • name: “” for global scene, “sky” for sky, “camera” for camera, “sun” for sun.

void GetAttributeObject_(ParaAttributeObject &output)

used for API exportation.

ParaScripting::ParaAttributeObject GetAttributeObjectCamera()

get the attribute object associated with the current camera object.

bool CreateSkyBox(const char *strObjectName, const char *strMeshAssetName, float fScaleX, float fScaleY, float fScaleZ, float fHeightOffset)

create a sky box and add it to the current list. sky box with the same name will not be recreated,but will be selected as the current sky box. It may be a sky box/dome/plane or whatever. The associated mesh will be scaled by the specified amount along x,y,z axis and then translate up or down along the y axis. in many cases, the mesh data in the mesh asset is of unit size.

Parameters
  • strObjectName: sky name
  • strMeshAssetName: mesh asset name. this is not the file name.
  • fScaleX: the static mesh local transform scale along the x axis
  • fScaleY: the static mesh local transform scale along the y axis
  • fScaleZ: the static mesh local transform scale along the z axis
  • fHeightOffset: the translation along the y axis.

void DeleteSkyBox(const char *strObjectName)

delete a name sky box.

Parameters
  • strObjectName: if this is “”, all sky boxes will be deleted.

void EnableLighting(bool bEnable)

Enable both global and local lighting. Turn off lighting will greatly improve performance, such as on slower computers

void SetTimeOfDaySTD(float time)

set standard time. see SetTimeOfDay()

Parameters
  • time: always in the range [-1,1], 0 means at noon, -1 is morning. 1 is night.

float GetTimeOfDaySTD()

get standard time. see GetTimeOfDay()

Return
: always in the range [-1,1], 0 means at noon, -1 is morning. 1 is night.

void SetFog(bool bRenderFog, const char *strFogColor, float fFogStart, float fFogEnd, float fFogDensity)

set the global fog effect

Parameters
  • bRenderFog: 1 to enable fog.
  • strFogColor: a string of RGB value in the format “%f %f %f”, such as “1.0 1.0 1.0”, value must be in the range [0, 1.0].
  • fFogDensity: between (0,1)
  • fFogStart: unit in meters.
  • fFogEnd: unit in meters.

bool IsVisible()

invisible object will not be drawn. e.g. one can turn off the visibility of physics object.

void SetVisible(bool bVisible)

set the visibility of this object. The visibility will recursively affect all its child objects.

void EnableCamera(bool bEnable)

enable or disable a given camera

bool IsCameraEnabled()

whether camera is enabled. it is disabled by default. it is much faster to disable camera, because it will use the main scene’s render pipeline and effects. Otherwise it will be rendered after the main scene is rendered, since the camera is different. TODO: currently mini scene graph is only rendered when its camera is disabled. local camera is not supported at the moment

ParaScripting::ParaObject GetObject(const char *name)

update the camera parameter by providing the lookat and eye position get the camera parameter of the lookat and eye position in scripting interface all inputs are outputs. get object by name, if there are multiple objects with the same name, the last added one is inserted.

Note
: This function will traverse the scene to search the object. So there might be some performance penalty.
Parameters
  • name:

ParaObject GetObject3(float x, float y, float z)

get the first object that matches the position. EPSILON is 0.01f

ParaObject GetObject4(float x, float y, float z, float fEpsilon)

get the first object that matches the position within fEpsilon, which is usually 0.01f

int RemoveObject(const char *name)

remove an object from this scene graph but do not destroy it. this function can be used to move a node from one scene graph to another

int RemoveObject_(const ParaObject &pObj)

remove an object from this scene graph but do not destroy it. this function can be used to move a node from one scene graph to another

void AddChild(const ParaObject obj)

attach the object as its child object.

Parameters
  • obj: the child object to attach

int DestroyObject(const char *name)

destroy all objects with the given name. the current version will only destroy the first met child with the given name.

Return
the number of objects deleted.

int DestroyObject_(const ParaObject &pObj)

delete an object from this scene graph but do not destroy it.This function will search the scene recursively this function can be used to move a node from one scene graph to another Note: this is like calling RemoveObject(pObj) and then delete the object.

Parameters
  • pObj: object to delete.

void DestroyChildren()

destroy all children of this mini-scenegraph. but still preserving other settings like camera and render target.

void Reset()

clear the entire scene graph

void SetActor(const ParaObject pActor)

set the actor: The camera always focuses on actor, so this actor can be used to control the current camera position.

Parameters
  • pActor: it must be a valid object.

ParaScripting::ParaObject GetActor()

get the current actor

ParaScripting::ParaAssetObject GetTexture()

the canvas texture, which can be used as any other ordinary texture on 3D or 2D object.

Return

void CameraZoom(float fAmount)

Zoom the camera

Parameters
  • fAmount:

void CameraZoomSphere(float center_x, float center_y, float center_z, float raduis)

reset the camera parameters to view the entire sphere at best (default) distance

Parameters
  • center_x: sphere center x
  • center_y: sphere center y
  • center_z: sphere center z
  • raduis: sphere raduis

void CameraRotate(float dx, float dy, float dz)

rotate the camera round the object on canvas

Parameters
  • dx:
  • dy: relative amount in radian.
  • dz:

void CameraPan(float dx, float dy)

pan the camera

Parameters
  • dx: relative amount in pixels
  • dy: relative amount in pixels

void CameraSetLookAtPos(float x, float y, float z)

set the camera look at position

void CameraSetEyePosByAngle(float fRotY, float fLiftupAngle, float fCameraObjectDist)

set the camera eye position

Parameters
  • fRotY: rotation of the camera around the Y axis, in the world coordinate.
  • fLiftupAngle: lift up angle of the camera.
  • fCameraObjectDist: the distance from the camera eye to the object being followed.

void Draw(float fDeltaTime)

draw the content of the scene graph to the current render target. If EnableActiveRendering is enabled, this function will be called each render frame after the main scene graph. however, if EnableActiveRendering is disabled, one can call this function to render a single frame to the render target on demand.

void SaveToFile(const char *sFileName, int nImageSize = 0)

save to file.

Parameters
  • sFileName: a texture file path to save the file to. we support ”.dds”, ”.jpg”, ”.png” files. If the file extension is not recognized, ”.png” file is used.
  • nImageSize: if this is zero, the original size is used. If it is dds, all mip map levels are saved.

void SetRenderTargetSize(int nWidth, int nHeight)

set the canvas size in pixels

Parameters
  • nWidth: default to 512
  • nHeight: default to 512

void SetBackGroundColor(const char *rgba)

set the color of the scene ground when it is not enabled.When scene is enabled, the background color is always the fog color.

Parameters
  • rgba: it can contain alpha channel, such as “255 255 255 128”. If no alpha is specified like “255 255 255”, alpha will be 1.0

void SetMaskTexture(ParaAssetObject pTexture)

this is an optional 2D mask, which is drawn over the entire canvas after scene is rendered in to it.

Parameters
  • pTexture:

void EnableActiveRendering(bool bEnable)

if true, contents will be drawn to the current render target each frame. Default value is false. where the user can call DrawToTexture() on demand.

bool IsActiveRenderingEnabled()

if true, contents will be drawn to the current render target each frame. Default value is false. where the user can call DrawToTexture() on demand.

ParaScripting::ParaObject MousePick(float x, float y, float fMaxDistance, const char *sFilterFunc)

Pick scene object at the current mouse cursor position. pick the smallest intersected object which is un-occluded by any objects. Object A is considered occluded by object B only if (1) both A and B intersect with the hit ray. (2) both A and B do not intersect with each other. (3) B is in front of A, with regard to the ray origin.

this function will ray-pick any loaded scene object(biped & mesh, but excluding the terrain) using their oriented bounding box. a filter function may be provided to further filter selected object. this function will transform all objects to near-camera coordinate system. This will remove some floating point inaccuracy near the camera position.Hence this function is most suitable for testing object near the camera eye position. This function does not rely on the physics engine to perform ray-picking.

Return
:the scene object. if the object is invalid, it means that the ray has hit nothing.
Parameters
  • x: screen position relative to the render target.
  • y: screen position relative to the render target. fMaxDistance: the longest distance from the ray origin to check for collision. If the value is 0 or negative, the view culling radius is used as the fMaxDistance.
  • sFnctFilter: it can be any of the following string or a number string “mesh”: mesh any mesh object in the scene. Usually for selection during scene editing. “cmesh”: mesh object that is clickable (associated with scripts). Usually for game playing. “notplayer”: any object in the scene except for the current player. Usually for selection during scene editing. “”: any object in the scene except. Usually for selection during scene editing. “light”: only pick light objects “biped”: any character objects :local or global. “anyobject”: any objects, including mesh and characters. but not including helper objects, such as light. “global”: all global objects, such as global character and mesh. This is usually for game mode. “point”: the returned object is invalid if there no collision with any physics faces. otherwise, one can use GetPosition function of the returned object to retrieve the intersection point. “terrain”: pick a point on the global terrain only. “walkpoint”: pick a point on the global terrain or any physical object with camera obstruction attribute set to true. “actionmesh”: mesh with action script. number: if it is a number, it is treated as a 32 bitwise DWORD filter code. see SetPickingFilter() for more example.

void ShowHeadOnDisplay(bool bShow)

show or hide all scene’s objects’ head on display

bool IsHeadOnDisplayShown()

whether all scene’s objects’ head on display

class ParaMisc
#include <ParaScriptingMisc.h>

Contains miscellaneous functions

Public Static Functions

int GetUnicodeCharNum(const char *str)

get the number of characters in str. Str is assumed to be in ANSI code page. it is converted to Unicode and return the character count.

std::string UniSubString(const char *str, int nFrom, int nTo)

same as LUA string.sub(), except that the index is character. get a sub string of a ANSI Code page string. However, the index are unicode characters.

Parameters
  • str: the string to use
  • nFrom: character index beginning from 1.

const char *SimpleEncode(const char *source)

encode a string using really simple algorithm. it just makes the source ineligible. It is still not immune to crackers. str = SimpleDecode(SimpleEncode(str))

Return
: it may return NULL if input invalid

const char *SimpleDecode(const char *source)

decode a string using really simple algorithm. str = SimpleDecode(SimpleEncode(str))

Return
: it may return NULL if input invalid

string md5(const char *source)

convert the md5 of the input source string.

long RandomLong(const object &seedTable)

Generating [-MAX, MAX] long integer

Parameters
  • seedTable: nil or a table containing {_seed=integer} when the function returned the seedTable._seed will be modified.

double RandomDouble(const object &seedTable)

generating [0,1] double value

const char *EncodingConvert(const object &srcEncoding, const object &dstEncoding, const object &bytes)

Converts an entire byte array from one encoding to another.

Parameters
  • srcEncoding: any encoding name. If nil or “”, it is the default coding in NPL. see Encoding.GetEncoding(). Below are some commonly used field | Code Page | Name | | 950 | big5 | | 936 | gb2312 | | 65001 | utf-8 | | 65005 | utf-32 | There is one special code name called “HTML”, which contains HTML special characters in ascii code page. This is usually true for most “iso8859-15” encoding in western worlds. It just writes the unicode number+XXXX in ascii character “&#XXXX;” where & is optional.
  • dstEncoding: save as above. If nil or “”, it will be converted to default coding in NPL. : the source bytes. e.g. The most common use of this function is to create HTML special character to NPL string, like below local text = ParaMisc.EncodingConvert(“HTML”, “”, “Chinese characters: &#24320;&#21457;”) log(text);

bool CopyTextToClipboard(const char *text)

copy text to clipboard. Input is ANSI code page

const char *GetTextFromClipboard()

get text from clipboard. text is converted to ANSI code page when returned.

class ParaMovie
#include <ParaScriptingMovie.h>

movie making and screen capture functions

Public Static Functions

ParaScripting::ParaAttributeObject GetAttributeObject()

get the attribute object associated with an object.

void SetMovieScreenSize(int nWidth, int nHeight)

set the movie screen size in pixel.

Parameters
  • nWidth: in pixels, must be multiple of 4.
  • nHeight: in pixels, must be multiple of 4.

void SetCaptureGUI(bool bGUI)

set whether GUI is captured.

bool CaptureGUI()

return true if GUI is also captured.

void SetRecordingFPS(int nFPS)

set the recording FPS, the default is 20 FPS. Some may prefer 30FPS.

int GetRecordingFPS()

Get the recording FPS, the default is 20 FPS. Some may prefer 30FPS.

void SetStereoCaptureMode(int nMode)

set the stereo capture mode. This is used to generate video files that can be viewed by 3d eye glasses and stereo video player.

  • 0 for disable stereo capture(default);
  • 1 for line interlaced stereo.
  • 2 for left right stereo;
  • 3 for above below stereo;
  • 4 for frame interlaved mode, where the odd frame is the left eye and even frame is the right image;

int GetStereoCaptureMode()

Get the stereo capture mode. This is used to generate video files that can be viewed by 3d eye glasses and stereo video player.

  • 0 for disable stereo capture(default);
  • 1 for iPod mode, where the odd frame is the left eye and even frame is the right image;
  • 2 for left right stereo;
  • 3 for above below stereo;
  • 4 for interlaced stereo.

void SetStereoEyeSeparation(float fDist)

the distance in meters between the left and right eye when generating the stereo image. some common values are in range [0.03, 0.1]. This is also related to the rendering unit that we used in games. since ParaEngine games usually use meter as its rendering unit, the value is such near the real eye separation distance.

float GetStereoEyeSeparation()

the distance in meters between the left and right eye when generating the stereo image. some common values are in range [0.03, 0.1]. This is also related to the rendering unit that we used in games. since ParaEngine games usually use meter as its rendering unit, the value is such near the real eye separation distance.

bool BeginCapture(string sFileName)

starting capturing a screen movie

Parameters
  • sFileName: the movie file name, which can be “”. If it is “”, a default name is used.

bool EndCapture()

end capturing a screen movie and save movie to file.

void PauseCapture()

pause the capturing.

void ResumeCapture()

resume capturing

bool IsInCaptureSession()

whether we are doing screen capture. I.e. true between BeginCapture() and EndCapture() However, it may be in the recording or paused state.

bool IsRecording()

whether it is recording.

bool FrameCapture()

capture a given frame

void GetMovieScreenSize(int *nWidth, int *nHeight)

get movie screen size. In script. Use like this : local x,y = ParaMovie.GetMovieScreenSize();

string GetMovieFileName()

get the movie file name

void SelectCodecOptions()

display a dialog which allows the user to set the codec to be used.

void SetEncodeMethod(int eType)

set the code

Parameters
  • eType: 0 for XVID; 1 for WMV; -1 for user select codec.

int GetEncodeMethod()

See
SetEncodeMethod()

bool TakeScreenShot(const char *filename)

we will automatically take screen shot according to the file extensions, supported file extensions are “jpg”,”dds”,”bmp”,”tga”,

Note
: “jpg” has small file size; where “bmp” and “tga” is lossless.
Parameters
  • filename: this is the file name.If this is NULL or “”, it will be automatically named as jpg file under the “screen shots” directory.

bool TakeScreenShot3(const char *filename, int width, int height)

render the current scene to texture, UI are disabled by default. Aspect ratio are changed according to width/height. supported file extensions are “jpg”,”dds”,”bmp”,”tga”,

Note
: “jpg” has small file size; where “bmp” and “tga” is lossless.
Parameters
  • filename: this is the file name.If this is NULL or “”, it will be automatically named as jpg file under the “screen shots” directory.
  • width;: in pixel, if 0 it will be the screen size
  • height;: in pixel, if 0 it will be the screen size

bool ResizeImage(const string &filename, int width, int height, const char *destFilename)

resize the given image. It can also be used to change the file format

Parameters
  • filename: source file name
  • width;: in pixel
  • height;: in pixel
  • destFilename: destination file name. If nil or “”, it will be the same as input. It can also be used to change the file format

void GetImageInfo(const string &filename, int *width, int *height, int *nFileSize)

get the given image info: i.e. size e.g. local width, height, filesize = ParaMovie.GetImageInfo(“abc.jpg”)

Parameters
  • width;: out in pixel
  • height;: out in pixel
  • nFileSize: out in size in bytes

class ParaMovieCtrler
#include <ParaScriptingCharacter.h>

ParaMovieCtrler object: it is used to control time based movie of character object.

Public Functions

bool IsValid()

check if the object is valid

string GetTime(const char *sFormat)

get the local time of a module of the character

Parameters
  • sFormat: the format of the time in the returning string “”: in seconds Formated: The format argument consists of one or more codes; as in printf, the formatting codes are preceded by a percent sign (%). Characters that do not begin with % are copied unchanged. H : Hour in 24-hour format (00 C 23) M : Minute as decimal number (00 C 59) S : Second as decimal number (00 C 59) e.g.: GetTime(“movie”, “time elapsed: %H:%M:%S”);

void SetTime(float fTime)

set the current time of the movie

Parameters
  • fTime: in seconds. 0 is the beginning of the movie

void Suspend()

suspend the movie

void Resume()

resume the movie

void Play()

play the movie

void Record()

record the movie from its current position. all movies behind will be erased.

void RecordNewDialog(const char *sDialog)

add a new dialog record to the current time. All trailing dialog will be removed.

bool RecordNewAction(const char *sActionName)

add a new action record to the current time. All trailing dialog will be removed.

bool RecordNewAction_(const char *sActionName, float fTime)

add a new action record to the current time. All trailing dialog will be removed.

void RecordNewEffect(int effectID, const char *sTarget)

add a new effect record to the current time. All trailing dialog will be removed.

void GetOffsetPosition(float *x, float *y, float *z)

get the offset position of the movie. All movie’s position key are relative to it. if there is no position key, 0,0,0 is returned e.g. x,y,z = movieCtrler:GetOffsetPosition();

void SetOffsetPosition(float x, float y, float z)

set the offset position of the movie. All movie’s position key are relative to it.

void SaveMovie(const char *filename)

save recorded movie to file.

Parameters
  • filename:file: path to save the movie

void LoadMovie(const char *filename)

load a recorded movie from file.

Parameters
  • filename:file: path to load the movie

class ParaNetwork
#include <ParaScriptingNetwork.h>

API wrapper for NPL Network Layer functions

Public Static Functions

void EnableNetwork(bool bEnable, const char *CenterName, const char *password)

Enable the network, by default the network layer is disabled. calling this function multiple time with different CenterName will restart the network layer with a different center name.

Return
true if succeeded.
Parameters
  • bEnable: true to enable, false to disable.If this is false, the CenterName and Password are ignored.
  • CenterName: the local nerve center name. it is also the user name which local receptor will use in the credentials to login in other NPL runtime.
  • Password:

bool IsNetworkLayerRunning()

whether network layer is running or not.

Return

void SetNerveCenterAddress(const char *pAddress)

set the IP and port for the nerve center: call this function before you enable the network (EnableNetwork) for it to take effect.

Parameters
  • pAddress: such as “127.0.0.1:60001”, or ”:60001” (if you want to use any available IP on the computer)

void SetNerveReceptorAddress(const char *pAddress)

set the IP and port for the nerve receptor: call this function before you enable the network (EnableNetwork) for it to take effect.

Parameters
  • pAddress: such as “127.0.0.1:60000”, or ”:60000” (if you want to use any available IP on the computer)

class ParaNPLRuntimeState
#include <ParaScriptingNPL.h>

A runtime state contains the scripting runtime stack and can be run in a single thread.

An NPL runtime state is message driven, however we also support timer and several other event callbacks. Normally we only use this class to start a new runtime, or get statistics about a runtime

Public Functions

bool IsValid()

if this is a valid state.

const char *GetName() const

return the name of this runtime state. if “”, it is considered an anonymous name

int Start()

start this runtime state in a worker thread

Return
the number of threads that are currently working on the runtime state. normally this is 1. only dll runtime state may have more than one worker thread.

bool Stop()

Stop the worker thread. this will stop processing messages in the thread.

void Reset()

it is like starting a fresh new runtime state. All memory, tables, timers, pending messages are removed. this function only takes effect on the next message loop. So there can be other clean up code following this function.

Parameters
  • onResetScode: the code to be executed immediately after runtime state is reset. default to NULL.

luabind::object GetStats(const object &inout)

TODO: get statistics about this runtime environment.

int GetCurrentQueueSize()

Get the current number of messages in the input message queue. Sometimes, a monitor or dispatcher logics may need to know the queue size of all NPL runtime states. and a dispatcher will usually need to add new messages to the NPL state with smallest queue size. This function will lock the message queue to retrieve the queue size, so do not call it very often, but use a timer to query it on some interval. [thread safe]

int GetProcessedMsgCount()

the total number of message processed by this runtime state since start. If this number does not increase, perhaps the processing is blocking somewhere, and we should take actions. [Not thread safe] in most cases, it will return correct result even in multi-threaded environment, but since we do not use lock, unexpected result may return. This function is usually used for stat printing and monitoring.

int GetMsgQueueSize()

get the message queue size. default to 500. For busy server side, we can set this to something like 5000 [thread safe]

void SetMsgQueueSize(int nSize = 500)

set the message queue size. default to 500. For busy server side, we can set this to something like 5000 [thread safe]

void WaitForMessage()

simply wait for the next message to arrive.

void WaitForMessage2(int nMessageCount)

Parameters
  • nMessageCount: if not negative, this function will immediately return when the message queue size is bigger than this value.

luabind::object PeekMessage(int nIndex, const object &inout)

Return
: msg table {filename, code, msg} if exist, or nil.
Parameters
  • inout: this should be a table {filename=true, code=true, msg=true}, specify which part of the message to retrieve in return value. {filename=true} will only retrieve the filename, because it is faster if code is big.

luabind::object PopMessageAt(int nIndex, const object &inout)

pop message at given index. usually we need to call peek() first.

Return
: msg table {filename, code, msg, result} if exist, or filename will be false. result is only available if process is true
Parameters
  • inout: this should be a table {filename=true, code=true, process=true}, specify which part of the message to retrieve in return value. {filename=true} will only retrieve the filename, because it is faster if code is big. if inout.process == true, we will pop and process the message via standard activation. if inout.process == false, we will pop without processing the message, in which case the caller may need to process it manually

class ParaObject
#include <ParaScriptingScene.h>

ParaObject class: it is used to control game scene objects from scripts.

Class Properties

Public Functions

const char *GetType()

get the Runtime class information of the object.

int GetMyType() const

get paraengine defined object type name. TODO: This function is not implemented

int GetID()

the ID of the object. The ID of the object is only generated when the first time this function is called. One can then easily get the object, by calling ParaScene.GetObject(nID). When an object is released, its ID is not longer used. Please note that we can ParaScene.GetObject(nID) even if the object is never attached before. Please note that the ID is neither unique outside the world, nor persistent in the same world.

Return
: return 0 if object is invalid.

bool IsValid() const

check if the object is valid

bool IsAttached() const

whether the object has been attached to the scene.

ParaAssetObject GetPrimaryAsset()

get the main asset object associated with this object. the object may be invalid.

void GetPrimaryAsset_(ParaAssetObject *pOut)

this function shall never be called from the scripting interface. this is solely for exporting API. and should not be used from the scripting interface.

ParaScripting::ParaParamBlock GetEffectParamBlock()

get the parameter block of the effect (shader) associated with this object.

bool IsPersistent()

whether the object is persistent in the world. If an object is persistent, it will be saved to the world’s database. if it is not persistent it will not be saved when the world closes. Player, OPC, some temporary movie actors may by non-persistent; whereas NPC are usually persistent to the world that it belongs.

void SetPersistent(bool bPersistent)

See
IsPersistent()

bool SaveToDB()

save the current character to database according to the persistent property. if the object is persistent, the action is to update or insert the character to db if the object is non-persistent, the action is to delete it from the database.

bool equals(const ParaObject obj) const

return true, if this object is the same as the given object.

const char *ToString() const

convert the object to object creation string.

Return
: “” if not valid

const char *ToString1(const char *sMethod) const

convert the object to string.

Return
: “” if not valid
Parameters
  • sMethod: it can be one of the following strings “create”: generate script to create the object “update”: generate script to update the object, useful for updating static physics object “delete”: generate script to delete the object “loader”: generate script to create the object in managed loader

ParaAttributeObject GetAttributeObject()

get the attribute object associated with an object.

void GetAttributeObject_(ParaAttributeObject &output)

for API exportation

void CheckLoadPhysics()

when this function is called, it ensures that the physics object around this object is properly loaded. It increases the hit count of these physics objects by 1. The garbage collector in the physics world may use the hit count to move out unused static physics object from the physics scene (Novodex). This function might be called for the current player, each active mobile object in the scene and the camera eye position. vCenter: the center of the object in world coordinates fRadius: the radius of the object within which all physics object must be active.

void LoadPhysics()

only load physics of this object if it has not loaded.

luabind::object GetField(const char *sFieldname, const object &output)

get field by name. e.g. suppose att is the attribute object. local bGloble = att:GetField(“global”, true); local facing = att:GetField(“facing”, 0); local pos = att:GetField(“position”, {0,0,0}); pos[1] = pos[1]+100;pos[2] = 0;pos[3] = 10;

Return
: return the field result. If field not found, output will be returned. if field type is vectorN, return a table with N items.Please note table index start from 1
Parameters
  • sFieldname: field name
  • output: default value. if field type is vectorN, output is a table with N items.

void SetField(const char *sFieldname, const object &input)

set field by name e.g. suppose att is the attribute object. att:SetField(“facing”, 3.14); att:SetField(“position”, {100,0,0});

Parameters
  • sFieldname: field name
  • input: input value. if field type is vectorN, input is a table with N items.

void CallField(const char *sFieldname)

call field by name. This function is only valid when The field type is void. It simply calls the function associated with the field name.

luabind::object GetDynamicField(const char *sFieldname, const object &output)

get field by name. e.g. suppose att is the attribute object. local bGloble = att:GetField(“URL”, nil); local facing = att:GetField(“Title”, “default one”);

Return
: return the field result. If field not found, output will be returned. if field type is vectorN, return a table with N items.Please note table index start from 1
Parameters
  • sFieldname: field name
  • output: default value. if field type is vectorN, output is a table with N items.

void SetDynamicField(const char *sFieldname, const object &input)

set field by name e.g. suppose att is the attribute object. att:SetDynamicField(“URL”, 3.14); att:SetDynamicField(“Title”, {100,0,0});

Parameters
  • sFieldname: field name
  • input: input value. can be value or string type

ParaScripting::ParaObject GetObject(const char *name)

get object by name, if there are multiple objects with the same name, the last added one is inserted.

Note
: This function will traverse the scene to search the object. So there might be some performance penalty.
Parameters
  • name:

bool IsStanding()

whether the object has 0 speed.

bool IsVisible()

invisible object will not be drawn. e.g. one can turn off the visibility of physics object.

void SetVisible(bool bVisible)

set the visibility of this object. The visibility will recursively affect all its child objects.

bool CheckAttribute(DWORD attribute)

whether an object attribute is enabled.

Return
true if enabled
Parameters
  • attribute: object volume bit fields enum OBJECT_ATTRIBUTE { / two solid objects with sensor volume will cause environment simulator to / to generate sensor/collision event when they come in to contact. OBJ_VOLUMN_SENSOR = 1, / all child objects are in this object’s volume OBJ_VOLUMN_CONTAINER = 0x1<<1, / solid objects(like biped) can be placed on its volume, provided / it’s not already occupied by any solid objects from its children / when we solve two solid object collision, this is the field we check first. OBJ_VOLUMN_FREESPACE = 0x1<<2, / whether the object is isolated from its siblings. An isolated object / can overlap in physical space with all its siblings regardless of their solidity. / multiple scenes or terrains can be declared as ISOLATED object. Note, the object / is not isolated from its parent, though. OBJ_VOLUMN_ISOLATED = 0x1<<3, / the object has a perceptive radius that may be larger than the object’s / collision radius. Currently only biped object might has this volume type OBJ_VOLUMN_PERCEPTIVE_RADIUS = 0x1<<4, / objects with this VIP volume type will trigger the plot of the scene in its view-culling radius. OBJ_VOLUMN_VIP = 0x1<<5, / Object invisible, the object is not drawn.but its physics may load. added by lxz 2006.3.5 OBJ_VOLUMN_INVISIBLE = 0x1<<6, / mask of the above bits. this field is never used externally. VOLUMN_MASK = 0x7f, / whether lights have effects on this object. MESH_USE_LIGHT = 0x1<<7, / whether to rotate the object around Y axis to let the object always facing the camera. MESH_BILLBOARDED= 0x1<<8, / whether it is a shadow receiver. MESH_SHADOW_RECEIVER= 0x1<<9, / whether it is a vegetation. MESH_VEGETATION= 0x1<<10, };

void SetAttribute(DWORD dwAtt, bool bTurnOn)

enable or disable a given attribute.

Below are some attributes. For more information please see BaseObject.h

/ two solid objects with sensor volume will cause environment simulator to / to generate sensor/collision event when they come in to contact. OBJ_VOLUMN_SENSOR = 1, / all child objects are in this object’s volume OBJ_VOLUMN_CONTAINER = 0x1<<1, / solid objects(like biped) can be placed on its volume, provided / it’s not already occupied by any solid objects from its children / when we solve two solid object collision, this is the field we check first. OBJ_VOLUMN_FREESPACE = 0x1<<2, / whether the object is isolated from its siblings. An isolated object / can overlap in physical space with all its siblings regardless of their solidity. / multiple scenes or terrains can be declared as ISOLATED object. Note, the object / is not isolated from its parent, though. OBJ_VOLUMN_ISOLATED = 0x1<<3, / the object has a perceptive radius that may be larger than the object’s / collision radius. Currently only biped object might has this volume type OBJ_VOLUMN_PERCEPTIVE_RADIUS = 0x1<<4, / objects with this VIP volume type will trigger the plot of the scene in its view-culling radius. OBJ_VOLUMN_VIP = 0x1<<5, / Object invisible, the object is not drawn.but its physics may load. added by lxz 2006.3.5 OBJ_VOLUMN_INVISIBLE = 0x1<<6,

Parameters
  • dwAtt:
  • bTurnOn: true to turn on, false to turn off.

void SetPosition(double x, double y, double z)

set world position. Please note, for static object, it may make the quad tree terrain in which the object is located invalid. it may also make the physics engine panic.In such cases, one should call ParaScene.Attach() after chancing the position or rotation of a static mesh or physics object. If any of the following rule matches, the function is safe to use.

  • Use this function for global biped if (x,y,z) changes.
  • Use this function for all objects if it has not been attached to the global terrain
  • Use this function for static mesh, with (0,y,0) only.i.e. only changing height.
  • Never use this function for physics object, unless you are building the world. If you do use it it with physics or static mesh object, make sure that you follow the following rules: create the physics object and save it in a global variable called physicsObj. physicsObj = ParaScene.Attach(physicsObj); attach the physics object to the scene modification of the position, orientation, scaling of the object occurred. local x,y,z = physicsObj:GetPosition(); physicsObj:SetPosition(x+2,y,z); immediately call Attach again with physicsObj, so that the physical scene will be updated and the object be re-inserted properly in to the scene. physicsObj = ParaScene.Attach(physicsObj);
    Parameters
    • x: global x
    • y: global y
    • z: global z

void GetPosition(double *x, double *y, double *z)

get the world position of the object. This function takes no parameters. x,y,z are not input, but pure output. In the script, we can call it as below x,y,z = biped:GetPosition(); get the biped’s position in Luabind, it is defined as .def(“GetPosition”, &ParaObject::GetPosition, pure_out_value(_2) + pure_out_value(_3) + pure_out_value(_4)) please note, y is the absolute position in world coordinate

See
SetPosition(double x, double y, double z)

void GetViewCenter(double *x, double *y, double *z)

get the world position of the center of the view object. This function takes no parameters. x,y,z are not input, but pure output. In the script, we can call it as below x,y,z = biped:GetViewCenter(); get the biped’s center

void OffsetPosition(float dx, float dy, float dz)

offset the current object position by (dx,dy,dz)

See
SetPosition(float x, float y, float z) for precautions of using this function

void SetFacing(float fFacing)

set object facing around the Y axis. this function is safe to call for all kind of objects except the physics mesh object. for physics mesh object, one must call ParaScene.Attach() immediately after this function. for more information, please see SetPostion();

See
: SetPostion();

float GetFacing()

get object facing around the Y axis

void Rotate(float x, float y, float z)

Rotate the object.This only takes effects on objects having 3D orientation, such as static mesh and physics mesh. The orientation is computed in the following way: first rotate around x axis, then around y, finally z axis. Note: this function is safe to call for all kind of objects except the physics mesh object. for physics mesh object, one must call ParaScene.Attach() immediately after this function. for more information, please see SetPostion();

See
: SetPostion();
Parameters
  • x: rotation around the x axis.
  • y: rotation around the y axis.
  • z: rotation around the z axis.

void Scale(float s)

set the scale of the object. This function takes effects on both character object and mesh object. Note: this function is safe to call for all kind of objects except the physics mesh object. for physics mesh object, one must call ParaScene.Attach() immediately after this function. for more information, please see SetPostion();

See
: SetPostion();
Parameters
  • s: This is a relative scale to its current size. Scaling applied to all axis.1.0 means original size.

float GetScale()

set the scale of the object. This function takes effects on both character object and mesh object. Note: this function is safe to call for all kind of objects except the physics mesh object. for physics mesh object, one must call ParaScene.Attach() immediately after this function. for more information, please see SetPostion();

Parameters
  • s: this is the absolute scale on the original mesh model. Scaling applied to all axis.1.0 means original size.

void SetScale(float s)

set scale

See
GetScale();
Parameters
  • s:

object GetRotation(const object &quat)

this usually applies only to mesh object. get the rotation as quaternion. e.g. local mat3x3 = obj:GetRotation({});

Return
the rotational matrix is of the following format: {x,y,z,w,}

void SetRotation(const object &quat)

set the rotation as quaternion.

Parameters
  • sRot: the rotational matrix is of the following format: {x,y,z,w,}

void Reset()

reset the object to its default settings.

void SetPhysicsGroup(int nGroup)

set the physics group ID to which this object belongs to default to 0, must be smaller than 32. please see groups Mask used to filter shape objects. See #NxShape::setGroup

  • group 0 means physics object that will block the camera and player, such as building walls, big tree trunks, etc.
  • group 1 means physics object that will block the player, but not the camera, such as small stones, thin posts, trees, etc.

int GetPhysicsGroup()

Get the physics group ID to which this object belongs to default to 0, must be smaller than 32. please see groups Mask used to filter shape objects. See #NxShape::setGroup

  • group 0 means physics object that will block the camera and player, such as building walls, big tree trunks, etc.
  • group 1 means physics object that will block the player, but not the camera, such as small stones, thin posts, trees, etc.

void SetSelectGroupIndex(int nGroupIndex)

set the selection group index. if -1, it means that it was not selected. this function is equivalent to calling ParaSelection.AddObject(obj, nGroupID);

Parameters
  • nGroupIndex: selection group index.

int GetSelectGroupIndex()

get the selection group index. if -1, it means that it was not selected.

void SetDensity(float fDensity)

body density. The water density is always 1.0 in the game engine. So if it is above 1.0, it will sink in water; otherwise it will float on water surface. So if it is below 0.5, it will fly or glind in air falling down with little gravity; otherwise it will fall down with full gravity. A density of 0 or negative, means that the character can fly. The default value is 1.2. the following are some examples

  • character: body density: 1.2
  • car: body density: 2.0 mount target
  • ship: body density: 0.8 mount target
  • plane: body density: 0.4 mount target
    Parameters
    • fDensity:

float GetDensity()

get body density

float GetPhysicsRadius()

the biped is modeled as a cylinder or sphere during rough physics calculation. this function returns the radius of the cylinder or sphere.

void SetPhysicsRadius(float fR)

the biped is modeled as a cylinder or sphere during rough physics calculation. this function set the radius of the cylinder or sphere.

float GetPhysicsHeight()

the biped is modeled as a cylinder or sphere during rough physics calculation. this function returns the height of the cylinder or sphere. this value will also restrict the biped’s vertical movement. if there is no head attachment, the GetPhysicsHeight is used for character head on text position instead. If PhysicsHeight is never set, it is always 4*PhysicsRadius. However, if it is set, its value are maintained.

void SetPhysicsHeight(float fHeight)

the biped is modeled as a cylinder or sphere during rough physics calculation. this function set the height of the cylinder or sphere. this value will also restrict the biped’s vertical movement. if there is no head attachment, the GetPhysicsHeight is used for character head on text position instead. If PhysicsHeight is never set, it is always 4*PhysicsRadius. However, if it is set, its value are maintained.

string GetName() const

get the object name

const char *GetName_() const

for .NET API use only.not thread safe.

void SetName(const char *sName)

set the object name

Remark
: currently, renaming an object after attaching it to the scene is dangerous, because when people use the ParaScene.GetObject(), it may return a renamed and deleted object. The good practice is that never change an object’s name when it is attached to the scene.
Remark
: In version 0.9 or above, renaming an object will detach the object from the scene and then reattach it to the scene using the new name; so it works fine when changing object name after attachment.
Remark
: this function will not take effect, if the object can not be renamed, such as due to another global object with the same name.
Parameters
  • sName: new name of the object

void SnapToTerrainSurface(int bUseNorm)

snap to terrain surface. Such as landscape trees, stones, etc. set bUseNorm to 1, if you want the norm to be aligned.

bool IsCharacter() const

Return
return true if object is a character(biped) object

bool IsOPC() const

Return
return true if object is a network player

ParaCharacter ToCharacter()

return the ParaCharacter object, if this object is a biped typed scene object. the ParaCharacter interface offers more specific functions to control the behavior and appearance of the character object.

See
ParaCharacter

IGameObject *ToGameObject()

convert to game object. This function may return NULL.

void AddEvent(const char *strEvent, int nEventType, bool bIsUnique)

add events to object to control the object, please refer to HLE for object event specifications. Generally, one can use event to tell a biped to walk to a new position play a certain animation, speak some words, follow another biped, attack, etc.

Parameters
  • strEvent: currently a biped object accepts the following events. A list of events (more will be coming in future release):
    • “stop” Stop the biped
    • “walk x y” Walk to (x,y) using the default animation
    • “colr r, g, b” Set model color[0, 1] e.g. colr 1.0 0 0 = to set red color
    • “anim string | number” Play animation
    • “asai type parameters” Assign AI module of type type to the biped. Old modules are discarded Currently only support creature type AI module, with one parameter which can be ranged or melee unit. type: AIModuleCreatures=1, // respawning creatures that may be neural,or aggressive. They will not attack bipeds of any type, but may attack any team bipeds. AIModuleTeam=2, // Player Controllable biped AI module. it recognize creatures and members in other teams by their IDs. “asai 1 1” Assign creature AI with ranged unit attribute “asai 1 0” Assign creature AI with melee unit attribute
    • “ClearAll” Clear all tasks that this biped is assigned.
    • “task taskType parameters” Assign task to the AImodule associated with the biped. taskType: Currently taskType should be string, not their number
      • DieAndReborn = 0,
      • WanderNearby = 1,
      • Evade=2, “task Evade name” name: which biped to evade e.g. “task Evade enemy1”
      • Follow=3, “task Follow name” name: which biped to follow e.g. “task Follow LiXizhi”
      • Movie=4, “task Movie string” string: list of key, no spaces in the str are allowed. Format is given below [<const char* anim, float x, float y, float z, float facing, float duration>]+ If y=0, then the height of the position is ignored. Duration is in seconds. e.g. “task Movie <attack-1,50,0,60,0,10><Die-1,50,0,60,0,0>”
  • nEventType: default to 0
  • bIsUnique: is it unique by string

void AddChild(const ParaObject obj)

attach the object as its child object.

Parameters
  • obj: the child object to attach

void EnablePhysics(bool bEnable)

if this is a physics mesh object, this function will turn on or off the physics of the object.

bool IsPhysicsEnabled()

whether this is a physics mesh object

float DistanceTo(ParaObject obj)

get the distance with another object

float DistanceToSq(ParaObject obj)

get the distance square with another object

float DistanceToPlayerSq()

get the distance square with the current player object

float DistanceToCameraSq()

get the distance square with the camera object

object GetViewBox(const object &output)

get the view box. e.g. local box = obj:GetViewBox({}); log(box.pos_x..box.pos_y..box.pos_z); return a table containing the following field:{pos_x, pos_y,pos_z,obb_x,obb_y,obb_z,} pos_x, pos_y,pos_z: is the point at the bottom center of the box. obb_x,obb_y,obb_z: is the size of the box.

bool HasAttachmentPoint(int nAttachmentID)

return whether this model has a given attachment point

Parameters
  • nAttachmentID: see ATTACHMENT_ID. default to 0, which is general mount point. ATT_ID_MOUNT1-9(20-28) is another mount points

void GetAttachmentPosition(int nAttachmentID, float *x, float *y, float *z)

return this object’s attachment point e.g. local x,y,z = obj:GetAttachmentPosition(0);

Return
x,y,z: in world coordinates
Parameters
  • nAttachmentID: see ATTACHMENT_ID. default to 0, which is general mount point. ATT_ID_MOUNT1-9(20-28) is another mount points

void SetHomeZone(const char *sHomeZone)

set the home zone of this object if any. it may return NULL, if zone is not visible.

Parameters
  • sHomeZone: if this is NULL, it will remove the zone.

const char *GetHomeZone()

get the home zone of this object if any. it may return NULL or “”, if zone is not visible.

void SetHeadOnText(const char *sText, int nIndex)

set the text to be displayed on head on display

const char *GetHeadOnText(int nIndex)

Get the text to be displayed on head on display

void SetHeadOnUITemplateName(const char *sUIName, int nIndex)

set which UI control the head on display will be used as a template for drawing the text it can be a single CGUIText Object or it can be a container with a direct children called “text” if this is “” or empty, the default UI template will be used. The default UI template is an invisible CGUIText control called “_HeadOnDisplayText_” By default, “_HeadOnDisplayText_” uses horizontal text alignment and system font.

const char *GetHeadOnUITemplateName(int nIndex)

get which UI control the head on display will be used as a template for drawing the text it can be a single CGUIText Object or it can be a container with a direct children called “text” if this is “” or empty, the default UI template will be used. The default UI template is an invisible CGUIText control called “_HeadOnDisplayText_” By default, “_HeadOnDisplayText_” uses horizontal text alignment and system font.

Return
: it returns NULL if no UI head on display.

void SetHeadOnTextColor(const char *color, int nIndex)

set the text to be displayed on head on display

Parameters
  • color: “r g b” or “r g b a”, such as “0 255 0”, “0 255 0 255”

void SetHeadOnOffest(float x, float y, float z, int nIndex)

set the offset where head on display should be rendered relative to the origin or head of the host 3d object

void GetHeadOnOffset(int nIndex, float *x, float *y, float *z)

Get the offset where head on display should be rendered relative to the origin or head of the host 3d object

void ShowHeadOnDisplay(bool bShow, int nIndex)

show or hide object’s head on display

bool IsHeadOnDisplayShown(int nIndex)

whether the object head on display shall be visible

bool HasHeadOnDisplay(int nIndex)

whether the object contains head on display

int GetXRefScriptCount()

get the number of the script X reference instances

const char *GetXRefScript(int nIndex)

return xref script file path by index

void GetXRefScriptPosition(int nIndex, float *x, float *y, float *z)

get the 3D position in world space of the script object’s origin

void GetXRefScriptScaling(int nIndex, float *x, float *y, float *z)

get the scaling of the object in both x,y,z directions

float GetXRefScriptFacing(int nIndex)

get the facing of the object in xz plane

const char *GetXRefScriptLocalMatrix(int nIndex)

get the local transform of the script object. It contains scale and rotation only the string returned by this function must be used at once and should not be saved. This function is also not thread-safe.

Return
: “11,12,13, 21,22,23, 31,32,33,41,42,43” ,where 41,42,43 are always 0. It may return NULL, if the local matrix does not exist.

bool IsSentient()

whether the biped is sentient or not

float GetSentientRadius()

get the sentient radius. usually this is much larger than the perceptive radius.

float GetPerceptiveRadius()

get the perceptive radius.

void SetPerceptiveRadius(float fNewRaduis)

Set the perceptive radius.

int GetNumOfPerceivedObject()

return the total number of perceived objects.

ParaObject GetPerceivedObject(int nIndex)

get the perceived object by index. This function may return NULL.

bool IsAlwaysSentient()

whether the object is always sentient. The current player is always sentient

void SetAlwaysSentient(bool bAlways)

set whether sentient.

void MakeSentient(bool bSentient)

set the object to sentient.

Parameters
  • bSentient: true to make sentient. if the object’s sentient count is larger than 0, this function has no effect false, to remove the object from the sentient list.

void UpdateTileContainer()

update the tile container according to the current position of the game object. This function is automatically called when a global object is attached.

void MakeGlobal(bool bGlobal)

make the biped global if it is not and vice versa.

bool IsGlobal()

whether the object is global or not.

void SetGroupID(int nGroup)

set the group ID to which this object belongs to. In order to be detected by other game object. Object needs to be in group 0 to 31. default value is 0

void SetSentientField(DWORD dwFieldOrGroup, bool bIsGroup)

set the sentient field. A bit field of sentient object. from lower bit to higher bits, it matches to the 0-31 groups.

See
SetGroupID() if this is 0x0000, it will detect no objects. If this is 0xffff, it will detects all objects in any of the 32 groups. if this is 0x0001, it will only detect group 0.
Parameters
  • dwFieldOrGroup: this is either treated as field or group,depending on the bIsGroup parameter.
  • bIsGroup: if this is true, dwFieldOrGroup is treated as a group number of which will object will detect. if this is false, dwFieldOrGroup is treated as a bitwise field of which will object will detect.

bool IsSentientWith(const ParaObject &pObj)

return true if the current object is sentient to the specified object. If the object is always sentient, this function will always return true.

void SetMovableRegion(float center_x, float center_y, float center_z, float extent_x, float extent_y, float extent_z)

Set the region within which the object can move. This function is not fully implemented on a per object basis.

Note
: currently it sets the global movable region of the character.

void GetMovableRegion(float *center_x, float *center_y, float *center_z, float *extent_x, float *extent_y, float *extent_z)

get the region within which the object can move.. This function takes no parameters. input are not input, but pure output. In the script, we can call it as below cx,cy,cz,ex,ey,ez = biped:GetMovableRegion(); get the biped’s position please note, y is the absolute position in world coordinate

See
SetMovableRegion()

void SetAnimation(int nAnimID)

Set the current animation id

Parameters
  • nAnimID: 0 is default standing animation. 4 is walking, 5 is running. more information, please see AnimationID

int GetAnimation()

get the scaling.

string GetOnEnterSentientArea() const

when other game objects of a different type entered the sentient area of this object. This function will be automatically called by the environment simulator.

string GetOnLeaveSentientArea() const

when no other game objects of different type is in the sentient area of this object. This function will be automatically called by the environment simulator.

string GetOnClick() const

when the player clicked on this object. This function will be automatically called by the environment simulator.

void On_Click(DWORD nMouseKey, DWORD dwParam1, DWORD dwParam2)

activate the OnClick

string GetOnPerceived() const

when other game objects of a different type entered the perceptive area of this object. This function will be automatically called by the environment simulator.

string GetOnFrameMove() const

called every frame move when this character is sentient. This is most likely used by active AI controllers, such as movie controller.

string GetOnNetSend() const

during the execution of this object, it may send various network commands to the server or client. the network module will decide when to group these commands and send them over the network in one package. this function will be called when such network package is being prepared.

string GetOnNetReceive() const

when the network module receives packages from the network and it is about a certain game object. Then this function will be automatically called. In this function, the game object may read the network packages and act accordingly.

int GetEffectHandle()

Get the current shader handle used to render the object

See
TechniqueHandle

void SetEffectHandle(int nHandle)

Set the shader handle used to render the object. Please note, object will be immediately rendered using the newly assigned shader in the next frame. shade handle in the range [0,2048] is reserved for ParaEngine’s internal usage. CAUTION: setting a shader whose input is incompatible with the object’s internal data presentation will cause the application to close.

See
TechniqueHandle
Parameters
  • nHandle:

int AddReference(const ParaObject &maker, int nTag)

add a new reference.

Return
Parameters
  • maker:

int DeleteReference(const ParaObject &ref)

delete a reference.

Return
return REF_FAIL if reference not found. otherwise REF_SUCCEED
Parameters
  • ref:

int DeleteAllRefs()

Deletes all references of this object.

int GetRefObjNum()

get the total number of references

ParaObject GetRefObject(int nIndex)

get the referenced object at the given index

ParaScripting::ParaAssetObject GetTexture()

get primary texture object

int GetNumReplaceableTextures()

get the total number of replaceable textures, which is the largest replaceable texture ID. but it does not mean that all ID contains valid replaceable textures. This function can be used to quickly decide whether the model contains replaceable textures. Generally we allow 32 replaceable textures per model.

Note
: This function will cause the mesh entity to be initialized.
Return
0 may be returned if no replaceable texture is used by the model.

ParaAssetObject GetDefaultReplaceableTexture(int ReplaceableTextureID)

get the default replaceable texture by its ID. The default replaceable texture is the main texture exported from the 3dsmax exporter.

Note
: This function will cause the mesh entity to be initialized.
Return
this may return NULL, if replaceable texture is not set before or ID is invalid.
Parameters
  • ReplaceableTextureID: usually [0-32) generally speaking, replaceable ID 0 is used for general purpose replaceable texture, ID 1 is for user defined. ID 2 is for custom skins.

ParaAssetObject GetReplaceableTexture(int ReplaceableTextureID)

get the current replaceable texture by its ID. if no replaceable textures is set before, this will return the same result as GetNumReplaceableTextures().

Note
: This function will cause the mesh entity to be initialized.
Return
this may return NULL, if replaceable texture is not set before or ID is invalid.
Parameters
  • ReplaceableTextureID: usually [0-32) generally speaking, replaceable ID 0 is used for general purpose replaceable texture, ID 1 is for user defined. ID 2 is for custom skins.

bool SetReplaceableTexture(int ReplaceableTextureID, ParaAssetObject pTextureEntity)

set the replaceable texture at the given index with a new texture. this function will succeed regardless whether the mesh is initialized. Hence it can be used at loading time. because default instance of the mesh may use different replaceable texture set.

Return
true if succeed. if ReplaceableTextureID exceed the total number of replaceable textures, this function will return false.
Parameters
  • ReplaceableTextureID: usually [0-32) generally speaking, replaceable ID 0 is used for general purpose replaceable texture, ID 1 is for user defined. ID 2 is for custom skins.
  • pTextureEntity: The reference account of the texture entity will be automatically increased by one.

class ParaObjectNode
#include <ParaScriptingGlobal.h>

for Para Script global dictionary object

class ParaPainter
#include <ParaScriptingPainter.h>

the current painter object. call Begin() End() to switch paint device. please note, for ownerdraw GUI callbacks, they are automatically called.

for performance reasons, all methods are static.

Public Static Functions

void SetFont(const object &font)

set current font

Parameters
  • font: {family=”System”, size=10, bold=true} or it can be string “System;14;” or “System;14;bold”

void SetPen(const object &pen)

set current pen

Parameters
  • pen: { width=1, brush = {color=”#00000000”, texture=”filename or texture asset”}, } or it can be {width=1, color=”#000000”, texture=”filename or texture asset”} or it can be pen color “#ff000000” or “255 255 255”

void SetBrush(const object &brush)

set current brush (texture and color)

Parameters
  • brush: { color=”#00000000”, texture=”filename or texture asset”} or it can be pen color “#ff000000” or “255 255 255”

void SetBackground(const object &brush)

set current background brush

Parameters
  • brush: { color=”#00000000”, texture=”filename or texture asset”}

void SetOpacity(float fOpacity)

between [0,1]

void SetTransform(const object &trans, bool combine)

Sets the world transformation matrix. If combine is true, the specified matrix is combined with the current matrix; otherwise it replaces the current matrix.

void DrawTriangleList(const object &triangleList, int nTriangleCount, int nIndexOffset)

draw 3d triangles

Parameters
  • triangleList: array of triangle vertices {{x,y,z}, {x,y,z}, {x,y,z}, ...},
  • nTriangleCount: triangle count.
  • nIndexOffset: start index offset. default to 0.

void DrawLineList(const object &lineList, int nLineCount, int nIndexOffset)

draw 3d lines

Parameters
  • lineList: array of line vertices {{x,y,z}, {x,y,z}, ...},
  • nTriangleCount: triangle count
  • nIndexOffset: start index offset. default to 0.

class ParaParamBlock
#include <ParaScriptingCommon.h>

a list of CParameter{name, value} pairs of anything. usually used for DirectX effect parameter block. value can be integer, float, vector3, vector4, matrix, TextureEntity, etc.

Public Functions

bool IsValid()

check if the object is valid

void Clear()

clear all parameters

void SetMatrix43(const char *sParamName, const char *matrix)

set matrix by a string of 4*3 number of float values separated by comma (see below): “mat._11, mat._12, mat._13, mat._21, mat._22, mat._23,mat._31, mat._32, mat._33,mat._41, mat._42, mat._43” If a blank string(“”) is specified, identity matrix is set

void SetParam(const char *sParamName, const char *sValue)

setting known parameters to its predefined or current value.

Parameters
  • sValue: known values such as “mat4Project”, “mat4ProjectionInverse”, “mat4Projection”, “mat4ModelView”, “mat4ModelViewInverse”, “mat4ShadowMapTex”, “vec3cameraPosition”

void SetTexture(int nTextureIndex, const char *sFilePath)

set texture with the given texture index,

Parameters
  • nTextureIndex: usually [0,9], which texture register to use in case of effect file parameter.
  • sFilePath: the file name of the texture.

void SetTextureObj(int nTextureIndex, const ParaAssetObject &assetObject)

same as SetTexture, except that ParaAssetObject is an object.

class ParaScene
#include <ParaScriptingScene.h>

ParaScene namespace contains a list of HAPI functions to create and modify scene objects in paraworld. The following are basic steps to create scene object:

  • Use Create*() functions to create scene object. The created object is return as a ParaObject instance.
  • Use the ParaObject instance to modify the position and orientation of the object.
  • Use Attach method to insert the scene object to the scene.

Please note: if an object is created without attaching to the scene, it may result in memory leak. although, we may automatically clear unattached scene object, when the application quit.

Public Static Functions

ParaAttributeObject GetAttributeObject()

get the attribute object associated with the global scene.

void GetAttributeObject_(ParaAttributeObject &output)

used for API exportation.

ParaAttributeObject GetAttributeObjectSky()

get the attribute object associated with the current sky object.

void GetAttributeObjectSky_(ParaAttributeObject &output)

used for API exportation.

ParaAttributeObject GetAttributeObjectPlayer()

get the attribute object associated with the current player.

void GetAttributeObjectPlayer_(ParaAttributeObject &output)

used for API exportation.

ParaAttributeObject GetAttributeObjectOcean()

get the attribute object associated with the global ocean manager.

void GetAttributeObjectOcean_(ParaAttributeObject &output)

used for API exportation.

ParaAttributeObject GetAttributeObjectSunLight()

get the attribute object associated with the sun light .

void GetAttributeObjectSunLight_(ParaAttributeObject &output)

used for API exportation.

ParaObject GetObject(const char *strObjName)

get the scene object by name. currently, the object must be global, in order to be found by its name.

Remark
: if local mesh’s name begins with “g_”, it can also be retrieved by calling this function. however, if a global object has the same name, the global object is always returned instead of the local mesh.
Parameters
  • strObjName: the format of the name is as below: strObjName := [<_type>]string _type := managed_loader | OPC | NPC | player | zone | portal e.g. strObjName = “creatures1” or “<managed_loader>sceneloader1” or “<player>”.

ParaScripting::ParaObject GetObject5(int nID)

get an object by its ID

ParaObject GetObject3(float x, float y, float z)

get the first local object,whose position is very close to vPos. This function will search for the first (local mesh) object throughout the hierachy of the scene. this function is kind of slow, please do not call on a per frame basis. Use GetObjectByViewBox() to get an object faster.

Return
: NULL if not found
Parameters
  • vPos: world position of the local mesh object
  • fEpsilon: if a mesh is close enough to vPos within this value.

ParaObject GetObject4(float x, float y, float z, float fEpsilon)

get the first object that matches the position within fEpsilon, which is usually 0.01f

void GetObject_(ParaObject *pOut, const char *strObjName)

this function shall never be called from the scripting interface. this is solely for exporting API. and should not be used from the scripting interface.

ParaObject GetPlayer()

Get the current player. same as ParaScene.GetObject(“<player>”).

void GetPlayer_(ParaObject *pOut)

this function shall never be called from the scripting interface. this is solely for exporting API. and should not be used from the scripting interface.

ParaObject GetNextObject(ParaObject &obj)

get the next scene object.

Return
: return the next object. the returned object is invalid if there is only one object left.
Parameters
  • obj: the object whose next object is retrieved.

void CreateWorld(const char *sWorldName, float fWorldSize, const char *sConfigFile)

Create a new parallel world of a given size. When this function is called, it will replace previously created world of the same name. Currently only a single world can be created at any given time. In future, we will support hosting several world simultaneously.

Parameters
  • sWorldName: name of the world to be created.
  • fWorldSize: the size of the world in meters.
  • sConfigFile: the file name of the configuration file. Currently it is the same as the terrain configuration file

void Reset()

reset the scene to blank. this function is NOT automatically called when a new isolated world is created. so one need to call Reset() when it wants to change the world, otherwise the new world will be merged into the previous world.

See
CreateWorld()

ParaObject CreateManagedLoader(const char *sLoaderName)

Create a managed loader for dynamic scene object loading and unloading. The behavior of a managed loader is below:

  • The child objects of a managed loader will be automatically loaded and unloaded as a single entity.
  • Generally only static objects are attached to a managed loader.
  • Different managed loaders in a ParaScene must have different names.
  • if one create a manager loader with the same name several times, the same managed loader will be returned.
  • the bounding box of a managed loader will be automatically calculated as new child objects are attached to it.
  • The current loader algorithm will linearly transverse all managed loaders in the scene to decide which scene objects to load or unload. Although the routine is executed when the CPU is free, it is good practice to keep the total number of managed loaders in a single scene low. I think a couple of thousand loaders will be fine for current hardware.
  • it is good practice to use managed loaders to group all static scene objects that appears in a scene. Because, it will keep the scene graph to a moderate size automatically and accelerate physics calculation, etc.

The following NPL code shows typical usage of the managed loader. Generally a managed loader and its children are written in a single script file. Then, any other script can call dofile() or NPL.ActivateCopy() to run the script as many times as they like. The code however will ensure that objects managed by the loader will only be created and attached once in the game engine.There may be a setting in ParaEngine to do automatic garbage collection with managed loaders, so one may need to call the following script file often enough for the managed objects to stay active in the game scene. local sceneLoader = ParaScene.GetObject(“<managed_loader>scene2”); if (sceneLoader:IsValid() == true) then if the scene loader already exists, just attach it to the scene. ParaScene.Attach(sceneLoader); else if the scene loader is not created before, we will create it now sceneLoader = ParaScene.CreateManagedLoader(“scene2”); ParaAsset.ParaXModel(“tiny”, “Units/Human/Peasant/peasant.x”); create scene objects and add them to managed loader object local player; player = ParaScene.CreateCharacter (“LiXizhi2”, “tiny”, “”, false, 0.5, 0, 1.0); player:SetPosition(21758, 0, 16221); player:SnapToTerrainSurface(0); sceneLoader:AddChild(player); attach all objects in the loader to the scene graph ParaScene.Attach(sceneLoader); end

See
CManagedLoaderObject in ParaEngine reference.
Parameters
  • sLoaderName: the name of the loader.

void CreateGlobalTerrain(float fRadius, int nDepth, const char *sHeightmapfile, float fTerrainSize, float fElevscale, int bSwapvertical, const char *sMainTextureFile, const char *sCommonTextureFile, int nMaxBlockSize, float fDetailThreshold)

update the terrain tile at a given tile location. In case a world is extremely large, it can be divided into a matrix of square tiles of a given size. there is no limitation on the size of this matrix, hence the (nRow, nCol) parameter can be any integer pair. but typically, the matrix is rarely larger than 64*64. We use indexed set to save the matrix, so the memory consumption of the matrix is linearly proportionally to the number of terrain tiles created.

See
CreateWorld(const char * sWorldName, float fWorldSize, float fTerrainTileSize); Create and set the global terrain from height map and texture files. this function can be called multiple times, in which cases previously loaded terrain will be discarded example: ParaScene.CreateGlobalTerrain(2048, 7, “LlanoElev.png”, 5.0, 15.0, 1, “LlanoTex.jpg”, “dirt2.jpg”, 64, 10.0”);
Parameters
  • nRow: the row number in the terrain tile matrix.nRow>=0.
  • nCol: the row number in the terrain tile matrix.nCol>=0.
  • sConfigFile: the terrain tile configuration file to be used to create the terrain at (nRow, nCol). if sConfigFile == “”, then the terrain at (nRow, nCol) will be removed.
Parameters
  • fRadius: entire terrain size, this has doing to do with the actual terrain map size, it just prevent mobile characters from walking outside it.
  • nDepth: depth of the quad tree terrain hierarchy. objects created on the terrain will be organized in a quad tree. This is the depth of the quad tree. It should not be too big. usually 7 is enough. the rest of the parameters specify the data to render the terrain.
  • sHeightmapfile: the height map used to create the terrain. It must be sized to 2*2*...*2 pixels for both height and width. so usually it is 1024*1024, 2048*2048, etc.
  • fTerrainSize: the actual terrain size in the game
  • bSwapvertical: if one want to swap the height map data vertically.
  • sMainTextureFile: texture to be mapped to entire terrain
  • sCommonTextureFile: texture to be tiles to the entire terrain to add some details.
  • nMaxBlockSize: When doing LOD with the height map, the max block size must be smaller than this one. This will be (nMaxBlockSize*nMaxBlockSize) sized region on the height map.
  • fDetailThreshold: we will use a LOD block to approximate the terrain at its location, if the block is smaller than fDetailThreshold pixels when projected to the 2D screen.

void Attach(ParaObject &pObj)

Automatically attach a scene object to the scene graph according to its type and position. The object can be a manager loader, a global object or any ordinary scene object.

  • For tiled object, it is added to the smallest CTerrainTile in the quad-tree
  • For global tiled object, it is added to the root CTerrainTile
  • For non-tiled object, it is added to an automatically created CContainerObject whose name is the class identifier name of the object. hence objects are automatically grouped by class type on the root scene’s child nodes. To explicitly add an object to a specified parent, use AddChild() method on the parent node.
    Return
    : parent object is returned if successfully attached. For tiled object, this is the smallest terrain tile that contains the object. For non-tiled object, this is the automatically created CContainerObject that.
    Note
    : If the object has already been attached to the scene, it will be removed and reattached. In most cases, a strong reference of the object is kept by its parent.

void Delete(ParaObject &pObj)

delete the object. If the object is root scene object, then the entire scene is deleted.

void Detach(ParaObject &pObj)

detach the object. Be sure that the object is properly deleted after it is detached from the scene, because the scene graph is not responsible to manage it any more. The only exception is the managed loader object.

See
CreateManagedLoader(const char * sLoaderName)

void FireMissile(int nMissileID, float fSpeed, double fromX, double fromY, double fromZ, double toX, double toY, double toZ)

fire a missile from (fromX, fromY, fromZ) to (toX, toY, toZ) using the specified missile object and speed.

void SetModified(bool bModified)

set whether scene is modified

bool IsModified()

Get whether scene is modified

bool IsScenePaused()

when a scene is paused, all animation will be frozen.

void PauseScene(bool bEnable)

pause the scene

bool IsSceneEnabled()

whether 3D scene is enabled or not. a disabled scene is not visible no matter what. This function must be called at least once whenever a new scene is loaded, or 3D scene will not be displayed. A scene is automatically disabled when cleaned up.

void EnableScene(bool bEnable)

enable the scene

ParaObject CreateMeshObject(const char *strObjectName, const char *strMeshAssetName, float fOBB_X, float fOBB_Y, float fOBB_Z, float fFacing, bool bSolid, const char *localMatrix)

create a simple and static mesh object in the scene. Solid mesh will collide with mobile characters. Simple mesh does not implement clipping optimization, hence should not be very large. It is good to use it

Parameters
  • strMeshAssetName: for small houses, trees, stones, small hills, etc. when naming mesh file, one can combine “_a”(no physics), “_b”(billboard), “_t”(transparent), “_d”(dim or no lighting), “_r”(receive shadow) in the file name in any order, such as “xxx_b_t_d.x”. all such special file endings are listed below
    • “_a”: no physics, it will have no physics, even bApplyPhysics is true. For example. “grass_a.x”.
    • “_b”: billboarded and no physics
    • “_r”: mesh is shadow receiver
    • “_e”: mesh is not a shadow caster
    • “_t”: mesh contains majority transparent objects. Please note that this is different from alpha testing. Transparency throguh alpha testing is not transparent.
    • “_p”: mesh is picture or particles. They are rendered with billboarding and Force No Light flag on.
    • “_d”: mesh is dim and is rendered with force no light on.
    • “_v”: mesh is rendered with vegetation shader. the static model like palm trees, grasses, bamboos can be animated by this shader.
  • fOBB_X: object bounding box.x
  • fOBB_Y: object bounding box.y
  • fOBB_Z: object bounding box.z
  • fFacing: rotation of the bounding box around the y axis.
  • bSolid: 1, if it is a solid mesh, otherwise it is passable.
  • localMatrix: the local transformation matrix of the mesh. It is a string of 4*3 number of float values separated by comma (see below): “mat._11, mat._12, mat._13, mat._21, mat._22, mat._23,mat._31, mat._32, mat._33,mat._41, mat._42, mat._43” If a blank string(“”) is specified, the local matrix is set to identity matrix.

ParaScripting::ParaObject CreateObject(const char *strType, const char *strObjectName, double x, double y, double z)

create an object according to type.

Return
ParaObject
Parameters
  • strType: as returned by GetAttributeClassName of IAttributeField, such as “CMeshPhysicsObject”, “CMeshObject”, “CBipedObject”, etc.
  • strObjectName: string identifier of the object
  • xyz: position of the object.

ParaScripting::ParaObject CreateZone(const char *sZoneName, const char *sBoundingVolumes, float width, float height, float depth, float facing)

create a portal zone object for portal rendering.

Parameters
  • sZoneName: it must be unique.
  • fRadius: the zone sphere radius is an approximation of the bounding volume. we will only further check if an object is inside a zone, if it is first inside this sphere.
  • sBoundingVolumes: if this is “”, the zone will not be able to automatically determine which mobile objects are in it. or it can be “x1,y1,z1;x2,y2,z2;x3,y3,z3;” each three value is a point in local space denoting a plane of the bounding volume. because the convex bounding volume in local space always contains the origin, three values is enough to represent a plane in the bounding volume.
  • widthheightdepthfacing: the bounding shape of the portal.

ParaScripting::ParaObject CreatePortal(const char *sPortalName, const char *sHomeZone, const char *sTargetZone, const char *sQuadVertices, float width, float height, float depth, float facing)

create a portal object for portal rendering

Parameters
  • sPortalName: it must be a unique name.
  • sHomeZone: a zone name that this portal connects. this can be “”, if a portal is not connected to any zone.
  • sTargetZone: another zone name that this portal connects. this can be “”, if the portal is connected to outer space.
  • sQuadVertices: it is coordinates of the 4 quad vertices, “x1,y1,z1;x2,y2,z2;x3,y3,z3;x4,y4,z4;” the order of the first three vertices decides the direction of the quad plane. direction of quad plane is only useful when the portal’s sTargetZone is empty(outer space), and it should always point from home zone to outer space.
  • widthheightdepthfacing: the bounding size of the portal.

ParaScripting::ParaObject CreateVoxelMesh(const char *strObjectName, const char *sGridFileName, const char *sTextureFileName)

create a voxel mesh object. A voxel mesh is a 32*32*32 grid which can be editable at runtime, and rendered using the matching cube algorithm.

Parameters
  • strObjectName:
  • sGridFileName: the file name from which to load.This can be “”, where an empty one is created.
  • sTextureFileName: the texture to use, one can later change this by calling SetReplaceableTexture.

bool CreateSkyBox(const char *strObjectName, const char *strMeshAssetName, float fScaleX, float fScaleY, float fScaleZ, float fHeightOffset)

create a sky box and add it to the current list. sky box with the same name will not be recreated,but will be selected as the current sky box. It may be a sky box/dome/plane or whatever. The associated mesh will be scaled by the specified amount along x,y,z axis and then translate up or down along the y axis. in many cases, the mesh data in the mesh asset is of unit size.

Parameters
  • strObjectName: sky name
  • strMeshAssetName: mesh asset name. this is not the file name.
  • fScaleX: the static mesh local transform scale along the x axis
  • fScaleY: the static mesh local transform scale along the y axis
  • fScaleZ: the static mesh local transform scale along the z axis
  • fHeightOffset: the translation along the y axis.

void DeleteSkyBox(const char *strObjectName)

delete a name sky box.

Parameters
  • strObjectName: if this is “”, all sky boxes will be deleted.

ParaObject CreateMeshPhysicsObject(const char *strObjectName, const char *strMeshAssetName, float fOBB_X, float fOBB_Y, float fOBB_Z, bool bApplyPhysics, const char *localMatrix)

Create static triangle mesh based actor for novodex physics engine. Some notes about meshes:

  • Be sure that you define face normals as facing in the direction you intend. Collision detection will only work correctly between shapes approaching the mesh from the outside, i.e. from the direction in which the face normals point.
  • Do not duplicate identical vertices! If you have two triangles sharing a vertex, this vertex should only occur once in the vertex list, and both triangles should index it in the index list. If you create two copies of the vertex, the collision detection code wont know that it is actually the same vertex, which leads to a decreased performance and unreliable results.
  • Also avoid t-joints and non-manifold edges for the same reason. (A t-joint is a vertex of one triangle that is placed right on top of an edge of another triangle, but this second triangle is not split into two triangles at the vertex, as it should. A non-manifold edge is an edge (a pair of vertices) that is referenced by more than two triangles.)
    Parameters
    • strMeshAssetName: the mesh asset name which contains the triangular mesh. when naming mesh file, one can combine “_a”(no physics), “_b”(billboard), “_t”(transparent), “_d”(dim or no lighting), “_r”(receive shadow) in the file name in any order, such as “xxx_b_t_d.x”. all such special file endings are listed below

“_a”: no physics, it will have no physics, even bApplyPhysics is true. For example. “grass_a.x”.

  • “_b”: billboarded and no physics
  • “_r”: mesh is shadow receiver
  • “_e”: mesh is not a shadow caster
  • “_t”: mesh contains majorily transparent objects. Please note that this is diferent from alpha testing. Transparency throguh alpha testing is not transparent.
  • “_p”: mesh is picture or particles. They are rendered with billboarding and Force No Light flag on.
  • “_d”: mesh is dim and is rendered with force no light on.
  • “_v”: mesh is rendered with vegetation shader. the static model like palm trees, grasses, bamboos can be animated by this shader.
    Parameters
    • fOBB_X: object bounding box.x
    • fOBB_Y: object bounding box.y
    • fOBB_Z: object bounding box.z
    • bApplyPhysics: whether to turn on the physics of the mesh
    • localMatrix: the local transformation matrix of the mesh. It is a string of 4*3 number of float values separated by comma (see below): “mat._11, mat._12, mat._13, mat._21, mat._22, mat._23,mat._31, mat._32, mat._33,mat._41, mat._42, mat._43” If a blank string(“”) is specified, the local matrix is set to identity matrix.

void CreateMeshPhysicsObject__(ParaObject *pOut, const char *strObjectName, ParaAssetObject &asset, float fOBB_X, float fOBB_Y, float fOBB_Z, bool bApplyPhysics, const char *localMatrix)

this function shall never be called from the scripting interface. this is solely for exporting API. and should not be used from the scripting interface.

ParaObject CreateLightObject(const char *strObjectName, float fPosX, float fPosY, float fPosZ, const char *sLightParams, const char *localMatrix)

Create a new light object. This is used to make light objects persistent.

Return
light object is created and returned. One need to attach it to scene.
Parameters
  • strObjectName: Light Object’s name
  • fPosX: world position X
  • fPosY: world position Y
  • fPosZ: world position Z
  • sLightParams: if this is “” a default light will be created. otherwise it is in the following format. format is “Type Range (r g b a) att0 att1 att2” D3DLIGHTTYPE Type; Type of light source
    • D3DLIGHT_POINT = 1,
    • D3DLIGHT_SPOT = 2,
    • D3DLIGHT_DIRECTIONAL = 3, float Range; Cutoff range D3DCOLORVALUE Diffuse; Diffuse color of light float Attenuation0; Constant attenuation float Attenuation1; Linear attenuation float Attenuation2; Quadratic attenuation e.g. “1 7.0 (1 1 0 1) 0.3 0.1 1” light intensity is calculated as 1/(Attenuation0+d*Attenuation1+d*d*Attenuation2), where d is the distance from the light to object center.
Parameters
  • localMatrix: the local transformation matrix of the mesh. It is a string of 4*3 number of float values separated by comma (see below): “mat._11, mat._12, mat._13, mat._21, mat._22, mat._23,mat._31, mat._32, mat._33,mat._41, mat._42, mat._43” If a blank string(“”) is specified, the local matrix is set to identity matrix.

ParaObject CreateDynamicPhysicsObject(const char *strObjectName, const char *strMeshAssetName, float fOBB_X, float fOBB_Y, float fOBB_Z, bool bRenderMesh)

Create dynamic physics actor for novodex physics engine. dynamic objects are considered global object and is loaded to the physics engine immediately currently, only Box and sphere shaped objects are supported.

ParaObject CreateCharacter(const char *strObjectName, const char *strMultiAnimationAssetName, const char *strScript, bool bIsGlobal, float fRadius, float fFacing, float fScaling)

Create Character.

Parameters
  • strObjectName: the name short cut for this object. If the character with the same name exists, it will be renamed to a random name. So that the character is always created.
  • strMultiAnimationAssetName: the asset name of the base model. It can be nil, in which one must specified it in other means. if the asset file name ends with “_s”, it will always be static and local , even IsGlobal is true. For example. “windmill_s.x”. Some other special file endings are listed below
    • “_s”: force static, solid and local.
  • strScript: The script file to be loaded when the object is loaded for the first time
  • bIsGlobal: a global character is not attached to the quad tree terrain, thus can move around the entire scene a non-global character is attached to the quad tree terrain, and is generally considered immobile. although it is OK for non-global character to move only in very small region.
  • fRadius: radius of the character used in collision detection. if radius is 0, then the object is regarded as passable (not solid).
  • fFacing: rotation around the y axis
  • fScaling: typically this should be 1, however, one can scale the mesh and animation to render the character in a different size.

void CreateCharacter__(ParaObject *pOut, const char *strObjectName, ParaAssetObject &asset, const char *strScript, bool bIsGlobal, float fRadius, float fFacing, float fScaling)

this function shall never be called from the scripting interface. this is solely for exporting API. and should not be used from the scripting interface.

void Play3DSound(const char *strSoundAssetName, float fX, float fY, float fZ)

play a 3D sound at world location (fx, fy, fz). Currently, the sound is played until it stopped(no looping). And the sound range is internally defined. Please use the ParaUI.PlaySound() to play an ordinary sound or music with or without looping.

void SetGlobalWater(bool bEnable, float fWaterLevel)

Set the global water drawing attribute. the global water level is just a water surface at a given height, which is always drawn at current camera location to fill the entire screen. Water surface will be drawn after terrain

Parameters
  • bEnable: whether to draw global water
  • fWaterLevel: water level in meters. Default value is 0.0f;

float GetGlobalWaterLevel()

get the current global water level in meters. This function will return valid value even if the water is disabled.

bool IsGlobalWaterEnabled()

return true if global ocean water is enabled.

void UpdateOcean()

call this function, when the ocean has changed or the environment has changed. This will cause the reflection map of the ocean surface to redraw regardless of whether the camera moves or not.

void AddWaterRipple(float x, float y, float z)

add water ripple to the ocean surface.

See
GetGlobalWaterLevel()
Parameters
  • x: position of the ripple
  • y: this is usually set to the current water level.
Parameters
  • z: position of the ripple

void Execute(const char *strCmd)

execute the scene command string. Most commands are for debugging purposes. The list of command is given below:

  • “show OBB” display every scene object’s bounding box
  • “hide OBB” hide every scene object’s bounding box
  • “show report” display the per frame report, such as number of mesh drawn, number of terrain triangles, etc,..
  • “hide report” hide the per frame report, such as number of mesh drawn, number of terrain triangles, etc,.. strCmd: the string command passed

ParaObject MousePick(float fMaxDistance, const char *sFilterFunc)

Pick scene object at the current mouse cursor position. pick the smallest intersected object which is un-occluded by any objects. Object A is considered occluded by object B only if (1) both A and B intersect with the hit ray. (2) both A and B do not intersect with each other. (3) B is in front of A, with regard to the ray origin.

this function will ray-pick any loaded scene object(biped & mesh, but excluding the terrain) using their oriented bounding box. a filter function may be provided to further filter selected object. this function will transform all objects to near-camera coordinate system. This will remove some floating point inaccuracy near the camera position.Hence this function is most suitable for testing object near the camera eye position. This function does not rely on the physics engine to perform ray-picking. fMaxDistance: the longest distance from the ray origin to check for collision. If the value is 0 or negative, the view culling radius is used as the fMaxDistance.

Return
:the scene object. if the object is invalid, it means that the ray has hit nothing.
Parameters
  • sFnctFilter: it can be any of the following string or a number string “mesh”: mesh any mesh object in the scene. Usually for selection during scene editing. “cmesh”: mesh object that is clickable (associated with scripts). Usually for game playing. “notplayer”: any object in the scene except for the current player. Usually for selection during scene editing. “”: any object in the scene except. Usually for selection during scene editing. “light”: only pick light objects “biped”: any character objects :local or global. “anyobject”: any objects, including mesh and characters. but not including helper objects, such as light. “global”: all global objects, such as global character and mesh. This is usually for game mode. “point”: the returned object is invalid if there no collision with any physics faces. otherwise, one can use GetPosition function of the returned object to retrieve the intersection point. “actionmesh”: mesh with action script. number: if it is a number, it is treated as a 32 bitwise DWORD filter code. see SetPickingFilter() for more example.

int SelectObject(int nGroupIndex, float x, float y, float z, float radius, const char *sFilterFunc)

select select objects within a given region into a given group.

Return
: the total number of selected objects is returned.
Parameters
  • nGroupIndex: which group to select to. One can get the result from ParaSelection. In most cases, select to group 1; since group 0 is reserved for current selection.
  • xyzradius: a sphere in world space.
  • sFnctFilter: it can be any of the following string. “mesh”: mesh any mesh object in the scene. Usually for selection during scene editing. “cmesh”: mesh object that is clickable (associated with scripts). Usually for game playing. “notplayer”: any object in the scene except for the current player. Usually for selection during scene editing. “”: any object in the scene except. Usually for selection during scene editing. “light”: only pick light objects “biped”: any character objects :local or global. “anyobject”: any objects, including mesh and characters. but not including helper objects, such as light. “global”: all global objects, such as global character and mesh. This is usually for game mode.

int SelectObject1(int nGroupIndex, float x1, float y1, float z1, float x2, float y2, float z2, float fRotY, const char *sFilterFunc)

Parameters
  • x1y1z1x2y2z2fRotY: a bounding box: two diagonal points in world space and rotation around Y.

void RegisterEvent(const char *sID, const char *sScript)

register a mouse or key event handler

Parameters
  • sID: a string identifier of the event handler. if sID begins with “_m” it is treated as a mouse click event, except that if sID begins with “_mm” it is treated as a mouse move event. if sID begins with “_md” it is treated as a mouse down event. if sID begins with “_mu” it is treated as a mouse up event. if sID begins with “_k” it is treated as a key down event. if sID begins with “_ku” it is treated as a key up event. if sID begins with “_n” it is treated as a network event handler. Note: mouse click is rarely used, since it can be produced in NPL via mouse down move and up. However, lazy NPL programmer can still use it if they do not like to write other mouse handlers in NPL.
  • sScript: the script to be executed when the event is triggered.This is usually a function call in NPL. sScript should be in the following format “{NPL filename};{sCode};”. this is the same format in the UI event handler

void RegisterEvent1(DWORD nEventType, const char *sID, const char *sScript)

same as above RegisterEvent(), except that it allows caller to explicitly specify the event type, instead of deriving it from the event name.

Parameters
  • nEventType: any bit combination of EventHandler_type
  • sID: any unique string identifier
  • sScript: the NPL script.

void UnregisterEvent(const char *sID)

unregister a mouse or key event handler

void UnregisterAllEvent()

unregister all mouse or key event handler

void EnableMouseClick(bool bEnable)

whether the game engine will automatically generate mouse events for Game Objects.If true, The OnClick callback will be automatically called whenever there is a mouse click.

ParaObject GetCurrentActor()

get the actor that is being processed by the AI module or a script call back. The validity of the pointer is not guaranteed.

void SetCurrentActor(ParaObject pActor)

Set the actor that is being processed by the AI module or a script call back. The pointer can be NULL.

ParaObject TogglePlayer()

It changes the current player to the next player in the scene. this function is mostly for testing and game purpose. if the object has a reference object, the reference object will become the current object. return : the new current player is returned.

ParaObject GetObjectByViewBox(const object &viewbox)

get an object(usually a static mesh object) by a given view box.

Return
: return the object with the closest match with the bounding box.
Parameters
  • viewbox: One can get the view box by calling ParaObject:GetViewBox(). Or one can construct it using a table with the following field:{pos_x, pos_y,pos_z,obb_x,obb_y,obb_z,} pos_x, pos_y,pos_z: is the point at the bottom center of the box. obb_x,obb_y,obb_z: is the size of the box.

int GetActionMeshesBySphere(const object &inout, float x, float y, float z, float radius)

get the action meshes within or intersect a sphere. same as GetObjectsBySphere(..., “actionmesh”)

int GetObjectsBySphere(const object &inout, float x, float y, float z, float radius, const char *sFilterFunc)

Parameters
  • inout: input and output, it should be an empty table.
  • x: sphere center x
  • y: sphere center y
  • z: sphere center z
  • radius: sphere radius
  • sFnctFilter: it can be any of the following string. “mesh”: mesh any mesh object in the scene. Usually for selection during scene editing. “cmesh”: mesh object that is clickable (associated with scripts). Usually for game playing. “notplayer”: any object in the scene except for the current player. Usually for selection during scene editing. “”: any object in the scene except. Usually for selection during scene editing. “light”: only pick light objects “biped”: any character objects :local or global. “anyobject”: any objects, including mesh and characters. but not including helper objects, such as light. “actionmesh”: mesh with action script. “global”: all global objects, such as global character and mesh. This is usually for game mode.

int GetObjectsByScreenRect(const object &inout, int left, int top, int right, int bottom, const char *sFilterFunc, float fMaxDistance)

Get objects inside or intersect with a screen rect. screen rect is translated to a 3d cone from the camera eye position to a plane fMaxDistance away. This function is usually used for finding other static mesh objects near a certain character. please note that: objects must be completely inside the near and far planes in order to pass the test.

Return
: return the number of objects in sphere.
Parameters
  • output: list to get the result
  • lefttoprightbottom: the rect in screen space coordinates
  • sFnctFilter: it can be any of the following string. “mesh”: mesh any mesh object in the scene. Usually for selection during scene editing. “cmesh”: mesh object that is clickable (associated with scripts). Usually for game playing. “notplayer”: any object in the scene except for the current player. Usually for selection during scene editing. “”: any object in the scene except. Usually for selection during scene editing. “light”: only pick light objects “biped”: any character objects :local or global. “anyobject”: any objects, including mesh and characters. but not including helper objects, such as light. “actionmesh”: mesh with action script. “global”: all global objects, such as global character and mesh. This is usually for game mode.
  • fMaxDistance: the world unit distance inside which we will test possible candidates. if negative, it will get all visible ones.

void OnTerrainChanged(float x, float y, float fRadius)

This function is called manually to update characters in a square region. So that when the terrain heightfield is changed, the characters within the region will act accordingly, either falling down or snap to terrain surface.

Parameters
  • x: center of the terrain region being modified.
  • y: center of the terrain region being modified.
  • fRadius: : radius of the terrain region being modified.

int SaveAllCharacters()

save all local characters in the scene to the current NPC database regardless of whether they are modified or not this function is usually called manually in some very rare cases. In most cases, call SaveLocalCharacters() instead.

Return
the number of saved characters are returned.

void ShowHeadOnDisplay(bool bShow)

show or hide all scene’s objects’ head on display

bool IsHeadOnDisplayShown()

whether all scene’s objects’ head on display

int LoadNPCsByRegion(float min_x, float min_y, float min_z, float max_x, float max_y, float max_z, bool bReload)

Preload NPCs By Regions. By default NPCs are loaded on demand when the ParaTerrain.GetElevation is called.

Return
the number of NPC is returned.
Parameters
  • pOut: : the list will be filled with data in the database that meat the criterion.
  • vMin: min point in world coordinate system, y component is ignored
  • vMax: max point in world coordinate system, y component is ignored
  • bReload: if the character already exists in the scene and it is true, the character will be updated with the parameter in the database

void SetCharacterRegionPath(int slot, const std::string &path)

NOTE by andy: 2011.5.23 set character customization system region path setting allow different projects share the same CCS implementation and separate region paths for asset management

Parameters
  • slot: region slot id
  • path: new region path NOTE: path string recorded in a static map <slot, path>

void SetCharTextureSize(int nCharacterTexSize, int nCartoonFaceTexSize)

the default character skin and cartoon face texture size.

Note
: One must call SetCharRegionCoordinates afterwards to change the region accordingly.
Parameters
  • nCharacterTexSize: the character texture size. default to 256. 512 is also fine.
  • nCartoonFaceTexSize: the character texture size. default to 256. 128 is also fine.

void SetCharRegionCoordinates(int nRegionIndex, int xpos, int ypos, int xsize, int ysize)

set char region coordinates. This function together with SetCharTextureSize makes CCS regions fully customizable via scripting interface. however, the region index are predefined and can not be changed.

Parameters
  • nRegionIndex: see enumeration CharRegions. it must be smaller than NUM_REGIONS.
  • xposyposxsizeysize: see struct CharRegionCoords. defines a rect region within the skin or face texture.

void SetTimeOfDay(float time)

set time of day in seconds. Use SetDayLength() to set the total number of minutes in a day.

Parameters
  • time: time in seconds. This can be any non-negative value. (timeday_length) will be used in case time is longer than a day.

void SetTimeOfDaySTD(float time)

set standard time. see SetTimeOfDay()

Parameters
  • time: always in the range [-1,1], 0 means at noon, -1 is morning. 1 is night.

float GetTimeOfDay()

get the current time of day in seconds.

float GetTimeOfDaySTD()

get standard time. see GetTimeOfDay()

Return
: always in the range [-1,1], 0 means at noon, -1 is morning. 1 is night.

void SetMaximumAngle(float fMaxAngle)

set the maximum sun angle with the Y (up) axis.

float AdvanceTimeOfDay(float timeDelta)

advance time is in seconds, this will also change the light direction, sun color and sun ambient color. this function is automatically called by the environment simulator

void SetDayLength(float fMinutes)

set how many minutes are there in a day, this is used in time simulation. default value is 300.

float GetDayLength()

return how many minutes are there in a day in minutes

void SetShadowMethod(int nMethod)

the current shadow method:both shadow volume and shadow mapping could be set.

Parameters
  • nMethod: 0: turn off all shadow rendering: this will greatly improve performance 1: turn on shadow using shadow volume 2: turn on shadow mapping 3: turn on both shadow volume and shadow mapping

void EnableLighting(bool bEnable)

Enable both global and local lighting. Turn off lighting will greatly improve performance, such as on slower computers

void SetFog(bool bRenderFog, const char *strFogColor, float fFogStart, float fFogEnd, float fFogDensity)

set the global fog effect

Parameters
  • bRenderFog: 1 to enable fog.
  • strFogColor: a string of RGB value in the format “%f %f %f”, such as “1.0 1.0 1.0”, value must be in the range [0, 1.0].
  • fFogDensity: between (0,1)
  • fFogStart: unit in meters.
  • fFogEnd: unit in meters.

ParaScripting::ParaMiniSceneGraph GetMiniSceneGraph(const char *name)

If the mini scene graph does not exist, it will be created

int DeleteMiniSceneGraph(const char *name)

Delete mini scene graphs by name. if name is “” or “*”, all mini scene graphs will be deleted.

Return
: the number of graphs deleted is returned.

void EnableMiniSceneGraph(bool bEnable)

enable to render all mini scene graphs

bool IsMiniSceneGraphEnabled()

enable to render all mini scene graphs

ParaScripting::ParaMiniSceneGraph GetPostProcessingScene()

get the post processing mini scene graph.

Return
: this is same as GetMiniSceneGraph(“_ps”)

void EnablePostProcessing(bool bEnable, const char *sCallbackScript)

set whether post processing is enabled.

Parameters
  • bEnable: bool
  • sCallbackScript: if bEnabled is true, this is a callback script to be called per frame at which one can process scene after the main 3d scene is rendered. if this is NULL, the old callback script is used.

bool IsPostProcessingEnabled()

get whether post processing is enabled.

bool GetScreenPosFrom3DPoint(float x, float y, float z, const object &output)

Get screen 2D position(x,y) from a 3d world point.

Return
true if the point is visible in screen.
Parameters
  • xyz: in world coordinate system.
  • output: output table, containing additional info, such as {x=screen position x,y=screen position y,z= depth in the 0,1 range, visible=bool:is point is visible in camera frustum, distance=float:distance from eye to the object, }

void SetMaxRenderCount(int nRenderImportance, int nCount)

set the max number of objects to be rendered of a given render importance. One can set the render importance of any objects by setting its “RenderImportance” property

Parameters
  • nRenderImportance: the render importance to set. All objects are by default set with render importance 0.
  • nCount: the max number to set for the above render importance.

int GetMaxRenderCount(int nRenderImportance)

Get the max number of objects to be rendered of a given render importance. One can set the render importance of any objects by setting its “RenderImportance” property

Parameters
  • nRenderImportance: the render importance to set. All objects are by default set with render importance 0.
  • nCount: the max number to set for the above render importance.

class ParaSearchResult
#include <ParaScriptingIO.h>

it represents a search result.

Public Functions

bool IsValid()

check if the object is valid

void Release()

release results.

string GetRootPath()

get the root path

int GetNumOfResult()

get the total number of result found

bool AddResult(const char *sItem)

add a new item. return false if the search is completed.

string GetItem(int nIndex)

get the item at the specified index. return “” if nIndex is out of range.

object GetItemData(int nIndex, const object &output)

get the item at the specified index. return nil if nIndex is out of range.

Return
: return the field result. If field not found, output will be returned. e.g. {filename=”abc.txt”, filesize=0, fileattr=0, createdate=”1982-11-26”, writedate=””, accessdate=”“} fileattr is the value same as defined in WIN32_FIND_DATA.dwFileAttributes
Parameters
  • output: [in|out] default value.

class ParaSelection
#include <ParaScriptingWorld.h>

A pool of currently selected objects. This is a singleton class. Object may be selected into different groups. Although, there are no limit to group number, better keep it smaller than 16 groups. Selected objected may be displayed or highlighted differently. When objects are deleted from the scene. It will be deleted from the selection automatically.

Public Static Functions

void RemoveObject(const ParaObject &obj)

remove a given object in all selections.

Parameters
  • obj: pointer to the object to delete

bool RemoveUIObject(const char *sName)

remove an UI object from all selection groups.

Return
if if removed
Parameters
  • sName: UI object name

void AddObject(const ParaObject &obj, int nGroupID)

Add a new object to a given group. An object may belong to multiple groups.

Parameters
  • obj: pointer to the object to add
  • nGroupID: which group the should be added to. by default it is added to group 0. group ID must be smaller than 32.

bool AddUIObject(const char *sName, int nGroupID)

Please note that UI object in selection is automatically highlighted using the default highlighting effect.

Return
true if the object is found and highlighted(selected).
Parameters
  • sName: UI object name
  • nGroupID: which group the should be added to. by default it is added to group 0.

ParaObject GetObject(int nGroupID, int nItemIndex)

get the nItemIndex object in the nGroupID group.

Return
selected item is returned
Parameters
  • nGroupID: from which group the object is get
  • nItemIndex: the index of the item to be retrieved.

void GetObject_(ParaObject *pOut, int nGroupID, int nItemIndex)

this function shall never be called from the scripting interface. this is solely for exporting API. and should not be used from the scripting interface.

int GetItemNumInGroup(int nGroupID)

get the total number item in the given group. This function can be used with GetObject() to iterate through all objects in any group.

Return
Parameters
  • nGroupID: group ID.

void SelectGroup(int nGroupID, bool bSelect)

select the entire group.

Parameters
  • nGroupID:
  • bSelect: true to select, false to de-select.

void ClearGroup(int nGroupID)

Clear a given group so that there are no objects in it.

Parameters
  • nGroupID: ID of the group. If ID is -1, all groups will be deleted.

void SetMaxItemNumberInGroup(int nGroupID, int nMaxItemsNumber)

set the maximum number of objects in the group.

Parameters
  • nGroupID: group ID group ID must be smaller than 32.
  • nMaxItemsNumber: the number to set. default value is 1

int GetMaxItemNumberInGroup(int nGroupID)

set the maximum number of objects in the group.

Return
the maximum number in the given group
Parameters
  • nGroupID: group ID,which ID must be smaller than 32.

class ParaSeqCtrler
#include <ParaScriptingCharacter.h>

ParaSeqCtrler object: A sequence controller is a biped controller which moves the biped according to some predefined sequence. it is used to control sequence based commands of character object.

Public Functions

bool IsValid()

check if the object is valid

int GetKeyPos()

Get the current absolute playing cursor position

void SetKeyPos(int nPos)

set the current absolute playing cursor position

int GetTotalKeys()

get total key count

int AdvanceKey(int nOffset)

offset the key index according to the current play mode. i.e. it will automatically wrap to the beginning if looping.

Return
: the number of keys that have been successfully offseted. Usually if the returned value is not equal to the input value, it means that the sequence should be paused.
Parameters
  • nOffset: number of keys to advance.

void BeginAddKeys()

call the command functions(RunTo, MoveTo, etc) only between the matching pair of BeginAddKeys() and EndAddKeys()

void EndAddKeys()

call the command functions(RunTo, MoveTo, etc) only between the matching pair of BeginAddKeys() and EndAddKeys()

bool DeleteKeysRange(int nFrom, int nTo)

delete keys range

Parameters
  • nFrom: 0 based index.
  • nTo: 0 based index, if -1, it means the last one.

bool GetPlayDirection()

get the play direction.

void SetPlayDirection(bool bForward)

set the play direction.

float GetInterval()

the minimum time between two successive calls.

void SetInterval(float fInterval)

the minimum time between two successive calls.

void GetStartPos(float &x, float &y, float &z)

get the starting position.

void SetStartPos(float x, float y, float z)

set the starting position.

float GetStartFacing()

get the start facing. usually default to 0.

void SetStartFacing(float facing)

Set the start facing. usually default to 0.

int GetPlayMode()

get the current play mode

void SetPlayMode(int mode)

set the current play mode

float GetMovingTimeout()

get the number of seconds after which all move commands will be treated as finished. default value is 30 seconds.

void SetMovingTimeout(float fTimeout)

set the number of seconds after which all move commands will be treated as finished. default value is 30 seconds.

void Suspend()

suspend

void Resume()

resume

class ParaServiceLogger
#include <ParaScriptingGlobal.h>

service logger

Public Functions

void log(int level, const object &message)

log to the current logger

int GetLevel()

Returns the assigned Level

Return
Level - the assigned Level

void SetLevel(const int level1)

set level of this logger.

bool IsEnabledFor(int level)

Check whether this logger is enabled for a given Level passed as parameter.

Return
bool True if this logger is enabled for level. It just checks (level>=this->m_level)

void SetAppendMode(bool bAppendToExistingFile)

by default, append mode is enabled in server mode, and disabled in client build.

Note
: only call this function when no log is written before using the logger.

void SetLogFile(const char *sFileName)

change the log file.

Note
: only call this function when no log is written before using the logger.
Parameters
  • sFileName: such as “log/test.log”

void SetForceFlush(bool bForceFlush)

if true we will flush the new log to file immediately. otherwise, flush operation is determined by the system. default to true for client log and false for service log.

Note
: only call this function when no log is written before using the logger.

class ParaTerrain
#include <ParaScriptingTerrain.h>

Contains Terrain functions

Public Static Functions

ParaAttributeObject GetAttributeObject()

get the attribute object associated with the global terrain.

void GetAttributeObject_(ParaAttributeObject &output)

used for API exportation.

ParaAttributeObject GetBlockAttributeObject()

get block terrain manager’s attribute object.

int GetTextureCount(float x, float y)

get the total number of textures in the texture set of the terrain tile specified by a world position (x,y) One can get each of the textures by calling GetTexture() function.

void GetTexturesInCell(float x, float y, const object &out)

get all texture indices in the cell specified by point(x,y) GetTextureCount() returns all textures used by the entire terrain tile (i.e. 500*500). however, each terrain tile is further subdevided into 8*8=64 terrain cell (each cell takes up about 64*64 meters). Alpha channels of a terrain texture is only created on a per cell basis. A single alpha image (128*128) will be created for each used texture in the cell.

Parameters
  • x: in world unit
  • y: in world unit
  • out: this should be an empty table to be filled with textures in the cell, so that {[1]=tex_index, [2]=tex_index, ...}.

bool RemoveTextureInCell(float x, float y, int nIndex)

remove the given texture in the cell specified by the point(x,y).

Parameters
  • x: in world unit
  • y: in world unit
  • nIndex: Texture index in the current terrain tile. this should be smaller than the total number of textures in the texture set. see GetTextureCount().

ParaAssetObject GetTexture(float x, float y, int nIndex)

get the terrain detailed texture by index. Please note that each terrain tile contains its own texture set. the total number of textures can be returned by GetTextureCount().

Return
: The texture entity object is returned. The returned object may be invalid if nIndex is invalid.
Parameters
  • nIndex: Texture index in the current terrain tile. this should be smaller than the total number of textures in the texture set. see GetTextureCount(). there are two reserved negative index for the common and main textures -1: common texture, which is repeated several times over each terrain tile surface. -2: main texture, which is chopped and mapped to the entire terrain surface.

void GetTexture__(ParaAssetObject *pOut, float x, float y, int nIndex)

only used for API exporting.

bool ReplaceTexture(float x, float y, int nIndex, ParaAssetObject &TextureAsset)

replace the texture at the given index. or append a new texture, or delete a texture if TextureAsset or sTextureAsset is NULL.

Parameters
  • nIndex: if it is smaller than the total number of textures in the texture set. see GetTextureCount(). there are two reserved negative index for the common and main textures -1: common texture, which is repeated several times over each terrain tile surface. -2: main texture, which is chopped and mapped to the entire terrain surface.
  • sTextureAsset: filename. if nil, texture will be removed.

ParaAttributeObject GetAttributeObjectAt(float x, float y)

get the attribute object associated with the terrain tile that contains the given point.

Return
Parameters
  • x: in world unit
  • y: in world unit

void GetAttributeObjectAt_(ParaAttributeObject &output, float x, float y)

used for API exportation.

float GetElevation(float x, float y)

get the terrain height at the specified position.

Return
: the terrain height.
Parameters
  • x: position in world unit
  • y: position in world unit

DWORD GetRegionValue(const char *sLayerName, float x, float y)

get value of a given terrain region layer

Parameters
  • sLayerName: the layer name
  • x: The x location of the point on the Terrain’s surface in world units.
  • y: The y location of the point on the Terrain’s surface in world units.

DWORD GetRegionValue4(const char *sLayerName, float x, float y, const char *argb)

get value of a given terrain region layer

Parameters
  • sLayerName: the layer name
  • x: The x location of the point on the Terrain’s surface in world units.
  • y: The y location of the point on the Terrain’s surface in world units.
  • argb: it can be a string containing “argb”, where the sum of them are returned. for example, specify “r” to get only the red channel value. specify “rgb” for the sum of the grey scale image. if this is empty string “”, the 32bits color value is returned as int.

string GetTerrainOnloadScript(float x, float y)

get the on load script which created all objects on this terrain that contains the point (x,y)

const char *GetTerrainOnloadScript__(float x, float y)

solely used for API exporting. Not thread-safe

string GetTerrainElevFile(float x, float y)

get the height map file name for the terrain tile that contains the point (x,y)

const char *GetTerrainElevFile__(float x, float y)

solely used for API exporting. Not thread-safe

void SaveTerrain(bool bHeightMap, bool bTextures)

save modified terrain to disk.

Parameters
  • bHeightMap: true to save height map
  • bTextures: true to save textures: alpha maps, etc

void ReloadTerrain(bool bHeightMap, bool bTextures)

reload terrain from disk. User will lose changes since last save operation. one can UNDO changes with this function.

Parameters
  • bHeightMap: true to save height map
  • bTextures: true to save textures: alpha maps, etc

void UpdateTerrain()

update terrain. this function is called, when the user changes the terrain surface.

Parameters
  • bForceUpdate: if true it will update the terrain even if the camera does not moves.

void SnapPointToVertexGrid(float x, float y, float *vertex_x, float *vertex_y)

snap any 2D point on the height map to a vertex position on the height map. in NPL, one should write as below: local x,y = ParaTerrain.SnapPointToVertexGrid(10,10);

Parameters
  • x: arbitrary 2D point on the height map
  • y: arbitrary 2D point on the height map
  • vertex_x: [out] vertex position on the height map
  • vertex_y: [out] vertex position on the height map

float GetVertexSpacing()

Returns the number of real units between vertices in the terrain’s mesh.

void Paint(const char *detailTexture, float brushRadius, float brushIntensity, float maxIntensity, bool erase, float x, float y)

paint on the specified location of the global terrain.

Parameters
  • detailTexture: the texture entity to paint on the terrain. The texture is usually tilable such as road and grass. if this is “”, it means the base layer or layer 0. Since version 0.9.9, the base layer also has an editable alpha mask .
  • brushRadius: The width of the brush to paint with in DetailTexture layer pixels. There are typically 256 of these pixels across a TextureCell.
  • brushIntensity: The intensity with which to paint, ranging from 0.0 to 1.0. This determines how opaque the painted “splat” will be.
  • maxIntensity: The maximum intensity of the painted splat, ranging from 0.0 to 1.0, accounting for mixing with a splat that may already reside on the surface.
  • erase: Specifies whether to add the splat to the surface or remove existing splat texels already on the surface (pass false to paint and pass true to erase existing splats)
  • x: The x location of the point to paint on the Terrain’s surface in world units.
  • y: The y location of the point to paint on the Terrain’s surface in world units.

void Paint_(int nDetailTextureID, float brushRadius, float brushIntensity, float maxIntensity, bool erase, float x, float y)

See
Paint().
Parameters
  • nDetailTextureID: multi-texture layer ID, beginning from 0. Such as 0,1,2,3. -1,-2 are reserved for special terrain editor textures. -1 means the base layer.

void DigCircleFlat(float x, float y, float radius, float fFlatPercentage, float factor)

flatten a land centered at x,y, with a specified radius. Algorithm: (1) flatten a circle with radius same as fFlatPercentage*radius (2) smooth the entire region twice.

Parameters
  • x: center of the circle in world unit
  • y: center of the circle in world unit
  • radius: radius of the inner circle in world unit
  • fFlatPercentage: value is between [0,1]. fFlatPercentage*radius is the actual radius that got flattened.
  • factor: value is between [0,1]. 1 means fully transformed; 0 means nothing is changed

void Flatten(float x, float y, float radius, int flatten_op, float elevation, float factor)

Flatten the terrain both up and down to the specified elevation, using using the tightness parameter to determine how much the altered points are allowed to deviate from the specified elevation.

Parameters
  • x: center of the circle in world unit
  • y: center of the circle in world unit
  • radius: radius of the inner circle in world unit
  • flatten_op: enum FlattenOperation{ Fill_Op=0, //Flatten the terrain up to the specified elevation ShaveTop_Op=1, //Flatten the terrain down to the specified elevation Flatten_Op=2, //Flatten the terrain up and down to the specified elevation };
  • elevation: the desired height
  • factor: value is between [0,1]. 1 means fully transformed; 0 means nothing is changed

void RadialScale(float x, float y, float scale_factor, float min_dist, float max_dist, float smooth_factor)

Note: terrain data should be in normalized space with height in the range [0,1]. Picks a point and scales the surrounding terrain in a circular manner. Can be used to make all sorts of circular shapes. Still needs some work. radial_scale: pick a point (center_x, center_y) and scale the points where distance is mindist<=distance<=maxdist linearly. The formula we’ll use for a nice sloping smoothing factor is (-cos(x*3)/2)+0.5.

Parameters
  • x: center of the circle in world unit
  • y: center of the circle in world unit
  • scale_factor: height of the scaled portion in world unit. This value can be negative.

void Spherical(float x, float y, float radius, float offset)

offset in a spherical region

Parameters
  • x: center of the circle in world unit
  • y: center of the circle in world unit
  • radius: radius of the inner circle in world unit

void Roughen_Smooth(float x, float y, float radius, bool roughen, bool big_grid, float factor)

square filter for sharpening and smoothing. Use neighbour-averaging to roughen or smooth the height field. The factor determines how much of the computed roughening is actually applied to the height field. In it’s default invocation, the 4 directly neighboring squares are used to calculate the roughening. If you select big sampling grid, all 8 neighboring cells will be used.

Parameters
  • x: center of the circle in world unit
  • y: center of the circle in world unit
  • radius: radius of the inner circle in world unit
  • roughen: true for sharpening, false for smoothing.
  • big_grid: true for 8 neighboring cells, false for 4.
  • factor: value is between [0,1]. 1 means fully transformed; 0 means nothing is changed

void Ramp(float x1, float y1, float x2, float y2, float radius, float borderpercentage, float factor)

create a ramp (inclined slope) from (x1,y1) to (x2,y2). The ramp’s half width is radius. this is usually used to created a slope path connecting a high land with a low land.

Parameters
  • radius: The ramp’s half width
  • borderpercentage: borderpercentage*radius is how long the ramp boarder is to linearly interpolate with the original terrain. specify 0 for sharp ramp border.
  • factor: in range[0,1]. it is the smoothness to merge with other border heights.Specify 1.0 for a complete merge

void AddHeightField(float x, float y, const char *filename, int nSmoothPixels)

Add rectangular height field from file to the current terrain.

Parameters
  • x: center of the rect in world unit
  • y: center of the rect in world unit
  • filename: : the raw elevation or gray scale image file that contains the height field.
  • nSmoothPixels: the number of pixels to smooth from the edge of the height field. if this is 0, the original height field will be loaded unmodified. if it is greater than 0, the loaded height field will be smoothed for nSmoothPixels from the edge, where the edge is always 0.

void MergeHeightField(float x, float y, const char *filename, int mergeOperation = 0, float weight1 = 1.0, float weight2 = 1.0, int nSmoothPixels = 7)

merge a rectangular height field from file to the current terrain.

Parameters
  • x: center of the rect in world unit
  • y: center of the rect in world unit
  • filename: : the raw elevation or gray scale image file that contains the height field.
  • MergeOperation: { Addition=0, Subtract=1, Multiplication=2, Division=3, Minimum=4, Maximum=5, };
  • weight1: the destination merging weight
  • weight2: the source file merging weight
  • nSmoothPixels: the number of pixels to smooth from the edge of the height field. if this is 0, the original height field will be loaded unmodified. if it is greater than 0, the loaded height field will be smoothed for nSmoothPixels from the edge, where the edge is always 0.

void UpdateHoles(float x, float y)

Update all holes in the terrain tile that contains the input point.

Parameters
  • x: The x location of the point on the Terrain’s surface in world units.
  • y: The y location of the point on the Terrain’s surface in world units.

bool IsHole(float x, float y)

Whether the terrain contains a hole at the specified location. Currently, we allow user to load a low resolution hole maps at the beginning of terrain creation.

Return
: true if the position specified by (x,y) is inside a terrain hole
Parameters
  • x: The x location of the point on the Terrain’s surface in world units.
  • y: The y location of the point on the Terrain’s surface in world units.

void SetHole(float x, float y, bool bIsHold)

set a new terrain hole at the specified location. Currently, we will allow user to dynamically dig holes in terrain. After calling this function, the user must manually Call UpdateHoles() to inform that the holes in the terrain has been updated.

See
UpdateHoles();
Parameters
  • x: The x location of the point on the Terrain’s surface in world units.
  • y: The y location of the point on the Terrain’s surface in world units.

bool IsModified()

return true, if the terrain is modified and should be saved.

void SetContentModified(float x, float y, bool bIsModified)

set the content of the terrain modified. the terrain is specified by a 2D point. the on load script will be rebuilt once saving the terrain.

Parameters
  • x: a position on the terrain where content is changed.
  • y: a position on the terrain where content is changed.
  • bIsModified: true to set modified.

void SetContentModified4(float x, float y, bool bIsModified, DWORD dwModifiedBits)

set the content of the terrain modified. the terrain is specified by a 2D point. the on load script will be rebuilt once saving the terrain.

Parameters
  • bIsModified: true to set modified.
  • dwModifiedBits: this is any combination of TERRAIN_MODIFIED_BITS. Default value is MODIFIED_ON_LOAD_SCRIPT (16) enum TERRAIN_MODIFIED_BITS { MODIFIED_NONE = 0, detailed terrain texture(with mask) has been modified. MODIFIED_TEXTURE = 0x1, height map has modified MODIFIED_HEIGHTMAP = 0x1<<1, configuration such as base texture, common file, holes, etc has been modified. MODIFIED_CONFIGURATION = 0x1<<2, holes have been changed. this should mean the same thing as MODIFIED_CONFIGURATION MODIFIED_HOLES = 0x1<<3, if static objects have been modified, so that we will need to update the on load script MODIFIED_ON_LOAD_SCRIPT = 0x1<<4, MODIFIED_ALL = 0xffff };

void SetAllLoadedModified(bool bIsModified, DWORD dwModifiedBits)

set all loaded terrain tile content modified. This is the refered way to perform a save all operation

void EnableLighting(bool bEnable)

Enable both global and local lighting. Turn off lighting will greatly improve performance, such as on slower computers

bool RegisterBlockTemplate(uint16_t templateId, const object &params)

Parameters
  • params: it can be attFlag of int type.

object GetBlocksInRegion(int32_t startChunkX, int32_t startChunkY, int32_t startChunkZ, int32_t endChunkX, int32_t endChunkY, int32_t endChunkZ, uint32_t matchType, const object &result)

get block in [startChunk,endChunk]

Return
{count,x{},y{},z{},tempId{}}
Parameters
  • startChunkYendChunkY: if negative, and startChunkY == endChunkY, -startChunkY will be used as verticalSectionFilter(a bitwise filter).

void SelectBlock(uint16_t x, uint16_t y, uint16_t z, bool isSelect)

add/remove block to/from highlight block list

Parameters
  • xyz: world space block id;
  • isSelect: : true to select block, false to de-select block
  • nGroupID: group id. 0 for highlight 1 for wireframe.

void DeselectAllBlock1(int nGroupID)

Parameters
  • nGroupID: 0 for animated selection, 1 for wire frame selection. -1 for all

int FindFirstBlock(uint16_t x, uint16_t y, uint16_t z, uint16_t nSide = 4, uint32_t max_dist = 32, uint32_t attrFilter = 0xffffffff, int nCategoryID = -1)

find a block in the side direction that matched filter from block(x,y,z) this function can be used to check for free space upward or download

Return
-1 if not found. otherwise distance to the first block that match in the side direction is returned.
Parameters
  • side: 4 is top. 5 is bottom.
  • attrFilter: attribute to match. 0 means air. default to any block
  • nCategoryID: -1 means any category_id. default to -1

int GetFirstBlock(uint16_t x, uint16_t y, uint16_t z, int nBlockId, uint16_t nSide = 4, uint32_t max_dist = 32)

get the y pos of the first block of nBlockID, start searching from x, y, z in the side direction

int32_t GetChunkColumnTimeStamp(uint32_t chunkX, uint32_t chunkZ)

get the time stamp of for the given chunk column 0 means not available, >1 means loaded before

void SetChunkColumnTimeStamp(uint32_t chunkX, uint32_t chunkZ, uint32_t nTimeStamp)

set chunk column time stamp. usually 0 for non-generated. 1 for generated. this is usually called by world generators, so that we will not generate again next time we load the world.

const std::string &GetMapChunkData(uint32_t chunkX, uint32_t chunkZ, bool bIncludeInit, uint32_t verticalSectionFilter)

Parameters
  • verticalSectionFilter: default to 0xffff. each bit is for one of the 16 vertical sections.

class ParaUI
#include <ParaScriptingGUI.h>

ParaUI namespace contains a list of HAPI functions to create user interface controls, such as windows, buttons, as well as event triggers. The main difference between the two is that (1) 2D GUI object are not tested against view frustum, instead its controlled by visibility tag automatically or through user input. (2) 2D GUI object generally does not obey the physical law of 3D world. (3) GUI object are generally specified by screen coordinates, instead of 3D position. (4) GUI object may be frequently created and discarded. If a object is discarded, so will its child objects. E.g. if one delete a window, all buttons, sensors, etc attach to it will also be discarded.

Public Static Functions

void PlaySound(const char *strSoundAssetName, bool bLoop)

Play a sound file

Parameters
  • strObjectName: the sound object name

void StopSound(const char *strSoundAssetName)

stop playing a sound file. one can use this function to stop playing looping sound such as a background music.

Parameters
  • strObjectName: the sound object name

void Destroy(const char *strObjectName)

delete a GUI object as well as all its child objects, by it name. If there are several objects who have the same id, only the last attached one is deleted.

Parameters
  • strObjectName: the object name

void Destroy1(int nID)

delete a GUI object as well as all its child objects, by it name. If there are several objects who have the same id, only the last attached one is deleted.

Parameters
  • nID: id.

void DestroyUIObject(ParaUIObject &obj)

destroy an UI object

void PostDestroy(const char *strObjectName)

delete at the end of frame.

ParaUIObject GetUIObject_any(const object &NameOrID)

Get GUI object by name or ID

Parameters
  • NameOrID: if it is string, we will get the first GUI object that matches the name. If name is “root”, the root object is returned. if it is number , we will get the object by its ID. NameOrID is then the id property value or result of GetID() from a UI object. If this is 0, the root object is returned.

ParaUIObject GetUIObjectAtPoint(int x, int y)

Get the first GUI object at the given coordinates x: x coordinate y: y coordinate

void GetMousePosition(float &x, float &y)

get the current mouse position. e.g. local x,y = ParaUI.GetMousePosition();

Parameters
  • &x: screen x
  • &y: screen y

ParaUIObject CreateUIObject(const char *strType, const char *strObjectName, const char *alignment, int x, int y, int width, int height)

Create a GUI object based on the default template object. All default template object is defined in “script/config.lua”, which will be loaded when GUI engine is loaded. One can change template object at runtime by GetDefaultObject(). the layout is given below: _lt _mt _rt _ml _ct _mr _lb _mb _rb

See
GetDefaultObject() Although it is possible to create many objects with the same name, we do not advice you to do so.
Remark
: we design _m? alignment types. _mt: x is coordinate from the left. y is coordinate from the top, width is the coordinate from the right and height is the height _mb: x is coordinate from the left. y is coordinate from the bottom, width is the coordinate from the right and height is the height _ml: x is coordinate from the left. y is coordinate from the top, width is the width and height is the coordinate from the bottom _mr: x is coordinate from the right. y is coordinate from the top, width is the width and height is the coordinate from the bottom
Parameters
  • strType: type of the new object. It can be “container”, “button”, “scrollbar”, “editbox”, “imeeditbox”,”slider”, “video”, “3dcanvas”, “listbox”, “painter” and “text”. “container” is the only type of control that can contain other objects
  • strObjectName: the new object’s name
  • alignment: can be one of the following strings or nil or left out entirely:
    • “_lt” align to left top of the screen
    • “_lb” align to left bottom of the screen
    • “_ct” align to center of the screen
    • “_ctt”: align to center top of the screen
    • “_ctb”: align to center bottom of the screen
    • “_ctl”: align to center left of the screen
    • “_ctr”: align to center right of the screen
    • “_rt” align to right top of the screen
    • “_rb” align to right bottom of the screen
    • “_mt”: align to middle top
    • “_ml”: align to middle left
    • “_mr”: align to middle right
    • “_mb”: align to middle bottom
    • “_fi”: align to left top and right bottom. This is like fill in the parent window.
Parameters
  • x: screen coordinate x, for _m? alignments, the meaning is different, see remark
  • y: screen coordinate y, for _m? alignments, the meaning is different, see remark
  • width: screen coordinate width or right, depending on alignment mode, for _m? alignments, the meaning is different, see remark
  • height: screen coordinate height or bottom, depending on alignment mode, for _m? alignments, the meaning is different, see remark

ParaScripting::ParaUIObject GetTopLevelControl()

get the top level control at level 0

ParaUIObject GetDefaultObject(const char *strType)

get the default template object from which all sub-sequent controls of the same type are cloned(created). one can modify the template object at runtime to change of the theme of all controls created subsequently. All default template object is defined in “script/config.lua”, which will be loaded when GUI engine is loaded

Return
the template object is returned.
Parameters
  • strType: It can be “container”, “button”, “scrollbar”, “editbox”, “imeeditbox”,”slider” and “text”.

void SetCursorFont(const char *fontname, const char *strColor, DWORD transparency)

@ obsoleted. Set Mouse Cursor appearance

void SetCursorTexture(const char *texturename, const char *strColor, DWORD transparency)

. Set Mouse Cursor appearance

void SetCursorText(const char *strText)

. Set Mouse Cursor appearance

void SetCursorFromFile(const char *szCursor, int XHotSpot, int YHotSpot)

Set the current cursor to use. One can call very often, since it will does nothing with identical cursor file and hot spot. Typically, hardware supports only 32x32 cursors and, when windowed, the system might support only 32x32 cursors.

Parameters
  • szCursor: cursor file name: The contents of this texture will be copied and potentially format-converted into an internal buffer from which the cursor is displayed. The dimensions of this surface must be less than the dimensions of the display mode, and must be a power of two in each direction, although not necessarily the same power of two. The alpha channel must be either 0.0 or 1.0.
  • XHotSpot: [in] X-coordinate offset (in pixels) that marks the center of the cursor. The offset is relative to the upper-left corner of the cursor. When the cursor is given a new position, the image is drawn at an offset from this new position determined by subtracting the hot spot coordinates from the position.
  • YHotSpot: [in] Y-coordinate offset (in pixels) that marks the center of the cursor. The offset is relative to the upper-left corner of the cursor. When the cursor is given a new position, the image is drawn at an offset from this new position determined by subtracting the hot spot coordinates from the position.

void SetCursorFromFile_(const char *szCursor)

same as above, with hot spot (0,0)

void SetUseSystemCursor(bool bUseSystem)

whether to use system cursor. If this is true, d3d hardware cursor is not shown, even you have loaded an cursor icon using SetCursorFromFile.

bool GetUseSystemCursor()

get whether to use system cursor

string ToScript()

to NPL script.

bool SaveLayout(const char *filename)

save current layout to file

Return
Parameters
  • *filename:

void SetDesignTime(bool bDesign)

whether to enable edit mode for all controls.

Parameters
  • bDesign:

void ShowCursor(bool bShow)

show cursor

Parameters
  • bShow:

void LockMouse(bool bLock)

Lock Mouse so that mouse move will not change the mouse position. this is useful when user is changing camera view during mouse drag operation.

Parameters
  • bLock: true to lock

bool IsMouseLocked()

check whether Mouse is locked. When mouse is locked, mouse move will not change the mouse position. this is useful when user is changing camera view during mouse drag operation.

void ResetUI()

clear all UI objects.

void SetIMEOpenStatus(bool bOpen)

This function opens or closes the IME programmtically. In most cases, we should never programmatically open or closes IME, instead the user usually pressed Ctrl+Space to change it. however, in some rare cases, such as we are opening a windowed mode flash window, and wants to disable IME programmatically.

Parameters
  • bOpen: true to open.

bool GetIMEOpenStatus()

Check if IME status is opened.

void SetUIScale(float fScalingX, float fScalingY)

set the UI scaling. This can be useful to render 1024*768 to a 800*600 surface; we can set to fScalingX to 800/1024 and fScalingY to 600/768 calling this function will cause OnSize() and UpdateBackbufferSize() to be called.

Parameters
  • fScalingX: x defaults to 1.0
  • fScalingY: y defaults to 1.0

void SetMinimumScreenSize(int nWidth, int nHeight, bool bAutoUIScaling)

the minimum screen size. if the backbuffer is smaller than this, we will use automatically use UI scaling for example, if minimum width is 1024, and backbuffer it 800, then m_fUIScalingX will be automatically set to 1024/800.

Parameters
  • nWidth: the new width.
  • nHeight: the new height.
  • bAutoUIScaling: usually set to true. whether we will automatically recalculate the UI scaling accordingly with regard to current backbuffer size.

void AddDragReceiver(const char *sName)

add an receiver to the current receiver list during an drag operation. call this function on an dragable UI object’s Begin Drag event handler.

Parameters
  • sName: name. if this is “root”, the dragging object can always to reattached.

void SetToolTipBehavior(const char *behavior)

How tooltip is displayed

Parameters
  • behavior: “normal” or “flashing”. default is “normal”

bool SetHighlightParam(const char *szEffectName, const char *szParamName, const char *szParamValue)

Set Highlight Param. this is usually called in the start up configuration file.

Return
Parameters
  • szEffectName:
  • szParamName:
  • szParamValue:

class ParaUIFont
#include <ParaScriptingGraphics.h>

a GUI font object

Class Properties
  • (“transparency”,&ParaUIFont::GetTransparency,&ParaUIFont::SetTransparency)
  • (“color”,&ParaUIFont::GetColor,&ParaUIFont::SetColor)
  • (“font”,&ParaUIFont::GetFont,&ParaUIFont::SetFont)
  • (“format”,&ParaUIFont::GetFormat,&ParaUIFont::SetFormat),

Public Functions

bool IsValid()

check if the object is valid

void SetFormat(DWORD format)

Set the text align and other text displaying formats

Parameters
  • dwFormat: the new format. It can be any combination of the following values. DT_BOTTOM (0x00000008) Justifies the text to the bottom of the rectangle. This value must be combined with DT_SINGLELINE. DT_CALCRECT (0x00000400) Determines the width and height of the rectangle. If there are multiple lines of text, ID3DXFont::DrawText uses the width of the rectangle pointed to by the pRect parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, ID3DXFont::DrawText modifies the right side of the rectangle so that it bounds the last character in the line. In either case, ID3DXFont::DrawText returns the height of the formatted text but does not draw the text. DT_CENTER (0x00000001) Centers text horizontally in the rectangle. DT_EXPANDTABS (0x00000040) Expands tab characters. The default number of characters per tab is eight. DT_LEFT (0x00000000) Aligns text to the left. DT_NOCLIP (0x00000100) Draws without clipping. ID3DXFont::DrawText is somewhat faster when DT_NOCLIP is used. DT_RIGHT (0x00000002) Aligns text to the right. DT_RTLREADING Displays text in right-to-left reading order for bi-directional text when a Hebrew or Arabic font is selected. The default reading order for all text is left-to-right. DT_SINGLELINE (0x00000020) Displays text on a single line only. Carriage returns and line feeds do not break the line. DT_TOP (0x00000000) Top-justifies text. DT_VCENTER (0x00000004) Centers text vertically (single line only). DT_WORDBREAK (0x00000010) Breaks words. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by the pRect parameter. A carriage return/line feed sequence also breaks the line.

class ParaUIObject
#include <ParaScriptingGUI.h>

it represents a GUI object.

  • (“text”,&ParaUIObject::GetText,&ParaUIObject::SetText1)
  • (“id”,&ParaUIObject::GetID,&ParaUIObject::SetID)
  • (“PasswordChar”,&ParaUIObject::GetPasswordChar,&ParaUIObject::SetPasswordChar)
  • (“name”,&ParaUIObject::GetName,&ParaUIObject::SetName)
  • (“enabled”,&ParaUIObject::GetEnabled,&ParaUIObject::SetEnabled)
  • (“highlightstyle”,&ParaUIObject::GetHighlightStyle,&ParaUIObject::SetHighlightStyle)
  • (“autosize”,&ParaUIObject::GetAutoSize,&ParaUIObject::SetAutoSize)
  • (“visible”,&ParaUIObject::GetVisible,&ParaUIObject::SetVisible)
  • (“candrag”,&ParaUIObject::GetCanDrag,&ParaUIObject::SetCanDrag)
  • (“scrollable”,&ParaUIObject::GetScrollable,&ParaUIObject::SetScrollable)
  • (“readonly”,&ParaUIObject::GetReadOnly,&ParaUIObject::SetReadOnly)
  • (“position”,&ParaUIObject::GetPosition,&ParaUIObject::SetPosition)
  • (“parent”,&ParaUIObject::GetParent,&ParaUIObject::SetParent)
  • (“background”,&ParaUIObject::GetBGImage,&ParaUIObject::SetBGImage1)
  • (“color”,&ParaUIObject::GetColor,&ParaUIObject::SetColor)
  • (“button”,&ParaUIObject::GetBtnImage,&ParaUIObject::SetBtnImage1)
  • (“font”,&ParaUIObject::GetFontString,&ParaUIObject::SetFontString1)
  • (“type”,&ParaUIObject::GetType)
  • (“shadow”,&ParaUIObject::GetUseTextShadow,&ParaUIObject::SetUseTextShadow)
  • (“textscale”,&ParaUIObject::GetTextScale,&ParaUIObject::SetTextScale)
  • (“script”,&ParaUIObject::ToScript)
  • (“ismodified”,&ParaUIObject::IsModified)
  • (“animstyle”,&ParaUIObject::GetAnimationStyle,&ParaUIObject::SetAnimationStyle)
  • (“receivedrag”,&ParaUIObject::GetReceiveDrag,&ParaUIObject::SetReceiveDrag)
  • (“wordbreak”,&ParaUIObject::GetWordbreak,&ParaUIObject::SetWordbreak)
  • (“itemheight”,&ParaUIObject::GetItemHeight,&ParaUIObject::SetItemHeight)
  • (“multiselect”,&ParaUIObject::GetMultipleSelect,&ParaUIObject::SetMultipleSelect)
  • (“tooltip”,&ParaUIObject::GetToolTip,&ParaUIObject::SetToolTip)
  • (“scrollbarwidth”,&ParaUIObject::GetScrollbarWidth,&ParaUIObject::SetScrollbarWidth)
  • (“fastrender”,&ParaUIObject::GetFastRender,&ParaUIObject::SetFastRender)
  • (“lifetime”,&ParaUIObject::GetLifeTime,&ParaUIObject::SetLifeTime)
  • (“zdepth”,&ParaUIObject::GetZDepth,&ParaUIObject::SetZDepth)
  • (“value”,&ParaUIObject::GetValue,&ParaUIObject::SetValue)
  • (“fixedthumb”,&ParaUIObject::GetFixedThumb,&ParaUIObject::SetFixedThumb)
  • (“thumbsize”,&ParaUIObject::GetThumbSize,&ParaUIObject::SetThumbSize)
  • (“tooltip”,&ParaUIObject::GetToolTip,&ParaUIObject::SetToolTip)
  • (“canvasindex”,&ParaUIObject::GetCanvasIndex,&ParaUIObject::SetCanvasIndex)
  • (“zorder”,&ParaUIObject::GetZOrder,&ParaUIObject::SetZOrder)
  • (“x”,&ParaUIObject::GetX,&ParaUIObject::SetX)
  • (“y”,&ParaUIObject::GetY,&ParaUIObject::SetY)
  • (“depth”,&ParaUIObject::GetDepth,&ParaUIObject::SetDepth)
  • (“width”,&ParaUIObject::Width,&ParaUIObject::SetWidth)
  • (“height”,&ParaUIObject::Height,&ParaUIObject::SetHeight)
  • (“rotation”,&ParaUIObject::GetRotation,&ParaUIObject::SetRotation)
  • (“scalingx”,&ParaUIObject::GetScalingX,&ParaUIObject::SetScalingX)
  • (“scalingy”,&ParaUIObject::GetScalingY,&ParaUIObject::SetScalingY)
  • (“translationx”,&ParaUIObject::GetTranslationX,&ParaUIObject::SetTranslationX)
  • (“translationy”,&ParaUIObject::GetTranslationY,&ParaUIObject::SetTranslationY)
  • (“colormask”,&ParaUIObject::GetColorMask,&ParaUIObject::SetColorMask)
  • (“spacing”,&ParaUIObject::GetSpacing,&ParaUIObject::SetSpacing)
  • (“popup”,&ParaUIObject::GetPopUp,&ParaUIObject::SetPopUp)
  • (“onframemove”,&ParaUIObject::GetOnFrameMove,&ParaUIObject::OnFrameMove)
  • (“onclick”,&ParaUIObject::GetOnClick,&ParaUIObject::OnClick)
  • (“onchange”,&ParaUIObject::GetOnChange,&ParaUIObject::OnChange)
  • (“onkeydown”,&ParaUIObject::GetOnKeyDown,&ParaUIObject::OnKeyDown)
  • (“onkeyup”,&ParaUIObject::GetOnKeyUp,&ParaUIObject::OnKeyUp)
  • (“ondoubleclick”,&ParaUIObject::GetOnDoubleClick,&ParaUIObject::OnDoubleClick)
  • (“ondragbegin”,&ParaUIObject::GetOnDragBegin,&ParaUIObject::OnDragBegin)
  • (“ondragend”,&ParaUIObject::GetOnDragEnd,&ParaUIObject::OnDragEnd)
  • (“ondragmove”,&ParaUIObject::GetOnDragOver,&ParaUIObject::OnDragOver)
  • (“onmousedown”,&ParaUIObject::GetOnMouseDown,&ParaUIObject::OnMouseDown)
  • (“onmouseup”,&ParaUIObject::GetOnMouseUp,&ParaUIObject::OnMouseUp)
  • (“onmousemove”,&ParaUIObject::GetOnMouseMove,&ParaUIObject::OnMouseMove)
  • (“onmousewheel”,&ParaUIObject::GetOnMouseWheel,&ParaUIObject::OnMouseWheel)
  • (“onmousehover”,&ParaUIObject::GetOnMouseHover,&ParaUIObject::OnMouseHover)
  • (“onmouseenter”,&ParaUIObject::GetOnMouseEnter,&ParaUIObject::OnMouseEnter)
  • (“onmouseleave”,&ParaUIObject::GetOnMouseLeave,&ParaUIObject::OnMouseLeave)
  • (“onselect”,&ParaUIObject::GetOnSelect,&ParaUIObject::OnSelect)
  • (“onmodify”,&ParaUIObject::GetOnModify,&ParaUIObject::OnModify)
  • (“ondestroy”,&ParaUIObject::GetOnDestroy,&ParaUIObject::OnDestroy)
  • (“onsize”,&ParaUIObject::GetOnSize,&ParaUIObject::OnSize)
Class Properties

Public Functions

bool IsValid() const

check if the object is valid

Return
: true is the object is a valid GUI object.

void AddChild(ParaUIObject pChild)

Attach a child GUI object to this object This function is only for container objects;

Parameters
  • pChild: the child object to be attached

ParaAttributeObject GetAttributeObject()

get the attribute object associated with an object.

void GetAttributeObject_(ParaAttributeObject &output)

for API exportation

void AddTextItem(const char *text)

Add a text item for listbox

Parameters
  • text: the text string to be added.

void AttachToRoot()

Attach this object to the root of the screen GUI.

string GetName() const

Get the name of this object

ParaUIObject GetChild(const char *name)

get child by name

ParaUIObject GetChildAt(int index)

get child by index.Index start from 0. Use GetChildCount() for total child count.

int GetChildCount()

get the total number of child UI objects.

int GetID() const

get id of this object. please note that this is a child id, not a globally unique id. the id is only available when this object is attached to a parent. And the ID will change if this object changes its parent. In all other circumstances, the id uniquely identify this object in its parent. One can call GetChildByID() from its parent control to get this object. Note: ID is assigned by its parent when this control is attached to a parent control (or parent changes) it ensures that ChildID is unique among all sibling children of the parent control during the lifetime of the parent.

void SetID(int nID)

this function is used internally. never call this unless you known why.

ParaScripting::ParaUIObject GetChildByID(int nChildID)

get a child node by its id

Return
: return the child object found. it may return invalid object if not found.
Parameters
  • nChildID: child ID usually obtained by GetID() method.

ParaScripting::ParaUIObject GetChildByName(const char *name)

get the first child node whose name is name. Since a name may not be unique among its sibling children. One is advised to use GetChildByID() instead.

Return
: return the child object found. it may return invalid object if not found.
Parameters
  • name: child name usually obtained by GetName() method.

void SetEnabled(bool bEnabled)

Set if a control is enabled

Parameters
  • bEnabled: the new value

void SetUseTextShadow(bool bUseTextShadow)

Set/Get whether the use text shadow

void SetTextScale(float fScale)

set the text scale the text scale, default to 1.f. if we have text scale between 1.1-1.5 and shadow to true, the text will have an alpha border. This is great for rendering text in 3d scene with a boarder using just normal system font.

float GetTextScale()

get the text scale the text scale, default to 1.f. if we have text scale between 1.1-1.5 and shadow to true, the text will have an alpha border. This is great for rendering text in 3d scene with a boarder using just normal system font.

string GetColor() const

Get the UI control color for the current state.

void SetColor(const char *strColor)

set the UI control color for the current state.

Parameters
  • strColor:"255: 0 0” or “255 0 0 128”

void SetZDepth(float fDepth)

set z depth in the range [0,1], where 0 is closest to screen. if this is -1(default), zdepth is automatically determined. Otherwise it will force the z depth.

float GetZDepth()

get z depth

void SetAutoSize(bool bAutosize)

Set if a control is auto resize

Parameters
  • bAutosize: the new value

void GetTextLineSize(int *width, int *height)

get the text line size in pixels, supposing the current font and text will be rendered in a single line.

void SetVisible(bool bVisible)

Set if a control is visible

Parameters
  • bVisible: the new value

void SetReceiveDrag(bool bReceiveDrag)

Get the resource of this control

luabind::object GetField(const char *sFieldname, const object &output)

get field by name.

void SetField(const char *sFieldname, const object &input)

set field by name

Parameters
  • sFieldname: field name
  • input: input value. if field type is vectorN, input is a table with N items.

void CallField(const char *sFieldname)

call field by name. This function is only valid when The field type is void. It simply calls the function associated with the field name.

void SetDefault(bool bDefaultButton)

set as the default button of the container. please note each container can only have one default button. so as one set a default button, it will automatically unset old default button in the parent container. when enter key is pressed in an edit box, the default button will be clicked.

void SetLifeTime(int nSeconds)

Set a count down timer in frames. when it is zero, the object will be automatically deleted If LifeTime is negative, the object will be permanent.

Parameters
  • nSeconds: how many seconds the window left to be alive.

int GetLifeTime() const

Get a count down timer in frames. when it is zero, the object will be automatically deleted If LifeTime is negative, the object will be permanent.

Return
: return how many seconds the window left to be alive.

string GetText() const

Get text of a control;

void SetText3(const char *strText, const char *strColor, const char *strFontAssetName)

Show text in the window. The text will fill the entire window. If one want to position text in a window, it must create another window to contain the text, then use the window to position the text.

Parameters
  • strText: text to display (must be in utf8)
  • strColor: color of the object. such as “255 255 255”.
  • strFontAssetName: the font asset name, it can be “”, in which case the default font will be used.

void SetTextAutoTranslate(const char *strText, const char *sConverter)

basically this is the same as the SetText method, except that it will automatically translate the text from one language to another. please note that this method does not solve all localization problems, but it allows for quick machine translation .

Parameters
  • strText: utf8 encoded text
  • sConverter: it should be one of the supported converter name. a most common usage is “c_S2T” where simplified Chinese character is translated to traditional Chinese. The asset file “locale/c_simpl_to_trad.txt” is used.

void SetPasswordChar(string PasswordChar)

this function is only supported in the “editbox” control, not the “text” or “IMEEditbox” The PasswordChar property specifies the character displayed in the edit box. For example, if you want asterisks displayed in the password box, specify * for the PasswordChar property in the Properties window. Then, regardless of what character a user types in the text box, an asterisk is displayed.

Remark
: Security Note: Using the PasswordChar property on a text box can help ensure that other people will not be able to determine a user’s password if they observe the user entering it. This security measure does not cover any sort of storage or transmission of the password that can occur due to your application logic. Because the text entered is not encrypted in any way, you should treat it as you would any other confidential data. Even though it does not appear as such, the password is still being treated as a plain-text string (unless you have implemented some additional security measure).
Parameters
  • PasswordChar: such as ‘*’

string GetPasswordChar() const

get password char

void SetTopLevel(bool value)

Set a container to be a top-level control or set a top-level control back to normal container.

void SetBGImage1(const object &szBackground)

set the background image of the control.

Note
: GUI also supports texture bound with dynamic width and height. such as “Texture/anyfile.dds;0 0 -1 -1”, where -1 is replaced with the dynamic width or height when needed. This is specially useful for specifying width and height of a HTTP remote texture where the dimension is not known immediately. things in [] are optional input;if not specified, the rectangle contains the whole picture;
Parameters
  • szBackground: the texture asset file name with the rectangle information the format of szBackground is filename[; left top width height][:left top toright to bottom]. if it is “” or width or height is zero, the texture is not drawn or is fully transparent. e.g. “texture/whitedot.png”, “texture/whitedot.png;0 0 64 64”, “texture/whitedot.png:10 10 10 10”, “texture/whitedot.png;0 0 64 64;10 10 10 10” [:left top toright to bottom] is used to specify the inner rect of the center tile in a nine texture element UI object

void SetBGImageStr(const char *szBackground)

szBackground can be filename[; left top width height][:left top toright to bottom], such as “texture/whitedot.png”, “texture/whitedot.png;0 0 64 64”, “texture/whitedot.png:10 10 10 10”, “texture/whitedot.png;0 0 64 64;10 10 10 10” [:left top toright to bottom] is used to specify the inner rect of the center tile in a nine texture element UI object

void SetNineElementBG(const char *TextFilename, int left, int top, int toRight, int toBottom)

drawing the background using nine element.

Note
: Right now, this is only valid on container, but we will support it for all other controll.
Parameters
  • TextFilename: the background texture to use. it will be divided into 3x3 tiles when drawing the control
  • lefttoptoRighttoBottom: the inner tile position relative to the dimension of TextFilename texture. If all are 0, it will be set back to one element background

int GetFirstVisibleCharIndex()

this method is only valid if the control is edit box or imeedit box if the text is longer than the edit box, the returned value is the index of the first visible character in the edit box Normally, this is 0 if the text can be fully contained in the edit box.

int GetCaretPosition()

return Caret position in characters

void SetCaretPosition(int nCharacterPos)

Set Caret position in characters

Parameters
  • nCharacterPos: in characters

int GetTextSize()

return the text size in Unicode character count.

void GetPriorWordPos(int nCP, int PriorIn, int &Prior)

get the prior word position

void GetNextWordPos(int nCP, int NextIn, int &Next)

get the next word position

void CPtoXY(int nCP, bool bTrail, int XIn, int YIn, int &X, int &Y)

Character position to X,Y in pixel

void XYtoCP(int nX, int nY, int CPIn, int nTrailIn, int &CP, int &nTrail)

X,Y in pixel to character position

void SetPageSize(int pagesize)

Get the page size of the scroll bar Page size is the size of how many items a page contains. The control will scroll a page size if we click on the empty space of the track of the scroll bar

void SetStep(int nDelta)

how many pixels to scroll each step

int GetStep()

how many pixels to scroll each step

void SetTrackRange(int nBegin, int nEnd)

set the page size of a container or a scroll bar

Parameters
  • nBegin: the start value of the range
  • nEnd: the end value of the range

int GetAnimationStyle() const

get the animation style of this object. Different GUI object may have different style definitions. for “button” object: 1 is gradually enlarge 5% when getting focus.2 is 10%, 3 is 15%, 4 is 20%, 5 is 25%

Return
: 0 always means no animation. 1 is gradually enlarge 5% when getting focus.2 is 10%, 3 is 15%, 4 is 20%, 5 is 25% 11-15 means the same as 1-5, except that the normal state alpha is the same as the highlighted state. 21-25 means the same as 11-15, except that the button animation will not stop in the highlighted state. 31-39 is clock-wise rotation, the larger the faster 41-49 is counter-clock-wise rotation, the larger the faster

void SetAnimationStyle(int nStyle)

set the animation style of this object. Different GUI object may have different style definitions. for “button” object: 1 is gradually enlarge 5% when getting focus.2 is 10%, 3 is 15%, 4 is 20%, 5 is 25%

Parameters
  • nStyle: 0 always means no animation. 1 is gradually enlarge 5% when getting focus.2 is 10%, 3 is 15%, 4 is 20%, 5 is 25% 11-15 means the same as 1-5, except that the normal state alpha is the same as the highlighted state. 21-25 means the same as 11-15, except that the button animation will not stop in the highlighted state. 31-39 is clock-wise rotation, the larger the faster 41-49 is counter-clock-wise rotation, the larger the faster

void SetScrollable(bool bScrollable)

Set if a container is scrollable

Parameters
  • bScrollable: the new scrollable value

void GetAbsPosition(float &x, float &y, float &width, float &height, float &z) const

get the absolute position of the control in screen coordinate e.g. local x,y = obj:GetAbsPosition();

Parameters
  • &x: screen x
  • &y: screen y
  • &width: width
  • &height: height
  • &z: depth, usually not used

void SetPosition(const char *pos)

set rect position of the control.

Parameters
  • pos: in format “x y width height”

string GetPosition() const

get rect position of the control

void Reposition(const char *alignment, int left, int top, int width, int height)

reposition the control using the same parameter definition used when control is created. see ParaUI::CreateUIObject() for parameter definition.

int GetValue() const

Gets and Sets the value of a control Controls that have value are CGUIScrollBar, CGUISlider

void OnClick(const object &strScriptName)

When the user clicked on the window, the script file or function will be activated. The following parameters are passed as global variables. id = int; the id of the triggering GUI window mouse_button = [“left”|”right”|”middle”]; mouse_x = number; mouse_y = number;

Parameters
  • strScriptName: the NPL script file to activate.

void OnSize(const object &strScriptName)

called when the size of the window is changed. id = int; the id of the triggering GUI window

void OnDestroy(const object &strScriptName)

called when the window is destroyed. Please note that GetUIObject() will return invalid object.

void OnActivate(const object &strScriptName)

The framework calls this member function when a window is being activated or deactivated. id = int; the id of the triggering GUI window param1: Specifies whether the window is being activated or deactivated. It can be one of the following values:

  • 0 The window is being deactivated.
  • 1 The window is being activated by a mouse click.
  • 2 The window is being activated through some method other than a mouse click.

void OnDoubleClick(const object &strScriptName)

The following parameters are passed as global variables. id = int; the id of the triggering GUI window mouse_button = [“left”|”right”|”middle”]; mouse_x = number; mouse_y = number;

Parameters
  • strScriptName:

void OnKeyDown(const object &strScriptName)

When the user pressed a key while the mouse cursor is inside the window, a script file or function will be activated. The following parameters are passed as global variables. id = int; the id of the triggering GUI window keystring = string;it is filled with the key character. e.g. “\r”, “a”, etc. It may contain multiple characters, if the user is typing fast or Multi-byte such as Chinese Character is entered.

Parameters
  • strScriptName: the NPL script file to activate.

void SetCursor(const object &szCursorFile)

Set/Get cursor file when mouse is over it. If empty, the parent cursor file is used.

void SetCursorEx(const char *szCursorFile, int nHotSpotX, int nHotSpotY)

Set cursor by file and hot spot.

void OnChange(const object &strScriptName)

usually the editbox will call this handle, “virtual_key” contains the last key stroke. Usually application may check if it is an enter key for special actions.

void SetRotation(float fRot)

set the rotation of the control around the center of the UI plus rotation origin offset. it only affects the drawing rect but not the mouse sensor rect. it is usually used for visual effect, so there is no need to update or calculate client rect.

float GetRotation() const

Get the rotation of the control around the center of the UI plus rotation origin offset. it only affects the drawing rect but not the mouse sensor rect. it is usually used for visual effect, so there is no need to update or calculate client rect.

void SetRotOriginOffset(float x, float y)

rotation origin offset from the center of the UI object.

void GetRotOriginOffset(float *x, float *y) const

rotation origin offset from the center of the UI object.

void SetScaling(float x, float y)

set the scaling of the control around the center of the UI plus rotation origin offset. it only affects the drawing rect but not the mouse sensor rect. it is usually used for visual effect, so there is no need to update or calculate client rect.

void GetScaling(float *x, float *y) const

Get the scaling of the control around the center of the UI plus rotation origin offset. it only affects the drawing rect but not the mouse sensor rect. it is usually used for visual effect, so there is no need to update or calculate client rect.

void SetTranslation(float x, float y)

set the translation of the control around the center of the UI plus rotation origin offset. it only affects the drawing rect but not the mouse sensor rect. it is usually used for visual effect, so there is no need to update or calculate client rect.

void GetTranslation(float *x, float *y) const

Get the translation of the control around the center of the UI plus rotation origin offset. it only affects the drawing rect but not the mouse sensor rect. it is usually used for visual effect, so there is no need to update or calculate client rect.

void SetColorMask(const char *strColor)

color mask, no matter what state the control is in. “r g b a”, such as “255 255 255 255”

void ApplyAnim()

automatically animate the child nodes according to this object’s rotation, scaling, translation and color mask values.

void SetSpacing(int nSpacing)

Spacing between the text and the edge of border

int GetSpacing() const

Spacing between the text and the edge of border

void AttachTo3D(const ParaObject obj)

Attach the control to the 3D object. This function will internally call AttachToRoot() if it has not been called previously One can call this function multiple times move the attached GUI object from one 3D object to another.

Remark
: The visible property of this GUI object is controlled internally as below:
  • if the 3d object does not exist, the GUI object is invisible.
  • if the 3d object is not visible in the current camera frustum, the GUI object is invisible.
  • if the 3d object is visible in the current camera frustum, the GUI object is visible.
Parameters
  • obj: this must be a global object

void AttachTo3D_(const char *s3DObjectName)

save as AttachTo3D, except that the 3D object’s name is specified.

Remark
: The visible property of this GUI object is controlled internally as below:
  • if the 3d object does not exist, the GUI object is invisible.
  • if the 3d object is not visible in the current camera frustum, the GUI object is invisible.
  • if the 3d object is visible in the current camera frustum, the GUI object is visible.
Parameters
  • s3DObjectName: this must be the name of a global object.

ParaUIFont GetFont(const char *name)

get font by name. The prefered way is to get by index.

Parameters
  • name: this is usually “text”.

ParaUIFont GetFont_(int nIndex)

get font by index

void DoAutoSize()

try to automatically adjust the size of this object to contain all its content.

ParaUITexture GetTexture(const object &name)

Get the texture object associated with the current control A control may be associated with multiple textures.

Return
Parameters
  • name: different controls have set of textures. it can be one of the following predefined string.
    • “background”: the background texture, this is the most commonly used texture and is available in all controls.
    • “track”: the track texture in a scroll bar. it is available in “scrollbar” control.
    • “up_left”: the up arrow texture in scroll bar. it is available in “scrollbar” control.
    • “down_left”: the down arrow texture in scroll bar. it is available in “scrollbar” control.
    • “thumb”: the thumb button texture in the scroll bar. it is available in “scrollbar” control.

void BringToFront()

bring to front among the same z order

void BringToBack()

bring to back among the same z order

int GetZOrder() const

z order affect the order of rendering. The parent control sort and render child control from small z value to larger z value. default value is 0.

void SetZOrder(int nOrder)

z order affect the order of rendering. The parent control sort and render child control from small z value to larger z value. default value is 0. if this control has a parent it will cause the parent to sort all children again.

void SetActiveLayer(const char *layer)

Set the active layer for setting resource;

Parameters
  • layer: name of the layer We have three layers “artwork”, “background” and “overlay” “artwork” layer is the primary layer. By default, we render a control using this layer “overlay” layer is a layer on top of the “artwork” layer. “background” layer is on the bottom of the “artwork” layer. All three layers are the same. If not implicitly set, the default active layer is the “artwork” layer. But when a user wants to set something, remember to call this function to ensure that the active layer is correct.

bool HasLayer(const char *layer)

return whether a given layer exist in the resource. One needs to call SetActiveLayer() in order to create a layer.

Parameters
  • layer: it can be one of the three layers “artwork”, “background” and “overlay”. Typically, all controls contains the “artwork” layer.

void SetCurrentState(const char *statename)

Set the current state for setting resource:

Parameters
  • statename: name of the state We have four states “normal”, “highlight”, “pressed”, “disabled” “normal” state is the default state. “highlight” state is the highlighted state. Some controls will change their state to “highlight” automatically when mouse enters them. “pressed” state is when a button or something else is pressed. “disabled” state is when a control is disabled. If not implicitly set, the default state is the “normal” state. But when a user wants to set something, remember to call this function to ensure that the current state is correct.

void CloneState(const char *statename)

Clones a state to the current state

Parameters
  • statename: name of the state We have four states “normal”, “highlight”, “pressed”, “disabled” “normal” state is the default state. “highlight” state is the highlighted state. Some controls will change their state to “highlight” automatically when mouse enters them. “pressed” state is when a button or something else is pressed. “disabled” state is when a control is disabled.

void InvalidateRect()

the window’s client(child) area that must be recalculated and redrawn this function is obsoleted, call UpdateRect() instead

void UpdateRect()

recalculated the window’s client rect

class ParaUITexture
#include <ParaScriptingGraphics.h>

a GUI texture object

Class Properties
  • (“transparency”,&ParaUITexture::GetTransparency,&ParaUITexture::SetTransparency)
  • (“color”,&ParaUITexture::GetColor,&ParaUITexture::SetColor)
  • (“texture”,&ParaUITexture::GetTexture,&ParaUITexture::SetTexture)
  • (“rect”,&ParaUITexture::GetTextureRect,&ParaUITexture::SetTextureRect),

Public Functions

bool IsValid()

check if the object is valid

class ParaWorld
#include <ParaScriptingWorld.h>

world creation functions.

Public Static Functions

string NewWorld(const char *sWorldName, const char *sBaseWorldName)

created a new empty world based on a given world. This is like class inheritance in C++ another world could derive from a given world, overriding certain terrain tile contents as it evolves. One can immediately create the new world which is identical to the base world. Every changes made to the new world will be saved in the new world folder and will not affect the base world. in reality, we just copy the base world’s world config file to the new world using the new world’s name. e.g local sConfigFileName = ParaWorld.NewWorld(“__TmpWorld”, “sample/worldconfig.txt”); if(sConfigFileName ~= “”) thenParaScene.CreateWorld(“”, 32000, sConfigFileName); end NOTE: if the sWorldName is the same as sBaseWorldName, the sBaseWorldName itself will be overridden

Return
: return the world config file. if failed, return “”
Parameters
  • sWorldName: world name, a directory with the same name will be created containing the world config file.
  • sBaseWorldName: any valid world config file.

const char *NewWorld_(const char *sWorldName, const char *sBaseWorldName)

solely used for exporting

void DeleteWorld(const char *sWorldName)

delete a given world.

string NewEmptyWorld(const char *sWorldName = NULL, float fTileSize = 533.3333f, int nTileDimension = 64)

Create an empty world, with flat land.

Parameters
  • sWorldName: world name, if NULL, it defaults to “_emptyworld”
  • fTileSize: terrain tile size in meters
  • nTileDimension: dimension of the tile matrix. default is 64, which is has 64*64 tiles

const char *NewEmptyWorld_(const char *sWorldName = NULL, float fTileSize = 533.3333f, int nTileDimension = 64)

solely used for exporting

void SetEnablePathEncoding(bool bEnable)

set whether we will encode world related files. default to true. By enabling path encoding, world related files like “worlddir/worldfile.txt” will be saved as “%WORLD%/worldfile.txt”, thus even the entire world directory changes, the world files can still be found using path variables. Path encoding needs to be disabled when you are creating a template world.

bool GetEnablePathEncoding()

get whether we will encode world related files. default to true. By enabling path encoding, world related files like “worlddir/worldfile.txt” will be saved as “%WORLD%/worldfile.txt”, thus even the entire world directory changes, the world files can still be found using path variables. Path encoding needs to be disabled when you are creating a template world.

ParaDataProvider GetNpcDB()

get the current NPC data provider.

void GetNpcDB_(ParaDataProvider *out)

solely used for exporting

void SetNpcDB(const char *sConnectionstring)

set the global NPC data base to a new database file.

Parameters
  • sConnectionstring: : currently it is the file path of the database file.

ParaDataProvider GetAttributeProvider()

get the current attribute data provider.

void GetAttributeProvider_(ParaDataProvider *out)

solely used for exporting

void SetAttributeProvider(const char *sConnectionstring)

set the current attribute data base to a new database file.

Parameters
  • sConnectionstring: : currently it is the file path of the database file.

void SetWorldDB(const char *sConnectionstring)

set world database. it sets attribute provider, NPC database, etc to the same database file.

Parameters
  • sConnectionstring: : currently it is the file path of the database file.

string GetStringbyID(int ID)

Get string from ID

Return
string in the current game language
Parameters
  • ID: ID in kids db’s string table.

int InsertString(const char *strEN, const char *strCN)

Insert the new string table entry to StringTable_DB

Return
ID of the inserted string
Parameters
  • str: Entry in the current game language

void SetServerState(int nState)

set the current server state. default value is 0. enum CurrentState { STATE_STAND_ALONE = 0, STATE_SERVER, STATE_CLIENT, };

bool SendTerrainUpdate(const char *sDestination, float center_x, float center_y, float center_z, float fRadius, float fResolution)

Call this function to send a copy of the local terrain to a destination world at a given resolution.

Return
Parameters
  • sDestination: a destination namespace, it could be “all@server” or “@server”, etc. This will be used to fill the destination address of the packet to be sent.
  • center_x: center of the terrain region to send
  • center_y: center of the terrain region to send
  • center_z: center of the terrain region to send
  • fRadius: radius of the terrain region to send
  • fResolution: if this is 1.f, the local world terrain grid resolution is used.

string GetWorldName()

get current world name

string GetWorldDirectory()

get world root path. suppose the given world name is “sample”. The generated file name is “sample/”

void SetScriptSandBox(const object &SandboxNeuronFile)

Paraworld is told to execute in the given sandbox. (1) ParaWorld namespace supports a sandbox mode, which can be turned on and off on demand. Once turned on, all scripts from the current game world will be executed in a separate and newly created script runtime environment. (2) Sandbox mode is an isolated mode that does not have any link with the glia file environment. (3) The world scripts protected by the sandbox runtime environment includes: terrain tile onload script, biped event handler scripts, such as character onload, onclick events. (4) The sandbox environment includes the following functions that could be used: ParaScene, ParaUI namespace functions. It also explicitly disabled the following functions: a) Dofile() b) Io, ParaIO, Exec c) Require(),NPL.load, NPL.activate, NPL.download: cut off any way to manually load a file. It adds d) Log e) Download some file to replace local file. f) Changing the Enter sand box function or almost any function to some fake function. (5) The following attack methods should be prevented by the sandbox environment a) Execute or load any external application b) Write to any file, including log file c) Compromise data or functions in the glia file environment. Such as, changing and hooking the string method d) Compromise the sandbox itself and then affect in the next sandbox entity. (6) glia file environment does not have a sandbox mode. Because I found that any global sandbox mode implementation has a way to hack in, and I give up any measure of protecting the glia file environment. Sandbox protection for the world file is enough because that is the only source file that may not be provided by ParaEngine. In order to run any other code not provided by the ParaEngine, the user should have been well informed of the danger. But so far, there is no need to have a world that should inform the user. Because most world functions are supported in the world sandbox.

Parameters
  • sNeuronFileName: script file name. Use NPL.CreateNeuronFile() to create a sandbox neuron file if you do not want to use a sandbox, please specify NULL or “”.

const char *GetScriptSandBox()

please see SetScriptSandBox()

Return
: it may return NULL if the sandbox does not exist.

class ParaXML
#include <ParaScriptingIO.h>

ParaXML class

Public Static Functions

int LuaXML_ParseString(lua_State *L)

only used for documentation generation. Spec by example lz = ParaXML.LuaXML_ParseString[[<paragraph justify=”centered”>first childboldsecond child</paragraph>]] lz = {name=”paragraph”, attr={justify=”centered”}, [1] = “first child”, [2] = {name=”b”, “bold”, n=1} [3] = “second child”, n=3 }

Return
return a table containing the lua table of xml Specifications: A tree is a Lua table representation of an element and its contents. The table must have a name key, giving the element name. The tree may have a attr key, which gives a table of all of the attributes of the element. Only string keys are relevant. If the element is not empty, each child node is contained in tree[1], tree[2], etc. Child nodes may be either strings, denoting character data content, or other trees.
Parameters
  • filename: string

void SetCondenseWhiteSpace(bool condense)

The world does not agree on whether white space should be kept or not. In order to make everyone happy, these global, static functions are provided to set whether or not the parser will condense all white space into a single space or not. The default is to condense. Note changing this value is not thread safe.

bool IsWhiteSpaceCondensed()

Return the current white space setting.

class ParaZipWriter
#include <ParaScriptingIO.h>

ParaZipWriter class: creating zip files

e.g. (1) Traditional use, creating a zipfile from existing files local writer = ParaIO.CreateZip(“c:\\simple1.zip”,””); writer:ZipAdd(“znsimple.bmp”, “c:\\simple.bmp”); writer:ZipAdd(“znsimple.txt”, “c:\\simple.txt”); writer:close();

Public Functions

bool IsValid()

whether it is valid

DWORD ZipAdd(const char *dstzn, const char *fn)

add a zip file to the zip. file call this for each file to be added to the zip.

Return
: 0 if succeed.

DWORD ZipAddFolder(const char *dstzn)

add a zip folder to the zip file. call this for each folder to be added to the zip.

Return
: 0 if succeed.

DWORD AddDirectory(const char *dstzn, const char *filepattern, int nSubLevel = 0)

add everything in side a directory to the zip. e.g. AddDirectory(“myworld/”, “worlds/myworld/ *.*”, 10);

Parameters
  • dstzn: all files in fn will be appended with this string to be saved in the zip file.
  • filepattern: file patterns, which can include wild characters in the file portion.
  • nSubLevel: sub directory levels. 0 means only files at parent directory.

DWORD close()

call this when you have finished adding files and folders to the zip file. Note: you can’t add any more after calling this.

template <typename _Ty>
class StackObjectPtr
#include <ParaScriptingGlobal.h>

this is for luabinding a pointer object on lua stack, instead of invoking new operator each time an object is created. Note: this class is not used, since we now uses a more universal template which treats all objects in ParaScripting namespace as stack object.