This is the main engine object, available to JavaScript as a global TurbulenzEngine. All other parts of the Turbulenz native api are accessed through TurbulenzEngine, either via methods on this object or by device objects that they return.
Note that the space occupied by the engine on the web page will not be drawn until a GraphicsDevice object is created with createGraphicsDevice.
Summary
Creates a GraphicsDevice. Only one graphics device can be created at any time. If you call this function again it will fail. To get the previously created device call getGraphicsDevice.
Syntax
var graphicsDeviceOptions = {
vsync: false,
multisample: 1,
alpha: false
};
var graphicsDevice = TurbulenzEngine.createGraphicsDevice(graphicsDeviceOptions);
Setting this option synchronizes the rendering with the vertical retrace in order to reduce tearing. It also limits the maximum frames per second to the frequency of the monitor. Defaults to false.
Note
This option is only supported in plugin mode.
Setting this option enables creation of an alpha channel, which allows blending of the rendered image with the web page background when the alpha value of the pixel is lower than 1. Defaults to false.
Note
This option is only supported in canvas mode.
Setting this option to false disables the availability of the stencil buffer. This can potentially save graphics memory if not required. If this option is set to false, do not attempt to make calls that act on the stencil buffer. It is recommended to disable both the stencil and depth buffer together. Defaults to true.
Note
This option is only supported in canvas mode.
Setting this option to false disables the availability of the depth buffer. This can potentially save graphics memory if not required. If this option is set to false, do not attempt to make calls that act on the depth buffer. It is recommended to disable both the stencil and depth buffer together. Defaults to true.
Note
This option is only supported in canvas mode.
Summary
Returns the current GraphicsDevice. If you call this function before creating a GraphicsDevice it will return null.
Syntax
var graphicsDevice = TurbulenzEngine.getGraphicsDevice();
Summary
Creates a PhysicsDevice. Only one physics device can be created at any time. If you call this function again it will fail. To get the previously created device call getPhysicsDevice.
Syntax
var physicsDevice = TurbulenzEngine.createPhysicsDevice({});
Currently, no parameters are required to create the physics device, however for consistency with other devices and to allow for parameters to be added in the future, an empty object must be passed in.
Summary
Returns the current PhysicsDevice. If you call this function before creating a PhysicsDevice it will return null.
Syntax
var physicsDevice = TurbulenzEngine.getPhysicsDevice();
Summary
Creates a SoundDevice. Only one sound device can be created at any time. If you call this function again it will fail. To get the previously created device call getSoundDevice.
This function can return ‘null’ if there is no audio device enabled on the host system.
Syntax
var soundDeviceOptions = {
deviceSpecifier: "DirectSound Software",
linearDistance: true
};
var soundDevice = TurbulenzEngine.createSoundDevice(soundDeviceOptions);
if (soundDevice)
{
// ...
}
All the sound device properties can also be passed as options.
Summary
Returns the current SoundDevice. If you call this function before creating a SoundDevice it will return null.
Syntax
var soundDevice = TurbulenzEngine.getSoundDevice();
Summary
Creates a NetworkDevice. Only one network device can be created at any time. If you call this function again it will fail. To get the previously created device call getNetworkDevice.
Syntax
var networkDeviceOptions = {
};
var networkDevice = TurbulenzEngine.createNetworkDevice(networkDeviceOptions);
This device does not have any configuration options at the moment.
Summary
Returns the current NetworkDevice. If you call this function before creating a NetworkDevice it will return null.
Syntax
var networkDevice = TurbulenzEngine.getNetworkDevice();
Summary
Creates an InputDevice. Only one input device can be created at any time. If you call this function again it will fail. To get the previously created device call getInputDevice.
Syntax
var inputDeviceOptions = {
};
var inputDevice = TurbulenzEngine.createInputDevice(inputDeviceOptions);
This device does not have any configuration options at the moment.
Summary
Returns the current InputDevice. If you call this function before creating a InputDevice it will return null.
Syntax
var inputDevice = TurbulenzEngine.getInputDevice();
Summary
Creates a MathDevice. Only one math device can be created at any time. If you call this function again it will fail. To get the previously created device call getMathDevice.
Syntax
var mathDeviceOptions = {
};
var mathDevice = TurbulenzEngine.createMathDevice(mathDeviceOptions);
This device does not have any configuration options at the moment.
Summary
Returns the current MathDevice. If you call this function before creating a MathDevice it will return null.
Syntax
var mathDevice = TurbulenzEngine.getMathDevice();
Summary
Compresses, encrypts and returns base 64 encoded the string passed in. Returns null if not running a TZO file as no key will exist to encrypt with.
Syntax
var plainText = "Hello World";
var encryptedStr = TurbulenzEngine.encrypt(plainText);
Summary
Decompresses and decrypts the string passed in. Returns null if decryption fails. Returns the string as it was given if not running a TZO file.
Syntax
var encryptedStr = "X8woxDiR2nu2YtMQf7LHpzOrUwKJQFZcc";
var decryptedStr = TurbulenzEngine.decrypt(encryptedStr);
Summary
Generates a base 64 encoded SHA-256 HMAC of a given string. Returns null if not running a TZO file.
Syntax
var str = "Hello World";
var signature = TurbulenzEngine.generateSignature(str);
Summary
Given a string and an existing signature generates a new signature and checks if the two are equal. Always returns true if not running a TZO file.
Syntax
var originalStr = "Hello World";
var originalSignature = "xdVw6STqGdSzGi1lFcMeQfiPDINGY+t/3k6K8e/rbkw=";
var verified = TurbulenzEngine.verifySignature(originalStr, originalSignature);
Summary
Requests the resource represented by the URL and when the transmission finishes the given function is called with the contents of the file as an string. Returns immediately.
Syntax
var onLoadedData = function onLoadedDataFn(responseText, status)
{
...
};
var resource = 'data/room_scene.json';
TurbulenzEngine.request(resource, onLoadedData);
A JavaScript function. The callback function called with the requested resource in a string format. For example:
var onLoadedData = function onLoadedDataFn(responseText, status)
{
if (responseText && status === 200)
{
var obj = JSON.parse(responseText);
}
else
{
//request failed
}
}
This function is always called asynchronously.
Returns true if the request can be made or false if parameters are incorrect.
Note
You should manage the response status codes correctly. See the RequestHandler for handling connection and service busy issues.
Summary
Calls the given function after the specified delay in milliseconds. Returns the ID of the timeout.
Syntax
var delay = 100;
var timeoutID = TurbulenzEngine.setTimeout(timeoutFunction, delay);
Summary
Calls the given function repeatedly, with a fixed time delay between each call to that function. Returns the ID of the interval.
Note that if the interval function takes a long time to execute, these callbacks may be skipped to avoid creating a backlog of interval events that cannot be handled. It is therefore recommended that the game measure the actual time between interval callbacks and update game logic accordingly.
The setTimeout function should be used to repeatedly schedule callbacks in the case where the game needs to guarantee that interval events are not skipped.
Note
In canvas mode, if the delay is set to 16.6±1ms (i.e. ~60Hz), the interval function may not be called if the game browser tab is not active (as it uses requestAnimationFrame). To ensure that the interval function is called even when the game tab is not active (e.g. during loading), it is best to set the interval to less than 60Hz, resetting it back as appropriate.
Browsers tend to prioritise loading callbacks above timer interval callbacks, which often results in long pauses during loading animations (progress bars, spinning wheels, etc). To help avoid such pauses, game code should update loading animations from asset request callbacks if interval timers have not been called recently enough.
Syntax
var delay = (1000 / 60);
var intervalID = TurbulenzEngine.setInterval(intervalFunction, delay);
Summary
Clears a delay set by setTimeout.
Syntax
TurbulenzEngine.clearTimeout(timeoutID);
Summary
Cancels repeated action set up using setInterval.
Syntax
TurbulenzEngine.clearInterval(intervalID);
Summary
Forces the JavaScript virtual machine garbage collector to immediately release as much unused memory as possible. This method could take an unpredictably long time to return.
Syntax
TurbulenzEngine.flush();
Summary
Returns a JavaScript object containing information about the system on which the engine is running. The returned object contains the following properties:
numPhysicalCores
Number of physical cores available on the system (note on some platforms this may not be accurately obtainable, in which case the number of logical cores will be returned).
architecture
String representing the architecture on which the game code is running. Typically this is either ‘x86’ or ‘x86_64’. Note that this may not necessarily be the same as the architecture of the browser, or the Operating System.
Syntax
var systemInfo = TurbulenzEngine.getSystemInfo();
var numThreads = systemInfo.numLogicalCores;
var useLowResAssets = (systemInfo.ramInMegabytes <= 1024);
Summary
Returns a JavaScript object containing information about the objects active in the JavaScript Engine. If no information is available, an empty object is returned. The object contains dictionary entries for each recorded object type by name (e.g. ‘ObjectTypeName1’) in the following format:
{
'ObjectTypeName1' :
{
totalCount : 23
},
'ObjectTypeName2' :
{
totalCount : 2
},
...
'Total' :
{
totalCount : 43
}
}
Each entry is a JavaScript object containing one or more ‘stat’ entries from the following item(s):
totalCount: | The total number of objects recorded for this type per instance of the Turbulenz engine. |
---|
In addition to the object type information, a separate entry ‘Total’ is also returned, which includes all recorded values, both identified (already in the list) and unidentified (name not available). This number should include all strings, numbers, identifiers, temporary or otherwise used by the JavaScript Engine during execution.
For example:
ObjectTypeName1 + ObjectTypeName2 + 'Unidentified' = Total
23 + 2 + X = 43
X = 18 (Unidentified objects)
Warning
The behavior of this function is different for each browser. If run in development mode, the ‘totalCount’ refers to that of the browser’s JavaScript Engine. If run in plugin mode in any browser, the ‘totalCount’ refers to that of the Turbulenz JavaScript Engine. The counts returned should be used as a guide. The exact figures are subject to the JavaScript Engine’s Garbage Collection method and may not be 100% accurate when calling the function.
Warning
The function can take some time to process for a large number of objects, therefore it should only be used for debugging purposes. In some browsers, using TurbulenzEngine.flush() prior to calling the function may assist in providing up-to-date information. This behavior cannot be guaranteed.
Syntax
// Expected v3's created
var v3CreatedCount = 10;
// Only for DEBUGGING
TurbulenzEngine.flush();
if (TurbulenzEngine.getObjectStats)
{
// getObjectStats is available for this engine
var objectStats = TurbulenzEngine.getObjectStats();
var v3ObjectCount = objectStats['Vector3'];
if (v3ObjectCount)
{
if (v3ObjectCount > v3CreatedCount)
{
if (console)
{
console.warn("Vector3 count is higher than expected: " + v3CreatedCount + ", actual: " + v3ObjectCount);
}
}
}
}
Summary
Enables the JavaScript engine profiler.
This utilizes the same technology that the browser development tools use when profiling is enabled to measure all the function calls and costs. For the native engine version the profiler will start on the next script execution, i.e. the next callback, interval or timeout. For browser based versions the behavior is varied, either immediately or on the next script execution.
Warning
When profiling is enabled the code may run markedly slower.
Syntax
var enable = true;
TurbulenzEngine.enableProfiling(enable);
Start profiling. TurbulenzEngine.enableProfiling should be called before this is called.
Summary
TurbulenzEngine.startProfiling();
Summary
Stops profiling.
The native engine returns an object that is the root profile node of the profile tree. The browsers versions Chrome and Safari return the same kind of root profile node while Firefox, with Firebug, and Explorer prints to the console.
Some utilities to help process the data are provided by JSProfiling.
Syntax
var result = TurbulenzEngine.stopProfiling();
if (result)
{
var array = JSProfiling.createArray(result);
JSProfiling.sort(result);
// ...
}
Each profile node has:
numberOfCalls
Note
The implementation of this is dependent on the underlying JavaScript VM and so the structure of the data may vary with future versions. The browser based versions may also vary.
Summary
The engine will call its TurbulenzEngine.onunload function property. This also stops any asynchronous callbacks from being called as everything should be unloaded by the TurbulenzEngine.onunload function.
Syntax
TurbulenzEngine.unload();
Summary
This returns false until TurbulenzEngine.unload() has been called then returns true.
Syntax
var isUnloading = TurbulenzEngine.isUnloading();
Summary
Returns time in milliseconds. The precision will be in the sub-millisecond range.
Syntax
var currentTime = TurbulenzEngine.getTime();
Summary
A JavaScript function. This should be set as the entry point to the game which will be called when the page has loaded and the engine is initialized.
Syntax
TurbulenzEngine.onload = function onloadFn()
{
var application = Application.create();
TurbulenzEngine.onunload = function onUnloadFn()
{
application.shutdown();
};
application.init();
};
This should not be called by the game. This is a callback the Turbulenz engine will call when ready.
Summary
A JavaScript function. A callback function that is called when the game is closed by the browser or by our site controls.
Syntax
// Destroy callback to run when the game is closed
var appDestroyCallback = function unloadCallbackFn()
{
TurbulenzEngine.clearInterval(intervalID);
gameSession.destroy();
};
TurbulenzEngine.onunload = appDestroyCallback;
This function should not be called directly you should use TurbulenzEngine.unload() instead.
Summary
The engine version string.
Syntax
var engineVersion = TurbulenzEngine.version;
Note
Read Only
Summary
Whether the engine currently contains a key that can be used for encryption. Always false in development builds.
Syntax
var encryption = TurbulenzEngine.encryptionEnabled;
Note
Read Only
Summary
The position and dimensions in pixels of the HTML element that contains the engine.
Syntax
var aspectRatio = (TurbulenzEngine.width / TurbulenzEngine.height);
Note
Read Only
Summary
The time in seconds since the engine was initialized. The precision will be in the sub-millisecond range.
Syntax
var startTime = TurbulenzEngine.time;
doSomething();
var totalTime = (TurbulenzEngine.time - startTime);
Summary
A callback to receive messages from the engine when errors occur during game execution. This is intended to catch code problems (such as bad parameters being passed to a function) and runtime errors (such as failure to allocate memory).
Note that in canvas mode, error checking is less thorough than in plugin mode (to reduce the execution overhead). We recommend that developers regularly run in plugin mode to catch coding errors.
Syntax
var onError = function onError(message)
{
globalErrors += 1;
if (alertErrors)
{
alert("ERROR FROM ENGINE: " + message);
}
};
TurbulenzEngine.onerror = onError;
Summary
A callback to receive messages from the engine when recoverable errors happen during game execution. The primary intention of this callback is to catch programming mistakes and potential problems that might otherwise not be highlighted until a later stage in the game execution.
Syntax
var onWarning = function onWarningFn(message)
{
if (alertWarnings)
{
alert("WARNING FROM ENGINE: " + message);
}
};
TurbulenzEngine.onwarning = onWarning;
The following code will result in a warning message
var renderTargetParams = {
colourTexture0 : myRenderTexture0, // < wrong spelling of 'color'
colorTexture1 : myRenderTexture1,
depthBuffer : myDepthBuffer
};
var renderTarget = graphicsDevice.createRenderTarget(renderTargetParams);
Summary
A callback to receive messages when the engine detects that some certain classes of potential performance problems. Note that this warning is currently only triggered in canvas-debug builds.
This can be used to detect problems such as the use of non-optimal array types in math code. In particular, developers targetting lower powered devices (such as tablets and phones) are recommended to make use of this callback, and pay particular attention to code that triggers this it each frame.
Syntax
var onPerformanceWarning = function onPerformanceWarningFn(message)
{
if (alertWarnings)
{
alert("WARNING FROM ENGINE: " + message);
}
};
TurbulenzEngine.onwarning = onPerformanceWarning;
The following code will result in a performance warning
var v3 = [ 1, 2, 3 ]; // less optimal than mathDevice.v3Build(1, 2, 3);
var m43 = mathDevice.m43Build( ... );
vec = mathDevice.m43TransformVector(m43, v3);
Summary
Exists only when the engine is running in canvas or canvas-debug mode. Game code can use this to determine which mode it is running in, but it must not set the value. It is used internally by the engine.
In general, game code should not need to make use of this property.