API Reference

Class List

Application

Extends: AppBase

An Application represents and manages your PlayCanvas application. If you are developing using the PlayCanvas Editor, the Application is created for you. You can access your Application instance in your scripts. Below is a skeleton script which shows how you can access the application 'app' property inside the initialize and update functions:

// Editor example: accessing the pc.Application from a script
var MyScript = pc.createScript('myScript');

MyScript.prototype.initialize = function() {
    // Every script instance has a property 'this.app' accessible in the initialize...
    const app = this.app;
};

MyScript.prototype.update = function(dt) {
    // ...and update functions.
    const app = this.app;
};

If you are using the Engine without the Editor, you have to create the application instance manually.

// Engine-only example: create the application manually
const app = new pc.Application(canvas, options);

// Start the application's main loop
app.start();

Summary

Inherited

Properties

assets

The asset registry managed by the application.

autoRender

When true, the application's render function is called every frame.

batcher

The application's batch manager.

elementInput

Used to handle input for ElementComponents.

fillMode

The current fill mode of the canvas.

gamepads

Used to access GamePad input.

graphicsDevice

The graphics device used by the application.

i18n

Handles localization.

keyboard

The keyboard device.

lightmapper

The run-time lightmapper.

loader

The resource loader.

maxDeltaTime

Clamps per-frame delta time to an upper bound.

mouse

The mouse device.

renderNextFrame

Set to true to render the scene on the next iteration of the main loop.

resolutionMode

The current resolution mode of the canvas, Can be:

  • RESOLUTION_AUTO: if width and height are not provided, canvas will be resized to match canvas client size.
root

The root entity of the application.

scene

The scene managed by the application.

scenes

The scene registry managed by the application.

scripts

The application's script registry.

systems

The application's component system registry.

timeScale

Scales the global time delta.

touch

Used to get touch events input.

xr

The XR Manager that provides ability to start VR/AR sessions.

Methods

applySceneSettings

Apply scene settings to the current scene.

configure

Load the application configuration file and apply application properties and fill the asset registry.

destroy

Destroys application and removes all event listeners at the end of the current engine frame update.

drawLine

Draws a single line.

drawLineArrays

Renders an arbitrary number of discrete line segments.

drawLines

Renders an arbitrary number of discrete line segments.

fire

Fire an event, all additional arguments are passed on to the event listener.

hasEvent

Test if there are any handlers bound to an event name.

init

Initialize the app.

isHidden

Queries the visibility of the window or tab in which the application is running.

off

Detach an event handler from an event.

on

Attach an event handler to an event.

once

Attach an event handler to an event.

preload

Load all assets in the asset registry that are marked as 'preload'.

resizeCanvas

Resize the application's canvas element in line with the current fill mode.

setAreaLightLuts

Sets the area light LUT tables for this app.

setCanvasFillMode

Controls how the canvas fills the window and resizes when the window changes.

setCanvasResolution

Change the resolution of the canvas, and set the way it behaves when the window is resized.

setSkybox

Sets the skybox asset to current scene, and subscribes to asset load/change events.

start

Start the application.

update

Update the application.

updateCanvasSize

Updates the GraphicsDevice canvas size to match the canvas size on the document page.

Details

Constructor

Application(canvas, [options])

Create a new Application instance.

// Engine-only example: create the application manually
const app = new pc.Application(canvas, options);

// Start the application's main loop
app.start();

Parameters

canvasHTMLCanvasElement

The canvas element.

optionsobject

The options object to configure the Application.

options.elementInputElementInput

Input handler for ElementComponents.

options.keyboardKeyboard

Keyboard handler for input.

options.mouseMouse

Mouse handler for input.

options.touchTouchDevice

TouchDevice handler for input.

options.gamepadsGamePads

Gamepad handler for input.

options.scriptPrefixstring

Prefix to apply to script urls before loading.

options.assetPrefixstring

Prefix to apply to asset urls before loading.

options.graphicsDeviceOptionsobject

Options object that is passed into the GraphicsDevice constructor.

options.scriptsOrderstring[]

Scripts in order of loading first.

Inherited

Properties

AssetRegistryassets

The asset registry managed by the application.

// Search the asset registry for all assets with the tag 'vehicle'
const vehicleAssets = this.app.assets.findByTag('vehicle');
booleanautoRender

When true, the application's render function is called every frame. Setting autoRender to false is useful to applications where the rendered image may often be unchanged over time. This can heavily reduce the application's load on the CPU and GPU. Defaults to true.

