Engine API Reference - v2.6.1
    Preparing search index...

    Class Application

    Application is a subclass of AppBase, which represents the base functionality for all PlayCanvas applications. It acts as a convenience class by internally registering all ComponentSystems and ResourceHandlers implemented in the PlayCanvas Engine. This makes app setup simple but results in the full engine being included when bundling your application.

    Hierarchy (View Summary)

    Index

    Constructors

    Properties

    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');
    autoRender: boolean = true

    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', (event) => {
    this.app.renderNextFrame = true;
    });
    elementInput: null | ElementInput = null

    Used to handle input for ElementComponents.

    gamepads: null | GamePads = null

    Used to access GamePad input.

    graphicsDevice: GraphicsDevice

    The graphics device used by the application.

    i18n: I18n = ...

    Handles localization.

    keyboard: null | Keyboard = null

    The keyboard device.

    lightmapper: null | Lightmapper = null

    The run-time lightmapper.

    loader: ResourceLoader = ...

    The resource loader.

    maxDeltaTime: number = 0.1

    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;
    mouse: null | Mouse = null

    The mouse device.

    renderNextFrame: boolean = false

    Set to true to render the scene on the next iteration of the main loop. This only has an effect if 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;
    }
    root: Entity

    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');
    scene: Scene

    The scene managed by the application.

    // Set the fog type property of the application's scene
    this.app.scene.fog.type = pc.FOG_LINEAR;
    scenes: SceneRegistry = ...

    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);
    scripts: ScriptRegistry = ...

    The application's script registry.

    scriptsOrder: string[] = []

    Scripts in order of loading first.

    The application's 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;
    timeScale: number = 1

    Scales the global time delta. Defaults to 1.

    // Set the app to run at half speed
    this.app.timeScale = 0.5;
    touch: null | TouchDevice = null

    Used to get touch events input.

    xr: null | XrManager = null

    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
    }

    Accessors

    • get batcher(): BatchManager

      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.

      Returns BatchManager

    • get fillMode(): string

      The current fill mode of the canvas. Can be:

      Returns string

    • get resolutionMode(): string

      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.

      Returns string

    Methods

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

      Parameters

      • settings: {
            physics: { gravity: number[] };
            render: {
                ambientBake: boolean;
                ambientBakeNumSamples: number;
                ambientBakeOcclusionBrightness: number;
                ambientBakeOcclusionContrast: number;
                ambientBakeSpherePart: number;
                ambientLuminance: number;
                clusteredLightingEnabled: boolean;
                exposure: number;
                fog: string;
                fog_color: number[];
                fog_density: number;
                fog_end: number;
                fog_start: number;
                gamma_correction: number;
                global_ambient: number[];
                lightingAreaLightsEnabled: boolean;
                lightingCells: Vec3;
                lightingCookieAtlasResolution: number;
                lightingCookiesEnabled: boolean;
                lightingMaxLightsPerCell: number;
                lightingShadowAtlasResolution: number;
                lightingShadowsEnabled: boolean;
                lightingShadowType: number;
                lightmapMaxResolution: number;
                lightmapMode: number;
                lightmapSizeMultiplier: number;
                skybox?: null | number;
                skyboxIntensity: number;
                skyboxLuminance: number;
                skyboxMip: number;
                skyboxRotation: number[];
                tonemapping: number;
            };
        }

        The scene settings to be applied.

        • physics: { gravity: number[] }

          The physics settings to be applied.

          • gravity: number[]

            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 ].

        • render: {
              ambientBake: boolean;
              ambientBakeNumSamples: number;
              ambientBakeOcclusionBrightness: number;
              ambientBakeOcclusionContrast: number;
              ambientBakeSpherePart: number;
              ambientLuminance: number;
              clusteredLightingEnabled: boolean;
              exposure: number;
              fog: string;
              fog_color: number[];
              fog_density: number;
              fog_end: number;
              fog_start: number;
              gamma_correction: number;
              global_ambient: number[];
              lightingAreaLightsEnabled: boolean;
              lightingCells: Vec3;
              lightingCookieAtlasResolution: number;
              lightingCookiesEnabled: boolean;
              lightingMaxLightsPerCell: number;
              lightingShadowAtlasResolution: number;
              lightingShadowsEnabled: boolean;
              lightingShadowType: number;
              lightmapMaxResolution: number;
              lightmapMode: number;
              lightmapSizeMultiplier: number;
              skybox?: null | number;
              skyboxIntensity: number;
              skyboxLuminance: number;
              skyboxMip: number;
              skyboxRotation: number[];
              tonemapping: number;
          }

          The rendering settings to be applied.

          • ambientBake: boolean

            Enable baking ambient light into lightmaps.

          • ambientBakeNumSamples: number

            Number of samples to use when baking ambient light.

          • ambientBakeOcclusionBrightness: number

            Brightness of the baked ambient occlusion.

          • ambientBakeOcclusionContrast: number

            Contrast of the baked ambient occlusion.

          • ambientBakeSpherePart: number

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

          • ambientLuminance: number

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

          • clusteredLightingEnabled: boolean

            Enable clustered lighting.

          • exposure: number

            The exposure value tweaks the overall brightness of the scene.

          • fog: string

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

          • fog_color: number[]

            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 ].

          • fog_density: number

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

          • fog_end: number

            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.

          • fog_start: number

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

          • gamma_correction: number

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

          • global_ambient: number[]

            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 ].

          • lightingAreaLightsEnabled: boolean

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

          • lightingCells: Vec3

            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.

          • lightingCookieAtlasResolution: number

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

          • lightingCookiesEnabled: boolean

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

          • lightingMaxLightsPerCell: number

            Maximum number of lights a cell can store.

          • lightingShadowAtlasResolution: number

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

          • lightingShadowsEnabled: boolean

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

          • lightingShadowType: number

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

          • lightmapMaxResolution: number

            The maximum lightmap resolution.

          • lightmapMode: number

            The lightmap baking mode. Can be:

            • BAKE_COLOR: single color lightmap
            • BAKE_COLORDIR: single color lightmap + dominant light direction (used for bump/specular)
          • lightmapSizeMultiplier: number

            The lightmap resolution multiplier.

          • Optionalskybox?: null | number

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

          • skyboxIntensity: number

            Multiplier for skybox intensity.

          • skyboxLuminance: number

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

          • skyboxMip: number

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

          • skyboxRotation: number[]

            Rotation of skybox.

          • tonemapping: number

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

      Returns void

      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);
    • Load the application configuration file and apply application properties and fill the asset registry.

      Parameters

      • url: string

        The URL of the configuration file to load.

      • callback: ConfigureAppCallback

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

      Returns void

    • 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.

      Returns void

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

      Parameters

      • start: Vec3

        The start world space coordinate of the line.

      • end: Vec3

        The end world space coordinate of the line.

      • Optionalcolor: Color

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

      • OptionaldepthTest: boolean

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

      • Optionallayer: Layer

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

      Returns void

      // 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);
    • 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.

      Parameters

      • positions: number[]

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

      • colors: number[] | Color

        A single color for all lines, or an array of colors to color the lines. If an array is specified, number of colors it stores must match the number of positions provided.

      • OptionaldepthTest: boolean = true

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

      • Optionallayer: Layer = ...

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

      Returns void

      // 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);
    • 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.

      Parameters

      • positions: Vec3[]

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

      • colors: Color | Color[]

        An array of colors or a single color. If an array is specified, this must be the same length as the position array. The length of the array must also be a multiple of 2.

      • OptionaldepthTest: boolean = true

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

      • Optionallayer: Layer = ...

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

      Returns void

      // 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);
    • Fire an event, all additional arguments are passed on to the event listener.

      Parameters

      • name: string

        Name of event to fire.

      • Optionalarg1: any

        First argument that is passed to the event handler.

      • Optionalarg2: any

        Second argument that is passed to the event handler.

      • Optionalarg3: any

        Third argument that is passed to the event handler.

      • Optionalarg4: any

        Fourth argument that is passed to the event handler.

      • Optionalarg5: any

        Fifth argument that is passed to the event handler.

      • Optionalarg6: any

        Sixth argument that is passed to the event handler.

      • Optionalarg7: any

        Seventh argument that is passed to the event handler.

      • Optionalarg8: any

        Eighth argument that is passed to the event handler.

      Returns EventHandler

      Self for chaining.

      obj.fire('test', 'This is the message');
      
    • Test if there are any handlers bound to an event name.

      Parameters

      • name: string

        The name of the event to test.

      Returns boolean

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

      obj.on('test', () => {}); // bind an event to 'test'
      obj.hasEvent('test'); // returns true
      obj.hasEvent('hello'); // returns false
    • 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.

    • 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.

      Parameters

      • Optionalname: string

        Name of the event to unbind.

      • Optionalcallback: HandleEventCallback

        Function to be unbound.

      • Optionalscope: any

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

      Returns EventHandler

      Self for chaining.

      const handler = () => {};
      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
    • Attach an event handler to an event.

      Parameters

      • name: string

        Name of the event to bind the callback to.

      • callback: HandleEventCallback

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

      • Optionalscope: any = ...

        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.

      obj.on('test', (a, b) => {
      console.log(a + b);
      });
      obj.fire('test', 1, 2); // prints 3 to the console
      const evt = obj.on('test', (a, b) => {
      console.log(a + b);
      });
      // some time later
      evt.off();
    • Attach an event handler to an event. This handler will be removed after being fired once.

      Parameters

      • name: string

        Name of the event to bind the callback to.

      • callback: HandleEventCallback

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

      • Optionalscope: any = ...

        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.
      obj.once('test', (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
    • 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

      • Optionalwidth: number

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

      • Optionalheight: number

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

      Returns any

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

    • Sets the area light LUT tables for this app.

      Parameters

      • ltcMat1: number[]

        LUT table of type array to be set.

      • ltcMat2: number[]

        LUT table of type array to be set.

      Returns void

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

      Parameters

      • mode: string

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

      • Optionalwidth: number

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

      • Optionalheight: number

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

      Returns void

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

      Parameters

      • mode: string

        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.
      • Optionalwidth: number

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

      • Optionalheight: number

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

      Returns void

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

      Parameters

      • asset: Asset

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

      Returns void

    • 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.

      Returns void

      app.start();
      
    • 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

      • dt: number

        The time delta in seconds since the last frame.

      Returns void

    • 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.

      Returns void

    • Get the current application. In the case where there are multiple running applications, the function can get an application based on a supplied canvas id. This function is particularly useful when the current Application is not readily available. For example, in the JavaScript console of the browser's developer tools.

      Parameters

      • Optionalid: string

        If defined, the returned application should use the canvas which has this id. Otherwise current application will be returned.

      Returns undefined | AppBase

      The running application, if any.

      const app = pc.AppBase.getApplication();