// Disable rendering every frame and only render on a keydown event
this.app.autoRender = false;
this.app.keyboard.on('keydown', function (event) {
    this.app.renderNextFrame = true;
}, this);
BatchManagerbatcher

The application's batch manager. The batch manager is used to merge mesh instances in the scene, which reduces the overall number of draw calls, thereby boosting performance.

ElementInputelementInput

Used to handle input for ElementComponents.

stringfillMode

The current fill mode of the canvas. Can be:

GamePadsgamepads

Used to access GamePad input.

GraphicsDevicegraphicsDevice

The graphics device used by the application.

I18ni18n

Handles localization.

Keyboardkeyboard

The keyboard device.

Lightmapperlightmapper

The run-time lightmapper.

ResourceLoaderloader

The resource loader.

numbermaxDeltaTime

Clamps per-frame delta time to an upper bound. Useful since returning from a tab deactivation can generate huge values for dt, which can adversely affect game state. Defaults to 0.1 (seconds).

// Don't clamp inter-frame times of 200ms or less
this.app.maxDeltaTime = 0.2;
Mousemouse

The mouse device.

booleanrenderNextFrame

Set to true to render the scene on the next iteration of the main loop. This only has an effect if AppBase#autoRender is set to false. The value of renderNextFrame is set back to false again as soon as the scene has been rendered.

// Render the scene only while space key is pressed
if (this.app.keyboard.isPressed(pc.KEY_SPACE)) {
    this.app.renderNextFrame = true;
}
stringresolutionMode

The current resolution mode of the canvas, Can be:

  • RESOLUTION_AUTO: if width and height are not provided, canvas will be resized to match canvas client size.
  • RESOLUTION_FIXED: resolution of canvas will be fixed.

Entityroot

The root entity of the application.

// Return the first entity called 'Camera' in a depth-first search of the scene hierarchy
const camera = this.app.root.findByName('Camera');
Scenescene

The scene managed by the application.

// Set the tone mapping property of the application's scene
this.app.scene.toneMapping = pc.TONEMAP_FILMIC;
SceneRegistryscenes

The scene registry managed by the application.

// Search the scene registry for a item with the name 'racetrack1'
const sceneItem = this.app.scenes.find('racetrack1');

// Load the scene using the item's url
this.app.scenes.loadScene(sceneItem.url);
ScriptRegistryscripts

The application's script registry.

ComponentSystemRegistrysystems

The application's component system registry. The Application constructor adds the following component systems to its component system registry:

// Set global gravity to zero
this.app.systems.rigidbody.gravity.set(0, 0, 0);
// Set the global sound volume to 50%
this.app.systems.sound.volume = 0.5;
numbertimeScale

Scales the global time delta. Defaults to 1.

// Set the app to run at half speed
this.app.timeScale = 0.5;
TouchDevicetouch

Used to get touch events input.

XrManagerxr

The XR Manager that provides ability to start VR/AR sessions.

// check if VR is available
if (app.xr.isAvailable(pc.XRTYPE_VR)) {
    // VR is available
}

Methods

applySceneSettings(settings)

Apply scene settings to the current scene. Useful when your scene settings are parsed or generated from a non-URL source.

const settings = {
    physics: {
        gravity: [0, -9.8, 0]
    },
    render: {
        fog_end: 1000,
        tonemapping: 0,
        skybox: null,
        fog_density: 0.01,
        gamma_correction: 1,
        exposure: 1,
        fog_start: 1,
        global_ambient: [0, 0, 0],
        skyboxIntensity: 1,
        skyboxRotation: [0, 0, 0],
        fog_color: [0, 0, 0],
        lightmapMode: 1,
        fog: 'none',
        lightmapMaxResolution: 2048,
        skyboxMip: 2,
        lightmapSizeMultiplier: 16
    }
};
app.applySceneSettings(settings);

Parameters

settingsobject

The scene settings to be applied.

settings.physicsobject

The physics settings to be applied.

settings.physics.gravitynumber[]

The world space vector representing global gravity in the physics simulation. Must be a fixed size array with three number elements, corresponding to each axis [ X, Y, Z ].

settings.renderobject

The rendering settings to be applied.

settings.render.global_ambientnumber[]

The color of the scene's ambient light. Must be a fixed size array with three number elements, corresponding to each color channel [ R, G, B ].

settings.render.fogstring

The type of fog used by the scene. Can be:

settings.render.fog_colornumber[]

The color of the fog (if enabled). Must be a fixed size array with three number elements, corresponding to each color channel [ R, G, B ].

settings.render.fog_densitynumber

The density of the fog (if enabled). This property is only valid if the fog property is set to FOG_EXP or FOG_EXP2.

settings.render.fog_startnumber

The distance from the viewpoint where linear fog begins. This property is only valid if the fog property is set to FOG_LINEAR.

settings.render.fog_endnumber

The distance from the viewpoint where linear fog reaches its maximum. This property is only valid if the fog property is set to FOG_LINEAR.

settings.render.gamma_correctionnumber

The gamma correction to apply when rendering the scene. Can be:

settings.render.tonemappingnumber

The tonemapping transform to apply when writing fragments to the frame buffer. Can be:

settings.render.exposurenumber

The exposure value tweaks the overall brightness of the scene.

settings.render.skyboxnumber, null

The asset ID of the cube map texture to be used as the scene's skybox. Defaults to null.

settings.render.skyboxIntensitynumber

Multiplier for skybox intensity.

settings.render.skyboxLuminancenumber

Lux (lm/m^2) value for skybox intensity when physical light units are enabled.

settings.render.skyboxMipnumber

The mip level of the skybox to be displayed. Only valid for prefiltered cubemap skyboxes.

settings.render.skyboxRotationnumber[]

Rotation of skybox.

settings.render.lightmapSizeMultipliernumber

The lightmap resolution multiplier.

settings.render.lightmapMaxResolutionnumber

The maximum lightmap resolution.

settings.render.lightmapModenumber

The lightmap baking mode. Can be:

  • BAKE_COLOR: single color lightmap
  • BAKE_COLORDIR: single color lightmap + dominant light direction (used for bump/specular)
settings.render.ambientBakeboolean

Enable baking ambient light into lightmaps.

settings.render.ambientBakeNumSamplesnumber

Number of samples to use when baking ambient light.

settings.render.ambientBakeSpherePartnumber

How much of the sphere to include when baking ambient light.

settings.render.ambientBakeOcclusionBrightnessnumber

Brightness of the baked ambient occlusion.

settings.render.ambientBakeOcclusionContrastnumber

Contrast of the baked ambient occlusion.

settings.render.ambientLuminancenumber

Lux (lm/m^2) value for ambient light intensity.

settings.render.clusteredLightingEnabledboolean

Enable clustered lighting.

settings.render.lightingShadowsEnabledboolean

If set to true, the clustered lighting will support shadows.

settings.render.lightingCookiesEnabledboolean

If set to true, the clustered lighting will support cookie textures.

settings.render.lightingAreaLightsEnabledboolean

If set to true, the clustered lighting will support area lights.

settings.render.lightingShadowAtlasResolutionnumber

Resolution of the atlas texture storing all non-directional shadow textures.

settings.render.lightingCookieAtlasResolutionnumber

Resolution of the atlas texture storing all non-directional cookie textures.

settings.render.lightingMaxLightsPerCellnumber

Maximum number of lights a cell can store.

settings.render.lightingShadowTypenumber

The type of shadow filtering used by all shadows. Can be:

settings.render.lightingCellsVec3

Number of cells along each world-space axis the space containing lights is subdivided into.

Only lights with bakeDir=true will be used for generating the dominant light direction.

configure(url, callback)

Load the application configuration file and apply application properties and fill the asset registry.

Parameters

urlstring

The URL of the configuration file to load.

callbackConfigureAppCallback

The Function called when the configuration file is loaded and parsed (or an error occurs).

destroy()

Destroys application and removes all event listeners at the end of the current engine frame update. However, if called outside of the engine frame update, calling destroy() will destroy the application immediately.

app.destroy();

drawLine(start, end, [color], [depthTest], [layer])

Draws a single line. Line start and end coordinates are specified in world-space. The line will be flat-shaded with the specified color.

// Render a 1-unit long white line
const start = new pc.Vec3(0, 0, 0);
const end = new pc.Vec3(1, 0, 0);
app.drawLine(start, end);
// Render a 1-unit long red line which is not depth tested and renders on top of other geometry
const start = new pc.Vec3(0, 0, 0);
const end = new pc.Vec3(1, 0, 0);
app.drawLine(start, end, pc.Color.RED, false);
// Render a 1-unit long white line into the world layer
const start = new pc.Vec3(0, 0, 0);
const end = new pc.Vec3(1, 0, 0);
const worldLayer = app.scene.layers.getLayerById(pc.LAYERID_WORLD);
app.drawLine(start, end, pc.Color.WHITE, true, worldLayer);

Parameters

startVec3

The start world-space coordinate of the line.

endVec3

The end world-space coordinate of the line.

colorColor

The color of the line. It defaults to white if not specified.

depthTestboolean

Specifies if the line is depth tested against the depth buffer. Defaults to true.

layerLayer

The layer to render the line into. Defaults to LAYERID_IMMEDIATE.

drawLineArrays(positions, colors, [depthTest], [layer])

Renders an arbitrary number of discrete line segments. The lines are not connected by each subsequent point in the array. Instead, they are individual segments specified by two points.

// Render 2 discrete line segments
const points = [
    // Line 1
    0, 0, 0,
    1, 0, 0,
    // Line 2
    1, 1, 0,
    1, 1, 1
];
const colors = [
    // Line 1
    1, 0, 0, 1,  // red
    0, 1, 0, 1,  // green
    // Line 2
    0, 0, 1, 1,  // blue
    1, 1, 1, 1   // white
];
app.drawLineArrays(points, colors);

Parameters

positionsnumber[]

An array of points to draw lines between. Each point is represented by 3 numbers - x, y and z coordinate.

colorsnumber[]

An array of colors to color the lines. This must be the same length as the position array. The length of the array must also be a multiple of 2.

depthTestboolean

Specifies if the lines are depth tested against the depth buffer. Defaults to true.

layerLayer

The layer to render the lines into. Defaults to LAYERID_IMMEDIATE.

drawLines(positions, colors, [depthTest], [layer])

Renders an arbitrary number of discrete line segments. The lines are not connected by each subsequent point in the array. Instead, they are individual segments specified by two points. Therefore, the lengths of the supplied position and color arrays must be the same and also must be a multiple of 2. The colors of the ends of each line segment will be interpolated along the length of each line.

// Render a single line, with unique colors for each point
const start = new pc.Vec3(0, 0, 0);
const end = new pc.Vec3(1, 0, 0);
app.drawLines([start, end], [pc.Color.RED, pc.Color.WHITE]);
// Render 2 discrete line segments
const points = [
    // Line 1
    new pc.Vec3(0, 0, 0),
    new pc.Vec3(1, 0, 0),
    // Line 2
    new pc.Vec3(1, 1, 0),
    new pc.Vec3(1, 1, 1)
];
const colors = [
    // Line 1
    pc.Color.RED,
    pc.Color.YELLOW,
    // Line 2
    pc.Color.CYAN,
    pc.Color.BLUE
];
app.drawLines(points, colors);

Parameters

positionsVec3[]

An array of points to draw lines between. The length of the array must be a multiple of 2.

colorsColor[]

An array of colors to color the lines. This must be the same length as the position array. The length of the array must also be a multiple of 2.

depthTestboolean

Specifies if the lines are depth tested against the depth buffer. Defaults to true.

layerLayer

The layer to render the lines into. Defaults to LAYERID_IMMEDIATE.

fire(name, [arg1], [arg2], [arg3], [arg4], [arg5], [arg6], [arg7], [arg8])

Fire an event, all additional arguments are passed on to the event listener.

obj.fire('test', 'This is the message');

Parameters

namestring

Name of event to fire.

arg1*

First argument that is passed to the event handler.

arg2*

Second argument that is passed to the event handler.

arg3*

Third argument that is passed to the event handler.

arg4*

Fourth argument that is passed to the event handler.

arg5*

Fifth argument that is passed to the event handler.

arg6*

Sixth argument that is passed to the event handler.

arg7*

Seventh argument that is passed to the event handler.

arg8*

Eighth argument that is passed to the event handler.

Returns

EventHandler

Self for chaining.

hasEvent(name)

Test if there are any handlers bound to an event name.

obj.on('test', function () { }); // bind an event to 'test'
obj.hasEvent('test'); // returns true
obj.hasEvent('hello'); // returns false

Parameters

namestring

The name of the event to test.

Returns

boolean

True if the object has handlers bound to the specified event name.

init(appOptions)

Initialize the app.

Parameters

appOptionsAppOptions

Options specifying the init parameters for the app.

isHidden()

Queries the visibility of the window or tab in which the application is running.

Returns

boolean

True if the application is not visible and false otherwise.

off([name], [callback], [scope])

Detach an event handler from an event. If callback is not provided then all callbacks are unbound from the event, if scope is not provided then all events with the callback will be unbound.

const handler = function () {
};
obj.on('test', handler);

obj.off(); // Removes all events
obj.off('test'); // Removes all events called 'test'
obj.off('test', handler); // Removes all handler functions, called 'test'
obj.off('test', handler, this); // Removes all handler functions, called 'test' with scope this

Parameters

namestring

Name of the event to unbind.

callbackHandleEventCallback

Function to be unbound.

scopeobject

Scope that was used as the this when the event is fired.

Returns

EventHandler

Self for chaining.

on(name, callback, [scope])

Attach an event handler to an event.

obj.on('test', function (a, b) {
    console.log(a + b);
});
obj.fire('test', 1, 2); // prints 3 to the console
const evt = obj.on('test', function (a, b) {
    console.log(a + b);
});
// some time later
evt.off();

Parameters

namestring

Name of the event to bind the callback to.

callbackHandleEventCallback

Function that is called when event is fired. Note the callback is limited to 8 arguments.

scopeobject

Object to use as 'this' when the event is fired, defaults to current this.

Returns

EventHandle

Can be used for removing event in the future.

once(name, callback, [scope])

Attach an event handler to an event. This handler will be removed after being fired once.

obj.once('test', function (a, b) {
    console.log(a + b);
});
obj.fire('test', 1, 2); // prints 3 to the console
obj.fire('test', 1, 2); // not going to get handled

Parameters

namestring

Name of the event to bind the callback to.

callbackHandleEventCallback

Function that is called when event is fired. Note the callback is limited to 8 arguments.

scopeobject

Object to use as 'this' when the event is fired, defaults to current this.

Returns

EventHandle
  • can be used for removing event in the future.

preload(callback)

Load all assets in the asset registry that are marked as 'preload'.

Parameters

callbackPreloadAppCallback

Function called when all assets are loaded.

resizeCanvas([width], [height])

Resize the application's canvas element in line with the current fill mode.

  • In FILLMODE_KEEP_ASPECT mode, the canvas will grow to fill the window as best it can while maintaining the aspect ratio.
  • In FILLMODE_FILL_WINDOW mode, the canvas will simply fill the window, changing aspect ratio.
  • In FILLMODE_NONE mode, the canvas will always match the size provided.

Parameters

widthnumber

The width of the canvas. Only used if current fill mode is FILLMODE_NONE.

heightnumber

The height of the canvas. Only used if current fill mode is FILLMODE_NONE.

Returns

object

A object containing the values calculated to use as width and height.

setAreaLightLuts(ltcMat1, ltcMat2)

Sets the area light LUT tables for this app.

Parameters

ltcMat1number[]

LUT table of type array to be set.

ltcMat2number[]

LUT table of type array to be set.

setCanvasFillMode(mode, [width], [height])

Controls how the canvas fills the window and resizes when the window changes.

Parameters

modestring

The mode to use when setting the size of the canvas. Can be:

widthnumber

The width of the canvas (only used when mode is FILLMODE_NONE).

heightnumber

The height of the canvas (only used when mode is FILLMODE_NONE).

setCanvasResolution(mode, [width], [height])

Change the resolution of the canvas, and set the way it behaves when the window is resized.

Parameters

modestring

The mode to use when setting the resolution. Can be:

  • RESOLUTION_AUTO: if width and height are not provided, canvas will be resized to match canvas client size.
  • RESOLUTION_FIXED: resolution of canvas will be fixed.
widthnumber

The horizontal resolution, optional in AUTO mode, if not provided canvas clientWidth is used.

heightnumber

The vertical resolution, optional in AUTO mode, if not provided canvas clientHeight is used.

setSkybox(asset)

Sets the skybox asset to current scene, and subscribes to asset load/change events.

Parameters

assetAsset

Asset of type skybox to be set to, or null to remove skybox.

start()

Start the application. This function does the following:

  1. Fires an event on the application named 'start'
  2. Calls initialize for all components on entities in the hierarchy
  3. Fires an event on the application named 'initialize'
  4. Calls postInitialize for all components on entities in the hierarchy
  5. Fires an event on the application named 'postinitialize'
  6. Starts executing the main loop of the application

This function is called internally by PlayCanvas applications made in the Editor but you will need to call start yourself if you are using the engine stand-alone.

app.start();

update(dt)

Update the application. This function will call the update functions and then the postUpdate functions of all enabled components. It will then update the current state of all connected input devices. This function is called internally in the application's main loop and does not need to be called explicitly.

Parameters

dtnumber

The time delta in seconds since the last frame.

updateCanvasSize()

Updates the GraphicsDevice canvas size to match the canvas size on the document page. It is recommended to call this function when the canvas size changes (e.g on window resize and orientation change events) so that the canvas resolution is immediately updated.